code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "@sizeOf and @TypeOf" {
const y: @TypeOf(x) = 120;
try expect(@sizeOf(@TypeOf(y)) == 2);
}
const x: u16 = 13;
const z: @TypeOf(x) = 19;
test "@sizeOf on compile-time types" {
try expect(@sizeOf(comptime_int) == 0);
try expect(@sizeOf(comptime_float) == 0);
try expect(@sizeOf(@TypeOf(.hi)) == 0);
try expect(@sizeOf(@TypeOf(type)) == 0);
}
test "@TypeOf() with multiple arguments" {
{
var var_1: u32 = undefined;
var var_2: u8 = undefined;
var var_3: u64 = undefined;
comptime try expect(@TypeOf(var_1, var_2, var_3) == u64);
}
{
var var_1: f16 = undefined;
var var_2: f32 = undefined;
var var_3: f64 = undefined;
comptime try expect(@TypeOf(var_1, var_2, var_3) == f64);
}
{
var var_1: u16 = undefined;
comptime try expect(@TypeOf(var_1, 0xffff) == u16);
}
{
var var_1: f32 = undefined;
comptime try expect(@TypeOf(var_1, 3.1415) == f32);
}
}
fn fn1(alpha: bool) void {
const n: usize = 7;
_ = if (alpha) n else @sizeOf(usize);
}
test "lazy @sizeOf result is checked for definedness" {
_ = fn1;
}
const A = struct {
a: u8,
b: u32,
c: u8,
d: u3,
e: u5,
f: u16,
g: u16,
h: u9,
i: u7,
};
const P = packed struct {
a: u8,
b: u32,
c: u8,
d: u3,
e: u5,
f: u16,
g: u16,
h: u9,
i: u7,
};
test "@offsetOf" {
// Packed structs have fixed memory layout
try expect(@offsetOf(P, "a") == 0);
try expect(@offsetOf(P, "b") == 1);
try expect(@offsetOf(P, "c") == 5);
try expect(@offsetOf(P, "d") == 6);
try expect(@offsetOf(P, "e") == 6);
try expect(@offsetOf(P, "f") == 7);
try expect(@offsetOf(P, "g") == 9);
try expect(@offsetOf(P, "h") == 11);
try expect(@offsetOf(P, "i") == 12);
// // Normal struct fields can be moved/padded
var a: A = undefined;
try expect(@ptrToInt(&a.a) - @ptrToInt(&a) == @offsetOf(A, "a"));
try expect(@ptrToInt(&a.b) - @ptrToInt(&a) == @offsetOf(A, "b"));
try expect(@ptrToInt(&a.c) - @ptrToInt(&a) == @offsetOf(A, "c"));
try expect(@ptrToInt(&a.d) - @ptrToInt(&a) == @offsetOf(A, "d"));
try expect(@ptrToInt(&a.e) - @ptrToInt(&a) == @offsetOf(A, "e"));
try expect(@ptrToInt(&a.f) - @ptrToInt(&a) == @offsetOf(A, "f"));
try expect(@ptrToInt(&a.g) - @ptrToInt(&a) == @offsetOf(A, "g"));
try expect(@ptrToInt(&a.h) - @ptrToInt(&a) == @offsetOf(A, "h"));
try expect(@ptrToInt(&a.i) - @ptrToInt(&a) == @offsetOf(A, "i"));
}
test "@offsetOf packed struct, array length not power of 2 or multiple of native pointer width in bytes" {
const p3a_len = 3;
const P3 = packed struct {
a: [p3a_len]u8,
b: usize,
};
try std.testing.expect(0 == @offsetOf(P3, "a"));
try std.testing.expect(p3a_len == @offsetOf(P3, "b"));
const p5a_len = 5;
const P5 = packed struct {
a: [p5a_len]u8,
b: usize,
};
try std.testing.expect(0 == @offsetOf(P5, "a"));
try std.testing.expect(p5a_len == @offsetOf(P5, "b"));
const p6a_len = 6;
const P6 = packed struct {
a: [p6a_len]u8,
b: usize,
};
try std.testing.expect(0 == @offsetOf(P6, "a"));
try std.testing.expect(p6a_len == @offsetOf(P6, "b"));
const p7a_len = 7;
const P7 = packed struct {
a: [p7a_len]u8,
b: usize,
};
try std.testing.expect(0 == @offsetOf(P7, "a"));
try std.testing.expect(p7a_len == @offsetOf(P7, "b"));
const p9a_len = 9;
const P9 = packed struct {
a: [p9a_len]u8,
b: usize,
};
try std.testing.expect(0 == @offsetOf(P9, "a"));
try std.testing.expect(p9a_len == @offsetOf(P9, "b"));
// 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25 etc. are further cases
}
test "@bitOffsetOf" {
// Packed structs have fixed memory layout
try expect(@bitOffsetOf(P, "a") == 0);
try expect(@bitOffsetOf(P, "b") == 8);
try expect(@bitOffsetOf(P, "c") == 40);
try expect(@bitOffsetOf(P, "d") == 48);
try expect(@bitOffsetOf(P, "e") == 51);
try expect(@bitOffsetOf(P, "f") == 56);
try expect(@bitOffsetOf(P, "g") == 72);
try expect(@offsetOf(A, "a") * 8 == @bitOffsetOf(A, "a"));
try expect(@offsetOf(A, "b") * 8 == @bitOffsetOf(A, "b"));
try expect(@offsetOf(A, "c") * 8 == @bitOffsetOf(A, "c"));
try expect(@offsetOf(A, "d") * 8 == @bitOffsetOf(A, "d"));
try expect(@offsetOf(A, "e") * 8 == @bitOffsetOf(A, "e"));
try expect(@offsetOf(A, "f") * 8 == @bitOffsetOf(A, "f"));
try expect(@offsetOf(A, "g") * 8 == @bitOffsetOf(A, "g"));
}
|
test/behavior/sizeof_and_typeof.zig
|
const std = @import("std");
const stdx = @import("stdx");
const string = stdx.string;
const algo = stdx.algo;
const ds = stdx.ds;
const t = stdx.testing;
const builtin = @import("builtin");
const tracy = stdx.debug.tracy;
const document = stdx.textbuf.document;
const Document = document.Document;
const LineChunkId = document.LineChunkId;
const log = stdx.log.scoped(.parser);
const tokenizer = @import("tokenizer.zig");
const Tokenizer = tokenizer.Tokenizer;
const grammar = @import("grammar.zig");
const RuleId = grammar.RuleId;
const RuleDecl = grammar.RuleDecl;
const MatchOp = grammar.MatchOp;
const MatchOpId = grammar.MatchOpId;
const Grammar = grammar.Grammar;
const _ast = @import("ast.zig");
const Tree = _ast.Tree;
const TokenId = _ast.TokenId;
const TokenListId = _ast.TokenListId;
const Token = _ast.Token;
const LineTokenBuffer = _ast.LineTokenBuffer;
const NullToken = stdx.ds.CompactNull(TokenId);
// Creates a runtime parser from a PEG based config grammar.
// Parses in linear time with respect to source size using a memoization cache. Two cache implementations depending on token list size.
// Supports left recursion.
// Supports look-ahead operators.
// Initial support for incremental retokenize.
// TODO: Implement incremental reparsing.
// TODO: Use literal hashmap for token choice ops
// TODO: Flatten rules with the same starting ops.
// LINKS:
// https://medium.com/@gvanrossum_83706/peg-parsing-series-de5d41b2ed60
// https://pest.rs/book/grammars/peg.html
const DebugParseRule = false and builtin.mode == .Debug;
// Sources with more tokens than this threshold use a cache map instead of a cache stack for parse rule memoization.
const CacheMapTokenThreshold = 10000;
pub const Parser = struct {
const Self = @This();
alloc: std.mem.Allocator,
tokenizer: Tokenizer,
decls: []const RuleDecl,
ops: []const MatchOp,
grammar: *Grammar,
buf: struct {
// Node ptrs.
node_ptrs: std.ArrayList(NodePtr),
// Slices to node_ptrs.
node_slices: std.ArrayList(NodeSlice),
// Node data that points to tokens.
node_tokens: std.ArrayList(NodeTokenPtr),
},
// Used to accumulate nodes together to create a list.
node_list_stack: std.ArrayList(NodePtr),
// For nodes that don't point to any additional data.
next_scalar_node_id: NodeId,
// Used to detect recursive calls to parseRule
is_parsing_rule_stack: ds.BitArrayList,
// Memoization stack to cache parseRule results at every token position.
// TODO: A future optimization could bucket rules that match the same first token together. It could save more memory.
parse_rule_cache_stack: std.ArrayList(CacheItem),
// Use a cache map for source with many tokens. It's slower than the cache stack but uses way a lot less memory.
parse_rule_cache_map: std.AutoHashMap(u32, CacheItem),
// The current starting pos in the stack bufs.
rule_stack_start: u32,
pub fn init(alloc: std.mem.Allocator, g: *Grammar) Self {
var new = Self{
.alloc = alloc,
.tokenizer = Tokenizer.init(g),
.decls = g.decls.items,
.ops = g.ops.items,
.grammar = g,
.node_list_stack = std.ArrayList(NodePtr).init(alloc),
.is_parsing_rule_stack = ds.BitArrayList.init(alloc),
.parse_rule_cache_stack = std.ArrayList(CacheItem).init(alloc),
.parse_rule_cache_map = std.AutoHashMap(u32, CacheItem).init(alloc),
.rule_stack_start = undefined,
.next_scalar_node_id = 1,
.buf = .{
.node_ptrs = std.ArrayList(NodePtr).init(alloc),
.node_slices = std.ArrayList(NodeSlice).init(alloc),
.node_tokens = std.ArrayList(NodeTokenPtr).init(alloc),
},
};
return new;
}
pub fn deinit(self: *Self) void {
self.node_list_stack.deinit();
self.is_parsing_rule_stack.deinit();
self.parse_rule_cache_stack.deinit();
self.parse_rule_cache_map.deinit();
self.buf.node_ptrs.deinit();
self.buf.node_slices.deinit();
self.buf.node_tokens.deinit();
}
fn parseMatchManyWithLeftTerm(self: *Self, comptime Context: type, ctx: *Context, comptime OneOrMore: bool, op_id: MatchOpId, left_id: RuleId, left_node: NodePtr) ParseNodeWithLeftResult {
// Save starting point and accumulate children on the stack.
const list_start = self.node_list_stack.items.len;
defer self.node_list_stack.shrinkRetainingCapacity(list_start);
var consumed_left = false;
inner: {
while (true) {
const mark = ctx.state.mark();
const res = self.parseMatchOpWithLeftTerm(Context, ctx, op_id, left_id, left_node);
if (res.matched) {
if (res.node_ptr) |node_ptr| {
self.node_list_stack.append(node_ptr) catch unreachable;
}
if (res.consumed_left) {
consumed_left = true;
break;
}
} else {
ctx.state.restoreMark(&mark);
break :inner;
}
}
// Parse the right terms.
while (true) {
const mark = ctx.state.mark();
const res = self.parseMatchOp(Context, ctx, op_id);
if (res.matched) {
if (res.node_ptr) |node_ptr| {
self.node_list_stack.append(node_ptr) catch unreachable;
}
} else {
ctx.state.restoreMark(&mark);
break :inner;
}
}
}
const num_children = @intCast(u32, self.node_list_stack.items.len - list_start);
if (OneOrMore and num_children == 0) {
return NoLeftMatch;
}
const list_id = @intCast(u32, self.buf.node_slices.items.len);
const start = @intCast(u32, self.buf.node_ptrs.items.len);
self.buf.node_slices.append(.{
.start = start,
.end = start + num_children,
}) catch unreachable;
self.buf.node_ptrs.appendSlice(self.node_list_stack.items[list_start..]) catch unreachable;
return .{
.matched = true,
.consumed_left = consumed_left,
.node_ptr = .{
.id = list_id,
.tag = self.grammar.node_list_tag,
},
};
}
// TODO: Since we only cache rules, we might need to create a separate stack so we don't keep creating new list nodes at the same pos.
fn parseMatchMany(self: *Self, comptime Context: type, ctx: *Context, comptime OneOrMore: bool, op_id: MatchOpId) ParseNodeResult {
// Save starting point and accumulate children on the stack.
const list_start = self.node_list_stack.items.len;
defer self.node_list_stack.shrinkRetainingCapacity(list_start);
while (true) {
const mark = ctx.state.mark();
const res = self.parseMatchOp(Context, ctx, op_id);
if (res.matched) {
if (res.node_ptr) |node_ptr| {
self.node_list_stack.append(node_ptr) catch unreachable;
}
} else {
ctx.state.restoreMark(&mark);
break;
}
}
const num_children = @intCast(u32, self.node_list_stack.items.len - list_start);
if (OneOrMore and num_children == 0) {
return NoMatch;
}
const list_id = @intCast(u32, self.buf.node_slices.items.len);
const start = @intCast(u32, self.buf.node_ptrs.items.len);
self.buf.node_slices.append(.{
.start = start,
.end = start + num_children,
}) catch unreachable;
self.buf.node_ptrs.appendSlice(self.node_list_stack.items[list_start..]) catch unreachable;
return .{
.matched = true,
.node_ptr = .{
.id = list_id,
.tag = self.grammar.node_list_tag,
},
};
}
fn parseMatchOpWithLeftTerm(self: *Self, comptime Context: type, ctx: *Context, id: MatchOpId, left_id: RuleId, left_node: NodePtr) ParseNodeWithLeftResult {
const op = self.ops[id];
switch (op) {
.MatchOptional => |inner| {
const res = self.parseMatchOpWithLeftTerm(Context, ctx, inner.op_id, left_id, left_node);
if (res.matched) {
return res;
} else {
return .{
.matched = true,
.consumed_left = false,
.node_ptr = null,
};
}
},
.MatchNegLookahead => |m| {
const mark = ctx.state.mark();
const res = self.parseMatchOpWithLeftTerm(Context, ctx, m.op_id, left_id, left_node);
if (res.matched) {
ctx.state.restoreMark(&mark);
return NoLeftMatch;
} else {
return .{
.matched = true,
.consumed_left = false,
.node_ptr = null,
};
}
},
.MatchPosLookahead => |m| {
const mark = ctx.state.mark();
const res = self.parseMatchOpWithLeftTerm(Context, ctx, m.op_id, left_id, left_node);
if (res.matched) {
ctx.state.restoreMark(&mark);
return .{
.matched = true,
.consumed_left = false,
.node_ptr = null,
};
} else {
return NoLeftMatch;
}
},
.MatchRule => |inner| {
// log.warn("MatchRule", .{});
if (inner.rule_id == left_id) {
return .{
.matched = true,
.consumed_left = true,
.node_ptr = left_node,
};
} else {
const res = self.parseRuleWithLeftTerm(Context, ctx, inner.rule_id, left_id, left_node, true);
if (res.matched) {
return res;
}
}
},
.MatchSeq => |inner| {
const mark = ctx.state.mark();
var last_match: ?NodePtr = null;
var i = inner.ops.start;
while (i < inner.ops.end) : (i += 1) {
const res = self.parseMatchOpWithLeftTerm(Context, ctx, i, left_id, left_node);
if (res.matched) {
if (res.node_ptr != null) {
last_match = res.node_ptr;
}
if (res.consumed_left) {
i += 1;
break;
}
} else {
ctx.state.restoreMark(&mark);
return NoLeftMatch;
}
}
while (i < inner.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (res.matched) {
if (res.node_ptr != null) {
last_match = res.node_ptr;
}
} else {
ctx.state.restoreMark(&mark);
return NoLeftMatch;
}
}
return .{
.matched = true,
.consumed_left = true,
.node_ptr = last_match,
};
},
.MatchOneOrMore => |m| {
return self.parseMatchManyWithLeftTerm(Context, ctx, true, m.op_id, left_id, left_node);
},
.MatchChoice => |inner| {
// log.warn("MatchChoice", .{});
var i = inner.ops.start;
while (i < inner.ops.end) : (i += 1) {
const res = self.parseMatchOpWithLeftTerm(Context, ctx, i, left_id, left_node);
if (res.matched) {
return res;
}
}
},
.MatchToken, .MatchLiteral => {
return NoLeftMatch;
},
else => stdx.panicFmt("unsupported: {s}", .{@tagName(op)}),
}
return NoLeftMatch;
}
// Assume each op will leave the parser pos in the right place on match or no match.
fn parseMatchOp(self: *Self, comptime Context: type, ctx: *Context, id: MatchOpId) ParseNodeResult {
if (Context.debug) {
ctx.debug.stats.parse_match_ops += 1;
}
const op = self.ops[id];
switch (op) {
.MatchToken => |inner| {
// log.warn("MatchToken {s}", .{self.grammar.getTokenName(inner.tag)});
if (ctx.state.nextAtEnd()) {
return NoMatch;
}
const next = ctx.state.peekNext();
if (inner.tag == next.tag) {
const token_ctx = ctx.state.getTokenContext();
defer _ = ctx.state.consumeNext(Context.useCacheMap);
return self.createMatchedNodeTokenResult(token_ctx, ctx.state.getAssertNextTokenId(), inner.capture);
}
},
.MatchLiteral => |m| {
// Fast comparison with precomputed literal tags.
if (ctx.state.nextAtEnd()) {
return NoMatch;
}
const next = ctx.state.peekNext();
if (m.computed_literal_tag == next.literal_tag) {
const token_ctx = ctx.state.getTokenContext();
defer _ = ctx.state.consumeNext(Context.useCacheMap);
return self.createMatchedNodeTokenResult(token_ctx, ctx.state.getAssertNextTokenId(), m.capture);
}
},
.MatchTokenText => |inner| {
// log.warn("MatchTokenText '{s}'", .{inner.str});
if (ctx.state.nextAtEnd()) {
return NoMatch;
}
const next = ctx.state.peekNext();
if (inner.tag == next.tag) {
const token_ctx = ctx.state.getTokenContext();
const str = ctx.state.getTokenString(token_ctx, next);
const inner_str = self.grammar.getString(inner.str);
if (stdx.string.eq(inner_str, str)) {
defer _ = ctx.state.consumeNext(Context.useCacheMap);
return self.createMatchedNodeTokenResult(token_ctx, ctx.state.getAssertNextTokenId(), inner.capture);
}
}
},
.MatchZeroOrMore => |inner| {
return self.parseMatchMany(Context, ctx, false, inner.op_id);
},
.MatchOneOrMore => |inner| {
return self.parseMatchMany(Context, ctx, true, inner.op_id);
},
.MatchRule => |inner| {
if (DebugParseRule) {
if (ctx.state.next_tok_id != null) {
const str = ctx.ast.getTokenString(ctx.state.next_tok_id.?);
log.warn("parseRule {s} {} '{s}'", .{ self.grammar.getRuleName(inner.rule_id), ctx.state.next_tok_id, str });
}
}
const res = self.parseRule(Context, ctx, inner.rule_id);
if (res.matched) {
if (DebugParseRule) {
if (ctx.state.next_tok_id != null) {
const str = ctx.ast.getTokenString(ctx.state.next_tok_id.?);
log.warn("MATCHED {s} {} '{s}'", .{ self.grammar.getRuleName(inner.rule_id), ctx.state.next_tok_id, str });
}
}
return res;
}
},
.MatchOptional => |m| {
// log.warn("MatchOptional", .{});
const res = self.parseMatchOp(Context, ctx, m.op_id);
if (res.matched) {
return res;
} else {
// Report to parent that we still matched.
return .{
.matched = true,
.node_ptr = null,
};
}
},
.MatchNegLookahead => |m| {
// Returns no match if inner op matches and resets position.
// Returns match if inner op doesn't match but does not advance the position.
const mark = ctx.state.mark();
const res = self.parseMatchOp(Context, ctx, m.op_id);
if (res.matched) {
ctx.state.restoreMark(&mark);
return NoMatch;
} else {
return .{
.matched = true,
.node_ptr = null,
};
}
},
.MatchPosLookahead => |m| {
// Returns match if inner op matches but does not advance the position.
// Returns no match if inner op doesn't match.
const mark = ctx.state.mark();
const res = self.parseMatchOp(Context, ctx, m.op_id);
if (res.matched) {
ctx.state.restoreMark(&mark);
return .{
.matched = true,
.node_ptr = null,
};
} else {
return NoMatch;
}
},
.MatchSeq => |inner| {
// log.warn("MatchSeq", .{});
const mark = ctx.state.mark();
var last_match: ?NodePtr = null;
var i = inner.ops.start;
while (i < inner.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (res.matched) {
if (res.node_ptr != null) {
last_match = res.node_ptr;
}
} else {
ctx.state.restoreMark(&mark);
return NoMatch;
}
}
return .{
.matched = true,
.node_ptr = last_match,
};
},
.MatchChoice => |inner| {
// log.warn("MatchChoice", .{});
var i = inner.ops.start;
while (i < inner.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (res.matched) {
return res;
}
}
},
}
return NoMatch;
}
fn setNodeField(self: *Self, _: RuleId, list_start: u32, idx: *u32, op_id: MatchOpId, node_ptr: ?NodePtr) void {
const op = &self.ops[op_id];
if (self.grammar.shouldCaptureRule(op)) {
if (node_ptr != null) {
// Save child field.
self.node_list_stack.items[list_start + idx.*] = node_ptr.?;
} else {
// Save null field.
self.node_list_stack.items[list_start + idx.*] = .{
.id = 0,
.tag = self.grammar.null_node_tag,
};
}
idx.* += 1;
}
}
fn parseRuleWithLeftTerm(self: *Self, comptime Context: type, ctx: *Context, id: RuleId, left_id: RuleId, left_node: NodePtr, check_recursion: bool) ParseNodeWithLeftResult {
// log.warn("parseRuleWithLeftTerm {s} {}", .{self.grammar.getRuleName(id), ctx.state.next_tok_id});
if (Context.debug) {
const frame = CallFrame{
.parse_rule_id = id,
.next_token_id = ctx.state.next_tok_id,
};
ctx.debug.call_stack.append(frame) catch unreachable;
if (self.rule_stack_start + self.decls.len == self.is_parsing_rule_stack.buf.items.len) {
// Copy the current call stack if this is furthest token idx reached.
ctx.debug.max_call_stack.resize(ctx.debug.call_stack.items.len) catch unreachable;
std.mem.copy(CallFrame, ctx.debug.max_call_stack.items, ctx.debug.call_stack.items);
}
}
defer if (Context.debug) {
_ = ctx.debug.call_stack.pop();
};
const stack_pos = self.rule_stack_start + id;
if (check_recursion) {
if (self.is_parsing_rule_stack.isSet(stack_pos)) {
return NoLeftMatch;
}
self.is_parsing_rule_stack.set(stack_pos);
}
defer {
if (check_recursion) {
self.is_parsing_rule_stack.unset(stack_pos);
}
}
const decl = self.decls[id];
const mark = ctx.state.mark();
inner: {
if (decl.is_inline) {
// Super decl will just return it's child and won't create a new node.
// TODO: What to do with multiple children? Currently we just return that last matched child node.
var last: ?NodePtr = null;
var i: u32 = decl.ops.start;
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOpWithLeftTerm(Context, ctx, i, left_id, left_node);
if (!res.matched) {
break :inner;
} else {
if (res.node_ptr != null) {
last = res.node_ptr.?;
}
if (res.consumed_left) {
i += 1;
break;
}
}
}
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (!res.matched) {
break :inner;
} else {
if (res.node_ptr != null) {
last = res.node_ptr.?;
}
}
}
return .{
.matched = true,
.consumed_left = true,
.node_ptr = last,
};
} else {
const list_start = @intCast(u32, self.node_list_stack.items.len);
defer self.node_list_stack.shrinkRetainingCapacity(list_start);
const num_fields = self.grammar.getNumChildFields(id);
self.node_list_stack.resize(list_start + num_fields) catch unreachable;
// Keep matching with given left node until an op consumed it.
// Some ops can match but not consume it. eg. MatchOptional
var cur_field: u32 = 0;
var i = decl.ops.start;
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOpWithLeftTerm(Context, ctx, i, left_id, left_node);
if (!res.matched) {
break :inner;
} else {
self.setNodeField(id, list_start, &cur_field, i, res.node_ptr);
if (res.consumed_left) {
i += 1;
break;
}
}
}
// Parse the rest of the ops normally.
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (!res.matched) {
break :inner;
} else {
self.setNodeField(id, list_start, &cur_field, i, res.node_ptr);
}
}
if (num_fields > 0) {
const list_id = @intCast(u32, self.buf.node_slices.items.len);
const start = @intCast(u32, self.buf.node_ptrs.items.len);
self.buf.node_slices.append(.{
.start = start,
.end = start + num_fields,
}) catch unreachable;
self.buf.node_ptrs.appendSlice(self.node_list_stack.items[list_start..]) catch unreachable;
return .{ .matched = true, .consumed_left = true, .node_ptr = NodePtr{
.id = list_id,
.tag = id,
} };
} else {
return .{ .matched = true, .consumed_left = true, .node_ptr = NodePtr{
.id = self.getNextScalarNodeId(),
.tag = id,
} };
}
}
}
// Failed to match. Revert to start state.
ctx.state.restoreMark(&mark);
return NoLeftMatch;
}
fn parseRuleDefault(self: *Self, comptime Context: type, ctx: *Context, id: RuleId) ParseNodeResult {
// log.warn("parsing rule {s}", .{self.grammar.getRuleName(id)});
const decl = self.decls[id];
const mark = ctx.state.mark();
inner: {
if (decl.is_inline) {
// Super decl will just return it's child and won't create a new node.
// TODO: What to do with multiple children? Currently we just return that last matched child node.
var last: ?NodePtr = null;
var i: u32 = decl.ops.start;
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (!res.matched) {
break :inner;
} else {
if (res.node_ptr != null) {
last = res.node_ptr.?;
}
}
}
return .{
.matched = true,
.node_ptr = last,
};
} else {
const list_start = @intCast(u32, self.node_list_stack.items.len);
defer self.node_list_stack.shrinkRetainingCapacity(list_start);
const num_fields = self.grammar.getNumChildFields(id);
self.node_list_stack.resize(list_start + num_fields) catch unreachable;
var cur_field: u32 = 0;
var i = decl.ops.start;
while (i < decl.ops.end) : (i += 1) {
const res = self.parseMatchOp(Context, ctx, i);
if (!res.matched) {
// log.warn("failed at idx {}", .{i - decl.ops.start});
break :inner;
} else {
self.setNodeField(id, list_start, &cur_field, i, res.node_ptr);
}
}
if (num_fields > 0) {
const list_id = @intCast(u32, self.buf.node_slices.items.len);
const start = @intCast(u32, self.buf.node_ptrs.items.len);
self.buf.node_slices.append(.{
.start = start,
.end = start + num_fields,
}) catch unreachable;
self.buf.node_ptrs.appendSlice(self.node_list_stack.items[list_start..]) catch unreachable;
return .{ .matched = true, .node_ptr = NodePtr{
.id = list_id,
.tag = id,
} };
} else {
return .{
.matched = true,
.node_ptr = NodePtr{
.id = self.getNextScalarNodeId(),
.tag = id,
},
};
}
}
}
// Failed to match. Revert to start state.
ctx.state.restoreMark(&mark);
return NoMatch;
}
fn getNextScalarNodeId(self: *Self) NodeId {
defer self.next_scalar_node_id += 1;
return self.next_scalar_node_id;
}
fn getCachedParseRule(self: *Self, comptime UseCacheMap: bool, key: u32) ?CacheItem {
if (UseCacheMap) {
return self.parse_rule_cache_map.get(key);
} else {
const res = self.parse_rule_cache_stack.items[key];
return if (res.state != .Empty) res else null;
}
}
fn setCachedParseRule(self: *Self, comptime UseCacheMap: bool, key: u32, res: CacheItem) void {
if (UseCacheMap) {
// log.warn("set cached {}", .{res});
self.parse_rule_cache_map.put(key, res) catch unreachable;
} else {
self.parse_rule_cache_stack.items[key] = res;
}
}
fn parseRule(self: *Self, comptime Context: type, ctx: *Context, id: RuleId) ParseNodeResult {
if (Context.debug) {
const frame = CallFrame{
.parse_rule_id = id,
.next_token_id = ctx.state.next_tok_id,
};
ctx.debug.call_stack.append(frame) catch unreachable;
if (self.rule_stack_start + self.decls.len == self.is_parsing_rule_stack.buf.items.len) {
// Copy the current call stack if this is furthest token idx reached.
ctx.debug.max_call_stack.resize(ctx.debug.call_stack.items.len) catch unreachable;
std.mem.copy(CallFrame, ctx.debug.max_call_stack.items, ctx.debug.call_stack.items);
}
}
defer if (Context.debug) {
_ = ctx.debug.call_stack.pop();
};
const stack_pos = self.rule_stack_start + id;
if (self.is_parsing_rule_stack.isSet(stack_pos)) {
// If we're parsing the same rule and haven't advanced return NoMatch.
return NoMatch;
}
self.is_parsing_rule_stack.set(stack_pos);
defer self.is_parsing_rule_stack.unset(stack_pos);
var final_res: ParseNodeResult = undefined;
// Check cache.
// log.warn("{} {}", .{stack_pos, self.parse_rule_cache_stack.items.len});
const mb_cache_res = self.getCachedParseRule(Context.useCacheMap, stack_pos);
if (mb_cache_res) |cache_res| {
const cache_state = cache_res.state;
if (cache_state == .Match) {
if (Context.State == TokenState) {
const mark = TokenState.Mark{
.next_tok_id = cache_res.next_token_id,
.rule_stack_start = cache_res.rule_stack_start,
};
ctx.state.restoreMark(&mark);
} else if (Context.State == LineTokenState) {
const mark = LineTokenState.Mark{
.rule_stack_start = cache_res.rule_stack_start,
.next_tok_id = cache_res.next_token_id,
.leaf_id = cache_res.next_token_ctx.leaf_id,
.chunk_line_idx = cache_res.next_token_ctx.chunk_line_idx,
};
ctx.state.restoreMark(&mark);
} else unreachable;
// Restoring mark either advances the token pointer or stays the same place.
if (stack_pos - id < self.rule_stack_start) {
// Reset any existing stack frame if we advanced.
const new_size = self.rule_stack_start + self.decls.len;
self.is_parsing_rule_stack.unsetRange(self.rule_stack_start, new_size);
}
return .{
.matched = true,
.node_ptr = cache_res.node_ptr,
};
} else {
return NoMatch;
}
}
defer if (mb_cache_res == null) {
if (final_res.matched) {
if (Context.State == TokenState) {
self.setCachedParseRule(Context.useCacheMap, stack_pos, .{
.state = .Match,
.node_ptr = final_res.node_ptr,
.next_token_id = ctx.state.next_tok_id,
.rule_stack_start = self.rule_stack_start,
});
} else if (Context.State == LineTokenState) {
self.setCachedParseRule(Context.useCacheMap, stack_pos, .{
.state = .Match,
.node_ptr = final_res.node_ptr,
.next_token_ctx = ctx.state.getTokenContext(),
.next_token_id = ctx.state.next_tok_id,
.rule_stack_start = self.rule_stack_start,
});
} else unreachable;
} else {
self.setCachedParseRule(Context.useCacheMap, stack_pos, .{
.state = .NoMatch,
});
}
};
if (Context.debug) {
ctx.debug.stats.parse_rule_ops_no_cache += 1;
}
const rule = self.grammar.getRule(id);
if (rule.is_left_recursive) {
// First parse rule normally.
var res = self.parseRuleDefault(Context, ctx, id);
if (res.node_ptr == null) {
// Matched but didn't capture. Initialize as a null node_ptr and continue with left recursion.
res.node_ptr = .{
.id = 0,
.tag = self.grammar.null_node_tag,
};
}
// Continue to try left recursion until it fails.
while (true) {
const new_res = self.parseRuleWithLeftTerm(Context, ctx, id, id, res.node_ptr.?, false);
if (new_res.matched) {
res = .{ .matched = true, .node_ptr = new_res.node_ptr };
} else {
break;
}
}
final_res = res;
return final_res;
} else {
final_res = self.parseRuleDefault(Context, ctx, id);
return final_res;
}
}
fn resetParser(self: *Self, comptime UseHashMap: bool) void {
self.rule_stack_start = 0;
const size = self.rule_stack_start + self.decls.len;
self.is_parsing_rule_stack.clearRetainingCapacity();
self.is_parsing_rule_stack.resizeFillNew(size, false) catch unreachable;
self.parse_rule_cache_map.clearRetainingCapacity();
if (UseHashMap) {
self.parse_rule_cache_stack.clearRetainingCapacity();
} else {
self.parse_rule_cache_stack.resize(size) catch unreachable;
std.mem.set(CacheItem, self.parse_rule_cache_stack.items[0..size], .{});
}
self.next_scalar_node_id = 1;
self.node_list_stack.clearRetainingCapacity();
self.buf.node_ptrs.clearRetainingCapacity();
self.buf.node_slices.clearRetainingCapacity();
self.buf.node_tokens.clearRetainingCapacity();
}
pub fn parse(self: *Self, comptime Config: ParseConfig, src: Source(Config)) ParseResult(Config) {
return self.parseMain(Config, src, {});
}
pub fn parseDebug(self: *Self, comptime Config: ParseConfig, src: Source(Config), debug: *DebugInfo) ParseResult(Config) {
return self.parseMain(Config, src, debug);
}
fn parseInternal(self: *Self, comptime Config: ParseConfig, comptime UseCacheMap: bool, comptime Debug: bool, debug: anytype, src: Source(Config), res: *ParseResult(Config)) void {
const State = if (Config.is_incremental) LineTokenState else TokenState;
const Context = ParseContext(State, Tree(Config), UseCacheMap, Debug);
var ctx: Context = undefined;
ctx.state.init(self, src, &res.ast.tokens);
ctx.ast = &res.ast;
if (Debug) {
ctx.debug = debug;
}
self.resetParser(Context.useCacheMap);
res.ast.mb_root = self.parseRule(Context, &ctx, self.grammar.root_rule_id).node_ptr;
// Check if we reached the end.
if (ctx.state.nextAtEnd()) {
res.success = true;
} else {
res.success = false;
res.err_token_id = ctx.state.getErrorToken();
}
}
fn parseMain(self: *Self, comptime Config: ParseConfig, src: Source(Config), debug: anytype) ParseResult(Config) {
const trace = tracy.trace(@src());
defer trace.end();
var ast: Tree(Config) = undefined;
ast.init(self.alloc, self, src);
var res: ParseResult(Config) = undefined;
res.ast = ast;
const Debug = @TypeOf(debug) == *DebugInfo;
if (Debug) {
debug.reset();
}
self.tokenizer.tokenize(Config, src, &res.ast.tokens);
stdx.debug.abortIfUserFlagSet();
const useCacheMap = res.ast.getNumTokens() > CacheMapTokenThreshold;
if (useCacheMap) {
self.parseInternal(Config, true, Debug, debug, src, &res);
} else {
self.parseInternal(Config, false, Debug, debug, src, &res);
}
return res;
}
pub fn reparseChange(self: *Self, comptime Config: ParseConfig, src: Source(Config), cur_ast: *Tree(Config), line_idx: u32, col_idx: u32, change_size: i32) void {
self.reparseChangeMain(Config, src, cur_ast, line_idx, col_idx, change_size, {});
}
pub fn reparseChangeDebug(self: *Self, comptime Config: ParseConfig, src: Source(Config), cur_ast: *Tree(Config), line_idx: u32, col_idx: u32, change_size: i32, debug: *DebugInfo) void {
self.reparseChangeMain(Config, src, cur_ast, line_idx, col_idx, change_size, debug);
}
// col_idx is the the starting pos where the change took place.
// positive change_size indicates it was an insert/replace.
// negative change_size indicates it was a delete/replace.
fn reparseChangeMain(self: *Self, comptime Config: ParseConfig, src: Source(Config), cur_ast: *Tree(Config), line_idx: u32, col_idx: u32, change_size: i32, debug: anytype) void {
const Debug = @TypeOf(debug) == *DebugInfo;
if (Debug) {
debug.reset();
}
self.tokenizer.retokenizeChange(src, &cur_ast.tokens, line_idx, col_idx, change_size, debug);
}
fn createMatchedNodeTokenResult(self: *Self, token_ctx: anytype, token_id: TokenId, capture: bool) ParseNodeResult {
if (capture) {
const id = @intCast(u32, self.buf.node_tokens.items.len);
if (@TypeOf(token_ctx) == LineTokenContext) {
self.buf.node_tokens.append(.{ .token_ctx = token_ctx, .token_id = token_id }) catch unreachable;
} else {
self.buf.node_tokens.append(.{ .token_ctx = .{ .leaf_id = 0, .chunk_line_idx = 0 }, .token_id = token_id }) catch unreachable;
}
return .{
.matched = true,
.node_ptr = .{
.id = id,
.tag = self.grammar.token_value_tag,
},
};
} else {
return .{
.matched = true,
.node_ptr = null,
};
}
}
// TODO: Keeping this code in case we need to detach an ast tree from the underlying source.
// fn createStringNodeData(self: *Self, str: []const u8) [*]u8 {
// _ = self;
// const data = self.alloc.alloc(u8, @sizeOf(u32) + str.len) catch unreachable;
// std.mem.copy(u8, data[0..@sizeOf(u32)], &std.mem.toBytes(@intCast(u32, str.len)));
// std.mem.copy(u8, data[@sizeOf(u32)..], str);
// return data.ptr;
// }
// fn createMatchedStringNodeResult(self: *Self, str: []const u8, capture: bool) ParseNodeResult {
// if (capture) {
// if (str.len == 1) {
// // Create a char value node instead to avoid extra allocation.
// return .{
// .matched = true,
// .node_ptr = .{
// .id = self.getNextNodeId(),
// .tag = self.grammar.char_value_tag,
// .data = @intToPtr([*]u8, str[0]),
// },
// };
// } else {
// return .{
// .matched = true,
// .node_ptr = .{
// .id = self.getNextNodeId(),
// .tag = self.grammar.string_value_tag,
// .data = self.createStringNodeData(str),
// },
// };
// }
// } else {
// return .{
// .matched = true,
// .node_ptr = null,
// };
// }
// }
};
fn Mark(comptime Config: ParseConfig) type {
if (Config.incremental) {
return LineTokenState.Mark;
} else {
return TokenState.Mark;
}
}
const TokenState = struct {
const Self = @This();
const Mark = struct {
next_tok_id: TokenId,
rule_stack_start: u32,
};
src: []const u8,
tokens: *std.ArrayList(Token),
next_tok_id: TokenId,
rule_stack_start: *u32,
is_parsing_rule_stack: *ds.BitArrayList,
parse_rule_cache_stack: *std.ArrayList(CacheItem),
num_decls: u32,
fn init(
self: *Self,
parser: *Parser,
src: []const u8,
tokens: *std.ArrayList(Token),
) void {
self.* = .{
.src = src,
.next_tok_id = 0,
.tokens = tokens,
.rule_stack_start = &parser.rule_stack_start,
.is_parsing_rule_stack = &parser.is_parsing_rule_stack,
.parse_rule_cache_stack = &parser.parse_rule_cache_stack,
.num_decls = @intCast(u32, parser.decls.len),
};
}
inline fn mark(self: *Self) Self.Mark {
return .{
.next_tok_id = self.next_tok_id,
.rule_stack_start = self.rule_stack_start.*,
};
}
inline fn restoreMark(self: *Self, m: *const Self.Mark) void {
// log.warn("restoreMark {}", .{m.next_tok_id});
self.next_tok_id = m.next_tok_id;
self.rule_stack_start.* = m.rule_stack_start;
}
inline fn nextAtEnd(self: *Self) bool {
return self.next_tok_id == self.tokens.items.len;
}
inline fn peekNext(self: *Self) Token {
return self.tokens.items[self.next_tok_id];
}
inline fn getAssertNextTokenId(self: *Self) TokenId {
return self.next_tok_id;
}
fn consumeNext(self: *Self, comptime UseCacheMap: bool) Token {
// Push new set since we advanced the parser pos.
self.rule_stack_start.* += self.num_decls;
const new_size = self.rule_stack_start.* + self.num_decls;
if (self.is_parsing_rule_stack.buf.items.len < new_size) {
self.is_parsing_rule_stack.resize(new_size) catch unreachable;
}
self.is_parsing_rule_stack.unsetRange(self.rule_stack_start.*, new_size);
if (!UseCacheMap) {
if (self.parse_rule_cache_stack.items.len < new_size) {
self.parse_rule_cache_stack.resize(new_size) catch unreachable;
std.mem.set(CacheItem, self.parse_rule_cache_stack.items[self.rule_stack_start.*..new_size], .{});
}
}
defer self.next_tok_id += 1;
return self.tokens.items[self.next_tok_id];
}
// Since we already use a stack frame at each token increment, we can use the len to determine the token index.
fn getErrorToken(self: *Self) TokenId {
const token_idx = self.is_parsing_rule_stack.buf.items.len / self.num_decls - 1;
return @intCast(u32, token_idx);
}
inline fn getNextTokenRef(self: *Self) ?TokenId {
return self.next_tok_id;
}
inline fn getTokenContext(_: *Self) void {
return;
}
inline fn getTokenString(self: *Self, _: void, token: Token) []const u8 {
return self.src[token.loc.start..token.loc.end];
}
};
const LineTokenState = struct {
const Self = @This();
const Mark = struct {
rule_stack_start: u32,
leaf_id: document.NodeId,
chunk_line_idx: u32,
next_tok_id: TokenId,
};
rule_stack_start: *u32,
is_parsing_rule_stack: *ds.BitArrayList,
parse_rule_cache_stack: *std.ArrayList(CacheItem),
doc: *Document,
buf: *LineTokenBuffer,
// Current line data.
next_tok_id: TokenId,
leaf_id: document.NodeId,
chunk: []document.LineId,
chunk_line_idx: u32,
last_leaf_id: u32,
last_chunk_size: u32,
num_decls: u32,
fn init(
self: *Self,
parser: *Parser,
doc: *Document,
buf: *LineTokenBuffer,
) void {
const last_leaf_id = doc.getLastLeaf();
const last_leaf = doc.getNode(last_leaf_id);
self.* = .{
.doc = doc,
.buf = buf,
.rule_stack_start = &parser.rule_stack_start,
.is_parsing_rule_stack = &parser.is_parsing_rule_stack,
.parse_rule_cache_stack = &parser.parse_rule_cache_stack,
.leaf_id = undefined,
.chunk = undefined,
.chunk_line_idx = undefined,
.next_tok_id = undefined,
.last_leaf_id = last_leaf_id,
.last_chunk_size = last_leaf.Leaf.chunk.size,
.num_decls = @intCast(u32, parser.decls.len),
};
self.seekToFirstToken();
}
fn getLineTokenIterator(self: *Self, loc: document.LineLocation) LineTokenIterator {
return LineTokenIterator.init(self.doc, self.buf.lines.items, &self.buf.tokens, loc, .{
.leaf_id = self.last_leaf_id,
.chunk_line_idx = self.last_chunk_size - 1,
});
}
fn getErrorToken(self: *Self) TokenId {
const token_idx = self.is_parsing_rule_stack.buf.items.len / self.num_decls - 1;
var i: u32 = 0;
var iter = self.getLineTokenIterator(self.doc.findLineLoc(0));
while (iter.next()) |token_id| {
if (i == token_idx) {
return token_id;
} else {
i += 1;
}
}
unreachable;
}
inline fn mark(self: *Self) Self.Mark {
return .{
.rule_stack_start = self.rule_stack_start.*,
.leaf_id = self.leaf_id,
.chunk_line_idx = self.chunk_line_idx,
.next_tok_id = self.next_tok_id,
};
}
inline fn restoreMark(self: *Self, m: *const Self.Mark) void {
// log.warn("restoreMark {} {} {}", .{m.leaf_id, m.chunk_line_idx, m.next_tok_id});
self.rule_stack_start.* = m.rule_stack_start;
self.leaf_id = m.leaf_id;
self.next_tok_id = m.next_tok_id;
self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id);
self.chunk_line_idx = m.chunk_line_idx;
}
inline fn nextAtEnd(self: *Self) bool {
return self.next_tok_id == NullToken;
}
inline fn peekNext(self: *Self) Token {
return self.buf.tokens.getNoCheck(self.next_tok_id);
}
inline fn getAssertNextTokenId(self: *Self) TokenId {
return if (self.next_tok_id != NullToken) self.next_tok_id else unreachable;
}
// Find the first next_tok_id and set line context.
fn seekToFirstToken(self: *Self) void {
self.leaf_id = self.doc.getFirstLeaf();
self.chunk_line_idx = 0;
while (true) {
if (self.leaf_id == self.last_leaf_id and self.chunk_line_idx == self.last_chunk_size) {
self.next_tok_id = NullToken;
return;
}
self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id);
const line_id = self.chunk[self.chunk_line_idx];
if (self.buf.lines.items[line_id]) |list_id| {
self.next_tok_id = self.buf.tokens.getListHead(list_id).?;
return;
}
self.chunk_line_idx += 1;
if (self.chunk_line_idx == self.chunk.len) {
// Advance to next chunk.
self.leaf_id = self.doc.getNextLeafNode(self.leaf_id).?;
self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id);
self.chunk_line_idx = 0;
}
}
}
// Called by consumeNext, so it assumes there is a next token.
fn seekToNextToken(self: *Self) void {
self.next_tok_id = self.buf.tokens.getNextIdNoCheck(self.next_tok_id);
if (self.next_tok_id != NullToken) {
// It's the next node in the list.
return;
}
// Find the next list head by iterating line chunks.
while (true) {
self.chunk_line_idx += 1;
if (self.leaf_id == self.last_leaf_id and self.chunk_line_idx == self.last_chunk_size) {
self.next_tok_id = NullToken;
return;
}
if (self.chunk_line_idx == self.chunk.len) {
stdx.debug.abort();
// Advance to next chunk.
self.leaf_id = self.doc.getNextLeafNode(self.leaf_id).?;
self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id);
self.chunk_line_idx = 0;
}
const line_id = self.chunk[self.chunk_line_idx];
if (self.buf.lines.items[line_id]) |list_id| {
if (self.buf.tokens.getListHead(list_id)) |head| {
self.next_tok_id = head;
return;
}
}
}
}
// Assumes there is a next token. Shouldn't be called without checking nextAtEnd first.
fn consumeNext(self: *Self, comptime UseCacheMap: bool) Token {
// log.warn("parser consume next {}", .{self.next_tok_id});
const item = self.buf.tokens.getNodePtrAssumeExists(self.next_tok_id);
self.seekToNextToken();
// Push new set since we advanced the parser pos.
self.rule_stack_start.* += self.num_decls;
const new_size = self.rule_stack_start.* + self.num_decls;
if (self.is_parsing_rule_stack.buf.items.len < new_size) {
self.is_parsing_rule_stack.resize(new_size) catch unreachable;
}
self.is_parsing_rule_stack.unsetRange(self.rule_stack_start.*, new_size);
if (!UseCacheMap) {
if (self.parse_rule_cache_stack.items.len < new_size) {
self.parse_rule_cache_stack.resize(new_size) catch unreachable;
std.mem.set(CacheItem, self.parse_rule_cache_stack.items[self.rule_stack_start.*..new_size], .{});
}
}
return item.data;
}
inline fn getTokenContext(self: *Self) LineTokenContext {
return .{
.leaf_id = self.leaf_id,
.chunk_line_idx = self.chunk_line_idx,
};
}
inline fn getTokenString(self: *Self, ctx: LineTokenContext, token: Token) []const u8 {
return self.doc.getSubstringFromLineLoc(ctx, token.loc.start, token.loc.end);
}
};
const LineTokenContext = document.LineLocation;
pub fn Source(comptime Config: ParseConfig) type {
if (Config.is_incremental) {
return *Document;
} else {
return []const u8;
}
}
const ParseNodeWithLeftResult = struct {
matched: bool,
consumed_left: bool,
node_ptr: ?NodePtr,
};
const ParseNodeResult = struct {
// TODO: accpet 3 values NoMatch/MatchAdvance/MatchNoAdvance like tokenizer
matched: bool,
// TODO: After making null_tag a predefined, remove optional to simplify.
// Whether node_ptr is defined depends on matched.
node_ptr: ?NodePtr,
};
const NoLeftMatch = ParseNodeWithLeftResult{ .matched = false, .consumed_left = false, .node_ptr = null };
const NoMatch = ParseNodeResult{ .matched = false, .node_ptr = null };
pub const DebugInfo = struct {
const Self = @This();
stats: struct {
inc_tokens_added: u32,
inc_tokens_removed: u32,
// Evaluated match ops, includes parseRules made a cache hit.
parse_match_ops: u32,
// Evaluated parse rules that didn't return early from a cache hit.
parse_rule_ops_no_cache: u32,
},
call_stack: std.ArrayList(CallFrame),
// If parsing failed, this is the call stack we want.
max_call_stack: std.ArrayList(CallFrame),
pub fn init(self: *Self, alloc: std.mem.Allocator) void {
self.* = .{
.stats = undefined,
.call_stack = std.ArrayList(CallFrame).init(alloc),
.max_call_stack = std.ArrayList(CallFrame).init(alloc),
};
self.reset();
}
pub fn deinit(self: *Self) void {
self.call_stack.deinit();
self.max_call_stack.deinit();
}
pub fn reset(self: *Self) void {
self.stats = .{
.inc_tokens_added = 0,
.inc_tokens_removed = 0,
.parse_match_ops = 0,
.parse_rule_ops_no_cache = 0,
};
self.call_stack.clearRetainingCapacity();
self.max_call_stack.clearRetainingCapacity();
}
pub fn formatMaxCallStack(self: *Self, comptime Config: ParseConfig, ast: *const Tree(Config), writer: anytype) void {
const first = self.max_call_stack.items[0];
writer.print("{s}({}'{s}')", .{ ast.grammar.getRuleName(first.parse_rule_id), first.next_token_id, ast.getTokenString(first.next_token_id.?) }) catch unreachable;
for (self.max_call_stack.items[1..]) |frame| {
writer.print(" -> {s}({}'{s}')", .{ ast.grammar.getRuleName(frame.parse_rule_id), frame.next_token_id, ast.getTokenString(frame.next_token_id.?) }) catch unreachable;
}
writer.print("\n", .{}) catch unreachable;
}
};
const CallFrame = struct {
parse_rule_id: RuleId,
next_token_id: ?TokenId,
};
fn ParseContext(comptime State: type, comptime Ast: type, comptime UseCacheMap: bool, comptime Debug: bool) type {
return struct {
const State = State;
const debug = Debug;
const useCacheMap = UseCacheMap;
state: State,
ast: *Ast,
debug: if (Debug) *DebugInfo else void,
};
}
pub const ParseConfig = struct {
is_incremental: bool = true,
};
// Contains parse rule result at some parser position.
const CacheItem = struct {
const State = enum {
Empty,
NoMatch,
Match,
};
state: State = .Empty,
// Only defined when state == .Matched
node_ptr: ?NodePtr = undefined,
next_token_ctx: LineTokenContext = undefined,
next_token_id: TokenId = undefined,
rule_stack_start: u32 = undefined,
};
pub const NodeTokenPtr = struct {
// Used only for incremental parser to locate a line relative token.
// TODO: When incremental ast reparsing is implemented, this will probably go away.
token_ctx: LineTokenContext,
token_id: TokenId,
};
// Points to data which can be a list of other NodePtrs or a NodeTokenPtr.
pub const NodePtr = struct {
id: NodeId,
tag: NodeTag,
};
// Index into a buffer.
pub const NodeId = u32;
// Index to RuleDecl and special node types.
pub const NodeTag = u32;
pub const NodeSlice = ds.RelSlice(u32);
pub fn ParseResult(comptime Config: ParseConfig) type {
return struct {
success: bool,
err_token_id: TokenId,
ast: Tree(Config),
pub fn deinit(self: *@This()) void {
self.ast.deinit();
}
};
}
pub fn TokenRef(comptime Config: ParseConfig) type {
if (Config.is_incremental) {
return struct {
line_ctx: LineTokenContext,
token_id: TokenId,
};
} else return TokenId;
}
const LineTokenIterator = struct {
const Self = @This();
cur_loc: document.LineLocation,
cur_chunk_line_end_idx: u32,
next_token_id: TokenId,
end_loc: document.LineLocation,
token_lists: []const ?TokenListId,
tokens: *ds.CompactManySinglyLinkedList(TokenListId, TokenId, Token),
doc: *Document,
fn init(doc: *Document, token_lists: []const ?TokenListId, tokens: *ds.CompactManySinglyLinkedList(TokenListId, TokenId, Token), loc: document.LineLocation, end_loc: document.LineLocation) Self {
var res = Self{
.doc = doc,
.tokens = tokens,
.cur_loc = loc,
.cur_chunk_line_end_idx = @intCast(u32, doc.getLeafLineChunkSlice(loc.leaf_id).len) - 1,
.next_token_id = NullToken,
.end_loc = end_loc,
.token_lists = token_lists,
};
res.seekToNextLineHead();
return res;
}
fn seekToNextLineHead(self: *Self) void {
while (true) {
if (std.meta.eql(self.cur_loc, self.end_loc)) {
self.next_token_id = NullToken;
return;
}
const line_id = self.doc.getLineIdByLoc(self.cur_loc);
if (self.token_lists[line_id]) |list_id| {
self.next_token_id = self.tokens.getListHead(list_id).?;
return;
} else {
self.cur_loc.leaf_id = self.doc.getNextLeafNode(self.cur_loc.leaf_id).?;
self.cur_loc.chunk_line_idx = 0;
self.cur_chunk_line_end_idx = @intCast(u32, self.doc.getLeafLineChunkSlice(self.cur_loc.leaf_id).len) - 1;
}
}
}
fn next(self: *Self) ?TokenId {
if (self.next_token_id == NullToken) {
return null;
} else {
defer {
self.next_token_id = self.tokens.getNextIdNoCheck(self.next_token_id);
if (self.next_token_id == NullToken) {
if (self.cur_loc.chunk_line_idx == self.cur_chunk_line_end_idx) {
if (!std.meta.eql(self.cur_loc, self.end_loc)) {
self.cur_loc.leaf_id = self.doc.getNextLeafNode(self.cur_loc.leaf_id).?;
self.cur_loc.chunk_line_idx = 0;
self.cur_chunk_line_end_idx = @intCast(u32, self.doc.getLeafLineChunkSlice(self.cur_loc.leaf_id).len) - 1;
self.seekToNextLineHead();
}
} else {
self.cur_loc.chunk_line_idx += 1;
}
}
}
return self.next_token_id;
}
}
};
|
parser/parser.zig
|
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
test "void parameters" {
try voidFun(1, void{}, 2, {});
}
fn voidFun(a: i32, b: void, c: i32, d: void) !void {
_ = d;
const v = b;
const vv: void = if (a == 1) v else {};
try expect(a + c == 3);
return vv;
}
test "call function with empty string" {
acceptsString("");
}
fn acceptsString(foo: []u8) void {
_ = foo;
}
test "function pointers" {
const fns = [_]@TypeOf(fn1){
fn1,
fn2,
fn3,
fn4,
};
for (fns) |f, i| {
try expect(f() == @intCast(u32, i) + 5);
}
}
fn fn1() u32 {
return 5;
}
fn fn2() u32 {
return 6;
}
fn fn3() u32 {
return 7;
}
fn fn4() u32 {
return 8;
}
test "number literal as an argument" {
try numberLiteralArg(3);
comptime try numberLiteralArg(3);
}
fn numberLiteralArg(a: anytype) !void {
try expect(a == 3);
}
test "function call with anon list literal" {
const S = struct {
fn doTheTest() !void {
try consumeVec(.{ 9, 8, 7 });
}
fn consumeVec(vec: [3]f32) !void {
try expect(vec[0] == 9);
try expect(vec[1] == 8);
try expect(vec[2] == 7);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "ability to give comptime types and non comptime types to same parameter" {
const S = struct {
fn doTheTest() !void {
var x: i32 = 1;
try expect(foo(x) == 10);
try expect(foo(i32) == 20);
}
fn foo(arg: anytype) i32 {
if (@typeInfo(@TypeOf(arg)) == .Type and arg == i32) return 20;
return 9 + arg;
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "function with inferred error set but returning no error" {
const S = struct {
fn foo() !void {}
};
const return_ty = @typeInfo(@TypeOf(S.foo)).Fn.return_type.?;
try expectEqual(0, @typeInfo(@typeInfo(return_ty).ErrorUnion.error_set).ErrorSet.?.len);
}
|
test/behavior/fn_stage1.zig
|
const std = @import("../std.zig");
usingnamespace std.c;
extern "c" fn __error() *c_int;
pub const _errno = __error;
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn posix_memalign(memptr: *?*c_void, alignment: usize, size: usize) c_int;
pub extern "c" fn malloc_usable_size(?*const c_void) usize;
pub const sf_hdtr = extern struct {
headers: [*]const iovec_const,
hdr_cnt: c_int,
trailers: [*]const iovec_const,
trl_cnt: c_int,
};
pub extern "c" fn sendfile(
in_fd: fd_t,
out_fd: fd_t,
offset: off_t,
nbytes: usize,
sf_hdtr: ?*sf_hdtr,
sbytes: ?*off_t,
flags: u32,
) c_int;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*c_void) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
pub const pthread_mutex_t = extern struct {
inner: ?*c_void = null,
};
pub const pthread_cond_t = extern struct {
inner: ?*c_void = null,
};
pub const pthread_attr_t = extern struct {
__size: [56]u8,
__align: c_long,
};
pub const EAI = extern enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// name could not be resolved at this time
AGAIN = 2,
/// flags parameter had an invalid value
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// address family not recognized
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// name does not resolve
NONAME = 8,
/// service not recognized for socket type
SERVICE = 9,
/// intended socket type was not recognized
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
/// get address to use bind()
pub const AI_PASSIVE = 0x00000001;
/// fill ai_canonname
pub const AI_CANONNAME = 0x00000002;
/// prevent host name resolution
pub const AI_NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const AI_NUMERICSERV = 0x00000008;
/// valid flags for addrinfo (not a standard def, apps should not use it)
pub const AI_MASK = (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG | AI_ALL | AI_V4MAPPED);
/// IPv6 and IPv4-mapped (with AI_V4MAPPED)
pub const AI_ALL = 0x00000100;
/// accept IPv4-mapped if kernel supports
pub const AI_V4MAPPED_CFG = 0x00000200;
/// only if any address is assigned
pub const AI_ADDRCONFIG = 0x00000400;
/// accept IPv4-mapped IPv6 address
pub const AI_V4MAPPED = 0x00000800;
/// special recommended flags for getipnodebyname
pub const AI_DEFAULT = (AI_V4MAPPED_CFG | AI_ADDRCONFIG);
|
lib/std/c/freebsd.zig
|
usingnamespace @import("clang_options.zig");
pub const data = blk: { @setEvalBranchQuota(6000); break :blk &[_]CliArg{
flagpd1("C"),
flagpd1("CC"),
.{
.name = "E",
.syntax = .flag,
.zig_equivalent = .preprocess_only,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("EB"),
flagpd1("EL"),
flagpd1("Eonly"),
flagpd1("faapcs-bitfield-load"),
flagpd1("H"),
.{
.name = "<input>",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = false,
.psl = false,
},
flagpd1("I-"),
flagpd1("M"),
.{
.name = "MD",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MG",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MM",
.syntax = .flag,
.zig_equivalent = .dep_file_mm,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MMD",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MP",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MV",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("Mach"),
.{
.name = "O0",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "O4",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "O",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("ObjC"),
flagpd1("ObjC++"),
flagpd1("P"),
flagpd1("Q"),
flagpd1("Qn"),
flagpd1("Qunused-arguments"),
flagpd1("Qy"),
.{
.name = "S",
.syntax = .flag,
.zig_equivalent = .asm_only,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "<unknown>",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = false,
.psl = false,
},
flagpd1("WCL4"),
flagpd1("Wall"),
flagpd1("Wdeprecated"),
flagpd1("Wlarge-by-value-copy"),
flagpd1("Wno-deprecated"),
flagpd1("Wno-rewrite-macros"),
flagpd1("Wno-write-strings"),
flagpd1("Wwrite-strings"),
flagpd1("X"),
sepd1("Xanalyzer"),
sepd1("Xarch_device"),
sepd1("Xarch_host"),
sepd1("Xassembler"),
sepd1("Xclang"),
sepd1("Xcuda-fatbinary"),
sepd1("Xcuda-ptxas"),
.{
.name = "Xlinker",
.syntax = .separate,
.zig_equivalent = .for_linker,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("Xopenmp-target"),
sepd1("Xpreprocessor"),
flagpd1("Z"),
flagpd1("Z-Xlinker-no-demangle"),
flagpd1("Z-reserved-lib-cckext"),
flagpd1("Z-reserved-lib-stdc++"),
sepd1("Zlinker-input"),
.{
.name = "CLASSPATH",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "###",
.syntax = .flag,
.zig_equivalent = .dry_run,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "Brepro",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Brepro-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Bt",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Bt+",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "C",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "E",
.syntax = .flag,
.zig_equivalent = .preprocess_only,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "EP",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FA",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FC",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FS",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fx",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "G1",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "G2",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GA",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GF",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GF-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GH",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GL",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GL-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GR",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GR-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GS",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GS-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GT",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GX",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GX-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "GZ",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gd",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ge",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gh",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gm",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gm-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gr",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gregcall",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gv",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gw",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gw-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gy",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gy-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gz",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "H",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "HELP",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "J",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "JMC",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "LD",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "LDd",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "LN",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "MD",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "MDd",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
flagpsl("MT"),
.{
.name = "MTd",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "P",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "QIfist",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "QIntel-jcc-erratum",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "?",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qfast_transcendentals",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qimprecise_fwaits",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qpar",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qsafe_fp_loads",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qspectre",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qspectre-load",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qspectre-load-cf",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qvec",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qvec-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "TC",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "TP",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "V",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "W0",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "W1",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "W2",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "W3",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "W4",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "WL",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "WX",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "WX-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Wall",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Wp64",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "X",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Y-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Yd",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Z7",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "ZH:MD5",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "ZH:SHA1",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "ZH:SHA_256",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "ZI",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Za",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:__cplusplus",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:alignedNew",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:alignedNew-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:auto",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:char8_t",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:char8_t-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:dllexportInlines",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:dllexportInlines-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:forScope",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:inline",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:rvalueCast",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:sizedDealloc",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:sizedDealloc-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:strictStrings",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:ternary",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:threadSafeInit",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:threadSafeInit-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:trigraphs",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:trigraphs-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:twoPhase",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:twoPhase-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:wchar_t",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ze",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zg",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zi",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zl",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zo",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zo-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zp",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zs",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "analyze-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "await",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "bigobj",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "c",
.syntax = .flag,
.zig_equivalent = .c,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "d1PP",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "d1reportAllClassLayout",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "d2FastFail",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "d2Zi+",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "diagnostics:caret",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "diagnostics:classic",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "diagnostics:column",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fallback",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fp:except",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fp:except-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fp:fast",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fp:precise",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "fp:strict",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "help",
.syntax = .flag,
.zig_equivalent = .driver_punt,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "homeparams",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "hotpatch",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "kernel",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "kernel-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "nologo",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "openmp",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "openmp-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "openmp:experimental",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "permissive-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "sdl",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "sdl-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "showFilenames",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "showFilenames-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "showIncludes",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "showIncludes:user",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "u",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "utf-8",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "validate-charset",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "validate-charset-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vmb",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vmg",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vmm",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vms",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vmv",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "volatile:iso",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "volatile:ms",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "w",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "wd4005",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "wd4018",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "wd4100",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "wd4910",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "wd4996",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "all-warnings",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "analyze",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "analyzer-no-default-checks",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "assemble",
.syntax = .flag,
.zig_equivalent = .asm_only,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "assert",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "bootclasspath",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "classpath",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "comments",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "comments-in-macros",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "compile",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "constant-cfstrings",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "debug",
.syntax = .flag,
.zig_equivalent = .debug,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "define-macro",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "dependencies",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "dyld-prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "encoding",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "entry",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "extdirs",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "extra-warnings",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "for-linker",
.syntax = .separate,
.zig_equivalent = .for_linker,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "force-link",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "help-hidden",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-barrier",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-directory",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-directory-after",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-with-prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-with-prefix-after",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-with-prefix-before",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "language",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "library-directory",
.syntax = .separate,
.zig_equivalent = .lib_dir,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "mhwdiv",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "migrate",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-line-commands",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-standard-includes",
.syntax = .flag,
.zig_equivalent = .nostdlibinc,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-standard-libraries",
.syntax = .flag,
.zig_equivalent = .nostdlib,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-undefined",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-warnings",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "optimize",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "output",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "output-class-directory",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "param",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "precompile",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "preprocess",
.syntax = .flag,
.zig_equivalent = .preprocess_only,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "print-diagnostic-categories",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "print-file-name",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "print-missing-file-dependencies",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "print-prog-name",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "profile",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "profile-blocks",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "resource",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "rtlib",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "serialize-diagnostics",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "signed-char",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "std",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "stdlib",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "sysroot",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "target-help",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "trace-includes",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "undefine-macro",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "unsigned-char",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "user-dependencies",
.syntax = .flag,
.zig_equivalent = .dep_file_mm,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "verbose",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "version",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "write-dependencies",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "write-user-dependencies",
.syntax = .flag,
.zig_equivalent = .dep_file,
.pd1 = false,
.pd2 = true,
.psl = false,
},
sepd1("add-plugin"),
flagpd1("faligned-alloc-unavailable"),
flagpd1("all_load"),
sepd1("allowable_client"),
flagpd1("cfg-add-implicit-dtors"),
flagpd1("unoptimized-cfg"),
flagpd1("analyze"),
sepd1("analyze-function"),
sepd1("analyzer-checker"),
flagpd1("analyzer-checker-help"),
flagpd1("analyzer-checker-help-alpha"),
flagpd1("analyzer-checker-help-developer"),
flagpd1("analyzer-checker-option-help"),
flagpd1("analyzer-checker-option-help-alpha"),
flagpd1("analyzer-checker-option-help-developer"),
sepd1("analyzer-config"),
sepd1("analyzer-config-compatibility-mode"),
flagpd1("analyzer-config-help"),
sepd1("analyzer-constraints"),
flagpd1("analyzer-disable-all-checks"),
sepd1("analyzer-disable-checker"),
flagpd1("analyzer-disable-retry-exhausted"),
flagpd1("analyzer-display-progress"),
sepd1("analyzer-dump-egraph"),
sepd1("analyzer-inline-max-stack-depth"),
sepd1("analyzer-inlining-mode"),
flagpd1("analyzer-list-enabled-checkers"),
sepd1("analyzer-max-loop"),
flagpd1("analyzer-opt-analyze-headers"),
flagpd1("analyzer-opt-analyze-nested-blocks"),
sepd1("analyzer-output"),
sepd1("analyzer-purge"),
flagpd1("analyzer-stats"),
sepd1("analyzer-store"),
flagpd1("analyzer-viz-egraph-graphviz"),
flagpd1("analyzer-werror"),
flagpd1("fslp-vectorize-aggressive"),
flagpd1("fno-slp-vectorize-aggressive"),
flagpd1("shared-libasan"),
.{
.name = "Gs",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "O1",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "O2",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ob0",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ob1",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ob2",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Od",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Og",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Oi",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Oi-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Os",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ot",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Ox",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Oy",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Oy-",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
flagpd1("frecord-gcc-switches"),
flagpd1("fno-record-gcc-switches"),
flagpd1("fident"),
flagpd1("fno-ident"),
flagpd1("fexpensive-optimizations"),
flagpd1("fno-expensive-optimizations"),
flagpd1("fdefer-pop"),
flagpd1("fno-defer-pop"),
flagpd1("fextended-identifiers"),
flagpd1("fno-extended-identifiers"),
flagpd1("fhonor-infinites"),
flagpd1("fno-honor-infinites"),
flagpd1("fcuda-rdc"),
flagpd1("fno-cuda-rdc"),
flagpd1("findirect-virtual-calls"),
sepd1("fnew-alignment"),
flagpd1("faligned-new"),
flagpd1("fno-aligned-new"),
flagpd1("fsched-interblock"),
flagpd1("ftree-vectorize"),
flagpd1("fno-tree-vectorize"),
flagpd1("ftree-slp-vectorize"),
flagpd1("fno-tree-slp-vectorize"),
flagpd1("fterminated-vtables"),
flagpd1("grecord-gcc-switches"),
flagpd1("gno-record-gcc-switches"),
flagpd1("nocudainc"),
flagpd1("nocudalib"),
.{
.name = "system-header-prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-system-header-prefix",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("integrated-as"),
flagpd1("no-integrated-as"),
.{
.name = "ansi",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
sepd1("arch"),
flagpd1("arch_errors_fatal"),
sepd1("arch_only"),
flagpd1("arcmt-migrate-emit-errors"),
sepd1("arcmt-migrate-report-output"),
flagpd1("ast-dump"),
flagpd1("ast-dump-all"),
flagpd1("ast-dump-decl-types"),
sepd1("ast-dump-filter"),
flagpd1("ast-dump-lookups"),
flagpd1("ast-list"),
sepd1("ast-merge"),
flagpd1("ast-print"),
flagpd1("ast-view"),
sepd1("aux-target-cpu"),
sepd1("aux-target-feature"),
sepd1("aux-triple"),
flagpd1("bind_at_load"),
flagpd1("building-pch-with-obj"),
flagpd1("bundle"),
sepd1("bundle_loader"),
.{
.name = "c",
.syntax = .flag,
.zig_equivalent = .c,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("cc1"),
flagpd1("cc1as"),
flagpd1("ccc-arcmt-check"),
sepd1("ccc-arcmt-migrate"),
flagpd1("ccc-arcmt-modify"),
sepd1("ccc-gcc-name"),
sepd1("ccc-install-dir"),
sepd1("ccc-objcmt-migrate"),
flagpd1("ccc-print-bindings"),
flagpd1("ccc-print-phases"),
flagpd1("cfguard"),
flagpd1("cfguard-no-checks"),
sepd1("chain-include"),
flagpd1("cl-denorms-are-zero"),
flagpd1("cl-fast-relaxed-math"),
flagpd1("cl-finite-math-only"),
flagpd1("cl-fp32-correctly-rounded-divide-sqrt"),
flagpd1("cl-kernel-arg-info"),
flagpd1("cl-mad-enable"),
flagpd1("cl-no-signed-zeros"),
flagpd1("cl-opt-disable"),
flagpd1("cl-single-precision-constant"),
flagpd1("cl-strict-aliasing"),
flagpd1("cl-uniform-work-group-size"),
flagpd1("cl-unsafe-math-optimizations"),
sepd1("code-completion-at"),
flagpd1("code-completion-brief-comments"),
flagpd1("code-completion-macros"),
flagpd1("code-completion-patterns"),
flagpd1("code-completion-with-fixits"),
.{
.name = "combine",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("compiler-options-dump"),
.{
.name = "compress-debug-sections",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "config",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "coverage",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
sepd1("coverage-data-file"),
sepd1("coverage-notes-file"),
flagpd1("cpp"),
flagpd1("cpp-precomp"),
.{
.name = "cuda-compile-host-device",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-device-only",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-host-only",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-noopt-device-debug",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-path-ignore-env",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("dA"),
flagpd1("dD"),
flagpd1("dI"),
flagpd1("dM"),
flagpd1("d"),
flagpd1("dead_strip"),
flagpd1("debug-forward-template-params"),
flagpd1("debug-info-macro"),
sepd1("default-function-attr"),
sepd1("defsym"),
sepd1("dependency-dot"),
sepd1("dependency-file"),
flagpd1("detailed-preprocessing-record"),
sepd1("diagnostic-log-file"),
sepd1("serialize-diagnostic-file"),
flagpd1("disable-O0-optnone"),
flagpd1("disable-free"),
flagpd1("disable-lifetime-markers"),
flagpd1("disable-llvm-optzns"),
flagpd1("disable-llvm-passes"),
flagpd1("disable-llvm-verifier"),
flagpd1("disable-objc-default-synthesize-properties"),
flagpd1("disable-pragma-debug-crash"),
flagpd1("disable-red-zone"),
flagpd1("discard-value-names"),
flagpd1("dump-coverage-mapping"),
flagpd1("dump-deserialized-decls"),
flagpd1("dump-raw-tokens"),
flagpd1("dump-tokens"),
flagpd1("dumpmachine"),
flagpd1("dumpspecs"),
flagpd1("dumpversion"),
sepd1("dwarf-debug-flags"),
sepd1("dwarf-debug-producer"),
flagpd1("dwarf-explicit-import"),
flagpd1("dwarf-ext-refs"),
sepd1("dylib_file"),
flagpd1("dylinker"),
flagpd1("dynamic"),
.{
.name = "dynamiclib",
.syntax = .flag,
.zig_equivalent = .shared,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("emit-ast"),
flagpd1("emit-codegen-only"),
flagpd1("emit-header-module"),
flagpd1("emit-html"),
flagpd1("emit-interface-stubs"),
flagpd1("emit-llvm"),
flagpd1("emit-llvm-bc"),
flagpd1("emit-llvm-only"),
flagpd1("emit-llvm-uselists"),
flagpd1("emit-merged-ifs"),
flagpd1("emit-module"),
flagpd1("emit-module-interface"),
flagpd1("emit-obj"),
flagpd1("emit-pch"),
.{
.name = "emit-static-lib",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang"),
sepd1("error-on-deserialized-decl"),
sepd1("exception-model"),
sepd1("exported_symbols_list"),
.{
.name = "fPIC",
.syntax = .flag,
.zig_equivalent = .pic,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "fPIE",
.syntax = .flag,
.zig_equivalent = .pie,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("faapcs-bitfield-width"),
flagpd1("faccess-control"),
flagpd1("faddrsig"),
flagpd1("faggressive-function-elimination"),
flagpd1("falign-commons"),
flagpd1("falign-functions"),
flagpd1("falign-jumps"),
flagpd1("falign-labels"),
flagpd1("falign-loops"),
flagpd1("faligned-allocation"),
flagpd1("fall-intrinsics"),
flagpd1("fallow-editor-placeholders"),
flagpd1("fallow-half-arguments-and-returns"),
flagpd1("fallow-pch-with-compiler-errors"),
flagpd1("fallow-pcm-with-compiler-errors"),
flagpd1("fallow-unsupported"),
flagpd1("faltivec"),
flagpd1("fkeep-inline-functions"),
flagpd1("fansi-escape-codes"),
flagpd1("fapple-kext"),
flagpd1("fapple-link-rtlib"),
flagpd1("fapple-pragma-pack"),
flagpd1("fapplication-extension"),
flagpd1("fapply-global-visibility-to-externs"),
flagpd1("fapprox-func"),
flagpd1("fasm"),
flagpd1("fasm-blocks"),
flagpd1("fassociative-math"),
flagpd1("fassume-sane-operator-new"),
flagpd1("fast"),
flagpd1("fastcp"),
flagpd1("fastf"),
flagpd1("fasynchronous-unwind-tables"),
flagpd1("fauto-profile"),
flagpd1("fauto-profile-accurate"),
flagpd1("fautolink"),
flagpd1("fautomatic"),
flagpd1("fbackslash"),
flagpd1("fbacktrace"),
flagpd1("fblocks"),
flagpd1("fblocks-runtime-optional"),
flagpd1("fborland-extensions"),
flagpd1("fbounds-check"),
sepd1("fbracket-depth"),
flagpd1("fbranch-count-reg"),
flagpd1("fbuiltin"),
flagpd1("fbuiltin-module-map"),
flagpd1("fcall-saved-x10"),
flagpd1("fcall-saved-x11"),
flagpd1("fcall-saved-x12"),
flagpd1("fcall-saved-x13"),
flagpd1("fcall-saved-x14"),
flagpd1("fcall-saved-x15"),
flagpd1("fcall-saved-x18"),
flagpd1("fcall-saved-x8"),
flagpd1("fcall-saved-x9"),
flagpd1("fcaller-saves"),
flagpd1("fcaret-diagnostics"),
sepd1("fcaret-diagnostics-max-lines"),
flagpd1("fcf-protection"),
flagpd1("fchar8_t"),
flagpd1("fcheck-array-temporaries"),
flagpd1("fcolor-diagnostics"),
flagpd1("fcommon"),
flagpd1("fcompatibility-qualified-id-block-type-checking"),
flagpd1("fcomplete-member-pointers"),
flagpd1("fconcepts-ts"),
flagpd1("fconst-strings"),
flagpd1("fconstant-cfstrings"),
sepd1("fconstant-string-class"),
sepd1("fconstexpr-backtrace-limit"),
sepd1("fconstexpr-depth"),
sepd1("fconstexpr-steps"),
flagpd1("fconvergent-functions"),
flagpd1("fcoroutines-ts"),
flagpd1("fcoverage-mapping"),
flagpd1("fcray-pointer"),
flagpd1("fcreate-profile"),
flagpd1("fcs-profile-generate"),
flagpd1("fcuda-allow-variadic-functions"),
flagpd1("fcuda-approx-transcendentals"),
flagpd1("fcuda-flush-denormals-to-zero"),
sepd1("fcuda-include-gpubinary"),
flagpd1("fcuda-is-device"),
flagpd1("fcuda-short-ptr"),
flagpd1("fcxx-exceptions"),
flagpd1("fcxx-modules"),
flagpd1("fc++-static-destructors"),
flagpd1("fd-lines-as-code"),
flagpd1("fd-lines-as-comments"),
flagpd1("fdata-sections"),
sepd1("fdebug-compilation-dir"),
flagpd1("fdebug-info-for-profiling"),
flagpd1("fdebug-macro"),
flagpd1("fdebug-pass-arguments"),
flagpd1("fdebug-pass-manager"),
flagpd1("fdebug-pass-structure"),
flagpd1("fdebug-ranges-base-address"),
flagpd1("fdebug-types-section"),
flagpd1("fdebugger-cast-result-to-id"),
flagpd1("fdebugger-objc-literal"),
flagpd1("fdebugger-support"),
flagpd1("fdeclare-opencl-builtins"),
flagpd1("fdeclspec"),
flagpd1("fdefault-double-8"),
flagpd1("fdefault-inline"),
flagpd1("fdefault-integer-8"),
flagpd1("fdefault-real-8"),
flagpd1("fdelayed-template-parsing"),
flagpd1("fdelete-null-pointer-checks"),
flagpd1("fdeprecated-macro"),
flagpd1("fdevirtualize"),
flagpd1("fdevirtualize-speculatively"),
flagpd1("fdiagnostics-absolute-paths"),
flagpd1("fdiagnostics-color"),
flagpd1("fdiagnostics-fixit-info"),
sepd1("fdiagnostics-format"),
flagpd1("fdiagnostics-parseable-fixits"),
flagpd1("fdiagnostics-print-source-range-info"),
sepd1("fdiagnostics-show-category"),
flagpd1("fdiagnostics-show-hotness"),
flagpd1("fdiagnostics-show-note-include-stack"),
flagpd1("fdiagnostics-show-option"),
flagpd1("fdiagnostics-show-template-tree"),
flagpd1("fdigraphs"),
flagpd1("fdirect-access-external-data"),
flagpd1("fdisable-module-hash"),
flagpd1("fdiscard-value-names"),
flagpd1("fdollar-ok"),
flagpd1("fdollars-in-identifiers"),
flagpd1("fdouble-square-bracket-attributes"),
flagpd1("fdump-fortran-optimized"),
flagpd1("fdump-fortran-original"),
flagpd1("fdump-parse-tree"),
flagpd1("fdump-record-layouts"),
flagpd1("fdump-record-layouts-simple"),
flagpd1("fdump-vtable-layouts"),
flagpd1("fdwarf2-cfi-asm"),
flagpd1("fdwarf-directory-asm"),
flagpd1("fdwarf-exceptions"),
flagpd1("felide-constructors"),
flagpd1("feliminate-unused-debug-symbols"),
flagpd1("feliminate-unused-debug-types"),
flagpd1("fembed-bitcode"),
flagpd1("fembed-bitcode-marker"),
flagpd1("femit-all-decls"),
flagpd1("femulated-tls"),
flagpd1("fenable-matrix"),
flagpd1("fencode-extended-block-signature"),
sepd1("ferror-limit"),
flagpd1("fescaping-block-tail-calls"),
flagpd1("fexceptions"),
flagpd1("fexperimental-debug-variable-locations"),
flagpd1("fexperimental-isel"),
flagpd1("fexperimental-new-constant-interpreter"),
flagpd1("fexperimental-new-pass-manager"),
flagpd1("fexperimental-relative-c++-abi-vtables"),
flagpd1("fexperimental-strict-floating-point"),
flagpd1("fexternal-blas"),
flagpd1("fexternc-nounwind"),
flagpd1("ff2c"),
flagpd1("ffake-address-space-map"),
flagpd1("ffast-math"),
flagpd1("ffat-lto-objects"),
flagpd1("fcheck-new"),
flagpd1("ffine-grained-bitfield-accesses"),
flagpd1("ffinite-loops"),
flagpd1("ffinite-math-only"),
flagpd1("finline-limit"),
flagpd1("ffixed-form"),
flagpd1("ffixed-point"),
flagpd1("ffixed-r19"),
flagpd1("ffixed-r9"),
flagpd1("ffixed-x1"),
flagpd1("ffixed-x10"),
flagpd1("ffixed-x11"),
flagpd1("ffixed-x12"),
flagpd1("ffixed-x13"),
flagpd1("ffixed-x14"),
flagpd1("ffixed-x15"),
flagpd1("ffixed-x16"),
flagpd1("ffixed-x17"),
flagpd1("ffixed-x18"),
flagpd1("ffixed-x19"),
flagpd1("ffixed-x2"),
flagpd1("ffixed-x20"),
flagpd1("ffixed-x21"),
flagpd1("ffixed-x22"),
flagpd1("ffixed-x23"),
flagpd1("ffixed-x24"),
flagpd1("ffixed-x25"),
flagpd1("ffixed-x26"),
flagpd1("ffixed-x27"),
flagpd1("ffixed-x28"),
flagpd1("ffixed-x29"),
flagpd1("ffixed-x3"),
flagpd1("ffixed-x30"),
flagpd1("ffixed-x31"),
flagpd1("ffixed-x4"),
flagpd1("ffixed-x5"),
flagpd1("ffixed-x6"),
flagpd1("ffixed-x7"),
flagpd1("ffixed-x8"),
flagpd1("ffixed-x9"),
flagpd1("ffloat-store"),
flagpd1("ffor-scope"),
flagpd1("fforbid-guard-variables"),
flagpd1("fforce-dwarf-frame"),
flagpd1("fforce-emit-vtables"),
flagpd1("fforce-enable-int128"),
flagpd1("ffree-form"),
flagpd1("ffreestanding"),
flagpd1("ffriend-injection"),
flagpd1("ffrontend-optimize"),
flagpd1("ffunction-attribute-list"),
flagpd1("ffunction-sections"),
flagpd1("fgcse"),
flagpd1("fgcse-after-reload"),
flagpd1("fgcse-las"),
flagpd1("fgcse-sm"),
flagpd1("fglobal-isel"),
flagpd1("fgnu"),
flagpd1("fgnu89-inline"),
flagpd1("fgnu-inline-asm"),
flagpd1("fgnu-keywords"),
flagpd1("fgnu-runtime"),
flagpd1("fgpu-allow-device-init"),
flagpd1("fgpu-defer-diag"),
flagpd1("fgpu-exclude-wrong-side-overloads"),
flagpd1("fgpu-rdc"),
flagpd1("fhalf-no-semantic-interposition"),
flagpd1("fheinous-gnu-extensions"),
flagpd1("fhip-dump-offload-linker-script"),
flagpd1("fhip-new-launch-api"),
flagpd1("fhonor-infinities"),
flagpd1("fhonor-nans"),
flagpd1("fhosted"),
flagpd1("fignore-exceptions"),
sepd1("filelist"),
sepd1("filetype"),
flagpd1("fimplement-inlines"),
flagpd1("fimplicit-module-maps"),
flagpd1("fimplicit-modules"),
flagpd1("fimplicit-none"),
flagpd1("fimplicit-templates"),
flagpd1("finclude-default-header"),
flagpd1("finit-local-zero"),
flagpd1("finline"),
flagpd1("finline-functions"),
flagpd1("finline-functions-called-once"),
flagpd1("finline-hint-functions"),
flagpd1("finline-small-functions"),
flagpd1("finstrument-function-entry-bare"),
flagpd1("finstrument-functions"),
flagpd1("finstrument-functions-after-inlining"),
flagpd1("finteger-4-integer-8"),
flagpd1("fintegrated-as"),
flagpd1("fintegrated-cc1"),
flagpd1("fintrinsic-modules-path"),
flagpd1("fipa-cp"),
flagpd1("fivopts"),
flagpd1("fix-only-warnings"),
flagpd1("fix-what-you-can"),
flagpd1("fixit"),
flagpd1("fixit-recompile"),
flagpd1("fixit-to-temporary"),
flagpd1("fjump-tables"),
flagpd1("fkeep-static-consts"),
flagpd1("flat_namespace"),
flagpd1("flax-vector-conversions"),
flagpd1("flegacy-pass-manager"),
flagpd1("flimit-debug-info"),
.{
.name = "flto",
.syntax = .flag,
.zig_equivalent = .lto,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("flto-unit"),
flagpd1("flto-visibility-public-std"),
sepd1("fmacro-backtrace-limit"),
flagpd1("fmath-errno"),
flagpd1("fmax-identifier-length"),
flagpd1("fmemory-profile"),
flagpd1("fmerge-all-constants"),
flagpd1("fmerge-constants"),
flagpd1("fmerge-functions"),
sepd1("fmodule-feature"),
flagpd1("fmodule-file-deps"),
sepd1("fmodule-implementation-of"),
flagpd1("fmodule-map-file-home-is-cwd"),
flagpd1("fmodule-maps"),
sepd1("fmodule-name"),
flagpd1("fmodule-private"),
flagpd1("fmodules"),
flagpd1("fmodules-codegen"),
flagpd1("fmodules-debuginfo"),
flagpd1("fmodules-decluse"),
flagpd1("fmodules-disable-diagnostic-validation"),
flagpd1("fmodules-hash-content"),
flagpd1("fmodules-local-submodule-visibility"),
flagpd1("fmodules-search-all"),
flagpd1("fmodules-strict-context-hash"),
flagpd1("fmodules-strict-decluse"),
flagpd1("fmodules-ts"),
sepd1("fmodules-user-build-path"),
flagpd1("fmodules-validate-input-files-content"),
flagpd1("fmodules-validate-once-per-build-session"),
flagpd1("fmodules-validate-system-headers"),
flagpd1("fmodulo-sched"),
flagpd1("fmodulo-sched-allow-regmoves"),
flagpd1("fms-compatibility"),
flagpd1("fms-extensions"),
flagpd1("fms-volatile"),
flagpd1("fmudflap"),
flagpd1("fmudflapth"),
flagpd1("fnative-half-arguments-and-returns"),
flagpd1("fnative-half-type"),
flagpd1("fnested-functions"),
flagpd1("fnext-runtime"),
.{
.name = "fno-PIC",
.syntax = .flag,
.zig_equivalent = .no_pic,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "fno-PIE",
.syntax = .flag,
.zig_equivalent = .no_pie,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("fno-aapcs-bitfield-width"),
flagpd1("fno-access-control"),
flagpd1("fno-addrsig"),
flagpd1("fno-aggressive-function-elimination"),
flagpd1("fno-align-commons"),
flagpd1("fno-align-functions"),
flagpd1("fno-align-jumps"),
flagpd1("fno-align-labels"),
flagpd1("fno-align-loops"),
flagpd1("fno-aligned-allocation"),
flagpd1("fno-all-intrinsics"),
flagpd1("fno-allow-editor-placeholders"),
flagpd1("fno-altivec"),
flagpd1("fno-keep-inline-functions"),
flagpd1("fno-apple-pragma-pack"),
flagpd1("fno-application-extension"),
flagpd1("fno-asm"),
flagpd1("fno-asm-blocks"),
flagpd1("fno-associative-math"),
flagpd1("fno-assume-sane-operator-new"),
flagpd1("fno-asynchronous-unwind-tables"),
flagpd1("fno-auto-profile"),
flagpd1("fno-auto-profile-accurate"),
flagpd1("fno-autolink"),
flagpd1("fno-automatic"),
flagpd1("fno-backslash"),
flagpd1("fno-backtrace"),
flagpd1("fno-bitfield-type-align"),
flagpd1("fno-blocks"),
flagpd1("fno-borland-extensions"),
flagpd1("fno-bounds-check"),
flagpd1("fno-branch-count-reg"),
flagpd1("fno-builtin"),
flagpd1("fno-caller-saves"),
flagpd1("fno-caret-diagnostics"),
flagpd1("fno-char8_t"),
flagpd1("fno-check-array-temporaries"),
flagpd1("fno-color-diagnostics"),
flagpd1("fno-common"),
flagpd1("fno-complete-member-pointers"),
flagpd1("fno-concept-satisfaction-caching"),
flagpd1("fno-const-strings"),
flagpd1("fno-constant-cfstrings"),
flagpd1("fno-coroutines-ts"),
flagpd1("fno-coverage-mapping"),
flagpd1("fno-crash-diagnostics"),
flagpd1("fno-cray-pointer"),
flagpd1("fno-cuda-approx-transcendentals"),
flagpd1("fno-cuda-flush-denormals-to-zero"),
flagpd1("fno-cuda-host-device-constexpr"),
flagpd1("fno-cuda-short-ptr"),
flagpd1("fno-cxx-exceptions"),
flagpd1("fno-cxx-modules"),
flagpd1("fno-c++-static-destructors"),
flagpd1("fno-d-lines-as-code"),
flagpd1("fno-d-lines-as-comments"),
flagpd1("fno-data-sections"),
flagpd1("fno-debug-info-for-profiling"),
flagpd1("fno-debug-macro"),
flagpd1("fno-debug-pass-manager"),
flagpd1("fno-debug-ranges-base-address"),
flagpd1("fno-debug-types-section"),
flagpd1("fno-declspec"),
flagpd1("fno-default-double-8"),
flagpd1("fno-default-inline"),
flagpd1("fno-default-integer-8"),
flagpd1("fno-default-real-8"),
flagpd1("fno-delayed-template-parsing"),
flagpd1("fno-delete-null-pointer-checks"),
flagpd1("fno-deprecated-macro"),
flagpd1("fno-devirtualize"),
flagpd1("fno-devirtualize-speculatively"),
flagpd1("fno-diagnostics-color"),
flagpd1("fno-diagnostics-fixit-info"),
flagpd1("fno-diagnostics-show-hotness"),
flagpd1("fno-diagnostics-show-note-include-stack"),
flagpd1("fno-diagnostics-show-option"),
flagpd1("fno-diagnostics-use-presumed-location"),
flagpd1("fno-digraphs"),
flagpd1("fno-direct-access-external-data"),
flagpd1("fno-discard-value-names"),
flagpd1("fno-dllexport-inlines"),
flagpd1("fno-dollar-ok"),
flagpd1("fno-dollars-in-identifiers"),
flagpd1("fno-double-square-bracket-attributes"),
flagpd1("fno-dump-fortran-optimized"),
flagpd1("fno-dump-fortran-original"),
flagpd1("fno-dump-parse-tree"),
flagpd1("fno-dwarf2-cfi-asm"),
flagpd1("fno-dwarf-directory-asm"),
flagpd1("fno-elide-constructors"),
flagpd1("fno-elide-type"),
flagpd1("fno-eliminate-unused-debug-symbols"),
flagpd1("fno-eliminate-unused-debug-types"),
flagpd1("fno-emulated-tls"),
flagpd1("fno-escaping-block-tail-calls"),
flagpd1("fno-exceptions"),
flagpd1("fno-experimental-isel"),
flagpd1("fno-experimental-new-pass-manager"),
flagpd1("fno-experimental-relative-c++-abi-vtables"),
flagpd1("fno-external-blas"),
flagpd1("fno-f2c"),
flagpd1("fno-fast-math"),
flagpd1("fno-fat-lto-objects"),
flagpd1("fno-check-new"),
flagpd1("fno-fine-grained-bitfield-accesses"),
flagpd1("fno-finite-loops"),
flagpd1("fno-finite-math-only"),
flagpd1("fno-inline-limit"),
flagpd1("fno-fixed-form"),
flagpd1("fno-fixed-point"),
flagpd1("fno-float-store"),
flagpd1("fno-for-scope"),
flagpd1("fno-force-dwarf-frame"),
flagpd1("fno-force-emit-vtables"),
flagpd1("fno-force-enable-int128"),
flagpd1("fno-free-form"),
flagpd1("fno-friend-injection"),
flagpd1("fno-frontend-optimize"),
flagpd1("fno-function-attribute-list"),
flagpd1("fno-function-sections"),
flagpd1("fno-gcse"),
flagpd1("fno-gcse-after-reload"),
flagpd1("fno-gcse-las"),
flagpd1("fno-gcse-sm"),
flagpd1("fno-global-isel"),
flagpd1("fno-gnu"),
flagpd1("fno-gnu89-inline"),
flagpd1("fno-gnu-inline-asm"),
flagpd1("fno-gnu-keywords"),
flagpd1("fno-gpu-allow-device-init"),
flagpd1("fno-gpu-defer-diag"),
flagpd1("fno-gpu-exclude-wrong-side-overloads"),
flagpd1("fno-gpu-rdc"),
flagpd1("fno-hip-new-launch-api"),
flagpd1("fno-honor-infinities"),
flagpd1("fno-honor-nans"),
flagpd1("fno-implement-inlines"),
flagpd1("fno-implicit-module-maps"),
flagpd1("fno-implicit-modules"),
flagpd1("fno-implicit-none"),
flagpd1("fno-implicit-templates"),
flagpd1("fno-init-local-zero"),
flagpd1("fno-inline"),
flagpd1("fno-inline-functions"),
flagpd1("fno-inline-functions-called-once"),
flagpd1("fno-inline-small-functions"),
flagpd1("fno-integer-4-integer-8"),
flagpd1("fno-integrated-as"),
flagpd1("fno-integrated-cc1"),
flagpd1("fno-intrinsic-modules-path"),
flagpd1("fno-ipa-cp"),
flagpd1("fno-ivopts"),
flagpd1("fno-jump-tables"),
flagpd1("fno-keep-static-consts"),
flagpd1("fno-lax-vector-conversions"),
flagpd1("fno-legacy-pass-manager"),
flagpd1("fno-limit-debug-info"),
.{
.name = "fno-lto",
.syntax = .flag,
.zig_equivalent = .no_lto,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("fno-lto-unit"),
flagpd1("fno-math-builtin"),
flagpd1("fno-math-errno"),
flagpd1("fno-max-identifier-length"),
flagpd1("fno-max-type-align"),
flagpd1("fno-memory-profile"),
flagpd1("fno-merge-all-constants"),
flagpd1("fno-merge-constants"),
flagpd1("fno-module-file-deps"),
flagpd1("fno-module-maps"),
flagpd1("fno-module-private"),
flagpd1("fno-modules"),
flagpd1("fno-modules-decluse"),
flagpd1("fno-modules-error-recovery"),
flagpd1("fno-modules-global-index"),
flagpd1("fno-modules-search-all"),
flagpd1("fno-strict-modules-decluse"),
flagpd1("fno_modules-validate-input-files-content"),
flagpd1("fno-modules-validate-system-headers"),
flagpd1("fno-modulo-sched"),
flagpd1("fno-modulo-sched-allow-regmoves"),
flagpd1("fno-ms-compatibility"),
flagpd1("fno-ms-extensions"),
flagpd1("fno-non-call-exceptions"),
flagpd1("fno-objc-arc"),
flagpd1("fno-objc-arc-exceptions"),
flagpd1("fno-objc-convert-messages-to-runtime-calls"),
flagpd1("fno-objc-exceptions"),
flagpd1("fno-objc-infer-related-result-type"),
flagpd1("fno-objc-legacy-dispatch"),
flagpd1("fno-objc-nonfragile-abi"),
flagpd1("fno-objc-weak"),
flagpd1("fno-omit-frame-pointer"),
flagpd1("fno-openmp"),
flagpd1("fno-openmp-cuda-force-full-runtime"),
flagpd1("fno-openmp-cuda-mode"),
flagpd1("fno-openmp-cuda-parallel-target-regions"),
flagpd1("fno-openmp-optimistic-collapse"),
flagpd1("fno-openmp-simd"),
flagpd1("fno-operator-names"),
flagpd1("fno-optimize-sibling-calls"),
flagpd1("fno-pack-derived"),
flagpd1("fno-pack-struct"),
flagpd1("fno-padding-on-unsigned-fixed-point"),
flagpd1("fno-pascal-strings"),
flagpd1("fno-pch-codegen"),
flagpd1("fno-pch-debuginfo"),
flagpd1("fno-pch-instantiate-templates"),
flagpd1("fno-pch-timestamp"),
flagpd1("fno_pch-validate-input-files-content"),
flagpd1("fno-peel-loops"),
flagpd1("fno-permissive"),
flagpd1("fno-pic"),
flagpd1("fno-pie"),
flagpd1("fno-plt"),
flagpd1("fno-prebuilt-implicit-modules"),
flagpd1("fno-prefetch-loop-arrays"),
flagpd1("fno-preserve-as-comments"),
flagpd1("fno-printf"),
flagpd1("fno-profile"),
flagpd1("fno-profile-arcs"),
flagpd1("fno-profile-correction"),
flagpd1("fno-profile-generate"),
flagpd1("fno-profile-generate-sampling"),
flagpd1("fno-profile-instr-generate"),
flagpd1("fno-profile-instr-use"),
flagpd1("fno-profile-reusedist"),
flagpd1("fno-profile-sample-accurate"),
flagpd1("fno-profile-sample-use"),
flagpd1("fno-profile-use"),
flagpd1("fno-profile-values"),
flagpd1("fno-protect-parens"),
flagpd1("fno-pseudo-probe-for-profiling"),
flagpd1("fno-range-check"),
flagpd1("fno-real-4-real-10"),
flagpd1("fno-real-4-real-16"),
flagpd1("fno-real-4-real-8"),
flagpd1("fno-real-8-real-10"),
flagpd1("fno-real-8-real-16"),
flagpd1("fno-real-8-real-4"),
flagpd1("fno-realloc-lhs"),
flagpd1("fno-reciprocal-math"),
flagpd1("fno-record-command-line"),
flagpd1("fno-recovery-ast"),
flagpd1("fno-recovery-ast-type"),
flagpd1("fno-recursive"),
flagpd1("fno-register-global-dtors-with-atexit"),
flagpd1("fno-regs-graph"),
flagpd1("fno-relaxed-template-template-args"),
flagpd1("fno-rename-registers"),
flagpd1("fno-reorder-blocks"),
flagpd1("fno-repack-arrays"),
flagpd1("fno-reroll-loops"),
flagpd1("fno-rewrite-imports"),
flagpd1("fno-rewrite-includes"),
flagpd1("fno-ripa"),
flagpd1("fno-ropi"),
flagpd1("fno-rounding-math"),
flagpd1("fno-rtlib-add-rpath"),
flagpd1("fno-rtti"),
flagpd1("fno-rtti-data"),
flagpd1("fno-rwpi"),
flagpd1("fno-sanitize-address-poison-custom-array-cookie"),
flagpd1("fno-sanitize-address-use-after-scope"),
flagpd1("fno-sanitize-address-use-odr-indicator"),
flagpd1("fno-sanitize-blacklist"),
flagpd1("fno-sanitize-cfi-canonical-jump-tables"),
flagpd1("fno-sanitize-cfi-cross-dso"),
flagpd1("fno-sanitize-link-c++-runtime"),
flagpd1("fno-sanitize-link-runtime"),
flagpd1("fno-sanitize-memory-track-origins"),
flagpd1("fno-sanitize-memory-use-after-dtor"),
flagpd1("fno-sanitize-minimal-runtime"),
flagpd1("fno-sanitize-recover"),
flagpd1("fno-sanitize-stats"),
flagpd1("fno-sanitize-thread-atomics"),
flagpd1("fno-sanitize-thread-func-entry-exit"),
flagpd1("fno-sanitize-thread-memory-access"),
flagpd1("fno-sanitize-trap"),
flagpd1("fno-sanitize-undefined-trap-on-error"),
flagpd1("fno-save-optimization-record"),
flagpd1("fno-schedule-insns"),
flagpd1("fno-schedule-insns2"),
flagpd1("fno-second-underscore"),
flagpd1("fno-see"),
flagpd1("fno-semantic-interposition"),
flagpd1("fno-short-enums"),
flagpd1("fno-short-wchar"),
flagpd1("fno-show-column"),
flagpd1("fno-show-source-location"),
flagpd1("fno-sign-zero"),
flagpd1("fno-signaling-math"),
flagpd1("fno-signaling-nans"),
flagpd1("fno-signed-char"),
flagpd1("fno-signed-wchar"),
flagpd1("fno-signed-zeros"),
flagpd1("fno-single-precision-constant"),
flagpd1("fno-sized-deallocation"),
flagpd1("fno-slp-vectorize"),
flagpd1("fno-spec-constr-count"),
flagpd1("fno-spell-checking"),
flagpd1("fno-split-dwarf-inlining"),
flagpd1("fno-split-lto-unit"),
flagpd1("fno-split-machine-functions"),
flagpd1("fno-stack-arrays"),
flagpd1("fno-stack-check"),
flagpd1("fno-stack-clash-protection"),
flagpd1("fno-stack-protector"),
flagpd1("fno-stack-size-section"),
flagpd1("fno-standalone-debug"),
flagpd1("fno-strength-reduce"),
flagpd1("fno-strict-aliasing"),
flagpd1("fno-strict-enums"),
flagpd1("fno-strict-float-cast-overflow"),
flagpd1("fno-strict-overflow"),
flagpd1("fno-strict-return"),
flagpd1("fno-strict-vtable-pointers"),
flagpd1("fno-struct-path-tbaa"),
flagpd1("fno-sycl"),
flagpd1("fno-temp-file"),
flagpd1("fno-test-coverage"),
flagpd1("fno-threadsafe-statics"),
flagpd1("fno-tls-model"),
flagpd1("fno-tracer"),
flagpd1("fno-trapping-math"),
flagpd1("fno-tree-dce"),
flagpd1("fno-tree-salias"),
flagpd1("fno-tree-ter"),
flagpd1("fno-tree-vectorizer-verbose"),
flagpd1("fno-tree-vrp"),
flagpd1("fno-trigraphs"),
flagpd1("fno-underscoring"),
flagpd1("fno-unique-basic-block-section-names"),
flagpd1("fno-unique-internal-linkage-names"),
flagpd1("fno-unique-section-names"),
flagpd1("fno-unit-at-a-time"),
flagpd1("fno-unroll-all-loops"),
flagpd1("fno-unroll-loops"),
flagpd1("fno-unsafe-loop-optimizations"),
flagpd1("fno-unsafe-math-optimizations"),
flagpd1("fno-unsigned-char"),
flagpd1("fno-unswitch-loops"),
flagpd1("fno-unwind-tables"),
flagpd1("fno-use-cxa-atexit"),
flagpd1("fno-use-init-array"),
flagpd1("fno-use-line-directives"),
flagpd1("fno-use-linker-plugin"),
flagpd1("fno-validate-pch"),
flagpd1("fno-var-tracking"),
flagpd1("fno-variable-expansion-in-unroller"),
flagpd1("fno-vect-cost-model"),
flagpd1("fno-vectorize"),
flagpd1("fno-verbose-asm"),
flagpd1("fno-virtual-function-elimination"),
flagpd1("fno-visibility-from-dllstorageclass"),
flagpd1("fno-visibility-inlines-hidden-static-local-var"),
flagpd1("fno-wchar"),
flagpd1("fno-web"),
flagpd1("fno-whole-file"),
flagpd1("fno-whole-program"),
flagpd1("fno-whole-program-vtables"),
flagpd1("fno-working-directory"),
flagpd1("fno-wrapv"),
flagpd1("fno-xl-pragma-pack"),
flagpd1("fno-xray-always-emit-customevents"),
flagpd1("fno-xray-always-emit-typedevents"),
flagpd1("fno-xray-function-index"),
flagpd1("fno-xray-ignore-loops"),
flagpd1("fno-xray-instrument"),
flagpd1("fno-zero-initialized-in-bss"),
flagpd1("fno-zvector"),
flagpd1("fnon-call-exceptions"),
flagpd1("fnoopenmp-relocatable-target"),
flagpd1("fnoopenmp-use-tls"),
flagpd1("fnoxray-link-deps"),
flagpd1("fobjc-arc"),
flagpd1("fobjc-arc-exceptions"),
flagpd1("fobjc-atdefs"),
flagpd1("fobjc-call-cxx-cdtors"),
flagpd1("fobjc-convert-messages-to-runtime-calls"),
flagpd1("fobjc-exceptions"),
flagpd1("fobjc-gc"),
flagpd1("fobjc-gc-only"),
flagpd1("fobjc-infer-related-result-type"),
flagpd1("fobjc-legacy-dispatch"),
flagpd1("fobjc-link-runtime"),
flagpd1("fobjc-new-property"),
flagpd1("fobjc-nonfragile-abi"),
flagpd1("fobjc-runtime-has-weak"),
flagpd1("fobjc-sender-dependent-dispatch"),
flagpd1("fobjc-subscripting-legacy-runtime"),
flagpd1("fobjc-weak"),
flagpd1("fomit-frame-pointer"),
flagpd1("fopenmp"),
flagpd1("fopenmp-cuda-force-full-runtime"),
flagpd1("fopenmp-cuda-mode"),
flagpd1("fopenmp-cuda-parallel-target-regions"),
flagpd1("fopenmp-enable-irbuilder"),
sepd1("fopenmp-host-ir-file-path"),
flagpd1("fopenmp-is-device"),
flagpd1("fopenmp-optimistic-collapse"),
flagpd1("fopenmp-relocatable-target"),
flagpd1("fopenmp-simd"),
flagpd1("fopenmp-use-tls"),
sepd1("foperator-arrow-depth"),
flagpd1("foptimize-sibling-calls"),
flagpd1("force_cpusubtype_ALL"),
flagpd1("force_flat_namespace"),
sepd1("force_load"),
flagpd1("forder-file-instrumentation"),
flagpd1("fpack-derived"),
flagpd1("fpack-struct"),
flagpd1("fpadding-on-unsigned-fixed-point"),
flagpd1("fparse-all-comments"),
flagpd1("fpascal-strings"),
flagpd1("fpass-by-value-is-noalias"),
flagpd1("fpcc-struct-return"),
flagpd1("fpch-codegen"),
flagpd1("fpch-debuginfo"),
flagpd1("fpch-instantiate-templates"),
flagpd1("fpch-preprocess"),
flagpd1("fpch-validate-input-files-content"),
flagpd1("fpeel-loops"),
flagpd1("fpermissive"),
flagpd1("fpic"),
flagpd1("fpie"),
flagpd1("fplt"),
flagpd1("fprebuilt-implicit-modules"),
flagpd1("fprefetch-loop-arrays"),
flagpd1("fpreserve-as-comments"),
flagpd1("fpreserve-vec3-type"),
flagpd1("fprintf"),
flagpd1("fprofile"),
flagpd1("fprofile-arcs"),
flagpd1("fprofile-correction"),
flagpd1("fprofile-generate"),
flagpd1("fprofile-generate-sampling"),
flagpd1("fprofile-instr-generate"),
flagpd1("fprofile-instr-use"),
sepd1("fprofile-remapping-file"),
flagpd1("fprofile-reusedist"),
flagpd1("fprofile-sample-accurate"),
flagpd1("fprofile-sample-use"),
flagpd1("fprofile-use"),
flagpd1("fprofile-values"),
flagpd1("fprotect-parens"),
flagpd1("fpseudo-probe-for-profiling"),
.{
.name = "framework",
.syntax = .separate,
.zig_equivalent = .framework,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("frange-check"),
flagpd1("freal-4-real-10"),
flagpd1("freal-4-real-16"),
flagpd1("freal-4-real-8"),
flagpd1("freal-8-real-10"),
flagpd1("freal-8-real-16"),
flagpd1("freal-8-real-4"),
flagpd1("frealloc-lhs"),
flagpd1("freciprocal-math"),
flagpd1("frecord-command-line"),
flagpd1("frecovery-ast"),
flagpd1("frecovery-ast-type"),
flagpd1("frecursive"),
flagpd1("freg-struct-return"),
flagpd1("fregister-global-dtors-with-atexit"),
flagpd1("fregs-graph"),
flagpd1("frelaxed-template-template-args"),
flagpd1("frename-registers"),
flagpd1("freorder-blocks"),
flagpd1("frepack-arrays"),
flagpd1("freroll-loops"),
flagpd1("fretain-comments-from-system-headers"),
flagpd1("frewrite-imports"),
flagpd1("frewrite-includes"),
sepd1("frewrite-map-file"),
flagpd1("fripa"),
flagpd1("fropi"),
flagpd1("frounding-math"),
flagpd1("frtlib-add-rpath"),
flagpd1("frtti"),
flagpd1("frtti-data"),
flagpd1("frwpi"),
flagpd1("fsanitize-address-globals-dead-stripping"),
flagpd1("fsanitize-address-poison-custom-array-cookie"),
flagpd1("fsanitize-address-use-after-scope"),
flagpd1("fsanitize-address-use-odr-indicator"),
flagpd1("fsanitize-cfi-canonical-jump-tables"),
flagpd1("fsanitize-cfi-cross-dso"),
flagpd1("fsanitize-cfi-icall-generalize-pointers"),
flagpd1("fsanitize-coverage-8bit-counters"),
flagpd1("fsanitize-coverage-indirect-calls"),
flagpd1("fsanitize-coverage-inline-8bit-counters"),
flagpd1("fsanitize-coverage-inline-bool-flag"),
flagpd1("fsanitize-coverage-no-prune"),
flagpd1("fsanitize-coverage-pc-table"),
flagpd1("fsanitize-coverage-stack-depth"),
flagpd1("fsanitize-coverage-trace-bb"),
flagpd1("fsanitize-coverage-trace-cmp"),
flagpd1("fsanitize-coverage-trace-div"),
flagpd1("fsanitize-coverage-trace-gep"),
flagpd1("fsanitize-coverage-trace-pc"),
flagpd1("fsanitize-coverage-trace-pc-guard"),
flagpd1("fsanitize-link-c++-runtime"),
flagpd1("fsanitize-link-runtime"),
flagpd1("fsanitize-memory-track-origins"),
flagpd1("fsanitize-memory-use-after-dtor"),
flagpd1("fsanitize-minimal-runtime"),
flagpd1("fsanitize-recover"),
flagpd1("fsanitize-stats"),
flagpd1("fsanitize-thread-atomics"),
flagpd1("fsanitize-thread-func-entry-exit"),
flagpd1("fsanitize-thread-memory-access"),
flagpd1("fsanitize-trap"),
flagpd1("fsanitize-undefined-trap-on-error"),
flagpd1("fsave-optimization-record"),
flagpd1("fschedule-insns"),
flagpd1("fschedule-insns2"),
flagpd1("fsecond-underscore"),
flagpd1("fsee"),
flagpd1("fseh-exceptions"),
flagpd1("fsemantic-interposition"),
flagpd1("fshort-enums"),
flagpd1("fshort-wchar"),
flagpd1("fshow-column"),
flagpd1("fshow-source-location"),
flagpd1("fsign-zero"),
flagpd1("fsignaling-math"),
flagpd1("fsignaling-nans"),
flagpd1("fsigned-bitfields"),
flagpd1("fsigned-char"),
flagpd1("fsigned-wchar"),
flagpd1("fsigned-zeros"),
flagpd1("fsingle-precision-constant"),
flagpd1("fsized-deallocation"),
flagpd1("fsjlj-exceptions"),
flagpd1("fslp-vectorize"),
flagpd1("fspec-constr-count"),
flagpd1("fspell-checking"),
sepd1("fspell-checking-limit"),
flagpd1("fsplit-dwarf-inlining"),
flagpd1("fsplit-lto-unit"),
flagpd1("fsplit-machine-functions"),
flagpd1("fsplit-stack"),
flagpd1("fstack-arrays"),
flagpd1("fstack-check"),
flagpd1("fstack-clash-protection"),
flagpd1("fstack-protector"),
flagpd1("fstack-protector-all"),
flagpd1("fstack-protector-strong"),
flagpd1("fstack-size-section"),
flagpd1("fstandalone-debug"),
flagpd1("fstrength-reduce"),
flagpd1("fstrict-aliasing"),
flagpd1("fstrict-enums"),
flagpd1("fstrict-float-cast-overflow"),
flagpd1("fstrict-overflow"),
flagpd1("fstrict-return"),
flagpd1("fstrict-vtable-pointers"),
flagpd1("fstruct-path-tbaa"),
flagpd1("fsycl"),
flagpd1("fsycl-is-device"),
flagpd1("fsyntax-only"),
flagpd1("fsystem-module"),
sepd1("ftabstop"),
sepd1("ftemplate-backtrace-limit"),
sepd1("ftemplate-depth"),
flagpd1("ftest-coverage"),
flagpd1("fthreadsafe-statics"),
flagpd1("ftime-report"),
flagpd1("ftime-trace"),
flagpd1("ftls-model"),
flagpd1("ftracer"),
flagpd1("ftrapping-math"),
flagpd1("ftrapv"),
sepd1("ftrapv-handler"),
flagpd1("ftree-dce"),
flagpd1("ftree-salias"),
flagpd1("ftree-ter"),
flagpd1("ftree-vectorizer-verbose"),
flagpd1("ftree-vrp"),
flagpd1("ftrigraphs"),
sepd1("ftype-visibility"),
sepd1("function-alignment"),
flagpd1("funderscoring"),
flagpd1("funique-basic-block-section-names"),
flagpd1("funique-internal-linkage-names"),
flagpd1("funique-section-names"),
flagpd1("funit-at-a-time"),
flagpd1("funknown-anytype"),
flagpd1("funroll-all-loops"),
flagpd1("funroll-loops"),
flagpd1("funsafe-loop-optimizations"),
flagpd1("funsafe-math-optimizations"),
flagpd1("funsigned-bitfields"),
flagpd1("funsigned-char"),
flagpd1("funswitch-loops"),
flagpd1("funwind-tables"),
flagpd1("fuse-ctor-homing"),
flagpd1("fuse-cxa-atexit"),
flagpd1("fuse-init-array"),
flagpd1("fuse-line-directives"),
flagpd1("fuse-linker-plugin"),
flagpd1("fuse-register-sized-bitfield-access"),
flagpd1("fvalidate-ast-input-files-content"),
flagpd1("fvariable-expansion-in-unroller"),
flagpd1("fvect-cost-model"),
flagpd1("fvectorize"),
flagpd1("fverbose-asm"),
flagpd1("fvirtual-function-elimination"),
sepd1("fvisibility"),
flagpd1("fvisibility-from-dllstorageclass"),
flagpd1("fvisibility-global-new-delete-hidden"),
flagpd1("fvisibility-inlines-hidden"),
flagpd1("fvisibility-inlines-hidden-static-local-var"),
flagpd1("fvisibility-ms-compat"),
flagpd1("fwasm-exceptions"),
flagpd1("fweb"),
flagpd1("fwhole-file"),
flagpd1("fwhole-program"),
flagpd1("fwhole-program-vtables"),
flagpd1("fwrapv"),
flagpd1("fwritable-strings"),
flagpd1("fxl-pragma-pack"),
flagpd1("fxray-always-emit-customevents"),
flagpd1("fxray-always-emit-typedevents"),
flagpd1("fxray-function-index"),
flagpd1("fxray-ignore-loops"),
flagpd1("fxray-instrument"),
flagpd1("fxray-link-deps"),
flagpd1("fzero-initialized-in-bss"),
flagpd1("fzvector"),
flagpd1("g0"),
.{
.name = "g1",
.syntax = .flag,
.zig_equivalent = .debug,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("g2"),
flagpd1("g3"),
.{
.name = "g",
.syntax = .flag,
.zig_equivalent = .debug,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("gcc-toolchain"),
flagpd1("gcodeview"),
flagpd1("gcodeview-ghash"),
flagpd1("gcolumn-info"),
flagpd1("gdwarf"),
flagpd1("gdwarf32"),
flagpd1("gdwarf64"),
flagpd1("gdwarf-2"),
flagpd1("gdwarf-3"),
flagpd1("gdwarf-4"),
flagpd1("gdwarf-5"),
flagpd1("gdwarf-aranges"),
flagpd1("gembed-source"),
sepd1("gen-cdb-fragment-path"),
flagpd1("gen-reproducer"),
flagpd1("gfull"),
flagpd1("ggdb"),
flagpd1("ggdb0"),
flagpd1("ggdb1"),
flagpd1("ggdb2"),
flagpd1("ggdb3"),
flagpd1("ggnu-pubnames"),
flagpd1("ginline-line-tables"),
flagpd1("gline-directives-only"),
.{
.name = "gline-tables-only",
.syntax = .flag,
.zig_equivalent = .debug,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("glldb"),
flagpd1("gmlt"),
flagpd1("gmodules"),
flagpd1("gno-codeview-ghash"),
flagpd1("gno-column-info"),
flagpd1("gno-embed-source"),
flagpd1("gno-gnu-pubnames"),
flagpd1("gno-inline-line-tables"),
flagpd1("gno-pubnames"),
flagpd1("gno-record-command-line"),
flagpd1("gno-split-dwarf"),
flagpd1("gno-strict-dwarf"),
.{
.name = "gpu-use-aux-triple-only",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("gpubnames"),
flagpd1("grecord-command-line"),
flagpd1("gsce"),
flagpd1("gsplit-dwarf"),
flagpd1("gstrict-dwarf"),
flagpd1("gtoggle"),
flagpd1("gused"),
flagpd1("gz"),
sepd1("header-include-file"),
.{
.name = "help",
.syntax = .flag,
.zig_equivalent = .driver_punt,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "hip-link",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("ibuiltininc"),
sepd1("image_base"),
sepd1("imultilib"),
sepd1("include-pch"),
flagpd1("index-header-map"),
sepd1("init"),
flagpd1("init-only"),
sepd1("install_name"),
flagpd1("keep_private_externs"),
sepd1("lazy_framework"),
sepd1("lazy_library"),
sepd1("load"),
flagpd1("m16"),
flagpd1("m32"),
flagpd1("m3dnow"),
flagpd1("m3dnowa"),
flagpd1("m64"),
flagpd1("m80387"),
flagpd1("mseses"),
flagpd1("mabi=ieeelongdouble"),
flagpd1("mabi=vec-default"),
flagpd1("mabi=vec-extabi"),
flagpd1("mabicalls"),
flagpd1("madx"),
flagpd1("maes"),
sepd1("main-file-name"),
flagpd1("maix-struct-return"),
flagpd1("malign-double"),
flagpd1("maltivec"),
flagpd1("mamx-bf16"),
flagpd1("mamx-tile"),
flagpd1("marm"),
flagpd1("massembler-fatal-warnings"),
flagpd1("massembler-no-warn"),
flagpd1("matomics"),
flagpd1("mavx"),
flagpd1("mavx2"),
flagpd1("mavx512bf16"),
flagpd1("mavx512bitalg"),
flagpd1("mavx512bw"),
flagpd1("mavx512cd"),
flagpd1("mavx512dq"),
flagpd1("mavx512er"),
flagpd1("mavx512f"),
flagpd1("mavx512ifma"),
flagpd1("mavx512pf"),
flagpd1("mavx512vbmi"),
flagpd1("mavx512vbmi2"),
flagpd1("mavx512vl"),
flagpd1("mavx512vnni"),
flagpd1("mavx512vp2intersect"),
flagpd1("mavx512vpopcntdq"),
flagpd1("mavxvnni"),
flagpd1("mbackchain"),
flagpd1("mbig-endian"),
flagpd1("mbmi"),
flagpd1("mbmi2"),
flagpd1("mbranch-likely"),
flagpd1("mbranch-target-enforce"),
flagpd1("mbranches-within-32B-boundaries"),
flagpd1("mbulk-memory"),
flagpd1("mcheck-zero-division"),
flagpd1("mcldemote"),
flagpd1("mclflushopt"),
flagpd1("mclwb"),
flagpd1("mclzero"),
flagpd1("mcmodel=medany"),
flagpd1("mcmodel=medlow"),
flagpd1("mcmpb"),
flagpd1("mcmse"),
flagpd1("mcode-object-v3"),
flagpd1("mconstant-cfstrings"),
flagpd1("mconstructor-aliases"),
flagpd1("mcpu=?"),
flagpd1("mcrbits"),
flagpd1("mcrc"),
flagpd1("mcumode"),
flagpd1("mcx16"),
sepd1("mdebug-pass"),
flagpd1("mdirect-move"),
flagpd1("mdisable-tail-calls"),
flagpd1("mdouble-float"),
flagpd1("mdsp"),
flagpd1("mdspr2"),
sepd1("meabi"),
flagpd1("mefpu2"),
flagpd1("membedded-data"),
flagpd1("menable-experimental-extensions"),
flagpd1("menable-no-infs"),
flagpd1("menable-no-nans"),
flagpd1("menable-unsafe-fp-math"),
flagpd1("menqcmd"),
flagpd1("mexception-handling"),
flagpd1("mexecute-only"),
flagpd1("mextern-sdata"),
flagpd1("mf16c"),
flagpd1("mfancy-math-387"),
flagpd1("mfentry"),
flagpd1("mfix-and-continue"),
flagpd1("mfix-cortex-a53-835769"),
flagpd1("mfloat128"),
sepd1("mfloat-abi"),
flagpd1("mfma"),
flagpd1("mfma4"),
flagpd1("mfp32"),
flagpd1("mfp64"),
sepd1("mfpmath"),
flagpd1("mfprnd"),
flagpd1("mfpxx"),
flagpd1("mfsgsbase"),
flagpd1("mfxsr"),
flagpd1("mgeneral-regs-only"),
flagpd1("mgfni"),
flagpd1("mginv"),
flagpd1("mglibc"),
flagpd1("mglobal-merge"),
flagpd1("mgpopt"),
flagpd1("mhard-float"),
flagpd1("mhvx"),
flagpd1("mhreset"),
flagpd1("mhtm"),
flagpd1("miamcu"),
flagpd1("mieee-fp"),
flagpd1("mieee-rnd-near"),
flagpd1("mignore-xcoff-visibility"),
flagpd1("migrate"),
flagpd1("no-finalize-removal"),
flagpd1("no-ns-alloc-error"),
flagpd1("mimplicit-float"),
flagpd1("mincremental-linker-compatible"),
flagpd1("minline-all-stringops"),
flagpd1("minvariant-function-descriptors"),
flagpd1("minvpcid"),
flagpd1("mips1"),
flagpd1("mips16"),
flagpd1("mips2"),
flagpd1("mips3"),
flagpd1("mips32"),
flagpd1("mips32r2"),
flagpd1("mips32r3"),
flagpd1("mips32r5"),
flagpd1("mips32r6"),
flagpd1("mips4"),
flagpd1("mips5"),
flagpd1("mips64"),
flagpd1("mips64r2"),
flagpd1("mips64r3"),
flagpd1("mips64r5"),
flagpd1("mips64r6"),
flagpd1("misel"),
flagpd1("mkernel"),
flagpd1("mkl"),
flagpd1("mldc1-sdc1"),
sepd1("mlimit-float-precision"),
sepd1("mlink-bitcode-file"),
sepd1("mlink-builtin-bitcode"),
sepd1("mlink-cuda-bitcode"),
flagpd1("mlittle-endian"),
sepd1("mllvm"),
flagpd1("mlocal-sdata"),
flagpd1("mlong-calls"),
flagpd1("mlong-double-128"),
flagpd1("mlong-double-64"),
flagpd1("mlong-double-80"),
flagpd1("mlongcall"),
flagpd1("mlvi-cfi"),
flagpd1("mlvi-hardening"),
flagpd1("mlwp"),
flagpd1("mlzcnt"),
flagpd1("mmadd4"),
flagpd1("mmark-bti-property"),
flagpd1("mmemops"),
flagpd1("mmfcrf"),
flagpd1("mmfocrf"),
flagpd1("mmicromips"),
flagpd1("mmma"),
flagpd1("mmmx"),
flagpd1("mmovbe"),
flagpd1("mmovdir64b"),
flagpd1("mmovdiri"),
flagpd1("mmpx"),
flagpd1("mms-bitfields"),
flagpd1("mmsa"),
flagpd1("mmt"),
flagpd1("mmultivalue"),
flagpd1("mmutable-globals"),
flagpd1("mmwaitx"),
flagpd1("mno-3dnow"),
flagpd1("mno-3dnowa"),
flagpd1("mno-80387"),
flagpd1("mno-abicalls"),
flagpd1("mno-adx"),
flagpd1("mno-aes"),
flagpd1("mno-altivec"),
flagpd1("mno-amx-bf16"),
flagpd1("mno-amx-int8"),
flagpd1("mno-amx-tile"),
flagpd1("mno-atomics"),
flagpd1("mno-avx"),
flagpd1("mno-avx2"),
flagpd1("mno-avx512bf16"),
flagpd1("mno-avx512bitalg"),
flagpd1("mno-avx512bw"),
flagpd1("mno-avx512cd"),
flagpd1("mno-avx512dq"),
flagpd1("mno-avx512er"),
flagpd1("mno-avx512f"),
flagpd1("mno-avx512ifma"),
flagpd1("mno-avx512pf"),
flagpd1("mno-avx512vbmi"),
flagpd1("mno-avx512vbmi2"),
flagpd1("mno-avx512vl"),
flagpd1("mno-avx512vnni"),
flagpd1("mno-avx512vp2intersect"),
flagpd1("mno-avx512vpopcntdq"),
flagpd1("mno-avxvnni"),
flagpd1("mno-backchain"),
flagpd1("mno-bmi"),
flagpd1("mno-bmi2"),
flagpd1("mno-branch-likely"),
flagpd1("mno-bulk-memory"),
flagpd1("mno-check-zero-division"),
flagpd1("mno-cldemote"),
flagpd1("mno-clflushopt"),
flagpd1("mno-clwb"),
flagpd1("mno-clzero"),
flagpd1("mno-cmpb"),
flagpd1("mno-code-object-v3"),
flagpd1("mno-constant-cfstrings"),
flagpd1("mno-crbits"),
flagpd1("mno-crc"),
flagpd1("mno-cumode"),
flagpd1("mno-cx16"),
flagpd1("mno-dsp"),
flagpd1("mno-dspr2"),
flagpd1("mno-embedded-data"),
flagpd1("mno-enqcmd"),
flagpd1("mno-exception-handling"),
flagpd1("mnoexecstack"),
flagpd1("mno-execute-only"),
flagpd1("mno-extern-sdata"),
flagpd1("mno-f16c"),
flagpd1("mno-fix-cortex-a53-835769"),
flagpd1("mno-float128"),
flagpd1("mno-fma"),
flagpd1("mno-fma4"),
flagpd1("mno-fprnd"),
flagpd1("mno-fsgsbase"),
flagpd1("mno-fxsr"),
flagpd1("mno-gfni"),
flagpd1("mno-ginv"),
flagpd1("mno-global-merge"),
flagpd1("mno-gpopt"),
flagpd1("mno-hvx"),
flagpd1("mno-hreset"),
flagpd1("mno-htm"),
flagpd1("mno-iamcu"),
flagpd1("mno-implicit-float"),
flagpd1("mno-incremental-linker-compatible"),
flagpd1("mno-inline-all-stringops"),
flagpd1("mno-invariant-function-descriptors"),
flagpd1("mno-invpcid"),
flagpd1("mno-isel"),
flagpd1("mno-kl"),
flagpd1("mno-ldc1-sdc1"),
flagpd1("mno-local-sdata"),
flagpd1("mno-long-calls"),
flagpd1("mno-longcall"),
flagpd1("mno-lvi-cfi"),
flagpd1("mno-lvi-hardening"),
flagpd1("mno-lwp"),
flagpd1("mno-lzcnt"),
flagpd1("mno-madd4"),
flagpd1("mno-memops"),
flagpd1("mno-mfcrf"),
flagpd1("mno-mfocrf"),
flagpd1("mno-micromips"),
flagpd1("mno-mips16"),
flagpd1("mno-mma"),
flagpd1("mno-mmx"),
flagpd1("mno-movbe"),
flagpd1("mno-movdir64b"),
flagpd1("mno-movdiri"),
flagpd1("mno-movt"),
flagpd1("mno-mpx"),
flagpd1("mno-ms-bitfields"),
flagpd1("mno-msa"),
flagpd1("mno-mt"),
flagpd1("mno-multivalue"),
flagpd1("mno-mutable-globals"),
flagpd1("mno-mwaitx"),
flagpd1("mno-neg-immediates"),
flagpd1("mno-nontrapping-fptoint"),
flagpd1("mno-nvj"),
flagpd1("mno-nvs"),
flagpd1("mno-odd-spreg"),
flagpd1("mno-omit-leaf-frame-pointer"),
flagpd1("mno-outline"),
flagpd1("mno-outline-atomics"),
flagpd1("mno-packed-stack"),
flagpd1("mno-packets"),
flagpd1("mno-pascal-strings"),
flagpd1("mno-pclmul"),
flagpd1("mno-pconfig"),
flagpd1("mno-pcrel"),
flagpd1("mno-pie-copy-relocations"),
flagpd1("mno-pku"),
flagpd1("mno-popcnt"),
flagpd1("mno-popcntd"),
flagpd1("mno-power10-vector"),
flagpd1("mno-power8-vector"),
flagpd1("mno-power9-vector"),
flagpd1("mno-prefetchwt1"),
flagpd1("mno-prfchw"),
flagpd1("mno-ptwrite"),
flagpd1("mno-pure-code"),
flagpd1("mno-rdpid"),
flagpd1("mno-rdrnd"),
flagpd1("mno-rdseed"),
.{
.name = "mno-red-zone",
.syntax = .flag,
.zig_equivalent = .no_red_zone,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("mno-reference-types"),
flagpd1("mno-relax"),
flagpd1("mno-relax-all"),
flagpd1("mno-relax-pic-calls"),
flagpd1("mno-restrict-it"),
flagpd1("mno-retpoline"),
flagpd1("mno-retpoline-external-thunk"),
flagpd1("mno-rtd"),
flagpd1("mno-rtm"),
flagpd1("mno-sahf"),
flagpd1("mno-save-restore"),
flagpd1("mno-serialize"),
flagpd1("mno-seses"),
flagpd1("mno-sgx"),
flagpd1("mno-sha"),
flagpd1("mno-shstk"),
flagpd1("mno-sign-ext"),
flagpd1("mno-simd128"),
flagpd1("mno-soft-float"),
flagpd1("mno-spe"),
flagpd1("mno-speculative-load-hardening"),
flagpd1("mno-sse"),
flagpd1("mno-sse2"),
flagpd1("mno-sse3"),
flagpd1("mno-sse4"),
flagpd1("mno-sse4.1"),
flagpd1("mno-sse4.2"),
flagpd1("mno-sse4a"),
flagpd1("mno-ssse3"),
flagpd1("mno-stack-arg-probe"),
flagpd1("mno-stackrealign"),
flagpd1("mno-tail-call"),
flagpd1("mno-tbm"),
flagpd1("mno-thumb"),
flagpd1("mno-tls-direct-seg-refs"),
flagpd1("mno-tsxldtrk"),
flagpd1("mno-uintr"),
flagpd1("mno-unaligned-access"),
flagpd1("mno-unimplemented-simd128"),
flagpd1("mno-unsafe-fp-atomics"),
flagpd1("mno-vaes"),
flagpd1("mno-virt"),
flagpd1("mno-vpclmulqdq"),
flagpd1("mno-vsx"),
flagpd1("mno-vx"),
flagpd1("mno-vzeroupper"),
flagpd1("mno-waitpkg"),
flagpd1("mno-warn-nonportable-cfstrings"),
flagpd1("mno-wavefrontsize64"),
flagpd1("mno-wbnoinvd"),
flagpd1("mno-widekl"),
flagpd1("mno-x87"),
flagpd1("mno-xgot"),
flagpd1("mno-xop"),
flagpd1("mno-xsave"),
flagpd1("mno-xsavec"),
flagpd1("mno-xsaveopt"),
flagpd1("mno-xsaves"),
flagpd1("mno-zvector"),
flagpd1("mnocrc"),
flagpd1("mno-direct-move"),
flagpd1("mnontrapping-fptoint"),
flagpd1("mnop-mcount"),
flagpd1("mno-paired-vector-memops"),
flagpd1("mno-crypto"),
flagpd1("mnvj"),
flagpd1("mnvs"),
flagpd1("modd-spreg"),
sepd1("module-dependency-dir"),
flagpd1("module-file-deps"),
flagpd1("module-file-info"),
flagpd1("momit-leaf-frame-pointer"),
flagpd1("moutline"),
flagpd1("moutline-atomics"),
flagpd1("mpacked-stack"),
flagpd1("mpackets"),
flagpd1("mpaired-vector-memops"),
flagpd1("mpascal-strings"),
flagpd1("mpclmul"),
flagpd1("mpconfig"),
flagpd1("mpcrel"),
flagpd1("mpie-copy-relocations"),
flagpd1("mpku"),
flagpd1("mpopcnt"),
flagpd1("mpopcntd"),
flagpd1("mpower10-vector"),
flagpd1("mcrypto"),
flagpd1("mpower8-vector"),
flagpd1("mpower9-vector"),
flagpd1("mprefetchwt1"),
flagpd1("mprfchw"),
flagpd1("mptwrite"),
flagpd1("mpure-code"),
flagpd1("mqdsp6-compat"),
flagpd1("mrdpid"),
flagpd1("mrdrnd"),
flagpd1("mrdseed"),
flagpd1("mreassociate"),
flagpd1("mrecip"),
flagpd1("mrecord-mcount"),
.{
.name = "mred-zone",
.syntax = .flag,
.zig_equivalent = .red_zone,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("mreference-types"),
sepd1("mregparm"),
flagpd1("mrelax"),
flagpd1("mrelax-all"),
flagpd1("mrelax-pic-calls"),
.{
.name = "mrelax-relocations",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
sepd1("mrelocation-model"),
flagpd1("mrestrict-it"),
flagpd1("mretpoline"),
flagpd1("mretpoline-external-thunk"),
flagpd1("mrtd"),
flagpd1("mrtm"),
flagpd1("msahf"),
flagpd1("msave-restore"),
flagpd1("msave-temp-labels"),
flagpd1("msecure-plt"),
flagpd1("mserialize"),
flagpd1("msgx"),
flagpd1("msha"),
flagpd1("mshstk"),
flagpd1("msign-ext"),
flagpd1("msim"),
flagpd1("msimd128"),
flagpd1("msingle-float"),
sepd1("msmall-data-limit"),
flagpd1("msoft-float"),
flagpd1("mspe"),
flagpd1("mspeculative-load-hardening"),
flagpd1("msse"),
flagpd1("msse2"),
flagpd1("msse3"),
flagpd1("msse4"),
flagpd1("msse4.1"),
flagpd1("msse4.2"),
flagpd1("msse4a"),
flagpd1("mssse3"),
flagpd1("mstack-arg-probe"),
flagpd1("mstackrealign"),
flagpd1("mstrict-align"),
flagpd1("msvr4-struct-return"),
sepd1("mt-migrate-directory"),
flagpd1("mtail-call"),
flagpd1("mamx-int8"),
flagpd1("mtbm"),
sepd1("mthread-model"),
flagpd1("mthumb"),
flagpd1("mtls-direct-seg-refs"),
sepd1("mtp"),
flagpd1("mtsxldtrk"),
flagpd1("mtune=?"),
flagpd1("muclibc"),
flagpd1("muintr"),
flagpd1("multi_module"),
sepd1("multiply_defined"),
sepd1("multiply_defined_unused"),
flagpd1("munaligned-access"),
flagpd1("munimplemented-simd128"),
flagpd1("munsafe-fp-atomics"),
flagpd1("munwind-tables"),
flagpd1("mv5"),
flagpd1("mv55"),
flagpd1("mv60"),
flagpd1("mv62"),
flagpd1("mv65"),
flagpd1("mv66"),
flagpd1("mv67"),
flagpd1("mv67t"),
flagpd1("mvaes"),
flagpd1("mvirt"),
flagpd1("mvpclmulqdq"),
flagpd1("mvsx"),
flagpd1("mvx"),
flagpd1("mvzeroupper"),
flagpd1("mwaitpkg"),
flagpd1("mwarn-nonportable-cfstrings"),
flagpd1("mwavefrontsize64"),
flagpd1("mwbnoinvd"),
flagpd1("mwidekl"),
flagpd1("mx32"),
flagpd1("mx87"),
flagpd1("mxgot"),
flagpd1("mxop"),
flagpd1("mxsave"),
flagpd1("mxsavec"),
flagpd1("mxsaveopt"),
flagpd1("mxsaves"),
flagpd1("mzvector"),
flagpd1("n"),
flagpd1("new-struct-path-tbaa"),
flagpd1("no_dead_strip_inits_and_terms"),
flagpd1("no-canonical-prefixes"),
flagpd1("no-code-completion-globals"),
flagpd1("no-code-completion-ns-level-decls"),
flagpd1("no-cpp-precomp"),
.{
.name = "no-cuda-noopt-device-debug",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "no-cuda-version-check",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("no-emit-llvm-uselists"),
flagpd1("no-implicit-float"),
.{
.name = "no-integrated-cpp",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "no-pedantic",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("no-pie"),
flagpd1("no-pthread"),
flagpd1("no-struct-path-tbaa"),
flagpd1("nobuiltininc"),
flagpd1("nocpp"),
flagpd1("nodefaultlibs"),
flagpd1("nofixprebinding"),
flagpd1("nogpuinc"),
flagpd1("nogpulib"),
.{
.name = "nolibc",
.syntax = .flag,
.zig_equivalent = .nostdlib,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("nomultidefs"),
flagpd1("nopie"),
flagpd1("noprebind"),
flagpd1("noprofilelib"),
flagpd1("noseglinkedit"),
flagpd1("nostartfiles"),
.{
.name = "nostdinc",
.syntax = .flag,
.zig_equivalent = .nostdlibinc,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "nostdinc++",
.syntax = .flag,
.zig_equivalent = .nostdlib_cpp,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "nostdlib",
.syntax = .flag,
.zig_equivalent = .nostdlib,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "nostdlibinc",
.syntax = .flag,
.zig_equivalent = .nostdlibinc,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "nostdlib++",
.syntax = .flag,
.zig_equivalent = .nostdlib_cpp,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("nostdsysteminc"),
flagpd1("objcmt-atomic-property"),
flagpd1("objcmt-migrate-all"),
flagpd1("objcmt-migrate-annotation"),
flagpd1("objcmt-migrate-designated-init"),
flagpd1("objcmt-migrate-instancetype"),
flagpd1("objcmt-migrate-literals"),
flagpd1("objcmt-migrate-ns-macros"),
flagpd1("objcmt-migrate-property"),
flagpd1("objcmt-migrate-property-dot-syntax"),
flagpd1("objcmt-migrate-protocol-conformance"),
flagpd1("objcmt-migrate-readonly-property"),
flagpd1("objcmt-migrate-readwrite-property"),
flagpd1("objcmt-migrate-subscripting"),
flagpd1("objcmt-ns-nonatomic-iosonly"),
flagpd1("objcmt-returns-innerpointer-property"),
flagpd1("object"),
sepd1("opt-record-file"),
sepd1("opt-record-format"),
sepd1("opt-record-passes"),
sepd1("output-asm-variant"),
flagpd1("p"),
.{
.name = "pass-exit-codes",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("pch-through-hdrstop-create"),
flagpd1("pch-through-hdrstop-use"),
.{
.name = "pedantic",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "pedantic-errors",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("pg"),
flagpd1("pic-is-pie"),
sepd1("pic-level"),
flagpd1("pie"),
.{
.name = "pipe",
.syntax = .flag,
.zig_equivalent = .ignore,
.pd1 = true,
.pd2 = true,
.psl = false,
},
sepd1("plugin"),
flagpd1("prebind"),
flagpd1("prebind_all_twolevel_modules"),
flagpd1("preload"),
flagpd1("print-dependency-directives-minimized-source"),
.{
.name = "print-effective-triple",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("print-ivar-layout"),
.{
.name = "print-libgcc-file-name",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-multi-directory",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-multi-lib",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-multi-os-directory",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("print-preamble"),
.{
.name = "print-resource-dir",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-search-dirs",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("print-stats"),
.{
.name = "print-supported-cpus",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-target-triple",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-targets",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("private_bundle"),
flagpd1("pthread"),
flagpd1("pthreads"),
flagpd1("r"),
.{
.name = "rdynamic",
.syntax = .flag,
.zig_equivalent = .rdynamic,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("read_only_relocs"),
sepd1("record-command-line"),
flagpd1("relaxed-aliasing"),
.{
.name = "relocatable-pch",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("remap"),
sepd1("remap-file"),
sepd1("resource-dir"),
flagpd1("rewrite-legacy-objc"),
flagpd1("rewrite-macros"),
flagpd1("rewrite-objc"),
flagpd1("rewrite-test"),
sepd1("rpath"),
.{
.name = "s",
.syntax = .flag,
.zig_equivalent = .strip,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "save-stats",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "save-temps",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "sectalign",
.syntax = .{.multi_arg=3},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "sectcreate",
.syntax = .{.multi_arg=3},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "sectobjectsymbols",
.syntax = .{.multi_arg=2},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "sectorder",
.syntax = .{.multi_arg=3},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("seg_addr_table"),
sepd1("seg_addr_table_filename"),
.{
.name = "segaddr",
.syntax = .{.multi_arg=2},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "segcreate",
.syntax = .{.multi_arg=3},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("seglinkedit"),
.{
.name = "segprot",
.syntax = .{.multi_arg=3},
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("segs_read_only_addr"),
sepd1("segs_read_write_addr"),
flagpd1("setup-static-analyzer"),
.{
.name = "shared",
.syntax = .flag,
.zig_equivalent = .shared,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("shared-libgcc"),
flagpd1("shared-libsan"),
flagpd1("show-encoding"),
.{
.name = "show-includes",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("show-inst"),
flagpd1("single_module"),
.{
.name = "specs",
.syntax = .separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
sepd1("split-dwarf-file"),
sepd1("split-dwarf-output"),
flagpd1("split-stacks"),
sepd1("stack-protector"),
sepd1("stack-protector-buffer-size"),
.{
.name = "static",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("static-define"),
flagpd1("static-libgcc"),
flagpd1("static-libgfortran"),
flagpd1("static-libsan"),
flagpd1("static-libstdc++"),
flagpd1("static-openmp"),
flagpd1("static-pie"),
flagpd1("sys-header-deps"),
flagpd1("t"),
sepd1("target-abi"),
sepd1("target-cpu"),
sepd1("target-feature"),
.{
.name = "target",
.syntax = .separate,
.zig_equivalent = .target,
.pd1 = true,
.pd2 = false,
.psl = false,
},
sepd1("target-linker-version"),
flagpd1("templight-dump"),
flagpd1("test-io"),
flagpd1("time"),
.{
.name = "traditional",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "traditional-cpp",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "trigraphs",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("trim-egraph"),
sepd1("triple"),
sepd1("tune-cpu"),
flagpd1("twolevel_namespace"),
flagpd1("twolevel_namespace_hints"),
sepd1("umbrella"),
flagpd1("undef"),
sepd1("unexported_symbols_list"),
.{
.name = "v",
.syntax = .flag,
.zig_equivalent = .verbose,
.pd1 = true,
.pd2 = false,
.psl = false,
},
flagpd1("vectorize-loops"),
flagpd1("vectorize-slp"),
flagpd1("verify"),
.{
.name = "verify-debug-info",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
flagpd1("verify-ignore-unexpected"),
flagpd1("verify-pch"),
flagpd1("version"),
.{
.name = "via-file-asm",
.syntax = .flag,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
flagpd1("w"),
sepd1("weak_framework"),
sepd1("weak_library"),
sepd1("weak_reference_mismatches"),
flagpd1("whatsloaded"),
flagpd1("whyload"),
.{
.name = "z",
.syntax = .separate,
.zig_equivalent = .linker_input_z,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fsanitize-undefined-strip-path-components="),
joinpd1("fopenmp-cuda-teams-reduction-recs-num="),
joinpd1("fvisibility-externs-nodllstorageclass="),
joinpd1("analyzer-config-compatibility-mode="),
joinpd1("ftrivial-auto-var-init-stop-after="),
joinpd1("fpatchable-function-entry-offset="),
joinpd1("analyzer-inline-max-stack-depth="),
joinpd1("fsanitize-address-field-padding="),
joinpd1("fdiagnostics-hotness-threshold="),
joinpd1("fsanitize-memory-track-origins="),
joinpd1("mwatchos-simulator-version-min="),
joinpd1("fvisibility-externs-dllimport="),
joinpd1("fvisibility-nodllstorageclass="),
joinpd1("fxray-selected-function-group="),
joinpd1("mappletvsimulator-version-min="),
joinpd1("mstack-protector-guard-offset="),
joinpd1("fsanitize-coverage-whitelist="),
joinpd1("fsanitize-coverage-blacklist="),
joinpd1("fobjc-nonfragile-abi-version="),
joinpd1("fprofile-instrument-use-path="),
joinpd1("fsanitize-coverage-allowlist="),
joinpd1("fsanitize-coverage-blocklist="),
jspd1("fxray-instrumentation-bundle="),
joinpd1("miphonesimulator-version-min="),
joinpd1("faddress-space-map-mangling="),
joinpd1("foptimization-record-passes="),
joinpd1("ftest-module-file-extension="),
jspd1("fxray-instruction-threshold="),
joinpd1("mno-default-build-attributes"),
joinpd1("mtvos-simulator-version-min="),
joinpd1("mwatchsimulator-version-min="),
.{
.name = "include-with-prefix-before=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("objcmt-white-list-dir-path="),
joinpd1("error-on-deserialized-decl="),
joinpd1("fconstexpr-backtrace-limit="),
joinpd1("fdiagnostics-show-category="),
joinpd1("fdiagnostics-show-location="),
joinpd1("fopenmp-cuda-blocks-per-sm="),
joinpd1("fsanitize-system-blacklist="),
jspd1("fxray-instruction-threshold"),
joinpd1("headerpad_max_install_names"),
.{
.name = "libomptarget-nvptx-bc-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("mios-simulator-version-min="),
joinpd1("mstack-protector-guard-reg="),
.{
.name = "include-with-prefix-after=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("fms-compatibility-version="),
joinpd1("fopenmp-cuda-number-of-sm="),
joinpd1("foptimization-record-file="),
joinpd1("fpatchable-function-entry="),
joinpd1("fsave-optimization-record="),
joinpd1("ftemplate-backtrace-limit="),
.{
.name = "gpu-max-threads-per-block=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("objcmt-whitelist-dir-path="),
joinpd1("Wno-nonportable-cfstrings"),
joinpd1("analyzer-disable-checker="),
joinpd1("fbuild-session-timestamp="),
joinpd1("fprofile-instrument-path="),
joinpd1("mdefault-build-attributes"),
joinpd1("msign-return-address-key="),
.{
.name = "verify-ignore-unexpected=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "include-directory-after=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "compress-debug-sections=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "fcomment-block-commands=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("flax-vector-conversions="),
joinpd1("fmodules-embed-all-files"),
joinpd1("fmodules-prune-interval="),
joinpd1("foverride-record-layout="),
joinpd1("fprofile-instr-generate="),
joinpd1("fprofile-remapping-file="),
joinpd1("fsanitize-coverage-type="),
joinpd1("fsanitize-hwaddress-abi="),
joinpd1("ftime-trace-granularity="),
jspd1("fxray-always-instrument="),
jspd1("internal-externc-isystem"),
.{
.name = "no-system-header-prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "output-class-directory=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("analyzer-inlining-mode="),
joinpd1("fconstant-string-class="),
joinpd1("fcrash-diagnostics-dir="),
joinpd1("fdebug-compilation-dir="),
joinpd1("fdebug-default-version="),
joinpd1("ffp-exception-behavior="),
joinpd1("fmacro-backtrace-limit="),
joinpd1("fmax-array-constructor="),
joinpd1("fprofile-exclude-files="),
joinpd1("ftrivial-auto-var-init="),
jspd1("fxray-never-instrument="),
jspd1("interface-stub-version="),
joinpd1("malign-branch-boundary="),
joinpd1("mappletvos-version-min="),
joinpd1("mstack-protector-guard="),
joinpd1("Wnonportable-cfstrings"),
joinpd1("fbasic-block-sections="),
joinpd1("fdefault-calling-conv="),
joinpd1("fdenormal-fp-math-f32="),
joinpd1("fmax-subrecord-length="),
joinpd1("fmodules-ignore-macro="),
.{
.name = "fno-sanitize-coverage=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fobjc-dispatch-method="),
joinpd1("foperator-arrow-depth="),
joinpd1("fprebuilt-module-path="),
joinpd1("fprofile-filter-files="),
joinpd1("fspell-checking-limit="),
joinpd1("fvisibility-dllexport="),
joinpd1("fxray-function-groups="),
joinpd1("miphoneos-version-min="),
joinpd1("msmall-data-threshold="),
joinpd1("Wlarge-by-value-copy="),
joinpd1("analyzer-constraints="),
joinpd1("analyzer-dump-egraph="),
jspd1("compatibility_version"),
jspd1("dylinker_install_name"),
joinpd1("fcs-profile-generate="),
joinpd1("fmodules-prune-after="),
.{
.name = "fno-sanitize-recover=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("iframeworkwithsysroot"),
joinpd1("mcode-object-version="),
joinpd1("mpad-max-prefix-size="),
joinpd1("mprefer-vector-width="),
joinpd1("msign-return-address="),
joinpd1("mwatchos-version-min="),
.{
.name = "rocm-device-lib-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "system-header-prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-with-prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "hip-device-lib-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("coverage-notes-file="),
joinpd1("fbuild-session-file="),
joinpd1("fdiagnostics-format="),
joinpd1("fmax-stack-var-size="),
joinpd1("fmodules-cache-path="),
joinpd1("fmodules-embed-file="),
joinpd1("fprofile-instrument="),
joinpd1("fprofile-prefix-map="),
joinpd1("fprofile-sample-use="),
joinpd1("fsanitize-blacklist="),
joinpd1("mmacosx-version-min="),
.{
.name = "no-cuda-include-ptx=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("Wframe-larger-than="),
joinpd1("code-completion-at="),
joinpd1("coverage-data-file="),
joinpd1("fblas-matmul-limit="),
joinpd1("fdiagnostics-color="),
joinpd1("ffixed-line-length-"),
joinpd1("flimited-precision="),
joinpd1("fprofile-instr-use="),
.{
.name = "fsanitize-coverage=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fthin-link-bitcode="),
.{
.name = "gpu-instrument-lib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("mbranch-protection="),
joinpd1("mmacos-version-min="),
joinpd1("pch-through-header="),
joinpd1("target-sdk-version="),
.{
.name = "execution-charset:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "include-directory=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "library-directory=",
.syntax = .joined,
.zig_equivalent = .lib_dir,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "config-system-dir=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("fbinutils-version="),
joinpd1("fclang-abi-compat="),
joinpd1("fcompile-resource="),
joinpd1("fdebug-prefix-map="),
joinpd1("fdenormal-fp-math="),
joinpd1("fexcess-precision="),
joinpd1("ffree-line-length-"),
joinpd1("fmacro-prefix-map="),
.{
.name = "fno-sanitize-trap=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fobjc-abi-version="),
joinpd1("foutput-class-dir="),
joinpd1("fproc-stat-report="),
joinpd1("fprofile-generate="),
joinpd1("frewrite-map-file="),
.{
.name = "fsanitize-recover=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fsymbol-partition="),
joinpd1("mcompact-branches="),
joinpd1("msmall-data-limit="),
joinpd1("mstack-probe-size="),
joinpd1("mtvos-version-min="),
joinpd1("working-directory="),
joinpd1("analyze-function="),
joinpd1("analyzer-checker="),
joinpd1("coverage-version="),
.{
.name = "cuda-include-ptx=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("falign-functions="),
joinpd1("fconstexpr-depth="),
joinpd1("fconstexpr-steps="),
joinpd1("ffile-prefix-map="),
joinpd1("fmodule-map-file="),
joinpd1("fobjc-arc-cxxlib="),
joinpd1("fproc-stat-report"),
jspd1("iwithprefixbefore"),
joinpd1("malign-functions="),
joinpd1("mios-version-min="),
joinpd1("mstack-alignment="),
joinpd1("msve-vector-bits="),
.{
.name = "no-cuda-gpu-arch=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
jspd1("working-directory"),
joinpd1("analyzer-output="),
.{
.name = "config-user-dir=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("debug-info-kind="),
joinpd1("debugger-tuning="),
joinpd1("exception-model="),
joinpd1("fcf-runtime-abi="),
joinpd1("finit-character="),
joinpd1("fmax-type-align="),
joinpd1("fmemory-profile="),
joinpd1("fmessage-length="),
.{
.name = "fopenmp-targets=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fopenmp-version="),
joinpd1("fprofile-update="),
joinpd1("fshow-overloads="),
joinpd1("ftemplate-depth-"),
joinpd1("ftemplate-depth="),
jspd1("fxray-attr-list="),
jspd1("internal-isystem"),
joinpd1("mlinker-version="),
.{
.name = "no-offload-arch=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "print-file-name=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "print-prog-name=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
jspd1("stdlib++-isystem"),
joinpd1("Rpass-analysis="),
.{
.name = "Xopenmp-target=",
.syntax = .joined_and_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "source-charset:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "analyzer-output",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include-prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "undefine-macro=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("analyzer-purge="),
joinpd1("analyzer-store="),
jspd1("current_version"),
joinpd1("fbootclasspath="),
joinpd1("fbracket-depth="),
joinpd1("fcf-protection="),
joinpd1("fdepfile-entry="),
joinpd1("fembed-bitcode="),
joinpd1("finput-charset="),
joinpd1("fmodule-format="),
joinpd1("fms-memptr-rep="),
joinpd1("fnew-alignment="),
joinpd1("frecord-marker="),
.{
.name = "fsanitize-trap=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fthinlto-index="),
joinpd1("ftrap-function="),
joinpd1("ftrapv-handler="),
.{
.name = "hip-device-lib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("mdynamic-no-pic"),
joinpd1("mframe-pointer="),
joinpd1("mindirect-jump="),
joinpd1("preamble-bytes="),
.{
.name = "Wundef-prefix=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "bootclasspath=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-gpu-arch=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "dependent-lib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("dwarf-version="),
joinpd1("falign-labels="),
joinpd1("fauto-profile="),
joinpd1("fexec-charset="),
joinpd1("fgnuc-version="),
joinpd1("finit-integer="),
joinpd1("finit-logical="),
joinpd1("finline-limit="),
joinpd1("fobjc-runtime="),
joinpd1("fprofile-list="),
.{
.name = "gcc-toolchain=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "linker-option=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "malign-branch=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("objcxx-isystem"),
joinpd1("vtordisp-mode="),
joinpd1("Rpass-missed="),
joinpd1("Wlarger-than-"),
joinpd1("Wlarger-than="),
.{
.name = "define-macro=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("arcmt-action="),
joinpd1("ast-dump-all="),
.{
.name = "autocomplete=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("falign-jumps="),
joinpd1("falign-loops="),
joinpd1("faligned-new="),
joinpd1("ferror-limit="),
joinpd1("ffp-contract="),
joinpd1("fmodule-file="),
joinpd1("fmodule-name="),
joinpd1("fmsc-version="),
.{
.name = "fno-sanitize=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("fpack-struct="),
joinpd1("fpass-plugin="),
joinpd1("fprofile-dir="),
joinpd1("fprofile-use="),
joinpd1("frandom-seed="),
joinpd1("ftime-report="),
joinpd1("gsplit-dwarf="),
jspd1("isystem-after"),
joinpd1("malign-jumps="),
joinpd1("malign-loops="),
joinpd1("mimplicit-it="),
.{
.name = "offload-arch=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
jspd1("pagezero_size"),
joinpd1("resource-dir="),
.{
.name = "dyld-prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "driver-mode=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("fmax-errors="),
joinpd1("fmax-tokens="),
joinpd1("fno-builtin-"),
joinpd1("fvisibility="),
joinpd1("fwchar-type="),
jspd1("fxray-modes="),
.{
.name = "hip-version=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
jspd1("iwithsysroot"),
.{
.name = "mexec-model=",
.syntax = .joined,
.zig_equivalent = .exec_model,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("mharden-sls="),
joinpd1("mhvx-length="),
jspd1("objc-isystem"),
.{
.name = "rsp-quoting=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("std-default="),
jspd1("sub_umbrella"),
.{
.name = "Qpar-report",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Qvec-report",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "errorReport",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "for-linker=",
.syntax = .joined,
.zig_equivalent = .for_linker,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "force-link=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
jspd1("client_name"),
jspd1("cxx-isystem"),
joinpd1("fclasspath="),
joinpd1("finit-real="),
joinpd1("fforce-addr"),
joinpd1("ftls-model="),
jspd1("ivfsoverlay"),
jspd1("iwithprefix"),
joinpd1("mfloat-abi="),
.{
.name = "plugin-arg-",
.syntax = .joined_and_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "ptxas-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "save-stats=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "save-temps=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
joinpd1("stats-file="),
jspd1("sub_library"),
.{
.name = "CLASSPATH=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "constexpr:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vctoolsdir",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "classpath=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cuda-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("fencoding="),
joinpd1("ffp-model="),
joinpd1("ffpe-trap="),
joinpd1("flto-jobs="),
.{
.name = "fsanitize=",
.syntax = .comma_joined,
.zig_equivalent = .sanitize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("iframework"),
joinpd1("mtls-size="),
.{
.name = "rocm-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("segs_read_"),
.{
.name = "unwindlib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "cgthreads",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "encoding=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "language=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "optimize=",
.syntax = .joined,
.zig_equivalent = .optimize,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "resource=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("ast-dump="),
jspd1("c-isystem"),
joinpd1("fcoarray="),
joinpd1("fconvert="),
joinpd1("fextdirs="),
joinpd1("ftabstop="),
jspd1("idirafter"),
joinpd1("mregparm="),
joinpd1("sycl-std="),
jspd1("undefined"),
.{
.name = "extdirs=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "imacros=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "include=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "sysroot=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
jspd1("dsym-dir"),
joinpd1("fopenmp="),
joinpd1("fplugin="),
joinpd1("fuse-ld="),
joinpd1("fveclib="),
jspd1("isysroot"),
.{
.name = "ld-path=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("mcmodel="),
joinpd1("mconsole"),
joinpd1("mdouble="),
joinpd1("mfpmath="),
joinpd1("mhwmult="),
joinpd1("mthreads"),
joinpd1("municode"),
joinpd1("mwindows"),
jspd1("seg1addr"),
.{
.name = "assert=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "mhwdiv=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "output=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "prefix=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "cl-ext=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("cl-std="),
joinpd1("fcheck="),
.{
.name = "imacros",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "include",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
jspd1("iprefix"),
jspd1("isystem"),
joinpd1("mhwdiv="),
joinpd1("moslib="),
.{
.name = "mrecip=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "stdlib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "target=",
.syntax = .joined,
.zig_equivalent = .target,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("triple="),
.{
.name = "verify=",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("Rpass="),
.{
.name = "Xarch_",
.syntax = .joined_and_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "clang:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "guard:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "debug=",
.syntax = .joined,
.zig_equivalent = .debug,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "param=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "warn-=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
joinpd1("fixit="),
joinpd1("gstabs"),
joinpd1("gxcoff"),
jspd1("iquote"),
.{
.name = "march=",
.syntax = .joined,
.zig_equivalent = .mcpu,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "mtune=",
.syntax = .joined,
.zig_equivalent = .mcpu,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "rtlib=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "specs=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
joinpd1("weak-l"),
.{
.name = "Ofast",
.syntax = .flag,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("Tdata"),
jspd1("Ttext"),
.{
.name = "arch:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "favor",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "imsvc",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "tune:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "warn-",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = false,
.pd2 = true,
.psl = false,
},
.{
.name = "flto=",
.syntax = .joined,
.zig_equivalent = .lto,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("gcoff"),
joinpd1("mabi="),
joinpd1("mabs="),
joinpd1("masm="),
.{
.name = "mcpu=",
.syntax = .joined,
.zig_equivalent = .mcpu,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("mfpu="),
joinpd1("mhvx="),
joinpd1("mmcu="),
joinpd1("mnan="),
jspd1("Tbss"),
.{
.name = "link",
.syntax = .remaining_args_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "std:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
joinpd1("ccc-"),
joinpd1("gvms"),
joinpd1("mdll"),
joinpd1("mtp="),
.{
.name = "std=",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = true,
.psl = false,
},
.{
.name = "Wa,",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "Wl,",
.syntax = .comma_joined,
.zig_equivalent = .wl,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "Wp,",
.syntax = .comma_joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "Fe:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "RTC",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zc:",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "clr",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "doc",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
joinpd1("gz="),
joinpd1("A-"),
joinpd1("G="),
.{
.name = "MF",
.syntax = .joined_or_separate,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MJ",
.syntax = .joined_or_separate,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MQ",
.syntax = .joined_or_separate,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "MT",
.syntax = .joined_or_separate,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "AI",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "EH",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FA",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FI",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FR",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "FU",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fa",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fd",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fe",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fi",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fm",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fo",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fp",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Fr",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Gs",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "MP",
.syntax = .joined,
.zig_equivalent = .dep_file,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Tc",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Tp",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Yc",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Yl",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Yu",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "ZW",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zm",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "Zp",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "d2",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "vd",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
jspd1("A"),
jspd1("B"),
jspd1("D"),
.{
.name = "F",
.syntax = .joined_or_separate,
.zig_equivalent = .framework_dir,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("G"),
jspd1("I"),
jspd1("J"),
.{
.name = "L",
.syntax = .joined_or_separate,
.zig_equivalent = .lib_dir,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "O",
.syntax = .joined,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = false,
},
joinpd1("R"),
.{
.name = "T",
.syntax = .joined_or_separate,
.zig_equivalent = .linker_script,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("U"),
jspd1("V"),
joinpd1("W"),
joinpd1("X"),
joinpd1("Z"),
.{
.name = "D",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "F",
.syntax = .joined_or_separate,
.zig_equivalent = .framework_dir,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "I",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "O",
.syntax = .joined,
.zig_equivalent = .optimize,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "U",
.syntax = .joined_or_separate,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "o",
.syntax = .joined_or_separate,
.zig_equivalent = .o,
.pd1 = true,
.pd2 = false,
.psl = true,
},
.{
.name = "w",
.syntax = .joined,
.zig_equivalent = .other,
.pd1 = true,
.pd2 = false,
.psl = true,
},
joinpd1("a"),
jspd1("b"),
joinpd1("d"),
jspd1("e"),
.{
.name = "l",
.syntax = .joined_or_separate,
.zig_equivalent = .l,
.pd1 = true,
.pd2 = false,
.psl = false,
},
.{
.name = "o",
.syntax = .joined_or_separate,
.zig_equivalent = .o,
.pd1 = true,
.pd2 = false,
.psl = false,
},
jspd1("u"),
jspd1("x"),
joinpd1("y"),
};};
|
src/clang_options_data.zig
|
const std = @import("std");
const builtin = @import("builtin");
const c = @This();
const page_size = std.mem.page_size;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
test {
_ = tokenizer;
}
pub const tokenizer = @import("c/tokenizer.zig");
pub const Token = tokenizer.Token;
pub const Tokenizer = tokenizer.Tokenizer;
/// The return type is `type` to force comptime function call execution.
/// TODO: https://github.com/ziglang/zig/issues/425
/// If not linking libc, returns struct{pub const ok = false;}
/// If linking musl libc, returns struct{pub const ok = true;}
/// If linking gnu libc (glibc), the `ok` value will be true if the target
/// version is greater than or equal to `glibc_version`.
/// If linking a libc other than these, returns `false`.
pub fn versionCheck(glibc_version: std.builtin.Version) type {
return struct {
pub const ok = blk: {
if (!builtin.link_libc) break :blk false;
if (builtin.abi.isMusl()) break :blk true;
if (builtin.target.isGnuLibC()) {
const ver = builtin.os.version_range.linux.glibc;
const order = ver.order(glibc_version);
break :blk switch (order) {
.gt, .eq => true,
.lt => false,
};
} else {
break :blk false;
}
};
};
}
pub usingnamespace switch (builtin.os.tag) {
.linux => @import("c/linux.zig"),
.windows => @import("c/windows.zig"),
.macos, .ios, .tvos, .watchos => @import("c/darwin.zig"),
.freebsd, .kfreebsd => @import("c/freebsd.zig"),
.netbsd => @import("c/netbsd.zig"),
.dragonfly => @import("c/dragonfly.zig"),
.openbsd => @import("c/openbsd.zig"),
.haiku => @import("c/haiku.zig"),
.hermit => @import("c/hermit.zig"),
.solaris => @import("c/solaris.zig"),
.fuchsia => @import("c/fuchsia.zig"),
.minix => @import("c/minix.zig"),
.emscripten => @import("c/emscripten.zig"),
.wasi => @import("c/wasi.zig"),
else => struct {},
};
pub const whence_t = if (builtin.os.tag == .wasi) std.os.wasi.whence_t else c_int;
pub usingnamespace switch (builtin.os.tag) {
.netbsd, .macos, .ios, .watchos, .tvos, .windows => struct {},
else => struct {
pub extern "c" fn clock_getres(clk_id: c_int, tp: *c.timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *c.timespec) c_int;
pub extern "c" fn fstat(fd: c.fd_t, buf: *c.Stat) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *c.rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*c.timeval, noalias tz: ?*c.timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const c.timespec, rmtp: ?*c.timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const c.Sigaction, noalias oact: ?*c.Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const c.sigset_t, noalias oset: ?*c.sigset_t) c_int;
pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *c.Stat) c_int;
pub extern "c" fn sigfillset(set: ?*c.sigset_t) void;
pub extern "c" fn alarm(seconds: c_uint) c_uint;
pub extern "c" fn sigwait(set: ?*c.sigset_t, sig: ?*c_int) c_int;
},
};
pub usingnamespace switch (builtin.os.tag) {
.macos, .ios, .watchos, .tvos => struct {},
else => struct {
pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub extern "c" fn fstatat(dirfd: c.fd_t, path: [*:0]const u8, stat_buf: *c.Stat, flags: u32) c_int;
},
};
pub fn getErrno(rc: anytype) c.E {
if (rc == -1) {
return @intToEnum(c.E, c._errno().*);
} else {
return .SUCCESS;
}
}
pub extern "c" var environ: [*:null]?[*:0]u8;
pub extern "c" fn fopen(noalias filename: [*:0]const u8, noalias modes: [*:0]const u8) ?*FILE;
pub extern "c" fn fclose(stream: *FILE) c_int;
pub extern "c" fn fwrite(noalias ptr: [*]const u8, size_of_type: usize, item_count: usize, noalias stream: *FILE) usize;
pub extern "c" fn fread(noalias ptr: [*]u8, size_of_type: usize, item_count: usize, noalias stream: *FILE) usize;
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
pub extern "c" fn abort() noreturn;
pub extern "c" fn exit(code: c_int) noreturn;
pub extern "c" fn _exit(code: c_int) noreturn;
pub extern "c" fn isatty(fd: c.fd_t) c_int;
pub extern "c" fn close(fd: c.fd_t) c_int;
pub extern "c" fn lseek(fd: c.fd_t, offset: c.off_t, whence: whence_t) c.off_t;
pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn openat(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn ftruncate(fd: c_int, length: c.off_t) c_int;
pub extern "c" fn raise(sig: c_int) c_int;
pub extern "c" fn read(fd: c.fd_t, buf: [*]u8, nbyte: usize) isize;
pub extern "c" fn readv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint) isize;
pub extern "c" fn pread(fd: c.fd_t, buf: [*]u8, nbyte: usize, offset: c.off_t) isize;
pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: c.off_t) isize;
pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize;
pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: c.off_t) isize;
pub extern "c" fn write(fd: c.fd_t, buf: [*]const u8, nbyte: usize) isize;
pub extern "c" fn pwrite(fd: c.fd_t, buf: [*]const u8, nbyte: usize, offset: c.off_t) isize;
pub extern "c" fn mmap(addr: ?*align(page_size) anyopaque, len: usize, prot: c_uint, flags: c_uint, fd: c.fd_t, offset: c.off_t) *anyopaque;
pub extern "c" fn munmap(addr: *align(page_size) const anyopaque, len: usize) c_int;
pub extern "c" fn msync(addr: *align(page_size) const anyopaque, len: usize, flags: c_int) c_int;
pub extern "c" fn mprotect(addr: *align(page_size) anyopaque, len: usize, prot: c_uint) c_int;
pub extern "c" fn link(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: c_int) c_int;
pub extern "c" fn linkat(oldfd: c.fd_t, oldpath: [*:0]const u8, newfd: c.fd_t, newpath: [*:0]const u8, flags: c_int) c_int;
pub extern "c" fn unlink(path: [*:0]const u8) c_int;
pub extern "c" fn unlinkat(dirfd: c.fd_t, path: [*:0]const u8, flags: c_uint) c_int;
pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8;
pub extern "c" fn waitpid(pid: c.pid_t, stat_loc: ?*c_int, options: c_int) c.pid_t;
pub extern "c" fn fork() c_int;
pub extern "c" fn access(path: [*:0]const u8, mode: c_uint) c_int;
pub extern "c" fn faccessat(dirfd: c.fd_t, path: [*:0]const u8, mode: c_uint, flags: c_uint) c_int;
pub extern "c" fn pipe(fds: *[2]c.fd_t) c_int;
pub extern "c" fn mkdir(path: [*:0]const u8, mode: c_uint) c_int;
pub extern "c" fn mkdirat(dirfd: c.fd_t, path: [*:0]const u8, mode: u32) c_int;
pub extern "c" fn symlink(existing: [*:0]const u8, new: [*:0]const u8) c_int;
pub extern "c" fn symlinkat(oldpath: [*:0]const u8, newdirfd: c.fd_t, newpath: [*:0]const u8) c_int;
pub extern "c" fn rename(old: [*:0]const u8, new: [*:0]const u8) c_int;
pub extern "c" fn renameat(olddirfd: c.fd_t, old: [*:0]const u8, newdirfd: c.fd_t, new: [*:0]const u8) c_int;
pub extern "c" fn chdir(path: [*:0]const u8) c_int;
pub extern "c" fn fchdir(fd: c.fd_t) c_int;
pub extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int;
pub extern "c" fn dup(fd: c.fd_t) c_int;
pub extern "c" fn dup2(old_fd: c.fd_t, new_fd: c.fd_t) c_int;
pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
pub extern "c" fn readlinkat(dirfd: c.fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
pub extern "c" fn fchmod(fd: c.fd_t, mode: c.mode_t) c_int;
pub extern "c" fn fchown(fd: c.fd_t, owner: c.uid_t, group: c.gid_t) c_int;
pub extern "c" fn rmdir(path: [*:0]const u8) c_int;
pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8;
pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*anyopaque, oldlenp: ?*usize, newp: ?*anyopaque, newlen: usize) c_int;
pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*anyopaque, oldlenp: ?*usize, newp: ?*anyopaque, newlen: usize) c_int;
pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int;
pub extern "c" fn tcgetattr(fd: c.fd_t, termios_p: *c.termios) c_int;
pub extern "c" fn tcsetattr(fd: c.fd_t, optional_action: c.TCSA, termios_p: *const c.termios) c_int;
pub extern "c" fn fcntl(fd: c.fd_t, cmd: c_int, ...) c_int;
pub extern "c" fn flock(fd: c.fd_t, operation: c_int) c_int;
pub extern "c" fn ioctl(fd: c.fd_t, request: c_int, ...) c_int;
pub extern "c" fn uname(buf: *c.utsname) c_int;
pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
pub extern "c" fn shutdown(socket: c.fd_t, how: c_int) c_int;
pub extern "c" fn bind(socket: c.fd_t, address: ?*const c.sockaddr, address_len: c.socklen_t) c_int;
pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]c.fd_t) c_int;
pub extern "c" fn listen(sockfd: c.fd_t, backlog: c_uint) c_int;
pub extern "c" fn getsockname(sockfd: c.fd_t, noalias addr: *c.sockaddr, noalias addrlen: *c.socklen_t) c_int;
pub extern "c" fn getpeername(sockfd: c.fd_t, noalias addr: *c.sockaddr, noalias addrlen: *c.socklen_t) c_int;
pub extern "c" fn connect(sockfd: c.fd_t, sock_addr: *const c.sockaddr, addrlen: c.socklen_t) c_int;
pub extern "c" fn accept(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t) c_int;
pub extern "c" fn accept4(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t, flags: c_uint) c_int;
pub extern "c" fn getsockopt(sockfd: c.fd_t, level: u32, optname: u32, noalias optval: ?*anyopaque, noalias optlen: *c.socklen_t) c_int;
pub extern "c" fn setsockopt(sockfd: c.fd_t, level: u32, optname: u32, optval: ?*const anyopaque, optlen: c.socklen_t) c_int;
pub extern "c" fn send(sockfd: c.fd_t, buf: *const anyopaque, len: usize, flags: u32) isize;
pub extern "c" fn sendto(
sockfd: c.fd_t,
buf: *const anyopaque,
len: usize,
flags: u32,
dest_addr: ?*const c.sockaddr,
addrlen: c.socklen_t,
) isize;
pub extern "c" fn sendmsg(sockfd: c.fd_t, msg: *const std.x.os.Socket.Message, flags: c_int) isize;
pub extern "c" fn recv(sockfd: c.fd_t, arg1: ?*anyopaque, arg2: usize, arg3: c_int) isize;
pub extern "c" fn recvfrom(
sockfd: c.fd_t,
noalias buf: *anyopaque,
len: usize,
flags: u32,
noalias src_addr: ?*c.sockaddr,
noalias addrlen: ?*c.socklen_t,
) isize;
pub extern "c" fn recvmsg(sockfd: c.fd_t, msg: *std.x.os.Socket.Message, flags: c_int) isize;
pub extern "c" fn kill(pid: c.pid_t, sig: c_int) c_int;
pub extern "c" fn getdirentries(fd: c.fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize;
pub extern "c" fn setuid(uid: c.uid_t) c_int;
pub extern "c" fn setgid(gid: c.gid_t) c_int;
pub extern "c" fn seteuid(euid: c.uid_t) c_int;
pub extern "c" fn setegid(egid: c.gid_t) c_int;
pub extern "c" fn setreuid(ruid: c.uid_t, euid: c.uid_t) c_int;
pub extern "c" fn setregid(rgid: c.gid_t, egid: c.gid_t) c_int;
pub extern "c" fn setresuid(ruid: c.uid_t, euid: c.uid_t, suid: c.uid_t) c_int;
pub extern "c" fn setresgid(rgid: c.gid_t, egid: c.gid_t, sgid: c.gid_t) c_int;
pub extern "c" fn malloc(usize) ?*anyopaque;
pub extern "c" fn realloc(?*anyopaque, usize) ?*anyopaque;
pub extern "c" fn free(?*anyopaque) void;
pub extern "c" fn futimes(fd: c.fd_t, times: *[2]c.timeval) c_int;
pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]c.timeval) c_int;
pub extern "c" fn utimensat(dirfd: c.fd_t, pathname: [*:0]const u8, times: *[2]c.timespec, flags: u32) c_int;
pub extern "c" fn futimens(fd: c.fd_t, times: *const [2]c.timespec) c_int;
pub extern "c" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const c.pthread_attr_t, start_routine: fn (?*anyopaque) callconv(.C) ?*anyopaque, noalias arg: ?*anyopaque) c.E;
pub extern "c" fn pthread_attr_init(attr: *c.pthread_attr_t) c.E;
pub extern "c" fn pthread_attr_setstack(attr: *c.pthread_attr_t, stackaddr: *anyopaque, stacksize: usize) c.E;
pub extern "c" fn pthread_attr_setstacksize(attr: *c.pthread_attr_t, stacksize: usize) c.E;
pub extern "c" fn pthread_attr_setguardsize(attr: *c.pthread_attr_t, guardsize: usize) c.E;
pub extern "c" fn pthread_attr_destroy(attr: *c.pthread_attr_t) c.E;
pub extern "c" fn pthread_self() pthread_t;
pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*anyopaque) c.E;
pub extern "c" fn pthread_detach(thread: pthread_t) c.E;
pub extern "c" fn pthread_atfork(
prepare: ?fn () callconv(.C) void,
parent: ?fn () callconv(.C) void,
child: ?fn () callconv(.C) void,
) c_int;
pub extern "c" fn pthread_key_create(key: *c.pthread_key_t, destructor: ?fn (value: *anyopaque) callconv(.C) void) c.E;
pub extern "c" fn pthread_key_delete(key: c.pthread_key_t) c.E;
pub extern "c" fn pthread_getspecific(key: c.pthread_key_t) ?*anyopaque;
pub extern "c" fn pthread_setspecific(key: c.pthread_key_t, value: ?*anyopaque) c_int;
pub extern "c" fn sem_init(sem: *c.sem_t, pshared: c_int, value: c_uint) c_int;
pub extern "c" fn sem_destroy(sem: *c.sem_t) c_int;
pub extern "c" fn sem_open(name: [*:0]const u8, flag: c_int, mode: c.mode_t, value: c_uint) *c.sem_t;
pub extern "c" fn sem_close(sem: *c.sem_t) c_int;
pub extern "c" fn sem_post(sem: *c.sem_t) c_int;
pub extern "c" fn sem_wait(sem: *c.sem_t) c_int;
pub extern "c" fn sem_trywait(sem: *c.sem_t) c_int;
pub extern "c" fn sem_timedwait(sem: *c.sem_t, abs_timeout: *const c.timespec) c_int;
pub extern "c" fn sem_getvalue(sem: *c.sem_t, sval: *c_int) c_int;
pub extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: c.mode_t) c_int;
pub extern "c" fn shm_unlink(name: [*:0]const u8) c_int;
pub extern "c" fn kqueue() c_int;
pub extern "c" fn kevent(
kq: c_int,
changelist: [*]const c.Kevent,
nchanges: c_int,
eventlist: [*]c.Kevent,
nevents: c_int,
timeout: ?*const c.timespec,
) c_int;
pub extern "c" fn port_create() c.port_t;
pub extern "c" fn port_associate(
port: c.port_t,
source: u32,
object: usize,
events: u32,
user_var: ?*anyopaque,
) c_int;
pub extern "c" fn port_dissociate(port: c.port_t, source: u32, object: usize) c_int;
pub extern "c" fn port_send(port: c.port_t, events: u32, user_var: ?*anyopaque) c_int;
pub extern "c" fn port_sendn(
ports: [*]c.port_t,
errors: []u32,
num_ports: u32,
events: u32,
user_var: ?*anyopaque,
) c_int;
pub extern "c" fn port_get(port: c.port_t, event: *c.port_event, timeout: ?*c.timespec) c_int;
pub extern "c" fn port_getn(
port: c.port_t,
event_list: []c.port_event,
max_events: u32,
events_retrieved: *u32,
timeout: ?*c.timespec,
) c_int;
pub extern "c" fn port_alert(port: c.port_t, flags: u32, events: u32, user_var: ?*anyopaque) c_int;
pub extern "c" fn getaddrinfo(
noalias node: ?[*:0]const u8,
noalias service: ?[*:0]const u8,
noalias hints: ?*const c.addrinfo,
noalias res: **c.addrinfo,
) c.EAI;
pub extern "c" fn freeaddrinfo(res: *c.addrinfo) void;
pub extern "c" fn getnameinfo(
noalias addr: *const c.sockaddr,
addrlen: c.socklen_t,
noalias host: [*]u8,
hostlen: c.socklen_t,
noalias serv: [*]u8,
servlen: c.socklen_t,
flags: u32,
) c.EAI;
pub extern "c" fn gai_strerror(errcode: c.EAI) [*:0]const u8;
pub extern "c" fn poll(fds: [*]c.pollfd, nfds: c.nfds_t, timeout: c_int) c_int;
pub extern "c" fn ppoll(fds: [*]c.pollfd, nfds: c.nfds_t, timeout: ?*const c.timespec, sigmask: ?*const c.sigset_t) c_int;
pub extern "c" fn dn_expand(
msg: [*:0]const u8,
eomorig: [*:0]const u8,
comp_dn: [*:0]const u8,
exp_dn: [*:0]u8,
length: c_int,
) c_int;
pub const PTHREAD_MUTEX_INITIALIZER = c.pthread_mutex_t{};
pub extern "c" fn pthread_mutex_lock(mutex: *c.pthread_mutex_t) c.E;
pub extern "c" fn pthread_mutex_unlock(mutex: *c.pthread_mutex_t) c.E;
pub extern "c" fn pthread_mutex_trylock(mutex: *c.pthread_mutex_t) c.E;
pub extern "c" fn pthread_mutex_destroy(mutex: *c.pthread_mutex_t) c.E;
pub const PTHREAD_COND_INITIALIZER = c.pthread_cond_t{};
pub extern "c" fn pthread_cond_wait(noalias cond: *c.pthread_cond_t, noalias mutex: *c.pthread_mutex_t) c.E;
pub extern "c" fn pthread_cond_timedwait(noalias cond: *c.pthread_cond_t, noalias mutex: *c.pthread_mutex_t, noalias abstime: *const c.timespec) c.E;
pub extern "c" fn pthread_cond_signal(cond: *c.pthread_cond_t) c.E;
pub extern "c" fn pthread_cond_broadcast(cond: *c.pthread_cond_t) c.E;
pub extern "c" fn pthread_cond_destroy(cond: *c.pthread_cond_t) c.E;
pub extern "c" fn pthread_rwlock_destroy(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub extern "c" fn pthread_rwlock_rdlock(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub extern "c" fn pthread_rwlock_wrlock(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub extern "c" fn pthread_rwlock_trywrlock(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub extern "c" fn pthread_rwlock_unlock(rwl: *c.pthread_rwlock_t) callconv(.C) c.E;
pub const pthread_t = *opaque {};
pub const FILE = opaque {};
pub extern "c" fn dlopen(path: [*:0]const u8, mode: c_int) ?*anyopaque;
pub extern "c" fn dlclose(handle: *anyopaque) c_int;
pub extern "c" fn dlsym(handle: ?*anyopaque, symbol: [*:0]const u8) ?*anyopaque;
pub extern "c" fn sync() void;
pub extern "c" fn syncfs(fd: c_int) c_int;
pub extern "c" fn fsync(fd: c_int) c_int;
pub extern "c" fn fdatasync(fd: c_int) c_int;
pub extern "c" fn prctl(option: c_int, ...) c_int;
pub extern "c" fn getrlimit(resource: c.rlimit_resource, rlim: *c.rlimit) c_int;
pub extern "c" fn setrlimit(resource: c.rlimit_resource, rlim: *const c.rlimit) c_int;
pub extern "c" fn fmemopen(noalias buf: ?*anyopaque, size: usize, noalias mode: [*:0]const u8) ?*FILE;
pub extern "c" fn syslog(priority: c_int, message: [*:0]const u8, ...) void;
pub extern "c" fn openlog(ident: [*:0]const u8, logopt: c_int, facility: c_int) void;
pub extern "c" fn closelog() void;
pub extern "c" fn setlogmask(maskpri: c_int) c_int;
pub extern "c" fn if_nametoindex([*:0]const u8) c_int;
pub const max_align_t = if (builtin.abi == .msvc)
f64
else if (builtin.target.isDarwin())
c_longdouble
else
extern struct {
a: c_longlong,
b: c_longdouble,
};
|
lib/std/c.zig
|
const std = @import("std");
const scanner = @import("scanner.zig");
const vm = @import("vm.zig");
const debug = @import("debug.zig");
const vl = @import("value.zig");
const Allocator = std.mem.Allocator;
const Stack = @import("stack.zig").Stack;
const Chunk = @import("chunk.zig").Chunk;
const OpCode = @import("chunk.zig").OpCode;
const Token = scanner.Token;
const TokenTag = scanner.TokenTag;
const Value = vl.Value;
const Function = vl.Function;
const Parser = struct {
current: Token = undefined,
previous: Token = undefined,
hadError: bool = false,
panicMode: bool = false,
};
const Compiler = struct {
const FunctionType = enum {
script,
function,
};
const Local = struct {
name: Token,
depth: i64,
is_captured: bool,
};
const Upvalue = struct {
index: u8,
is_local: bool,
};
const stack_max = std.math.maxInt(u8) + 1;
const Locals = Stack(Local, stack_max);
const Upvalues = Stack(Upvalue, stack_max);
enclosing: ?*Compiler = null,
function: *Function,
ty: FunctionType,
locals: Locals = .{},
upvalues: Upvalues = .{},
scope_depth: i64 = 0,
};
const Precedence = enum(u8) {
none,
assignment,
or_,
and_,
equality,
comparison,
term,
factor,
unary,
call,
primary,
};
const PrefixFn = fn (bool) ParseError!void;
const InfixFn = fn () ParseError!void;
const ParseError = anyerror;
const ParseRule = struct {
prefix: ?PrefixFn,
infix: ?InfixFn,
precedence: Precedence,
};
const rules_table = blk: {
var table = [_]ParseRule{.{
.prefix = null,
.infix = null,
.precedence = .none,
}} ** @typeInfo(TokenTag).Enum.fields.len;
table[@enumToInt(TokenTag.left_paren)] = ParseRule{
.prefix = grouping,
.infix = call,
.precedence = .call,
};
table[@enumToInt(TokenTag.minus)] = ParseRule{
.prefix = unary,
.infix = binary,
.precedence = .term,
};
table[@enumToInt(TokenTag.plus)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .term,
};
table[@enumToInt(TokenTag.star)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .factor,
};
table[@enumToInt(TokenTag.slash)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .factor,
};
table[@enumToInt(TokenTag.number)].prefix = number;
table[@enumToInt(TokenTag.nil)].prefix = literal;
table[@enumToInt(TokenTag.true_)].prefix = literal;
table[@enumToInt(TokenTag.false_)].prefix = literal;
table[@enumToInt(TokenTag.string)].prefix = string;
table[@enumToInt(TokenTag.bang)].prefix = unary;
table[@enumToInt(TokenTag.bang_equal)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .equality,
};
table[@enumToInt(TokenTag.equal_equal)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .equality,
};
table[@enumToInt(TokenTag.less)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .comparison,
};
table[@enumToInt(TokenTag.less_equal)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .comparison,
};
table[@enumToInt(TokenTag.greater)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .comparison,
};
table[@enumToInt(TokenTag.greater_equal)] = ParseRule{
.prefix = null,
.infix = binary,
.precedence = .comparison,
};
table[@enumToInt(TokenTag.identifier)].prefix = variable;
table[@enumToInt(TokenTag.and_)] = ParseRule{
.prefix = null,
.infix = and_,
.precedence = .and_,
};
table[@enumToInt(TokenTag.or_)] = ParseRule{
.prefix = null,
.infix = or_,
.precedence = .or_,
};
break :blk table;
};
fn getRule(tag: TokenTag) *const ParseRule {
return &rules_table[@enumToInt(tag)];
}
var parser = Parser{};
var current: *Compiler = undefined;
pub fn compile(allocator: *Allocator, source_code: []const u8) !*Function {
scanner.init(source_code);
var compiler = Compiler{
.function = try vm.newFunction(),
.ty = .script,
};
current = &compiler;
parser.hadError = false;
parser.panicMode = false;
try advance();
while (!try match(.eof)) {
try declaration();
}
const func = try endCompiler();
if (parser.hadError) {
return vm.InterpretError.Compilation;
}
return func;
}
fn parsePrecedence(prec: Precedence) ParseError!void {
try advance();
const prefixFn = getRule(parser.previous.tag).prefix;
if (prefixFn == null) {
try errorAtPrevious("Expect expression.");
return;
}
const can_assign = @enumToInt(prec) <= @enumToInt(Precedence.assignment);
try prefixFn.?(can_assign);
while (@enumToInt(prec) <= @enumToInt(getRule(parser.current.tag).precedence)) {
try advance();
const infixFn = getRule(parser.previous.tag).infix;
try infixFn.?();
}
}
fn declaration() ParseError!void {
if (try match(.fun)) {
try funDeclaration();
} else if (try match(.var_)) {
try varDeclaration();
} else {
try statement();
}
if (parser.panicMode) try synchronize();
}
fn funDeclaration() ParseError!void {
const global = try parseVariable("Expect function name.");
markInitialized();
try function(.function);
try defineVariable(global);
}
fn function(ty: Compiler.FunctionType) ParseError!void {
var compiler = Compiler{
.enclosing = current,
.function = try vm.newFunction(),
.ty = ty,
};
if (ty != .script) {
const name = try vm.createString(parser.previous.span);
compiler.function.name = name.cast(vl.String).?;
}
compiler.locals.push(Compiler.Local{
.depth = 0,
.is_captured = false,
.name = scanner.Token{
.tag = undefined,
.span = "",
.line = parser.previous.line,
},
});
current = &compiler;
try beginScope();
try consume(.left_paren, "Expect '(' after function name.");
if (!check(.right_paren)) {
while (true) {
current.function.arity += 1;
if (current.function.arity > 255) {
try errorAtCurrent("Can't have more than 255 parameters");
}
const param = try parseVariable("Expected parameter name.");
try defineVariable(param);
if (!try match(.comma)) break;
}
}
try consume(.right_paren, "Expect ')' after function name.");
try consume(.left_brace, "Expect '{' before function body.");
try block();
const func = try endCompiler();
current = compiler.enclosing.?;
try emitOpByte(.closure, try makeConstant(Value{ .obj = &func.base }));
for (compiler.upvalues.slice()) |upvalue| {
try emitByte(if (upvalue.is_local) 1 else 0);
try emitByte(upvalue.index);
}
}
fn varDeclaration() ParseError!void {
var global = try parseVariable("Expected variable name.");
if (try match(.equal)) {
try expression();
} else {
try emitOp(.nil);
}
try consume(.semicolon, "Expect ';' after variable declaration.");
try defineVariable(global);
}
fn parseVariable(errorMessage: []const u8) ParseError!u8 {
try consume(.identifier, errorMessage);
try declareVariable();
if (current.scope_depth > 0) return @as(u8, 0);
return identifierConstant(&parser.previous);
}
fn declareVariable() ParseError!void {
if (current.scope_depth == 0) return;
const name: *Token = &parser.previous;
{
var i: usize = 0;
while (i < current.locals.top) : (i += 1) {
const local = current.locals.peek(i);
if (local.depth != -1 and local.depth < current.scope_depth) {
break;
}
if (identifiersEqual(name, &local.name)) {
try errorAtPrevious("Already a variable with this name in this scope.");
}
}
}
try addLocal(name);
}
fn addLocal(name: *Token) ParseError!void {
if (current.locals.full()) {
try errorAtPrevious("Too many local variables in function.");
return;
}
current.locals.push(Compiler.Local{
.name = name.*,
.depth = -1,
.is_captured = false,
});
}
fn identifiersEqual(a: *Token, b: *Token) bool {
return std.mem.eql(u8, a.span, b.span);
}
fn defineVariable(global: u8) ParseError!void {
if (current.scope_depth > 0) {
markInitialized();
return;
}
try emitOpByte(.define_global, global);
}
fn markInitialized() void {
if (current.scope_depth == 0) return;
current.locals.peek(0).depth = current.scope_depth;
}
fn statement() ParseError!void {
if (try match(.print)) {
try printStatement();
} else if (try match(.for_)) {
try forStatement();
} else if (try match(.if_)) {
try ifStatement();
} else if (try match(.return_)) {
try returnStatement();
} else if (try match(.while_)) {
try whileStatement();
} else if (try match(.left_brace)) {
try beginScope();
try block();
try endScope();
} else {
try expressionStatement();
}
}
fn block() ParseError!void {
while (!check(.right_brace) and !check(.eof)) {
try declaration();
}
try consume(.right_brace, "Expect '}' after block.");
}
fn beginScope() ParseError!void {
current.scope_depth += 1;
}
fn endScope() ParseError!void {
current.scope_depth -= 1;
while (!current.locals.empty() and
current.locals.peek(0).depth > current.scope_depth)
{
if (current.locals.peek(0).is_captured) {
try emitOp(.close_upvalue);
} else {
try emitOp(.pop);
}
_ = current.locals.pop();
}
}
fn printStatement() ParseError!void {
try expression();
try consume(.semicolon, "Expect ';' after value.");
try emitOp(.print);
}
fn returnStatement() ParseError!void {
if (current.ty == .script) {
try errorAtPrevious("Can't return from top-level code.");
}
if (try match(.semicolon)) {
try emitOp(.nil);
try emitOp(.return_);
} else {
try expression();
try consume(.semicolon, "Expected ';' after return value.");
try emitOp(.return_);
}
}
fn ifStatement() ParseError!void {
try consume(.left_paren, "Expect '(' after 'if'.");
try expression();
try consume(.right_paren, "Expect '(' after 'if'.");
const thenJump = try emitJump(.jump_if_false);
try emitOp(.pop);
try statement();
const elseJump = try emitJump(.jump);
try patchJump(thenJump);
try emitOp(.pop);
if (try match(.else_)) try statement();
try patchJump(elseJump);
}
fn whileStatement() ParseError!void {
const loopStart = current.function.chunk.code.items.len;
try consume(.left_paren, "Expect '(' after 'while'.");
try expression();
try consume(.right_paren, "Expect '(' after 'while'.");
const exitJump = try emitJump(.jump_if_false);
try emitOp(.pop);
try statement();
try emitLoop(loopStart);
try patchJump(exitJump);
try emitOp(.pop);
}
fn forStatement() ParseError!void {
try beginScope();
try consume(.left_paren, "Expect '(' after 'for'");
// Initializer clause
if (try match(.semicolon)) {
// No initializer
} else if (try match(.var_)) {
try varDeclaration();
} else {
try expressionStatement();
}
var loopStart = current.function.chunk.code.items.len;
// Condition clause
var exitJump: ?usize = null;
if (!try match(.semicolon)) {
try expression();
try consume(.semicolon, "Expect ';' after loop condition.");
exitJump = try emitJump(.jump_if_false);
try emitOp(.pop);
}
// Increment clause
if (!try match(.right_paren)) {
const bodyJump = try emitJump(.jump);
const incrementStart = current.function.chunk.code.items.len;
try expression();
try emitOp(.pop);
try consume(.right_paren, "Expect ')' after 'for clauses'");
try emitLoop(loopStart);
loopStart = incrementStart;
try patchJump(bodyJump);
}
// User code
try statement();
try emitLoop(loopStart);
if (exitJump != null) {
try patchJump(exitJump.?);
try emitOp(.pop);
}
try endScope();
}
fn expressionStatement() ParseError!void {
try expression();
try consume(.semicolon, "Expect ';' after expression.");
try emitOp(.pop);
}
fn expression() ParseError!void {
try parsePrecedence(.assignment);
}
fn literal(can_assign: bool) ParseError!void {
switch (parser.previous.tag) {
.false_ => try emitOp(.false_),
.true_ => try emitOp(.true_),
.nil => try emitOp(.nil),
else => unreachable,
}
}
fn number(can_assign: bool) ParseError!void {
const num = try std.fmt.parseFloat(f64, parser.previous.span);
const val = Value{ .number = num };
try emitOpByte(.constant, try makeConstant(val));
}
fn string(can_assign: bool) ParseError!void {
const allocator = vm.getAllocator();
const len = parser.previous.span.len;
var obj = try vm.createString(parser.previous.span[1 .. len - 1]);
try emitOpByte(.constant, try makeConstant(Value{ .obj = obj }));
}
fn call() ParseError!void {
const arg_count = try argumentList();
try emitOpByte(.call, arg_count);
}
fn argumentList() ParseError!u8 {
var arg_count: u8 = 0;
if (!check(.right_paren)) {
while (true) {
try expression();
if (arg_count == 255) {
try errorAtPrevious("Can't have more than 255 arguments.");
}
arg_count += 1;
if (!try match(.comma)) break;
}
}
try consume(.right_paren, "Expect ')' after arguments");
return arg_count;
}
fn grouping(can_assign: bool) ParseError!void {
try expression();
try consume(.right_paren, "Expected ')' after expression.");
}
fn unary(can_assign: bool) ParseError!void {
const tag = parser.previous.tag;
try parsePrecedence(.unary);
switch (tag) {
.minus => try emitOp(.negate),
.bang => try emitOp(.not),
else => unreachable,
}
}
fn binary() ParseError!void {
const tag = parser.previous.tag;
const rule = getRule(tag);
try parsePrecedence(@intToEnum(Precedence, @enumToInt(rule.precedence) + 1));
switch (tag) {
.plus => try emitOp(.add),
.minus => try emitOp(.subtract),
.star => try emitOp(.multiply),
.slash => try emitOp(.divide),
.equal_equal => try emitOp(.equal),
.bang_equal => try emitOp(.not_equal),
.less => try emitOp(.less),
.less_equal => try emitOp(.less_equal),
.greater => try emitOp(.greater),
.greater_equal => try emitOp(.greater_equal),
else => unreachable,
}
}
fn and_() ParseError!void {
const endJump = try emitJump(.jump_if_false);
try emitOp(.pop);
try parsePrecedence(.and_);
try patchJump(endJump);
}
fn or_() ParseError!void {
const endJump = try emitJump(.jump_if_true);
try emitOp(.pop);
try parsePrecedence(.or_);
try patchJump(endJump);
}
fn variable(can_assign: bool) ParseError!void {
var get_op: OpCode = undefined;
var set_op: OpCode = undefined;
const name = &parser.previous;
var arg: u8 = undefined;
if (try resolveLocal(current, name)) |local| {
arg = local;
get_op = .get_local;
set_op = .set_local;
} else if (try resolveUpvalue(current, name)) |upvalue| {
arg = upvalue;
get_op = .get_upvalue;
set_op = .set_upvalue;
} else {
arg = try identifierConstant(&parser.previous);
get_op = .get_global;
set_op = .set_global;
}
if (can_assign and try match(.equal)) {
try expression();
try emitOpByte(set_op, arg);
} else {
try emitOpByte(get_op, arg);
}
}
fn endCompiler() !*Function {
try emitOp(.nil);
try emitOp(.return_);
const func = current.function;
func.upvalue_count = @intCast(i32, current.upvalues.top);
if (debug.print_code) {
const writer = std.io.getStdOut().writer();
if (!parser.hadError) {
try debug.disassembleChunk(writer, ¤t.function.chunk, if (func.name != null) func.name.?.chars else "<script>");
}
}
return func;
}
fn makeConstant(val: Value) !u8 {
const index = try current.function.chunk.addConstant(val);
if (index > std.math.maxInt(u8)) {
try errorAtPrevious("Too many constants for single chunk.");
return 0;
}
return @intCast(u8, index);
}
fn identifierConstant(name: *const scanner.Token) !u8 {
return try makeConstant(Value{ .obj = try vm.createString(name.span) });
}
fn resolveLocal(compiler: *Compiler, name: *Token) ParseError!?u8 {
var i: usize = 0;
while (i < compiler.locals.top) : (i += 1) {
const local = compiler.locals.peek(i);
if (identifiersEqual(name, &local.name)) {
if (local.depth == -1) {
try errorAtPrevious("Cannot read local variable in its own initializer.");
}
return @intCast(u8, compiler.locals.top - i - 1);
}
}
return null;
}
fn resolveUpvalue(compiler: *Compiler, name: *Token) ParseError!?u8 {
if (compiler.enclosing) |enclosing| {
if (try resolveLocal(enclosing, name)) |local| {
enclosing.locals.buffer[local].is_captured = true;
return try addUpvalue(compiler, local, true);
} else if (try resolveUpvalue(enclosing, name)) |upvalue| {
return try addUpvalue(compiler, upvalue, false);
}
}
return null;
}
fn addUpvalue(compiler: *Compiler, index: u8, is_local: bool) ParseError!u8 {
for (compiler.upvalues.slice()) |upvalue, i| {
if (upvalue.index == index and upvalue.is_local == is_local) {
return @intCast(u8, i);
}
}
if (compiler.upvalues.full()) {
try errorAtPrevious("Too many closure variables in function.");
return 0;
}
compiler.upvalues.push(Compiler.Upvalue{
.index = index,
.is_local = is_local,
});
return @intCast(u8, compiler.upvalues.top - 1);
}
fn advance() ParseError!void {
parser.previous = parser.current;
while (true) {
parser.current = scanner.nextToken();
if (parser.current.tag != .error_) break;
try errorAtCurrent(parser.current.span);
}
}
fn match(tag: scanner.TokenTag) ParseError!bool {
if (!check(tag)) return false;
try advance();
return true;
}
fn check(tag: scanner.TokenTag) bool {
return parser.current.tag == tag;
}
fn consume(expected: scanner.TokenTag, error_message: []const u8) !void {
if (parser.current.tag == expected) {
try advance();
return;
}
try errorAtCurrent(error_message);
}
fn emitOp(op: OpCode) !void {
try current.function.chunk.writeOp(op, parser.previous.line);
}
fn emitByte(byte: u8) !void {
try current.function.chunk.write(byte, parser.previous.line);
}
fn emitOpByte(op: OpCode, byte: u8) !void {
try current.function.chunk.writeOp(op, parser.previous.line);
try current.function.chunk.write(byte, parser.previous.line);
}
fn emitJump(jump: OpCode) !usize {
try emitOp(jump);
try emitByte(0xff);
try emitByte(0xff);
return current.function.chunk.code.items.len - 2;
}
fn emitLoop(start: usize) !void {
try emitOp(.loop);
const offset = current.function.chunk.code.items.len - start + 2;
if (offset > std.math.maxInt(u16)) try errorAtPrevious("Loop body too large.");
try emitByte(@intCast(u8, (offset >> 8) & 0xff));
try emitByte(@intCast(u8, offset & 0xff));
}
fn patchJump(offset: usize) !void {
// -2 to adjust for the bytecode for the jump offset itself.
const jump = current.function.chunk.code.items.len - offset - 2;
if (jump > std.math.maxInt(u16)) {
try errorAtPrevious("Too much code to jump over.");
}
current.function.chunk.code.items[offset] = @intCast(u8, (jump >> 8) & 0xff);
current.function.chunk.code.items[offset + 1] = @intCast(u8, jump & 0xff);
}
fn errorAtPrevious(message: []const u8) ParseError!void {
try errorAt(parser.previous, message);
}
fn errorAtCurrent(message: []const u8) ParseError!void {
try errorAt(parser.current, message);
}
fn errorAt(token: scanner.Token, message: []const u8) ParseError!void {
if (parser.panicMode) return;
parser.panicMode = true;
const stderr = std.io.getStdErr().writer();
try stderr.print("[line {}] Error ", .{token.line});
if (token.tag == .eof) {
try stderr.print("at end", .{});
} else if (token.tag == .error_) {
// nothing
} else {
try stderr.print("at '{}'", .{token.span});
}
try stderr.print(": {}\n", .{message});
parser.hadError = true;
}
fn synchronize() ParseError!void {
parser.panicMode = false;
while (parser.current.tag != .eof) {
if (parser.previous.tag == .semicolon) return;
switch (parser.current.tag) {
.class, .fun, .var_, .for_, .if_, .while_, .print, .return_ => return,
else => {},
}
try advance();
}
}
|
src/compiler.zig
|
const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("build_options");
const debug = std.debug;
const heap = std.heap;
const io = std.io;
const mem = std.mem;
const testing = std.testing;
pub const c = @cImport({
@cInclude("sqlite3.h");
});
pub const Text = @import("query.zig").Text;
pub const ParsedQuery = @import("query.zig").ParsedQuery;
const errors = @import("errors.zig");
pub const Error = errors.Error;
const logger = std.log.scoped(.sqlite);
/// ZeroBlob is a blob with a fixed length containing only zeroes.
///
/// A ZeroBlob is intended to serve as a placeholder; content can later be written with incremental i/o.
///
/// Here is an example allowing you to write up to 1024 bytes to a blob with incremental i/o.
///
/// try db.exec("INSERT INTO user VALUES(1, ?)", .{}, .{sqlite.ZeroBlob{ .length = 1024 }});
/// const row_id = db.getLastInsertRowID();
///
/// var blob = try db.openBlob(.main, "user", "data", row_id, .{ .write = true });
///
/// var blob_writer = blob.writer();
/// try blob_writer.writeAll("foobar");
///
/// try blob.close();
///
/// Search for "zeroblob" on https://sqlite.org/c3ref/blob_open.html for more details.
pub const ZeroBlob = struct {
length: usize,
};
/// Blob is a wrapper for a sqlite BLOB.
///
/// This type is useful when reading or binding data and for doing incremental i/o.
pub const Blob = struct {
const Self = @This();
pub const OpenFlags = struct {
read: bool = true,
write: bool = false,
};
pub const DatabaseName = union(enum) {
main,
temp,
attached: [:0]const u8,
fn toString(self: @This()) [:0]const u8 {
return switch (self) {
.main => "main",
.temp => "temp",
.attached => |name| name,
};
}
};
// Used when reading or binding data.
data: []const u8,
// Used for incremental i/o.
handle: *c.sqlite3_blob = undefined,
offset: c_int = 0,
size: c_int = 0,
/// close closes the blob.
pub fn close(self: *Self) Error!void {
const result = c.sqlite3_blob_close(self.handle);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
pub const Reader = io.Reader(*Self, errors.Error, read);
/// reader returns a io.Reader.
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
fn read(self: *Self, buffer: []u8) Error!usize {
if (self.offset >= self.size) {
return 0;
}
var tmp_buffer = blk: {
const remaining = @intCast(usize, self.size) - @intCast(usize, self.offset);
break :blk if (buffer.len > remaining) buffer[0..remaining] else buffer;
};
const result = c.sqlite3_blob_read(
self.handle,
tmp_buffer.ptr,
@intCast(c_int, tmp_buffer.len),
self.offset,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
self.offset += @intCast(c_int, tmp_buffer.len);
return tmp_buffer.len;
}
pub const Writer = io.Writer(*Self, Error, write);
/// writer returns a io.Writer.
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
fn write(self: *Self, data: []const u8) Error!usize {
const result = c.sqlite3_blob_write(
self.handle,
data.ptr,
@intCast(c_int, data.len),
self.offset,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
self.offset += @intCast(c_int, data.len);
return data.len;
}
/// Reset the offset used for reading and writing.
pub fn reset(self: *Self) void {
self.offset = 0;
}
pub const ReopenError = error{
CannotReopenBlob,
};
/// reopen moves this blob to another row of the same table.
///
/// See https://sqlite.org/c3ref/blob_reopen.html.
pub fn reopen(self: *Self, row: i64) ReopenError!void {
const result = c.sqlite3_blob_reopen(self.handle, row);
if (result != c.SQLITE_OK) {
return error.CannotReopenBlob;
}
self.size = c.sqlite3_blob_bytes(self.handle);
self.offset = 0;
}
pub const OpenError = error{
CannotOpenBlob,
};
/// open opens a blob for incremental i/o.
fn open(db: *c.sqlite3, db_name: DatabaseName, table: [:0]const u8, column: [:0]const u8, row: i64, comptime flags: OpenFlags) OpenError!Blob {
comptime if (!flags.read and !flags.write) {
@compileError("must open a blob for either read, write or both");
};
const open_flags: c_int = if (flags.write) 1 else 0;
var blob: Blob = undefined;
const result = c.sqlite3_blob_open(
db,
db_name.toString(),
table,
column,
row,
open_flags,
@ptrCast([*c]?*c.sqlite3_blob, &blob.handle),
);
if (result == c.SQLITE_MISUSE) debug.panic("sqlite misuse while opening a blob", .{});
if (result != c.SQLITE_OK) {
return error.CannotOpenBlob;
}
blob.size = c.sqlite3_blob_bytes(blob.handle);
blob.offset = 0;
return blob;
}
};
/// ThreadingMode controls the threading mode used by SQLite.
///
/// See https://sqlite.org/threadsafe.html
pub const ThreadingMode = enum {
/// SingleThread makes SQLite unsafe to use with more than a single thread at once.
SingleThread,
/// MultiThread makes SQLite safe to use with multiple threads at once provided that
/// a single database connection is not by more than a single thread at once.
MultiThread,
/// Serialized makes SQLite safe to use with multiple threads at once with no restriction.
Serialized,
};
/// Diagnostics can be used by the library to give more information in case of failures.
pub const Diagnostics = struct {
message: []const u8 = "",
err: ?DetailedError = null,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
if (self.err) |err| {
if (self.message.len > 0) {
_ = try writer.print("{{message: {s}, detailed error: {s}}}", .{ self.message, err });
return;
}
_ = try err.format(fmt, options, writer);
return;
}
if (self.message.len > 0) {
_ = try writer.write(self.message);
return;
}
_ = try writer.write("none");
}
};
pub const InitOptions = struct {
/// mode controls how the database is opened.
///
/// Defaults to a in-memory database.
mode: Db.Mode = .Memory,
/// open_flags controls the flags used when opening a database.
///
/// Defaults to a read only database.
open_flags: Db.OpenFlags = .{},
/// threading_mode controls the threading mode used by SQLite.
///
/// Defaults to Serialized.
threading_mode: ThreadingMode = .Serialized,
/// shared_cache controls whether or not concurrent SQLite
/// connections share the same cache.
///
/// Defaults to false.
shared_cache: bool = false,
/// if provided, diags will be populated in case of failures.
diags: ?*Diagnostics = null,
};
/// DetailedError contains a SQLite error code and error message.
pub const DetailedError = struct {
code: usize,
near: i32,
message: []const u8,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
_ = try writer.print("{{code: {}, near: {d}, message: {s}}}", .{ self.code, self.near, self.message });
}
};
fn isThreadSafe() bool {
return c.sqlite3_threadsafe() > 0;
}
fn getDetailedErrorFromResultCode(code: c_int) DetailedError {
return .{
.code = @intCast(usize, code),
.near = -1,
.message = blk: {
const msg = c.sqlite3_errstr(code);
break :blk mem.sliceTo(msg, 0);
},
};
}
fn getErrorOffset(db: *c.sqlite3) i32 {
if (comptime c.SQLITE_VERSION_NUMBER >= 3038000) {
return c.sqlite3_error_offset(db);
}
return -1;
}
fn getLastDetailedErrorFromDb(db: *c.sqlite3) DetailedError {
return .{
.code = @intCast(usize, c.sqlite3_extended_errcode(db)),
.near = getErrorOffset(db),
.message = blk: {
const msg = c.sqlite3_errmsg(db);
break :blk mem.sliceTo(msg, 0);
},
};
}
/// Db is a wrapper around a SQLite database, providing high-level functions for executing queries.
/// A Db can be opened with a file database or a in-memory database:
///
/// // File database
/// var db = try sqlite.Db.init(.{ .mode = .{ .File = "/tmp/data.db" } });
///
/// // In memory database
/// var db = try sqlite.Db.init(.{ .mode = .{ .Memory = {} } });
///
pub const Db = struct {
const Self = @This();
db: *c.sqlite3,
/// Mode determines how the database will be opened.
///
/// * File means opening the database at this path with sqlite3_open_v2.
/// * Memory means opening the database in memory.
/// This works by opening the :memory: path with sqlite3_open_v2 with the flag SQLITE_OPEN_MEMORY.
pub const Mode = union(enum) {
File: [:0]const u8,
Memory,
};
/// OpenFlags contains various flags used when opening a SQLite databse.
///
/// These flags partially map to the flags defined in https://sqlite.org/c3ref/open.html
/// * write=false and create=false means SQLITE_OPEN_READONLY
/// * write=true and create=false means SQLITE_OPEN_READWRITE
/// * write=true and create=true means SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE
pub const OpenFlags = struct {
write: bool = false,
create: bool = false,
};
pub const InitError = error{
SQLiteBuildNotThreadSafe,
} || Error;
/// init creates a database with the provided options.
pub fn init(options: InitOptions) InitError!Self {
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
// Validate the threading mode
if (options.threading_mode != .SingleThread and !isThreadSafe()) {
return error.SQLiteBuildNotThreadSafe;
}
// Compute the flags
var flags: c_int = c.SQLITE_OPEN_URI;
flags |= @as(c_int, if (options.open_flags.write) c.SQLITE_OPEN_READWRITE else c.SQLITE_OPEN_READONLY);
if (options.open_flags.create) {
flags |= c.SQLITE_OPEN_CREATE;
}
if (options.shared_cache) {
flags |= c.SQLITE_OPEN_SHAREDCACHE;
}
switch (options.threading_mode) {
.MultiThread => flags |= c.SQLITE_OPEN_NOMUTEX,
.Serialized => flags |= c.SQLITE_OPEN_FULLMUTEX,
else => {},
}
switch (options.mode) {
.File => |path| {
var db: ?*c.sqlite3 = undefined;
const result = c.sqlite3_open_v2(path, &db, flags, null);
if (result != c.SQLITE_OK or db == null) {
if (db) |v| {
diags.err = getLastDetailedErrorFromDb(v);
} else {
diags.err = getDetailedErrorFromResultCode(result);
}
return errors.errorFromResultCode(result);
}
return Self{ .db = db.? };
},
.Memory => {
flags |= c.SQLITE_OPEN_MEMORY;
var db: ?*c.sqlite3 = undefined;
const result = c.sqlite3_open_v2(":memory:", &db, flags, null);
if (result != c.SQLITE_OK or db == null) {
if (db) |v| {
diags.err = getLastDetailedErrorFromDb(v);
} else {
diags.err = getDetailedErrorFromResultCode(result);
}
return errors.errorFromResultCode(result);
}
return Self{ .db = db.? };
},
}
}
/// deinit closes the database.
pub fn deinit(self: *Self) void {
_ = c.sqlite3_close(self.db);
}
// getDetailedError returns the detailed error for the last API call if it failed.
pub fn getDetailedError(self: *Self) DetailedError {
return getLastDetailedErrorFromDb(self.db);
}
fn getPragmaQuery(comptime name: []const u8, comptime arg: ?[]const u8) []const u8 {
if (arg) |a| {
return std.fmt.comptimePrint("PRAGMA {s} = {s}", .{ name, a });
}
return std.fmt.comptimePrint("PRAGMA {s}", .{name});
}
/// getLastInsertRowID returns the last inserted rowid.
pub fn getLastInsertRowID(self: *Self) i64 {
const rowid = c.sqlite3_last_insert_rowid(self.db);
return rowid;
}
/// pragmaAlloc is like `pragma` but can allocate memory.
///
/// Useful when the pragma command returns text, for example:
///
/// const journal_mode = try db.pragma([]const u8, allocator, .{}, "journal_mode", null);
///
pub fn pragmaAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, comptime name: []const u8, comptime arg: ?[]const u8) !?Type {
comptime var query = getPragmaQuery(name, arg);
var stmt = try self.prepare(query);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, .{});
}
/// pragma is a convenience function to use the PRAGMA statement.
///
/// Here is how to set a pragma value:
///
/// _ = try db.pragma(void, .{}, "foreign_keys", "1");
///
/// Here is how to query a pragma value:
///
/// const journal_mode = try db.pragma([128:0]const u8, .{}, "journal_mode", null);
///
/// The pragma name must be known at comptime.
///
/// This cannot allocate memory. If your pragma command returns text you must use an array or call `pragmaAlloc`.
pub fn pragma(self: *Self, comptime Type: type, options: QueryOptions, comptime name: []const u8, comptime arg: ?[]const u8) !?Type {
comptime var query = getPragmaQuery(name, arg);
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, .{});
}
/// exec is a convenience function which prepares a statement and executes it directly.
pub fn exec(self: *Self, comptime query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
try stmt.exec(options, values);
}
/// execDynamic is a convenience function which prepares a statement and executes it directly.
pub fn execDynamic(self: *Self, query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
try stmt.exec(options, values);
}
/// execAlloc is like `exec` but can allocate memory.
pub fn execAlloc(self: *Self, allocator: mem.Allocator, comptime query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
try stmt.execAlloc(allocator, options, values);
}
/// one is a convenience function which prepares a statement and reads a single row from the result set.
pub fn one(self: *Self, comptime Type: type, comptime query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, values);
}
/// oneDynamic is a convenience function which prepares a statement and reads a single row from the result set.
pub fn oneDynamic(self: *Self, comptime Type: type, query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, values);
}
/// oneAlloc is like `one` but can allocate memory.
pub fn oneAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, comptime query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, values);
}
/// oneDynamicAlloc is like `oneDynamic` but can allocate memory.
pub fn oneDynamicAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, values);
}
/// prepareWithDiags is like `prepare` but takes an additional options argument.
pub fn prepareWithDiags(self: *Self, comptime query: []const u8, options: QueryOptions) DynamicStatement.PrepareError!blk: {
@setEvalBranchQuota(100000);
break :blk StatementType(.{}, query);
} {
@setEvalBranchQuota(100000);
return StatementType(.{}, query).prepare(self, options, 0);
}
/// prepareDynamicWithDiags is like `prepareDynamic` but takes an additional options argument.
pub fn prepareDynamicWithDiags(self: *Self, query: []const u8, options: QueryOptions) DynamicStatement.PrepareError!DynamicStatement {
return try DynamicStatement.prepare(self, query, options, 0);
}
/// prepare prepares a statement for the `query` provided.
///
/// The query is analysed at comptime to search for bind markers.
/// prepare enforces having as much fields in the `values` tuple as there are bind markers.
///
/// Example usage:
///
/// var stmt = try db.prepare("INSERT INTO foo(id, name) VALUES(?, ?)");
/// defer stmt.deinit();
///
/// The statement returned is only compatible with the number of bind markers in the input query.
/// This is done because we type check the bind parameters when executing the statement later.
///
/// If you want additional error information in case of failures, use `prepareWithDiags`.
pub fn prepare(self: *Self, comptime query: []const u8) DynamicStatement.PrepareError!blk: {
@setEvalBranchQuota(100000);
break :blk StatementType(.{}, query);
} {
@setEvalBranchQuota(100000);
return StatementType(.{}, query).prepare(self, .{}, 0);
}
/// prepareDynamic prepares a dynamic statement for the `query` provided.
///
/// The query will be directly sent to create statement without analysing.
/// That means such statements does not support comptime type-checking.
///
/// Dynamic statement supports host parameter names. See `DynamicStatement`.
pub fn prepareDynamic(self: *Self, query: []const u8) DynamicStatement.PrepareError!DynamicStatement {
return try self.prepareDynamicWithDiags(query, .{});
}
/// rowsAffected returns the number of rows affected by the last statement executed.
pub fn rowsAffected(self: *Self) usize {
return @intCast(usize, c.sqlite3_changes(self.db));
}
/// openBlob opens a blob for incremental i/o.
///
/// Incremental i/o enables writing and reading data using a std.io.Writer and std.io.Reader:
/// * the writer type wraps sqlite3_blob_write, see https://sqlite.org/c3ref/blob_write.html
/// * the reader type wraps sqlite3_blob_read, see https://sqlite.org/c3ref/blob_read.html
///
/// Note that:
/// * the blob must exist before writing; you must use INSERT to create one first (either with data or using a placeholder with ZeroBlob).
/// * the blob is not extensible, if you want to change the blob size you must use an UPDATE statement.
///
/// You can get a std.io.Writer to write data to the blob:
///
/// var blob = try db.openBlob(.main, "mytable", "mycolumn", 1, .{ .write = true });
/// var blob_writer = blob.writer();
///
/// try blob_writer.writeAll(my_data);
///
/// You can get a std.io.Reader to read the blob data:
///
/// var blob = try db.openBlob(.main, "mytable", "mycolumn", 1, .{});
/// var blob_reader = blob.reader();
///
/// const data = try blob_reader.readAlloc(allocator);
///
/// See https://sqlite.org/c3ref/blob_open.html for more details on incremental i/o.
///
pub fn openBlob(self: *Self, db_name: Blob.DatabaseName, table: [:0]const u8, column: [:0]const u8, row: i64, comptime flags: Blob.OpenFlags) Blob.OpenError!Blob {
return Blob.open(self.db, db_name, table, column, row, flags);
}
/// savepoint starts a new named transaction.
///
/// The returned type is a helper useful for managing commits and rollbacks, for example:
///
/// var savepoint = try db.savepoint("foobar");
/// defer savepoint.rollback();
///
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 1, "foo" });
///
/// savepoint.commit();
///
pub fn savepoint(self: *Self, name: []const u8) Savepoint.InitError!Savepoint {
return Savepoint.init(self, name);
}
// Helpers functions to implement SQLite functions.
fn sliceFromValue(sqlite_value: *c.sqlite3_value) []const u8 {
const size = @intCast(usize, c.sqlite3_value_bytes(sqlite_value));
const value = c.sqlite3_value_text(sqlite_value);
debug.assert(value != null); // TODO(vincent): how do we handle this properly ?
return value.?[0..size];
}
/// Sets the result of a function call in the context `ctx`.
///
/// Determines at compile time which sqlite3_result_XYZ function to use based on the type of `result`.
fn setFunctionResult(ctx: ?*c.sqlite3_context, result: anytype) void {
const ResultType = @TypeOf(result);
switch (ResultType) {
Text => c.sqlite3_result_text(ctx, result.data.ptr, @intCast(c_int, result.data.len), c.SQLITE_TRANSIENT),
Blob => c.sqlite3_result_blob(ctx, result.data.ptr, @intCast(c_int, result.data.len), c.SQLITE_TRANSIENT),
else => switch (@typeInfo(ResultType)) {
.Int => |info| if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 32) {
c.sqlite3_result_int(ctx, result);
} else if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 64) {
c.sqlite3_result_int64(ctx, result);
} else {
@compileError("integer " ++ @typeName(ResultType) ++ " is not representable in sqlite");
},
.Float => c.sqlite3_result_double(ctx, result),
.Bool => c.sqlite3_result_int(ctx, if (result) 1 else 0),
.Array => |arr| switch (arr.child) {
u8 => c.sqlite3_result_blob(ctx, &result, arr.len, c.SQLITE_TRANSIENT),
else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
},
.Pointer => |ptr| switch (ptr.size) {
.Slice => switch (ptr.child) {
u8 => c.sqlite3_result_text(ctx, result.ptr, @intCast(c_int, result.len), c.SQLITE_TRANSIENT),
else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
},
else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
},
else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
},
}
}
/// Sets a function argument using the provided value.
///
/// Determines at compile time which sqlite3_value_XYZ function to use based on the type `ArgType`.
fn setFunctionArgument(comptime ArgType: type, arg: *ArgType, sqlite_value: *c.sqlite3_value) void {
switch (ArgType) {
Text => arg.*.data = sliceFromValue(sqlite_value),
Blob => arg.*.data = sliceFromValue(sqlite_value),
else => switch (@typeInfo(ArgType)) {
.Int => |info| if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 32) {
const value = c.sqlite3_value_int(sqlite_value);
arg.* = @intCast(ArgType, value);
} else if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 64) {
const value = c.sqlite3_value_int64(sqlite_value);
arg.* = @intCast(ArgType, value);
} else {
@compileError("integer " ++ @typeName(ArgType) ++ " is not representable in sqlite");
},
.Float => {
const value = c.sqlite3_value_double(sqlite_value);
arg.* = @floatCast(ArgType, value);
},
.Bool => {
const value = c.sqlite3_value_int(sqlite_value);
arg.* = value > 0;
},
.Pointer => |ptr| switch (ptr.size) {
.Slice => switch (ptr.child) {
u8 => arg.* = sliceFromValue(sqlite_value),
else => @compileError("cannot use an argument of type " ++ @typeName(ArgType)),
},
else => @compileError("cannot use an argument of type " ++ @typeName(ArgType)),
},
else => @compileError("cannot use an argument of type " ++ @typeName(ArgType)),
},
}
}
/// CreateFunctionFlag controls the flags used when creating a custom SQL function.
/// See https://sqlite.org/c3ref/c_deterministic.html.
///
/// The flags SQLITE_UTF16LE, SQLITE_UTF16BE are not supported yet. SQLITE_UTF8 is the default and always on.
///
/// TODO(vincent): allow these flags when we know how to handle UTF16 data.
pub const CreateFunctionFlag = struct {
/// Equivalent to SQLITE_DETERMINISTIC
deterministic: bool = true,
/// Equivalent to SQLITE_DIRECTONLY
direct_only: bool = true,
fn toCFlags(self: *const CreateFunctionFlag) c_int {
var flags: c_int = c.SQLITE_UTF8;
if (self.deterministic) {
flags |= c.SQLITE_DETERMINISTIC;
}
if (self.direct_only) {
flags |= c.SQLITE_DIRECTONLY;
}
return flags;
}
};
/// Creates an aggregate SQLite function with the given name.
///
/// When the SQLite function is called in a statement, `step_func` will be called for each row with the input arguments.
/// Each SQLite argument is converted to a Zig value according to the following rules:
/// * TEXT values can be either sqlite.Text or []const u8
/// * BLOB values can be either sqlite.Blob or []const u8
/// * INTEGER values can be any Zig integer
/// * REAL values can be any Zig float
///
/// The final result of the SQL function call will be what `finalize_func` returns.
///
/// The context `my_ctx` contains the state necessary to perform the aggregation, both `step_func` and `finalize_func` must have at least the first argument of type ContextType.
///
pub fn createAggregateFunction(self: *Self, func_name: [:0]const u8, my_ctx: anytype, comptime step_func: anytype, comptime finalize_func: anytype, comptime create_flags: CreateFunctionFlag) Error!void {
// Check that the context type is usable
const ContextPtrType = @TypeOf(my_ctx);
const ContextType = switch (@typeInfo(ContextPtrType)) {
.Pointer => |ptr_info| switch (ptr_info.size) {
.One => ptr_info.child,
else => @compileError("cannot use context of type " ++ @typeName(ContextPtrType) ++ ", must be a single-item pointer"),
},
else => @compileError("cannot use context of type " ++ @typeName(ContextPtrType) ++ ", must be a single-item pointer"),
};
// Validate the step function
const StepFuncType = @TypeOf(step_func);
const step_fn_info = switch (@typeInfo(StepFuncType)) {
.Fn => |fn_info| fn_info,
else => @compileError("cannot use step_fn, expecting a function"),
};
if (step_fn_info.is_generic) @compileError("step_fn function can't be generic");
if (step_fn_info.is_var_args) @compileError("step_fn function can't be variadic");
const StepFuncArgTuple = std.meta.ArgsTuple(StepFuncType);
// subtract one because the user-provided function always takes an additional context
const step_func_args_len = step_fn_info.args.len - 1;
// Validate the finalize function
const FinalizeFuncType = @TypeOf(finalize_func);
const finalize_fn_info = switch (@typeInfo(FinalizeFuncType)) {
.Fn => |fn_info| fn_info,
else => @compileError("cannot use finalize_fn, expecting a function"),
};
if (finalize_fn_info.args.len != 1) @compileError("finalize_fn must take exactly one argument");
const FinalizeFuncArgTuple = std.meta.ArgsTuple(FinalizeFuncType);
//
const flags = create_flags.toCFlags();
const result = c.sqlite3_create_function_v2(
self.db,
func_name,
step_func_args_len,
flags,
my_ctx,
null, // xFunc
struct {
fn xStep(ctx: ?*c.sqlite3_context, argc: c_int, argv: [*c]?*c.sqlite3_value) callconv(.C) void {
debug.assert(argc == step_func_args_len);
const sqlite_args = argv.?[0..step_func_args_len];
var fn_args: StepFuncArgTuple = undefined;
// First argument is always the user-provided context
fn_args[0] = @ptrCast(ContextPtrType, @alignCast(@alignOf(ContextType), c.sqlite3_user_data(ctx)));
comptime var i: usize = 0;
inline while (i < step_func_args_len) : (i += 1) {
// we add 1 because we need to ignore the first argument which is the user-provided context, not a SQLite value.
const arg = step_fn_info.args[i + 1];
const arg_ptr = &fn_args[i + 1];
const ArgType = arg.arg_type.?;
setFunctionArgument(ArgType, arg_ptr, sqlite_args[i].?);
}
@call(.{}, step_func, fn_args);
}
}.xStep,
struct {
fn xFinal(ctx: ?*c.sqlite3_context) callconv(.C) void {
var fn_args: FinalizeFuncArgTuple = undefined;
// Only one argument, the user-provided context
fn_args[0] = @ptrCast(ContextPtrType, @alignCast(@alignOf(ContextType), c.sqlite3_user_data(ctx)));
const result = @call(.{}, finalize_func, fn_args);
setFunctionResult(ctx, result);
}
}.xFinal,
null,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
/// Creates a scalar SQLite function with the given name.
///
/// When the SQLite function is called in a statement, `func` will be called with the input arguments.
/// Each SQLite argument is converted to a Zig value according to the following rules:
/// * TEXT values can be either sqlite.Text or []const u8
/// * BLOB values can be either sqlite.Blob or []const u8
/// * INTEGER values can be any Zig integer
/// * REAL values can be any Zig float
///
/// The return type of the function is converted to a SQLite value according to the same rules but reversed.
///
pub fn createScalarFunction(self: *Self, func_name: [:0]const u8, comptime func: anytype, comptime create_flags: CreateFunctionFlag) Error!void {
const Type = @TypeOf(func);
const fn_info = switch (@typeInfo(Type)) {
.Fn => |fn_info| fn_info,
else => @compileError("expecting a function"),
};
if (fn_info.is_generic) @compileError("function can't be generic");
if (fn_info.is_var_args) @compileError("function can't be variadic");
const ArgTuple = std.meta.ArgsTuple(Type);
//
const flags = create_flags.toCFlags();
const result = c.sqlite3_create_function_v2(
self.db,
func_name,
fn_info.args.len,
flags,
null,
struct {
fn xFunc(ctx: ?*c.sqlite3_context, argc: c_int, argv: [*c]?*c.sqlite3_value) callconv(.C) void {
debug.assert(argc == fn_info.args.len);
const sqlite_args = argv.?[0..fn_info.args.len];
var fn_args: ArgTuple = undefined;
inline for (fn_info.args) |arg, i| {
const ArgType = arg.arg_type.?;
setFunctionArgument(ArgType, &fn_args[i], sqlite_args[i].?);
}
const result = @call(.{}, func, fn_args);
setFunctionResult(ctx, result);
}
}.xFunc,
null,
null,
null,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
/// This is a convenience function to run statements that do not need
/// bindings to values, but have multiple commands inside.
///
/// Exmaple: 'create table a(); create table b();'
pub fn execMulti(self: *Self, comptime query: []const u8, options: QueryOptions) !void {
var new_options = options;
var sql_tail_ptr: ?[*:0]const u8 = null;
new_options.sql_tail_ptr = &sql_tail_ptr;
while (true) {
// continuously prepare and execute (dynamically as there's no
// values to bind in this case)
var stmt: DynamicStatement = undefined;
if (sql_tail_ptr != null) {
const new_query = std.mem.span(sql_tail_ptr.?);
if (new_query.len == 0) break;
stmt = try self.prepareDynamicWithDiags(new_query, new_options);
} else {
stmt = try self.prepareDynamicWithDiags(query, new_options);
}
defer stmt.deinit();
try stmt.exec(new_options, .{});
}
}
};
/// Savepoint is a helper type for managing savepoints.
///
/// A savepoint creates a transaction like BEGIN/COMMIT but they're named and can be nested.
/// See https://sqlite.org/lang_savepoint.html.
///
/// You can create a savepoint like this:
///
/// var savepoint = try db.savepoint("foobar");
/// defer savepoint.rollback();
///
/// ...
///
/// Savepoint.commit();
///
/// This is equivalent to BEGIN/COMMIT/ROLLBACK.
///
/// Savepoints are more useful for _nesting_ transactions, for example:
///
/// var savepoint = try db.savepoint("outer");
/// defer savepoint.rollback();
///
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 1, "foo" });
///
/// {
/// var savepoint2 = try db.savepoint("inner");
/// defer savepoint2.rollback();
///
/// var i: usize = 0;
/// while (i < 30) : (i += 1) {
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 2, "bar" });
/// }
///
/// savepoint2.commit();
/// }
///
/// try db.exec("UPDATE bar SET processed = ? WHERE id = ?", .{ true, 20 });
///
/// savepoint.commit();
///
/// In this example if any query in the inner transaction fail, all previously executed queries are discarded but the outer transaction is untouched.
///
pub const Savepoint = struct {
const Self = @This();
db: *Db,
committed: bool,
commit_stmt: DynamicStatement,
rollback_stmt: DynamicStatement,
pub const InitError = error{
SavepointNameTooShort,
SavepointNameTooLong,
SavepointNameInvalid,
// From execDynamic
ExecReturnedData,
} || std.fmt.AllocPrintError || Error;
fn init(db: *Db, name: []const u8) InitError!Self {
if (name.len < 1) return error.SavepointNameTooShort;
if (name.len > 20) return error.SavepointNameTooLong;
if (!std.ascii.isAlpha(name[0])) return error.SavepointNameInvalid;
for (name) |b| {
if (b != '_' and !std.ascii.isAlNum(b)) {
return error.SavepointNameInvalid;
}
}
var buffer: [256]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
var allocator = fba.allocator();
const commit_query = try std.fmt.allocPrint(allocator, "RELEASE SAVEPOINT {s}", .{name});
const rollback_query = try std.fmt.allocPrint(allocator, "ROLLBACK TRANSACTION TO SAVEPOINT {s}", .{name});
var res = Self{
.db = db,
.committed = false,
.commit_stmt = try db.prepareDynamic(commit_query),
.rollback_stmt = try db.prepareDynamic(rollback_query),
};
try res.db.execDynamic(
try std.fmt.allocPrint(allocator, "SAVEPOINT {s}", .{name}),
.{},
.{},
);
return res;
}
pub fn commit(self: *Self) void {
self.commit_stmt.exec(.{}, .{}) catch |err| {
const detailed_error = self.db.getDetailedError();
logger.err("unable to release savepoint, error: {}, message: {s}", .{ err, detailed_error });
};
self.committed = true;
}
pub fn rollback(self: *Self) void {
defer {
self.commit_stmt.deinit();
self.rollback_stmt.deinit();
}
if (self.committed) return;
self.rollback_stmt.exec(.{}, .{}) catch |err| {
const detailed_error = self.db.getDetailedError();
std.debug.panic("unable to rollback transaction, error: {}, message: {s}\n", .{ err, detailed_error });
};
}
};
pub const QueryOptions = struct {
/// if provided, diags will be populated in case of failures.
diags: ?*Diagnostics = null,
/// if provided, sql_tail_ptr will point to the last uncompiled statement
/// in the prepare() call. this is useful for multiple-statements being
/// processed.
sql_tail_ptr: ?*?[*:0]const u8 = null,
};
/// Iterator allows iterating over a result set.
///
/// Each call to `next` returns the next row of the result set, or null if the result set is exhausted.
/// Each row will have the type `Type` so the columns returned in the result set must be compatible with this type.
///
/// Here is an example of how to use the iterator:
///
/// const User = struct {
/// name: Text,
/// age: u16,
/// };
///
/// var stmt = try db.prepare("SELECT name, age FROM user");
/// defer stmt.deinit();
///
/// var iter = try stmt.iterator(User, .{});
/// while (try iter.next(.{})) |row| {
/// ...
/// }
///
/// The iterator _must not_ outlive the statement.
pub fn Iterator(comptime Type: type) type {
return struct {
const Self = @This();
const TypeInfo = @typeInfo(Type);
db: *c.sqlite3,
stmt: *c.sqlite3_stmt,
// next scans the next row using the prepared statement.
// If it returns null iterating is done.
//
// This cannot allocate memory. If you need to read TEXT or BLOB columns you need to use arrays or alternatively call nextAlloc.
pub fn next(self: *Self, options: QueryOptions) !?Type {
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
var result = c.sqlite3_step(self.stmt);
if (result == c.SQLITE_DONE) {
return null;
}
if (result != c.SQLITE_ROW) {
diags.err = getLastDetailedErrorFromDb(self.db);
return errors.errorFromResultCode(result);
}
const columns = c.sqlite3_column_count(self.stmt);
switch (TypeInfo) {
.Int => {
debug.assert(columns == 1);
return try self.readInt(Type, 0);
},
.Float => {
debug.assert(columns == 1);
return try self.readFloat(Type, 0);
},
.Bool => {
debug.assert(columns == 1);
return try self.readBool(0);
},
.Void => {
debug.assert(columns == 1);
},
.Array => {
debug.assert(columns == 1);
return try self.readArray(Type, 0);
},
.Enum => |TI| {
debug.assert(columns == 1);
if (comptime std.meta.trait.isZigString(Type.BaseType)) {
@compileError("cannot read into type " ++ @typeName(Type) ++ " ; BaseType " ++ @typeName(Type.BaseType) ++ " requires allocation, use nextAlloc or oneAlloc");
}
if (@typeInfo(Type.BaseType) == .Int) {
const inner_value = try self.readField(Type.BaseType, options, 0);
return @intToEnum(Type, @intCast(TI.tag_type, inner_value));
}
@compileError("enum column " ++ @typeName(Type) ++ " must have a BaseType of either string or int");
},
.Struct => {
std.debug.assert(columns == TypeInfo.Struct.fields.len);
return try self.readStruct(options);
},
else => @compileError("cannot read into type " ++ @typeName(Type) ++ " ; if dynamic memory allocation is required use nextAlloc or oneAlloc"),
}
}
// nextAlloc is like `next` but can allocate memory.
pub fn nextAlloc(self: *Self, allocator: mem.Allocator, options: QueryOptions) !?Type {
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
var result = c.sqlite3_step(self.stmt);
if (result == c.SQLITE_DONE) {
return null;
}
if (result != c.SQLITE_ROW) {
diags.err = getLastDetailedErrorFromDb(self.db);
return errors.errorFromResultCode(result);
}
const columns = c.sqlite3_column_count(self.stmt);
switch (Type) {
[]const u8, []u8 => {
debug.assert(columns == 1);
return try self.readBytes(Type, allocator, 0, .Text);
},
Blob => {
debug.assert(columns == 1);
return try self.readBytes(Blob, allocator, 0, .Blob);
},
Text => {
debug.assert(columns == 1);
return try self.readBytes(Text, allocator, 0, .Text);
},
else => {},
}
switch (TypeInfo) {
.Int => {
debug.assert(columns == 1);
return try self.readInt(Type, 0);
},
.Float => {
debug.assert(columns == 1);
return try self.readFloat(Type, 0);
},
.Bool => {
debug.assert(columns == 1);
return try self.readBool(0);
},
.Void => {
debug.assert(columns == 1);
},
.Array => {
debug.assert(columns == 1);
return try self.readArray(Type, 0);
},
.Pointer => {
debug.assert(columns == 1);
return try self.readPointer(Type, .{
.allocator = allocator,
}, 0);
},
.Enum => |TI| {
debug.assert(columns == 1);
const inner_value = try self.readField(Type.BaseType, .{ .allocator = allocator }, 0);
if (comptime std.meta.trait.isZigString(Type.BaseType)) {
// The inner value is never returned to the user, we must free it ourselves.
defer allocator.free(inner_value);
// TODO(vincent): don't use unreachable
return std.meta.stringToEnum(Type, inner_value) orelse unreachable;
}
if (@typeInfo(Type.BaseType) == .Int) {
return @intToEnum(Type, @intCast(TI.tag_type, inner_value));
}
@compileError("enum column " ++ @typeName(Type) ++ " must have a BaseType of either string or int");
},
.Struct => {
std.debug.assert(columns == TypeInfo.Struct.fields.len);
return try self.readStruct(.{
.allocator = allocator,
});
},
else => @compileError("cannot read into type " ++ @typeName(Type)),
}
}
// readArray reads a sqlite BLOB or TEXT column into an array of u8.
//
// We also require the array to be the exact size of the data, or have a sentinel;
// otherwise we have no way of communicating the end of the data to the caller.
//
// If the array is too small for the data an error will be returned.
fn readArray(self: *Self, comptime ArrayType: type, _i: usize) !ArrayType {
const i = @intCast(c_int, _i);
const type_info = @typeInfo(ArrayType);
var ret: ArrayType = undefined;
switch (type_info) {
.Array => |arr| {
switch (arr.child) {
u8 => {
const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i));
if (arr.sentinel) |sentinel_ptr| {
// An array with a sentinel need to be as big as the data, + 1 byte for the sentinel.
if (size >= @as(usize, arr.len)) {
return error.ArrayTooSmall;
}
// Set the sentinel in the result at the correct position.
const sentinel = @ptrCast(*const arr.child, sentinel_ptr).*;
ret[size] = sentinel;
} else if (size != arr.len) {
// An array without a sentinel must have the exact same size as the data because we can't
// communicate the real size to the caller.
return error.ArraySizeMismatch;
}
const data = c.sqlite3_column_blob(self.stmt, i);
if (data != null) {
const ptr = @ptrCast([*c]const u8, data)[0..size];
mem.copy(u8, ret[0..], ptr);
}
},
else => @compileError("cannot read into array of " ++ @typeName(arr.child)),
}
},
else => @compileError("cannot read into type " ++ @typeName(ret)),
}
return ret;
}
// readInt reads a sqlite INTEGER column into an integer.
fn readInt(self: *Self, comptime IntType: type, i: usize) error{Workaround}!IntType { // TODO remove the workaround once https://github.com/ziglang/zig/issues/5149 is resolved or if we actually return an error
const n = c.sqlite3_column_int64(self.stmt, @intCast(c_int, i));
return @intCast(IntType, n);
}
// readFloat reads a sqlite REAL column into a float.
fn readFloat(self: *Self, comptime FloatType: type, i: usize) error{Workaround}!FloatType { // TODO remove the workaround once https://github.com/ziglang/zig/issues/5149 is resolved or if we actually return an error
const d = c.sqlite3_column_double(self.stmt, @intCast(c_int, i));
return @floatCast(FloatType, d);
}
// readFloat reads a sqlite INTEGER column into a bool (true is anything > 0, false is anything <= 0).
fn readBool(self: *Self, i: usize) error{Workaround}!bool { // TODO remove the workaround once https://github.com/ziglang/zig/issues/5149 is resolved or if we actually return an error
const d = c.sqlite3_column_int64(self.stmt, @intCast(c_int, i));
return d > 0;
}
const ReadBytesMode = enum {
Blob,
Text,
};
// dupeWithSentinel is like dupe/dupeZ but allows for any sentinel value.
fn dupeWithSentinel(comptime SliceType: type, allocator: mem.Allocator, data: []const u8) !SliceType {
switch (@typeInfo(SliceType)) {
.Pointer => |ptr_info| {
if (ptr_info.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const ptr_info.child, sentinel_ptr).*;
const slice = try allocator.alloc(u8, data.len + 1);
mem.copy(u8, slice, data);
slice[data.len] = sentinel;
return slice[0..data.len :sentinel];
} else {
return try allocator.dupe(u8, data);
}
},
else => @compileError("cannot dupe type " ++ @typeName(SliceType)),
}
}
// readBytes reads a sqlite BLOB or TEXT column.
//
// The mode controls which sqlite function is used to retrieve the data:
// * .Blob uses sqlite3_column_blob
// * .Text uses sqlite3_column_text
//
// When using .Blob you can only read into either []const u8, []u8 or Blob.
// When using .Text you can only read into either []const u8, []u8 or Text.
//
// The options must contain an `allocator` field which will be used to create a copy of the data.
fn readBytes(self: *Self, comptime BytesType: type, allocator: mem.Allocator, _i: usize, comptime mode: ReadBytesMode) !BytesType {
const i = @intCast(c_int, _i);
switch (mode) {
.Blob => {
const data = c.sqlite3_column_blob(self.stmt, i);
if (data == null) {
return switch (BytesType) {
Text, Blob => .{ .data = try allocator.dupe(u8, "") },
else => try dupeWithSentinel(BytesType, allocator, ""),
};
}
const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i));
const ptr = @ptrCast([*c]const u8, data)[0..size];
if (BytesType == Blob) {
return Blob{ .data = try allocator.dupe(u8, ptr) };
}
return try dupeWithSentinel(BytesType, allocator, ptr);
},
.Text => {
const data = c.sqlite3_column_text(self.stmt, i);
if (data == null) {
return switch (BytesType) {
Text, Blob => .{ .data = try allocator.dupe(u8, "") },
else => try dupeWithSentinel(BytesType, allocator, ""),
};
}
const size = @intCast(usize, c.sqlite3_column_bytes(self.stmt, i));
const ptr = @ptrCast([*c]const u8, data)[0..size];
if (BytesType == Text) {
return Text{ .data = try allocator.dupe(u8, ptr) };
}
return try dupeWithSentinel(BytesType, allocator, ptr);
},
}
}
fn readPointer(self: *Self, comptime PointerType: type, options: anytype, i: usize) !PointerType {
if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) {
@compileError("options passed to readPointer must be a struct");
}
if (!comptime std.meta.trait.hasField("allocator")(@TypeOf(options))) {
@compileError("options passed to readPointer must have an allocator field");
}
var ret: PointerType = undefined;
switch (@typeInfo(PointerType)) {
.Pointer => |ptr| {
switch (ptr.size) {
.One => {
ret = try options.allocator.create(ptr.child);
errdefer options.allocator.destroy(ret);
ret.* = try self.readField(ptr.child, options, i);
},
.Slice => switch (ptr.child) {
u8 => ret = try self.readBytes(PointerType, options.allocator, i, .Text),
else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)),
},
else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)),
}
},
else => @compileError("cannot read pointer of type " ++ @typeName(PointerType)),
}
return ret;
}
fn readOptional(self: *Self, comptime OptionalType: type, options: anytype, _i: usize) !OptionalType {
if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) {
@compileError("options passed to readOptional must be a struct");
}
var ret: OptionalType = undefined;
switch (@typeInfo(OptionalType)) {
.Optional => |opt| {
// Easy way to know if the column represents a null value.
const value = c.sqlite3_column_value(self.stmt, @intCast(c_int, _i));
const datatype = c.sqlite3_value_type(value);
if (datatype == c.SQLITE_NULL) {
return null;
} else {
const val = try self.readField(opt.child, options, _i);
ret = val;
return ret;
}
},
else => @compileError("cannot read optional of type " ++ @typeName(OptionalType)),
}
}
// readStruct reads an entire sqlite row into a struct.
//
// Each field correspond to a column; its position in the struct determines the column used for it.
// For example, given the following query:
//
// SELECT id, name, age FROM user
//
// The struct must have the following fields:
//
// struct {
// id: usize,
// name: []const u8,
// age: u16,
// }
//
// The field `id` will be associated with the column `id` and so on.
//
// This function relies on the fact that there are the same number of fields than columns and
// that the order is correct.
//
// TODO(vincent): add comptime checks for the fields/columns.
fn readStruct(self: *Self, options: anytype) !Type {
if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) {
@compileError("options passed to readStruct must be a struct");
}
var value: Type = undefined;
inline for (@typeInfo(Type).Struct.fields) |field, _i| {
const i = @as(usize, _i);
const ret = try self.readField(field.field_type, options, i);
@field(value, field.name) = ret;
}
return value;
}
fn readField(self: *Self, comptime FieldType: type, options: anytype, i: usize) !FieldType {
if (!comptime std.meta.trait.is(.Struct)(@TypeOf(options))) {
@compileError("options passed to readField must be a struct");
}
const field_type_info = @typeInfo(FieldType);
return switch (FieldType) {
Blob => blk: {
if (!comptime std.meta.trait.hasField("allocator")(@TypeOf(options))) {
@compileError("options passed to readPointer must have an allocator field when reading a Blob");
}
break :blk try self.readBytes(Blob, options.allocator, i, .Blob);
},
Text => blk: {
if (!comptime std.meta.trait.hasField("allocator")(@TypeOf(options))) {
@compileError("options passed to readField must have an allocator field when reading a Text");
}
break :blk try self.readBytes(Text, options.allocator, i, .Text);
},
else => switch (field_type_info) {
.Int => try self.readInt(FieldType, i),
.Float => try self.readFloat(FieldType, i),
.Bool => try self.readBool(i),
.Void => {},
.Array => try self.readArray(FieldType, i),
.Pointer => try self.readPointer(FieldType, options, i),
.Optional => try self.readOptional(FieldType, options, i),
.Enum => |TI| {
const inner_value = try self.readField(FieldType.BaseType, options, i);
if (comptime std.meta.trait.isZigString(FieldType.BaseType)) {
// The inner value is never returned to the user, we must free it ourselves.
defer options.allocator.free(inner_value);
// TODO(vincent): don't use unreachable
return std.meta.stringToEnum(FieldType, inner_value) orelse unreachable;
}
if (@typeInfo(FieldType.BaseType) == .Int) {
return @intToEnum(FieldType, @intCast(TI.tag_type, inner_value));
}
@compileError("enum column " ++ @typeName(FieldType) ++ " must have a BaseType of either string or int");
},
.Struct => {
const inner_value = try self.readField(FieldType.BaseType, options, i);
return try FieldType.readField(options.allocator, inner_value);
},
else => @compileError("cannot populate field of type " ++ @typeName(FieldType)),
},
};
}
};
}
/// StatementType returns the type of a statement you would get by calling Db.prepare and derivatives.
///
/// Useful if you want to store a statement in a struct, for example:
///
/// const MyStatements = struct {
/// insert_stmt: sqlite.StatementType(.{}, insert_query),
/// delete_stmt: sqlite.StatementType(.{}, delete_query),
/// };
///
pub fn StatementType(comptime opts: StatementOptions, comptime query: []const u8) type {
@setEvalBranchQuota(100000);
return Statement(opts, ParsedQuery.from(query));
}
pub const StatementOptions = struct {};
/// DynamicStatement is a wrapper around a SQLite statement, providing high-level functions to execute
/// a statement and retrieve rows for SELECT queries.
///
/// The difference to `Statement` is that this type isn't bound to a single parsed query and can execute any query.
///
/// `DynamicStatement` supports "host parameter names", which can be used in a query to identify a bind marker:
///
/// SELECT email FROM users WHERE name = @name AND password = <PASSWORD>;
///
/// You can read more about these parameters in the sqlite documentation: https://sqlite.org/c3ref/bind_blob.html
///
/// To use these names use an anonymous struct with corresponding names like this:
///
/// const stmt = "SELECT * FROM users WHERE name = @name AND password = <PASSWORD>";
/// const row = try stmt.one(Row, .{
/// .name = "Tankman",
/// .password = "<PASSWORD>",
/// });
///
/// This works regardless of the prefix you used in the query.
/// While using the same name with a different prefix is supported by sqlite, `DynamicStatement` doesn't support
/// it because we can't have multiple fields in a struct with the same name.
///
/// You can also use unnamed markers with a tuple:
///
/// const stmt = "SELECT email FROM users WHERE name = ? AND password = ?";
/// const row = try stmt.one(Row, .{"Tankman", "<PASSWORD>"});
///
/// You can only mix named and unnamed bind markers if:
/// * the bind values data is a tuple (without field names)
/// * the bind values data is a struct with the same field orders as in the query
/// This is because with a unnamed bind markers we use the field index in the struct as bind column; if the fields
/// are in the wrong order the query will not work correctly.
///
pub const DynamicStatement = struct {
db: *c.sqlite3,
stmt: *c.sqlite3_stmt,
const Self = @This();
pub const PrepareError = error{} || Error;
fn prepare(db: *Db, query: []const u8, options: QueryOptions, flags: c_uint) PrepareError!Self {
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
var stmt = blk: {
var tmp: ?*c.sqlite3_stmt = undefined;
const result = c.sqlite3_prepare_v3(
db.db,
query.ptr,
@intCast(c_int, query.len),
flags,
&tmp,
options.sql_tail_ptr,
);
if (result != c.SQLITE_OK) {
diags.err = getLastDetailedErrorFromDb(db.db);
return errors.errorFromResultCode(result);
}
if (tmp == null) {
diags.err = .{
.code = 0,
.near = -1,
.message = "the input query is not valid SQL (empty string or a comment)",
};
return error.SQLiteError;
}
break :blk tmp.?;
};
return Self{
.db = db.db,
.stmt = stmt,
};
}
/// deinit releases the prepared statement.
///
/// After a call to `deinit` the statement must not be used.
pub fn deinit(self: *Self) void {
const result = c.sqlite3_finalize(self.stmt);
if (result != c.SQLITE_OK) {
const detailed_error = getLastDetailedErrorFromDb(self.db);
logger.err("unable to finalize prepared statement, result: {}, detailed error: {}", .{ result, detailed_error });
}
}
/// reset resets the prepared statement to make it reusable.
pub fn reset(self: *Self) void {
const result = c.sqlite3_clear_bindings(self.stmt);
if (result != c.SQLITE_OK) {
const detailed_error = getLastDetailedErrorFromDb(self.db);
logger.err("unable to clear prepared statement bindings, result: {}, detailed error: {}", .{ result, detailed_error });
}
const result2 = c.sqlite3_reset(self.stmt);
if (result2 != c.SQLITE_OK) {
const detailed_error = getLastDetailedErrorFromDb(self.db);
logger.err("unable to reset prepared statement, result: {}, detailed error: {}", .{ result2, detailed_error });
}
}
fn convertResultToError(result: c_int) !void {
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
fn bindField(self: *Self, comptime FieldType: type, options: anytype, comptime field_name: []const u8, i: c_int, field: FieldType) !void {
const field_type_info = @typeInfo(FieldType);
const column = i + 1;
switch (FieldType) {
Text => {
const result = c.sqlite3_bind_text(self.stmt, column, field.data.ptr, @intCast(c_int, field.data.len), null);
return convertResultToError(result);
},
Blob => {
const result = c.sqlite3_bind_blob(self.stmt, column, field.data.ptr, @intCast(c_int, field.data.len), null);
return convertResultToError(result);
},
ZeroBlob => {
const result = c.sqlite3_bind_zeroblob64(self.stmt, column, field.length);
return convertResultToError(result);
},
else => switch (field_type_info) {
.Int, .ComptimeInt => {
const result = c.sqlite3_bind_int64(self.stmt, column, @intCast(c_longlong, field));
return convertResultToError(result);
},
.Float, .ComptimeFloat => {
const result = c.sqlite3_bind_double(self.stmt, column, field);
return convertResultToError(result);
},
.Bool => {
const result = c.sqlite3_bind_int64(self.stmt, column, @boolToInt(field));
return convertResultToError(result);
},
.Pointer => |ptr| switch (ptr.size) {
.One => {
try self.bindField(ptr.child, options, field_name, i, field.*);
},
.Slice => switch (ptr.child) {
u8 => {
const result = c.sqlite3_bind_text(self.stmt, column, field.ptr, @intCast(c_int, field.len), null);
return convertResultToError(result);
},
else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)),
},
else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)),
},
.Array => |arr| switch (arr.child) {
u8 => {
const data: []const u8 = field[0..field.len];
const result = c.sqlite3_bind_text(self.stmt, column, data.ptr, @intCast(c_int, data.len), null);
return convertResultToError(result);
},
else => @compileError("cannot bind field " ++ field_name ++ " of type array of " ++ @typeName(arr.child)),
},
.Optional => |opt| if (field) |non_null_field| {
try self.bindField(opt.child, options, field_name, i, non_null_field);
} else {
const result = c.sqlite3_bind_null(self.stmt, column);
return convertResultToError(result);
},
.Null => {
const result = c.sqlite3_bind_null(self.stmt, column);
return convertResultToError(result);
},
.Enum => {
if (comptime std.meta.trait.isZigString(FieldType.BaseType)) {
try self.bindField(FieldType.BaseType, options, field_name, i, @tagName(field));
} else if (@typeInfo(FieldType.BaseType) == .Int) {
try self.bindField(FieldType.BaseType, options, field_name, i, @enumToInt(field));
} else {
@compileError("enum column " ++ @typeName(FieldType) ++ " must have a BaseType of either string or int to bind");
}
},
.Struct => {
if (!comptime std.meta.trait.hasFn("bindField")(FieldType)) {
@compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType) ++ ", consider implementing the bindField() method");
}
const field_value = try field.bindField(options.allocator);
try self.bindField(FieldType.BaseType, options, field_name, i, field_value);
},
.Union => |info| {
if (info.tag_type) |UnionTagType| {
inline for (info.fields) |u_field| {
// This wasn't entirely obvious when I saw code like this elsewhere, it works because of type coercion.
// See https://ziglang.org/documentation/master/#Type-Coercion-unions-and-enums
const field_tag: std.meta.Tag(FieldType) = field;
const this_tag: std.meta.Tag(FieldType) = @field(UnionTagType, u_field.name);
if (field_tag == this_tag) {
const field_value = @field(field, u_field.name);
try self.bindField(u_field.field_type, options, u_field.name, i, field_value);
}
}
} else {
@compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType));
}
},
else => @compileError("cannot bind field " ++ field_name ++ " of type " ++ @typeName(FieldType)),
},
}
}
// bind iterates over the fields in `values` and binds them using `bindField`.
//
// Depending on the query and the type of `values` the binding behaviour differs in regards to the column used.
//
// If `values` is a tuple (and therefore doesn't have field names) then the field _index_ is used.
// This means that if you have a query like this:
//
// SELECT id FROM user WHERE age = ? AND name = ?
//
// You must provide a tuple with the fields in the same order like this:
//
// var iter = try stmt.iterator(.{30, "Vincent"});
//
//
// If `values` is a struct (and therefore has field names) then we check sqlite to see if each field name might be a name bind marker.
// This uses sqlite3_bind_parameter_index and supports bind markers prefixed with ":", "@" and "$".
// For example if you have a query like this:
//
// SELECT id FROM user WHERE age = :age AND name = @name
//
// Then we can provide a struct with fields in any order, like this:
//
// var iter = try stmt.iterator(.{ .age = 30, .name = "Vincent" });
//
// Or
//
// var iter = try stmt.iterator(.{ .name = "Vincent", .age = 30 });
//
// Both will bind correctly.
//
// If however there are no name bind markers then the behaviour will revert to using the field index in the struct, and the fields order must be correct.
fn bind(self: *Self, options: anytype, values: anytype) !void {
const Type = @TypeOf(values);
switch (@typeInfo(Type)) {
.Struct => |StructTypeInfo| {
inline for (StructTypeInfo.fields) |struct_field, struct_field_i| {
const field_value = @field(values, struct_field.name);
const i = sqlite3BindParameterIndex(self.stmt, struct_field.name);
if (i >= 0) {
try self.bindField(struct_field.field_type, options, struct_field.name, i, field_value);
} else {
try self.bindField(struct_field.field_type, options, struct_field.name, struct_field_i, field_value);
}
}
},
.Pointer => |PointerTypeInfo| {
switch (PointerTypeInfo.size) {
.Slice => {
for (values) |value_to_bind, index| {
try self.bindField(PointerTypeInfo.child, options, "unknown", @intCast(c_int, index), value_to_bind);
}
},
else => @compileError("TODO support pointer size " ++ @tagName(PointerTypeInfo.size)),
}
},
.Array => |ArrayTypeInfo| {
for (values) |value_to_bind, index| {
try self.bindField(ArrayTypeInfo.child, options, "unknown", @intCast(c_int, index), value_to_bind);
}
},
else => @compileError("Unsupported type for values: " ++ @typeName(Type)),
}
}
fn sqlite3BindParameterIndex(stmt: *c.sqlite3_stmt, comptime name: []const u8) c_int {
if (name.len == 0) return -1;
inline for (.{ ":", "@", "$" }) |prefix| {
const id = prefix ++ name;
const i = c.sqlite3_bind_parameter_index(stmt, id);
if (i > 0) return i - 1; // .bindField uses 0-based while sqlite3 uses 1-based index.
}
return -1;
}
/// exec executes a statement which does not return data.
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` variable is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
/// The values will be binded depends on the numberic name when it's a tuple, or the
/// string name when it's a normal structure.
///
/// Possible errors:
/// - SQLiteError.SQLiteNotFound if some fields not found
pub fn exec(self: *Self, options: QueryOptions, values: anytype) !void {
try self.bind(.{}, values);
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
const result = c.sqlite3_step(self.stmt);
switch (result) {
c.SQLITE_DONE => {},
c.SQLITE_ROW => return error.ExecReturnedData,
else => {
diags.err = getLastDetailedErrorFromDb(self.db);
return errors.errorFromResultCode(result);
},
}
}
/// iterator returns an iterator to read data from the result set, one row at a time.
///
/// The data in the row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use the iterator:
///
/// var iter = try stmt.iterator(usize, .{});
/// while (try iter.next(.{})) |row| {
/// ...
/// }
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
/// The values will be binded depends on the numberic name when it's a tuple, or the
/// string name when it's a normal structure.
///
/// The iterator _must not_ outlive the statement.
///
/// Possible errors:
/// - SQLiteError.SQLiteNotFound if some fields not found
pub fn iterator(self: *Self, comptime Type: type, values: anytype) !Iterator(Type) {
try self.bind(.{}, values);
var res: Iterator(Type) = undefined;
res.db = self.db;
res.stmt = self.stmt;
return res;
}
/// iterator returns an iterator to read data from the result set, one row at a time.
///
/// The data in the row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use the iterator:
///
/// var iter = try stmt.iterator(usize, .{});
/// while (try iter.next(.{})) |row| {
/// ...
/// }
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
/// The values will be binded depends on the numberic name when it's a tuple, or the
/// string name when it's a normal structure.
///
/// The iterator _must not_ outlive the statement.
///
/// Possible errors:
/// - SQLiteError.SQLiteNotFound if some fields not found
pub fn iteratorAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, values: anytype) !Iterator(Type) {
try self.bind(.{ .allocator = allocator }, values);
var res: Iterator(Type) = undefined;
res.db = self.db;
res.stmt = self.stmt;
return res;
}
/// one reads a single row from the result set of this statement.
///
/// The data in the row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use an anonymous struct type:
///
/// const row = try stmt.one(
/// struct {
/// id: usize,
/// name: [400]u8,
/// age: usize,
/// },
/// .{},
/// .{ .foo = "bar", .age = 500 },
/// );
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
/// This cannot allocate memory. If you need to read TEXT or BLOB columns you need to use arrays or alternatively call `oneAlloc`.
pub fn one(self: *Self, comptime Type: type, options: QueryOptions, values: anytype) !?Type {
var iter = try self.iterator(Type, values);
const row = (try iter.next(options)) orelse return null;
return row;
}
/// oneAlloc is like `one` but can allocate memory.
pub fn oneAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, values: anytype) !?Type {
var iter = try self.iteratorAlloc(Type, allocator, values);
const row = (try iter.nextAlloc(allocator, options)) orelse return null;
return row;
}
/// all reads all rows from the result set of this statement.
///
/// The data in each row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use an anonymous struct type:
///
/// const rows = try stmt.all(
/// struct {
/// id: usize,
/// name: []const u8,
/// age: usize,
/// },
/// allocator,
/// .{},
/// .{ .foo = "bar", .age = 500 },
/// );
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
/// Note that this allocates all rows into a single slice: if you read a lot of data this can use a lot of memory.
pub fn all(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, values: anytype) ![]Type {
var iter = try self.iterator(Type, values);
var rows = std.ArrayList(Type).init(allocator);
while (try iter.nextAlloc(allocator, options)) |row| {
try rows.append(row);
}
return rows.toOwnedSlice();
}
};
/// Statement is a wrapper around a SQLite statement, providing high-level functions to execute
/// a statement and retrieve rows for SELECT queries.
///
/// The exec function can be used to execute a query which does not return rows:
///
/// var stmt = try db.prepare("UPDATE foo SET id = ? WHERE name = ?");
/// defer stmt.deinit();
///
/// try stmt.exec(.{
/// .id = 200,
/// .name = "José",
/// });
///
/// The one function can be used to select a single row:
///
/// var stmt = try db.prepare("SELECT name FROM foo WHERE id = ?");
/// defer stmt.deinit();
///
/// const name = try stmt.one([]const u8, .{}, .{ .id = 200 });
///
/// The all function can be used to select all rows:
///
/// var stmt = try db.prepare("SELECT id, name FROM foo");
/// defer stmt.deinit();
///
/// const Row = struct {
/// id: usize,
/// name: []const u8,
/// };
/// const rows = try stmt.all(Row, .{ .allocator = allocator }, .{});
///
/// Look at each function for more complete documentation.
///
pub fn Statement(comptime opts: StatementOptions, comptime query: ParsedQuery) type {
_ = opts;
return struct {
const Self = @This();
dynamic_stmt: DynamicStatement,
fn prepare(db: *Db, options: QueryOptions, flags: c_uint) DynamicStatement.PrepareError!Self {
return Self{
.dynamic_stmt = try DynamicStatement.prepare(db, query.getQuery(), options, flags),
};
}
pub fn dynamic(self: *Self) *DynamicStatement {
return &self.dynamic_stmt;
}
/// deinit releases the prepared statement.
///
/// After a call to `deinit` the statement must not be used.
pub fn deinit(self: *Self) void {
self.dynamic().deinit();
}
/// reset resets the prepared statement to make it reusable.
pub fn reset(self: *Self) void {
self.dynamic().reset();
}
/// bind binds values to every bind marker in the prepared statement.
///
/// The `values` variable must be a struct where each field has the type of the corresponding bind marker.
/// For example this query:
/// SELECT 1 FROM user WHERE name = ?{text} AND age < ?{u32}
///
/// Has two bind markers, so `values` must have at least the following fields:
/// struct {
/// name: Text,
/// age: u32
/// }
///
/// The types are checked at comptime.
fn bind(self: *Self, options: anytype, values: anytype) !void {
const StructType = @TypeOf(values);
if (!comptime std.meta.trait.is(.Struct)(@TypeOf(values))) {
@compileError("options passed to Statement.bind must be a struct (DynamicStatement supports runtime slices)");
}
const StructTypeInfo = @typeInfo(StructType).Struct;
if (comptime query.nb_bind_markers != StructTypeInfo.fields.len) {
@compileError(comptime std.fmt.comptimePrint("number of bind markers ({d}) not equal to number of fields ({d})", .{
query.nb_bind_markers,
StructTypeInfo.fields.len,
}));
}
inline for (StructTypeInfo.fields) |struct_field, _i| {
const bind_marker = query.bind_markers[_i];
if (bind_marker.typed) |typ| {
const FieldTypeInfo = @typeInfo(struct_field.field_type);
switch (FieldTypeInfo) {
.Struct, .Enum, .Union => comptime assertMarkerType(
if (@hasDecl(struct_field.field_type, "BaseType")) struct_field.field_type.BaseType else struct_field.field_type,
typ,
),
else => comptime assertMarkerType(struct_field.field_type, typ),
}
}
}
return self.dynamic().bind(options, values) catch |e| switch (e) {
errors.Error.SQLiteNotFound => unreachable, // impossible to have non-exists field
else => e,
};
}
fn assertMarkerType(comptime Actual: type, comptime Expected: type) void {
if (Actual != Expected) {
@compileError("value type " ++ @typeName(Actual) ++ " is not the bind marker type " ++ @typeName(Expected));
}
}
/// execAlloc is like `exec` but can allocate memory.
pub fn execAlloc(self: *Self, allocator: mem.Allocator, options: QueryOptions, values: anytype) !void {
try self.bind(.{ .allocator = allocator }, values);
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
const result = c.sqlite3_step(self.dynamic().stmt);
switch (result) {
c.SQLITE_DONE => {},
else => {
diags.err = getLastDetailedErrorFromDb(self.dynamic().db);
return errors.errorFromResultCode(result);
},
}
}
/// exec executes a statement which does not return data.
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` variable is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
pub fn exec(self: *Self, options: QueryOptions, values: anytype) !void {
try self.bind(.{}, values);
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
const result = c.sqlite3_step(self.dynamic().stmt);
switch (result) {
c.SQLITE_DONE => {},
else => {
diags.err = getLastDetailedErrorFromDb(self.dynamic().db);
return errors.errorFromResultCode(result);
},
}
}
/// iterator returns an iterator to read data from the result set, one row at a time.
///
/// The data in the row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use the iterator:
///
/// var iter = try stmt.iterator(usize, .{});
/// while (try iter.next(.{})) |row| {
/// ...
/// }
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
/// The iterator _must not_ outlive the statement.
pub fn iterator(self: *Self, comptime Type: type, values: anytype) !Iterator(Type) {
try self.bind(.{}, values);
var res: Iterator(Type) = undefined;
res.db = self.dynamic().db;
res.stmt = self.dynamic().stmt;
return res;
}
/// iteratorAlloc is like `iterator` but can allocate memory.
pub fn iteratorAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, values: anytype) !Iterator(Type) {
try self.bind(.{ .allocator = allocator }, values);
var res: Iterator(Type) = undefined;
res.db = self.dynamic().db;
res.stmt = self.dynamic().stmt;
return res;
}
/// one reads a single row from the result set of this statement.
///
/// The data in the row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use an anonymous struct type:
///
/// const row = try stmt.one(
/// struct {
/// id: usize,
/// name: [400]u8,
/// age: usize,
/// },
/// .{},
/// .{ .foo = "bar", .age = 500 },
/// );
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
/// This cannot allocate memory. If you need to read TEXT or BLOB columns you need to use arrays or alternatively call `oneAlloc`.
pub fn one(self: *Self, comptime Type: type, options: QueryOptions, values: anytype) !?Type {
var iter = try self.iterator(Type, values);
const row = (try iter.next(options)) orelse return null;
return row;
}
/// oneAlloc is like `one` but can allocate memory.
pub fn oneAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, values: anytype) !?Type {
var iter = try self.iteratorAlloc(Type, allocator, values);
const row = (try iter.nextAlloc(allocator, options)) orelse return null;
return row;
}
/// all reads all rows from the result set of this statement.
///
/// The data in each row is used to populate a value of the type `Type`.
/// This means that `Type` must have as many fields as is returned in the query
/// executed by this statement.
/// This also means that the type of each field must be compatible with the SQLite type.
///
/// Here is an example of how to use an anonymous struct type:
///
/// const rows = try stmt.all(
/// struct {
/// id: usize,
/// name: []const u8,
/// age: usize,
/// },
/// allocator,
/// .{},
/// .{ .foo = "bar", .age = 500 },
/// );
///
/// The `options` tuple is used to provide additional state in some cases.
///
/// The `values` tuple is used for the bind parameters. It must have as many fields as there are bind markers
/// in the input query string.
///
/// Note that this allocates all rows into a single slice: if you read a lot of data this can use a lot of memory.
pub fn all(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, values: anytype) ![]Type {
var iter = try self.iteratorAlloc(Type, allocator, values);
var rows = std.ArrayList(Type).init(allocator);
while (try iter.nextAlloc(allocator, options)) |row| {
try rows.append(row);
}
return rows.toOwnedSlice();
}
};
}
const TestUser = struct {
name: []const u8,
id: usize,
age: usize,
weight: f32,
favorite_color: Color,
pub const Color = enum {
red,
majenta,
violet,
indigo,
blue,
cyan,
green,
lime,
yellow,
//
orange,
//
pub const BaseType = []const u8;
};
};
const test_users = &[_]TestUser{
.{ .name = "Vincent", .id = 20, .age = 33, .weight = 85.4, .favorite_color = .violet },
.{ .name = "Julien", .id = 40, .age = 35, .weight = 100.3, .favorite_color = .green },
.{ .name = "José", .id = 60, .age = 40, .weight = 240.2, .favorite_color = .indigo },
};
fn createTestTables(db: *Db) !void {
const AllDDL = &[_][]const u8{
"DROP TABLE IF EXISTS user",
"DROP TABLE IF EXISTS article",
"DROP TABLE IF EXISTS test_blob",
\\CREATE TABLE user(
\\ name text,
\\ id integer PRIMARY KEY,
\\ age integer,
\\ weight real,
\\ favorite_color text
\\)
,
\\CREATE TABLE article(
\\ id integer PRIMARY KEY,
\\ author_id integer,
\\ data text,
\\ is_published integer,
\\ FOREIGN KEY(author_id) REFERENCES user(id)
\\)
};
// Create the tables
inline for (AllDDL) |ddl| {
try db.exec(ddl, .{}, .{});
}
}
fn addTestData(db: *Db) !void {
try createTestTables(db);
for (test_users) |user| {
try db.exec("INSERT INTO user(name, id, age, weight, favorite_color) VALUES(?{[]const u8}, ?{usize}, ?{usize}, ?{f32}, ?{[]const u8})", .{}, user);
const rows_inserted = db.rowsAffected();
try testing.expectEqual(@as(usize, 1), rows_inserted);
}
}
test "sqlite: db init" {
var db = try getTestDb();
defer db.deinit();
_ = db;
}
test "sqlite: exec multi" {
var db = try getTestDb();
defer db.deinit();
try db.execMulti("create table a(b int);\n\n--test comment\ncreate table b(c int);", .{});
const val = try db.one(i32, "select max(c) from b", .{}, .{});
try testing.expectEqual(@as(?i32, 0), val);
}
test "sqlite: exec multi with single statement" {
var db = try getTestDb();
defer db.deinit();
try db.execMulti("create table a(b int);", .{});
const val = try db.one(i32, "select max(b) from a", .{}, .{});
try testing.expectEqual(@as(?i32, 0), val);
}
test "sqlite: db pragma" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
const foreign_keys = try db.pragma(usize, .{}, "foreign_keys", null);
try testing.expect(foreign_keys != null);
try testing.expectEqual(@as(usize, 0), foreign_keys.?);
if (build_options.in_memory) {
{
const journal_mode = try db.pragma([128:0]u8, .{}, "journal_mode", "wal");
try testing.expect(journal_mode != null);
try testing.expectEqualStrings("memory", mem.sliceTo(&journal_mode.?, 0));
}
{
const journal_mode = try db.pragmaAlloc([]const u8, allocator, .{}, "journal_mode", "wal");
try testing.expect(journal_mode != null);
try testing.expectEqualStrings("memory", journal_mode.?);
}
} else {
{
const journal_mode = try db.pragma([128:0]u8, .{}, "journal_mode", "wal");
try testing.expect(journal_mode != null);
try testing.expectEqualStrings("wal", mem.sliceTo(&journal_mode.?, 0));
}
{
const journal_mode = try db.pragmaAlloc([]const u8, allocator, .{}, "journal_mode", "wal");
try testing.expect(journal_mode != null);
try testing.expectEqualStrings("wal", journal_mode.?);
}
}
}
test "sqlite: last insert row id" {
var db = try getTestDb();
defer db.deinit();
try createTestTables(&db);
try db.exec("INSERT INTO user(name, age) VALUES(?, ?{u32})", .{}, .{
.name = "test-user",
.age = @as(u32, 400),
});
const id = db.getLastInsertRowID();
try testing.expectEqual(@as(i64, 1), id);
}
test "sqlite: statement exec" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
// Test with a Blob struct
{
try db.exec("INSERT INTO user(id, name, age) VALUES(?{usize}, ?{blob}, ?{u32})", .{}, .{
.id = @as(usize, 200),
.name = Blob{ .data = "hello" },
.age = @as(u32, 20),
});
}
// Test with a Text struct
{
try db.exec("INSERT INTO user(id, name, age) VALUES(?{usize}, ?{text}, ?{u32})", .{}, .{
.id = @as(usize, 201),
.name = Text{ .data = "hello" },
.age = @as(u32, 20),
});
}
}
test "sqlite: statement execDynamic" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
// Test with a Blob struct
{
try db.execDynamic("INSERT INTO user(id, name, age) VALUES(@id, @name, @age)", .{}, .{
.id = @as(usize, 200),
.name = Blob{ .data = "hello" },
.age = @as(u32, 20),
});
}
// Test with a Text struct
{
try db.execDynamic("INSERT INTO user(id, name, age) VALUES(@id, @name, @age)", .{}, .{
.id = @as(usize, 201),
.name = Text{ .data = "hello" },
.age = @as(u32, 20),
});
}
}
test "sqlite: db execAlloc" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
try db.execAlloc(testing.allocator, "INSERT INTO user(id, name, age) VALUES(@id, @name, @age)", .{}, .{
.id = @as(usize, 502),
.name = Blob{ .data = "hello" },
.age = @as(u32, 20),
});
}
test "sqlite: read a single user into a struct" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var stmt = try db.prepare("SELECT * FROM user WHERE id = ?{usize}");
defer stmt.deinit();
var rows = try stmt.all(TestUser, allocator, .{}, .{
.id = @as(usize, 20),
});
for (rows) |row| {
try testing.expectEqual(test_users[0].id, row.id);
try testing.expectEqualStrings(test_users[0].name, row.name);
try testing.expectEqual(test_users[0].age, row.age);
}
// Read a row with db.one()
{
var row = try db.one(
struct {
name: [128:0]u8,
id: usize,
age: usize,
},
"SELECT name, id, age FROM user WHERE id = ?{usize}",
.{},
.{@as(usize, 20)},
);
try testing.expect(row != null);
const exp = test_users[0];
try testing.expectEqual(exp.id, row.?.id);
try testing.expectEqualStrings(exp.name, mem.sliceTo(&row.?.name, 0));
try testing.expectEqual(exp.age, row.?.age);
}
// Read a row with db.oneAlloc()
{
var row = try db.oneAlloc(
struct {
name: Text,
id: usize,
age: usize,
},
allocator,
"SELECT name, id, age FROM user WHERE id = ?{usize}",
.{},
.{@as(usize, 20)},
);
try testing.expect(row != null);
const exp = test_users[0];
try testing.expectEqual(exp.id, row.?.id);
try testing.expectEqualStrings(exp.name, row.?.name.data);
try testing.expectEqual(exp.age, row.?.age);
}
}
test "sqlite: read all users into a struct" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var stmt = try db.prepare("SELECT * FROM user");
defer stmt.deinit();
var rows = try stmt.all(TestUser, allocator, .{}, .{});
try testing.expectEqual(@as(usize, 3), rows.len);
for (rows) |row, i| {
const exp = test_users[i];
try testing.expectEqual(exp.id, row.id);
try testing.expectEqualStrings(exp.name, row.name);
try testing.expectEqual(exp.age, row.age);
try testing.expectEqual(exp.weight, row.weight);
}
}
test "sqlite: read in an anonymous struct" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var stmt = try db.prepare("SELECT name, id, name, age, id, weight FROM user WHERE id = ?{usize}");
defer stmt.deinit();
var row = try stmt.oneAlloc(
struct {
name: []const u8,
id: usize,
name_2: [200:0xAD]u8,
age: usize,
is_id: bool,
weight: f64,
},
allocator,
.{},
.{ .id = @as(usize, 20) },
);
try testing.expect(row != null);
const exp = test_users[0];
try testing.expectEqual(exp.id, row.?.id);
try testing.expectEqualStrings(exp.name, row.?.name);
try testing.expectEqualStrings(exp.name, mem.sliceTo(&row.?.name_2, 0xAD));
try testing.expectEqual(exp.age, row.?.age);
try testing.expect(row.?.is_id);
try testing.expectEqual(exp.weight, @floatCast(f32, row.?.weight));
}
test "sqlite: read in a Text struct" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var stmt = try db.prepare("SELECT name, id, age FROM user WHERE id = ?{usize}");
defer stmt.deinit();
var row = try stmt.oneAlloc(
struct {
name: Text,
id: usize,
age: usize,
},
allocator,
.{},
.{@as(usize, 20)},
);
try testing.expect(row != null);
const exp = test_users[0];
try testing.expectEqual(exp.id, row.?.id);
try testing.expectEqualStrings(exp.name, row.?.name.data);
try testing.expectEqual(exp.age, row.?.age);
}
test "sqlite: read a single text value" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const types = &[_]type{
// Slices
[]const u8,
[]u8,
[:0]const u8,
[:0]u8,
[:0xAD]const u8,
[:0xAD]u8,
// Array
[8:0]u8,
[8:0xAD]u8,
[7]u8,
// Specific text or blob
Text,
Blob,
};
inline for (types) |typ| {
const query = "SELECT name FROM user WHERE id = ?{usize}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const name = try stmt.oneAlloc(typ, allocator, .{}, .{
.id = @as(usize, 20),
});
try testing.expect(name != null);
switch (typ) {
Text, Blob => {
try testing.expectEqualStrings("Vincent", name.?.data);
},
else => {
const type_info = @typeInfo(typ);
switch (type_info) {
.Pointer => {
try testing.expectEqualStrings("Vincent", name.?);
},
.Array => |arr| if (arr.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const arr.child, sentinel_ptr).*;
const res = mem.sliceTo(&name.?, sentinel);
try testing.expectEqualStrings("Vincent", res);
} else {
const res = mem.span(&name.?);
try testing.expectEqualStrings("Vincent", res);
},
else => @compileError("invalid type " ++ @typeName(typ)),
}
},
}
}
}
test "sqlite: read a single integer value" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const types = &[_]type{
u8,
u16,
u32,
u64,
u128,
usize,
f16,
f32,
f64,
f128,
};
inline for (types) |typ| {
const query = "SELECT age FROM user WHERE id = ?{usize}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
var age = try stmt.one(typ, .{}, .{
.id = @as(usize, 20),
});
try testing.expect(age != null);
try testing.expectEqual(@as(typ, 33), age.?);
}
}
test "sqlite: read a single value into an enum backed by an integer" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try createTestTables(&db);
try db.exec("INSERT INTO user(id, age) VALUES(?{usize}, ?{usize})", .{}, .{
.id = @as(usize, 10),
.age = @as(usize, 0),
});
const query = "SELECT age FROM user WHERE id = ?{usize}";
const IntColor = enum {
violet,
pub const BaseType = u1;
};
// Use one
{
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.one(IntColor, .{}, .{
.id = @as(usize, 10),
});
try testing.expect(b != null);
try testing.expectEqual(IntColor.violet, b.?);
}
// Use oneAlloc
{
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.oneAlloc(IntColor, allocator, .{}, .{
.id = @as(usize, 10),
});
try testing.expect(b != null);
try testing.expectEqual(IntColor.violet, b.?);
}
}
test "sqlite: read a single value into an enum backed by a string" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try createTestTables(&db);
try db.exec("INSERT INTO user(id, favorite_color) VALUES(?{usize}, ?{[]const u8})", .{}, .{
.id = @as(usize, 10),
.age = @as([]const u8, "violet"),
});
const query = "SELECT favorite_color FROM user WHERE id = ?{usize}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.oneAlloc(TestUser.Color, allocator, .{}, .{
.id = @as(usize, 10),
});
try testing.expect(b != null);
try testing.expectEqual(TestUser.Color.violet, b.?);
}
test "sqlite: read a single value into void" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const query = "SELECT age FROM user WHERE id = ?{usize}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
_ = try stmt.one(void, .{}, .{
.id = @as(usize, 20),
});
}
test "sqlite: read a single value into bool" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const query = "SELECT id FROM user WHERE id = ?{usize}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.one(bool, .{}, .{
.id = @as(usize, 20),
});
try testing.expect(b != null);
try testing.expect(b.?);
}
test "sqlite: insert bool and bind bool" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
try db.exec("INSERT INTO article(id, author_id, is_published) VALUES(?{usize}, ?{usize}, ?{bool})", .{}, .{
.id = @as(usize, 1),
.author_id = @as(usize, 20),
.is_published = true,
});
const query = "SELECT id FROM article WHERE is_published = ?{bool}";
var stmt: StatementType(.{}, query) = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.one(bool, .{}, .{
.is_published = true,
});
try testing.expect(b != null);
try testing.expect(b.?);
}
test "sqlite: bind string literal" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
try db.exec("INSERT INTO article(id, data) VALUES(?, ?)", .{}, .{
@as(usize, 10),
"foobar",
});
const query = "SELECT id FROM article WHERE data = ?";
var stmt = try db.prepare(query);
defer stmt.deinit();
const b = try stmt.one(usize, .{}, .{"foobar"});
try testing.expect(b != null);
try testing.expectEqual(@as(usize, 10), b.?);
}
test "sqlite: bind pointer" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const query = "SELECT name FROM user WHERE id = ?";
var stmt = try db.prepare(query);
defer stmt.deinit();
for (test_users) |test_user, i| {
stmt.reset();
const name = try stmt.oneAlloc([]const u8, allocator, .{}, .{&test_user.id});
try testing.expect(name != null);
try testing.expectEqualStrings(test_users[i].name, name.?);
}
}
test "sqlite: read pointers" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const query = "SELECT id, name, age, weight FROM user";
var stmt = try db.prepare(query);
defer stmt.deinit();
const rows = try stmt.all(
struct {
id: *usize,
name: *[]const u8,
age: *u32,
weight: *f32,
},
allocator,
.{},
.{},
);
try testing.expectEqual(@as(usize, 3), rows.len);
for (rows) |row, i| {
const exp = test_users[i];
try testing.expectEqual(exp.id, row.id.*);
try testing.expectEqualStrings(exp.name, row.name.*);
try testing.expectEqual(exp.age, row.age.*);
try testing.expectEqual(exp.weight, row.weight.*);
}
}
test "sqlite: optional" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const published: ?bool = true;
{
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ 1, null, published });
var stmt = try db.prepare("SELECT data, is_published FROM article");
defer stmt.deinit();
const row = try stmt.one(
struct {
data: ?[128:0]u8,
is_published: ?bool,
},
.{},
.{},
);
try testing.expect(row != null);
try testing.expect(row.?.data == null);
try testing.expectEqual(true, row.?.is_published.?);
}
{
const data: ?[]const u8 = "hello";
try db.exec("INSERT INTO article(author_id, data) VALUES(?, :data{?[]const u8})", .{}, .{
.author_id = 20,
.dhe = data,
});
const row = try db.oneAlloc(
[]const u8,
arena.allocator(),
"SELECT data FROM article WHERE author_id = ?",
.{},
.{ .author_id = 20 },
);
try testing.expect(row != null);
try testing.expectEqualStrings(data.?, row.?);
}
}
test "sqlite: statement reset" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
// Add data
var stmt = try db.prepare("INSERT INTO user(name, id, age, weight, favorite_color) VALUES(?{[]const u8}, ?{usize}, ?{usize}, ?{f32}, ?{[]const u8})");
defer stmt.deinit();
const users = &[_]TestUser{
.{ .id = 200, .name = "Vincent", .age = 33, .weight = 10.0, .favorite_color = .violet },
.{ .id = 400, .name = "Julien", .age = 35, .weight = 12.0, .favorite_color = .green },
.{ .id = 600, .name = "José", .age = 40, .weight = 14.0, .favorite_color = .indigo },
};
for (users) |user| {
stmt.reset();
try stmt.exec(.{}, user);
const rows_inserted = db.rowsAffected();
try testing.expectEqual(@as(usize, 1), rows_inserted);
}
}
test "sqlite: statement iterator" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
// Cleanup first
try db.exec("DELETE FROM user", .{}, .{});
// Add data
var stmt = try db.prepare("INSERT INTO user(name, id, age, weight, favorite_color) VALUES(?{[]const u8}, ?{usize}, ?{usize}, ?{f32}, ?{[]const u8})");
defer stmt.deinit();
var expected_rows = std.ArrayList(TestUser).init(allocator);
var i: usize = 0;
while (i < 20) : (i += 1) {
const name = try std.fmt.allocPrint(allocator, "Vincent {d}", .{i});
const user = TestUser{ .id = i, .name = name, .age = i + 200, .weight = @intToFloat(f32, i + 200), .favorite_color = .indigo };
try expected_rows.append(user);
stmt.reset();
try stmt.exec(.{}, user);
const rows_inserted = db.rowsAffected();
try testing.expectEqual(@as(usize, 1), rows_inserted);
}
// Get data with a non-allocating iterator.
{
var stmt2 = try db.prepare("SELECT name, age FROM user");
defer stmt2.deinit();
const RowType = struct {
name: [128:0]u8,
age: usize,
};
var iter = try stmt2.iterator(RowType, .{});
var rows = std.ArrayList(RowType).init(allocator);
while (try iter.next(.{})) |row| {
try rows.append(row);
}
// Check the data
try testing.expectEqual(expected_rows.items.len, rows.items.len);
for (rows.items) |row, j| {
const exp_row = expected_rows.items[j];
try testing.expectEqualStrings(exp_row.name, mem.sliceTo(&row.name, 0));
try testing.expectEqual(exp_row.age, row.age);
}
}
// Get data with an iterator
{
var stmt2 = try db.prepare("SELECT name, age FROM user");
defer stmt2.deinit();
const RowType = struct {
name: Text,
age: usize,
};
var iter = try stmt2.iterator(RowType, .{});
var rows = std.ArrayList(RowType).init(allocator);
while (try iter.nextAlloc(allocator, .{})) |row| {
try rows.append(row);
}
// Check the data
try testing.expectEqual(expected_rows.items.len, rows.items.len);
for (rows.items) |row, j| {
const exp_row = expected_rows.items[j];
try testing.expectEqualStrings(exp_row.name, row.name.data);
try testing.expectEqual(exp_row.age, row.age);
}
}
}
test "sqlite: blob open, reopen" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
const blob_data1 = "\xDE\xAD\xBE\xEFabcdefghijklmnopqrstuvwxyz0123456789";
const blob_data2 = "\xCA\xFE\xBA\xBEfoobar";
// Insert two blobs with a set length
try db.exec("CREATE TABLE test_blob(id integer primary key, data blob)", .{}, .{});
try db.exec("INSERT INTO test_blob(data) VALUES(?)", .{}, .{
.data = ZeroBlob{ .length = blob_data1.len * 2 },
});
const rowid1 = db.getLastInsertRowID();
try db.exec("INSERT INTO test_blob(data) VALUES(?)", .{}, .{
.data = ZeroBlob{ .length = blob_data2.len * 2 },
});
const rowid2 = db.getLastInsertRowID();
// Open the blob in the first row
var blob = try db.openBlob(.main, "test_blob", "data", rowid1, .{ .write = true });
{
// Write the first blob data
var blob_writer = blob.writer();
try blob_writer.writeAll(blob_data1);
try blob_writer.writeAll(blob_data1);
blob.reset();
var blob_reader = blob.reader();
const data = try blob_reader.readAllAlloc(allocator, 8192);
try testing.expectEqualSlices(u8, blob_data1 ** 2, data);
}
// Reopen the blob in the second row
try blob.reopen(rowid2);
{
// Write the second blob data
var blob_writer = blob.writer();
try blob_writer.writeAll(blob_data2);
try blob_writer.writeAll(blob_data2);
blob.reset();
var blob_reader = blob.reader();
const data = try blob_reader.readAllAlloc(allocator, 8192);
try testing.expectEqualSlices(u8, blob_data2 ** 2, data);
}
try blob.close();
}
test "sqlite: failing open" {
var diags: Diagnostics = undefined;
const res = Db.init(.{
.diags = &diags,
.open_flags = .{},
.mode = .{ .File = "/tmp/not_existing.db" },
});
try testing.expectError(error.SQLiteCantOpen, res);
try testing.expectEqual(@as(usize, 14), diags.err.?.code);
try testing.expectEqualStrings("unable to open database file", diags.err.?.message);
}
test "sqlite: failing prepare statement" {
var db = try getTestDb();
defer db.deinit();
var diags: Diagnostics = undefined;
const result = db.prepareWithDiags("SELECT id FROM foobar", .{ .diags = &diags });
try testing.expectError(error.SQLiteError, result);
const detailed_err = db.getDetailedError();
try testing.expectEqual(@as(usize, 1), detailed_err.code);
try testing.expectEqualStrings("no such table: foobar", detailed_err.message);
}
test "sqlite: diagnostics format" {
const TestCase = struct {
input: Diagnostics,
exp: []const u8,
};
const testCases = &[_]TestCase{
.{
.input = .{},
.exp = "my diagnostics: none",
},
.{
.input = .{
.message = "foobar",
},
.exp = "my diagnostics: foobar",
},
.{
.input = .{
.err = .{
.code = 20,
.near = -1,
.message = "barbaz",
},
},
.exp = "my diagnostics: {code: 20, near: -1, message: barbaz}",
},
.{
.input = .{
.message = "foobar",
.err = .{
.code = 20,
.near = 10,
.message = "barbaz",
},
},
.exp = "my diagnostics: {message: foobar, detailed error: {code: 20, near: 10, message: barbaz}}",
},
};
inline for (testCases) |tc| {
var buf: [1024]u8 = undefined;
const str = try std.fmt.bufPrint(&buf, "my diagnostics: {s}", .{tc.input});
try testing.expectEqualStrings(tc.exp, str);
}
}
test "sqlite: exec with diags, failing statement" {
var db = try getTestDb();
defer db.deinit();
var diags = Diagnostics{};
const result = blk: {
var stmt = try db.prepareWithDiags("ROLLBACK", .{ .diags = &diags });
break :blk stmt.exec(.{ .diags = &diags }, .{});
};
try testing.expectError(error.SQLiteError, result);
try testing.expect(diags.err != null);
try testing.expectEqualStrings("cannot rollback - no transaction is active", diags.err.?.message);
const detailed_err = db.getDetailedError();
try testing.expectEqual(@as(usize, 1), detailed_err.code);
try testing.expectEqualStrings("cannot rollback - no transaction is active", detailed_err.message);
}
test "sqlite: savepoint with no failures" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
{
var savepoint = try db.savepoint("outer1");
defer savepoint.rollback();
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ 1, null, true });
{
var savepoint2 = try db.savepoint("inner1");
defer savepoint2.rollback();
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ 2, "foobar", true });
savepoint2.commit();
}
savepoint.commit();
}
// No failures, expect to have two rows.
var stmt = try db.prepare("SELECT data, author_id FROM article ORDER BY id ASC");
defer stmt.deinit();
var rows = try stmt.all(
struct {
data: []const u8,
author_id: usize,
},
allocator,
.{},
.{},
);
try testing.expectEqual(@as(usize, 2), rows.len);
try testing.expectEqual(@as(usize, 1), rows[0].author_id);
try testing.expectEqualStrings("", rows[0].data);
try testing.expectEqual(@as(usize, 2), rows[1].author_id);
try testing.expectEqualStrings("foobar", rows[1].data);
}
test "sqlite: two nested savepoints with inner failure" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
{
var savepoint = try db.savepoint("outer2");
defer savepoint.rollback();
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ 10, "barbaz", true });
inner: {
var savepoint2 = try db.savepoint("inner2");
defer savepoint2.rollback();
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ 20, null, true });
// Explicitly fail
db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?)", .{}, .{ 22, null }) catch {
break :inner;
};
savepoint2.commit();
}
savepoint.commit();
}
// The inner transaction failed, expect to have only one row.
var stmt = try db.prepare("SELECT data, author_id FROM article");
defer stmt.deinit();
var rows = try stmt.all(
struct {
data: []const u8,
author_id: usize,
},
allocator,
.{},
.{},
);
try testing.expectEqual(@as(usize, 1), rows.len);
try testing.expectEqual(@as(usize, 10), rows[0].author_id);
try testing.expectEqualStrings("barbaz", rows[0].data);
}
test "sqlite: two nested savepoints with outer failure" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
blk: {
var savepoint = try db.savepoint("outer3");
defer savepoint.rollback();
var i: usize = 100;
while (i < 120) : (i += 1) {
try db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?, ?)", .{}, .{ i, null, true });
}
// Explicitly fail
db.exec("INSERT INTO article(author_id, data, is_published) VALUES(?, ?)", .{}, .{ 2, null }) catch {
break :blk;
};
savepoint.commit();
}
// The outer transaction failed, expect to have no rows.
var stmt = try db.prepare("SELECT 1 FROM article");
defer stmt.deinit();
var rows = try stmt.all(usize, allocator, .{}, .{});
try testing.expectEqual(@as(usize, 0), rows.len);
}
fn getTestDb() !Db {
var buf: [1024]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
var mode = dbMode(fba.allocator());
return try Db.init(.{
.open_flags = .{
.write = true,
.create = true,
},
.mode = mode,
});
}
fn tmpDbPath(allocator: mem.Allocator) ![:0]const u8 {
const tmp_dir = testing.tmpDir(.{});
const path = try std.fs.path.join(allocator, &[_][]const u8{
"zig-cache",
"tmp",
&tmp_dir.sub_path,
"zig-sqlite.db",
});
defer allocator.free(path);
return allocator.dupeZ(u8, path);
}
fn dbMode(allocator: mem.Allocator) Db.Mode {
return if (build_options.in_memory) blk: {
break :blk .{ .Memory = {} };
} else blk: {
if (build_options.dbfile) |dbfile| {
return .{ .File = allocator.dupeZ(u8, dbfile) catch unreachable };
}
const path = tmpDbPath(allocator) catch unreachable;
std.fs.cwd().deleteFile(path) catch {};
break :blk .{ .File = path };
};
}
const MyData = struct {
data: [16]u8,
const BaseType = []const u8;
pub fn bindField(self: MyData, allocator: mem.Allocator) !BaseType {
return try std.fmt.allocPrint(allocator, "{}", .{std.fmt.fmtSliceHexLower(&self.data)});
}
pub fn readField(alloc: mem.Allocator, value: BaseType) !MyData {
_ = alloc;
var result = [_]u8{0} ** 16;
var i: usize = 0;
while (i < result.len) : (i += 1) {
const j = i * 2;
result[i] = try std.fmt.parseUnsigned(u8, value[j..][0..2], 16);
}
return MyData{ .data = result };
}
};
test "sqlite: bind custom type" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
{
var i: usize = 0;
while (i < 20) : (i += 1) {
var my_data: MyData = undefined;
mem.set(u8, &my_data.data, @intCast(u8, i));
var arena = heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
// insertion
var stmt = try db.prepare("INSERT INTO article(data) VALUES(?)");
try stmt.execAlloc(arena.allocator(), .{}, .{my_data});
}
}
{
// reading back
var stmt = try db.prepare("SELECT * FROM article");
defer stmt.deinit();
const Article = struct {
id: u32,
author_id: u32,
data: MyData,
is_published: bool,
};
var arena = heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const rows = try stmt.all(Article, arena.allocator(), .{}, .{});
try testing.expectEqual(@as(usize, 20), rows.len);
for (rows) |row, i| {
var exp_data: MyData = undefined;
mem.set(u8, &exp_data.data, @intCast(u8, i));
try testing.expectEqualSlices(u8, &exp_data.data, &row.data.data);
}
}
}
test "sqlite: bind runtime slice" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
// creating array list on heap so that it's deemed runtime size
var list = std.ArrayList([]const u8).init(allocator);
defer list.deinit();
try list.append("this is some data");
const args = list.toOwnedSlice();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
{
// insertion
var stmt = try db.prepareDynamic("INSERT INTO article(data) VALUES(?)");
defer stmt.deinit();
try stmt.exec(.{}, args);
}
}
test "sqlite: prepareDynamic" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var diags = Diagnostics{};
var stmt = try db.prepareDynamicWithDiags("SELECT id FROM user WHERE age = ?", .{ .diags = &diags });
defer stmt.deinit();
{
var iter = try stmt.iterator(usize, .{ .age = 33 });
const id = try iter.next(.{});
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
stmt.reset();
{
var iter = try stmt.iteratorAlloc(usize, allocator, .{ .age = 33 });
const id = try iter.next(.{});
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
stmt.reset();
{
var iter = try stmt.iteratorAlloc(usize, allocator, .{33});
const id = try iter.next(.{});
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
}
test "sqlite: oneDynamic" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var allocator = arena.allocator();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var diags = Diagnostics{};
{
const id = try db.oneDynamic(
usize,
"SELECT id FROM user WHERE age = ?",
.{ .diags = &diags },
.{ .age = 33 },
);
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
{
// Mix bind marker prefix for good measure
const id = try db.oneDynamic(
usize,
"SELECT id FROM user WHERE age = $age AND weight < :weight and id < @id",
.{ .diags = &diags },
.{ .id = 400, .age = 33, .weight = 200 },
);
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
{
const id = try db.oneDynamicAlloc(
usize,
allocator,
"SELECT id FROM user WHERE age = ?",
.{ .diags = &diags },
.{ .age = 33 },
);
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
{
const id = try db.oneDynamicAlloc(
usize,
allocator,
"SELECT id FROM user WHERE age = ?",
.{ .diags = &diags },
.{33},
);
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
}
test "sqlite: one with all named parameters" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var diags = Diagnostics{};
// Mix bind marker prefix for good measure
const id = try db.one(
usize,
"SELECT id FROM user WHERE age = $age AND weight < :weight and id < @my_id",
.{ .diags = &diags },
.{ .my_id = 400, .age = 33, .weight = 200 },
);
try testing.expect(id != null);
try testing.expectEqual(@as(usize, 20), id.?);
}
test "sqlite: create scalar function" {
var db = try getTestDb();
defer db.deinit();
{
try db.createScalarFunction(
"myInteger",
struct {
fn run(input: u16) u16 {
return input * 2;
}
}.run,
.{},
);
const result = try db.one(usize, "SELECT myInteger(20)", .{}, .{});
try testing.expect(result != null);
try testing.expectEqual(@as(usize, 40), result.?);
}
{
try db.createScalarFunction(
"myInteger64",
struct {
fn run(input: i64) i64 {
return @intCast(i64, input) * 2;
}
}.run,
.{},
);
const result = try db.one(usize, "SELECT myInteger64(20)", .{}, .{});
try testing.expect(result != null);
try testing.expectEqual(@as(usize, 40), result.?);
}
{
try db.createScalarFunction(
"myMax",
struct {
fn run(a: f64, b: f64) f64 {
return std.math.max(a, b);
}
}.run,
.{},
);
const result = try db.one(f64, "SELECT myMax(2.0, 23.4)", .{}, .{});
try testing.expect(result != null);
try testing.expectEqual(@as(f64, 23.4), result.?);
}
{
try db.createScalarFunction(
"myBool",
struct {
fn run() bool {
return true;
}
}.run,
.{},
);
const result = try db.one(bool, "SELECT myBool()", .{}, .{});
try testing.expect(result != null);
try testing.expectEqual(true, result.?);
}
{
try db.createScalarFunction(
"mySlice",
struct {
fn run() []const u8 {
return "foobar";
}
}.run,
.{},
);
const result = try db.oneAlloc([]const u8, testing.allocator, "SELECT mySlice()", .{}, .{});
try testing.expect(result != null);
try testing.expectEqualStrings("foobar", result.?);
testing.allocator.free(result.?);
}
{
const Blake3 = std.crypto.hash.Blake3;
var expected_hash: [Blake3.digest_length]u8 = undefined;
Blake3.hash("hello", &expected_hash, .{});
try db.createScalarFunction(
"blake3",
struct {
fn run(input: []const u8) [std.crypto.hash.Blake3.digest_length]u8 {
var hash: [Blake3.digest_length]u8 = undefined;
Blake3.hash(input, &hash, .{});
return hash;
}
}.run,
.{},
);
const hash = try db.one([Blake3.digest_length]u8, "SELECT blake3('hello')", .{}, .{});
try testing.expect(hash != null);
try testing.expectEqual(expected_hash, hash.?);
}
{
try db.createScalarFunction(
"myText",
struct {
fn run() Text {
return Text{ .data = "foobar" };
}
}.run,
.{},
);
const result = try db.oneAlloc(Text, testing.allocator, "SELECT myText()", .{}, .{});
try testing.expect(result != null);
try testing.expectEqualStrings("foobar", result.?.data);
testing.allocator.free(result.?.data);
}
{
try db.createScalarFunction(
"myBlob",
struct {
fn run() Blob {
return Blob{ .data = "barbaz" };
}
}.run,
.{},
);
const result = try db.oneAlloc(Blob, testing.allocator, "SELECT myBlob()", .{}, .{});
try testing.expect(result != null);
try testing.expectEqualStrings("barbaz", result.?.data);
testing.allocator.free(result.?.data);
}
}
test "sqlite: create aggregate function" {
var db = try getTestDb();
defer db.deinit();
var rand = std.rand.DefaultPrng.init(@intCast(u64, std.time.milliTimestamp()));
// Create an aggregate function working with a MyContext
const MyContext = struct {
sum: u32,
};
var my_ctx = MyContext{ .sum = 0 };
try db.createAggregateFunction(
"mySum",
&my_ctx,
struct {
fn step(ctx: *MyContext, input: u32) void {
ctx.sum += input;
}
}.step,
struct {
fn finalize(ctx: *MyContext) u32 {
return ctx.sum;
}
}.finalize,
.{},
);
// Initialize some data
try db.exec("CREATE TABLE view(id integer PRIMARY KEY, nb integer)", .{}, .{});
var i: usize = 0;
var exp: usize = 0;
while (i < 20) : (i += 1) {
const val = rand.random().intRangeAtMost(u32, 0, 5205905);
exp += val;
try db.exec("INSERT INTO view(nb) VALUES(?{u32})", .{}, .{val});
}
// Get the sum and check the result
var diags = Diagnostics{};
const result = db.one(
usize,
"SELECT mySum(nb) FROM view",
.{ .diags = &diags },
.{},
) catch |err| {
debug.print("err: {}\n", .{diags});
return err;
};
try testing.expect(result != null);
try testing.expectEqual(@as(usize, exp), result.?);
}
test "sqlite: empty slice" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
var list = std.ArrayList(u8).init(arena.allocator());
const ptr = list.toOwnedSlice();
try db.exec("INSERT INTO article(author_id, data) VALUES(?, ?)", .{}, .{ 1, ptr });
// Read into an array
{
var stmt = try db.prepare("SELECT data FROM article");
defer stmt.deinit();
const row = try stmt.one(
struct {
data: [128:0]u8,
},
.{},
.{},
);
try testing.expect(row != null);
try testing.expectEqualSlices(u8, "", mem.sliceTo(&row.?.data, 0));
}
// Read into an allocated slice
{
var stmt = try db.prepare("SELECT data FROM article");
defer stmt.deinit();
const row = try stmt.oneAlloc(
struct {
data: []const u8,
},
arena.allocator(),
.{},
.{},
);
try testing.expect(row != null);
try testing.expectEqualSlices(u8, "", row.?.data);
}
// Read into a Text
{
var stmt = try db.prepare("SELECT data FROM article");
defer stmt.deinit();
const row = try stmt.oneAlloc(
struct {
data: Text,
},
arena.allocator(),
.{},
.{},
);
try testing.expect(row != null);
try testing.expectEqualSlices(u8, "", row.?.data.data);
}
}
test "sqlite: fuzzer found crashes" {
const test_cases = &[_]struct {
input: []const u8,
exp_error: anyerror,
}{
.{
.input = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00CREATE TABLE \x80\x00\x00\x00ar(Wb)\x01",
.exp_error = error.SQLiteError,
},
.{
.input = "SELECT?",
.exp_error = error.ExecReturnedData,
},
};
inline for (test_cases) |tc| {
var db = try getTestDb();
defer db.deinit();
try testing.expectError(tc.exp_error, db.execDynamic(tc.input, .{}, .{}));
}
}
test "tagged union" {
var db = try getTestDb();
defer db.deinit();
try addTestData(&db);
const Foobar = union(enum) {
name: []const u8,
age: usize,
};
try db.exec("CREATE TABLE foobar(key TEXT, value ANY)", .{}, .{});
var foobar = Foobar{ .name = "hello" };
{
try db.exec("INSERT INTO foobar(key, value) VALUES($key, $value)", .{}, .{
.key = std.meta.tagName(std.meta.activeTag(foobar)),
.value = foobar,
});
var arena = heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const result = try db.oneAlloc(
struct {
key: []const u8,
value: []const u8,
},
arena.allocator(),
"SELECT key, value FROM foobar WHERE key = $key",
.{},
.{
std.meta.tagName(std.meta.activeTag(foobar)),
},
);
try testing.expect(result != null);
try testing.expectEqualStrings("name", result.?.key);
try testing.expectEqualStrings(foobar.name, result.?.value);
}
{
foobar = Foobar{ .age = 204 };
try db.exec("INSERT INTO foobar(key, value) VALUES($key, $value)", .{}, .{
.key = std.meta.tagName(std.meta.activeTag(foobar)),
.value = foobar,
});
var arena = heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const result = try db.oneAlloc(
struct {
key: []const u8,
value: usize,
},
arena.allocator(),
"SELECT key, value FROM foobar WHERE key = $key",
.{},
.{
std.meta.tagName(std.meta.activeTag(foobar)),
},
);
try testing.expect(result != null);
try testing.expectEqualStrings("age", result.?.key);
try testing.expectEqual(foobar.age, result.?.value);
}
}
|
sqlite.zig
|
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const heap = std.heap;
const Tree = @import("tree.zig").Tree;
const o = @import("ops.zig");
const Op = o.Op;
const OpTag = o.OpTag;
const DB = @import("db.zig").RocksDataBbase;
const root_key = @import("db.zig").root_key;
const Hash = @import("hash.zig").H;
const Commiter = @import("commit.zig").Commiter;
const LinkTag = @import("link.zig").LinkTag;
const U = @import("util.zig");
pub const Merk = struct {
tree: ?*Tree = null,
pub var db: ?DB = null;
pub var stack_allocator: *Allocator = testing.allocator;
pub var heap_allocator: ?heap.ArenaAllocator = null;
pub fn init(allocator: *Allocator, name: ?[]const u8) !Merk {
Merk.stack_allocator = allocator;
var _allocator = try allocator.create(Allocator);
_allocator = heap.page_allocator;
Merk.heap_allocator = heap.ArenaAllocator.init(_allocator);
Merk.db = try DB.init(name);
var merk: Merk = Merk{ .tree = null };
var buf: [o.BatchKeyLimit]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
const top_key_len = try Merk.db.?.read(root_key, fbs.writer());
if (top_key_len == 0) return merk;
var tree = Tree.fetchTrees(Merk.db, fbs.getWritten(), Commiter.DafaultLevels);
merk.tree = tree;
return merk;
}
pub fn deinit(self: Merk) void {
if (Merk.heap_allocator) |arena| arena.deinit();
if (Merk.db) |d| d.deinit();
}
pub fn rootHash(self: *Merk) Hash {
if (self.tree) |tree| {
return tree.hash();
} else {
return Hash.zeroHash();
}
}
pub fn apply(self: *Merk, batch: []Op) !void {
var pre_key: []const u8 = "";
if (batch.len > o.BatcSizeLimit) return error.ExceedBatchSizeLimit;
for (batch) |op| {
if (op.val.len > o.BatchValueLimit) return error.ExeceedBatchValueLimit;
if (std.mem.lessThan(u8, op.key, pre_key)) {
std.debug.print("keys in batch must be sorted\n", .{});
return error.InvalidOrder;
} else if (std.mem.eql(u8, op.key, pre_key)) {
std.debug.print("keys in batch must be unique, {}\n", .{op.key});
return error.Invalid;
}
pre_key = op.key;
}
try self.applyUnchecked(batch);
}
pub fn applyUnchecked(self: *Merk, batch: []Op) !void {
self.tree = try o.applyTo(self.tree, batch);
}
pub fn commit(self: *Merk) !void {
var commiter: Commiter = undefined;
if (self.tree) |tree| {
commiter = try Commiter.init(Merk.db.?, tree.height());
tree.commit(&commiter);
commiter.put(root_key, tree.key());
} else {
// TODO: delete root key
}
try commiter.commit();
}
pub fn get(self: *Merk, output: []u8, key: []const u8) usize {
var tree = Tree.fetchTree(null, key);
const allocator = &Merk.heap_allocator.?.allocator;
defer allocator.destroy(tree);
var val = tree.value();
std.mem.copy(u8, output, val);
return val.len;
}
};
test "init" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var merk = try Merk.init(&arena.allocator, "dbtest");
defer merk.deinit();
}
test "apply" {
var merk: *Merk = undefined;
var op0 = Op{ .op = OpTag.Put, .key = "key0", .val = "value" };
var op1 = Op{ .op = OpTag.Put, .key = "key1", .val = "value" };
var op2 = Op{ .op = OpTag.Put, .key = "key2", .val = "value" };
var batch1 = [_]Op{ op0, op2, op1 };
testing.expectError(error.InvalidOrder, merk.apply(&batch1));
var batch2 = [_]Op{ op0, op2, op2 };
testing.expectError(error.Invalid, merk.apply(&batch2));
}
test "apply and commit and fetch" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var merk = try Merk.init(&arena.allocator, "dbtest");
defer Merk.db.?.destroy("dbtest");
defer merk.deinit();
merk.tree = null;
// apply
var op0 = Op{ .op = OpTag.Put, .key = "key0", .val = "value0" };
var op1 = Op{ .op = OpTag.Put, .key = "key1", .val = "value1" };
var op2 = Op{ .op = OpTag.Put, .key = "key2", .val = "value2" };
var op3 = Op{ .op = OpTag.Put, .key = "key3", .val = "value3" };
var op4 = Op{ .op = OpTag.Put, .key = "key4", .val = "value4" };
var op5 = Op{ .op = OpTag.Put, .key = "key5", .val = "value5" };
var op6 = Op{ .op = OpTag.Put, .key = "key6", .val = "value6" };
var op7 = Op{ .op = OpTag.Put, .key = "key7", .val = "value7" };
var op8 = Op{ .op = OpTag.Put, .key = "key8", .val = "value8" };
var op9 = Op{ .op = OpTag.Put, .key = "key9", .val = "value9" };
var batch = [_]Op{ op0, op1, op2, op3, op4, op5, op6, op7, op8, op9 };
try merk.apply(&batch);
testing.expectEqualSlices(u8, merk.tree.?.key(), "key5");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.key(), "key2");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(true).?.key(), "key1");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(false).?.key(), "key4");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(false).?.child(true).?.key(), "key3");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(true).?.child(true).?.key(), "key0");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.key(), "key8");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(true).?.key(), "key7");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(true).?.child(true).?.key(), "key6");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(false).?.key(), "key9");
// commit
try merk.commit();
testing.expect(merk.tree.?.verify());
// testing.expectEqual(@as(LinkTag, merk.tree.?.child(true).?.link(true).?), .Pruned);
// testing.expectEqual(@as(LinkTag, merk.tree.?.child(true).?.link(false).?), .Pruned);
// testing.expectEqual(@as(LinkTag, merk.tree.?.child(false).?.link(true).?), .Pruned);
// testing.expectEqual(@as(LinkTag, merk.tree.?.child(false).?.link(false).?), .Pruned);
// top key
var buf: [o.BatchKeyLimit]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
_ = try Merk.db.?.read(root_key, fbs.writer());
var top_key = fbs.getWritten();
testing.expectEqualSlices(u8, top_key, merk.tree.?.key());
// fetch
var tree = Tree.fetchTrees(Merk.db, top_key, Commiter.DafaultLevels);
testing.expectEqualSlices(u8, merk.tree.?.key(), "key5");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.key(), "key2");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.value(), "value2");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(true).?.key(), "key1");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(false).?.key(), "key4");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(false).?.child(true).?.key(), "key3");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(false).?.child(true).?.value(), "value3");
testing.expectEqualSlices(u8, merk.tree.?.child(true).?.child(true).?.child(true).?.key(), "key0");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.key(), "key8");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(true).?.key(), "key7");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(true).?.child(true).?.key(), "key6");
testing.expectEqualSlices(u8, merk.tree.?.child(false).?.child(false).?.key(), "key9");
// get
var output: [1024]u8 = undefined;
var size = merk.get(&output, "key0");
testing.expectEqualSlices(u8, output[0..size], "value0");
}
pub fn main() !void {
var buf: [65536]u8 = undefined;
var buffer = heap.FixedBufferAllocator.init(&buf);
var arena = heap.ArenaAllocator.init(&buffer.allocator);
defer arena.deinit();
var merk = try Merk.init(&arena.allocator);
defer merk.deinit();
std.debug.print("merk.tree: {}\n", .{merk.tree});
}
|
src/merk.zig
|
const std = @import("std");
const arg_matches = @import("arg_matches.zig");
const Command = @import("Command.zig");
const Arg = @import("Arg.zig");
const ArgvIterator = @import("ArgvIterator.zig");
const MatchedArg = @import("MatchedArg.zig");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const ArgMatches = arg_matches.ArgMatches;
// TODO: Clean up errors
pub const Error = error{
UnknownArg,
UnknownCommand,
UnknownFlag,
CommandArgumentNotProvided,
MissingCommandSubCommand,
ValueIsNotInAllowedValues,
UnneededAttachedValue,
UnneededEmptyAttachedValue,
ArgValueNotProvided,
EmptyArgValueNotAllowed,
} || Allocator.Error;
const InternalError = error{
AttachedValueNotConsumed,
} || Error;
pub fn parse(
allocator: Allocator,
argv: []const [:0]const u8,
cmd: *const Command,
) Error!ArgMatches {
var argv_iter = ArgvIterator.init(argv);
var matches = ArgMatches.init(allocator);
errdefer matches.deinit();
if (cmd.setting.takes_value) {
for (cmd.args.items) |arg| {
if ((arg.short_name == null) and (arg.long_name == null)) {
var parsed_arg = consumeArgValue(allocator, &arg, null, &argv_iter) catch |err| switch (err) {
InternalError.AttachedValueNotConsumed => unreachable,
InternalError.ArgValueNotProvided => break,
else => |e| return e,
};
try matches.putMatchedArg(parsed_arg);
}
}
if (cmd.setting.arg_required and (matches.args.count() == 0)) {
return Error.CommandArgumentNotProvided;
}
}
while (argv_iter.next()) |*raw_arg| {
if (raw_arg.isShort() or raw_arg.isLong()) {
if (cmd.args.items.len == 0)
return Error.UnknownArg;
try parseArg(allocator, cmd.args.items, raw_arg, &argv_iter, &matches);
} else {
if (cmd.subcommands.items.len == 0)
return Error.UnknownCommand;
const subcmd = try parseSubCommand(allocator, cmd.subcommands.items, raw_arg.name, &argv_iter);
try matches.setSubcommand(subcmd);
}
}
if (cmd.setting.subcommand_required and matches.subcommand == null) {
return Error.MissingCommandSubCommand;
}
return matches;
}
pub fn parseArg(
allocator: Allocator,
valid_args: []const Arg,
raw_arg: *ArgvIterator.RawArg,
argv_iter: *ArgvIterator,
matches: *ArgMatches,
) Error!void {
if (raw_arg.isShort()) {
if (raw_arg.toShort()) |*short_arg| {
const parsed_args = try parseShortArg(allocator, valid_args, short_arg, argv_iter);
for (parsed_args) |parsed_arg| {
try matches.putMatchedArg(parsed_arg);
}
}
} else if (raw_arg.isLong()) {
if (raw_arg.toLong()) |*long_arg| {
const parsed_arg = try parseLongArg(allocator, valid_args, long_arg, argv_iter);
try matches.putMatchedArg(parsed_arg);
}
}
}
fn parseShortArg(
allocator: Allocator,
valid_args: []const Arg,
short_args: *ArgvIterator.ShortFlags,
argv_iter: *ArgvIterator,
) Error![]const MatchedArg {
var parsed_args = std.ArrayList(MatchedArg).init(allocator);
errdefer parsed_args.deinit();
while (short_args.nextFlag()) |short_flag| {
if (findArgByShortName(valid_args, short_flag)) |arg| {
if (!arg.settings.takes_value) {
if (short_args.fixed_value) |val| {
if (val.len >= 1) {
return Error.UnneededAttachedValue;
} else {
return Error.UnneededEmptyAttachedValue;
}
}
try parsed_args.append(MatchedArg.initWithoutValue(arg.name));
continue;
}
const value = short_args.nextValue();
const parsed_arg = consumeArgValue(allocator, arg, value, argv_iter) catch |err| switch (err) {
InternalError.AttachedValueNotConsumed => {
// If attached value is not consumed, we may have more flags to parse
short_args.rollbackValue();
try parsed_args.append(MatchedArg.initWithoutValue(arg.name));
continue;
},
else => |e| return e,
};
try parsed_args.append(parsed_arg);
} else {
return Error.UnknownFlag;
}
}
return parsed_args.toOwnedSlice();
}
fn findArgByShortName(valid_args: []const Arg, short_name: u8) ?*const Arg {
for (valid_args) |*valid_arg| {
if (valid_arg.short_name) |valid_short_name| {
if (valid_short_name == short_name) return valid_arg;
}
}
return null;
}
fn parseLongArg(
allocator: Allocator,
valid_args: []const Arg,
long_arg: *ArgvIterator.LongFlag,
argv_iter: *ArgvIterator,
) Error!MatchedArg {
if (findArgByLongName(valid_args, long_arg.name)) |arg| {
if (!arg.settings.takes_value) {
if (long_arg.value != null) {
return Error.UnneededAttachedValue;
} else {
return MatchedArg.initWithoutValue(arg.name);
}
}
const parsed_arg = consumeArgValue(allocator, arg, long_arg.value, argv_iter) catch |err| switch (err) {
InternalError.AttachedValueNotConsumed => {
return MatchedArg.initWithoutValue(arg.name);
},
else => |e| return e,
};
return parsed_arg;
} else {
return Error.UnknownFlag;
}
}
fn findArgByLongName(valid_args: []const Arg, long_name: []const u8) ?*const Arg {
for (valid_args) |*valid_arg| {
if (valid_arg.long_name) |valid_long_name| {
if (mem.eql(u8, valid_long_name, long_name))
return valid_arg;
}
}
return null;
}
pub fn consumeArgValue(
allocator: Allocator,
arg: *const Arg,
attached_value: ?[]const u8,
argv_iter: *ArgvIterator,
) InternalError!MatchedArg {
if (arg.min_values) |min_values| {
if (min_values == 0) {
if (attached_value != null) {
return InternalError.AttachedValueNotConsumed;
} else if (arg.settings.allow_empty_value) {
return MatchedArg.initWithSingleValue(arg.name, " ");
}
}
}
if (attached_value) |val| {
return processValue(allocator, arg, val, true, null);
} else {
const value = argv_iter.nextValue() orelse return Error.ArgValueNotProvided;
return processValue(allocator, arg, value, false, argv_iter);
}
}
pub fn processValue(
allocator: Allocator,
arg: *const Arg,
value: []const u8,
is_attached_value: bool,
argv_iter: ?*ArgvIterator,
) Error!MatchedArg {
if (arg.values_delimiter) |delimiter| {
var values_iter = mem.split(u8, value, delimiter);
var values = std.ArrayList([]const u8).init(allocator);
errdefer values.deinit();
while (values_iter.next()) |val| {
const _val = @as([]const u8, val);
if ((_val.len == 0) and !(arg.settings.allow_empty_value))
return Error.EmptyArgValueNotAllowed;
if (!arg.verifyValueInAllowedValues(_val))
return Error.ValueIsNotInAllowedValues;
try values.append(_val);
}
// zig fmt: off
if (mem.containsAtLeast(u8, value, 1, delimiter)
or arg.remainingValuesToConsume(values.items.len) == 0) {
// zig fmt: on
return MatchedArg.initWithManyValues(arg.name, values);
} else {
values.deinit();
}
}
if (is_attached_value) {
// Ignore multiples values seperated with delimiter
// if have
//
// For ex: -f=v1,v2
// flag = f
// value = v1,v2
return MatchedArg.initWithSingleValue(arg.name, value);
} else {
// we have given only one value hence we pass 1 here
const num_remaining_values = arg.remainingValuesToConsume(1);
if (num_remaining_values == 0) {
return MatchedArg.initWithSingleValue(arg.name, value);
} else {
var index: usize = 1;
var values = std.ArrayList([]const u8).init(allocator);
errdefer values.deinit();
try values.append(value);
// consume each value using ArgvIterator
while (index <= num_remaining_values) : (index += 1) {
const _value = argv_iter.?.nextValue() orelse break;
if ((_value.len == 0) and !(arg.settings.allow_empty_value))
return Error.EmptyArgValueNotAllowed;
if (!arg.verifyValueInAllowedValues(_value))
return Error.ValueIsNotInAllowedValues;
try values.append(_value);
}
return MatchedArg.initWithManyValues(arg.name, values);
}
}
}
pub fn parseSubCommand(
allocator: Allocator,
valid_subcmds: []const Command,
provided_subcmd: []const u8,
argv_iterator: *ArgvIterator,
) Error!arg_matches.SubCommand {
for (valid_subcmds) |valid_subcmd| {
if (mem.eql(u8, valid_subcmd.name, provided_subcmd)) {
// zig fmt: off
if (valid_subcmd.setting.takes_value
or valid_subcmd.args.items.len >= 1
or valid_subcmd.subcommands.items.len >= 1) {
// zig fmt: on
const subcmd_argv = argv_iterator.rest() orelse return Error.CommandArgumentNotProvided;
const subcmd_argmatches = try parse(allocator, subcmd_argv, &valid_subcmd);
return arg_matches.SubCommand.initWithArg(valid_subcmd.name, subcmd_argmatches);
}
return arg_matches.SubCommand.initWithoutArg(valid_subcmd.name);
}
}
return Error.UnknownCommand;
}
|
src/parser.zig
|
const fmath = @import("index.zig");
fn frexp_result(comptime T: type) -> type {
struct {
significand: T,
exponent: i32,
}
}
pub const frexp32_result = frexp_result(f32);
pub const frexp64_result = frexp_result(f64);
pub fn frexp(x: var) -> frexp_result(@typeOf(x)) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(frexp32, x),
f64 => @inlineCall(frexp64, x),
else => @compileError("frexp not implemented for " ++ @typeName(T)),
}
}
fn frexp32(x: f32) -> frexp32_result {
var result: frexp32_result = undefined;
var y = @bitCast(u32, x);
const e = i32(y >> 23) & 0xFF;
if (e == 0) {
if (x != 0) {
// subnormal
result = frexp32(x * 0x1.0p64);
result.exponent -= 64;
} else {
// frexp(+-0) = (+-0, 0)
result.significand = x;
result.exponent = 0;
}
return result;
} else if (e == 0xFF) {
// frexp(nan) = (nan, 0)
result.significand = x;
result.exponent = 0;
return result;
}
result.exponent = e - 0x7E;
y &= 0x807FFFFF;
y |= 0x3F000000;
result.significand = @bitCast(f32, y);
result
}
fn frexp64(x: f64) -> frexp64_result {
var result: frexp64_result = undefined;
var y = @bitCast(u64, x);
const e = i32(y >> 52) & 0x7FF;
if (e == 0) {
if (x != 0) {
// subnormal
result = frexp64(x * 0x1.0p64);
result.exponent -= 64;
} else {
// frexp(+-0) = (+-0, 0)
result.significand = x;
result.exponent = 0;
}
return result;
} else if (e == 0x7FF) {
// frexp(nan) = (nan, 0)
result.significand = x;
return result;
}
result.exponent = e - 0x3FE;
y &= 0x800FFFFFFFFFFFFF;
y |= 0x3FE0000000000000;
result.significand = @bitCast(f64, y);
result
}
test "frexp" {
const a = frexp(f32(1.3));
const b = frexp32(1.3);
fmath.assert(a.significand == b.significand and a.exponent == b.exponent);
const c = frexp(f64(1.3));
const d = frexp64(1.3);
fmath.assert(c.significand == d.significand and c.exponent == d.exponent);
}
test "frexp32" {
const epsilon = 0.000001;
var r: frexp32_result = undefined;
r = frexp32(1.3);
fmath.assert(fmath.approxEq(f32, r.significand, 0.65, epsilon) and r.exponent == 1);
r = frexp32(78.0234);
fmath.assert(fmath.approxEq(f32, r.significand, 0.609558, epsilon) and r.exponent == 7);
}
test "frexp64" {
const epsilon = 0.000001;
var r: frexp64_result = undefined;
r = frexp64(1.3);
fmath.assert(fmath.approxEq(f64, r.significand, 0.65, epsilon) and r.exponent == 1);
r = frexp64(78.0234);
fmath.assert(fmath.approxEq(f64, r.significand, 0.609558, epsilon) and r.exponent == 7);
}
|
src/frexp.zig
|
pub const AVRF_MAX_TRACES = @as(u32, 32);
//--------------------------------------------------------------------------------
// Section: Types (12)
//--------------------------------------------------------------------------------
pub const VERIFIER_ENUM_RESOURCE_FLAGS = enum(u32) {
DONT_RESOLVE_TRACES = 2,
SUSPEND = 1,
_,
pub fn initFlags(o: struct {
DONT_RESOLVE_TRACES: u1 = 0,
SUSPEND: u1 = 0,
}) VERIFIER_ENUM_RESOURCE_FLAGS {
return @intToEnum(VERIFIER_ENUM_RESOURCE_FLAGS,
(if (o.DONT_RESOLVE_TRACES == 1) @enumToInt(VERIFIER_ENUM_RESOURCE_FLAGS.DONT_RESOLVE_TRACES) else 0)
| (if (o.SUSPEND == 1) @enumToInt(VERIFIER_ENUM_RESOURCE_FLAGS.SUSPEND) else 0)
);
}
};
pub const AVRF_ENUM_RESOURCES_FLAGS_DONT_RESOLVE_TRACES = VERIFIER_ENUM_RESOURCE_FLAGS.DONT_RESOLVE_TRACES;
pub const AVRF_ENUM_RESOURCES_FLAGS_SUSPEND = VERIFIER_ENUM_RESOURCE_FLAGS.SUSPEND;
pub const AVRF_BACKTRACE_INFORMATION = extern struct {
Depth: u32,
Index: u32,
ReturnAddresses: [32]u64,
};
pub const eUserAllocationState = enum(i32) {
Unknown = 0,
Busy = 1,
Free = 2,
};
pub const AllocationStateUnknown = eUserAllocationState.Unknown;
pub const AllocationStateBusy = eUserAllocationState.Busy;
pub const AllocationStateFree = eUserAllocationState.Free;
pub const eHeapAllocationState = enum(i32) {
FullPageHeap = 1073741824,
Metadata = -2147483648,
StateMask = -65536,
};
pub const HeapFullPageHeap = eHeapAllocationState.FullPageHeap;
pub const HeapMetadata = eHeapAllocationState.Metadata;
pub const HeapStateMask = eHeapAllocationState.StateMask;
pub const eHeapEnumerationLevel = enum(i32) {
Everything = 0,
Stop = -1,
};
pub const HeapEnumerationEverything = eHeapEnumerationLevel.Everything;
pub const HeapEnumerationStop = eHeapEnumerationLevel.Stop;
pub const AVRF_HEAP_ALLOCATION = extern struct {
HeapHandle: u64,
UserAllocation: u64,
UserAllocationSize: u64,
Allocation: u64,
AllocationSize: u64,
UserAllocationState: u32,
HeapState: u32,
HeapContext: u64,
BackTraceInformation: ?*AVRF_BACKTRACE_INFORMATION,
};
pub const eHANDLE_TRACE_OPERATIONS = enum(i32) {
Unused = 0,
OPEN = 1,
CLOSE = 2,
BADREF = 3,
};
pub const OperationDbUnused = eHANDLE_TRACE_OPERATIONS.Unused;
pub const OperationDbOPEN = eHANDLE_TRACE_OPERATIONS.OPEN;
pub const OperationDbCLOSE = eHANDLE_TRACE_OPERATIONS.CLOSE;
pub const OperationDbBADREF = eHANDLE_TRACE_OPERATIONS.BADREF;
pub const AVRF_HANDLE_OPERATION = extern struct {
Handle: u64,
ProcessId: u32,
ThreadId: u32,
OperationType: u32,
Spare0: u32,
BackTraceInformation: AVRF_BACKTRACE_INFORMATION,
};
pub const eAvrfResourceTypes = enum(i32) {
HeapAllocation = 0,
HandleTrace = 1,
Max = 2,
};
pub const AvrfResourceHeapAllocation = eAvrfResourceTypes.HeapAllocation;
pub const AvrfResourceHandleTrace = eAvrfResourceTypes.HandleTrace;
pub const AvrfResourceMax = eAvrfResourceTypes.Max;
pub const AVRF_RESOURCE_ENUMERATE_CALLBACK = fn(
ResourceDescription: ?*anyopaque,
EnumerationContext: ?*anyopaque,
EnumerationLevel: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const AVRF_HEAPALLOCATION_ENUMERATE_CALLBACK = fn(
HeapAllocation: ?*AVRF_HEAP_ALLOCATION,
EnumerationContext: ?*anyopaque,
EnumerationLevel: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const AVRF_HANDLEOPERATION_ENUMERATE_CALLBACK = fn(
HandleOperation: ?*AVRF_HANDLE_OPERATION,
EnumerationContext: ?*anyopaque,
EnumerationLevel: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// Section: Functions (1)
//--------------------------------------------------------------------------------
pub extern "verifier" fn VerifierEnumerateResource(
Process: ?HANDLE,
Flags: VERIFIER_ENUM_RESOURCE_FLAGS,
ResourceType: eAvrfResourceTypes,
ResourceCallback: ?AVRF_RESOURCE_ENUMERATE_CALLBACK,
EnumerationContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// 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 (1)
//--------------------------------------------------------------------------------
const HANDLE = @import("../foundation.zig").HANDLE;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "AVRF_RESOURCE_ENUMERATE_CALLBACK")) { _ = AVRF_RESOURCE_ENUMERATE_CALLBACK; }
if (@hasDecl(@This(), "AVRF_HEAPALLOCATION_ENUMERATE_CALLBACK")) { _ = AVRF_HEAPALLOCATION_ENUMERATE_CALLBACK; }
if (@hasDecl(@This(), "AVRF_HANDLEOPERATION_ENUMERATE_CALLBACK")) { _ = AVRF_HANDLEOPERATION_ENUMERATE_CALLBACK; }
@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/system/application_verifier.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
pub const ALU = struct {
const NUM_VARS = 4;
const NUM_STAGES = 14;
const NUM_INSTR = 10;
const INSTR_PER_STAGE = 18;
pub const OP = enum {
INP,
ADD,
MUL,
DIV,
MOD,
EQL,
pub fn parse(str: []const u8) OP {
if (std.mem.eql(u8, str, "inp")) return .INP;
if (std.mem.eql(u8, str, "add")) return .ADD;
if (std.mem.eql(u8, str, "mul")) return .MUL;
if (std.mem.eql(u8, str, "div")) return .DIV;
if (std.mem.eql(u8, str, "mod")) return .MOD;
if (std.mem.eql(u8, str, "eql")) return .EQL;
unreachable;
}
};
pub const Instruction = struct {
op: OP,
v0: usize,
v1: usize,
n1: isize,
pub fn init(op: OP, v0: usize, v1: usize, n1: isize) Instruction {
var self = Instruction{
.op = op,
.v0 = v0,
.v1 = v1,
.n1 = n1,
};
return self;
}
};
pub const Simulator = struct {
code: [1024]Instruction,
nc: usize,
vars: [NUM_VARS]isize,
pub fn init() Simulator {
var self = Simulator{
.code = undefined,
.nc = 0,
.vars = [_]isize{0} ** NUM_VARS,
};
return self;
}
pub fn deinit(_: *Simulator) void {}
pub fn get_var(self: Simulator, v: u8) isize {
return self.vars[v - 'w'];
}
pub fn reset(self: *Simulator, vars: [NUM_VARS]isize) void {
self.vars = vars;
}
pub fn clear(self: *Simulator) void {
self.reset([_]isize{0} ** NUM_VARS);
}
pub fn run(self: *Simulator, input: []const u8) bool {
var pi: usize = 0;
var pc: usize = 0;
while (pc < self.nc) : (pc += 1) {
const i = self.code[pc];
switch (i.op) {
.INP => {
self.vars[i.v0] = input[pi] - '0';
pi += 1;
},
.ADD => {
const val = if (i.v1 >= NUM_VARS) i.n1 else self.vars[i.v1];
self.vars[i.v0] += val;
},
.MUL => {
const val = if (i.v1 >= NUM_VARS) i.n1 else self.vars[i.v1];
self.vars[i.v0] *= val;
},
.DIV => {
const val = if (i.v1 >= NUM_VARS) i.n1 else self.vars[i.v1];
if (val == 0) return false;
self.vars[i.v0] = @divTrunc(self.vars[i.v0], val);
},
.MOD => {
if (self.vars[i.v0] < 0) return false;
const val = if (i.v1 >= NUM_VARS) i.n1 else self.vars[i.v1];
if (val <= 0) return false;
self.vars[i.v0] = @rem(self.vars[i.v0], val);
},
.EQL => {
const val = if (i.v1 >= NUM_VARS) i.n1 else self.vars[i.v1];
self.vars[i.v0] = if (self.vars[i.v0] == val) 1 else 0;
},
}
// std.debug.warn("PC {}: VARS {d}\n", .{ pc, self.vars });
}
return true;
}
};
power10: [NUM_STAGES]isize,
values: [NUM_STAGES][NUM_INSTR]isize,
cache: [NUM_STAGES]std.AutoHashMap(isize, isize),
stage: usize,
sim: Simulator,
pub fn init() ALU {
var self = ALU{
.power10 = undefined,
.values = undefined,
.cache = undefined,
.stage = 0,
.sim = Simulator.init(),
};
for (self.cache) |*c| {
c.* = std.AutoHashMap(isize, isize).init(allocator);
}
for (self.power10) |*p, j| {
if (j == 0) {
p.* = 1;
continue;
}
p.* = 10 * self.power10[j - 1];
}
return self;
}
pub fn deinit(self: *ALU) void {
self.sim.deinit();
for (self.cache) |*c| {
c.*.deinit();
}
}
pub fn process_line(self: *ALU, data: []const u8) !void {
var op: OP = undefined;
var v0: usize = 0;
var v1: usize = 0;
var n1: isize = 0;
var p: usize = 0;
var it = std.mem.tokenize(u8, data, " ");
while (it.next()) |str| : (p += 1) {
if (p == 0) {
op = OP.parse(str);
continue;
}
if (p == 1 or p == 2) {
if (str[0] == '-' or (str[0] >= '0' and str[0] <= '9')) {
if (p == 1) unreachable;
n1 = std.fmt.parseInt(isize, str, 10) catch unreachable;
v1 = 255;
} else {
if (p == 1) {
v0 = str[0] - 'w';
}
if (p == 2) {
v1 = str[0] - 'w';
n1 = 0;
}
}
}
if (p == 1 and op != .INP) continue;
if (op == .INP) self.stage += 1;
self.sim.code[self.sim.nc] = Instruction.init(op, v0, v1, n1);
// std.debug.warn("INSTRUCTION {}: {}\n", .{ self.sim.nc, self.sim.code[self.sim.nc] });
const k: usize = switch (self.sim.nc % INSTR_PER_STAGE) {
1 => 0,
3 => 1,
4 => 2,
5 => 3,
7 => 4,
8 => 5,
9 => 6,
11 => 7,
13 => 8,
15 => 9,
else => std.math.maxInt(usize),
};
if (k != std.math.maxInt(usize)) self.values[self.stage - 1][k] = n1;
self.sim.nc += 1;
continue;
}
}
const SearchErrors = error{OutOfMemory};
pub fn search_max(self: *ALU) SearchErrors!usize {
const found = try self.search_from(0, 0, 9, -1, -1);
if (found < 0) return 0;
return @intCast(usize, found);
}
pub fn search_min(self: *ALU) SearchErrors!usize {
const found = try self.search_from(0, 0, 1, 10, 1);
if (found < 0) return 0;
return @intCast(usize, found);
}
pub fn search_from(self: *ALU, index: usize, z: isize, w0: isize, w1: isize, dw: isize) SearchErrors!isize {
// reached the end!
if (index == NUM_STAGES) {
if (z == 0) {
return 0; // yay!
}
return -1;
}
// read cache
const entry = self.cache[index].getEntry(z);
if (entry) |e| return e.value_ptr.*;
var w: isize = w0;
while (w != w1) : (w += dw) {
var nx = z;
if (nx < 0 or self.values[index][1] <= 0) continue;
nx = @rem(nx, self.values[index][1]);
if (self.values[index][2] == 0) continue;
var nz = @divTrunc(z, self.values[index][2]);
nx += self.values[index][3];
nx = if (nx == w) 1 else 0;
nx = if (nx == self.values[index][4]) 1 else 0;
var ny = self.values[index][6];
ny *= nx;
ny += self.values[index][7];
nz *= ny;
ny *= self.values[index][8];
ny += w;
ny += self.values[index][9];
ny *= nx;
nz += ny;
const t = try self.search_from(index + 1, nz, w0, w1, dw);
if (t == -1) continue;
const v = t + w * self.power10[NUM_STAGES - 1 - index];
try self.cache[index].put(z, v);
return v;
}
// failed, remember and return
try self.cache[index].put(z, -1);
return -1;
}
};
test "sample part a small 1" {
const data: []const u8 =
\\inp x
\\mul x -1
;
var alu = ALU.init();
defer alu.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try alu.process_line(line);
}
const ok = alu.sim.run("7");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('x') == -7);
}
test "sample part a small 2" {
const data: []const u8 =
\\inp w
\\add z w
\\mod z 2
\\div w 2
\\add y w
\\mod y 2
\\div w 2
\\add x w
\\mod x 2
\\div w 2
\\mod w 2
;
var alu = ALU.init();
defer alu.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try alu.process_line(line);
}
{
alu.sim.clear();
const ok = alu.sim.run("9");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('w') == 1);
try testing.expect(alu.sim.get_var('x') == 0);
try testing.expect(alu.sim.get_var('y') == 0);
try testing.expect(alu.sim.get_var('z') == 1);
}
{
alu.sim.clear();
const ok = alu.sim.run("7");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('w') == 0);
try testing.expect(alu.sim.get_var('x') == 1);
try testing.expect(alu.sim.get_var('y') == 1);
try testing.expect(alu.sim.get_var('z') == 1);
}
{
alu.sim.clear();
const ok = alu.sim.run("4");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('w') == 0);
try testing.expect(alu.sim.get_var('x') == 1);
try testing.expect(alu.sim.get_var('y') == 0);
try testing.expect(alu.sim.get_var('z') == 0);
}
{
alu.sim.clear();
const ok = alu.sim.run("1");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('w') == 0);
try testing.expect(alu.sim.get_var('x') == 0);
try testing.expect(alu.sim.get_var('y') == 0);
try testing.expect(alu.sim.get_var('z') == 1);
}
{
alu.sim.clear();
const ok = alu.sim.run("0");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('w') == 0);
try testing.expect(alu.sim.get_var('x') == 0);
try testing.expect(alu.sim.get_var('y') == 0);
try testing.expect(alu.sim.get_var('z') == 0);
}
}
test "sample parts a & b" {
const data: []const u8 =
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 13
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 15
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 13
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 16
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 10
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 4
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 15
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 14
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -8
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 1
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -10
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 5
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 11
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 1
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -3
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 3
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 14
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 3
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -4
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 7
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 1
\\add x 14
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 5
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -5
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 13
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -8
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 3
\\mul y x
\\add z y
\\inp w
\\mul x 0
\\add x z
\\mod x 26
\\div z 26
\\add x -11
\\eql x w
\\eql x 0
\\mul y 0
\\add y 25
\\mul y x
\\add y 1
\\mul z y
\\mul y 0
\\add y w
\\add y 10
\\mul y x
\\add z y
;
var alu = ALU.init();
defer alu.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try alu.process_line(line);
}
{
alu.sim.clear();
const ok = alu.sim.run("51939397989999");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('z') == 0);
}
{
alu.sim.clear();
const ok = alu.sim.run("11717131211195");
try testing.expect(ok);
try testing.expect(alu.sim.get_var('z') == 0);
}
}
|
2021/p24/alu.zig
|
const std = @import("std");
/// There are n choose k ways to choose k elements from a set of n elements.
/// This iterator produces a binary representation of which k elements are chosen
/// calling `next()` on `NChooseK(u8).init(3,2)` will produce {0b011, 0b101, 0b110, null}
pub fn NChooseK(comptime T: type) type {
// this method is known as 'Gosper's Hack': http://programmingforinsomniacs.blogspot.com/2018/03/
return struct {
/// n: total number of elements in set
n: TLog2,
/// k: number of elements to choose (number of set bits at any point after calling `next()`)
k: TLog2,
set: T,
limit: T,
const Self = @This();
const TSigned = std.meta.Int(.signed, @typeInfo(T).Int.bits);
const TLog2 = std.math.Log2Int(T);
pub fn init(n: TLog2, k: TLog2) !Self {
if (n == 0 or k > n) return error.ArgumentBounds;
return Self{
.k = k,
.n = n,
.set = (@as(T, 1) << @intCast(TLog2, k)) - 1,
.limit = @as(T, 1) << @intCast(TLog2, n),
};
}
pub fn next(self: *Self) ?T {
// save and return the set at this point otherwise initial set is skipped
const result = self.set;
// prevent overflow when converting to signed
if (self.set >= std.math.maxInt(TSigned)) return null;
// compute next set value
// c is equal to the rightmost 1-bit in set.
const c = self.set & @bitCast(T, -@bitCast(TSigned, self.set));
if (c == 0) return null;
const r = self.set + c;
self.set = @divFloor(((r ^ self.set) >> 2), c) | r;
return if (result >= self.limit) null else result;
}
};
}
test "basic" {
const expecteds_bycount = [_][]const usize{
&.{ 0b01, 0b10 }, // n,k: 2,1
&.{ 0b011, 0b101, 0b110 }, // 3,2
&.{ 0b0111, 0b1011, 0b1101, 0b1110 }, // 4,3
&.{ 0b01111, 0b10111, 0b11011, 0b11101, 0b11110 }, // 5,4
&.{ 0b011111, 0b101111, 0b110111, 0b111011, 0b111101, 0b111110 }, // 6,5
};
for (expecteds_bycount) |expecteds, count_| {
const count = @intCast(u6, count_);
var it = try NChooseK(usize).init(count + 2, count + 1);
for (expecteds) |expected, i| {
const actual = it.next().?;
try std.testing.expectEqual(expected, actual);
}
try std.testing.expectEqual(@as(?usize, null), it.next());
}
}
test "edge cases" {
// n == 0
try std.testing.expectError(error.ArgumentBounds, NChooseK(usize).init(0, 1));
// k > n
try std.testing.expectError(error.ArgumentBounds, NChooseK(usize).init(1, 2));
// sanity check various types making sure x is always valid
const Ts = [_]type{ u3, u8, u16, u64, u65, u128 };
inline for (Ts) |T| {
var it = try NChooseK(T).init(std.math.log2_int(T, std.math.maxInt(T)), 1);
while (it.next()) |x| {
try std.testing.expect(@popCount(T, x) == 1);
}
}
}
const bigint = std.math.big.int;
pub const NChooseKBig = struct {
/// n: total number of elements in set
n: usize,
/// k: number of elements to choose (number of set bits at any point after calling `next()`)
k: usize,
set: bigint.Managed,
limit: bigint.Managed,
pub fn init(allocator: *std.mem.Allocator, n: usize, k: usize) !NChooseKBig {
if (n == 0 or k > n) return error.ArgumentBounds;
// set = 1 << k - 1;
var set = try bigint.Managed.initSet(allocator, 1);
try set.shiftLeft(set, k);
try set.addScalar(set.toConst(), -1);
// limit = 1 << n;
var limit = try bigint.Managed.initSet(allocator, 1);
try limit.shiftLeft(limit, n);
return NChooseKBig{
.k = k,
.n = n,
.set = set,
.limit = limit,
};
}
pub fn deinit(self: *NChooseKBig) void {
self.set.deinit();
self.limit.deinit();
}
pub fn next(self: *NChooseKBig) !?bigint.Managed {
// TODO: figure out how to eliminate some allocations
// save for return at end the set at this point otherwise initial set is skipped
var result = try self.set.clone();
// int c = set & -set; // c is equal to the rightmost 1-bit in set.
var c = try self.set.clone();
defer c.deinit();
for (c.limbs[0..c.len()]) |limb, i| {
// prevent overflow here. 1 << 63 is std.math.maxInt(isize) + 1.
// if we try to negate this value, overflow will happen.
// in this case we know the leftmost 1-bit is just 1 << 63
const x = if (limb == 1 << 63)
1 << 63
else
limb & @bitCast(usize, -@bitCast(isize, limb));
if (x > 0) {
try c.set(0);
c.limbs[i] = x;
c.setLen(i + 1);
break;
}
}
try c.bitAnd(self.set, c);
// this check for c == 0 may not be necessary.
// going to leave this here commented out incase of future problems.
// if (c.eqZero()) {
// result.deinit();
// return null;
// }
// const r = self.set + c;
// Find the rightmost 1-bit that can be moved left into a 0-bit. Move it left one.
var r = try bigint.Managed.init(self.set.allocator);
defer r.deinit();
try r.add(self.set.toConst(), c.toConst());
// set = (((r ^ set) >> 2) / c) | r;
var tmp = try bigint.Managed.init(self.set.allocator);
defer tmp.deinit();
// Xor’ng r and set returns a cluster of 1-bits representing the bits that were changed between set and r
try tmp.bitXor(r, self.set);
try tmp.shiftRight(tmp, 2);
var rem = try bigint.Managed.init(self.set.allocator);
// rem must be able to hold this many limbs or else divFloor below may fail
try rem.ensureCapacity(tmp.len() + 1);
defer rem.deinit();
// work around for result location bug (i think?) make a copy of tmp
// WARNING: do not remove tmp2. strange things will happen. the following division will produce
// something very strange, 101010.... when dividing 111111... by 1. possibly garbage.
var tmp2 = try tmp.clone();
defer tmp2.deinit();
try tmp.divFloor(&rem, tmp2.toConst(), c.toConst());
try self.set.bitOr(tmp, r);
const order = result.order(self.limit);
return if (order == .gt or order == .eq) blk: {
result.deinit();
break :blk null;
} else result;
}
};
test "basic big" {
const expecteds_bycount = [_][]const usize{
&.{ 0b01, 0b10 }, // n,k: 2,1
&.{ 0b011, 0b101, 0b110 }, // 3,2
&.{ 0b0111, 0b1011, 0b1101, 0b1110 }, // 4,3
&.{ 0b01111, 0b10111, 0b11011, 0b11101, 0b11110 }, // 5,4
&.{ 0b011111, 0b101111, 0b110111, 0b111011, 0b111101, 0b111110 }, // 6,5
};
for (expecteds_bycount) |expecteds, count| {
var it = try NChooseKBig.init(std.testing.allocator, count + 2, count + 1);
defer it.deinit();
for (expecteds) |expected, i| {
var actual = (try it.next()).?;
defer actual.deinit();
try std.testing.expectEqual(expected, try actual.to(usize));
}
try std.testing.expectEqual(@as(?bigint.Managed, null), try it.next());
}
}
test "256" {
const count = 256;
var it = try NChooseKBig.init(std.testing.allocator, count, count - 1);
defer it.deinit();
var i: usize = 0;
while (try it.next()) |*n| : (i += 1) {
n.deinit();
}
try std.testing.expectEqual(@as(usize, count), i);
}
|
src/misc.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;
const prefix = EncodingControl.prefix;
const prefix2 = EncodingControl.prefix2;
const hint = EncodingControl.encodingHint;
test "user prefixes" {
debugPrint(false);
const m16 = Machine.init(.x86_16);
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
{
testOpCtrl2(m64, prefix(.Lock), .MOV, reg(.RAX), memRm(.GS, .QWORD, .EAX, 0x11), "f0 65 67 48 8b 40 11");
testOpCtrl2(m64, prefix2(.Repne, .Lock), .MOV, reg(.RAX), memRm(.GS, .QWORD, .EAX, 0x11), "f2 f0 65 67 48 8b 40 11");
testOpCtrl2(m64, prefix2(.Lock, .Repne), .MOV, reg(.RAX), memRm(.GS, .QWORD, .EAX, 0x11), "f0 f2 65 67 48 8b 40 11");
testOpCtrl0(m64, prefix(.Repne), .CMPSQ, "f2 48 a7");
}
{
const ctrl = EncodingControl.init(
.NoHint,
.AddPrefixes,
&[_]Prefix{ .OpSize, .AddrSize, .SegmentCS, .Repne },
);
testOpCtrl0(m64, ctrl, .NOP, "66 67 2E F2 90");
testOpCtrl1(m64, ctrl, .NOP, memRm(.GS, .QWORD, .EAX, 0x11), "66 67 2e f2 65 67 48 0f 1f 40 11");
}
{
const ctrl = EncodingControl.init(
.NoHint,
.ExactPrefixes,
&[_]Prefix{ .OpSize, .AddrSize, .SegmentCS, .Repne },
);
testOpCtrl0(m64, ctrl, .NOP, "66 67 2E F2 90");
testOpCtrl1(m64, ctrl, .NOP, memRm(.GS, .QWORD, .EAX, 0x11), AsmError.InvalidPrefixes);
}
{
const ctrl = EncodingControl.init(
.NoHint,
.ExactPrefixes,
&[_]Prefix{ .OpSize, .AddrSize, .SegmentGS, .Repne },
);
testOpCtrl0(m64, ctrl, .NOP, "66 67 65 F2 90");
testOpCtrl1(m64, ctrl, .NOP, memRm(.GS, .QWORD, .EAX, 0x11), "66 67 65 f2 48 0f 1f 40 11");
}
{
const ctrl = EncodingControl.init(
.NoHint,
.ExactPrefixes,
&[_]Prefix{ .OpSize, .SegmentGS, .Repne },
);
testOpCtrl0(m64, ctrl, .NOP, "66 65 F2 90");
testOpCtrl1(m64, ctrl, .NOP, memRm(.GS, .QWORD, .EAX, 0x11), AsmError.InvalidPrefixes);
}
{
const cs_x11 = EncodingControl.init(.NoHint, .AddPrefixes, &([_]Prefix{.SegmentCS} ** 11));
testOpCtrl0(m64, cs_x11, .NOP, "2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 90");
testOpCtrl1(m64, cs_x11, .NOP, memRm(.DefaultSeg, .QWORD, .RAX, 0x00), "2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 48 0f 1f 00");
testOpCtrl1(m64, cs_x11, .NOP, memRm(.DefaultSeg, .QWORD, .RAX, 0x11), AsmError.InstructionTooLong);
testOpCtrl1(m64, cs_x11, .NOP, memRm(.DefaultSeg, .QWORD, .RAX, 0x44332211), AsmError.InstructionTooLong);
}
{
const cs_x14 = EncodingControl.init(.NoHint, .ExactPrefixes, &([_]Prefix{.SegmentCS} ** 14));
testOpCtrl0(m64, cs_x14, .NOP, "2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 90");
testOpCtrl1(m64, cs_x14, .NOP, memRm(.DefaultSeg, .DWORD, .RAX, 0x00), AsmError.InstructionTooLong);
}
{
const cs_x10 = EncodingControl.init(.NoHint, .ExactPrefixes, &([_]Prefix{.SegmentCS} ** 10));
testOpCtrl1(m64, cs_x10, .NOP, memRm(.CS, .DWORD, .RAX, 0x00), "2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 0f 1f 00");
testOpCtrl1(m64, cs_x10, .NOP, memRm(.GS, .DWORD, .RAX, 0x00), AsmError.InvalidPrefixes);
testOpCtrl1(m64, cs_x10, .NOP, memRm(.GS, .DWORD, .RAX, 0x44332211), AsmError.InstructionTooLong);
testOpCtrl1(m64, cs_x10, .NOP, memRm(.CS, .DWORD, .RAX, 0x44332211), AsmError.InstructionTooLong);
}
}
|
src/x86/tests/prefixes.zig
|
const keyboard = @import("keyboard.zig");
const keys = @import("keyboard_keys.zig");
const Location = keys.Location;
const Input = keys.Input;
pub const KeyboardLayout = enum {
en_US_QWERTY,
sv_SE_QWERTY,
};
// Keys that are common between keyboard layouts
fn default_key_lookup(key: Location) error{unknownKey}!Input {
return switch(key) {
.Escape => .Escape,
.LeftShift => .LeftShift, .RightShift => .RightShift,
.LeftCtrl => .LeftCtrl, .RightCtrl => .RightCtrl,
.LeftSuper => .LeftSuper, .RightSuper => .RightSuper,
.LeftAlt => .LeftAlt, .RightAlt => .RightAlt,
.Spacebar => .Spacebar,
.OptionKey => .OptionKey,
.PrintScreen => .PrintScreen,
.PauseBreak => .PauseBreak,
.ScrollLock => .ScrollLock,
.Insert => .Insert,
.Home => .Home,
.PageUp => .PageUp,
.Delete => .Delete,
.End => .End,
.PageDown => .PageDown,
.ArrowUp => .ArrowUp,
.ArrowLeft => .ArrowLeft,
.ArrowDown => .ArrowDown,
.ArrowRight => .ArrowRight,
.Backspace => .Backspace,
.MediaStop => .MediaStop,
.MediaRewind => .MediaRewind,
.MediaPausePlay => .MediaPausePlay,
.MediaForward => .MediaForward,
.MediaMute => .MediaMute,
.MediaVolumeUp => .MediaVolumeUp,
.MediaVolumeDown => .MediaVolumeDown,
.Tab => .Tab,
.CapsLock => .CapsLock,
.Enter => .Enter,
.NumLock => .NumLock,
.NumpadDivision => .NumpadDivision,
.NumpadMultiplication => .NumpadMultiplication,
.Numpad7 => .Numpad7,
.Numpad8 => .Numpad8,
.Numpad9 => .Numpad9,
.NumpadSubtraction => .NumpadSubtraction,
.Numpad4 => .Numpad4,
.Numpad5 => .Numpad5,
.Numpad6 => .Numpad6,
.NumpadAddition => .NumpadAddition,
.Numpad1 => .Numpad1,
.Numpad2 => .Numpad2,
.Numpad3 => .Numpad3,
.Numpad0 => .Numpad0,
.NumpadPoint => .NumpadPoint,
.NumpadEnter => .NumpadEnter,
.F1 => .F1, .F2 => .F2, .F3 => .F3, .F4 => .F4, .F5 => .F5, .F6 => .F6,
.F7 => .F7, .F8 => .F8, .F9 => .F9, .F10 => .F10, .F11 => .F11, .F12 => .F12,
.F13 => .F13, .F14 => .F14, .F15 => .F15, .F16 => .F16, .F17 => .F17, .F18 => .F18,
.F19 => .F19, .F20 => .F20, .F21 => .F21, .F22 => .F22, .F23 => .F23, .F24 => .F24,
else => error.unknownKey,
};
}
fn qwerty_family(key: Location) error{unknownKey}!Input {
return switch(key) {
.Line1_1 => .Q,
.Line1_2 => .W,
.Line1_3 => .E,
.Line1_4 => .R,
.Line1_5 => .T,
.Line1_6 => .Y,
.Line1_7 => .U,
.Line1_8 => .I,
.Line1_9 => .O,
.Line1_10 => .P,
.Line2_1 => .A,
.Line2_2 => .S,
.Line2_3 => .D,
.Line2_4 => .F,
.Line2_5 => .G,
.Line2_6 => .H,
.Line2_7 => .J,
.Line2_8 => .K,
.Line2_9 => .L,
.Line3_1 => .Z,
.Line3_2 => .X,
.Line3_3 => .C,
.Line3_4 => .V,
.Line3_5 => .B,
.Line3_6 => .N,
.Line3_7 => .M,
else => default_key_lookup(key),
};
}
fn sv_SE_QWERTY(state: *const keyboard.KeyboardState, key: Location) !Input {
const shift = state.is_shift_pressed();
const alt = state.is_alt_pressed();
switch(key) {
.LeftOf1 => { if(alt) return Input.ParagraphSign; return Input.SectionSign; },
.NumberKey1 => { if(shift) return Input.ExclamationMark; return Input.@"1"; },
.NumberKey2 => {
if(alt) return Input.At;
if(shift) return Input.QuotationMark;
return Input.@"2";
},
.NumberKey3 => {
if(alt) return Input.PoundCurrency;
if(shift) return Input.Hash;
return Input.@"3";
},
.NumberKey4 => {
if(alt) return Input.DollarCurrency;
if(shift) return Input.CurrencySign;
return Input.@"4";
},
.NumberKey5 => {
if(alt) return Input.EuroCurrency;
if(shift) return Input.Percent;
return Input.@"5";
},
.NumberKey6 => {
if(alt) return Input.YenCurrency;
if(shift) return Input.Ampersand;
return Input.@"6";
},
.NumberKey7 => {
if(alt) return Input.OpenCurlyBrace;
if(shift) return Input.Forwardslash;
return Input.@"7";
},
.NumberKey8 => {
if(alt) return Input.OpenSqBracket;
if(shift) return Input.OpenParen;
return Input.@"8";
},
.NumberKey9 => {
if(alt) return Input.CloseSqBracket;
if(shift) return Input.CloseParen;
return Input.@"9";
},
.NumberKey0 => {
if(alt) return Input.CloseCurlyBrace;
if(shift) return Input.Equals;
return Input.@"0";
},
.RightOf0 => {
if(alt) return Input.Backslash;
if(shift) return Input.Questionmark;
return Input.Plus;
},
.LeftOfBackspace => {
if(alt) return Input.Plusminus;
if(shift) return Input.Backtick;
return Input.Acute;
},
.Line1_11 => { if(alt) return Input.Umlaut; return Input.AWithRing; },
.Line1_12 => {
if(alt) return Input.Tilde;
if(shift) return Input.Caret;
return Input.Umlaut;
},
.Line2_10 => { if(alt) return Input.SlashedO; return Input.OWithUmlaut; },
.Line2_11 => { if(alt) return Input.Ash; return Input.AWithUmlaut; },
.Line2_12 => {
if(alt) return Input.Backtick;
if(shift) return Input.Asterisk;
return Input.Apostrophe;
},
.RightOfLeftShift => {
if(alt) return Input.VerticalBar;
if(shift) return Input.GreaterThan;
return Input.LessThan;
},
.Line3_8 => { if(shift) return Input.Semicolon; return Input.Comma; },
.Line3_9 => { if(shift) return Input.Colon; return Input.Period; },
.Line3_10 => { if(shift) return Input.Underscore; return Input.Minus; },
else => return qwerty_family(key),
}
}
fn en_US_QWERTY(state: *const keyboard.KeyboardState, key: Location) !Input {
const shift = state.is_shift_pressed();
switch(key) {
.LeftOf1 => { if(shift) return Input.Tilde; return Input.Backtick; },
.NumberKey1 => { if(shift) return Input.ExclamationMark; return Input.@"1"; },
.NumberKey2 => { if(shift) return Input.At; return Input.@"2"; },
.NumberKey3 => { if(shift) return Input.Hash; return Input.@"3"; },
.NumberKey4 => { if(shift) return Input.DollarCurrency; return Input.@"4"; },
.NumberKey5 => { if(shift) return Input.Percent; return Input.@"5"; },
.NumberKey6 => { if(shift) return Input.Caret; return Input.@"6"; },
.NumberKey7 => { if(shift) return Input.Ampersand; return Input.@"7"; },
.NumberKey8 => { if(shift) return Input.Asterisk; return Input.@"8"; },
.NumberKey9 => { if(shift) return Input.OpenParen; return Input.@"9"; },
.NumberKey0 => { if(shift) return Input.CloseParen; return Input.@"0"; },
.RightOf0 => { if(shift) return Input.Underscore; return Input.Minus; },
.LeftOfBackspace => { if(shift) return Input.Plus; return Input.Equals; },
.Line1_11 => { if(shift) return Input.OpenCurlyBrace; return Input.OpenSqBracket; },
.Line1_12 => { if(shift) return Input.CloseCurlyBrace; return Input.CloseSqBracket; },
.Line1_13 => { if(shift) return Input.VerticalBar; return Input.Backslash; },
.Line2_10 => { if(shift) return Input.Colon; return Input.Semicolon; },
.Line2_11 => { if(shift) return Input.Apostrophe; return Input.QuotationMark; },
.Line3_8 => { if(shift) return Input.LessThan; return Input.Comma; },
.Line3_9 => { if(shift) return Input.GreaterThan; return Input.Period; },
.Line3_10 => { if(shift) return Input.Questionmark; return Input.Forwardslash; },
else => return qwerty_family(key),
}
}
pub fn get_input(state: *const keyboard.KeyboardState, key: Location, layout: KeyboardLayout) !Input {
return switch(layout) {
.en_US_QWERTY => return en_US_QWERTY(state, key),
.sv_SE_QWERTY => return sv_SE_QWERTY(state, key),
};
}
|
src/drivers/hid/keyboard_layouts.zig
|
const std = @import("std");
const builtin = @import("builtin");
const is_test = builtin.is_test;
const comparedf2 = @import("compareXf2.zig");
const TestVector = struct {
a: f64,
b: f64,
eqReference: c_int,
geReference: c_int,
gtReference: c_int,
leReference: c_int,
ltReference: c_int,
neReference: c_int,
unReference: c_int,
};
fn test__cmpdf2(vector: TestVector) bool {
if (comparedf2.__eqdf2(vector.a, vector.b) != vector.eqReference) {
return false;
}
if (comparedf2.__gedf2(vector.a, vector.b) != vector.geReference) {
return false;
}
if (comparedf2.__gtdf2(vector.a, vector.b) != vector.gtReference) {
return false;
}
if (comparedf2.__ledf2(vector.a, vector.b) != vector.leReference) {
return false;
}
if (comparedf2.__ltdf2(vector.a, vector.b) != vector.ltReference) {
return false;
}
if (comparedf2.__nedf2(vector.a, vector.b) != vector.neReference) {
return false;
}
if (comparedf2.__unorddf2(vector.a, vector.b) != vector.unReference) {
return false;
}
return true;
}
const arguments = [_]f64{
std.math.nan(f64),
-std.math.inf(f64),
-0x1.fffffffffffffp1023,
-0x1.0000000000001p0 - 0x1.0000000000000p0,
-0x1.fffffffffffffp-1,
-0x1.0000000000000p-1022,
-0x0.fffffffffffffp-1022,
-0x0.0000000000001p-1022,
-0.0,
0.0,
0x0.0000000000001p-1022,
0x0.fffffffffffffp-1022,
0x1.0000000000000p-1022,
0x1.fffffffffffffp-1,
0x1.0000000000000p0,
0x1.0000000000001p0,
0x1.fffffffffffffp1023,
std.math.inf(f64),
};
fn generateVector(comptime a: f64, comptime b: f64) TestVector {
const leResult = if (a < b) -1 else if (a == b) 0 else 1;
const geResult = if (a > b) 1 else if (a == b) 0 else -1;
const unResult = if (a != a or b != b) 1 else 0;
return TestVector{
.a = a,
.b = b,
.eqReference = leResult,
.geReference = geResult,
.gtReference = geResult,
.leReference = leResult,
.ltReference = leResult,
.neReference = leResult,
.unReference = unResult,
};
}
const test_vectors = init: {
@setEvalBranchQuota(10000);
var vectors: [arguments.len * arguments.len]TestVector = undefined;
for (arguments[0..]) |arg_i, i| {
for (arguments[0..]) |arg_j, j| {
vectors[(i * arguments.len) + j] = generateVector(arg_i, arg_j);
}
}
break :init vectors;
};
test "compare f64" {
for (test_vectors) |vector, i| {
try std.testing.expect(test__cmpdf2(vector));
}
}
|
lib/std/special/compiler_rt/comparedf2_test.zig
|
const std = @import("std");
const parseInt = std.fmt.parseInt;
const print = std.debug.print;
const tokenize = std.mem.tokenize;
const testing = std.testing;
const input = @embedFile("./input.txt");
const size = 10;
const DELTAS = .{
.{ 1, 0 },
.{ 0, 1 },
.{ -1, 0 },
.{ 0, -1 },
.{ 1, 1 },
.{ -1, -1 },
.{ 1, -1 },
.{ -1, 1 },
};
pub fn main() anyerror!void {
print("--- Part One ---\n", .{});
print("Result: {d}\n", .{part1()});
print("--- Part Two ---\n", .{});
print("Result: {d}\n", .{part2()});
}
///
/// --- Part One ---
///
fn part1() !u32 {
var ans: u32 = 0;
var grid: [size][size]u8 = try parseGrid();
var i: u8 = 0;
while (i < 100) : (i += 1) {
ans += step(&grid);
}
return ans;
}
test "day11.part1" {
@setEvalBranchQuota(200_000);
try testing.expectEqual(1755, comptime try part1());
}
///
/// --- Part Two ---
///
fn part2() !u32 {
var ans: u8 = 0;
var grid: [size][size]u8 = try parseGrid();
while (true) {
ans += 1;
if (step(&grid) == size * size) {
break;
}
}
return ans;
}
test "day11.part2" {
@setEvalBranchQuota(200_000);
try testing.expectEqual(212, comptime try part2());
}
///
/// parseGrid parses the input into a 2D array of u8s representing energy levels
///
fn parseGrid() ![size][size]u8 {
var grid: [size][size]u8 = undefined;
var input_iter = tokenize(u8, input, "\n");
var i: usize = 0;
while (input_iter.next()) |row| : (i += 1) {
for (row) |octopus, j| {
grid[i][j] = octopus - '0';
}
}
return grid;
}
///
/// step performs one step of the Dumbo Octopus simulation 🐙
///
fn step(grid: *[size][size]u8) u32 {
var flashers: [size * size][2]usize = undefined;
var flashed: u32 = 0;
flashed = levelUpStep(grid, &flashers);
flashed = flashStep(grid, &flashers, flashed);
resetFlashed(grid, &flashers, flashed);
return flashed;
}
///
/// levelUpStep walks the grid cell by cell, increasing each value and filling
/// a list of positions with energy level equal to 10
///
fn levelUpStep(grid: *[size][size]u8, flashers: *[size * size][2]usize) u32 {
var flashed: u32 = 0;
for (grid) |_, i| {
for (grid[i]) |_, j| {
grid[i][j] += 1;
if (grid[i][j] == 10) {
flashers[flashed] = .{ i, j };
flashed += 1;
}
}
}
return flashed;
}
///
/// flashStep walks through the grid in a BSF fashion flashing all octopuses
/// with energy level equal to 10
///
fn flashStep(grid: *[size][size]u8, flashers: *[size * size][2]usize, flashed: u32) u32 {
var back = flashed;
var front: u32 = 0;
while (front < back) : (front += 1) {
var i = flashers[front][0];
var j = flashers[front][1];
inline for (DELTAS) |deltas| {
if ((i != 0 or deltas[0] != -1) and (j != 0 or deltas[1] != -1)) {
var x: usize = @intCast(usize, @intCast(i16, i) + deltas[0]);
var y: usize = @intCast(usize, @intCast(i16, j) + deltas[1]);
if (x < size and y < size and grid[x][y] < 10) {
grid[x][y] += 1;
if (grid[x][y] == 10) {
flashers[back] = .{ x, y };
back += 1;
}
}
}
}
}
return back;
}
///
/// resetFlashed resets all octopuses that flashed
///
fn resetFlashed(grid: *[size][size]u8, flashers: *[size * size][2]usize, flashed: u32) void {
var i: u32 = 0;
while (i < flashed) : (i += 1) {
grid[flashers[i][0]][flashers[i][1]] = 0;
}
}
|
src/day11/day11.zig
|
const std = @import("std");
const log = std.log.scoped(.hw5);
const math = std.math;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Random = std.rand.Random;
const cuda = @import("cudaz");
const cu = cuda.cu;
const utils = @import("utils.zig");
const RawKernels = @import("hw5_kernel.zig");
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &general_purpose_allocator.allocator();
try initModule(0);
log.info("***** HW5 ******", .{});
const num_bins: usize = 1024;
const num_elems: usize = 10_000 * num_bins;
var data = try allocator.alloc(u32, num_elems);
defer allocator.free(data);
var random = std.rand.DefaultPrng.init(387418298).random();
// make the mean unpredictable, but close enough to the middle
// so that timings are unaffected
const mean = random.intRangeLessThan(u32, num_bins / 2 - num_bins / 8, num_bins / 2 + num_bins / 8);
const std_dev: f32 = 100;
// TODO: generate this on the GPU
for (data) |*x| {
var r = @floatToInt(i32, random.floatNorm(f32) * std_dev) + @intCast(i32, mean);
x.* = math.min(math.absCast(r), @intCast(u32, num_bins - 1));
}
var ref_histo = try allocator.alloc(u32, num_bins);
defer allocator.free(ref_histo);
cpu_histogram(data, ref_histo);
var atomic_histo = try allocator.alloc(u32, num_bins);
defer allocator.free(atomic_histo);
var elapsed = try histogram(k.atomicHistogram.f, data, atomic_histo, ref_histo, cuda.Grid.init1D(data.len, 1024));
log.info("atomicHistogram of {} array took {:.3}ms", .{ num_elems, elapsed });
log.info("atomicHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6});
elapsed = try histogram(k.bychunkHistogram.f, data, atomic_histo, ref_histo, cuda.Grid.init1D(data.len / 32, 1024));
log.info("bychunkHistogram of {} array took {:.3}ms", .{ num_elems, elapsed });
log.info("bychunkHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6});
elapsed = try fastHistogram(data, atomic_histo, ref_histo);
log.info("fastHistogram of {} array took {:.3}ms", .{ num_elems, elapsed });
log.info("fastHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6});
}
pub fn cpu_histogram(data: []const u32, histo: []u32) void {
std.mem.set(u32, histo, 0);
for (data) |x| {
histo[x] += 1;
}
}
pub fn histogram(kernel: cu.CUfunction, data: []const u32, histo: []u32, ref_histo: []const u32, grid: cuda.Grid) !f64 {
var stream = try cuda.Stream.init(0);
var d_data = try stream.allocAndCopy(u32, data);
var d_histo = try stream.alloc(u32, histo.len);
stream.memset(u32, d_histo, 0);
var timer = cuda.GpuTimer.start(&stream);
try stream.launchWithSharedMem(
kernel,
grid,
d_histo.len * @sizeOf(u32),
.{ d_data, d_histo },
);
timer.stop();
stream.memcpyDtoH(u32, histo, d_histo);
stream.synchronize();
var elapsed = timer.elapsed();
std.testing.expectEqualSlices(u32, ref_histo, histo) catch {
if (ref_histo.len < 100) {
log.err("Histogram mismatch. Expected: {d}, got {d}", .{ ref_histo, histo });
}
// return err;
};
return elapsed;
}
const Kernels = struct {
atomicHistogram: cuda.FnStruct("atomicHistogram", RawKernels.atomicHistogram),
bychunkHistogram: cuda.FnStruct("bychunkHistogram", RawKernels.bychunkHistogram),
coarseBins: cuda.FnStruct("coarseBins", RawKernels.coarseBins),
shuffleCoarseBins: cuda.FnStruct("shuffleCoarseBins32", RawKernels.shuffleCoarseBins32),
cdfIncremental: cuda.FnStruct("cdfIncremental", RawKernels.cdfIncremental),
cdfIncrementalShift: cuda.FnStruct("cdfIncrementalShift", RawKernels.cdfIncrementalShift),
};
var k: Kernels = undefined;
fn initModule(device: u3) !void {
_ = try cuda.Stream.init(device);
// Panic if we can't load the module.
k = Kernels{
.atomicHistogram = try @TypeOf(k.atomicHistogram).init(),
.bychunkHistogram = try @TypeOf(k.bychunkHistogram).init(),
.coarseBins = try @TypeOf(k.coarseBins).init(),
.shuffleCoarseBins = try @TypeOf(k.shuffleCoarseBins).init(),
.cdfIncremental = try @TypeOf(k.cdfIncremental).init(),
.cdfIncrementalShift = try @TypeOf(k.cdfIncrementalShift).init(),
};
}
fn computeBandwith(elapsed_ms: f64, data: []const u32) f64 {
const n = @intToFloat(f64, data.len);
const bytes = @intToFloat(f64, @sizeOf(u32));
return n * bytes / elapsed_ms * 1000;
}
fn fastHistogram(data: []const u32, histo: []u32, ref_histo: []const u32) !f32 {
var stream = &(try cuda.Stream.init(0));
_ = try stream.allocAndCopy(u32, data);
var d_histo = try stream.alloc(u32, histo.len);
stream.memset(u32, d_histo, 0);
var d_radix = try stream.alloc(u32, data.len * 32);
stream.memset(u32, d_radix, 0);
try cuda.memset(u32, d_radix, 0);
_ = ref_histo;
return 0.0;
}
fn fastHistogramBroken(data: []const u32, histo: []u32, ref_histo: []const u32) !f32 {
var stream = &(try cuda.Stream.init(0));
var d_values = try stream.allocAndCopy(u32, data);
var d_histo = try stream.alloc(u32, histo.len);
stream.memset(u32, d_histo, 0);
var d_radix = try stream.alloc(u32, data.len * 32);
stream.memset(u32, d_radix, 0);
var timer = cuda.GpuTimer.start(stream);
const n = d_values.len;
try cuda.memset(u32, d_radix, 0);
// We split the bins into 32 coarse bins.
const d_histo_boundaries = try stream.alloc(u32, 32);
try k.coarseBins.launch(
stream,
cuda.Grid.init1D(n, 1024),
.{ d_values, d_radix },
);
// const radix_sum = try cuda.algorithms.reduce(&stream, k.sumU32, d_radix);
// log.debug("Radix sums to {}, expected {}", .{ radix_sum, d_values.len });
// std.debug.assert(radix_sum == d_values.len);
try inPlaceCdf(stream, d_radix, 1024);
// debugDevice("d_radix + cdf", d_radix);
try k.shuffleCoarseBins.launch(
stream,
cuda.Grid.init1D(n, 1024),
.{ d_histo, d_histo_boundaries, d_radix, d_values },
);
var histo_boundaries: [33]u32 = undefined;
stream.memcpyDtoH(u32, &histo_boundaries, d_histo_boundaries);
timer.stop();
stream.synchronize();
// Now we can partition d_values into coarse bins.
var bin: u32 = 0;
while (bin < 32) : (bin += 1) {
var bin_start = histo_boundaries[bin];
var bin_end = histo_boundaries[bin + 1];
var d_bin_values = d_histo[bin_start .. bin_end + 1];
// TODO histogram(d_bin_values)
_ = d_bin_values;
}
var elapsed = timer.elapsed();
std.testing.expectEqualSlices(u32, ref_histo, histo) catch {
if (ref_histo.len < 100) {
log.err("Histogram mismatch. Expected: {d}, got {d}", .{ ref_histo, histo });
}
// return err;
};
return elapsed;
}
// TODO: the cdf kernels should be part of cudaz
pub fn inPlaceCdf(stream: *const cuda.Stream, d_values: []u32, n_threads: u32) cuda.Error!void {
const n = d_values.len;
const grid_N = cuda.Grid.init1D(n, n_threads);
const n_blocks = grid_N.blocks.x;
var d_grid_bins = try cuda.alloc(u32, n_blocks);
defer cuda.free(d_grid_bins);
var n_threads_pow_2 = n_threads;
while (n_threads_pow_2 > 1) {
std.debug.assert(n_threads_pow_2 % 2 == 0);
n_threads_pow_2 /= 2;
}
log.warn("cdf(n={}, n_threads={}, n_blocks={})", .{ n, n_threads, n_blocks });
try k.cdfIncremental.launchWithSharedMem(
stream,
grid_N,
n_threads * @sizeOf(u32),
.{ d_values, d_grid_bins },
);
if (n_blocks == 1) return;
try inPlaceCdf(stream, d_grid_bins, n_threads);
try k.cdfIncrementalShift.launch(
stream,
grid_N,
.{ d_values, d_grid_bins },
);
}
test "inPlaceCdf" {
try initModule(0);
var stream = try cuda.Stream.init(0);
defer stream.deinit();
const h_x = [_]u32{ 0, 2, 1, 1, 0, 1, 3, 0, 2 };
var h_out = [_]u32{0} ** h_x.len;
const h_cdf = [_]u32{ 0, 0, 2, 3, 4, 4, 5, 8, 8 };
const d_x = try cuda.alloc(u32, h_x.len);
defer cuda.free(d_x);
try cuda.memcpyHtoD(u32, d_x, &h_x);
try inPlaceCdf(&stream, d_x, 16);
try utils.expectEqualDeviceSlices(u32, &h_cdf, d_x);
try cuda.memcpyHtoD(u32, d_x, &h_x);
try inPlaceCdf(&stream, d_x, 8);
try cuda.memcpyDtoH(u32, &h_out, d_x);
try testing.expectEqual(h_cdf, h_out);
// Try with smaller batch sizes, forcing several passes
try cuda.memcpyHtoD(u32, d_x, &h_x);
try inPlaceCdf(&stream, d_x, 4);
try cuda.memcpyDtoH(u32, &h_out, d_x);
try testing.expectEqual(h_cdf, h_out);
try cuda.memcpyHtoD(u32, d_x, &h_x);
try inPlaceCdf(&stream, d_x, 2);
try utils.expectEqualDeviceSlices(u32, &h_cdf, d_x);
}
|
CS344/src/hw5.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
data: []u8,
width: usize,
height: usize,
num_bytes: usize,
allocator: Allocator,
const Self = @This();
pub fn Rgb(comptime T: type) type {
return struct {
r: T,
g: T,
b: T,
};
}
pub const Rgb8 = Rgb(u8);
pub const RgbFloat32 = Rgb(f32);
pub const RgbFloat64 = Rgb(f64);
pub fn ShaderFn(comptime T: type) type {
return fn (T, T) Rgb(T);
}
pub fn Init(allocator: Allocator, w: usize, h: usize) !Self {
var num_bytes = w * h * 3;
return Self{
.data = try allocator.alloc(u8, num_bytes),
.width = w,
.height = h,
.num_bytes = num_bytes,
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.data);
}
fn baseIndex(self: Self, x: usize, y: usize) usize {
return (y * self.width + x) * 3;
}
pub fn set(self: *Self, x: usize, y: usize, rgb: Rgb8) void {
var i = self.baseIndex(x, y);
self.data[i] = rgb.r;
self.data[i + 1] = rgb.g;
self.data[i + 2] = rgb.b;
}
pub fn get(self: *Self, x: usize, y: usize) struct { r: u8, g: u8, b: u8 } {
var i = self.baseIndex(x, y);
return .{
.r = self.data[i],
.g = self.data[i + 1],
.b = self.data[i + 2],
};
}
pub fn fill(self: *Self, rgb: Rgb) void {
var i: usize = 0;
while (i < self.data.len) : (i += 3) {
self.data[i] = rgb.r;
self.data[i + 1] = rgb.g;
self.data[i + 2] = rgb.b;
}
}
pub fn ppm(self: Self, wr: anytype) !void {
try wr.writeAll("P3\n");
try wr.print("{} {}\n255\n", .{ self.width, self.height });
var i: usize = 0;
while (i < self.width * self.height * 3) : (i += 3) {
var r = self.data[i];
var g = self.data[i + 1];
var b = self.data[i + 2];
try wr.print("{} {} {}\n", .{ r, g, b });
}
}
/// This will call the function `ps(u, v)` to every pixel of the image,
/// transforming the pixel's value according to the output of `ps`. The
/// arguments to `ps` are within the [0, 1] range, just like texture
/// coordinates.
///
/// `T` must be a float type, i.e., either `f32` or `f64`.
///
pub fn shader(self: *Self, comptime T: type, ps: ShaderFn(T)) void {
if (@typeInfo(T) != .Float) {
unreachable;
}
var dx: T = 1.0 / @intToFloat(T, self.width);
var dy: T = 1.0 / @intToFloat(T, self.height);
var i: usize = 0;
while (i < self.data.len) : (i += 3) {
var x = @rem(i / 3, self.width);
var y = @divTrunc(i / 3, self.width);
var u = @intToFloat(T, x) * dx;
var v = @intToFloat(T, y) * dy;
var c = ps(u, v);
self.data[i] = @floatToInt(u8, std.math.clamp(c.r, 0, 1) * 255.0);
self.data[i + 1] = @floatToInt(u8, std.math.clamp(c.g, 0, 1) * 255.0);
self.data[i + 2] = @floatToInt(u8, std.math.clamp(c.b, 0, 1) * 255.0);
}
}
|
src/image.zig
|
const macro = @import("pspmacros.zig");
comptime {
asm (macro.import_module_start("sceAudio", "0x40010000", "27"));
asm (macro.import_function("sceAudio", "0x8C1009B2", "sceAudioOutput"));
asm (macro.import_function("sceAudio", "0x136CAF51", "sceAudioOutputBlocking"));
asm (macro.import_function("sceAudio", "0xE2D56B2D", "sceAudioOutputPanned"));
asm (macro.import_function("sceAudio", "0x13F592BC", "sceAudioOutputPannedBlocking"));
asm (macro.import_function("sceAudio", "0x5EC81C55", "sceAudioChReserve"));
asm (macro.import_function("sceAudio", "0x41EFADE7", "sceAudioOneshotOutput"));
asm (macro.import_function("sceAudio", "0x6FC46853", "sceAudioChRelease"));
asm (macro.import_function("sceAudio", "0xE9D97901", "sceAudioGetChannelRestLen"));
asm (macro.import_function("sceAudio", "0xCB2E439E", "sceAudioSetChannelDataLen"));
asm (macro.import_function("sceAudio", "0x95FD0C2D", "sceAudioChangeChannelConfig"));
asm (macro.import_function("sceAudio", "0xB7E1D8E7", "sceAudioChangeChannelVolume"));
asm (macro.import_function("sceAudio", "0x38553111", "sceAudioSRCChReserve"));
asm (macro.import_function("sceAudio", "0x5C37C0AE", "sceAudioSRCChRelease"));
asm (macro.import_function("sceAudio", "0xE0727056", "sceAudioSRCOutputBlocking"));
asm (macro.import_function("sceAudio", "0x086E5895", "sceAudioInputBlocking"));
asm (macro.import_function("sceAudio", "0x6D4BEC68", "sceAudioInput"));
asm (macro.import_function("sceAudio", "0xA708C6A6", "sceAudioGetInputLength"));
asm (macro.import_function("sceAudio", "0x87B2E651", "sceAudioWaitInputEnd"));
asm (macro.import_function("sceAudio", "0x7DE61688", "sceAudioInputInit"));
asm (macro.import_function("sceAudio", "0xA633048E", "sceAudioPollInputEnd"));
asm (macro.import_function("sceAudio", "0xB011922F", "sceAudioGetChannelRestLength"));
asm (macro.import_function("sceAudio", "0xE926D3FB", "sceAudioInputInitEx"));
asm (macro.import_function("sceAudio", "0x01562BA3", "sceAudioOutput2Reserve"));
asm (macro.import_function("sceAudio", "0x2D53F36E", "sceAudioOutput2OutputBlocking"));
asm (macro.import_function("sceAudio", "0x43196845", "sceAudioOutput2Release"));
asm (macro.import_function("sceAudio", "0x63F2889C", "sceAudioOutput2ChangeLength"));
asm (macro.import_function("sceAudio", "0x647CEF33", "sceAudioOutput2GetRestSample"));
}
|
src/psp/nids/pspaudio.zig
|
const std = @import("std");
const deps = @import("deps.zig");
const Options = struct {
mode: std.builtin.Mode,
target: std.zig.CrossTarget,
fn apply(self: Options, lib: *std.build.LibExeObjStep) void {
lib.setBuildMode(self.mode);
lib.setTarget(self.target);
}
};
pub fn build(b: *std.build.Builder) void {
const options = Options{
// 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.
.target = b.standardTargetOptions(.{}),
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
.mode = b.standardReleaseOptions(),
};
const lib = b.addStaticLibrary("zCord", "src/main.zig");
deps.pkgs.addAllTo(lib);
lib.install();
options.apply(lib);
const main_tests = b.addTest("src/main.zig");
options.apply(main_tests);
deps.pkgs.addAllTo(main_tests);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
for ([_][]const u8{ "print-bot", "reconnect-bot", "reply-bot" }) |name| {
const exe = createExampleExe(b, name);
options.apply(exe);
test_step.dependOn(&exe.step);
const run_cmd = exe.run();
const run_step = b.step(
std.fmt.allocPrint(b.allocator, "example:{s}", .{name}) catch unreachable,
std.fmt.allocPrint(b.allocator, "Run example {s}", .{name}) catch unreachable,
);
run_step.dependOn(&run_cmd.step);
}
}
fn createExampleExe(b: *std.build.Builder, name: []const u8) *std.build.LibExeObjStep {
const filename = std.fmt.allocPrint(b.allocator, "examples/{s}.zig", .{name}) catch unreachable;
const exe = b.addExecutable(name, filename);
exe.addPackage(deps.exports.zCord);
return exe;
}
|
build.zig
|
usingnamespace @import("../windows/bits.zig");
const ws2_32 = @import("../windows/ws2_32.zig");
pub const fd_t = HANDLE;
pub const ino_t = LARGE_INTEGER;
pub const pid_t = HANDLE;
pub const mode_t = u0;
pub const PATH_MAX = 260;
pub const time_t = c_longlong;
pub const timespec = extern struct {
tv_sec: time_t,
tv_nsec: c_long,
};
pub const timeval = extern struct {
tv_sec: c_long,
tv_usec: c_long,
};
pub const sig_atomic_t = c_int;
/// maximum signal number + 1
pub const NSIG = 23;
// Signal types
/// interrupt
pub const SIGINT = 2;
/// illegal instruction - invalid function image
pub const SIGILL = 4;
/// floating point exception
pub const SIGFPE = 8;
/// segment violation
pub const SIGSEGV = 11;
/// Software termination signal from kill
pub const SIGTERM = 15;
/// Ctrl-Break sequence
pub const SIGBREAK = 21;
/// abnormal termination triggered by abort call
pub const SIGABRT = 22;
/// SIGABRT compatible with other platforms, same as SIGABRT
pub const SIGABRT_COMPAT = 6;
// Signal action codes
/// default signal action
pub const SIG_DFL = 0;
/// ignore signal
pub const SIG_IGN = 1;
/// return current value
pub const SIG_GET = 2;
/// signal gets error
pub const SIG_SGE = 3;
/// acknowledge
pub const SIG_ACK = 4;
/// Signal error value (returned by signal call on error)
pub const SIG_ERR = -1;
pub const SEEK_SET = 0;
pub const SEEK_CUR = 1;
pub const SEEK_END = 2;
pub const EPERM = 1;
pub const ENOENT = 2;
pub const ESRCH = 3;
pub const EINTR = 4;
pub const EIO = 5;
pub const ENXIO = 6;
pub const E2BIG = 7;
pub const ENOEXEC = 8;
pub const EBADF = 9;
pub const ECHILD = 10;
pub const EAGAIN = 11;
pub const ENOMEM = 12;
pub const EACCES = 13;
pub const EFAULT = 14;
pub const EBUSY = 16;
pub const EEXIST = 17;
pub const EXDEV = 18;
pub const ENODEV = 19;
pub const ENOTDIR = 20;
pub const EISDIR = 21;
pub const ENFILE = 23;
pub const EMFILE = 24;
pub const ENOTTY = 25;
pub const EFBIG = 27;
pub const ENOSPC = 28;
pub const ESPIPE = 29;
pub const EROFS = 30;
pub const EMLINK = 31;
pub const EPIPE = 32;
pub const EDOM = 33;
pub const EDEADLK = 36;
pub const ENAMETOOLONG = 38;
pub const ENOLCK = 39;
pub const ENOSYS = 40;
pub const ENOTEMPTY = 41;
pub const EINVAL = 22;
pub const ERANGE = 34;
pub const EILSEQ = 42;
pub const STRUNCATE = 80;
// Support EDEADLOCK for compatibility with older Microsoft C versions
pub const EDEADLOCK = EDEADLK;
// POSIX Supplement
pub const EADDRINUSE = 100;
pub const EADDRNOTAVAIL = 101;
pub const EAFNOSUPPORT = 102;
pub const EALREADY = 103;
pub const EBADMSG = 104;
pub const ECANCELED = 105;
pub const ECONNABORTED = 106;
pub const ECONNREFUSED = 107;
pub const ECONNRESET = 108;
pub const EDESTADDRREQ = 109;
pub const EHOSTUNREACH = 110;
pub const EIDRM = 111;
pub const EINPROGRESS = 112;
pub const EISCONN = 113;
pub const ELOOP = 114;
pub const EMSGSIZE = 115;
pub const ENETDOWN = 116;
pub const ENETRESET = 117;
pub const ENETUNREACH = 118;
pub const ENOBUFS = 119;
pub const ENODATA = 120;
pub const ENOLINK = 121;
pub const ENOMSG = 122;
pub const ENOPROTOOPT = 123;
pub const ENOSR = 124;
pub const ENOSTR = 125;
pub const ENOTCONN = 126;
pub const ENOTRECOVERABLE = 127;
pub const ENOTSOCK = 128;
pub const ENOTSUP = 129;
pub const EOPNOTSUPP = 130;
pub const EOTHER = 131;
pub const EOVERFLOW = 132;
pub const EOWNERDEAD = 133;
pub const EPROTO = 134;
pub const EPROTONOSUPPORT = 135;
pub const EPROTOTYPE = 136;
pub const ETIME = 137;
pub const ETIMEDOUT = 138;
pub const ETXTBSY = 139;
pub const EWOULDBLOCK = 140;
pub const EDQUOT = 10069;
pub const F_OK = 0;
/// Remove directory instead of unlinking file
pub const AT_REMOVEDIR = 0x200;
pub const in_port_t = u16;
pub const sa_family_t = ws2_32.ADDRESS_FAMILY;
pub const socklen_t = ws2_32.socklen_t;
pub const sockaddr = ws2_32.sockaddr;
pub const sockaddr_in = ws2_32.sockaddr_in;
pub const sockaddr_in6 = ws2_32.sockaddr_in6;
pub const sockaddr_un = ws2_32.sockaddr_un;
pub const in6_addr = [16]u8;
pub const in_addr = u32;
pub const addrinfo = ws2_32.addrinfo;
pub const AF_UNSPEC = ws2_32.AF_UNSPEC;
pub const AF_UNIX = ws2_32.AF_UNIX;
pub const AF_INET = ws2_32.AF_INET;
pub const AF_IMPLINK = ws2_32.AF_IMPLINK;
pub const AF_PUP = ws2_32.AF_PUP;
pub const AF_CHAOS = ws2_32.AF_CHAOS;
pub const AF_NS = ws2_32.AF_NS;
pub const AF_IPX = ws2_32.AF_IPX;
pub const AF_ISO = ws2_32.AF_ISO;
pub const AF_OSI = ws2_32.AF_OSI;
pub const AF_ECMA = ws2_32.AF_ECMA;
pub const AF_DATAKIT = ws2_32.AF_DATAKIT;
pub const AF_CCITT = ws2_32.AF_CCITT;
pub const AF_SNA = ws2_32.AF_SNA;
pub const AF_DECnet = ws2_32.AF_DECnet;
pub const AF_DLI = ws2_32.AF_DLI;
pub const AF_LAT = ws2_32.AF_LAT;
pub const AF_HYLINK = ws2_32.AF_HYLINK;
pub const AF_APPLETALK = ws2_32.AF_APPLETALK;
pub const AF_NETBIOS = ws2_32.AF_NETBIOS;
pub const AF_VOICEVIEW = ws2_32.AF_VOICEVIEW;
pub const AF_FIREFOX = ws2_32.AF_FIREFOX;
pub const AF_UNKNOWN1 = ws2_32.AF_UNKNOWN1;
pub const AF_BAN = ws2_32.AF_BAN;
pub const AF_ATM = ws2_32.AF_ATM;
pub const AF_INET6 = ws2_32.AF_INET6;
pub const AF_CLUSTER = ws2_32.AF_CLUSTER;
pub const AF_12844 = ws2_32.AF_12844;
pub const AF_IRDA = ws2_32.AF_IRDA;
pub const AF_NETDES = ws2_32.AF_NETDES;
pub const AF_TCNPROCESS = ws2_32.AF_TCNPROCESS;
pub const AF_TCNMESSAGE = ws2_32.AF_TCNMESSAGE;
pub const AF_ICLFXBM = ws2_32.AF_ICLFXBM;
pub const AF_BTH = ws2_32.AF_BTH;
pub const AF_MAX = ws2_32.AF_MAX;
pub const SOCK_STREAM = ws2_32.SOCK_STREAM;
pub const SOCK_DGRAM = ws2_32.SOCK_DGRAM;
pub const SOCK_RAW = ws2_32.SOCK_RAW;
pub const SOCK_RDM = ws2_32.SOCK_RDM;
pub const SOCK_SEQPACKET = ws2_32.SOCK_SEQPACKET;
/// WARNING: this flag is not supported by windows socket functions directly,
/// it is only supported by std.os.socket. Be sure that this value does
/// not share any bits with any of the SOCK_* values.
pub const SOCK_CLOEXEC = 0x10000;
/// WARNING: this flag is not supported by windows socket functions directly,
/// it is only supported by std.os.socket. Be sure that this value does
/// not share any bits with any of the SOCK_* values.
pub const SOCK_NONBLOCK = 0x20000;
pub const IPPROTO_ICMP = ws2_32.IPPROTO_ICMP;
pub const IPPROTO_IGMP = ws2_32.IPPROTO_IGMP;
pub const BTHPROTO_RFCOMM = ws2_32.BTHPROTO_RFCOMM;
pub const IPPROTO_TCP = ws2_32.IPPROTO_TCP;
pub const IPPROTO_UDP = ws2_32.IPPROTO_UDP;
pub const IPPROTO_ICMPV6 = ws2_32.IPPROTO_ICMPV6;
pub const IPPROTO_RM = ws2_32.IPPROTO_RM;
pub const nfds_t = c_ulong;
pub const pollfd = ws2_32.pollfd;
pub const POLLRDNORM = ws2_32.POLLRDNORM;
pub const POLLRDBAND = ws2_32.POLLRDBAND;
pub const POLLIN = ws2_32.POLLIN;
pub const POLLPRI = ws2_32.POLLPRI;
pub const POLLWRNORM = ws2_32.POLLWRNORM;
pub const POLLOUT = ws2_32.POLLOUT;
pub const POLLWRBAND = ws2_32.POLLWRBAND;
pub const POLLERR = ws2_32.POLLERR;
pub const POLLHUP = ws2_32.POLLHUP;
pub const POLLNVAL = ws2_32.POLLNVAL;
pub const SOL_SOCKET = ws2_32.SOL_SOCKET;
pub const SO_DEBUG = ws2_32.SO_DEBUG;
pub const SO_ACCEPTCONN = ws2_32.SO_ACCEPTCONN;
pub const SO_REUSEADDR = ws2_32.SO_REUSEADDR;
pub const SO_KEEPALIVE = ws2_32.SO_KEEPALIVE;
pub const SO_DONTROUTE = ws2_32.SO_DONTROUTE;
pub const SO_BROADCAST = ws2_32.SO_BROADCAST;
pub const SO_USELOOPBACK = ws2_32.SO_USELOOPBACK;
pub const SO_LINGER = ws2_32.SO_LINGER;
pub const SO_OOBINLINE = ws2_32.SO_OOBINLINE;
pub const SO_DONTLINGER = ws2_32.SO_DONTLINGER;
pub const SO_EXCLUSIVEADDRUSE = ws2_32.SO_EXCLUSIVEADDRUSE;
pub const SO_SNDBUF = ws2_32.SO_SNDBUF;
pub const SO_RCVBUF = ws2_32.SO_RCVBUF;
pub const SO_SNDLOWAT = ws2_32.SO_SNDLOWAT;
pub const SO_RCVLOWAT = ws2_32.SO_RCVLOWAT;
pub const SO_SNDTIMEO = ws2_32.SO_SNDTIMEO;
pub const SO_RCVTIMEO = ws2_32.SO_RCVTIMEO;
pub const SO_ERROR = ws2_32.SO_ERROR;
pub const SO_TYPE = ws2_32.SO_TYPE;
pub const SO_GROUP_ID = ws2_32.SO_GROUP_ID;
pub const SO_GROUP_PRIORITY = ws2_32.SO_GROUP_PRIORITY;
pub const SO_MAX_MSG_SIZE = ws2_32.SO_MAX_MSG_SIZE;
pub const SO_PROTOCOL_INFOA = ws2_32.SO_PROTOCOL_INFOA;
pub const SO_PROTOCOL_INFOW = ws2_32.SO_PROTOCOL_INFOW;
pub const PVD_CONFIG = ws2_32.PVD_CONFIG;
pub const SO_CONDITIONAL_ACCEPT = ws2_32.SO_CONDITIONAL_ACCEPT;
pub const TCP_NODELAY = ws2_32.TCP_NODELAY;
pub const O_RDONLY = 0o0;
pub const O_WRONLY = 0o1;
pub const O_RDWR = 0o2;
pub const O_CREAT = 0o100;
pub const O_EXCL = 0o200;
pub const O_NOCTTY = 0o400;
pub const O_TRUNC = 0o1000;
pub const O_APPEND = 0o2000;
pub const O_NONBLOCK = 0o4000;
pub const O_DSYNC = 0o10000;
pub const O_SYNC = 0o4010000;
pub const O_RSYNC = 0o4010000;
pub const O_DIRECTORY = 0o200000;
pub const O_NOFOLLOW = 0o400000;
pub const O_CLOEXEC = 0o2000000;
pub const O_ASYNC = 0o20000;
pub const O_DIRECT = 0o40000;
pub const O_LARGEFILE = 0;
pub const O_NOATIME = 0o1000000;
pub const O_PATH = 0o10000000;
pub const O_TMPFILE = 0o20200000;
pub const O_NDELAY = O_NONBLOCK;
|
lib/std/os/bits/windows.zig
|
const std = @import("std");
const math = std.math;
const builtin = @import("builtin");
const compiler_rt = @import("../compiler_rt.zig");
pub fn __multf3(a: f128, b: f128) callconv(.C) f128 {
return mulXf3(f128, a, b);
}
pub fn __mulxf3(a: f80, b: f80) callconv(.C) f80 {
return mulXf3(f80, a, b);
}
pub fn __muldf3(a: f64, b: f64) callconv(.C) f64 {
return mulXf3(f64, a, b);
}
pub fn __mulsf3(a: f32, b: f32) callconv(.C) f32 {
return mulXf3(f32, a, b);
}
pub fn __aeabi_fmul(a: f32, b: f32) callconv(.C) f32 {
@setRuntimeSafety(false);
return @call(.{ .modifier = .always_inline }, __mulsf3, .{ a, b });
}
pub fn __aeabi_dmul(a: f64, b: f64) callconv(.C) f64 {
@setRuntimeSafety(false);
return @call(.{ .modifier = .always_inline }, __muldf3, .{ a, b });
}
fn mulXf3(comptime T: type, a: T, b: T) T {
@setRuntimeSafety(builtin.is_test);
const typeWidth = @typeInfo(T).Float.bits;
const significandBits = math.floatMantissaBits(T);
const fractionalBits = math.floatFractionalBits(T);
const exponentBits = math.floatExponentBits(T);
const Z = std.meta.Int(.unsigned, typeWidth);
// ZSignificand is large enough to contain the significand, including an explicit integer bit
const ZSignificand = PowerOfTwoSignificandZ(T);
const ZSignificandBits = @typeInfo(ZSignificand).Int.bits;
const roundBit = (1 << (ZSignificandBits - 1));
const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
const integerBit = (@as(ZSignificand, 1) << fractionalBits);
const quietBit = integerBit >> 1;
const significandMask = (@as(Z, 1) << significandBits) - 1;
const absMask = signBit - 1;
const qnanRep = @bitCast(Z, math.nan(T)) | quietBit;
const infRep = @bitCast(Z, math.inf(T));
const minNormalRep = @bitCast(Z, math.floatMin(T));
const aExponent = @truncate(u32, (@bitCast(Z, a) >> significandBits) & maxExponent);
const bExponent = @truncate(u32, (@bitCast(Z, b) >> significandBits) & maxExponent);
const productSign: Z = (@bitCast(Z, a) ^ @bitCast(Z, b)) & signBit;
var aSignificand: ZSignificand = @intCast(ZSignificand, @bitCast(Z, a) & significandMask);
var bSignificand: ZSignificand = @intCast(ZSignificand, @bitCast(Z, b) & significandMask);
var scale: i32 = 0;
// Detect if a or b is zero, denormal, infinity, or NaN.
if (aExponent -% 1 >= maxExponent - 1 or bExponent -% 1 >= maxExponent - 1) {
const aAbs: Z = @bitCast(Z, a) & absMask;
const bAbs: Z = @bitCast(Z, b) & absMask;
// NaN * anything = qNaN
if (aAbs > infRep) return @bitCast(T, @bitCast(Z, a) | quietBit);
// anything * NaN = qNaN
if (bAbs > infRep) return @bitCast(T, @bitCast(Z, b) | quietBit);
if (aAbs == infRep) {
// infinity * non-zero = +/- infinity
if (bAbs != 0) {
return @bitCast(T, aAbs | productSign);
} else {
// infinity * zero = NaN
return @bitCast(T, qnanRep);
}
}
if (bAbs == infRep) {
//? non-zero * infinity = +/- infinity
if (aAbs != 0) {
return @bitCast(T, bAbs | productSign);
} else {
// zero * infinity = NaN
return @bitCast(T, qnanRep);
}
}
// zero * anything = +/- zero
if (aAbs == 0) return @bitCast(T, productSign);
// anything * zero = +/- zero
if (bAbs == 0) return @bitCast(T, productSign);
// one or both of a or b is denormal, the other (if applicable) is a
// normal number. Renormalize one or both of a and b, and set scale to
// include the necessary exponent adjustment.
if (aAbs < minNormalRep) scale += normalize(T, &aSignificand);
if (bAbs < minNormalRep) scale += normalize(T, &bSignificand);
}
// Or in the implicit significand bit. (If we fell through from the
// denormal path it was already set by normalize( ), but setting it twice
// won't hurt anything.)
aSignificand |= integerBit;
bSignificand |= integerBit;
// Get the significand of a*b. Before multiplying the significands, shift
// one of them left to left-align it in the field. Thus, the product will
// have (exponentBits + 2) integral digits, all but two of which must be
// zero. Normalizing this result is just a conditional left-shift by one
// and bumping the exponent accordingly.
var productHi: ZSignificand = undefined;
var productLo: ZSignificand = undefined;
const left_align_shift = ZSignificandBits - fractionalBits - 1;
wideMultiply(ZSignificand, aSignificand, bSignificand << left_align_shift, &productHi, &productLo);
var productExponent: i32 = @intCast(i32, aExponent + bExponent) - exponentBias + scale;
// Normalize the significand, adjust exponent if needed.
if ((productHi & integerBit) != 0) {
productExponent +%= 1;
} else {
productHi = (productHi << 1) | (productLo >> (ZSignificandBits - 1));
productLo = productLo << 1;
}
// If we have overflowed the type, return +/- infinity.
if (productExponent >= maxExponent) return @bitCast(T, infRep | productSign);
var result: Z = undefined;
if (productExponent <= 0) {
// Result is denormal before rounding
//
// If the result is so small that it just underflows to zero, return
// a zero of the appropriate sign. Mathematically there is no need to
// handle this case separately, but we make it a special case to
// simplify the shift logic.
const shift: u32 = @truncate(u32, @as(Z, 1) -% @bitCast(u32, productExponent));
if (shift >= ZSignificandBits) return @bitCast(T, productSign);
// Otherwise, shift the significand of the result so that the round
// bit is the high bit of productLo.
const sticky = wideShrWithTruncation(ZSignificand, &productHi, &productLo, shift);
productLo |= @boolToInt(sticky);
result = productHi;
} else {
// Result is normal before rounding; insert the exponent.
result = productHi & significandMask;
result |= @intCast(Z, productExponent) << significandBits;
}
// Final rounding. The final result may overflow to infinity, or underflow
// to zero, but those are the correct results in those cases. We use the
// default IEEE-754 round-to-nearest, ties-to-even rounding mode.
if (productLo > roundBit) result +%= 1;
if (productLo == roundBit) result +%= result & 1;
// Restore any explicit integer bit, if it was rounded off
if (significandBits != fractionalBits) {
if ((result >> significandBits) != 0) result |= integerBit;
}
// Insert the sign of the result:
result |= productSign;
return @bitCast(T, result);
}
fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
@setRuntimeSafety(builtin.is_test);
switch (Z) {
u16 => {
// 16x16 --> 32 bit multiply
const product = @as(u32, a) * @as(u32, b);
hi.* = @intCast(u16, product >> 16);
lo.* = @truncate(u16, product);
},
u32 => {
// 32x32 --> 64 bit multiply
const product = @as(u64, a) * @as(u64, b);
hi.* = @intCast(u32, product >> 32);
lo.* = @truncate(u32, product);
},
u64 => {
const S = struct {
fn loWord(x: u64) u64 {
return @truncate(u32, x);
}
fn hiWord(x: u64) u64 {
return @intCast(u32, x >> 32);
}
};
// 64x64 -> 128 wide multiply for platforms that don't have such an operation;
// many 64-bit platforms have this operation, but they tend to have hardware
// floating-point, so we don't bother with a special case for them here.
// Each of the component 32x32 -> 64 products
const plolo: u64 = S.loWord(a) * S.loWord(b);
const plohi: u64 = S.loWord(a) * S.hiWord(b);
const philo: u64 = S.hiWord(a) * S.loWord(b);
const phihi: u64 = S.hiWord(a) * S.hiWord(b);
// Sum terms that contribute to lo in a way that allows us to get the carry
const r0: u64 = S.loWord(plolo);
const r1: u64 = S.hiWord(plolo) +% S.loWord(plohi) +% S.loWord(philo);
lo.* = r0 +% (r1 << 32);
// Sum terms contributing to hi with the carry from lo
hi.* = S.hiWord(plohi) +% S.hiWord(philo) +% S.hiWord(r1) +% phihi;
},
u128 => {
const Word_LoMask = @as(u64, 0x00000000ffffffff);
const Word_HiMask = @as(u64, 0xffffffff00000000);
const Word_FullMask = @as(u64, 0xffffffffffffffff);
const S = struct {
fn Word_1(x: u128) u64 {
return @truncate(u32, x >> 96);
}
fn Word_2(x: u128) u64 {
return @truncate(u32, x >> 64);
}
fn Word_3(x: u128) u64 {
return @truncate(u32, x >> 32);
}
fn Word_4(x: u128) u64 {
return @truncate(u32, x);
}
};
// 128x128 -> 256 wide multiply for platforms that don't have such an operation;
// many 64-bit platforms have this operation, but they tend to have hardware
// floating-point, so we don't bother with a special case for them here.
const product11: u64 = S.Word_1(a) * S.Word_1(b);
const product12: u64 = S.Word_1(a) * S.Word_2(b);
const product13: u64 = S.Word_1(a) * S.Word_3(b);
const product14: u64 = S.Word_1(a) * S.Word_4(b);
const product21: u64 = S.Word_2(a) * S.Word_1(b);
const product22: u64 = S.Word_2(a) * S.Word_2(b);
const product23: u64 = S.Word_2(a) * S.Word_3(b);
const product24: u64 = S.Word_2(a) * S.Word_4(b);
const product31: u64 = S.Word_3(a) * S.Word_1(b);
const product32: u64 = S.Word_3(a) * S.Word_2(b);
const product33: u64 = S.Word_3(a) * S.Word_3(b);
const product34: u64 = S.Word_3(a) * S.Word_4(b);
const product41: u64 = S.Word_4(a) * S.Word_1(b);
const product42: u64 = S.Word_4(a) * S.Word_2(b);
const product43: u64 = S.Word_4(a) * S.Word_3(b);
const product44: u64 = S.Word_4(a) * S.Word_4(b);
const sum0: u128 = @as(u128, product44);
const sum1: u128 = @as(u128, product34) +%
@as(u128, product43);
const sum2: u128 = @as(u128, product24) +%
@as(u128, product33) +%
@as(u128, product42);
const sum3: u128 = @as(u128, product14) +%
@as(u128, product23) +%
@as(u128, product32) +%
@as(u128, product41);
const sum4: u128 = @as(u128, product13) +%
@as(u128, product22) +%
@as(u128, product31);
const sum5: u128 = @as(u128, product12) +%
@as(u128, product21);
const sum6: u128 = @as(u128, product11);
const r0: u128 = (sum0 & Word_FullMask) +%
((sum1 & Word_LoMask) << 32);
const r1: u128 = (sum0 >> 64) +%
((sum1 >> 32) & Word_FullMask) +%
(sum2 & Word_FullMask) +%
((sum3 << 32) & Word_HiMask);
lo.* = r0 +% (r1 << 64);
hi.* = (r1 >> 64) +%
(sum1 >> 96) +%
(sum2 >> 64) +%
(sum3 >> 32) +%
sum4 +%
(sum5 << 32) +%
(sum6 << 64);
},
else => @compileError("unsupported"),
}
}
/// Returns a power-of-two integer type that is large enough to contain
/// the significand of T, including an explicit integer bit
fn PowerOfTwoSignificandZ(comptime T: type) type {
const bits = math.ceilPowerOfTwoAssert(u16, math.floatFractionalBits(T) + 1);
return std.meta.Int(.unsigned, bits);
}
fn normalize(comptime T: type, significand: *PowerOfTwoSignificandZ(T)) i32 {
@setRuntimeSafety(builtin.is_test);
const Z = PowerOfTwoSignificandZ(T);
const integerBit = @as(Z, 1) << math.floatFractionalBits(T);
const shift = @clz(Z, significand.*) - @clz(Z, integerBit);
significand.* <<= @intCast(math.Log2Int(Z), shift);
return @as(i32, 1) - shift;
}
// Returns `true` if the right shift is inexact (i.e. any bit shifted out is non-zero)
//
// This is analogous to an shr version of `@shlWithOverflow`
fn wideShrWithTruncation(comptime Z: type, hi: *Z, lo: *Z, count: u32) bool {
@setRuntimeSafety(builtin.is_test);
const typeWidth = @typeInfo(Z).Int.bits;
const S = math.Log2Int(Z);
var inexact = false;
if (count < typeWidth) {
inexact = (lo.* << @intCast(S, typeWidth -% count)) != 0;
lo.* = (hi.* << @intCast(S, typeWidth -% count)) | (lo.* >> @intCast(S, count));
hi.* = hi.* >> @intCast(S, count);
} else if (count < 2 * typeWidth) {
inexact = (hi.* << @intCast(S, 2 * typeWidth -% count) | lo.*) != 0;
lo.* = hi.* >> @intCast(S, count -% typeWidth);
hi.* = 0;
} else {
inexact = (hi.* | lo.*) != 0;
lo.* = 0;
hi.* = 0;
}
return inexact;
}
test {
_ = @import("mulXf3_test.zig");
}
|
lib/std/special/compiler_rt/mulXf3.zig
|
const std = @import("std");
const ResourceTracker = struct {
const Self = @This();
var instance: ?*@This() = null;
resources: std.AutoHashMap(usize, usize),
resources_trace: std.AutoHashMap(usize, std.builtin.StackTrace),
resource_count: usize = 0,
alloc: *std.mem.Allocator,
pub fn get() ?*@This() {
return instance;
}
pub fn set(rs: *ResourceTracker) void {
instance = rs;
}
pub fn init(alloc: *std.mem.Allocator) @This() {
return @This(){
.alloc = alloc,
.resources = std.AutoHashMap(usize, usize).init(alloc),
.resources_trace = std.AutoHashMap(usize, std.builtin.StackTrace).init(alloc),
};
}
pub fn track(self: *Self, resource: anytype) void {
resource.index = self.resource_count;
self.resource_count += 1;
var trace = std.builtin.StackTrace{
.instruction_addresses = self.alloc.alloc(u64, 32) catch unreachable,
.index = 0,
};
_ = std.debug.captureStackTrace(null, &trace);
self.resources_trace.put(resource.index, trace) catch unreachable;
}
pub fn untrack(self: *Self, resource: anytype) void {
self.alloc.free(self.resources_trace.get(resource.index).?.instruction_addresses);
_ = self.resources_trace.remove(resource.index);
}
pub fn deinit(self: *Self) void {
// const stderr = std.io.getStdErr().writer();
var iter = self.resources_trace.iterator();
var panic = false;
while (iter.next()) |entry| {
if (self.resources_trace.get(entry.key_ptr.*)) |trace| {
std.debug.print("\n!!! RESOURCE LEAK STACK TRACE BEGIN !!!\n", .{});
std.debug.dumpStackTrace(trace);
std.debug.print("!!! RESOURCE LEAK STACK TRACE END !!!\n", .{});
}
panic = true;
}
var values = self.resources_trace.iterator();
while (values.next()) |v| {
self.alloc.free(v.value_ptr.instruction_addresses);
}
self.resources_trace.deinit();
self.resources.deinit();
if (panic)
std.debug.panic("Some resources remain allocated\n", .{});
}
};
pub fn R(comptime T: type) type {
return struct {
pub const __IsResource__ = true;
value: T,
resource_manager: usize,
deinit_fn: fn (usize, T) void,
index: usize = 0,
pub fn init(value: T, resource_manager: anytype, comptime deinit_fn: anytype) @This() {
const RM = @TypeOf(resource_manager);
const inner = struct {
pub fn deinit(rm: usize, v: T) void {
deinit_fn(@intToPtr(RM, rm), v);
}
};
var self = @This(){
.value = value,
.resource_manager = @ptrToInt(resource_manager),
.deinit_fn = inner.deinit,
};
if (ResourceTracker.get()) |rs|
rs.track(&self);
return self;
}
pub fn get(self: *@This()) T {
return self.value;
}
pub fn deinit(self: *@This()) void {
if (ResourceTracker.get()) |rs|
rs.untrack(self);
self.deinit_fn(self.resource_manager, self.value);
}
};
}
pub fn clean(value: anytype) void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Struct => {
if (@hasDecl(T, "deinit")) {
//hack to avoid *const
var v_ptr = @intToPtr(*T, @ptrToInt(&value));
v_ptr.deinit();
} else {
const fields = std.meta.fields(T);
inline for (fields) |field| {
clean(@field(value, field.name));
}
}
},
.Array => {
for (value) |e| {
clean(e);
}
},
.Optional => {
if (value) |v| {
clean(v);
}
},
.Union => |u| {
if (u.tag_type != null) {
var active = std.meta.activeTag(value);
const fields = std.meta.fields(std.meta.TagType(@TypeOf(value)));
inline for (fields) |f| {
if (f.value == @enumToInt(active)) {
clean(@field(value, f.name));
break;
}
}
}
},
else => {},
}
}
const Foo = struct {
data: R([]u8),
single: R(*u64),
pub fn init(allocator: *std.mem.Allocator) !@This() {
var data = R([]u8).init(try allocator.alloc(u8, 10), allocator, std.mem.Allocator.free);
errdefer clean(&data);
var data_v = data.get();
@memset(data_v.ptr, 0, data_v.len);
var single = R(*u64).init(try allocator.create(u64), allocator, std.mem.Allocator.destroy);
errdefer clean(&single);
return @This(){
.data = data,
.single = single,
};
}
};
//clean only works on tagged unions. for untagged unions, the struct should implement a deinit function
const FooU = union(enum) {
foo: Foo,
};
const Bar = struct {
foo: [2]?FooU = undefined, //an array of optional tagged unions, will get cleaned by clean
array: std.ArrayList(u8), //has a deinit function that takes no parameters, will be called by clean
pub fn init(allocator: *std.mem.Allocator) !@This() {
return @This(){
.foo = .{ .{ .foo = try Foo.init(allocator) }, .{ .foo = try Foo.init(allocator) } },
.array = std.ArrayList(u8).init(allocator),
};
}
};
test "R" {
var resource_tracker = ResourceTracker.init(std.testing.allocator);
ResourceTracker.set(&resource_tracker);
defer clean(resource_tracker);
{
var foo = try Foo.init(std.testing.allocator);
defer clean(foo);
var bar = try Bar.init(std.testing.allocator);
defer clean(bar);
try bar.array.append('a');
var foo2 = try Foo.init(std.testing.allocator);
defer clean(foo2);
}
}
|
r.zig
|
const std = @import("../index.zig");
const assert = std.debug.assert;
const ArrayList = std.ArrayList;
const Token = std.zig.Token;
const mem = std.mem;
pub const Node = struct {
id: Id,
pub const Id = enum {
// Top level
Root,
Use,
TestDecl,
// Statements
VarDecl,
Defer,
// Operators
InfixOp,
PrefixOp,
SuffixOp,
// Control flow
Switch,
While,
For,
If,
ControlFlowExpression,
Suspend,
// Type expressions
VarType,
ErrorType,
FnProto,
// Primary expressions
IntegerLiteral,
FloatLiteral,
StringLiteral,
MultilineStringLiteral,
CharLiteral,
BoolLiteral,
NullLiteral,
UndefinedLiteral,
ThisLiteral,
Unreachable,
Identifier,
GroupedExpression,
BuiltinCall,
ErrorSetDecl,
ContainerDecl,
Asm,
Comptime,
Block,
// Misc
LineComment,
SwitchCase,
SwitchElse,
Else,
Payload,
PointerPayload,
PointerIndexPayload,
StructField,
UnionTag,
EnumTag,
AsmInput,
AsmOutput,
AsyncAttribute,
ParamDecl,
FieldInitializer,
};
pub fn iterate(base: &Node, index: usize) ?&Node {
comptime var i = 0;
inline while (i < @memberCount(Id)) : (i += 1) {
if (base.id == @field(Id, @memberName(Id, i))) {
const T = @field(Node, @memberName(Id, i));
return @fieldParentPtr(T, "base", base).iterate(index);
}
}
unreachable;
}
pub fn firstToken(base: &Node) Token {
comptime var i = 0;
inline while (i < @memberCount(Id)) : (i += 1) {
if (base.id == @field(Id, @memberName(Id, i))) {
const T = @field(Node, @memberName(Id, i));
return @fieldParentPtr(T, "base", base).firstToken();
}
}
unreachable;
}
pub fn lastToken(base: &Node) Token {
comptime var i = 0;
inline while (i < @memberCount(Id)) : (i += 1) {
if (base.id == @field(Id, @memberName(Id, i))) {
const T = @field(Node, @memberName(Id, i));
return @fieldParentPtr(T, "base", base).lastToken();
}
}
unreachable;
}
pub fn typeToId(comptime T: type) Id {
comptime var i = 0;
inline while (i < @memberCount(Id)) : (i += 1) {
if (T == @field(Node, @memberName(Id, i))) {
return @field(Id, @memberName(Id, i));
}
}
unreachable;
}
pub const Root = struct {
base: Node,
decls: ArrayList(&Node),
eof_token: Token,
pub fn iterate(self: &Root, index: usize) ?&Node {
if (index < self.decls.len) {
return self.decls.items[self.decls.len - index - 1];
}
return null;
}
pub fn firstToken(self: &Root) Token {
return if (self.decls.len == 0) self.eof_token else self.decls.at(0).firstToken();
}
pub fn lastToken(self: &Root) Token {
return if (self.decls.len == 0) self.eof_token else self.decls.at(self.decls.len - 1).lastToken();
}
};
pub const VarDecl = struct {
base: Node,
comments: ?&LineComment,
visib_token: ?Token,
name_token: Token,
eq_token: Token,
mut_token: Token,
comptime_token: ?Token,
extern_export_token: ?Token,
lib_name: ?&Node,
type_node: ?&Node,
align_node: ?&Node,
init_node: ?&Node,
semicolon_token: Token,
pub fn iterate(self: &VarDecl, index: usize) ?&Node {
var i = index;
if (self.type_node) |type_node| {
if (i < 1) return type_node;
i -= 1;
}
if (self.align_node) |align_node| {
if (i < 1) return align_node;
i -= 1;
}
if (self.init_node) |init_node| {
if (i < 1) return init_node;
i -= 1;
}
return null;
}
pub fn firstToken(self: &VarDecl) Token {
if (self.visib_token) |visib_token| return visib_token;
if (self.comptime_token) |comptime_token| return comptime_token;
if (self.extern_export_token) |extern_export_token| return extern_export_token;
assert(self.lib_name == null);
return self.mut_token;
}
pub fn lastToken(self: &VarDecl) Token {
return self.semicolon_token;
}
};
pub const Use = struct {
base: Node,
visib_token: ?Token,
expr: &Node,
semicolon_token: Token,
pub fn iterate(self: &Use, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &Use) Token {
if (self.visib_token) |visib_token| return visib_token;
return self.expr.firstToken();
}
pub fn lastToken(self: &Use) Token {
return self.semicolon_token;
}
};
pub const ErrorSetDecl = struct {
base: Node,
error_token: Token,
decls: ArrayList(&Node),
rbrace_token: Token,
pub fn iterate(self: &ErrorSetDecl, index: usize) ?&Node {
var i = index;
if (i < self.decls.len) return self.decls.at(i);
i -= self.decls.len;
return null;
}
pub fn firstToken(self: &ErrorSetDecl) Token {
return self.error_token;
}
pub fn lastToken(self: &ErrorSetDecl) Token {
return self.rbrace_token;
}
};
pub const ContainerDecl = struct {
base: Node,
ltoken: Token,
layout: Layout,
kind: Kind,
init_arg_expr: InitArg,
fields_and_decls: ArrayList(&Node),
rbrace_token: Token,
const Layout = enum {
Auto,
Extern,
Packed,
};
const Kind = enum {
Struct,
Enum,
Union,
};
const InitArg = union(enum) {
None,
Enum,
Type: &Node,
};
pub fn iterate(self: &ContainerDecl, index: usize) ?&Node {
var i = index;
switch (self.init_arg_expr) {
InitArg.Type => |t| {
if (i < 1) return t;
i -= 1;
},
InitArg.None,
InitArg.Enum => { }
}
if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i);
i -= self.fields_and_decls.len;
return null;
}
pub fn firstToken(self: &ContainerDecl) Token {
return self.ltoken;
}
pub fn lastToken(self: &ContainerDecl) Token {
return self.rbrace_token;
}
};
pub const StructField = struct {
base: Node,
visib_token: ?Token,
name_token: Token,
type_expr: &Node,
pub fn iterate(self: &StructField, index: usize) ?&Node {
var i = index;
if (i < 1) return self.type_expr;
i -= 1;
return null;
}
pub fn firstToken(self: &StructField) Token {
if (self.visib_token) |visib_token| return visib_token;
return self.name_token;
}
pub fn lastToken(self: &StructField) Token {
return self.type_expr.lastToken();
}
};
pub const UnionTag = struct {
base: Node,
name_token: Token,
type_expr: ?&Node,
pub fn iterate(self: &UnionTag, index: usize) ?&Node {
var i = index;
if (self.type_expr) |type_expr| {
if (i < 1) return type_expr;
i -= 1;
}
return null;
}
pub fn firstToken(self: &UnionTag) Token {
return self.name_token;
}
pub fn lastToken(self: &UnionTag) Token {
if (self.type_expr) |type_expr| {
return type_expr.lastToken();
}
return self.name_token;
}
};
pub const EnumTag = struct {
base: Node,
name_token: Token,
value: ?&Node,
pub fn iterate(self: &EnumTag, index: usize) ?&Node {
var i = index;
if (self.value) |value| {
if (i < 1) return value;
i -= 1;
}
return null;
}
pub fn firstToken(self: &EnumTag) Token {
return self.name_token;
}
pub fn lastToken(self: &EnumTag) Token {
if (self.value) |value| {
return value.lastToken();
}
return self.name_token;
}
};
pub const Identifier = struct {
base: Node,
token: Token,
pub fn iterate(self: &Identifier, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &Identifier) Token {
return self.token;
}
pub fn lastToken(self: &Identifier) Token {
return self.token;
}
};
pub const AsyncAttribute = struct {
base: Node,
async_token: Token,
allocator_type: ?&Node,
rangle_bracket: ?Token,
pub fn iterate(self: &AsyncAttribute, index: usize) ?&Node {
var i = index;
if (self.allocator_type) |allocator_type| {
if (i < 1) return allocator_type;
i -= 1;
}
return null;
}
pub fn firstToken(self: &AsyncAttribute) Token {
return self.async_token;
}
pub fn lastToken(self: &AsyncAttribute) Token {
if (self.rangle_bracket) |rangle_bracket| {
return rangle_bracket;
}
return self.async_token;
}
};
pub const FnProto = struct {
base: Node,
comments: ?&LineComment,
visib_token: ?Token,
fn_token: Token,
name_token: ?Token,
params: ArrayList(&Node),
return_type: ReturnType,
var_args_token: ?Token,
extern_export_inline_token: ?Token,
cc_token: ?Token,
async_attr: ?&AsyncAttribute,
body_node: ?&Node,
lib_name: ?&Node, // populated if this is an extern declaration
align_expr: ?&Node, // populated if align(A) is present
pub const ReturnType = union(enum) {
Explicit: &Node,
InferErrorSet: &Node,
};
pub fn iterate(self: &FnProto, index: usize) ?&Node {
var i = index;
if (self.body_node) |body_node| {
if (i < 1) return body_node;
i -= 1;
}
switch (self.return_type) {
// TODO allow this and next prong to share bodies since the types are the same
ReturnType.Explicit => |node| {
if (i < 1) return node;
i -= 1;
},
ReturnType.InferErrorSet => |node| {
if (i < 1) return node;
i -= 1;
},
}
if (self.align_expr) |align_expr| {
if (i < 1) return align_expr;
i -= 1;
}
if (i < self.params.len) return self.params.items[self.params.len - i - 1];
i -= self.params.len;
if (self.lib_name) |lib_name| {
if (i < 1) return lib_name;
i -= 1;
}
return null;
}
pub fn firstToken(self: &FnProto) Token {
if (self.visib_token) |visib_token| return visib_token;
if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token;
assert(self.lib_name == null);
if (self.cc_token) |cc_token| return cc_token;
return self.fn_token;
}
pub fn lastToken(self: &FnProto) Token {
if (self.body_node) |body_node| return body_node.lastToken();
switch (self.return_type) {
// TODO allow this and next prong to share bodies since the types are the same
ReturnType.Explicit => |node| return node.lastToken(),
ReturnType.InferErrorSet => |node| return node.lastToken(),
}
}
};
pub const ParamDecl = struct {
base: Node,
comptime_token: ?Token,
noalias_token: ?Token,
name_token: ?Token,
type_node: &Node,
var_args_token: ?Token,
pub fn iterate(self: &ParamDecl, index: usize) ?&Node {
var i = index;
if (i < 1) return self.type_node;
i -= 1;
return null;
}
pub fn firstToken(self: &ParamDecl) Token {
if (self.comptime_token) |comptime_token| return comptime_token;
if (self.noalias_token) |noalias_token| return noalias_token;
if (self.name_token) |name_token| return name_token;
return self.type_node.firstToken();
}
pub fn lastToken(self: &ParamDecl) Token {
if (self.var_args_token) |var_args_token| return var_args_token;
return self.type_node.lastToken();
}
};
pub const Block = struct {
base: Node,
label: ?Token,
lbrace: Token,
statements: ArrayList(&Node),
rbrace: Token,
pub fn iterate(self: &Block, index: usize) ?&Node {
var i = index;
if (i < self.statements.len) return self.statements.items[i];
i -= self.statements.len;
return null;
}
pub fn firstToken(self: &Block) Token {
if (self.label) |label| {
return label;
}
return self.lbrace;
}
pub fn lastToken(self: &Block) Token {
return self.rbrace;
}
};
pub const Defer = struct {
base: Node,
defer_token: Token,
kind: Kind,
expr: &Node,
const Kind = enum {
Error,
Unconditional,
};
pub fn iterate(self: &Defer, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &Defer) Token {
return self.defer_token;
}
pub fn lastToken(self: &Defer) Token {
return self.expr.lastToken();
}
};
pub const Comptime = struct {
base: Node,
comptime_token: Token,
expr: &Node,
pub fn iterate(self: &Comptime, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &Comptime) Token {
return self.comptime_token;
}
pub fn lastToken(self: &Comptime) Token {
return self.expr.lastToken();
}
};
pub const Payload = struct {
base: Node,
lpipe: Token,
error_symbol: &Node,
rpipe: Token,
pub fn iterate(self: &Payload, index: usize) ?&Node {
var i = index;
if (i < 1) return self.error_symbol;
i -= 1;
return null;
}
pub fn firstToken(self: &Payload) Token {
return self.lpipe;
}
pub fn lastToken(self: &Payload) Token {
return self.rpipe;
}
};
pub const PointerPayload = struct {
base: Node,
lpipe: Token,
ptr_token: ?Token,
value_symbol: &Node,
rpipe: Token,
pub fn iterate(self: &PointerPayload, index: usize) ?&Node {
var i = index;
if (i < 1) return self.value_symbol;
i -= 1;
return null;
}
pub fn firstToken(self: &PointerPayload) Token {
return self.lpipe;
}
pub fn lastToken(self: &PointerPayload) Token {
return self.rpipe;
}
};
pub const PointerIndexPayload = struct {
base: Node,
lpipe: Token,
ptr_token: ?Token,
value_symbol: &Node,
index_symbol: ?&Node,
rpipe: Token,
pub fn iterate(self: &PointerIndexPayload, index: usize) ?&Node {
var i = index;
if (i < 1) return self.value_symbol;
i -= 1;
if (self.index_symbol) |index_symbol| {
if (i < 1) return index_symbol;
i -= 1;
}
return null;
}
pub fn firstToken(self: &PointerIndexPayload) Token {
return self.lpipe;
}
pub fn lastToken(self: &PointerIndexPayload) Token {
return self.rpipe;
}
};
pub const Else = struct {
base: Node,
else_token: Token,
payload: ?&Node,
body: &Node,
pub fn iterate(self: &Else, index: usize) ?&Node {
var i = index;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
return null;
}
pub fn firstToken(self: &Else) Token {
return self.else_token;
}
pub fn lastToken(self: &Else) Token {
return self.body.lastToken();
}
};
pub const Switch = struct {
base: Node,
switch_token: Token,
expr: &Node,
cases: ArrayList(&SwitchCase),
rbrace: Token,
pub fn iterate(self: &Switch, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
if (i < self.cases.len) return &self.cases.at(i).base;
i -= self.cases.len;
return null;
}
pub fn firstToken(self: &Switch) Token {
return self.switch_token;
}
pub fn lastToken(self: &Switch) Token {
return self.rbrace;
}
};
pub const SwitchCase = struct {
base: Node,
items: ArrayList(&Node),
payload: ?&Node,
expr: &Node,
pub fn iterate(self: &SwitchCase, index: usize) ?&Node {
var i = index;
if (i < self.items.len) return self.items.at(i);
i -= self.items.len;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &SwitchCase) Token {
return self.items.at(0).firstToken();
}
pub fn lastToken(self: &SwitchCase) Token {
return self.expr.lastToken();
}
};
pub const SwitchElse = struct {
base: Node,
token: Token,
pub fn iterate(self: &SwitchElse, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &SwitchElse) Token {
return self.token;
}
pub fn lastToken(self: &SwitchElse) Token {
return self.token;
}
};
pub const While = struct {
base: Node,
label: ?Token,
inline_token: ?Token,
while_token: Token,
condition: &Node,
payload: ?&Node,
continue_expr: ?&Node,
body: &Node,
@"else": ?&Else,
pub fn iterate(self: &While, index: usize) ?&Node {
var i = index;
if (i < 1) return self.condition;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (self.continue_expr) |continue_expr| {
if (i < 1) return continue_expr;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: &While) Token {
if (self.label) |label| {
return label;
}
if (self.inline_token) |inline_token| {
return inline_token;
}
return self.while_token;
}
pub fn lastToken(self: &While) Token {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const For = struct {
base: Node,
label: ?Token,
inline_token: ?Token,
for_token: Token,
array_expr: &Node,
payload: ?&Node,
body: &Node,
@"else": ?&Else,
pub fn iterate(self: &For, index: usize) ?&Node {
var i = index;
if (i < 1) return self.array_expr;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: &For) Token {
if (self.label) |label| {
return label;
}
if (self.inline_token) |inline_token| {
return inline_token;
}
return self.for_token;
}
pub fn lastToken(self: &For) Token {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const If = struct {
base: Node,
if_token: Token,
condition: &Node,
payload: ?&Node,
body: &Node,
@"else": ?&Else,
pub fn iterate(self: &If, index: usize) ?&Node {
var i = index;
if (i < 1) return self.condition;
i -= 1;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (i < 1) return self.body;
i -= 1;
if (self.@"else") |@"else"| {
if (i < 1) return &@"else".base;
i -= 1;
}
return null;
}
pub fn firstToken(self: &If) Token {
return self.if_token;
}
pub fn lastToken(self: &If) Token {
if (self.@"else") |@"else"| {
return @"else".body.lastToken();
}
return self.body.lastToken();
}
};
pub const InfixOp = struct {
base: Node,
op_token: Token,
lhs: &Node,
op: Op,
rhs: &Node,
pub const Op = union(enum) {
Add,
AddWrap,
ArrayCat,
ArrayMult,
Assign,
AssignBitAnd,
AssignBitOr,
AssignBitShiftLeft,
AssignBitShiftRight,
AssignBitXor,
AssignDiv,
AssignMinus,
AssignMinusWrap,
AssignMod,
AssignPlus,
AssignPlusWrap,
AssignTimes,
AssignTimesWarp,
BangEqual,
BitAnd,
BitOr,
BitShiftLeft,
BitShiftRight,
BitXor,
BoolAnd,
BoolOr,
Catch: ?&Node,
Div,
EqualEqual,
ErrorUnion,
GreaterOrEqual,
GreaterThan,
LessOrEqual,
LessThan,
MergeErrorSets,
Mod,
Mult,
MultWrap,
Period,
Range,
Sub,
SubWrap,
UnwrapMaybe,
};
pub fn iterate(self: &InfixOp, index: usize) ?&Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
switch (self.op) {
Op.Catch => |maybe_payload| {
if (maybe_payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
},
Op.Add,
Op.AddWrap,
Op.ArrayCat,
Op.ArrayMult,
Op.Assign,
Op.AssignBitAnd,
Op.AssignBitOr,
Op.AssignBitShiftLeft,
Op.AssignBitShiftRight,
Op.AssignBitXor,
Op.AssignDiv,
Op.AssignMinus,
Op.AssignMinusWrap,
Op.AssignMod,
Op.AssignPlus,
Op.AssignPlusWrap,
Op.AssignTimes,
Op.AssignTimesWarp,
Op.BangEqual,
Op.BitAnd,
Op.BitOr,
Op.BitShiftLeft,
Op.BitShiftRight,
Op.BitXor,
Op.BoolAnd,
Op.BoolOr,
Op.Div,
Op.EqualEqual,
Op.ErrorUnion,
Op.GreaterOrEqual,
Op.GreaterThan,
Op.LessOrEqual,
Op.LessThan,
Op.MergeErrorSets,
Op.Mod,
Op.Mult,
Op.MultWrap,
Op.Period,
Op.Range,
Op.Sub,
Op.SubWrap,
Op.UnwrapMaybe => {},
}
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: &InfixOp) Token {
return self.lhs.firstToken();
}
pub fn lastToken(self: &InfixOp) Token {
return self.rhs.lastToken();
}
};
pub const PrefixOp = struct {
base: Node,
op_token: Token,
op: Op,
rhs: &Node,
const Op = union(enum) {
AddrOf: AddrOfInfo,
ArrayType: &Node,
Await,
BitNot,
BoolNot,
Cancel,
Deref,
MaybeType,
Negation,
NegationWrap,
Resume,
SliceType: AddrOfInfo,
Try,
UnwrapMaybe,
};
const AddrOfInfo = struct {
align_expr: ?&Node,
bit_offset_start_token: ?Token,
bit_offset_end_token: ?Token,
const_token: ?Token,
volatile_token: ?Token,
};
pub fn iterate(self: &PrefixOp, index: usize) ?&Node {
var i = index;
switch (self.op) {
Op.SliceType => |addr_of_info| {
if (addr_of_info.align_expr) |align_expr| {
if (i < 1) return align_expr;
i -= 1;
}
},
Op.AddrOf => |addr_of_info| {
if (addr_of_info.align_expr) |align_expr| {
if (i < 1) return align_expr;
i -= 1;
}
},
Op.ArrayType => |size_expr| {
if (i < 1) return size_expr;
i -= 1;
},
Op.Await,
Op.BitNot,
Op.BoolNot,
Op.Cancel,
Op.Deref,
Op.MaybeType,
Op.Negation,
Op.NegationWrap,
Op.Try,
Op.Resume,
Op.UnwrapMaybe => {},
}
if (i < 1) return self.rhs;
i -= 1;
return null;
}
pub fn firstToken(self: &PrefixOp) Token {
return self.op_token;
}
pub fn lastToken(self: &PrefixOp) Token {
return self.rhs.lastToken();
}
};
pub const FieldInitializer = struct {
base: Node,
period_token: Token,
name_token: Token,
expr: &Node,
pub fn iterate(self: &FieldInitializer, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &FieldInitializer) Token {
return self.period_token;
}
pub fn lastToken(self: &FieldInitializer) Token {
return self.expr.lastToken();
}
};
pub const SuffixOp = struct {
base: Node,
lhs: &Node,
op: Op,
rtoken: Token,
const Op = union(enum) {
Call: CallInfo,
ArrayAccess: &Node,
Slice: SliceRange,
ArrayInitializer: ArrayList(&Node),
StructInitializer: ArrayList(&FieldInitializer),
};
const CallInfo = struct {
params: ArrayList(&Node),
async_attr: ?&AsyncAttribute,
};
const SliceRange = struct {
start: &Node,
end: ?&Node,
};
pub fn iterate(self: &SuffixOp, index: usize) ?&Node {
var i = index;
if (i < 1) return self.lhs;
i -= 1;
switch (self.op) {
Op.Call => |call_info| {
if (i < call_info.params.len) return call_info.params.at(i);
i -= call_info.params.len;
},
Op.ArrayAccess => |index_expr| {
if (i < 1) return index_expr;
i -= 1;
},
Op.Slice => |range| {
if (i < 1) return range.start;
i -= 1;
if (range.end) |end| {
if (i < 1) return end;
i -= 1;
}
},
Op.ArrayInitializer => |exprs| {
if (i < exprs.len) return exprs.at(i);
i -= exprs.len;
},
Op.StructInitializer => |fields| {
if (i < fields.len) return &fields.at(i).base;
i -= fields.len;
},
}
return null;
}
pub fn firstToken(self: &SuffixOp) Token {
return self.lhs.firstToken();
}
pub fn lastToken(self: &SuffixOp) Token {
return self.rtoken;
}
};
pub const GroupedExpression = struct {
base: Node,
lparen: Token,
expr: &Node,
rparen: Token,
pub fn iterate(self: &GroupedExpression, index: usize) ?&Node {
var i = index;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &GroupedExpression) Token {
return self.lparen;
}
pub fn lastToken(self: &GroupedExpression) Token {
return self.rparen;
}
};
pub const ControlFlowExpression = struct {
base: Node,
ltoken: Token,
kind: Kind,
rhs: ?&Node,
const Kind = union(enum) {
Break: ?&Node,
Continue: ?&Node,
Return,
};
pub fn iterate(self: &ControlFlowExpression, index: usize) ?&Node {
var i = index;
switch (self.kind) {
Kind.Break => |maybe_label| {
if (maybe_label) |label| {
if (i < 1) return label;
i -= 1;
}
},
Kind.Continue => |maybe_label| {
if (maybe_label) |label| {
if (i < 1) return label;
i -= 1;
}
},
Kind.Return => {},
}
if (self.rhs) |rhs| {
if (i < 1) return rhs;
i -= 1;
}
return null;
}
pub fn firstToken(self: &ControlFlowExpression) Token {
return self.ltoken;
}
pub fn lastToken(self: &ControlFlowExpression) Token {
if (self.rhs) |rhs| {
return rhs.lastToken();
}
switch (self.kind) {
Kind.Break => |maybe_label| {
if (maybe_label) |label| {
return label.lastToken();
}
},
Kind.Continue => |maybe_label| {
if (maybe_label) |label| {
return label.lastToken();
}
},
Kind.Return => return self.ltoken,
}
return self.ltoken;
}
};
pub const Suspend = struct {
base: Node,
suspend_token: Token,
payload: ?&Node,
body: ?&Node,
pub fn iterate(self: &Suspend, index: usize) ?&Node {
var i = index;
if (self.payload) |payload| {
if (i < 1) return payload;
i -= 1;
}
if (self.body) |body| {
if (i < 1) return body;
i -= 1;
}
return null;
}
pub fn firstToken(self: &Suspend) Token {
return self.suspend_token;
}
pub fn lastToken(self: &Suspend) Token {
if (self.body) |body| {
return body.lastToken();
}
if (self.payload) |payload| {
return payload.lastToken();
}
return self.suspend_token;
}
};
pub const IntegerLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &IntegerLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &IntegerLiteral) Token {
return self.token;
}
pub fn lastToken(self: &IntegerLiteral) Token {
return self.token;
}
};
pub const FloatLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &FloatLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &FloatLiteral) Token {
return self.token;
}
pub fn lastToken(self: &FloatLiteral) Token {
return self.token;
}
};
pub const BuiltinCall = struct {
base: Node,
builtin_token: Token,
params: ArrayList(&Node),
rparen_token: Token,
pub fn iterate(self: &BuiltinCall, index: usize) ?&Node {
var i = index;
if (i < self.params.len) return self.params.at(i);
i -= self.params.len;
return null;
}
pub fn firstToken(self: &BuiltinCall) Token {
return self.builtin_token;
}
pub fn lastToken(self: &BuiltinCall) Token {
return self.rparen_token;
}
};
pub const StringLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &StringLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &StringLiteral) Token {
return self.token;
}
pub fn lastToken(self: &StringLiteral) Token {
return self.token;
}
};
pub const MultilineStringLiteral = struct {
base: Node,
tokens: ArrayList(Token),
pub fn iterate(self: &MultilineStringLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &MultilineStringLiteral) Token {
return self.tokens.at(0);
}
pub fn lastToken(self: &MultilineStringLiteral) Token {
return self.tokens.at(self.tokens.len - 1);
}
};
pub const CharLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &CharLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &CharLiteral) Token {
return self.token;
}
pub fn lastToken(self: &CharLiteral) Token {
return self.token;
}
};
pub const BoolLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &BoolLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &BoolLiteral) Token {
return self.token;
}
pub fn lastToken(self: &BoolLiteral) Token {
return self.token;
}
};
pub const NullLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &NullLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &NullLiteral) Token {
return self.token;
}
pub fn lastToken(self: &NullLiteral) Token {
return self.token;
}
};
pub const UndefinedLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &UndefinedLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &UndefinedLiteral) Token {
return self.token;
}
pub fn lastToken(self: &UndefinedLiteral) Token {
return self.token;
}
};
pub const ThisLiteral = struct {
base: Node,
token: Token,
pub fn iterate(self: &ThisLiteral, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &ThisLiteral) Token {
return self.token;
}
pub fn lastToken(self: &ThisLiteral) Token {
return self.token;
}
};
pub const AsmOutput = struct {
base: Node,
symbolic_name: &Node,
constraint: &Node,
kind: Kind,
const Kind = union(enum) {
Variable: &Identifier,
Return: &Node
};
pub fn iterate(self: &AsmOutput, index: usize) ?&Node {
var i = index;
if (i < 1) return self.symbolic_name;
i -= 1;
if (i < 1) return self.constraint;
i -= 1;
switch (self.kind) {
Kind.Variable => |variable_name| {
if (i < 1) return &variable_name.base;
i -= 1;
},
Kind.Return => |return_type| {
if (i < 1) return return_type;
i -= 1;
}
}
return null;
}
pub fn firstToken(self: &AsmOutput) Token {
return self.symbolic_name.firstToken();
}
pub fn lastToken(self: &AsmOutput) Token {
return switch (self.kind) {
Kind.Variable => |variable_name| variable_name.lastToken(),
Kind.Return => |return_type| return_type.lastToken(),
};
}
};
pub const AsmInput = struct {
base: Node,
symbolic_name: &Node,
constraint: &Node,
expr: &Node,
pub fn iterate(self: &AsmInput, index: usize) ?&Node {
var i = index;
if (i < 1) return self.symbolic_name;
i -= 1;
if (i < 1) return self.constraint;
i -= 1;
if (i < 1) return self.expr;
i -= 1;
return null;
}
pub fn firstToken(self: &AsmInput) Token {
return self.symbolic_name.firstToken();
}
pub fn lastToken(self: &AsmInput) Token {
return self.expr.lastToken();
}
};
pub const Asm = struct {
base: Node,
asm_token: Token,
volatile_token: ?Token,
template: &Node,
//tokens: ArrayList(AsmToken),
outputs: ArrayList(&AsmOutput),
inputs: ArrayList(&AsmInput),
cloppers: ArrayList(&Node),
rparen: Token,
pub fn iterate(self: &Asm, index: usize) ?&Node {
var i = index;
if (i < self.outputs.len) return &self.outputs.at(index).base;
i -= self.outputs.len;
if (i < self.inputs.len) return &self.inputs.at(index).base;
i -= self.inputs.len;
if (i < self.cloppers.len) return self.cloppers.at(index);
i -= self.cloppers.len;
return null;
}
pub fn firstToken(self: &Asm) Token {
return self.asm_token;
}
pub fn lastToken(self: &Asm) Token {
return self.rparen;
}
};
pub const Unreachable = struct {
base: Node,
token: Token,
pub fn iterate(self: &Unreachable, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &Unreachable) Token {
return self.token;
}
pub fn lastToken(self: &Unreachable) Token {
return self.token;
}
};
pub const ErrorType = struct {
base: Node,
token: Token,
pub fn iterate(self: &ErrorType, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &ErrorType) Token {
return self.token;
}
pub fn lastToken(self: &ErrorType) Token {
return self.token;
}
};
pub const VarType = struct {
base: Node,
token: Token,
pub fn iterate(self: &VarType, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &VarType) Token {
return self.token;
}
pub fn lastToken(self: &VarType) Token {
return self.token;
}
};
pub const LineComment = struct {
base: Node,
lines: ArrayList(Token),
pub fn iterate(self: &LineComment, index: usize) ?&Node {
return null;
}
pub fn firstToken(self: &LineComment) Token {
return self.lines.at(0);
}
pub fn lastToken(self: &LineComment) Token {
return self.lines.at(self.lines.len - 1);
}
};
pub const TestDecl = struct {
base: Node,
comments: ?&LineComment,
test_token: Token,
name: &Node,
body_node: &Node,
pub fn iterate(self: &TestDecl, index: usize) ?&Node {
var i = index;
if (i < 1) return self.body_node;
i -= 1;
return null;
}
pub fn firstToken(self: &TestDecl) Token {
return self.test_token;
}
pub fn lastToken(self: &TestDecl) Token {
return self.body_node.lastToken();
}
};
};
|
std/zig/ast.zig
|
const std = @import("std");
const json = std.json;
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const Step = std.build.Step;
const print = std.debug.print;
const builtin = @import("builtin");
const Pkg = std.build.Pkg;
pub fn build(b: *Builder) !void {
// Options.
//const build_v8 = b.option(bool, "build_v8", "Whether to build from v8 source") orelse false;
const path = b.option([]const u8, "path", "Path to main file, for: build, run") orelse "";
const use_zig_tc = b.option(bool, "zig-toolchain", "Experimental: Use zig cc/c++/ld to build v8.") orelse false;
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const get_tools = createGetTools(b);
b.step("get-tools", "Gets the build tools.").dependOn(&get_tools.step);
const get_v8 = createGetV8(b);
b.step("get-v8", "Gets v8 source using gclient.").dependOn(&get_v8.step);
const get_cross = try createGetCross(b);
b.step("get-cross", "Gets sysroot headers for cross compilation to macos.").dependOn(&get_cross.step);
const v8 = try createV8_Build(b, target, mode, use_zig_tc);
b.step("v8", "Build v8 c binding lib.").dependOn(&v8.step);
const run_test = createTest(b, target, mode, use_zig_tc);
b.step("test", "Run tests.").dependOn(&run_test.step);
const build_exe = createBuildExeStep(b, path, target, mode, use_zig_tc);
b.step("exe", "Build exe with main file at -Dpath").dependOn(&build_exe.step);
const run_exe = build_exe.run();
b.step("run", "Run with main file at -Dpath").dependOn(&run_exe.step);
b.default_step.dependOn(&v8.step);
}
// When this is true, we'll strip V8 features down to a minimum so the resulting library is smaller.
// eg. i18n will be excluded.
const MinimalV8 = true;
// gclient is comprehensive and will pull everything for the v8 project.
// Set this to false to pull the minimal required src by parsing v8/DEPS and whitelisting deps we care about.
const UseGclient = false;
// V8's build process is complex and porting it to zig could take quite awhile.
// It would be nice if there was a way to import .gn files into the zig build system.
// For now we just use gn/ninja like rusty_v8 does: https://github.com/denoland/rusty_v8/blob/main/build.rs
fn createV8_Build(b: *Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode, use_zig_tc: bool) !*std.build.LogStep {
const step = b.addLog("Built V8\n", .{});
if (UseGclient) {
const mkpath = MakePathStep.create(b, "./gclient/v8/zig");
step.step.dependOn(&mkpath.step);
const cp = CopyFileStep.create(b, b.pathFromRoot("BUILD.gclient.gn"), b.pathFromRoot("gclient/v8/zig/BUILD.gn"));
step.step.dependOn(&cp.step);
} else {
const mkpath = MakePathStep.create(b, "./v8/zig");
step.step.dependOn(&mkpath.step);
const cp = CopyFileStep.create(b, b.pathFromRoot("BUILD.gn"), b.pathFromRoot("v8/zig/BUILD.gn"));
step.step.dependOn(&cp.step);
}
var gn_args = std.ArrayList([]const u8).init(b.allocator);
switch (target.getOsTag()) {
.macos => try gn_args.append("target_os=\"mac\""),
.windows => {
try gn_args.append("target_os=\"win\"");
if (!UseGclient) {
// Don't use depot_tools.
try b.env_map.put("DEPOT_TOOLS_WIN_TOOLCHAIN", "0");
}
},
.linux => try gn_args.append("target_os=\"linux\""),
else => {},
}
switch (target.getCpuArch()) {
.x86_64 => try gn_args.append("target_cpu=\"x64\""),
.aarch64 => try gn_args.append("target_cpu=\"arm64\""),
else => {},
}
var zig_asmflags = std.ArrayList([]const u8).init(b.allocator);
var zig_cppflags = std.ArrayList([]const u8).init(b.allocator);
var v8_zig_cppflags = std.ArrayList([]const u8).init(b.allocator);
var v8_zig_ldflags = std.ArrayList([]const u8).init(b.allocator);
if (mode == .Debug) {
try gn_args.append("is_debug=true");
// full debug info (symbol_level=2).
// Setting symbol_level=1 will produce enough information for stack traces, but not line-by-line debugging.
// Setting symbol_level=0 will include no debug symbols at all. Either will speed up the build compared to full symbols.
// This will eventually pass down to v8_symbol_level.
try gn_args.append("symbol_level=1");
} else {
try gn_args.append("is_debug=false");
try gn_args.append("symbol_level=0");
// is_official_build is meant to ship chrome.
// It might be interesting to see how far we can get with it (previously saw illegal instruction in Zone::NewExpand during mksnapshot_default since stacktraces were removed)
// but a better approach for now is to set to false and slowly enable optimizations. eg. We probably still want to unwind stack traces.
try gn_args.append("is_official_build=false");
// is_official_build will do pgo optimization by default for chrome specific builds that require gclient to fetch profile data.
// https://groups.google.com/a/chromium.org/g/chromium-dev/c/-0t4s0RlmOI
// Disable that with this:
//try gn_args.append("chrome_pgo_phase=0");
//if (use_zig_tc) {
// is_official_build will enable cfi but zig does not come with the default cfi_ignorelist.
//try zig_cppflags.append("-fno-sanitize-ignorelist");
//}
}
if (MinimalV8) {
// Don't add i18n for now. It has a large dependency on third_party/icu.
try gn_args.append("v8_enable_i18n_support=false");
}
if (mode != .Debug) {
// TODO: document
try gn_args.append("v8_enable_handle_zapping=false");
}
// Fix GN's host_cpu detection when using x86_64 bins on Apple Silicon
if (builtin.os.tag == .macos and builtin.cpu.arch == .aarch64) {
try gn_args.append("host_cpu=\"arm64\"");
}
if (use_zig_tc) {
// Use zig's libcxx instead.
// If there are problems we can see what types of flags is enabled when this is true.
try gn_args.append("use_custom_libcxx=false");
// custom_toolchain is how we can set zig as the cc/cxx compiler and linker.
try gn_args.append("custom_toolchain=\"//zig:main_zig_toolchain\"");
if (target.getOsTag() == .linux and target.getCpuArch() == .x86_64) {
// Should add target flags that matches: //build/config/compiler:compiler_cpu_abi
try zig_cppflags.append("--target=x86_64-linux-gnu");
try zig_cppflags.append("-m64");
try zig_cppflags.append("-msse3");
try gn_args.append("zig_ldflags=\"-m64\"");
} else if (target.getOsTag() == .macos and target.getCpuArch() == .aarch64) {
try zig_asmflags.append("--target=aarch64-macos-gnu");
try zig_cppflags.append("--target=aarch64-macos-gnu");
if (builtin.os.tag != .macos) {
// Cross compiling.
try zig_cppflags.append("-isystem");
const sysroot_abs = b.pathFromRoot("./vendor/sysroot/macos-12/usr/include");
try zig_cppflags.append(sysroot_abs);
}
if (builtin.cpu.arch != target.getCpuArch()) {
try gn_args.append("v8_snapshot_toolchain=\"//zig:v8_zig_toolchain\"");
const target_arg = try std.fmt.allocPrint(b.allocator, "--target={s}", .{getArchOs(b.allocator, builtin.cpu.arch, builtin.os.tag)});
try v8_zig_cppflags.append(target_arg);
try v8_zig_ldflags.append(target_arg);
}
}
// Just warn for now. TODO: Check to remove after next clang update.
// https://bugs.chromium.org/p/chromium/issues/detail?id=1016945
try gn_args.append("zig_cxxflags=\"-Wno-error=builtin-assume-aligned-alignment\"");
try gn_args.append("v8_zig_cxxflags=\"-Wno-error=builtin-assume-aligned-alignment\"");
try gn_args.append("use_zig_tc=true");
try gn_args.append("cxx_use_ld=\"zig ld.lld\"");
// Build extra compiler flags.
const zig_asmflags_str = try std.mem.join(b.allocator, " ", zig_asmflags.items);
const zig_asmflags_arg = try std.fmt.allocPrint(b.allocator, "zig_asmflags=\"{s}\"", .{zig_asmflags_str});
try gn_args.append(zig_asmflags_arg);
const zig_cppflags_str = try std.mem.join(b.allocator, " ", zig_cppflags.items);
const zig_cppflags_arg = try std.fmt.allocPrint(b.allocator, "zig_cppflags=\"{s}\"", .{zig_cppflags_str});
try gn_args.append(zig_cppflags_arg);
const v8_zig_cppflags_str = try std.mem.join(b.allocator, " ", v8_zig_cppflags.items);
const v8_zig_cppflags_arg = try std.fmt.allocPrint(b.allocator, "v8_zig_cppflags=\"{s}\"", .{v8_zig_cppflags_str});
try gn_args.append(v8_zig_cppflags_arg);
const v8_zig_ldflags_str = try std.mem.join(b.allocator, " ", v8_zig_ldflags.items);
const v8_zig_ldflags_arg = try std.fmt.allocPrint(b.allocator, "v8_zig_ldflags=\"{s}\"", .{v8_zig_ldflags_str});
try gn_args.append(v8_zig_ldflags_arg);
} else {
if (builtin.os.tag != .windows) {
try gn_args.append("cxx_use_ld=\"lld\"");
}
}
// sccache, currently does not work with zig cc
if (!use_zig_tc) {
if (b.env_map.get("SCCACHE")) |path| {
const cc_wrapper = try std.fmt.allocPrint(b.allocator, "cc_wrapper=\"{s}\"", .{path});
try gn_args.append(cc_wrapper);
} else {
if (builtin.os.tag == .windows) {
// findProgram look for "PATH" case sensitive.
try b.env_map.put("PATH", b.env_map.get("Path") orelse "");
}
if (b.findProgram(&.{"sccache"}, &.{})) |_| {
const cc_wrapper = try std.fmt.allocPrint(b.allocator, "cc_wrapper=\"{s}\"", .{"sccache"});
try gn_args.append(cc_wrapper);
} else |err| {
if (err != error.FileNotFound) {
unreachable;
}
}
if (builtin.os.tag == .windows) {
// After creating PATH for windows so findProgram can find sccache, we need to delete it
// or a gn tool (build/toolchain/win/setup_toolchain.py) will complain about not finding cl.exe.
b.env_map.remove("PATH");
}
}
}
// var check_deps = CheckV8DepsStep.create(b);
// step.step.dependOn(&check_deps.step);
const mode_str: []const u8 = if (mode == .Debug) "debug" else "release";
// GN will generate ninja build files in ninja_out_path which will also contain the artifacts after running ninja.
const ninja_out_path = try std.fmt.allocPrint(b.allocator, "v8-out/{s}/{s}/ninja", .{
getTargetId(b.allocator, target),
mode_str,
});
const gn = getGnPath(b);
const arg_items = try std.mem.join(b.allocator, " ", gn_args.items);
const args = try std.mem.join(b.allocator, "", &.{ "--args=", arg_items });
// Currently we have to use gclient/v8 as the source root since all those nested gn files expects it, (otherwise, we'll run into duplicate argument declaration errors.)
// --dotfile lets us use a different .gn outside of the source root.
// --root-target is a directory that must be inside the source root where we can have a custom BUILD.gn.
// Since gclient/v8 is not part of our repo, we copy over BUILD.gn to gclient/v8/zig/BUILD.gn before we run gn.
// To see v8 dependency tree:
// cd gclient/v8 && gn desc ../../v8-out/x86_64-linux/release/ninja/ :v8 --tree
// We can't see our own config because gn desc doesn't accept a --root-target.
// One idea is to append our BUILD.gn to the v8 BUILD.gn instead of putting it in a subdirectory.
if (UseGclient) {
var run_gn = b.addSystemCommand(&.{ gn, "--root=gclient/v8", "--root-target=//zig", "--dotfile=.gn", "gen", ninja_out_path, args });
step.step.dependOn(&run_gn.step);
} else {
// To see available args for gn: cd v8 && gn args --list ../v8-out/{target}/release/ninja/
var run_gn = b.addSystemCommand(&.{ gn, "--root=v8", "--root-target=//zig", "--dotfile=.gn", "gen", ninja_out_path, args });
step.step.dependOn(&run_gn.step);
}
const ninja = getNinjaPath(b);
// Only build our target. If no target is specified, ninja will build all the targets which includes developer tools, tests, etc.
var run_ninja = b.addSystemCommand(&.{ ninja, "-C", ninja_out_path, "c_v8" });
step.step.dependOn(&run_ninja.step);
return step;
}
fn getArchOs(alloc: std.mem.Allocator, arch: std.Target.Cpu.Arch, os: std.Target.Os.Tag) []const u8 {
return std.fmt.allocPrint(alloc, "{s}-{s}-gnu", .{@tagName(arch), @tagName(os)}) catch unreachable;
}
fn getTargetId(alloc: std.mem.Allocator, target: std.zig.CrossTarget) []const u8 {
return std.fmt.allocPrint(alloc, "{s}-{s}", .{ @tagName(target.getCpuArch()), @tagName(target.getOsTag()) }) catch unreachable;
}
const CheckV8DepsStep = struct {
const Self = @This();
step: Step,
b: *Builder,
fn create(b: *Builder) *Self {
const step = b.allocator.create(Self) catch unreachable;
step.* = .{
.step = Step.init(.custom, "check_v8_deps", b.allocator, make),
.b = b,
};
return step;
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(Self, "step", step);
const output = try self.b.execFromStep(&.{ "clang", "--version" }, step);
print("clang: {s}", .{output});
// TODO: Find out the actual minimum and check against other clang flavors.
if (std.mem.startsWith(u8, output, "Homebrew clang version ")) {
const i = std.mem.indexOfScalar(u8, output, '.').?;
const major_v = try std.fmt.parseInt(u8, output["Homebrew clang version ".len..i], 10);
if (major_v < 13) {
return error.BadClangVersion;
}
}
}
};
fn createGetCross(b: *Builder) !*std.build.LogStep {
const step = b.addLog("Get Cross Tools\n", .{});
const stat = try statPathFromRoot(b, "vendor");
if (stat == .NotExist) {
const clone = b.addSystemCommand(&.{ "git", "clone", "--depth=1", "https://github.com/fubark/zig-v8-vendor.git", "vendor"});
step.step.dependOn(&clone.step);
}
return step;
}
fn createGetV8(b: *Builder) *std.build.LogStep {
const step = b.addLog("Get V8\n", .{});
if (UseGclient) {
const mkpath = MakePathStep.create(b, "./gclient");
step.step.dependOn(&mkpath.step);
// About depot_tools: https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up
const cmd = b.addSystemCommand(&.{ b.pathFromRoot("./tools/depot_tools/fetch"), "v8" });
cmd.cwd = "./gclient";
cmd.addPathDir(b.pathFromRoot("./tools/depot_tools"));
step.step.dependOn(&cmd.step);
} else {
const get = GetV8SourceStep.create(b);
step.step.dependOn(&get.step);
}
return step;
}
fn createGetTools(b: *Builder) *std.build.LogStep {
const step = b.addLog("Get Tools\n", .{});
var sub_step = b.addSystemCommand(&.{ "python", "./tools/get_ninja_gn_binaries.py", "--dir", "./tools" });
step.step.dependOn(&sub_step.step);
if (UseGclient) {
// Pull depot_tools for fetch tool.
sub_step = b.addSystemCommand(&.{ "git", "clone", "--depth=1", "https://chromium.googlesource.com/chromium/tools/depot_tools.git", "tools/depot_tools"});
step.step.dependOn(&sub_step.step);
}
return step;
}
fn getNinjaPath(b: *Builder) []const u8 {
const platform = switch (builtin.os.tag) {
.windows => "win",
.linux => "linux64",
.macos => "mac",
else => unreachable,
};
const ext = if (builtin.os.tag == .windows) ".exe" else "";
const bin = std.mem.concat(b.allocator, u8, &.{ "ninja", ext }) catch unreachable;
return std.fs.path.resolve(b.allocator, &.{ "./tools/ninja_gn_binaries-20210101", platform, bin }) catch unreachable;
}
fn getGnPath(b: *Builder) []const u8 {
const platform = switch (builtin.os.tag) {
.windows => "win",
.linux => "linux64",
.macos => "mac",
else => unreachable,
};
const ext = if (builtin.os.tag == .windows) ".exe" else "";
const bin = std.mem.concat(b.allocator, u8, &.{ "gn", ext }) catch unreachable;
return std.fs.path.resolve(b.allocator, &.{ "./tools/ninja_gn_binaries-20210101", platform, bin }) catch unreachable;
}
const MakePathStep = struct {
const Self = @This();
step: std.build.Step,
b: *Builder,
path: []const u8,
fn create(b: *Builder, root_path: []const u8) *Self {
const new = b.allocator.create(Self) catch unreachable;
new.* = .{
.step = std.build.Step.init(.custom, b.fmt("make-path", .{}), b.allocator, make),
.b = b,
.path = root_path,
};
return new;
}
fn make(step: *std.build.Step) anyerror!void {
const self = @fieldParentPtr(Self, "step", step);
try self.b.makePath(self.path);
}
};
const CopyFileStep = struct {
const Self = @This();
step: std.build.Step,
b: *Builder,
src_path: []const u8,
dst_path: []const u8,
fn create(b: *Builder, src_path: []const u8, dst_path: []const u8) *Self {
const new = b.allocator.create(Self) catch unreachable;
new.* = .{
.step = std.build.Step.init(.custom, b.fmt("cp", .{}), b.allocator, make),
.b = b,
.src_path = src_path,
.dst_path = dst_path,
};
return new;
}
fn make(step: *std.build.Step) anyerror!void {
const self = @fieldParentPtr(Self, "step", step);
try std.fs.copyFileAbsolute(self.src_path, self.dst_path, .{});
}
};
fn linkV8(b: *Builder, step: *std.build.LibExeObjStep, use_zig_tc: bool) void {
const mode = step.build_mode;
const target = step.target;
const mode_str: []const u8 = if (mode == .Debug) "debug" else "release";
const lib: []const u8 = if (target.getOsTag() == .windows) "c_v8.lib" else "libc_v8.a";
const lib_path = std.fmt.allocPrint(b.allocator, "./v8-out/{s}/{s}/ninja/obj/zig/{s}", .{
getTargetId(b.allocator, target),
mode_str,
lib,
}) catch unreachable;
step.addAssemblyFile(lib_path);
if (builtin.os.tag == .linux) {
if (use_zig_tc) {
// TODO: This should be linked already when we built v8.
step.linkLibCpp();
}
step.linkSystemLibrary("unwind");
} else if (builtin.os.tag == .windows) {
step.linkSystemLibrary("Dbghelp");
step.linkSystemLibrary("Winmm");
step.linkSystemLibrary("Advapi32");
// We need libcpmt to statically link with c++ stl for exception_ptr references from V8.
// Zig already adds the SDK path to the linker but doesn't sync it to the internal libs array which linkSystemLibrary checks against.
// For now we'll hardcode the MSVC path here.
step.addLibPath("C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/lib/x64");
step.linkSystemLibrary("libcpmt");
}
}
fn createTest(b: *Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode, use_zig_tc: bool) *std.build.LibExeObjStep {
const step = b.addTest("./test/test.zig");
step.setMainPkgPath(".");
step.addIncludeDir("./src");
step.setTarget(target);
step.setBuildMode(mode);
step.linkLibC();
linkV8(b, step, use_zig_tc);
return step;
}
const DepEntry = struct {
const Self = @This();
alloc: std.mem.Allocator,
repo_url: []const u8,
repo_rev: []const u8,
pub fn deinit(self: Self) void {
self.alloc.free(self.repo_url);
self.alloc.free(self.repo_rev);
}
};
fn getV8Rev(b: *Builder) ![]const u8 {
const file = try std.fs.openFileAbsolute(b.pathFromRoot("V8_REVISION"), .{ .read = true, .write = false});
defer file.close();
return std.mem.trim(u8, try file.readToEndAlloc(b.allocator, 1e9), "\n\r ");
}
pub const GetV8SourceStep = struct {
const Self = @This();
step: Step,
b: *Builder,
pub fn create(b: *Builder) *Self {
const self = b.allocator.create(Self) catch unreachable;
self.* = .{
.b = b,
.step = Step.init(.run, "Get V8 Sources.", b.allocator, make),
};
return self;
}
fn parseDep(self: Self, deps: json.Value, key: []const u8) !DepEntry {
const val = deps.Object.get(key).?;
const i = std.mem.lastIndexOfScalar(u8, val.String, '@').?;
const repo_rev = try self.b.allocator.dupe(u8, val.String[i+1..]);
const repo_url = try std.mem.replaceOwned(u8, self.b.allocator, val.String[0..i], "@chromium_url", "https://chromium.googlesource.com");
return DepEntry{
.alloc = self.b.allocator,
.repo_url = repo_url,
.repo_rev = repo_rev,
};
}
fn getDep(self: *Self, deps: json.Value, key: []const u8, local_path: []const u8) !void {
const dep = try self.parseDep(deps, key);
defer dep.deinit();
const stat = try statPathFromRoot(self.b, local_path);
if (stat == .NotExist) {
_ = try self.b.execFromStep(&.{ "git", "clone", dep.repo_url, local_path }, &self.step);
// Apply patch for v8/build
if (std.mem.eql(u8, key, "build")) {
_ = try self.b.execFromStep(&.{ "git", "apply", "patches/v8_build.patch", "--directory=v8/build" }, &self.step);
}
}
_ = try self.b.execFromStep(&.{ "git", "-C", local_path, "checkout", dep.repo_rev }, &self.step);
}
fn runHook(self: *Self, hooks: json.Value, name: []const u8) !void {
for (hooks.Array.items) |hook| {
if (std.mem.eql(u8, name, hook.Object.get("name").?.String)) {
const cmd = hook.Object.get("action").?.Array;
var args = std.ArrayList([]const u8).init(self.b.allocator);
defer args.deinit();
for (cmd.items) |it| {
try args.append(it.String);
}
const cwd = self.b.pathFromRoot("v8");
_ = try self.b.spawnChildEnvMap(cwd, self.b.env_map, args.items);
break;
}
}
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(Self, "step", step);
// Pull the minimum source we need by looking at DEPS.
// TODO: Check if we have the right branches, otherwise reclone.
// Get revision/tag to checkout.
const v8_rev = try getV8Rev(self.b);
// Clone V8.
const stat = try statPathFromRoot(self.b, "v8");
if (stat == .NotExist) {
_ = try self.b.execFromStep(&.{ "git", "clone", "--depth=1", "--branch", v8_rev, "https://chromium.googlesource.com/v8/v8.git", "v8" }, &self.step);
}
// Get DEPS in json.
const deps_json = try self.b.execFromStep(&.{ "python", "tools/parse_deps.py", "v8/DEPS" }, &self.step);
defer self.b.allocator.free(deps_json);
var p = json.Parser.init(self.b.allocator, false);
defer p.deinit();
var tree = try p.parse(deps_json);
defer tree.deinit();
var deps = tree.root.Object.get("deps").?;
var hooks = tree.root.Object.get("hooks").?;
// build
try self.getDep(deps, "build", "v8/build");
// Add an empty gclient_args.gni so gn is happy. gclient also creates an empty file.
const file = try std.fs.createFileAbsolute(self.b.pathFromRoot("v8/build/config/gclient_args.gni"), .{ .read = false, .truncate = true });
try file.writeAll("# Generated from build.zig");
file.close();
// buildtools
try self.getDep(deps, "buildtools", "v8/buildtools");
// libc++
try self.getDep(deps, "buildtools/third_party/libc++/trunk", "v8/buildtools/third_party/libc++/trunk");
// tools/clang
try self.getDep(deps, "tools/clang", "v8/tools/clang");
try self.runHook(hooks, "clang");
// third_party/zlib
try self.getDep(deps, "third_party/zlib", "v8/third_party/zlib");
// libc++abi
try self.getDep(deps, "buildtools/third_party/libc++abi/trunk", "v8/buildtools/third_party/libc++abi/trunk");
// googletest
try self.getDep(deps, "third_party/googletest/src", "v8/third_party/googletest/src");
// trace_event
try self.getDep(deps, "base/trace_event/common", "v8/base/trace_event/common");
// jinja2
try self.getDep(deps, "third_party/jinja2", "v8/third_party/jinja2");
// markupsafe
try self.getDep(deps, "third_party/markupsafe", "v8/third_party/markupsafe");
// For windows.
if (builtin.os.tag == .windows) {
// lastchange.py is flaky when it tries to do git commands from subprocess.Popen. Will sometimes get [WinError 50].
// For now we'll just do it in zig.
// try self.runHook(hooks, "lastchange");
const merge_base_sha = "HEAD";
const commit_filter = "^Change-Id:";
const grep_arg = try std.fmt.allocPrint(self.b.allocator, "--grep={s}", .{commit_filter});
const version_info = try self.b.execFromStep(&.{ "git", "-C", "v8/build", "log", "-1", "--format=%H %ct", grep_arg, merge_base_sha }, &self.step);
const idx = std.mem.indexOfScalar(u8, version_info, ' ').?;
const commit_timestamp = version_info[idx+1..];
// build/timestamp.gni expects the file to be just the unix timestamp.
const write = std.fs.createFileAbsolute(self.b.pathFromRoot("v8/build/util/LASTCHANGE.committime"), .{ .truncate = true }) catch unreachable;
defer write.close();
write.writeAll(commit_timestamp) catch unreachable;
}
}
};
fn createBuildExeStep(b: *Builder, path: []const u8, target: std.zig.CrossTarget, mode: std.builtin.Mode, use_zig_tc: bool) *LibExeObjStep {
const basename = std.fs.path.basename(path);
const i = std.mem.indexOf(u8, basename, ".zig") orelse basename.len;
const name = basename[0..i];
const step = b.addExecutable(name, path);
step.setBuildMode(mode);
step.setTarget(target);
step.linkLibC();
step.addIncludeDir("src");
const output_dir_rel = std.fmt.allocPrint(b.allocator, "zig-out/{s}", .{ name }) catch unreachable;
const output_dir = b.pathFromRoot(output_dir_rel);
step.setOutputDir(output_dir);
if (mode == .ReleaseSafe) {
step.strip = true;
}
linkV8(b, step, use_zig_tc);
return step;
}
const PathStat = enum {
NotExist,
Directory,
File,
SymLink,
Unknown,
};
fn statPathFromRoot(b: *Builder, path_rel: []const u8) !PathStat {
const path_abs = b.pathFromRoot(path_rel);
const file = std.fs.openFileAbsolute(path_abs, .{ .read = false, .write = false }) catch |err| {
if (err == error.FileNotFound) {
return .NotExist;
} else if (err == error.IsDir) {
return .Directory;
} else {
return err;
}
};
defer file.close();
const stat = try file.stat();
switch (stat.kind) {
.SymLink => return .SymLink,
.Directory => return .Directory,
.File => return .File,
else => return .Unknown,
}
}
|
build.zig
|
const std = @import("std");
usingnamespace std.os.windows;
const GetLastError = kernel32.GetLastError;
pub const GDI_ERROR = 0xFFFFFFFF;
pub const DIB_RGB_COLORS = 0;
pub const SRCCOPY = 0x00CC0020;
pub const BI_RGB = 0;
pub const HGDIOBJ = ?*c_void;
pub const PAINTSTRUCT = extern struct {
hdc: ?HDC,
fErase: BOOL,
rcPaint: RECT,
fRestore: BOOL,
fIncUpdate: BOOL,
rgbReserved: [32]BYTE,
};
pub const HBITMAP = *opaque {};
pub const RGBQUAD = extern struct {
rgbBlue: BYTE,
rgbGreen: BYTE,
rgbRed: BYTE,
rgbReserved: BYTE,
};
pub const BITMAPINFOHEADER = extern struct {
biSize: DWORD,
biWidth: LONG,
biHeight: LONG,
biPlanes: WORD,
biBitCount: WORD,
biCompression: DWORD,
biSizeImage: DWORD,
biXPelsPerMeter: LONG,
biYPelsPerMeter: LONG,
biClrUsed: DWORD,
biClrImportant: DWORD,
};
pub const BITMAPINFO = extern struct {
bmiHeader: BITMAPINFOHEADER,
bmiColors: [1]RGBQUAD,
};
pub const VK_ESCAPE = 0x1B;
pub const VK_SPACE = 0x20;
pub const VK_LEFT = 0x25;
pub const VK_UP = 0x26;
pub const VK_RIGHT = 0x27;
pub const VK_DOWN = 0x28;
pub const VK_PRINT = 0x2A;
pub const VK_F4 = 0x73;
// TODO is simply changing HDC to HWND correct?
pub extern "user32" fn PatBlt(hdc: HWND, x: c_int, y: c_int, w: c_int, h: c_int, rop: DWORD) callconv(WINAPI) BOOL;
pub fn patBlt(hWnd: HWND, x: i32, y: i32, w: i32, h: i32, rop: u32) bool {
return if (PatBlt(hWnd, x, y, w, h, rop) != 0) true else false;
}
pub extern "user32" fn BeginPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) callconv(WINAPI) ?HDC;
pub fn beginPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) ?HDC {
return BeginPaint(hWnd, lpPaint);
}
pub extern "user32" fn EndPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) callconv(WINAPI) BOOL;
pub fn endPaint(hWnd: HWND, lpPaint: *PAINTSTRUCT) bool {
return if (EndPaint(hWnd, lpPaint) != 0) true else false;
}
pub extern "user32" fn GetClientRect(hWnd: HWND, lpRect: *RECT) callconv(WINAPI) BOOL;
pub fn getClientRect(hWnd: HWND, lpRect: *RECT) !void {
const r = GetClientRect(hWnd, lpRect);
if (r != 0) return;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
}
pub extern "user32" fn CreateDIBSection(hdc: HDC, pbmi: *BITMAPINFO, usage: c_uint, ppvBits: [*c]?*c_void, hSection: ?HANDLE, offset: DWORD) callconv(WINAPI) ?HBITMAP;
pub fn createDIBSection(hdc: HDC, pbmi: *BITMAPINFO, usage: c_uint, ppvBits: [*c]?*c_void, hSection: ?HANDLE, offset: DWORD) ?HBITMAP {
return CreateDIBSection(hdc, pbmi, usage, ppvBits, hSection, offset);
}
// NOTE: Another way is to change lpBits to `?[*:0]const u32`
// Then I can use a slice instead of the slice's pointer
pub extern "user32" fn StretchDIBits(hdc: HDC, xDest: c_int, yDest: c_int, DestWidth: c_int, DestHeight: c_int, xSrc: c_int, ySrc: c_int, SrcWidth: c_int, SrcHeight: c_int, lpBits: ?*const c_void, lpbmi: *BITMAPINFO, iUsage: c_uint, rop: DWORD) callconv(WINAPI) c_int;
pub fn stretchDIBits(hdc: HDC, xDest: i32, yDest: i32, DestWidth: i32, DestHeight: i32, xSrc: i32, ySrc: i32, SrcWidth: i32, SrcHeight: i32, lpBits: ?*const c_void, lpbmi: *BITMAPINFO, iUsage: c_uint, rop: DWORD) !i32 {
const r = StretchDIBits(hdc, xDest, yDest, DestWidth, DestHeight, xSrc, ySrc, SrcWidth, SrcHeight, lpBits, lpbmi, iUsage, rop);
// TODO: check if we should really return an error if r == 0
// if (r == 0) return error.SomeError;
if (r == GDI_ERROR) return error.GdiError;
return r;
}
pub extern "user32" fn DeleteObject(ho: ?LPVOID) callconv(WINAPI) BOOL;
pub fn deleteObject(ho: ?*c_void) bool {
return if (DeleteObject(ho) != 0) true else false;
}
pub extern "gdi32" fn CreateCompatibleDC(hdc: ?HDC) callconv(WINAPI) ?HDC;
pub fn createCompatibleDC(hdc: ?HDC) ?HDC {
return CreateCompatibleDC(hdc);
}
|
src/windows.zig
|
const std = @import("std");
const ston = @import("../ston.zig");
const debug = std.debug;
const fmt = std.fmt;
const io = std.io;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const testing = std.testing;
/// Given a type `T`, figure out wether or not it is an `Index(G, K)`.
pub fn isIndex(comptime T: type) bool {
if (@typeInfo(T) != .Struct)
return false;
if (!@hasDecl(T, "IndexType") or !@hasDecl(T, "ValueType"))
return false;
if (@TypeOf(T.IndexType) != type or @TypeOf(T.ValueType) != type)
return false;
return T == ston.Index(T.IndexType, T.ValueType);
}
comptime {
debug.assert(!isIndex(u8));
debug.assert(isIndex(ston.Index(u8, u8)));
debug.assert(isIndex(ston.Index(u16, u16)));
debug.assert(!isIndex(struct {
pub const IndexType = u8;
pub const ValueType = u8;
index: IndexType,
value: ValueType,
}));
}
/// Given a type `T`, figure out wether or not it is an `Field(K)`.
pub fn isField(comptime T: type) bool {
if (@typeInfo(T) != .Struct)
return false;
if (!@hasDecl(T, "ValueType"))
return false;
if (@TypeOf(T.ValueType) != type)
return false;
return T == ston.Field(T.ValueType);
}
comptime {
debug.assert(!isField(u8));
debug.assert(isField(ston.Field(u8)));
debug.assert(isField(ston.Field(u16)));
debug.assert(!isField(struct {
pub const ValueType = u8;
name: []const u8,
value: ValueType,
}));
}
const HashMapParams = struct {
K: type,
V: type,
Context: type,
Hash: type,
};
fn hashMapParams(comptime T: type) ?HashMapParams {
if (@hasDecl(T, "Managed"))
return hashMapParams(T.Managed);
if (!@hasDecl(T, "KV") or !@hasField(T, "ctx"))
return null;
if (@typeInfo(T.KV) != .Struct)
return null;
if (!@hasField(T.KV, "key") or !@hasField(T.KV, "value"))
return null;
const Context = std.meta.fieldInfo(T, .ctx).field_type;
if (!@hasDecl(Context, "hash"))
return null;
const HashFn = @TypeOf(Context.hash);
const Hash = switch (@typeInfo(HashFn)) {
.Fn => |info| info.return_type orelse return null,
else => return null,
};
return HashMapParams{
.K = std.meta.fieldInfo(T.KV, .key).field_type,
.V = std.meta.fieldInfo(T.KV, .value).field_type,
.Context = Context,
.Hash = Hash,
};
}
/// Given a type `T`, figure out wether it is a `std.HashMap`
pub fn isHashMap(comptime T: type) bool {
if (@typeInfo(T) != .Struct)
return false;
if (@hasDecl(T, "Managed"))
return isHashMap(T.Managed);
const Params = hashMapParams(T) orelse return false;
if (Params.Hash != u64)
return false;
for ([_]void{{}} ** 100) |_, i| {
if (T == std.HashMap(Params.K, Params.V, Params.Context, i + 1))
return true;
}
return false;
}
comptime {
debug.assert(!isHashMap(u8));
debug.assert(isHashMap(std.AutoHashMap(u8, u8)));
debug.assert(!isHashMap(std.AutoArrayHashMap(u8, u8)));
}
/// Given a type `T`, figure out wether it is a `std.ArrayHashMap`
pub fn isArrayHashMap(comptime T: type) bool {
if (@typeInfo(T) != .Struct)
return false;
if (@hasDecl(T, "Managed"))
return isArrayHashMap(T.Managed);
const Params = hashMapParams(T) orelse return false;
if (Params.Hash != u32)
return false;
return T == std.ArrayHashMap(Params.K, Params.V, Params.Context, false) or
T == std.ArrayHashMap(Params.K, Params.V, Params.Context, true);
}
comptime {
debug.assert(!isArrayHashMap(u8));
debug.assert(!isArrayHashMap(std.AutoHashMap(u8, u8)));
debug.assert(isArrayHashMap(std.AutoArrayHashMap(u8, u8)));
}
pub fn isMap(comptime T: type) bool {
return isArrayHashMap(T) or isHashMap(T);
}
comptime {
debug.assert(!isMap(u8));
debug.assert(isMap(std.AutoHashMap(u8, u8)));
debug.assert(isMap(std.AutoArrayHashMap(u8, u8)));
}
pub fn isIntMap(comptime T: type) bool {
if (!isMap(T))
return false;
const Params = hashMapParams(T).?;
return @typeInfo(Params.K) == .Int;
}
comptime {
debug.assert(!isIntMap(u8));
debug.assert(isIntMap(std.AutoHashMap(u8, u8)));
debug.assert(isIntMap(std.AutoArrayHashMap(u8, u8)));
debug.assert(isIntMap(std.AutoArrayHashMapUnmanaged(u8, u16)));
debug.assert(!isIntMap(std.AutoHashMap([2]u8, u8)));
debug.assert(!isIntMap(std.AutoArrayHashMap([2]u8, u8)));
}
pub fn isArrayList(comptime T: type) bool {
if (@typeInfo(T) != .Struct or !@hasDecl(T, "Slice"))
return false;
const Slice = T.Slice;
const ptr_info = switch (@typeInfo(Slice)) {
.Pointer => |info| info,
else => return false,
};
return T == std.ArrayListAligned(ptr_info.child, null) or
T == std.ArrayListAligned(ptr_info.child, ptr_info.alignment) or
T == std.ArrayListAlignedUnmanaged(ptr_info.child, null) or
T == std.ArrayListAlignedUnmanaged(ptr_info.child, ptr_info.alignment);
}
comptime {
debug.assert(!isArrayList(u8));
debug.assert(isArrayList(std.ArrayList(u8)));
debug.assert(isArrayList(std.ArrayListUnmanaged(u8)));
}
|
src/meta.zig
|
const upaya = @import("upaya.zig");
const imgui = @import("imgui");
pub fn setTintColor(color: imgui.ImVec4) void {
var colors = &imgui.igGetStyle().Colors;
colors[imgui.ImGuiCol_FrameBg] = hsvShiftColor(color, 0, 0, -0.2);
colors[imgui.ImGuiCol_Border] = hsvShiftColor(color, 0, 0, -0.2);
const header = hsvShiftColor(color, 0, -0.2, 0);
colors[imgui.ImGuiCol_Header] = header;
colors[imgui.ImGuiCol_HeaderHovered] = hsvShiftColor(header, 0, 0, 0.1);
colors[imgui.ImGuiCol_HeaderActive] = hsvShiftColor(header, 0, 0, -0.1);
const title = hsvShiftColor(color, 0, 0.1, 0);
colors[imgui.ImGuiCol_TitleBg] = title;
colors[imgui.ImGuiCol_TitleBgActive] = title;
const tab = hsvShiftColor(color, 0, 0.1, 0);
colors[imgui.ImGuiCol_Tab] = tab;
colors[imgui.ImGuiCol_TabActive] = hsvShiftColor(tab, 0.05, 0.2, 0.2);
colors[imgui.ImGuiCol_TabHovered] = hsvShiftColor(tab, 0.02, 0.1, 0.2);
colors[imgui.ImGuiCol_TabUnfocused] = hsvShiftColor(tab, 0, -0.1, 0);
colors[imgui.ImGuiCol_TabUnfocusedActive] = colors[imgui.ImGuiCol_TabActive];
const button = hsvShiftColor(color, -0.05, 0, 0);
colors[imgui.ImGuiCol_Button] = button;
colors[imgui.ImGuiCol_ButtonHovered] = hsvShiftColor(button, 0, 0, 0.1);
colors[imgui.ImGuiCol_ButtonActive] = hsvShiftColor(button, 0, 0, -0.1);
}
pub fn hsvShiftColor(color: imgui.ImVec4, h_shift: f32, s_shift: f32, v_shift: f32) imgui.ImVec4 {
var h: f32 = undefined;
var s: f32 = undefined;
var v: f32 = undefined;
imgui.igColorConvertRGBtoHSV(color.x, color.y, color.z, &h, &s, &v);
h += h_shift;
s += s_shift;
v += v_shift;
var out_color = color;
imgui.igColorConvertHSVtoRGB(h, s, v, &out_color.x, &out_color.y, &out_color.z);
return out_color;
}
pub fn rgbToU32(r: i32, g: i32, b: i32) imgui.ImU32 {
return imgui.ogColorConvertFloat4ToU32(.{ .x = @intToFloat(f32, r) / 255, .y = @intToFloat(f32, g) / 255, .z = @intToFloat(f32, b) / 255, .w = 1 });
}
pub fn rgbToVec4(r: i32, g: i32, b: i32) imgui.ImVec4 {
return .{ .x = @intToFloat(f32, r) / 255, .y = @intToFloat(f32, g) / 255, .z = @intToFloat(f32, b) / 255, .w = 1 };
}
pub fn rgbaToU32(r: i32, g: i32, b: i32, a: i32) imgui.ImU32 {
return imgui.ogColorConvertFloat4ToU32(.{ .x = @intToFloat(f32, r) / 255, .y = @intToFloat(f32, g) / 255, .z = @intToFloat(f32, b) / 255, .w = @intToFloat(f32, a) / 255 });
}
pub fn rgbaToVec4(r: i32, g: i32, b: i32, a: i32) imgui.ImVec4 {
return .{ .x = @intToFloat(f32, r) / 255, .y = @intToFloat(f32, g) / 255, .z = @intToFloat(f32, b) / 255, .w = @intToFloat(f32, a) };
}
|
src/colors.zig
|
const std = @import("std");
const info = std.log.info;
const warn = std.log.warn;
const bus = @import("bus.zig");
const pif = @import("pif.zig");
const mi = @import("mi.zig");
const InterruptSource = mi.InterruptSource;
const SIReg = enum(u64) {
SIDRAMAddr = 0x00,
SIPIFAddrRD64 = 0x04,
SIPIFAddrWR4 = 0x08,
SIPIFAddrWR64 = 0x10,
SIPIFAddrRD4 = 0x14,
SIStatus = 0x18,
};
const SIStatus = packed struct {
dmaBusy : bool = false,
ioBusy : bool = false,
readPending: bool = false,
dmaError : bool = false,
pchState : u3 = 0,
dmaState : u3 = 0,
dmaIRQ : bool = false,
_pad0 : u21 = 0,
};
const SIRegs = struct {
siDRAMAddr: u24 = 0,
siPIFAddr : u32 = 0,
siStatus : SIStatus = SIStatus{},
};
var siRegs = SIRegs{};
pub fn read32(pAddr: u64) u32 {
var data: u32 = undefined;
switch (pAddr & 0xFF) {
@enumToInt(SIReg.SIStatus) => {
info("[SI] Read32 @ pAddr: {X}h (SI Status).", .{pAddr});
data = @bitCast(u32, siRegs.siStatus);
},
else => {
warn("[SI] Unhandled read32 @ pAddr: {X}h.", .{pAddr});
@panic("unhandled SI read");
}
}
return data;
}
pub fn write32(pAddr: u64, data: u32) void {
switch (pAddr & 0xFF) {
@enumToInt(SIReg.SIDRAMAddr) => {
info("[SI] Write32 @ pAddr: {X}h (SI DRAM Address), data: {X}h.", .{pAddr, data});
siRegs.siDRAMAddr = @truncate(u24, data);
},
@enumToInt(SIReg.SIPIFAddrRD64) => {
info("[SI] Write32 @ pAddr: {X}h (SI PIF Address RD64), data: {X}h.", .{pAddr, data});
siRegs.siPIFAddr = data;
doDMAToRAM(64);
},
@enumToInt(SIReg.SIPIFAddrWR64) => {
info("[SI] Write32 @ pAddr: {X}h (SI PIF Address WR64), data: {X}h.", .{pAddr, data});
siRegs.siPIFAddr = data;
doDMAToPIF(64);
},
@enumToInt(SIReg.SIStatus) => {
info("[SI] Write32 @ pAddr: {X}h (SI Status), data: {X}h.", .{pAddr, data});
siRegs.siStatus.dmaIRQ = false;
mi.clearPending(InterruptSource.SI);
},
else => {
warn("[SI] Unhandled write32 @ pAddr: {X}h, data: {X}h.", .{pAddr, data});
@panic("unhandled SI write");
}
}
}
fn doDMAToPIF(comptime len: comptime_int) void {
const ramAddr = @intCast(usize, siRegs.siDRAMAddr);
const pifAddr = @intCast(usize, siRegs.siPIFAddr);
info("[SI] RAM->PIF DMA, DRAM pAddr: {X}h, PIF pAddr: {X}h, length: {}.", .{ramAddr, pifAddr, len});
var idx: usize = 0;
while (idx < len) : (idx += 1) {
pif.pifRAM[(pifAddr + idx) - pif.pifRAMBase] = bus.ram[ramAddr + idx];
}
siRegs.siStatus.dmaIRQ = true;
mi.setPending(InterruptSource.SI);
}
fn doDMAToRAM(comptime len: comptime_int) void {
const ramAddr = @intCast(usize, siRegs.siDRAMAddr);
const pifAddr = @intCast(usize, siRegs.siPIFAddr);
info("[SI] PIF->RAM DMA, DRAM pAddr: {X}h, PIF pAddr: {X}h, length: {}.", .{ramAddr, pifAddr, len});
pif.checkStatus();
var idx: usize = 0;
while (idx < len) : (idx += 1) {
bus.ram[ramAddr + idx] = pif.pifRAM[(pifAddr + idx) - pif.pifRAMBase];
}
siRegs.siStatus.dmaIRQ = true;
mi.setPending(InterruptSource.SI);
}
|
src/core/si.zig
|
const Object = @This();
const std = @import("std");
const coff = std.coff;
const mem = std.mem;
const fs = std.fs;
const assert = std.debug.assert;
const log = std.log.scoped(.coff);
const Allocator = mem.Allocator;
file: fs.File,
name: []const u8,
header: CoffHeader = undefined,
symtab: std.ArrayListUnmanaged(Symbol) = .{},
shdrtab: std.ArrayListUnmanaged(SectionHeader) = .{},
strtab: []u8 = undefined,
// TODO: Make these public in std.coff
const CoffHeader = packed struct {
machine: u16,
number_of_sections: u16,
timedate_stamp: u32,
pointer_to_symbol_table: u32,
number_of_symbols: u32,
size_of_optional_header: u16,
characteristics: u16,
};
const IMAGE_FILE_MACHINE_I386 = 0x014c;
const IMAGE_FILE_MACHINE_IA64 = 0x0200;
const IMAGE_FILE_MACHINE_AMD64 = 0x8664;
const SectionHeader = packed struct {
const Misc = packed union {
physical_address: u32,
virtual_size: u32,
};
name: [8]u8,
misc: Misc,
size_of_raw_data: u32,
pointer_to_raw_data: u32,
pointer_to_relocations: u32,
pointer_to_line_numbers: u32,
number_of_relocations: u16,
number_of_line_numbers: u16,
characteristics: u32,
};
const Symbol = packed struct {
name: [8]u8,
value: u32,
sect_num: i16,
type: u16,
storage_class: i8,
num_aux: u8,
pub fn getName(self: Symbol, object: *Object) []const u8 {
if (mem.readIntNative(u32, self.name[0..4]) == 0x0) {
const offset = mem.readIntNative(u32, self.name[4..]);
return object.getString(offset);
} else {
return mem.span(@ptrCast([*:0]const u8, &self.name));
}
}
};
pub const IMAGE_SYM_CLASS_END_OF_FUNCTION = 0xff;
pub const IMAGE_SYM_CLASS_NULL = 0;
pub const IMAGE_SYM_CLASS_AUTOMATIC = 1;
pub const IMAGE_SYM_CLASS_EXTERNAL = 2;
pub const IMAGE_SYM_CLASS_STATIC = 3;
pub const IMAGE_SYM_CLASS_REGISTER = 4;
pub const IMAGE_SYM_CLASS_EXTERNAL_DEF = 5;
pub const IMAGE_SYM_CLASS_LABEL = 6;
pub const IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7;
pub const IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8;
pub const IMAGE_SYM_CLASS_ARGUMENT = 9;
pub const IMAGE_SYM_CLASS_STRUCT_TAG = 10;
pub const IMAGE_SYN_CLASS_MEMBER_OF_UNION = 11;
pub const IMAGE_SYM_CLASS_UNION_TAG = 12;
pub const IMAGE_SYM_CLASS_TYPE_DEFINITION = 13;
pub const IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14;
pub const IMAGE_SYM_CLASS_ENUM_TAG = 15;
pub const IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16;
pub const IMAGE_SYM_CLASS_REGISTER_PARAM = 17;
pub const IMAGE_SYM_CLASS_BIT_FIELD = 18;
pub const IMAGE_SYM_CLASS_BLOCK = 100;
pub const IMAGE_SYM_CLASS_FUNCTION = 101;
pub const IMAGE_SYM_CLASS_END_OF_STRUCT = 102;
pub const IMAGE_SYM_CLASS_FILE = 103;
pub const IMAGE_SYM_CLASS_SECTION = 104;
pub const IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105;
pub const IMAGE_SYM_CLASS_CLR_TOKEN = 107;
comptime {
assert(@sizeOf(Symbol) == 18);
assert(@sizeOf(CoffHeader) == 20);
}
pub fn deinit(self: *Object, allocator: Allocator) void {
self.symtab.deinit(allocator);
self.shdrtab.deinit(allocator);
allocator.free(self.strtab);
allocator.free(self.name);
}
pub fn parse(self: *Object, allocator: Allocator, target: std.Target) !void {
const reader = self.file.reader();
const header = try reader.readStruct(CoffHeader);
if (header.size_of_optional_header != 0) {
log.debug("Optional header not expected in an object file", .{});
return error.NotObject;
}
if (header.machine != @enumToInt(target.cpu.arch.toCoffMachine())) {
log.debug("Invalid architecture {any}, expected {any}", .{
header.machine,
target.cpu.arch.toCoffMachine(),
});
return error.InvalidCpuArch;
}
self.header = header;
try self.parseShdrs(allocator);
try self.parseSymtab(allocator);
try self.parseStrtab(allocator);
}
fn parseShdrs(self: *Object, allocator: Allocator) !void {
try self.shdrtab.ensureTotalCapacity(allocator, self.header.number_of_sections);
var i: usize = 0;
while (i < self.header.number_of_sections) : (i += 1) {
const section = try self.file.reader().readStruct(SectionHeader);
self.shdrtab.appendAssumeCapacity(section);
}
}
fn parseSymtab(self: *Object, allocator: Allocator) !void {
const offset = self.header.pointer_to_symbol_table;
try self.file.seekTo(offset);
try self.symtab.ensureTotalCapacity(allocator, self.header.number_of_symbols);
var i: usize = 0;
var num_aux: usize = 0;
while (i < self.header.number_of_symbols) : (i += 1) {
const symbol = try self.file.reader().readStruct(Symbol);
// Ignore symbol if it has invalid section number
if (symbol.sect_num < 1 or symbol.sect_num > self.shdrtab.items.len) {
continue;
}
// Ignore auxillary symbols
if (num_aux > 0) {
num_aux -= 1;
continue;
}
// Check for upcoming auxillary symbols
if (symbol.num_aux != 0) {
num_aux = symbol.num_aux;
}
self.symtab.appendAssumeCapacity(symbol);
}
}
fn parseStrtab(self: *Object, allocator: Allocator) !void {
const string_table_size = (try self.file.reader().readIntNative(u32)) - @sizeOf(u32);
self.strtab = try allocator.alloc(u8, string_table_size);
_ = try self.file.reader().read(self.strtab);
}
pub fn getString(self: *Object, off: u32) []const u8 {
const local_offset = off - @sizeOf(u32);
assert(local_offset < self.symtab.items.len);
return mem.span(@ptrCast([*:0]const u8, self.strtab.ptr + local_offset));
}
|
src/Coff/Object.zig
|
const std = @import("std");
const stdx = @import("stdx");
const build_options = @import("build_options");
const Backend = build_options.GraphicsBackend;
const gl = @import("gl");
pub const GLTextureId = gl.GLuint;
const vk = @import("vk");
const stbi = @import("stbi");
const graphics = @import("../../graphics.zig");
const gpu = graphics.gpu;
const gvk = graphics.vk;
const log = stdx.log.scoped(.image);
const ImageId = graphics.ImageId;
pub const TextureId = u32;
pub const ImageStore = struct {
alloc: std.mem.Allocator,
images: stdx.ds.CompactUnorderedList(ImageId, Image),
gctx: *graphics.gpu.Graphics,
textures: stdx.ds.CompactUnorderedList(TextureId, Texture),
/// Images are queued for removal due to multiple frames in flight.
removals: std.ArrayList(RemoveEntry),
const Self = @This();
pub fn init(alloc: std.mem.Allocator, gctx: *graphics.gpu.Graphics) Self {
var ret = Self{
.alloc = alloc,
.images = stdx.ds.CompactUnorderedList(ImageId, Image).init(alloc),
.textures = stdx.ds.CompactUnorderedList(TextureId, Texture).init(alloc),
.gctx = gctx,
.removals = std.ArrayList(RemoveEntry).init(alloc),
};
return ret;
}
pub fn deinit(self: Self) void {
// Delete images after since some deinit could have removed images.
self.images.deinit();
var iter = self.textures.iterator();
while (iter.next()) |tex| {
if (Backend == .Vulkan) {
tex.deinitVK(self.gctx.inner.ctx.device);
} else if (Backend == .OpenGL) {
tex.deinitGL();
}
}
self.textures.deinit();
self.removals.deinit();
}
/// Cleans up images and their textures that are no longer used.
pub fn processRemovals(self: *Self) void {
for (self.removals.items) |*entry, entry_idx| {
if (entry.frame_age < gpu.MaxActiveFrames) {
entry.frame_age += 1;
continue;
}
const image = self.images.getNoCheck(entry.image_id);
const tex_id = image.tex_id;
const tex = self.textures.getPtrNoCheck(tex_id);
self.images.remove(entry.image_id);
// Remove from texture's image list.
for (tex.inner.cs_images.items) |id, i| {
if (id == entry.image_id) {
_ = tex.inner.cs_images.swapRemove(i);
}
}
// No more images in the texture. Cleanup.
if (tex.inner.cs_images.items.len == 0) {
if (Backend == .Vulkan) {
tex.deinitVK(self.gctx.inner.ctx.device);
} else if (Backend == .OpenGL) {
tex.deinitGL();
}
self.textures.remove(tex_id);
}
// Remove the entry.
_ = self.removals.swapRemove(entry_idx);
}
}
pub fn createImageFromData(self: *Self, data: []const u8) !graphics.Image {
var src_width: c_int = undefined;
var src_height: c_int = undefined;
var channels: c_int = undefined;
const bitmap = stbi.stbi_load_from_memory(data.ptr, @intCast(c_int, data.len), &src_width, &src_height, &channels, 0);
defer stbi.stbi_image_free(bitmap);
if (bitmap == null) {
log.debug("{s}", .{stbi.stbi_failure_reason()});
return error.BadImage;
}
// log.debug("loaded image: {} {} {} {*}", .{src_width, src_height, channels, bitmap});
const bitmap_len = @intCast(usize, src_width * src_height * channels);
const desc = self.createImageFromBitmap(@intCast(usize, src_width), @intCast(usize, src_height), bitmap[0..bitmap_len], true);
return graphics.Image{
.id = desc.image_id,
.width = @intCast(usize, src_width),
.height = @intCast(usize, src_height),
};
}
// TODO: Each texture resource should be an atlas of images since the number of textures is limited on the gpu.
pub fn createImageFromBitmapInto(self: *Self, image: *Image, width: usize, height: usize, data: ?[]const u8, linear_filter: bool) ImageId {
self.initImage(image, width, height, data, linear_filter);
if (Backend == .Vulkan) {
const device = self.gctx.inner.ctx.device;
const desc_pool = self.gctx.inner.tex_desc_pool;
const layout = self.gctx.inner.tex_desc_set_layout;
const desc_set = gvk.descriptor.createDescriptorSet(device, desc_pool, layout);
const image_infos: []vk.VkDescriptorImageInfo = &[_]vk.VkDescriptorImageInfo{
vk.VkDescriptorImageInfo{
.imageLayout = vk.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.imageView = image.inner.image_view,
.sampler = image.inner.sampler,
},
};
gvk.descriptor.updateDescriptorSet(device, desc_set, image_infos);
// Currently each image allocates a new texture.
const tex_id = self.textures.add(.{
.inner = .{
.desc_set = desc_set,
.image = image.inner.image,
.image_view = image.inner.image_view,
.image_mem = image.inner.image_mem,
.sampler = image.inner.sampler,
.cs_images = std.ArrayList(ImageId).init(self.alloc),
},
}) catch stdx.fatal();
image.tex_id = tex_id;
} else if (Backend == .OpenGL) {
const tex_id = self.textures.add(.{
.inner = .{
// TODO: initImage shouldn't be set tex_id to gl tex id.
.tex_id = image.tex_id,
},
}) catch stdx.fatal();
image.tex_id = tex_id;
}
return self.images.add(image.*) catch stdx.fatal();
}
// TODO: Rename to initTexture.
pub fn initImage(self: *Self, image: *Image, width: usize, height: usize, data: ?[]const u8, linear_filter: bool) void {
switch (Backend) {
.OpenGL => {
graphics.gl.initImage(image, width, height, data, linear_filter);
},
.Vulkan => {
graphics.vk.VkContext.initImage(self.gctx.inner.ctx, image, width, height, data, linear_filter);
},
else => stdx.panicUnsupported(),
}
}
pub fn createImageFromBitmap(self: *Self, width: usize, height: usize, data: ?[]const u8, linear_filter: bool) ImageTex {
var image: Image = undefined;
const image_id = self.createImageFromBitmapInto(&image, width, height, data, linear_filter);
return ImageTex{
.image_id = image_id,
.tex_id = image.tex_id,
};
}
pub fn markForRemoval(self: *Self, id: ImageId) void {
const image = self.images.getPtrNoCheck(id);
if (!image.remove) {
self.removals.append(.{
.image_id = id,
.frame_age = 0,
}) catch stdx.fatal();
image.remove = true;
}
}
pub inline fn getTexture(self: Self, id: TextureId) Texture {
return self.textures.getNoCheck(id);
}
pub fn endCmdAndMarkForRemoval(self: *Self, image_id: ImageId) void {
const image = self.images.getNoCheck(image_id);
// If we deleted the current tex, flush and reset to default texture.
if (self.gctx.batcher.cur_image_tex.tex_id == image.tex_id) {
self.gctx.endCmd();
self.gctx.batcher.cur_image_tex = self.gctx.white_tex;
}
self.markForRemoval(image_id);
}
};
/// It's often useful to pass around the image id and texture id.
pub const ImageTex = struct {
image_id: ImageId,
tex_id: TextureId,
};
pub const Image = struct {
/// Texture resource this image belongs to.
tex_id: TextureId,
width: usize,
height: usize,
inner: switch (Backend) {
.OpenGL => struct {},
.Vulkan => struct {
// TODO: Remove this since Texture should own these.
image: vk.VkImage,
image_view: vk.VkImageView,
image_mem: vk.VkDeviceMemory,
sampler: vk.VkSampler,
},
else => void,
},
/// Framebuffer used to draw to the texture.
fbo_id: ?gl.GLuint = null,
remove: bool,
};
pub const Texture = struct {
inner: switch (Backend) {
.OpenGL => struct {
tex_id: GLTextureId,
},
.Vulkan => struct {
/// Used to bind to this texture for draw commands.
desc_set: vk.VkDescriptorSet,
image: vk.VkImage,
image_view: vk.VkImageView,
image_mem: vk.VkDeviceMemory,
// Not owned by the texture.
sampler: vk.VkSampler,
cs_images: std.ArrayList(ImageId),
},
else => struct {},
},
fn deinitGL(self: Texture) void {
gl.deleteTextures(1, &self.inner.tex_id);
}
fn deinitVK(self: Texture, device: vk.VkDevice) void {
vk.destroyImageView(device, self.inner.image_view, null);
vk.destroyImage(device, self.inner.image, null);
vk.freeMemory(device, self.inner.image_mem, null);
self.inner.cs_images.deinit();
}
};
const RemoveEntry = struct {
image_id: ImageId,
frame_age: u32,
};
|
graphics/src/backend/gpu/image.zig
|
const std = @import("std");
const fs = std.fs;
const io = std.io;
const info = std.log.info;
const print = std.debug.print;
const fmt = std.fmt;
const utils = @import("utils.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const PartParams = struct {
view_distance: ?usize,
crowded: usize,
};
const State = enum {
floor,
chair,
taken,
edge,
};
fn printMap(map: [][]State) void {
for (map) |row| {
for (row) |col| {
const repr = switch (col) {
.floor => ".",
.chair => "L",
.taken => "#",
.edge => "E",
};
print("{}", .{repr});
}
print("\n", .{});
}
}
fn countState(state: State, map: [][]State) usize {
var ret: usize = 0;
for (map) |row| {
for (row) |col| {
if (col == state) {
ret += 1;
}
}
}
return ret;
}
fn reset(map: [][]State) void {
for (map) |row, i| {
for (row) |*col, ii| {
switch (col.*) {
.taken => {
col.* = .chair;
},
else => {},
}
}
}
}
fn getTile(y: usize, x: usize, delta_y: isize, delta_x: isize, view_dist: ?usize, map: [][]State) State {
var pos = .{
.y = @intCast(isize, y),
.x = @intCast(isize, x),
};
var moved: usize = 0;
while (true) {
if (view_dist == moved) {
return .floor;
}
moved += 1;
pos.y += delta_y;
pos.x += delta_x;
const y_edge = pos.y < 0 or pos.y >= map.len;
const x_edge = pos.x < 0 or pos.x >= map[0].len;
if (y_edge or x_edge) {
return .edge;
}
const seeing = map[@intCast(usize, pos.y)][@intCast(usize, pos.x)];
switch (seeing) {
.floor => continue,
.chair => return .chair,
.taken => return .taken,
.edge => unreachable,
}
}
}
fn vision(y: usize, x: usize, map: [][]State, view_dist: ?usize) [8]State {
const x_prim = @intCast(isize, x);
const y_prim = @intCast(isize, y);
const nbors = [8]State{
getTile(y, x, -1, 0, view_dist, map),
getTile(y, x, -1, 1, view_dist, map),
getTile(y, x, 0, 1, view_dist, map),
getTile(y, x, 1, 1, view_dist, map),
getTile(y, x, 1, 0, view_dist, map),
getTile(y, x, 1, -1, view_dist, map),
getTile(y, x, 0, -1, view_dist, map),
getTile(y, x, -1, -1, view_dist, map),
};
return nbors;
}
fn newState(state: State, nbors: [8]State, crowded: usize) State {
var taken_nbor: usize = 0;
for (nbors) |nbor| {
if (nbor == .taken) {
taken_nbor += 1;
}
}
const ret = switch (state) {
.floor => State.floor,
.taken => if (taken_nbor >= crowded) blk: {
break :blk State.chair;
} else blk: {
break :blk State.taken;
},
.chair => switch (taken_nbor) {
0 => State.taken,
else => State.chair,
},
.edge => unreachable,
};
return ret;
}
fn update(cur: [][]State, nxt: *[][]State, params: PartParams) usize {
var update_cnt: usize = 0;
for (cur) |cur_row, row_i| {
for (cur_row) |*cur_col, col_i| {
const visible = vision(row_i, col_i, cur, params.view_distance);
const new_state = newState(cur_col.*, visible, params.crowded);
if (new_state != cur_col.*) {
update_cnt += 1;
}
nxt.*[row_i][col_i] = new_state;
}
}
return update_cnt;
}
pub fn main() !void {
const begin = @divTrunc(std.time.nanoTimestamp(), 1000);
// setup
//
defer _ = gpa.deinit();
var allo = &gpa.allocator;
var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1");
defer allo.free(lines.buffer);
// allocate seats
//
var cur_seats: [][]State = allo.alloc([]State, 0) catch unreachable;
defer allo.free(cur_seats);
while (lines.next()) |line| {
cur_seats = allo.realloc(cur_seats, cur_seats.len + 1) catch unreachable;
const seats = allo.alloc(State, line.len) catch unreachable;
cur_seats[cur_seats.len - 1] = seats;
for (line) |token, i| {
seats[i] = switch (token) {
'.' => State.floor,
'L' => State.chair,
else => unreachable, // we cannot have filled seats as input
};
}
}
// allocate our other buffer
//
var nxt_seats: [][]State = allo.alloc([]State, cur_seats.len) catch unreachable;
defer allo.free(nxt_seats);
for (cur_seats) |seats, i| {
nxt_seats[i] = allo.dupe(State, seats) catch unreachable;
}
// do p1 stuff
//
const p1_params = PartParams{
.view_distance = 1,
.crowded = 4,
};
while (true) {
reset(nxt_seats);
const update_cnt = update(
cur_seats,
&nxt_seats,
p1_params,
);
if (update_cnt == 0) {
// stabilized
info("p1: {}", .{countState(.taken, nxt_seats)});
break;
}
const tmp = cur_seats;
cur_seats = nxt_seats;
nxt_seats = tmp;
}
// do p2 stuff
//
const p2_params = PartParams{
.view_distance = null,
.crowded = 5,
};
// this reset means we can only take empty chairs as input
reset(cur_seats);
while (true) {
reset(nxt_seats);
const update_cnt = update(cur_seats, &nxt_seats, p2_params);
if (update_cnt == 0) {
// stabilized
info("p2: {}", .{countState(.taken, nxt_seats)});
break;
}
const tmp = cur_seats;
cur_seats = nxt_seats;
nxt_seats = tmp;
}
// end
//
for (cur_seats) |cur_seat| {
allo.free(cur_seat);
}
for (nxt_seats) |nxt_seat| {
allo.free(nxt_seat);
}
const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin;
print("all done in {} microseconds\n", .{delta});
}
|
day_11/src/main.zig
|
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Platform Constants │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
pub const CANVAS_SIZE: u32 = 160;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Memory Addresses │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
pub const PALETTE: *[4]u32 = @intToPtr(*[4]u32, 0x04);
pub const DRAW_COLORS: *u16 = @intToPtr(*u16, 0x14);
pub const GAMEPAD1: *const Gamepad = @intToPtr(*const Gamepad, 0x16);
pub const GAMEPAD2: *const Gamepad = @intToPtr(*const Gamepad, 0x17);
pub const GAMEPAD3: *const Gamepad = @intToPtr(*const Gamepad, 0x18);
pub const GAMEPAD4: *const Gamepad = @intToPtr(*const Gamepad, 0x19);
pub const MOUSE: *const Mouse = @intToPtr(*const Mouse, 0x1a);
pub const SYSTEM_FLAGS: *SystemFlags = @intToPtr(*SystemFlags, 0x1f);
pub const FRAMEBUFFER: *[6400]u8 = @intToPtr(*[6400]u8, 0xA0);
pub const Gamepad = packed struct {
button_1: bool,
button_2: bool,
_: u2 = 0,
button_left: bool,
button_right: bool,
button_up: bool,
button_down: bool,
comptime {
if(@sizeOf(@This()) != @sizeOf(u8)) unreachable;
}
pub fn format(value: @This(), comptime _: []const u8, _: @import("std").fmt.FormatOptions, writer: anytype) !void {
if(value.button_1) try writer.writeAll("1");
if(value.button_2) try writer.writeAll("2");
if(value.button_left) try writer.writeAll("<");//"←");
if(value.button_right) try writer.writeAll(">");
if(value.button_up) try writer.writeAll("^");
if(value.button_down) try writer.writeAll("v");
}
};
pub const Mouse = packed struct {
x: i16,
y: i16,
buttons: MouseButtons,
pub fn pos(mouse: Mouse) Vec2 {
return .{mouse.x, mouse.y};
}
comptime {
if(@sizeOf(@This()) != 5) unreachable;
}
};
pub const MouseButtons = packed struct {
left: bool,
right: bool,
middle: bool,
_: u5 = 0,
comptime {
if(@sizeOf(@This()) != @sizeOf(u8)) unreachable;
}
};
pub const SystemFlags = packed struct {
preserve_framebuffer: bool,
hide_gamepad_overlay: bool,
_: u6 = 0,
comptime {
if(@sizeOf(@This()) != @sizeOf(u8)) unreachable;
}
};
pub const SYSTEM_PRESERVE_FRAMEBUFFER: u8 = 1;
pub const SYSTEM_HIDE_GAMEPAD_OVERLAY: u8 = 2;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Drawing Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Copies pixels to the framebuffer.
pub extern fn blit(sprite: [*]const u8, x: i32, y: i32, width: i32, height: i32, flags: u32) void;
/// Copies a subregion within a larger sprite atlas to the framebuffer.
pub extern fn blitSub(sprite: [*]const u8, x: i32, y: i32, width: i32, height: i32, src_x: u32, src_y: u32, stride: i32, flags: u32) void;
pub const BLIT_2BPP: u32 = 1;
pub const BLIT_1BPP: u32 = 0;
pub const BLIT_FLIP_X: u32 = 2;
pub const BLIT_FLIP_Y: u32 = 4;
pub const BLIT_ROTATE: u32 = 8;
/// Draws a line between two points.
pub extern fn line(x1: i32, y1: i32, x2: i32, y2: i32) void;
/// Draws an oval (or circle).
pub extern fn oval(x: i32, y: i32, width: i32, height: i32) void;
/// Draws a rectangle.
pub extern fn rect(x: i32, y: i32, width: u32, height: u32) void;
/// Draws text using the built-in system font.
pub fn text(str: []const u8, x: i32, y: i32) void {
textUtf8(str.ptr, str.len, x, y);
}
extern fn textUtf8(strPtr: [*]const u8, strLen: usize, x: i32, y: i32) void;
/// Draws a vertical line
pub extern fn vline(x: i32, y: i32, len: u32) void;
/// Draws a horizontal line
pub extern fn hline(x: i32, y: i32, len: u32) void;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Sound Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
const externs = struct {
extern fn tone(frequency: u32, duration: u32, volume: u32, flags: u32) void;
};
/// Plays a sound tone.
pub fn tone(frequency: ToneFrequency, duration: ToneDuration, volume: u32, flags: ToneFlags) void {
return externs.tone(@bitCast(u32, frequency), @bitCast(u32, duration), volume, @bitCast(u8, flags));
}
pub const ToneFrequency = packed struct {
start: u16,
end: u16 = 0,
comptime {
if(@sizeOf(@This()) != @sizeOf(u32)) unreachable;
}
};
pub const ToneDuration = packed struct {
sustain: u8,
release: u8 = 0,
decay: u8 = 0,
attack: u8 = 0,
comptime {
if(@sizeOf(@This()) != @sizeOf(u32)) unreachable;
}
};
pub const ToneFlags = packed struct {
pub const Channel = enum(u2) {
pulse1,
pulse2,
triangle,
noise,
};
pub const Mode = enum(u2) {
p12_5,
p25,
p50,
p75,
};
channel: Channel,
mode: Mode = .p12_5,
_: u4 = 0,
comptime {
if(@sizeOf(@This()) != @sizeOf(u8)) unreachable;
}
};
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Storage Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Reads up to `size` bytes from persistent storage into the pointer `dest`.
pub extern fn diskr(dest: [*]u8, size: u32) u32;
/// Writes up to `size` bytes from the pointer `src` into persistent storage.
pub extern fn diskw(src: [*]const u8, size: u32) u32;
// ┌───────────────────────────────────────────────────────────────────────────┐
// │ │
// │ Other Functions │
// │ │
// └───────────────────────────────────────────────────────────────────────────┘
/// Prints a message to the debug console.
pub fn trace(x: []const u8) void {
traceUtf8(x.ptr, x.len);
}
extern fn traceUtf8(strPtr: [*]const u8, strLen: usize) void;
/// Use with caution, as there's no compile-time type checking.
///
/// * %c, %d, and %x expect 32-bit integers.
/// * %f expects 64-bit floats.
/// * %s expects a *zero-terminated* string pointer.
///
/// See https://github.com/aduros/wasm4/issues/244 for discussion and type-safe
/// alternatives.
pub extern fn tracef(x: [*:0]const u8, ...) void;
|
cli/assets/templates/zig/src/wasm4.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Timetable = struct {
departure: usize,
buses: std.AutoHashMap(usize, usize),
pub fn init() Timetable {
var self = Timetable{
.departure = 0,
.buses = std.AutoHashMap(usize, usize).init(allocator),
};
return self;
}
pub fn deinit(self: *Timetable) void {
self.buses.deinit();
}
pub fn add_line(self: *Timetable, line: []const u8) void {
if (self.departure <= 0) {
self.departure = std.fmt.parseInt(usize, line, 10) catch unreachable;
return;
}
var pos: usize = 0;
var it = std.mem.tokenize(u8, line, ",");
while (it.next()) |str| : (pos += 1) {
if (str[0] == 'x') continue;
const id = std.fmt.parseInt(usize, str, 10) catch unreachable;
_ = self.buses.put(pos, id) catch unreachable;
}
}
pub fn product_for_earliest_bus(self: Timetable) usize {
var product: usize = 0;
var min: usize = std.math.maxInt(usize);
var it = self.buses.iterator();
while (it.next()) |kv| {
const id = kv.value_ptr.*;
const next = self.departure % id;
const wait = id - next;
const departure = self.departure + wait;
if (min > departure) {
min = departure;
product = id * wait;
}
}
return product;
}
pub fn earliest_departure(self: Timetable) usize {
var divs = std.ArrayList(usize).init(allocator);
defer divs.deinit();
var rems = std.ArrayList(usize).init(allocator);
defer rems.deinit();
var it = self.buses.iterator();
while (it.next()) |kv| {
const pos = kv.key_ptr.*;
const id = kv.value_ptr.*;
divs.append(id) catch unreachable;
const rem: usize = if (pos == 0) 0 else id - pos % id;
rems.append(rem) catch unreachable;
}
const cr = chinese_remainder(divs.items, rems.items);
return cr;
}
};
fn chinese_remainder(divs: []const usize, rems: []const usize) usize {
if (divs.len != rems.len) return 0;
const len = divs.len;
if (len == 0) return 0;
var prod: usize = 1;
var j: usize = 0;
while (j < len) : (j += 1) {
// if this overflows, can't do
prod *= divs[j];
}
var sum: usize = 0;
var k: usize = 0;
while (k < len) : (k += 1) {
const p: usize = prod / divs[k];
sum += rems[k] * mul_inv(p, divs[k]) * p;
}
return sum % prod;
}
// returns x where (a * x) % b == 1
fn mul_inv(a: usize, b: usize) usize {
if (b == 1) return 1;
var ax = @intCast(isize, a);
var bx = @intCast(isize, b);
var x0: isize = 0;
var x1: isize = 1;
while (ax > 1) {
const q = @divTrunc(ax, bx);
// both @mod and @rem work here
const t0 = bx;
bx = @rem(ax, bx);
ax = t0;
const t1 = x0;
x0 = x1 - q * x0;
x1 = t1;
}
if (x1 < 0) {
x1 += @intCast(isize, b);
}
return @intCast(usize, x1);
}
test "sample earliest bus" {
const data: []const u8 =
\\939
\\7,13,x,x,59,x,31,19
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const product = timetable.product_for_earliest_bus();
try testing.expect(product == 295);
}
test "chinese reminder" {
const n = [_]usize{ 3, 5, 7 };
const a = [_]usize{ 2, 3, 2 };
const cr = chinese_remainder(n[0..], a[0..]);
try testing.expect(cr == 23);
}
test "sample earliest departure 1" {
const data: []const u8 =
\\939
\\7,13,x,x,59,x,31,19
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 1068781);
}
test "sample earliest departure 2" {
const data: []const u8 =
\\999
\\17,x,13,19
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 3417);
}
test "sample earliest departure 3" {
const data: []const u8 =
\\999
\\67,7,59,61
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 754018);
}
test "sample earliest departure 4" {
const data: []const u8 =
\\999
\\67,x,7,59,61
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 779210);
}
test "sample earliest departure 5" {
const data: []const u8 =
\\999
\\67,7,x,59,61
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 1261476);
}
test "sample earliest departure 6" {
const data: []const u8 =
\\999
\\1789,37,47,1889
;
var timetable = Timetable.init();
defer timetable.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
timetable.add_line(line);
}
const timestamp = timetable.earliest_departure();
try testing.expect(timestamp == 1202161486);
}
|
2020/p13/timetable.zig
|
const std = @import("std");
const build_options = @import("build_options");
const utils = @import("utils");
const Point = utils.Point;
const multiboot = @import("multiboot.zig");
const pmemory = @import("memory.zig");
const putil = @import("util.zig");
const bios_int = @import("bios_int.zig");
const vbe_console = @import("vbe_console.zig");
const kernel = @import("root").kernel;
const print = kernel.print;
const kmemory = kernel.memory;
const Range = kmemory.Range;
pub const font = kernel.font;
// TODO Make these not fixed
const find_width = 800;
const find_height = 600;
const find_bpp = 24;
const RealModePtr = packed struct {
offset: u16,
segment: u16,
pub fn get(self: *const RealModePtr) u32 {
return @intCast(u32, self.segment) * 0x10 + self.offset;
}
};
const Info = packed struct {
const magic_expected = "VESA";
magic: [4]u8,
version: u16,
oem_ptr: RealModePtr,
capabilities: u32,
video_modes_ptr: RealModePtr,
memory: u16,
software_rev: u16,
vendor: RealModePtr,
product_name: RealModePtr,
product_rev: RealModePtr,
const Version = enum (u8) {
V1 = 1,
V2 = 2,
V3 = 3,
};
pub fn get_version(self: *const Info) ?Version {
return utils.int_to_enum(Version, @intCast(u8, self.version >> 8));
}
pub fn get_modes(self: *const Info) []const u16 {
var mode_count: usize = 0;
const modes_ptr = @intToPtr([*]const u16, self.video_modes_ptr.get());
while (modes_ptr[mode_count] != 0xffff) {
mode_count += 1;
}
const modes = kernel.alloc.alloc_array(u16, mode_count) catch
@panic("vbe.Info.get_modes: alloc mode array failed");
var mode_i: usize = 0;
while (modes_ptr[mode_i] != 0xffff) {
modes[mode_i] = modes_ptr[mode_i];
mode_i += 1;
}
return modes;
}
};
const Mode = packed struct {
attributes: u16,
window_a: u8,
window_b: u8,
granularity: u16,
window_size: u16,
segment_a: u16,
segment_b: u16,
win_func_ptr: u32,
pitch: u16,
width: u16,
height: u16,
w_char: u8,
y_char: u8,
planes: u8,
bpp: u8,
banks: u8,
memory_model: u8,
bank_size: u8,
image_pages: u8,
reserved0: u8,
red_mask: u8,
red_position: u8,
green_mask: u8,
green_position: u8,
blue_mask: u8,
blue_position: u8,
reserved_mask: u8,
reserved_position: u8,
direct_color_attributes: u8,
framebuffer: u32,
off_screen_mem_off: u32,
off_screen_mem_size: u16,
};
var vbe_setup = false;
var info: Info = undefined;
var mode: Mode = undefined;
var mode_id: ?u16 = null;
pub fn get_res() ?Point {
return if (vbe_setup) .{.x = mode.width, .y = mode.height} else null;
}
fn video_memory_offset(x: u32, y: u32) callconv(.Inline) u32 {
return y * mode.pitch + x * bytes_per_pixel;
}
fn draw_pixel(x: u32, y: u32, color: u32) callconv(.Inline) void {
const offset = video_memory_offset(x, y);
if (offset + 2 < buffer.len) {
buffer[offset] = @truncate(u8, color);
buffer[offset + 1] = @truncate(u8, color >> 8);
buffer[offset + 2] = @truncate(u8, color >> 16);
buffer_clean = false;
}
}
fn draw_pixel_bgr(x: u32, y: u32, color: u32) callconv(.Inline) void {
const offset = video_memory_offset(x, y);
if (offset + 2 < buffer.len) {
buffer[offset + 2] = @truncate(u8, color);
buffer[offset + 1] = @truncate(u8, color >> 8);
buffer[offset] = @truncate(u8, color >> 16);
buffer_clean = false;
}
}
pub fn draw_glyph(x: u32, y: u32, c: u8, fg_color: u32, bg_color: ?u32) void {
var xi: usize = 0;
var yi: usize = 0;
const glyph = font.bitmaps[c - ' '];
while (yi < font.height) {
while (xi < font.width) {
const o = (glyph[yi][xi / 8] << @intCast(u3, xi % 8)) & 0x80 != 0;
if (o) {
draw_pixel(x + xi, y + yi, fg_color);
} else if (bg_color) |bgc| {
draw_pixel(x + xi, y + yi, bgc);
}
xi += 1;
}
xi = 0;
yi += 1;
}
}
pub fn draw_string(x: u32, y: u32, s: []const u8, color: u32) Point {
var x_offset = x;
var y_offset = y;
var max_x = x;
for (s) |c| {
if (c >= ' ' and c <= '~') {
draw_glyph(x_offset, y_offset, c, color, null);
x_offset += font.width;
if (x_offset > max_x) {
max_x = x_offset;
}
}
if (c == '\n') {
y_offset += font.height;
x_offset = x;
}
}
return Point{.x = max_x, .y = y_offset + font.height};
}
pub fn draw_string_continue(start: Point, s: []const u8, color: u32) Point {
var x_offset = start.x;
var y_offset = start.y;
for (s) |c| {
if (c >= ' ' and c <= '~') {
draw_glyph(x_offset, y_offset, c, color, null);
const next_offset = x_offset + font.width;
if (next_offset >= mode.width) {
y_offset += font.height;
x_offset = 0;
} else {
x_offset = next_offset;
}
} else if (c == '\n') {
y_offset += font.height;
x_offset = 0;
}
}
return Point{.x = x_offset, .y = y_offset};
}
pub fn draw_line(x1: u32, y1: u32, x2: u32, y2: u32, color: u32) void {
const dx = x2 - x1;
const dy = y2 - y1;
if (dx > 0) {
var x = x1;
while (x <= x2) {
draw_pixel(x, y1 + dy * (x - x1) / dx, color);
x += 1;
}
} else {
var y = y1;
while (y <= y2) {
draw_pixel(x1, y, color);
y += 1;
}
}
}
pub fn draw_frame(x: u32, y: u32, w: u32, h: u32, color: u32) void {
const x2 = x + w;
const y2 = y + h;
draw_line(x, y, x2, y, color);
draw_line(x, y, x, y2, color);
draw_line(x2, y, x2, y2, color);
draw_line(x, y2, x2, y2, color);
}
pub fn draw_raw_image_chunk(data: []const u8, w: u32, pos: *const Point, last: *Point) void {
const pixels = std.mem.bytesAsSlice(u32, data);
for (pixels) |px| {
draw_pixel_bgr(pos.x + last.x, pos.y + last.y, px);
last.x += 1;
if (last.x >= w) {
last.y += 1;
last.x = 0;
}
}
}
pub fn draw_raw_image(data: []const u8, w: u32, x: u32, y: u32) void {
var last = Point{};
draw_raw_image_chunk(data, w, .{.x = x, .y = y}, &last);
}
var buffer: []u8 = undefined;
var buffer_clean: bool = false;
var video_memory: []u8 = undefined;
var bytes_per_pixel: u32 = undefined;
pub fn fill_buffer(color: u32) void {
if (bytes_per_pixel == 4) {
const color64 = (@as(u64, color) << 32) + color;
const b = Range.from_bytes(buffer).to_slice(u64);
for (b) |*p| {
p.* = color64;
}
} else {
// TODO: Optimize?
var x: u32 = 0;
while (x < mode.width) {
var y: u32 = 0;
while (y < mode.height) {
const offset = video_memory_offset(x, y);
buffer[offset + 2] = @truncate(u8, color);
buffer[offset + 1] = @truncate(u8, color >> 8);
buffer[offset] = @truncate(u8, color >> 16);
y += 1;
}
x += 1;
}
}
buffer_clean = false;
}
// TODO: This could certainly be done faster, maybe through unrolling the loop
// some or CPU features like SSE.
pub fn flush_buffer() void {
if (buffer_clean) return;
const b = Range.from_bytes(buffer).to_slice(u64);
const vm = Range.from_bytes(video_memory).to_slice(u64);
while ((putil.in8(0x03da) & 0x8) != 0) {}
while ((putil.in8(0x03da) & 0x8) == 0) {}
for (vm) |*p, i| {
p.* = b[i];
}
buffer_clean = true;
}
const vbe_result_ptr: u16 = 0x8000;
const VbeFuncArgs = struct {
bx: u16 = 0,
cx: u16 = 0,
di: u16 = 0,
slow: bool = false,
};
fn vbe_func(name: []const u8, func_num: u16, args: VbeFuncArgs) bool {
var params = bios_int.Params{
.interrupt = 0x10,
.eax = func_num,
.ebx = args.bx,
.ecx = args.cx,
.edi = args.di,
.slow = args.slow,
};
bios_int.run(¶ms) catch {
print.format(" - vbe_func: {}: bios_int.run failed\n", .{name});
return false;
};
if (@truncate(u16, params.eax) != 0x4f) {
print.format(" - vbe_func: {}: failed, eax: {:x}\n", .{name, params.eax});
return false;
}
return true;
}
fn get_vbe_info() ?*const Info {
const vbe2 = "VBE2"; // Set the interface to use VBE Version 2
_ = utils.memory_copy_truncate(@intToPtr([*]u8, vbe_result_ptr)[0..vbe2.len], vbe2);
return if (vbe_func("get_vbe_info", 0x4f00, .{
.di = vbe_result_ptr
})) @intToPtr(*const Info, vbe_result_ptr) else null;
}
fn get_mode_info(mode_number: u16) ?*const Mode {
return if (vbe_func("get_mode_info", 0x4f01, .{
.cx = mode_number,
.di = vbe_result_ptr
})) @intToPtr(*const Mode, vbe_result_ptr) else null;
}
fn set_mode() void {
vbe_setup = vbe_func("set_mode", 0x4f02, .{
.bx = mode_id.? | 0x4000, // Use Linear Buffer
.slow = true,
});
}
pub fn init() void {
if (!build_options.vbe) {
return;
}
print.string(" - See if we can use VESA graphics..\n");
// First see GRUB setup VBE
if (multiboot.get_vbe_info()) |vbe| {
print.string(" - Got VBE info from Multiboot...\n");
info = @ptrCast(*Info, &vbe.control_info[0]).*;
mode_id = vbe.mode;
mode = @ptrCast(*Mode, &vbe.mode_info[0]).*;
vbe_setup = true;
}
// Then see if we can set it up using the BIOS
if (!vbe_setup) {
// Get Info
print.string(" - Trying to get VBE info directly from BIOS...\n");
info = (get_vbe_info() orelse return).*;
print.format("{}\n", .{info});
if (info.get_version()) |version| {
print.format("VERSION {}\n", .{version});
}
// Find the Mode We're Looking For
const supported_modes = info.get_modes();
defer kernel.alloc.free_array(supported_modes) catch unreachable;
for (supported_modes) |supported_mode| {
print.format(" - mode {:x}\n", .{supported_mode});
const mode_ptr = get_mode_info(supported_mode) orelse return;
print.format(" - {}x{}x{}\n", .{
mode_ptr.width, mode_ptr.height, mode_ptr.bpp});
if ((mode_ptr.attributes & (1 << 7)) == 0) {
print.string(" - Non-linear, skipping...\n");
continue;
}
if (mode_ptr.width == find_width and mode_ptr.height == find_height and
mode_ptr.bpp == find_bpp) {
mode = mode_ptr.*;
mode_id = supported_mode;
break;
}
}
if (mode_id == null) {
print.string(" - Didn't Find VBE Mode\n");
return;
}
// Set the Mode
set_mode();
}
if (vbe_setup) {
print.string(" - Got VBE info\n");
if (info.get_version()) |version| {
print.format("{}\n", .{version});
}
print.format("{}\n", .{info});
print.format("{}\n", .{mode});
// TODO
// if (mode.bpp != 32 and mode.bpp != 16) {
// @panic("bpp is not 32 bits or 16 bits");
// }
bytes_per_pixel = mode.bpp / 8;
const video_memory_size = @as(usize, mode.height) * @as(usize, mode.pitch);
// TODO: Zig Bug? If catch is taken away Zig 0.5 fails to reject not
// handling the error return. LLVM catches the mistake instead.
print.format("vms: {}\n", .{video_memory_size});
buffer = kernel.memory_mgr.big_alloc.alloc_array(u8, video_memory_size) catch {
@panic("Couldn't alloc VBE Buffer");
};
const video_memory_range = kernel.memory_mgr.impl.get_unused_kernel_space(
video_memory_size) catch {
@panic("Couldn't Reserve VBE Buffer");
};
video_memory = @intToPtr([*]u8, video_memory_range.start)[0..video_memory_size];
kernel.memory_mgr.impl.map(
video_memory_range, mode.framebuffer, false) catch {
@panic("Couldn't map VBE Buffer");
};
if (false) {
fill_buffer(0xe8e6e3);
const w = 301;
const h = 170;
const x = mode.width - w - 10;
const y = mode.height - h - 10;
const image align(@alignOf(u64)) = @embedFile("../../root/files/dragon.img");
draw_raw_image(image, w, x, y);
_ = draw_string(x, y, " Georgios ", 0x181a1b);
flush_buffer();
}
vbe_console.init(mode.width, mode.height);
kernel.console = &vbe_console.console;
} else {
print.string(" - Could not init VBE graphics\n");
}
}
|
kernel/platform/vbe.zig
|
const std = @import("std");
const sf = struct {
pub usingnamespace @import("../sfml.zig");
pub usingnamespace sf.network;
};
const TcpSocket = @This();
// Constructor/destructor
/// Creates a new udp socket
pub fn create() !TcpSocket {
var sock = sf.c.sfTcpSocket_create();
if (sock) |s| {
return TcpSocket{ ._ptr = s };
} else
return sf.Error.nullptrUnknownReason;
}
/// Destroys this socket
pub fn destroy(self: *TcpSocket) void {
sf.c.sfTcpSocket_destroy(self._ptr);
}
// Methods
/// Enables or disables blocking mode (true for blocking)
/// In blocking mode, receive waits for data
pub fn setBlocking(self: *TcpSocket, blocking: bool) void {
sf.c.sfTcpSocket_setBlocking(self._ptr, @boolToInt(blocking));
}
/// Tells whether or not the socket is in blocking mode
pub fn isBlocking(self: TcpSocket) bool {
return sf.c.sfTcpSocket_isBlocking(self._ptr) != 0;
}
/// Gets the port this socket is bound to (null for no port)
pub fn getLocalPort(self: TcpSocket) ?u16 {
const port = sf.c.sfTcpSocket_getLocalPort(self._ptr);
return if (port == 0) null else port;
}
/// Gets the address of the other tcp socket that is currently connected
pub fn getRemote(self: TcpSocket) error{notConnected}!sf.IpAndPort {
const port = sf.c.sfTcpSocket_getRemotePort(self._ptr);
if (port == 0)
return error.notConnected;
const ip = sf.c.sfTcpSocket_getRemoteAddress(self._ptr);
const ip_and_port = sf.IpAndPort{ .ip = .{ ._ip = ip }, .port = port };
std.debug.assert(!ip_and_port.ip.equals(sf.IpAddress.none()));
return ip_and_port;
}
/// Connects to a server (the server typically has a Tcp Listener)
/// To connect to clients, use a tcp listener instead and wait for connections
pub fn connect(self: *TcpSocket, remote: sf.IpAndPort, timeout: sf.system.Time) sf.Socket.Error!void {
const code = sf.c.sfTcpSocket_connect(self._ptr, remote.ip._ip, remote.port, timeout._toCSFML());
try sf.Socket._codeToErr(code);
}
/// Disconnects from the remote
pub fn disconnect(self: *TcpSocket) void {
sf.c.sfTcpSocket_disconnect(self._ptr);
}
/// Sends raw data to the remote
pub fn send(self: *TcpSocket, data: []const u8) sf.Socket.Error!void {
const code = sf.c.sfTcpSocket_send(self._ptr, data.ptr, data.len);
try sf.Socket._codeToErr(code);
}
/// Sends part of the buffer to the remote
/// Returns the slice of the rest of the data that hasn't been sent, what is left to send
pub fn sendPartial(self: *TcpSocket, data: []const u8) sf.Socket.Error![]const u8 {
var sent: usize = undefined;
var ret = data;
const code = sf.c.sfTcpSocket_sendPartial(self._ptr, data.ptr, data.len, &sent);
try sf.Socket._codeToErr(code);
ret.ptr += sent;
ret.len -= sent;
return ret;
}
/// Sends a packet to the remote
pub fn sendPacket(self: *TcpSocket, packet: sf.Packet) sf.Socket.Error!void {
const code = sf.c.sfTcpSocket_sendPacket(self._ptr, packet._ptr);
try sf.Socket._codeToErr(code);
}
/// Receives raw data from the remote
/// Pass in a buffer large enough
/// Returns the slice of the received data
pub fn receive(self: *TcpSocket, buf: []u8) sf.Socket.Error![]const u8 {
var size: usize = undefined;
const code = sf.c.sfUdpSocket_receive(self._ptr, buf.ptr, buf.len, &size);
try sf.Socket._codeToErr(code);
return buf[0..size];
}
// TODO: consider receiveAlloc
// TODO: should this return its own new packet
/// Receives a packet from the remote
/// Pass the packet to fill with the data
pub fn receivePacket(self: *TcpSocket, packet: *sf.Packet) sf.Socket.Error!void {
const code = sf.c.sfUdpSocket_receivePacket(self._ptr, packet._ptr);
try sf.Socket._codeToErr(code);
}
/// Pointer to the csfml structure
_ptr: *sf.c.sfTcpSocket,
// TODO: write tests
|
src/sfml/network/TcpSocket.zig
|
const std = @import("std");
const assert = std.debug.assert;
pub const Protein = struct {
pub const Unit = "aa";
pub const SupportsStrands = false;
pub fn complement(letter: u8) u8 {
return letter;
}
const BitMapping = [_]?u4{
0b0000, // 'A'
null, // 'B' ambiguous/invalid
0b0011, // 'C'
0b0100, // 'D'
0b0100, // 'E'
0b1111, // 'F'
0b0101, // 'G'
0b0110, // 'H'
0b0111, // 'I'
null, // 'J' ambiguous/invalid
0b1001, // 'K'
0b1000, // 'L'
0b1010, // 'M'
0b0010, // 'N'
null, // 'O' ambiguous/invalid
0b1011, // 'P'
0b0100, // 'Q'
0b0001, // 'R'
0b1100, // 'S'
0b1101, // 'T'
null, // 'U' ambiguous/invalid
0b0111, // 'V'
0b1110, // 'W'
null, // 'X' ambiguous/invalid
0b1111, // 'Y'
null, // 'Z' ambiguous/invalid
};
pub fn mapToBits(aa: u8) ?u4 {
if (aa <= 'A' or aa >= 'Z')
return null;
const idx: usize = aa - 'A';
assert(idx <= BitMapping.len);
return BitMapping[idx];
}
// BLOSUM62
const ScoreMatrixSize = 26;
const ScoreMatrix = [ScoreMatrixSize][ScoreMatrixSize]i8{
// A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
[_]i8{ 4, -2, 0, -2, -1, -2, 0, -2, -1, 0, -1, -1, -1, -2, 0, -1, -1, -1, 1, 0, 0, 0, -3, 0, -2, -1 }, // A
[_]i8{ -2, 4, -3, 4, 1, -3, -1, 0, -3, 0, 0, -4, -3, 3, 0, -2, 0, -1, 0, -1, 0, -3, -4, -1, -3, 1 }, // B
[_]i8{ 0, -3, 9, -3, -4, -2, -3, -3, -1, 0, -3, -1, -1, -3, 0, -3, -3, -3, -1, -1, 0, -1, -2, -2, -2, -3 }, // C
[_]i8{ -2, 4, -3, 6, 2, -3, -1, -1, -3, 0, -1, -4, -3, 1, 0, -1, 0, -2, 0, -1, 0, -3, -4, -1, -3, 1 }, // D
[_]i8{ -1, 1, -4, 2, 5, -3, -2, 0, -3, 0, 1, -3, -2, 0, 0, -1, 2, 0, 0, -1, 0, -2, -3, -1, -2, 4 }, // E
[_]i8{ -2, -3, -2, -3, -3, 6, -3, -1, 0, 0, -3, 0, 0, -3, 0, -4, -3, -3, -2, -2, 0, -1, 1, -1, 3, -3 }, // F
[_]i8{ 0, -1, -3, -1, -2, -3, 6, -2, -4, 0, -2, -4, -3, 0, 0, -2, -2, -2, 0, -2, 0, -3, -2, -1, -3, -2 }, // G
[_]i8{ -2, 0, -3, -1, 0, -1, -2, 8, -3, 0, -1, -3, -2, 1, 0, -2, 0, 0, -1, -2, 0, -3, -2, -1, 2, 0 }, // H
[_]i8{ -1, -3, -1, -3, -3, 0, -4, -3, 4, 0, -3, 2, 1, -3, 0, -3, -3, -3, -2, -1, 0, 3, -3, -1, -1, -3 }, // I
[_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // J
[_]i8{ -1, 0, -3, -1, 1, -3, -2, -1, -3, 0, 5, -2, -1, 0, 0, -1, 1, 2, 0, -1, 0, -2, -3, -1, -2, 1 }, // K
[_]i8{ -1, -4, -1, -4, -3, 0, -4, -3, 2, 0, -2, 4, 2, -3, 0, -3, -2, -2, -2, -1, 0, 1, -2, -1, -1, -3 }, // L
[_]i8{ -1, -3, -1, -3, -2, 0, -3, -2, 1, 0, -1, 2, 5, -2, 0, -2, 0, -1, -1, -1, 0, 1, -1, -1, -1, -1 }, // M
[_]i8{ -2, 3, -3, 1, 0, -3, 0, 1, -3, 0, 0, -3, -2, 6, 0, -2, 0, 0, 1, 0, 0, -3, -4, -1, -2, 0 }, // N
[_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // O
[_]i8{ -1, -2, -3, -1, -1, -4, -2, -2, -3, 0, -1, -3, -2, -2, 0, 7, -1, -2, -1, -1, 0, -2, -4, -2, -3, -1 }, // P
[_]i8{ -1, 0, -3, 0, 2, -3, -2, 0, -3, 0, 1, -2, 0, 0, 0, -1, 5, 1, 0, -1, 0, -2, -2, -1, -1, 3 }, // Q
[_]i8{ -1, -1, -3, -2, 0, -3, -2, 0, -3, 0, 2, -2, -1, 0, 0, -2, 1, 5, -1, -1, 0, -3, -3, -1, -2, 0 }, // R
[_]i8{ 1, 0, -1, 0, 0, -2, 0, -1, -2, 0, 0, -2, -1, 1, 0, -1, 0, -1, 4, 1, 0, -2, -3, 0, -2, 0 }, // S
[_]i8{ 0, -1, -1, -1, -1, -2, -2, -2, -1, 0, -1, -1, -1, 0, 0, -1, -1, -1, 1, 5, 0, 0, -2, 0, -2, -1 }, // T
[_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // U
[_]i8{ 0, -3, -1, -3, -2, -1, -3, -3, 3, 0, -2, 1, 1, -3, 0, -2, -2, -3, -2, 0, 0, 4, -3, -1, -1, -2 }, // V
[_]i8{ -3, -4, -2, -4, -3, 1, -2, -2, -3, 0, -3, -2, -1, -4, 0, -4, -2, -3, -3, -2, 0, -3, 11, -2, 2, -3 }, // W
[_]i8{ 0, -1, -2, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, -2, -1, -1, 0, 0, 0, -1, -2, -1, -1, -1 }, // X
[_]i8{ -2, -3, -2, -3, -2, 3, -3, 2, -1, 0, -2, -1, -1, -2, 0, -3, -1, -2, -2, -2, 0, -1, 2, -1, 7, -2 }, // Y
[_]i8{ -1, 1, -3, 1, 4, -3, -2, 0, -3, 0, 1, -3, -1, 0, 0, -1, 3, 0, 0, -1, 0, -2, -3, -1, -2, 4 }, // Z
};
pub fn score(a: u8, b: u8) i8 {
var idx1: usize = a - 'A';
var idx2: usize = b - 'A';
assert(idx1 <= ScoreMatrixSize and idx2 <= ScoreMatrixSize);
return ScoreMatrix[idx1][idx2];
}
pub fn match(a: u8, b: u8) bool {
return score(a, b) >= 4;
}
pub fn matchSymbol(a: u8, b: u8) u8 {
const s = score(a, b);
if (s >= 4) return '|';
if (s >= 2) return ':';
if (s >= 0) return '.';
return ' ';
}
};
test "complement" {
try std.testing.expectEqual(Protein.complement('A'), 'A');
}
test "bit mapping" {
try std.testing.expectEqual(Protein.mapToBits('B'), null);
try std.testing.expectEqual(Protein.mapToBits('C'), 0b0011);
try std.testing.expectEqual(Protein.mapToBits('Y'), 0b1111);
}
test "scoring" {
try std.testing.expectEqual(Protein.score('Q', 'S'), 0);
try std.testing.expectEqual(Protein.score('L', 'P'), -3);
try std.testing.expectEqual(Protein.score('T', 'T'), 5);
}
test "match" {
try std.testing.expectEqual(Protein.match('L', 'L'), true);
try std.testing.expectEqual(Protein.match('I', 'V'), false);
try std.testing.expectEqual(Protein.match('I', 'I'), true);
}
|
src/bio/alphabet/protein.zig
|
const std = @import("../std.zig");
const assert = std.debug.assert;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const meta = std.meta;
const ast = std.zig.ast;
const Token = std.zig.Token;
const indent_delta = 4;
const asm_indent_delta = 2;
pub const Error = ast.Tree.RenderError;
const Ais = AutoIndentingStream(std.ArrayList(u8).Writer);
pub fn renderTree(buffer: *std.ArrayList(u8), tree: ast.Tree) Error!void {
assert(tree.errors.len == 0); // Cannot render an invalid tree.
var auto_indenting_stream = Ais{
.indent_delta = indent_delta,
.underlying_writer = buffer.writer(),
};
const ais = &auto_indenting_stream;
// Render all the line comments at the beginning of the file.
const comment_end_loc = tree.tokens.items(.start)[0];
_ = try renderComments(ais, tree, 0, comment_end_loc);
if (tree.tokens.items(.tag)[0] == .container_doc_comment) {
try renderContainerDocComments(ais, tree, 0);
}
try renderMembers(buffer.allocator, ais, tree, tree.rootDecls());
if (ais.disabled_offset) |disabled_offset| {
try writeFixingWhitespace(ais.underlying_writer, tree.source[disabled_offset..]);
}
}
/// Render all members in the given slice, keeping empty lines where appropriate
fn renderMembers(gpa: *Allocator, ais: *Ais, tree: ast.Tree, members: []const ast.Node.Index) Error!void {
if (members.len == 0) return;
try renderMember(gpa, ais, tree, members[0], .newline);
for (members[1..]) |member| {
try renderExtraNewline(ais, tree, member);
try renderMember(gpa, ais, tree, member, .newline);
}
}
fn renderMember(gpa: *Allocator, ais: *Ais, tree: ast.Tree, decl: ast.Node.Index, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const datas = tree.nodes.items(.data);
try renderDocComments(ais, tree, tree.firstToken(decl));
switch (tree.nodes.items(.tag)[decl]) {
.fn_decl => {
// Some examples:
// pub extern "foo" fn ...
// export fn ...
const fn_proto = datas[decl].lhs;
const fn_token = main_tokens[fn_proto];
// Go back to the first token we should render here.
var i = fn_token;
while (i > 0) {
i -= 1;
switch (token_tags[i]) {
.keyword_extern,
.keyword_export,
.keyword_pub,
.string_literal,
.keyword_inline,
.keyword_noinline,
=> continue,
else => {
i += 1;
break;
},
}
}
while (i < fn_token) : (i += 1) {
try renderToken(ais, tree, i, .space);
}
switch (tree.nodes.items(.tag)[fn_proto]) {
.fn_proto_one, .fn_proto => {
const callconv_expr = if (tree.nodes.items(.tag)[fn_proto] == .fn_proto_one)
tree.extraData(datas[fn_proto].lhs, ast.Node.FnProtoOne).callconv_expr
else
tree.extraData(datas[fn_proto].lhs, ast.Node.FnProto).callconv_expr;
if (callconv_expr != 0 and tree.nodes.items(.tag)[callconv_expr] == .enum_literal) {
if (mem.eql(u8, "Inline", tree.tokenSlice(main_tokens[callconv_expr]))) {
try ais.writer().writeAll("inline ");
}
}
},
.fn_proto_simple, .fn_proto_multi => {},
else => unreachable,
}
assert(datas[decl].rhs != 0);
try renderExpression(gpa, ais, tree, fn_proto, .space);
return renderExpression(gpa, ais, tree, datas[decl].rhs, space);
},
.fn_proto_simple,
.fn_proto_multi,
.fn_proto_one,
.fn_proto,
=> {
// Extern function prototypes are parsed as these tags.
// Go back to the first token we should render here.
const fn_token = main_tokens[decl];
var i = fn_token;
while (i > 0) {
i -= 1;
switch (token_tags[i]) {
.keyword_extern,
.keyword_export,
.keyword_pub,
.string_literal,
.keyword_inline,
.keyword_noinline,
=> continue,
else => {
i += 1;
break;
},
}
}
while (i < fn_token) : (i += 1) {
try renderToken(ais, tree, i, .space);
}
try renderExpression(gpa, ais, tree, decl, .none);
return renderToken(ais, tree, tree.lastToken(decl) + 1, space); // semicolon
},
.@"usingnamespace" => {
const main_token = main_tokens[decl];
const expr = datas[decl].lhs;
if (main_token > 0 and token_tags[main_token - 1] == .keyword_pub) {
try renderToken(ais, tree, main_token - 1, .space); // pub
}
try renderToken(ais, tree, main_token, .space); // usingnamespace
try renderExpression(gpa, ais, tree, expr, .none);
return renderToken(ais, tree, tree.lastToken(expr) + 1, space); // ;
},
.global_var_decl => return renderVarDecl(gpa, ais, tree, tree.globalVarDecl(decl)),
.local_var_decl => return renderVarDecl(gpa, ais, tree, tree.localVarDecl(decl)),
.simple_var_decl => return renderVarDecl(gpa, ais, tree, tree.simpleVarDecl(decl)),
.aligned_var_decl => return renderVarDecl(gpa, ais, tree, tree.alignedVarDecl(decl)),
.test_decl => {
const test_token = main_tokens[decl];
try renderToken(ais, tree, test_token, .space);
if (token_tags[test_token + 1] == .string_literal) {
try renderToken(ais, tree, test_token + 1, .space);
}
try renderExpression(gpa, ais, tree, datas[decl].rhs, space);
},
.container_field_init => return renderContainerField(gpa, ais, tree, tree.containerFieldInit(decl), space),
.container_field_align => return renderContainerField(gpa, ais, tree, tree.containerFieldAlign(decl), space),
.container_field => return renderContainerField(gpa, ais, tree, tree.containerField(decl), space),
.@"comptime" => return renderExpression(gpa, ais, tree, decl, space),
.root => unreachable,
else => unreachable,
}
}
/// Render all expressions in the slice, keeping empty lines where appropriate
fn renderExpressions(gpa: *Allocator, ais: *Ais, tree: ast.Tree, expressions: []const ast.Node.Index, space: Space) Error!void {
if (expressions.len == 0) return;
try renderExpression(gpa, ais, tree, expressions[0], space);
for (expressions[1..]) |expression| {
try renderExtraNewline(ais, tree, expression);
try renderExpression(gpa, ais, tree, expression, space);
}
}
fn renderExpression(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.Index, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const node_tags = tree.nodes.items(.tag);
const datas = tree.nodes.items(.data);
switch (node_tags[node]) {
.identifier,
.integer_literal,
.float_literal,
.char_literal,
.unreachable_literal,
.anyframe_literal,
.string_literal,
=> return renderToken(ais, tree, main_tokens[node], space),
.multiline_string_literal => {
var locked_indents = ais.lockOneShotIndent();
try ais.maybeInsertNewline();
var i = datas[node].lhs;
while (i <= datas[node].rhs) : (i += 1) try renderToken(ais, tree, i, .newline);
while (locked_indents > 0) : (locked_indents -= 1) ais.popIndent();
switch (space) {
.none, .space, .newline, .skip => {},
.semicolon => if (token_tags[i] == .semicolon) try renderToken(ais, tree, i, .newline),
.comma => if (token_tags[i] == .comma) try renderToken(ais, tree, i, .newline),
.comma_space => if (token_tags[i] == .comma) try renderToken(ais, tree, i, .space),
}
},
.error_value => {
try renderToken(ais, tree, main_tokens[node], .none);
try renderToken(ais, tree, main_tokens[node] + 1, .none);
return renderToken(ais, tree, main_tokens[node] + 2, space);
},
.@"anytype" => return renderToken(ais, tree, main_tokens[node], space),
.block_two,
.block_two_semicolon,
=> {
const statements = [2]ast.Node.Index{ datas[node].lhs, datas[node].rhs };
if (datas[node].lhs == 0) {
return renderBlock(gpa, ais, tree, node, statements[0..0], space);
} else if (datas[node].rhs == 0) {
return renderBlock(gpa, ais, tree, node, statements[0..1], space);
} else {
return renderBlock(gpa, ais, tree, node, statements[0..2], space);
}
},
.block,
.block_semicolon,
=> {
const statements = tree.extra_data[datas[node].lhs..datas[node].rhs];
return renderBlock(gpa, ais, tree, node, statements, space);
},
.@"errdefer" => {
const defer_token = main_tokens[node];
const payload_token = datas[node].lhs;
const expr = datas[node].rhs;
try renderToken(ais, tree, defer_token, .space);
if (payload_token != 0) {
try renderToken(ais, tree, payload_token - 1, .none); // |
try renderToken(ais, tree, payload_token, .none); // identifier
try renderToken(ais, tree, payload_token + 1, .space); // |
}
return renderExpression(gpa, ais, tree, expr, space);
},
.@"defer" => {
const defer_token = main_tokens[node];
const expr = datas[node].rhs;
try renderToken(ais, tree, defer_token, .space);
return renderExpression(gpa, ais, tree, expr, space);
},
.@"comptime", .@"nosuspend" => {
const comptime_token = main_tokens[node];
const block = datas[node].lhs;
try renderToken(ais, tree, comptime_token, .space);
return renderExpression(gpa, ais, tree, block, space);
},
.@"suspend" => {
const suspend_token = main_tokens[node];
const body = datas[node].lhs;
try renderToken(ais, tree, suspend_token, .space);
return renderExpression(gpa, ais, tree, body, space);
},
.@"catch" => {
const main_token = main_tokens[node];
const fallback_first = tree.firstToken(datas[node].rhs);
const same_line = tree.tokensOnSameLine(main_token, fallback_first);
const after_op_space = if (same_line) Space.space else Space.newline;
try renderExpression(gpa, ais, tree, datas[node].lhs, .space); // target
if (token_tags[fallback_first - 1] == .pipe) {
try renderToken(ais, tree, main_token, .space); // catch keyword
try renderToken(ais, tree, main_token + 1, .none); // pipe
try renderToken(ais, tree, main_token + 2, .none); // payload identifier
try renderToken(ais, tree, main_token + 3, after_op_space); // pipe
} else {
assert(token_tags[fallback_first - 1] == .keyword_catch);
try renderToken(ais, tree, main_token, after_op_space); // catch keyword
}
ais.pushIndentOneShot();
try renderExpression(gpa, ais, tree, datas[node].rhs, space); // fallback
},
.field_access => {
const main_token = main_tokens[node];
const field_access = datas[node];
try renderExpression(gpa, ais, tree, field_access.lhs, .none);
// Allow a line break between the lhs and the dot if the lhs and rhs
// are on different lines.
const lhs_last_token = tree.lastToken(field_access.lhs);
const same_line = tree.tokensOnSameLine(lhs_last_token, main_token + 1);
if (!same_line) {
if (!hasComment(tree, lhs_last_token, main_token)) try ais.insertNewline();
ais.pushIndentOneShot();
}
try renderToken(ais, tree, main_token, .none);
// This check ensures that zag() is indented in the following example:
// const x = foo
// .bar()
// . // comment
// zag();
if (!same_line and hasComment(tree, main_token, main_token + 1)) {
ais.pushIndentOneShot();
}
return renderToken(ais, tree, field_access.rhs, space);
},
.error_union,
.switch_range,
=> {
const infix = datas[node];
try renderExpression(gpa, ais, tree, infix.lhs, .none);
try renderToken(ais, tree, main_tokens[node], .none);
return renderExpression(gpa, ais, tree, infix.rhs, space);
},
.add,
.add_wrap,
.array_cat,
.array_mult,
.assign,
.assign_bit_and,
.assign_bit_or,
.assign_bit_shift_left,
.assign_bit_shift_right,
.assign_bit_xor,
.assign_div,
.assign_sub,
.assign_sub_wrap,
.assign_mod,
.assign_add,
.assign_add_wrap,
.assign_mul,
.assign_mul_wrap,
.bang_equal,
.bit_and,
.bit_or,
.bit_shift_left,
.bit_shift_right,
.bit_xor,
.bool_and,
.bool_or,
.div,
.equal_equal,
.greater_or_equal,
.greater_than,
.less_or_equal,
.less_than,
.merge_error_sets,
.mod,
.mul,
.mul_wrap,
.sub,
.sub_wrap,
.@"orelse",
=> {
const infix = datas[node];
try renderExpression(gpa, ais, tree, infix.lhs, .space);
const op_token = main_tokens[node];
if (tree.tokensOnSameLine(op_token, op_token + 1)) {
try renderToken(ais, tree, op_token, .space);
} else {
ais.pushIndent();
try renderToken(ais, tree, op_token, .newline);
ais.popIndent();
}
ais.pushIndentOneShot();
return renderExpression(gpa, ais, tree, infix.rhs, space);
},
.bit_not,
.bool_not,
.negation,
.negation_wrap,
.optional_type,
.address_of,
=> {
try renderToken(ais, tree, main_tokens[node], .none);
return renderExpression(gpa, ais, tree, datas[node].lhs, space);
},
.@"try",
.@"resume",
.@"await",
=> {
try renderToken(ais, tree, main_tokens[node], .space);
return renderExpression(gpa, ais, tree, datas[node].lhs, space);
},
.array_type => return renderArrayType(gpa, ais, tree, tree.arrayType(node), space),
.array_type_sentinel => return renderArrayType(gpa, ais, tree, tree.arrayTypeSentinel(node), space),
.ptr_type_aligned => return renderPtrType(gpa, ais, tree, tree.ptrTypeAligned(node), space),
.ptr_type_sentinel => return renderPtrType(gpa, ais, tree, tree.ptrTypeSentinel(node), space),
.ptr_type => return renderPtrType(gpa, ais, tree, tree.ptrType(node), space),
.ptr_type_bit_range => return renderPtrType(gpa, ais, tree, tree.ptrTypeBitRange(node), space),
.array_init_one, .array_init_one_comma => {
var elements: [1]ast.Node.Index = undefined;
return renderArrayInit(gpa, ais, tree, tree.arrayInitOne(&elements, node), space);
},
.array_init_dot_two, .array_init_dot_two_comma => {
var elements: [2]ast.Node.Index = undefined;
return renderArrayInit(gpa, ais, tree, tree.arrayInitDotTwo(&elements, node), space);
},
.array_init_dot,
.array_init_dot_comma,
=> return renderArrayInit(gpa, ais, tree, tree.arrayInitDot(node), space),
.array_init,
.array_init_comma,
=> return renderArrayInit(gpa, ais, tree, tree.arrayInit(node), space),
.struct_init_one, .struct_init_one_comma => {
var fields: [1]ast.Node.Index = undefined;
return renderStructInit(gpa, ais, tree, node, tree.structInitOne(&fields, node), space);
},
.struct_init_dot_two, .struct_init_dot_two_comma => {
var fields: [2]ast.Node.Index = undefined;
return renderStructInit(gpa, ais, tree, node, tree.structInitDotTwo(&fields, node), space);
},
.struct_init_dot,
.struct_init_dot_comma,
=> return renderStructInit(gpa, ais, tree, node, tree.structInitDot(node), space),
.struct_init,
.struct_init_comma,
=> return renderStructInit(gpa, ais, tree, node, tree.structInit(node), space),
.call_one, .call_one_comma, .async_call_one, .async_call_one_comma => {
var params: [1]ast.Node.Index = undefined;
return renderCall(gpa, ais, tree, tree.callOne(¶ms, node), space);
},
.call,
.call_comma,
.async_call,
.async_call_comma,
=> return renderCall(gpa, ais, tree, tree.callFull(node), space),
.array_access => {
const suffix = datas[node];
const lbracket = tree.firstToken(suffix.rhs) - 1;
const rbracket = tree.lastToken(suffix.rhs) + 1;
const one_line = tree.tokensOnSameLine(lbracket, rbracket);
const inner_space = if (one_line) Space.none else Space.newline;
try renderExpression(gpa, ais, tree, suffix.lhs, .none);
ais.pushIndentNextLine();
try renderToken(ais, tree, lbracket, inner_space); // [
try renderExpression(gpa, ais, tree, suffix.rhs, inner_space);
ais.popIndent();
return renderToken(ais, tree, rbracket, space); // ]
},
.slice_open => return renderSlice(gpa, ais, tree, node, tree.sliceOpen(node), space),
.slice => return renderSlice(gpa, ais, tree, node, tree.slice(node), space),
.slice_sentinel => return renderSlice(gpa, ais, tree, node, tree.sliceSentinel(node), space),
.deref => {
try renderExpression(gpa, ais, tree, datas[node].lhs, .none);
return renderToken(ais, tree, main_tokens[node], space);
},
.unwrap_optional => {
try renderExpression(gpa, ais, tree, datas[node].lhs, .none);
try renderToken(ais, tree, main_tokens[node], .none);
return renderToken(ais, tree, datas[node].rhs, space);
},
.@"break" => {
const main_token = main_tokens[node];
const label_token = datas[node].lhs;
const target = datas[node].rhs;
if (label_token == 0 and target == 0) {
try renderToken(ais, tree, main_token, space); // break keyword
} else if (label_token == 0 and target != 0) {
try renderToken(ais, tree, main_token, .space); // break keyword
try renderExpression(gpa, ais, tree, target, space);
} else if (label_token != 0 and target == 0) {
try renderToken(ais, tree, main_token, .space); // break keyword
try renderToken(ais, tree, label_token - 1, .none); // colon
try renderToken(ais, tree, label_token, space); // identifier
} else if (label_token != 0 and target != 0) {
try renderToken(ais, tree, main_token, .space); // break keyword
try renderToken(ais, tree, label_token - 1, .none); // colon
try renderToken(ais, tree, label_token, .space); // identifier
try renderExpression(gpa, ais, tree, target, space);
}
},
.@"continue" => {
const main_token = main_tokens[node];
const label = datas[node].lhs;
if (label != 0) {
try renderToken(ais, tree, main_token, .space); // continue
try renderToken(ais, tree, label - 1, .none); // :
return renderToken(ais, tree, label, space); // label
} else {
return renderToken(ais, tree, main_token, space); // continue
}
},
.@"return" => {
if (datas[node].lhs != 0) {
try renderToken(ais, tree, main_tokens[node], .space);
try renderExpression(gpa, ais, tree, datas[node].lhs, space);
} else {
try renderToken(ais, tree, main_tokens[node], space);
}
},
.grouped_expression => {
try renderToken(ais, tree, main_tokens[node], .none); // lparen
ais.pushIndentOneShot();
try renderExpression(gpa, ais, tree, datas[node].lhs, .none);
return renderToken(ais, tree, datas[node].rhs, space); // rparen
},
.container_decl,
.container_decl_trailing,
=> return renderContainerDecl(gpa, ais, tree, node, tree.containerDecl(node), space),
.container_decl_two, .container_decl_two_trailing => {
var buffer: [2]ast.Node.Index = undefined;
return renderContainerDecl(gpa, ais, tree, node, tree.containerDeclTwo(&buffer, node), space);
},
.container_decl_arg,
.container_decl_arg_trailing,
=> return renderContainerDecl(gpa, ais, tree, node, tree.containerDeclArg(node), space),
.tagged_union,
.tagged_union_trailing,
=> return renderContainerDecl(gpa, ais, tree, node, tree.taggedUnion(node), space),
.tagged_union_two, .tagged_union_two_trailing => {
var buffer: [2]ast.Node.Index = undefined;
return renderContainerDecl(gpa, ais, tree, node, tree.taggedUnionTwo(&buffer, node), space);
},
.tagged_union_enum_tag,
.tagged_union_enum_tag_trailing,
=> return renderContainerDecl(gpa, ais, tree, node, tree.taggedUnionEnumTag(node), space),
.error_set_decl => {
const error_token = main_tokens[node];
const lbrace = error_token + 1;
const rbrace = datas[node].rhs;
try renderToken(ais, tree, error_token, .none);
if (lbrace + 1 == rbrace) {
// There is nothing between the braces so render condensed: `error{}`
try renderToken(ais, tree, lbrace, .none);
return renderToken(ais, tree, rbrace, space);
} else if (lbrace + 2 == rbrace and token_tags[lbrace + 1] == .identifier) {
// There is exactly one member and no trailing comma or
// comments, so render without surrounding spaces: `error{Foo}`
try renderToken(ais, tree, lbrace, .none);
try renderToken(ais, tree, lbrace + 1, .none); // identifier
return renderToken(ais, tree, rbrace, space);
} else if (token_tags[rbrace - 1] == .comma) {
// There is a trailing comma so render each member on a new line.
ais.pushIndentNextLine();
try renderToken(ais, tree, lbrace, .newline);
var i = lbrace + 1;
while (i < rbrace) : (i += 1) {
if (i > lbrace + 1) try renderExtraNewlineToken(ais, tree, i);
switch (token_tags[i]) {
.doc_comment => try renderToken(ais, tree, i, .newline),
.identifier => try renderToken(ais, tree, i, .comma),
.comma => {},
else => unreachable,
}
}
ais.popIndent();
return renderToken(ais, tree, rbrace, space);
} else {
// There is no trailing comma so render everything on one line.
try renderToken(ais, tree, lbrace, .space);
var i = lbrace + 1;
while (i < rbrace) : (i += 1) {
switch (token_tags[i]) {
.doc_comment => unreachable, // TODO
.identifier => try renderToken(ais, tree, i, .comma_space),
.comma => {},
else => unreachable,
}
}
return renderToken(ais, tree, rbrace, space);
}
},
.builtin_call_two, .builtin_call_two_comma => {
if (datas[node].lhs == 0) {
return renderBuiltinCall(gpa, ais, tree, main_tokens[node], &.{}, space);
} else if (datas[node].rhs == 0) {
return renderBuiltinCall(gpa, ais, tree, main_tokens[node], &.{datas[node].lhs}, space);
} else {
return renderBuiltinCall(gpa, ais, tree, main_tokens[node], &.{ datas[node].lhs, datas[node].rhs }, space);
}
},
.builtin_call, .builtin_call_comma => {
const params = tree.extra_data[datas[node].lhs..datas[node].rhs];
return renderBuiltinCall(gpa, ais, tree, main_tokens[node], params, space);
},
.fn_proto_simple => {
var params: [1]ast.Node.Index = undefined;
return renderFnProto(gpa, ais, tree, tree.fnProtoSimple(¶ms, node), space);
},
.fn_proto_multi => return renderFnProto(gpa, ais, tree, tree.fnProtoMulti(node), space),
.fn_proto_one => {
var params: [1]ast.Node.Index = undefined;
return renderFnProto(gpa, ais, tree, tree.fnProtoOne(¶ms, node), space);
},
.fn_proto => return renderFnProto(gpa, ais, tree, tree.fnProto(node), space),
.anyframe_type => {
const main_token = main_tokens[node];
if (datas[node].rhs != 0) {
try renderToken(ais, tree, main_token, .none); // anyframe
try renderToken(ais, tree, main_token + 1, .none); // ->
return renderExpression(gpa, ais, tree, datas[node].rhs, space);
} else {
return renderToken(ais, tree, main_token, space); // anyframe
}
},
.@"switch",
.switch_comma,
=> {
const switch_token = main_tokens[node];
const condition = datas[node].lhs;
const extra = tree.extraData(datas[node].rhs, ast.Node.SubRange);
const cases = tree.extra_data[extra.start..extra.end];
const rparen = tree.lastToken(condition) + 1;
try renderToken(ais, tree, switch_token, .space); // switch keyword
try renderToken(ais, tree, switch_token + 1, .none); // lparen
try renderExpression(gpa, ais, tree, condition, .none); // condtion expression
try renderToken(ais, tree, rparen, .space); // rparen
ais.pushIndentNextLine();
if (cases.len == 0) {
try renderToken(ais, tree, rparen + 1, .none); // lbrace
} else {
try renderToken(ais, tree, rparen + 1, .newline); // lbrace
try renderExpressions(gpa, ais, tree, cases, .comma);
}
ais.popIndent();
return renderToken(ais, tree, tree.lastToken(node), space); // rbrace
},
.switch_case_one => return renderSwitchCase(gpa, ais, tree, tree.switchCaseOne(node), space),
.switch_case => return renderSwitchCase(gpa, ais, tree, tree.switchCase(node), space),
.while_simple => return renderWhile(gpa, ais, tree, tree.whileSimple(node), space),
.while_cont => return renderWhile(gpa, ais, tree, tree.whileCont(node), space),
.@"while" => return renderWhile(gpa, ais, tree, tree.whileFull(node), space),
.for_simple => return renderWhile(gpa, ais, tree, tree.forSimple(node), space),
.@"for" => return renderWhile(gpa, ais, tree, tree.forFull(node), space),
.if_simple => return renderIf(gpa, ais, tree, tree.ifSimple(node), space),
.@"if" => return renderIf(gpa, ais, tree, tree.ifFull(node), space),
.asm_simple => return renderAsm(gpa, ais, tree, tree.asmSimple(node), space),
.@"asm" => return renderAsm(gpa, ais, tree, tree.asmFull(node), space),
.enum_literal => {
try renderToken(ais, tree, main_tokens[node] - 1, .none); // .
return renderToken(ais, tree, main_tokens[node], space); // name
},
.fn_decl => unreachable,
.container_field => unreachable,
.container_field_init => unreachable,
.container_field_align => unreachable,
.root => unreachable,
.global_var_decl => unreachable,
.local_var_decl => unreachable,
.simple_var_decl => unreachable,
.aligned_var_decl => unreachable,
.@"usingnamespace" => unreachable,
.test_decl => unreachable,
.asm_output => unreachable,
.asm_input => unreachable,
}
}
fn renderArrayType(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
array_type: ast.full.ArrayType,
space: Space,
) Error!void {
const rbracket = tree.firstToken(array_type.ast.elem_type) - 1;
const one_line = tree.tokensOnSameLine(array_type.ast.lbracket, rbracket);
const inner_space = if (one_line) Space.none else Space.newline;
ais.pushIndentNextLine();
try renderToken(ais, tree, array_type.ast.lbracket, inner_space); // lbracket
try renderExpression(gpa, ais, tree, array_type.ast.elem_count, inner_space);
if (array_type.ast.sentinel != 0) {
try renderToken(ais, tree, tree.firstToken(array_type.ast.sentinel) - 1, inner_space); // colon
try renderExpression(gpa, ais, tree, array_type.ast.sentinel, inner_space);
}
ais.popIndent();
try renderToken(ais, tree, rbracket, .none); // rbracket
return renderExpression(gpa, ais, tree, array_type.ast.elem_type, space);
}
fn renderPtrType(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
ptr_type: ast.full.PtrType,
space: Space,
) Error!void {
switch (ptr_type.size) {
.One => {
// Since ** tokens exist and the same token is shared by two
// nested pointer types, we check to see if we are the parent
// in such a relationship. If so, skip rendering anything for
// this pointer type and rely on the child to render our asterisk
// as well when it renders the ** token.
if (tree.tokens.items(.tag)[ptr_type.ast.main_token] == .asterisk_asterisk and
ptr_type.ast.main_token == tree.nodes.items(.main_token)[ptr_type.ast.child_type])
{
return renderExpression(gpa, ais, tree, ptr_type.ast.child_type, space);
}
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // asterisk
},
.Many => {
if (ptr_type.ast.sentinel == 0) {
try renderToken(ais, tree, ptr_type.ast.main_token - 1, .none); // lbracket
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // asterisk
try renderToken(ais, tree, ptr_type.ast.main_token + 1, .none); // rbracket
} else {
try renderToken(ais, tree, ptr_type.ast.main_token - 1, .none); // lbracket
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // asterisk
try renderToken(ais, tree, ptr_type.ast.main_token + 1, .none); // colon
try renderExpression(gpa, ais, tree, ptr_type.ast.sentinel, .none);
try renderToken(ais, tree, tree.lastToken(ptr_type.ast.sentinel) + 1, .none); // rbracket
}
},
.C => {
try renderToken(ais, tree, ptr_type.ast.main_token - 1, .none); // lbracket
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // asterisk
try renderToken(ais, tree, ptr_type.ast.main_token + 1, .none); // c
try renderToken(ais, tree, ptr_type.ast.main_token + 2, .none); // rbracket
},
.Slice => {
if (ptr_type.ast.sentinel == 0) {
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // lbracket
try renderToken(ais, tree, ptr_type.ast.main_token + 1, .none); // rbracket
} else {
try renderToken(ais, tree, ptr_type.ast.main_token, .none); // lbracket
try renderToken(ais, tree, ptr_type.ast.main_token + 1, .none); // colon
try renderExpression(gpa, ais, tree, ptr_type.ast.sentinel, .none);
try renderToken(ais, tree, tree.lastToken(ptr_type.ast.sentinel) + 1, .none); // rbracket
}
},
}
if (ptr_type.allowzero_token) |allowzero_token| {
try renderToken(ais, tree, allowzero_token, .space);
}
if (ptr_type.ast.align_node != 0) {
const align_first = tree.firstToken(ptr_type.ast.align_node);
try renderToken(ais, tree, align_first - 2, .none); // align
try renderToken(ais, tree, align_first - 1, .none); // lparen
try renderExpression(gpa, ais, tree, ptr_type.ast.align_node, .none);
if (ptr_type.ast.bit_range_start != 0) {
assert(ptr_type.ast.bit_range_end != 0);
try renderToken(ais, tree, tree.firstToken(ptr_type.ast.bit_range_start) - 1, .none); // colon
try renderExpression(gpa, ais, tree, ptr_type.ast.bit_range_start, .none);
try renderToken(ais, tree, tree.firstToken(ptr_type.ast.bit_range_end) - 1, .none); // colon
try renderExpression(gpa, ais, tree, ptr_type.ast.bit_range_end, .none);
try renderToken(ais, tree, tree.lastToken(ptr_type.ast.bit_range_end) + 1, .space); // rparen
} else {
try renderToken(ais, tree, tree.lastToken(ptr_type.ast.align_node) + 1, .space); // rparen
}
}
if (ptr_type.const_token) |const_token| {
try renderToken(ais, tree, const_token, .space);
}
if (ptr_type.volatile_token) |volatile_token| {
try renderToken(ais, tree, volatile_token, .space);
}
try renderExpression(gpa, ais, tree, ptr_type.ast.child_type, space);
}
fn renderSlice(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
slice_node: ast.Node.Index,
slice: ast.full.Slice,
space: Space,
) Error!void {
const node_tags = tree.nodes.items(.tag);
const after_start_space_bool = nodeCausesSliceOpSpace(node_tags[slice.ast.start]) or
if (slice.ast.end != 0) nodeCausesSliceOpSpace(node_tags[slice.ast.end]) else false;
const after_start_space = if (after_start_space_bool) Space.space else Space.none;
const after_dots_space = if (slice.ast.end != 0)
after_start_space
else if (slice.ast.sentinel != 0) Space.space else Space.none;
try renderExpression(gpa, ais, tree, slice.ast.sliced, .none);
try renderToken(ais, tree, slice.ast.lbracket, .none); // lbracket
const start_last = tree.lastToken(slice.ast.start);
try renderExpression(gpa, ais, tree, slice.ast.start, after_start_space);
try renderToken(ais, tree, start_last + 1, after_dots_space); // ellipsis2 ("..")
if (slice.ast.end != 0) {
const after_end_space = if (slice.ast.sentinel != 0) Space.space else Space.none;
try renderExpression(gpa, ais, tree, slice.ast.end, after_end_space);
}
if (slice.ast.sentinel != 0) {
try renderToken(ais, tree, tree.firstToken(slice.ast.sentinel) - 1, .none); // colon
try renderExpression(gpa, ais, tree, slice.ast.sentinel, .none);
}
try renderToken(ais, tree, tree.lastToken(slice_node), space); // rbracket
}
fn renderAsmOutput(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
asm_output: ast.Node.Index,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const datas = tree.nodes.items(.data);
assert(node_tags[asm_output] == .asm_output);
const symbolic_name = main_tokens[asm_output];
try renderToken(ais, tree, symbolic_name - 1, .none); // lbracket
try renderToken(ais, tree, symbolic_name, .none); // ident
try renderToken(ais, tree, symbolic_name + 1, .space); // rbracket
try renderToken(ais, tree, symbolic_name + 2, .space); // "constraint"
try renderToken(ais, tree, symbolic_name + 3, .none); // lparen
if (token_tags[symbolic_name + 4] == .arrow) {
try renderToken(ais, tree, symbolic_name + 4, .space); // ->
try renderExpression(gpa, ais, tree, datas[asm_output].lhs, Space.none);
return renderToken(ais, tree, datas[asm_output].rhs, space); // rparen
} else {
try renderToken(ais, tree, symbolic_name + 4, .none); // ident
return renderToken(ais, tree, symbolic_name + 5, space); // rparen
}
}
fn renderAsmInput(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
asm_input: ast.Node.Index,
space: Space,
) Error!void {
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const datas = tree.nodes.items(.data);
assert(node_tags[asm_input] == .asm_input);
const symbolic_name = main_tokens[asm_input];
try renderToken(ais, tree, symbolic_name - 1, .none); // lbracket
try renderToken(ais, tree, symbolic_name, .none); // ident
try renderToken(ais, tree, symbolic_name + 1, .space); // rbracket
try renderToken(ais, tree, symbolic_name + 2, .space); // "constraint"
try renderToken(ais, tree, symbolic_name + 3, .none); // lparen
try renderExpression(gpa, ais, tree, datas[asm_input].lhs, Space.none);
return renderToken(ais, tree, datas[asm_input].rhs, space); // rparen
}
fn renderVarDecl(gpa: *Allocator, ais: *Ais, tree: ast.Tree, var_decl: ast.full.VarDecl) Error!void {
if (var_decl.visib_token) |visib_token| {
try renderToken(ais, tree, visib_token, Space.space); // pub
}
if (var_decl.extern_export_token) |extern_export_token| {
try renderToken(ais, tree, extern_export_token, Space.space); // extern
if (var_decl.lib_name) |lib_name| {
try renderToken(ais, tree, lib_name, Space.space); // "lib"
}
}
if (var_decl.threadlocal_token) |thread_local_token| {
try renderToken(ais, tree, thread_local_token, Space.space); // threadlocal
}
if (var_decl.comptime_token) |comptime_token| {
try renderToken(ais, tree, comptime_token, Space.space); // comptime
}
try renderToken(ais, tree, var_decl.ast.mut_token, .space); // var
const name_space = if (var_decl.ast.type_node == 0 and
(var_decl.ast.align_node != 0 or
var_decl.ast.section_node != 0 or
var_decl.ast.init_node != 0))
Space.space
else
Space.none;
try renderToken(ais, tree, var_decl.ast.mut_token + 1, name_space); // name
if (var_decl.ast.type_node != 0) {
try renderToken(ais, tree, var_decl.ast.mut_token + 2, Space.space); // :
if (var_decl.ast.align_node != 0 or var_decl.ast.section_node != 0 or
var_decl.ast.init_node != 0)
{
try renderExpression(gpa, ais, tree, var_decl.ast.type_node, .space);
} else {
try renderExpression(gpa, ais, tree, var_decl.ast.type_node, .none);
const semicolon = tree.lastToken(var_decl.ast.type_node) + 1;
return renderToken(ais, tree, semicolon, Space.newline); // ;
}
}
if (var_decl.ast.align_node != 0) {
const lparen = tree.firstToken(var_decl.ast.align_node) - 1;
const align_kw = lparen - 1;
const rparen = tree.lastToken(var_decl.ast.align_node) + 1;
try renderToken(ais, tree, align_kw, Space.none); // align
try renderToken(ais, tree, lparen, Space.none); // (
try renderExpression(gpa, ais, tree, var_decl.ast.align_node, Space.none);
if (var_decl.ast.section_node != 0 or var_decl.ast.init_node != 0) {
try renderToken(ais, tree, rparen, .space); // )
} else {
try renderToken(ais, tree, rparen, .none); // )
return renderToken(ais, tree, rparen + 1, Space.newline); // ;
}
}
if (var_decl.ast.section_node != 0) {
const lparen = tree.firstToken(var_decl.ast.section_node) - 1;
const section_kw = lparen - 1;
const rparen = tree.lastToken(var_decl.ast.section_node) + 1;
try renderToken(ais, tree, section_kw, Space.none); // linksection
try renderToken(ais, tree, lparen, Space.none); // (
try renderExpression(gpa, ais, tree, var_decl.ast.section_node, Space.none);
if (var_decl.ast.init_node != 0) {
try renderToken(ais, tree, rparen, .space); // )
} else {
try renderToken(ais, tree, rparen, .none); // )
return renderToken(ais, tree, rparen + 1, Space.newline); // ;
}
}
if (var_decl.ast.init_node != 0) {
const eq_token = tree.firstToken(var_decl.ast.init_node) - 1;
const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline;
{
ais.pushIndent();
try renderToken(ais, tree, eq_token, eq_space); // =
ais.popIndent();
}
ais.pushIndentOneShot();
return renderExpression(gpa, ais, tree, var_decl.ast.init_node, .semicolon); // ;
}
return renderToken(ais, tree, var_decl.ast.mut_token + 2, .newline); // ;
}
fn renderIf(gpa: *Allocator, ais: *Ais, tree: ast.Tree, if_node: ast.full.If, space: Space) Error!void {
return renderWhile(gpa, ais, tree, .{
.ast = .{
.while_token = if_node.ast.if_token,
.cond_expr = if_node.ast.cond_expr,
.cont_expr = 0,
.then_expr = if_node.ast.then_expr,
.else_expr = if_node.ast.else_expr,
},
.inline_token = null,
.label_token = null,
.payload_token = if_node.payload_token,
.else_token = if_node.else_token,
.error_token = if_node.error_token,
}, space);
}
/// Note that this function is additionally used to render if and for expressions, with
/// respective values set to null.
fn renderWhile(gpa: *Allocator, ais: *Ais, tree: ast.Tree, while_node: ast.full.While, space: Space) Error!void {
const node_tags = tree.nodes.items(.tag);
const token_tags = tree.tokens.items(.tag);
if (while_node.label_token) |label| {
try renderToken(ais, tree, label, .none); // label
try renderToken(ais, tree, label + 1, .space); // :
}
if (while_node.inline_token) |inline_token| {
try renderToken(ais, tree, inline_token, .space); // inline
}
try renderToken(ais, tree, while_node.ast.while_token, .space); // if/for/while
try renderToken(ais, tree, while_node.ast.while_token + 1, .none); // lparen
try renderExpression(gpa, ais, tree, while_node.ast.cond_expr, .none); // condition
var last_prefix_token = tree.lastToken(while_node.ast.cond_expr) + 1; // rparen
if (while_node.payload_token) |payload_token| {
try renderToken(ais, tree, last_prefix_token, .space);
try renderToken(ais, tree, payload_token - 1, .none); // |
const ident = blk: {
if (token_tags[payload_token] == .asterisk) {
try renderToken(ais, tree, payload_token, .none); // *
break :blk payload_token + 1;
} else {
break :blk payload_token;
}
};
try renderToken(ais, tree, ident, .none); // identifier
const pipe = blk: {
if (token_tags[ident + 1] == .comma) {
try renderToken(ais, tree, ident + 1, .space); // ,
try renderToken(ais, tree, ident + 2, .none); // index
break :blk ident + 3;
} else {
break :blk ident + 1;
}
};
last_prefix_token = pipe;
}
if (while_node.ast.cont_expr != 0) {
try renderToken(ais, tree, last_prefix_token, .space);
const lparen = tree.firstToken(while_node.ast.cont_expr) - 1;
try renderToken(ais, tree, lparen - 1, .space); // :
try renderToken(ais, tree, lparen, .none); // lparen
try renderExpression(gpa, ais, tree, while_node.ast.cont_expr, .none);
last_prefix_token = tree.lastToken(while_node.ast.cont_expr) + 1; // rparen
}
const then_expr_is_block = nodeIsBlock(node_tags[while_node.ast.then_expr]);
const indent_then_expr = !then_expr_is_block and
!tree.tokensOnSameLine(last_prefix_token, tree.firstToken(while_node.ast.then_expr));
if (indent_then_expr or (then_expr_is_block and ais.isLineOverIndented())) {
ais.pushIndentNextLine();
try renderToken(ais, tree, last_prefix_token, .newline);
ais.popIndent();
} else {
try renderToken(ais, tree, last_prefix_token, .space);
}
if (while_node.ast.else_expr != 0) {
if (indent_then_expr) {
ais.pushIndent();
try renderExpression(gpa, ais, tree, while_node.ast.then_expr, .newline);
ais.popIndent();
} else {
try renderExpression(gpa, ais, tree, while_node.ast.then_expr, .space);
}
var last_else_token = while_node.else_token;
if (while_node.error_token) |error_token| {
try renderToken(ais, tree, while_node.else_token, .space); // else
try renderToken(ais, tree, error_token - 1, .none); // |
try renderToken(ais, tree, error_token, .none); // identifier
last_else_token = error_token + 1; // |
}
const indent_else_expr = indent_then_expr and
!nodeIsBlock(node_tags[while_node.ast.else_expr]) and
!nodeIsIfForWhileSwitch(node_tags[while_node.ast.else_expr]);
if (indent_else_expr) {
ais.pushIndentNextLine();
try renderToken(ais, tree, last_else_token, .newline);
ais.popIndent();
try renderExpressionIndented(gpa, ais, tree, while_node.ast.else_expr, space);
} else {
try renderToken(ais, tree, last_else_token, .space);
try renderExpression(gpa, ais, tree, while_node.ast.else_expr, space);
}
} else {
if (indent_then_expr) {
try renderExpressionIndented(gpa, ais, tree, while_node.ast.then_expr, space);
} else {
try renderExpression(gpa, ais, tree, while_node.ast.then_expr, space);
}
}
}
fn renderContainerField(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
field: ast.full.ContainerField,
space: Space,
) Error!void {
if (field.comptime_token) |t| {
try renderToken(ais, tree, t, .space); // comptime
}
if (field.ast.type_expr == 0 and field.ast.value_expr == 0) {
return renderTokenComma(ais, tree, field.ast.name_token, space); // name
}
if (field.ast.type_expr != 0 and field.ast.value_expr == 0) {
try renderToken(ais, tree, field.ast.name_token, .none); // name
try renderToken(ais, tree, field.ast.name_token + 1, .space); // :
if (field.ast.align_expr != 0) {
try renderExpression(gpa, ais, tree, field.ast.type_expr, .space); // type
const align_token = tree.firstToken(field.ast.align_expr) - 2;
try renderToken(ais, tree, align_token, .none); // align
try renderToken(ais, tree, align_token + 1, .none); // (
try renderExpression(gpa, ais, tree, field.ast.align_expr, .none); // alignment
const rparen = tree.lastToken(field.ast.align_expr) + 1;
return renderTokenComma(ais, tree, rparen, space); // )
} else {
return renderExpressionComma(gpa, ais, tree, field.ast.type_expr, space); // type
}
}
if (field.ast.type_expr == 0 and field.ast.value_expr != 0) {
try renderToken(ais, tree, field.ast.name_token, .space); // name
try renderToken(ais, tree, field.ast.name_token + 1, .space); // =
return renderExpressionComma(gpa, ais, tree, field.ast.value_expr, space); // value
}
try renderToken(ais, tree, field.ast.name_token, .none); // name
try renderToken(ais, tree, field.ast.name_token + 1, .space); // :
try renderExpression(gpa, ais, tree, field.ast.type_expr, .space); // type
if (field.ast.align_expr != 0) {
const lparen_token = tree.firstToken(field.ast.align_expr) - 1;
const align_kw = lparen_token - 1;
const rparen_token = tree.lastToken(field.ast.align_expr) + 1;
try renderToken(ais, tree, align_kw, .none); // align
try renderToken(ais, tree, lparen_token, .none); // (
try renderExpression(gpa, ais, tree, field.ast.align_expr, .none); // alignment
try renderToken(ais, tree, rparen_token, .space); // )
}
const eq_token = tree.firstToken(field.ast.value_expr) - 1;
const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline;
{
ais.pushIndent();
try renderToken(ais, tree, eq_token, eq_space); // =
ais.popIndent();
}
if (eq_space == .space)
return renderExpressionComma(gpa, ais, tree, field.ast.value_expr, space); // value
const token_tags = tree.tokens.items(.tag);
const maybe_comma = tree.lastToken(field.ast.value_expr) + 1;
if (token_tags[maybe_comma] == .comma) {
ais.pushIndent();
try renderExpression(gpa, ais, tree, field.ast.value_expr, .none); // value
ais.popIndent();
try renderToken(ais, tree, maybe_comma, space);
} else {
ais.pushIndent();
try renderExpression(gpa, ais, tree, field.ast.value_expr, space); // value
ais.popIndent();
}
}
fn renderBuiltinCall(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
builtin_token: ast.TokenIndex,
params: []const ast.Node.Index,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
const builtin_name = tokenSliceForRender(tree, builtin_token);
if (mem.eql(u8, builtin_name, "@byteOffsetOf")) {
try ais.writer().writeAll("@offsetOf");
} else {
try renderToken(ais, tree, builtin_token, .none); // @name
}
if (params.len == 0) {
try renderToken(ais, tree, builtin_token + 1, .none); // (
return renderToken(ais, tree, builtin_token + 2, space); // )
}
const last_param = params[params.len - 1];
const after_last_param_token = tree.lastToken(last_param) + 1;
if (token_tags[after_last_param_token] != .comma) {
// Render all on one line, no trailing comma.
try renderToken(ais, tree, builtin_token + 1, .none); // (
for (params) |param_node, i| {
const first_param_token = tree.firstToken(param_node);
if (token_tags[first_param_token] == .multiline_string_literal_line or
hasSameLineComment(tree, first_param_token - 1))
{
ais.pushIndentOneShot();
}
try renderExpression(gpa, ais, tree, param_node, .none);
if (i + 1 < params.len) {
const comma_token = tree.lastToken(param_node) + 1;
try renderToken(ais, tree, comma_token, .space); // ,
}
}
return renderToken(ais, tree, after_last_param_token, space); // )
} else {
// Render one param per line.
ais.pushIndent();
try renderToken(ais, tree, builtin_token + 1, Space.newline); // (
for (params) |param_node| {
try renderExpression(gpa, ais, tree, param_node, .comma);
}
ais.popIndent();
return renderToken(ais, tree, after_last_param_token + 1, space); // )
}
}
fn renderFnProto(gpa: *Allocator, ais: *Ais, tree: ast.Tree, fn_proto: ast.full.FnProto, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const token_starts = tree.tokens.items(.start);
const after_fn_token = fn_proto.ast.fn_token + 1;
const lparen = if (token_tags[after_fn_token] == .identifier) blk: {
try renderToken(ais, tree, fn_proto.ast.fn_token, .space); // fn
try renderToken(ais, tree, after_fn_token, .none); // name
break :blk after_fn_token + 1;
} else blk: {
try renderToken(ais, tree, fn_proto.ast.fn_token, .space); // fn
break :blk fn_proto.ast.fn_token + 1;
};
assert(token_tags[lparen] == .l_paren);
const maybe_bang = tree.firstToken(fn_proto.ast.return_type) - 1;
const rparen = blk: {
// These may appear in any order, so we have to check the token_starts array
// to find out which is first.
var rparen = if (token_tags[maybe_bang] == .bang) maybe_bang - 1 else maybe_bang;
var smallest_start = token_starts[maybe_bang];
if (fn_proto.ast.align_expr != 0) {
const tok = tree.firstToken(fn_proto.ast.align_expr) - 3;
const start = token_starts[tok];
if (start < smallest_start) {
rparen = tok;
smallest_start = start;
}
}
if (fn_proto.ast.section_expr != 0) {
const tok = tree.firstToken(fn_proto.ast.section_expr) - 3;
const start = token_starts[tok];
if (start < smallest_start) {
rparen = tok;
smallest_start = start;
}
}
if (fn_proto.ast.callconv_expr != 0) {
const tok = tree.firstToken(fn_proto.ast.callconv_expr) - 3;
const start = token_starts[tok];
if (start < smallest_start) {
rparen = tok;
smallest_start = start;
}
}
break :blk rparen;
};
assert(token_tags[rparen] == .r_paren);
// The params list is a sparse set that does *not* include anytype or ... parameters.
const trailing_comma = token_tags[rparen - 1] == .comma;
if (!trailing_comma and !hasComment(tree, lparen, rparen)) {
// Render all on one line, no trailing comma.
try renderToken(ais, tree, lparen, .none); // (
var param_i: usize = 0;
var last_param_token = lparen;
while (true) {
last_param_token += 1;
switch (token_tags[last_param_token]) {
.doc_comment => {
try renderToken(ais, tree, last_param_token, .newline);
continue;
},
.ellipsis3 => {
try renderToken(ais, tree, last_param_token, .none); // ...
break;
},
.keyword_noalias, .keyword_comptime => {
try renderToken(ais, tree, last_param_token, .space);
last_param_token += 1;
},
.identifier => {},
.keyword_anytype => {
try renderToken(ais, tree, last_param_token, .none); // anytype
continue;
},
.r_paren => break,
.comma => {
try renderToken(ais, tree, last_param_token, .space); // ,
continue;
},
else => {}, // Parameter type without a name.
}
if (token_tags[last_param_token] == .identifier and
token_tags[last_param_token + 1] == .colon)
{
try renderToken(ais, tree, last_param_token, .none); // name
last_param_token += 1;
try renderToken(ais, tree, last_param_token, .space); // :
last_param_token += 1;
}
if (token_tags[last_param_token] == .keyword_anytype) {
try renderToken(ais, tree, last_param_token, .none); // anytype
continue;
}
const param = fn_proto.ast.params[param_i];
param_i += 1;
try renderExpression(gpa, ais, tree, param, .none);
last_param_token = tree.lastToken(param);
}
} else {
// One param per line.
ais.pushIndent();
try renderToken(ais, tree, lparen, .newline); // (
var param_i: usize = 0;
var last_param_token = lparen;
while (true) {
last_param_token += 1;
switch (token_tags[last_param_token]) {
.doc_comment => {
try renderToken(ais, tree, last_param_token, .newline);
continue;
},
.ellipsis3 => {
try renderToken(ais, tree, last_param_token, .comma); // ...
break;
},
.keyword_noalias, .keyword_comptime => {
try renderToken(ais, tree, last_param_token, .space);
last_param_token += 1;
},
.identifier => {},
.keyword_anytype => {
try renderToken(ais, tree, last_param_token, .comma); // anytype
if (token_tags[last_param_token + 1] == .comma)
last_param_token += 1;
continue;
},
.r_paren => break,
else => {}, // Parameter type without a name.
}
if (token_tags[last_param_token] == .identifier and
token_tags[last_param_token + 1] == .colon)
{
try renderToken(ais, tree, last_param_token, .none); // name
last_param_token += 1;
try renderToken(ais, tree, last_param_token, .space); // :
last_param_token += 1;
}
if (token_tags[last_param_token] == .keyword_anytype) {
try renderToken(ais, tree, last_param_token, .comma); // anytype
if (token_tags[last_param_token + 1] == .comma)
last_param_token += 1;
continue;
}
const param = fn_proto.ast.params[param_i];
param_i += 1;
try renderExpression(gpa, ais, tree, param, .comma);
last_param_token = tree.lastToken(param);
if (token_tags[last_param_token + 1] == .comma) last_param_token += 1;
}
ais.popIndent();
}
try renderToken(ais, tree, rparen, .space); // )
if (fn_proto.ast.align_expr != 0) {
const align_lparen = tree.firstToken(fn_proto.ast.align_expr) - 1;
const align_rparen = tree.lastToken(fn_proto.ast.align_expr) + 1;
try renderToken(ais, tree, align_lparen - 1, .none); // align
try renderToken(ais, tree, align_lparen, .none); // (
try renderExpression(gpa, ais, tree, fn_proto.ast.align_expr, .none);
try renderToken(ais, tree, align_rparen, .space); // )
}
if (fn_proto.ast.section_expr != 0) {
const section_lparen = tree.firstToken(fn_proto.ast.section_expr) - 1;
const section_rparen = tree.lastToken(fn_proto.ast.section_expr) + 1;
try renderToken(ais, tree, section_lparen - 1, .none); // section
try renderToken(ais, tree, section_lparen, .none); // (
try renderExpression(gpa, ais, tree, fn_proto.ast.section_expr, .none);
try renderToken(ais, tree, section_rparen, .space); // )
}
if (fn_proto.ast.callconv_expr != 0 and
!mem.eql(u8, "Inline", tree.tokenSlice(tree.nodes.items(.main_token)[fn_proto.ast.callconv_expr])))
{
const callconv_lparen = tree.firstToken(fn_proto.ast.callconv_expr) - 1;
const callconv_rparen = tree.lastToken(fn_proto.ast.callconv_expr) + 1;
try renderToken(ais, tree, callconv_lparen - 1, .none); // callconv
try renderToken(ais, tree, callconv_lparen, .none); // (
try renderExpression(gpa, ais, tree, fn_proto.ast.callconv_expr, .none);
try renderToken(ais, tree, callconv_rparen, .space); // )
}
if (token_tags[maybe_bang] == .bang) {
try renderToken(ais, tree, maybe_bang, .none); // !
}
return renderExpression(gpa, ais, tree, fn_proto.ast.return_type, space);
}
fn renderSwitchCase(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
switch_case: ast.full.SwitchCase,
space: Space,
) Error!void {
const node_tags = tree.nodes.items(.tag);
const token_tags = tree.tokens.items(.tag);
const trailing_comma = token_tags[switch_case.ast.arrow_token - 1] == .comma;
// Render everything before the arrow
if (switch_case.ast.values.len == 0) {
try renderToken(ais, tree, switch_case.ast.arrow_token - 1, .space); // else keyword
} else if (switch_case.ast.values.len == 1) {
// render on one line and drop the trailing comma if any
try renderExpression(gpa, ais, tree, switch_case.ast.values[0], .space);
} else if (trailing_comma or
hasComment(tree, tree.firstToken(switch_case.ast.values[0]), switch_case.ast.arrow_token))
{
// Render each value on a new line
try renderExpressions(gpa, ais, tree, switch_case.ast.values, .comma);
} else {
// Render on one line
for (switch_case.ast.values) |value_expr| {
try renderExpression(gpa, ais, tree, value_expr, .comma_space);
}
}
// Render the arrow and everything after it
const pre_target_space = if (node_tags[switch_case.ast.target_expr] == .multiline_string_literal)
// Newline gets inserted when rendering the target expr.
Space.none
else
Space.space;
const after_arrow_space: Space = if (switch_case.payload_token == null) pre_target_space else .space;
try renderToken(ais, tree, switch_case.ast.arrow_token, after_arrow_space);
if (switch_case.payload_token) |payload_token| {
try renderToken(ais, tree, payload_token - 1, .none); // pipe
if (token_tags[payload_token] == .asterisk) {
try renderToken(ais, tree, payload_token, .none); // asterisk
try renderToken(ais, tree, payload_token + 1, .none); // identifier
try renderToken(ais, tree, payload_token + 2, pre_target_space); // pipe
} else {
try renderToken(ais, tree, payload_token, .none); // identifier
try renderToken(ais, tree, payload_token + 1, pre_target_space); // pipe
}
}
try renderExpression(gpa, ais, tree, switch_case.ast.target_expr, space);
}
fn renderBlock(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
block_node: ast.Node.Index,
statements: []const ast.Node.Index,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
const node_tags = tree.nodes.items(.tag);
const lbrace = tree.nodes.items(.main_token)[block_node];
if (token_tags[lbrace - 1] == .colon and
token_tags[lbrace - 2] == .identifier)
{
try renderToken(ais, tree, lbrace - 2, .none);
try renderToken(ais, tree, lbrace - 1, .space);
}
ais.pushIndentNextLine();
if (statements.len == 0) {
try renderToken(ais, tree, lbrace, .none);
} else {
try renderToken(ais, tree, lbrace, .newline);
for (statements) |stmt, i| {
if (i != 0) try renderExtraNewline(ais, tree, stmt);
switch (node_tags[stmt]) {
.global_var_decl => try renderVarDecl(gpa, ais, tree, tree.globalVarDecl(stmt)),
.local_var_decl => try renderVarDecl(gpa, ais, tree, tree.localVarDecl(stmt)),
.simple_var_decl => try renderVarDecl(gpa, ais, tree, tree.simpleVarDecl(stmt)),
.aligned_var_decl => try renderVarDecl(gpa, ais, tree, tree.alignedVarDecl(stmt)),
else => try renderExpression(gpa, ais, tree, stmt, .semicolon),
}
}
}
ais.popIndent();
try renderToken(ais, tree, tree.lastToken(block_node), space); // rbrace
}
fn renderStructInit(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
struct_node: ast.Node.Index,
struct_init: ast.full.StructInit,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
if (struct_init.ast.type_expr == 0) {
try renderToken(ais, tree, struct_init.ast.lbrace - 1, .none); // .
} else {
try renderExpression(gpa, ais, tree, struct_init.ast.type_expr, .none); // T
}
if (struct_init.ast.fields.len == 0) {
ais.pushIndentNextLine();
try renderToken(ais, tree, struct_init.ast.lbrace, .none); // lbrace
ais.popIndent();
return renderToken(ais, tree, struct_init.ast.lbrace + 1, space); // rbrace
}
const rbrace = tree.lastToken(struct_node);
const trailing_comma = token_tags[rbrace - 1] == .comma;
if (trailing_comma or hasComment(tree, struct_init.ast.lbrace, rbrace)) {
// Render one field init per line.
ais.pushIndentNextLine();
try renderToken(ais, tree, struct_init.ast.lbrace, .newline);
try renderToken(ais, tree, struct_init.ast.lbrace + 1, .none); // .
try renderToken(ais, tree, struct_init.ast.lbrace + 2, .space); // name
try renderToken(ais, tree, struct_init.ast.lbrace + 3, .space); // =
try renderExpression(gpa, ais, tree, struct_init.ast.fields[0], .comma);
for (struct_init.ast.fields[1..]) |field_init| {
const init_token = tree.firstToken(field_init);
try renderExtraNewlineToken(ais, tree, init_token - 3);
try renderToken(ais, tree, init_token - 3, .none); // .
try renderToken(ais, tree, init_token - 2, .space); // name
try renderToken(ais, tree, init_token - 1, .space); // =
try renderExpression(gpa, ais, tree, field_init, .comma);
}
ais.popIndent();
} else {
// Render all on one line, no trailing comma.
try renderToken(ais, tree, struct_init.ast.lbrace, .space);
for (struct_init.ast.fields) |field_init| {
const init_token = tree.firstToken(field_init);
try renderToken(ais, tree, init_token - 3, .none); // .
try renderToken(ais, tree, init_token - 2, .space); // name
try renderToken(ais, tree, init_token - 1, .space); // =
try renderExpression(gpa, ais, tree, field_init, .comma_space);
}
}
return renderToken(ais, tree, rbrace, space);
}
fn renderArrayInit(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
array_init: ast.full.ArrayInit,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
if (array_init.ast.type_expr == 0) {
try renderToken(ais, tree, array_init.ast.lbrace - 1, .none); // .
} else {
try renderExpression(gpa, ais, tree, array_init.ast.type_expr, .none); // T
}
if (array_init.ast.elements.len == 0) {
ais.pushIndentNextLine();
try renderToken(ais, tree, array_init.ast.lbrace, .none); // lbrace
ais.popIndent();
return renderToken(ais, tree, array_init.ast.lbrace + 1, space); // rbrace
}
const last_elem = array_init.ast.elements[array_init.ast.elements.len - 1];
const last_elem_token = tree.lastToken(last_elem);
const trailing_comma = token_tags[last_elem_token + 1] == .comma;
const rbrace = if (trailing_comma) last_elem_token + 2 else last_elem_token + 1;
assert(token_tags[rbrace] == .r_brace);
if (array_init.ast.elements.len == 1) {
const only_elem = array_init.ast.elements[0];
const first_token = tree.firstToken(only_elem);
if (token_tags[first_token] != .multiline_string_literal_line and
!anythingBetween(tree, last_elem_token, rbrace))
{
try renderToken(ais, tree, array_init.ast.lbrace, .none);
try renderExpression(gpa, ais, tree, only_elem, .none);
return renderToken(ais, tree, rbrace, space);
}
}
const contains_comment = hasComment(tree, array_init.ast.lbrace, rbrace);
const contains_multiline_string = hasMultilineString(tree, array_init.ast.lbrace, rbrace);
if (!trailing_comma and !contains_comment and !contains_multiline_string) {
// Render all on one line, no trailing comma.
if (array_init.ast.elements.len == 1) {
// If there is only one element, we don't use spaces
try renderToken(ais, tree, array_init.ast.lbrace, .none);
try renderExpression(gpa, ais, tree, array_init.ast.elements[0], .none);
} else {
try renderToken(ais, tree, array_init.ast.lbrace, .space);
for (array_init.ast.elements) |elem| {
try renderExpression(gpa, ais, tree, elem, .comma_space);
}
}
return renderToken(ais, tree, last_elem_token + 1, space); // rbrace
}
ais.pushIndentNextLine();
try renderToken(ais, tree, array_init.ast.lbrace, .newline);
var expr_index: usize = 0;
while (true) {
const row_size = rowSize(tree, array_init.ast.elements[expr_index..], rbrace);
const row_exprs = array_init.ast.elements[expr_index..];
// A place to store the width of each expression and its column's maximum
const widths = try gpa.alloc(usize, row_exprs.len + row_size);
defer gpa.free(widths);
mem.set(usize, widths, 0);
const expr_newlines = try gpa.alloc(bool, row_exprs.len);
defer gpa.free(expr_newlines);
mem.set(bool, expr_newlines, false);
const expr_widths = widths[0..row_exprs.len];
const column_widths = widths[row_exprs.len..];
// Find next row with trailing comment (if any) to end the current section.
const section_end = sec_end: {
var this_line_first_expr: usize = 0;
var this_line_size = rowSize(tree, row_exprs, rbrace);
for (row_exprs) |expr, i| {
// Ignore comment on first line of this section.
if (i == 0) continue;
const expr_last_token = tree.lastToken(expr);
if (tree.tokensOnSameLine(tree.firstToken(row_exprs[0]), expr_last_token))
continue;
// Track start of line containing comment.
if (!tree.tokensOnSameLine(tree.firstToken(row_exprs[this_line_first_expr]), expr_last_token)) {
this_line_first_expr = i;
this_line_size = rowSize(tree, row_exprs[this_line_first_expr..], rbrace);
}
const maybe_comma = expr_last_token + 1;
if (token_tags[maybe_comma] == .comma) {
if (hasSameLineComment(tree, maybe_comma))
break :sec_end i - this_line_size + 1;
}
}
break :sec_end row_exprs.len;
};
expr_index += section_end;
const section_exprs = row_exprs[0..section_end];
var sub_expr_buffer = std.ArrayList(u8).init(gpa);
defer sub_expr_buffer.deinit();
var auto_indenting_stream = Ais{
.indent_delta = indent_delta,
.underlying_writer = sub_expr_buffer.writer(),
};
// Calculate size of columns in current section
var column_counter: usize = 0;
var single_line = true;
var contains_newline = false;
for (section_exprs) |expr, i| {
sub_expr_buffer.shrinkRetainingCapacity(0);
if (i + 1 < section_exprs.len) {
try renderExpression(gpa, &auto_indenting_stream, tree, expr, .none);
const width = sub_expr_buffer.items.len;
const this_contains_newline = mem.indexOfScalar(u8, sub_expr_buffer.items, '\n') != null;
contains_newline = contains_newline or this_contains_newline;
expr_widths[i] = width;
expr_newlines[i] = this_contains_newline;
if (!this_contains_newline) {
const column = column_counter % row_size;
column_widths[column] = std.math.max(column_widths[column], width);
const expr_last_token = tree.lastToken(expr) + 1;
const next_expr = section_exprs[i + 1];
column_counter += 1;
if (!tree.tokensOnSameLine(expr_last_token, tree.firstToken(next_expr))) single_line = false;
} else {
single_line = false;
column_counter = 0;
}
} else {
try renderExpression(gpa, &auto_indenting_stream, tree, expr, .none);
const width = sub_expr_buffer.items.len;
contains_newline = contains_newline or mem.indexOfScalar(u8, sub_expr_buffer.items, '\n') != null;
expr_widths[i] = width;
expr_newlines[i] = contains_newline;
if (!contains_newline) {
const column = column_counter % row_size;
column_widths[column] = std.math.max(column_widths[column], width);
}
break;
}
}
// Render exprs in current section.
column_counter = 0;
var last_col_index: usize = row_size - 1;
for (section_exprs) |expr, i| {
if (i + 1 < section_exprs.len) {
const next_expr = section_exprs[i + 1];
try renderExpression(gpa, ais, tree, expr, .none);
const comma = tree.lastToken(expr) + 1;
if (column_counter != last_col_index) {
if (!expr_newlines[i] and !expr_newlines[i + 1]) {
// Neither the current or next expression is multiline
try renderToken(ais, tree, comma, .space); // ,
assert(column_widths[column_counter % row_size] >= expr_widths[i]);
const padding = column_widths[column_counter % row_size] - expr_widths[i];
try ais.writer().writeByteNTimes(' ', padding);
column_counter += 1;
continue;
}
}
if (single_line and row_size != 1) {
try renderToken(ais, tree, comma, .space); // ,
continue;
}
column_counter = 0;
try renderToken(ais, tree, comma, .newline); // ,
try renderExtraNewline(ais, tree, next_expr);
} else {
try renderExpression(gpa, ais, tree, expr, .comma); // ,
}
}
if (expr_index == array_init.ast.elements.len)
break;
}
ais.popIndent();
return renderToken(ais, tree, rbrace, space); // rbrace
}
fn renderContainerDecl(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
container_decl_node: ast.Node.Index,
container_decl: ast.full.ContainerDecl,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
const node_tags = tree.nodes.items(.tag);
if (container_decl.layout_token) |layout_token| {
try renderToken(ais, tree, layout_token, .space);
}
var lbrace: ast.TokenIndex = undefined;
if (container_decl.ast.enum_token) |enum_token| {
try renderToken(ais, tree, container_decl.ast.main_token, .none); // union
try renderToken(ais, tree, enum_token - 1, .none); // lparen
try renderToken(ais, tree, enum_token, .none); // enum
if (container_decl.ast.arg != 0) {
try renderToken(ais, tree, enum_token + 1, .none); // lparen
try renderExpression(gpa, ais, tree, container_decl.ast.arg, .none);
const rparen = tree.lastToken(container_decl.ast.arg) + 1;
try renderToken(ais, tree, rparen, .none); // rparen
try renderToken(ais, tree, rparen + 1, .space); // rparen
lbrace = rparen + 2;
} else {
try renderToken(ais, tree, enum_token + 1, .space); // rparen
lbrace = enum_token + 2;
}
} else if (container_decl.ast.arg != 0) {
try renderToken(ais, tree, container_decl.ast.main_token, .none); // union
try renderToken(ais, tree, container_decl.ast.main_token + 1, .none); // lparen
try renderExpression(gpa, ais, tree, container_decl.ast.arg, .none);
const rparen = tree.lastToken(container_decl.ast.arg) + 1;
try renderToken(ais, tree, rparen, .space); // rparen
lbrace = rparen + 1;
} else {
try renderToken(ais, tree, container_decl.ast.main_token, .space); // union
lbrace = container_decl.ast.main_token + 1;
}
const rbrace = tree.lastToken(container_decl_node);
if (container_decl.ast.members.len == 0) {
ais.pushIndentNextLine();
if (token_tags[lbrace + 1] == .container_doc_comment) {
try renderToken(ais, tree, lbrace, .newline); // lbrace
try renderContainerDocComments(ais, tree, lbrace + 1);
} else {
try renderToken(ais, tree, lbrace, .none); // lbrace
}
ais.popIndent();
return renderToken(ais, tree, rbrace, space); // rbrace
}
const src_has_trailing_comma = token_tags[rbrace - 1] == .comma;
if (!src_has_trailing_comma) one_line: {
// We can only print all the members in-line if all the members are fields.
for (container_decl.ast.members) |member| {
if (!node_tags[member].isContainerField()) break :one_line;
}
// All the declarations on the same line.
try renderToken(ais, tree, lbrace, .space); // lbrace
for (container_decl.ast.members) |member| {
try renderMember(gpa, ais, tree, member, .space);
}
return renderToken(ais, tree, rbrace, space); // rbrace
}
// One member per line.
ais.pushIndentNextLine();
try renderToken(ais, tree, lbrace, .newline); // lbrace
if (token_tags[lbrace + 1] == .container_doc_comment) {
try renderContainerDocComments(ais, tree, lbrace + 1);
}
try renderMembers(gpa, ais, tree, container_decl.ast.members);
ais.popIndent();
return renderToken(ais, tree, rbrace, space); // rbrace
}
fn renderAsm(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
asm_node: ast.full.Asm,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
try renderToken(ais, tree, asm_node.ast.asm_token, .space); // asm
if (asm_node.volatile_token) |volatile_token| {
try renderToken(ais, tree, volatile_token, .space); // volatile
try renderToken(ais, tree, volatile_token + 1, .none); // lparen
} else {
try renderToken(ais, tree, asm_node.ast.asm_token + 1, .none); // lparen
}
if (asm_node.ast.items.len == 0) {
ais.pushIndent();
if (asm_node.first_clobber) |first_clobber| {
// asm ("foo" ::: "a", "b")
// asm ("foo" ::: "a", "b",)
try renderExpression(gpa, ais, tree, asm_node.ast.template, .space);
// Render the three colons.
try renderToken(ais, tree, first_clobber - 3, .none);
try renderToken(ais, tree, first_clobber - 2, .none);
try renderToken(ais, tree, first_clobber - 1, .space);
var tok_i = first_clobber;
while (true) : (tok_i += 1) {
try renderToken(ais, tree, tok_i, .none);
tok_i += 1;
switch (token_tags[tok_i]) {
.r_paren => {
ais.popIndent();
return renderToken(ais, tree, tok_i, space);
},
.comma => {
if (token_tags[tok_i + 1] == .r_paren) {
ais.popIndent();
return renderToken(ais, tree, tok_i + 1, space);
} else {
try renderToken(ais, tree, tok_i, .space);
}
},
else => unreachable,
}
}
} else {
// asm ("foo")
try renderExpression(gpa, ais, tree, asm_node.ast.template, .none);
ais.popIndent();
return renderToken(ais, tree, asm_node.ast.rparen, space); // rparen
}
}
ais.pushIndent();
try renderExpression(gpa, ais, tree, asm_node.ast.template, .newline);
ais.setIndentDelta(asm_indent_delta);
const colon1 = tree.lastToken(asm_node.ast.template) + 1;
const colon2 = if (asm_node.outputs.len == 0) colon2: {
try renderToken(ais, tree, colon1, .newline); // :
break :colon2 colon1 + 1;
} else colon2: {
try renderToken(ais, tree, colon1, .space); // :
ais.pushIndent();
for (asm_node.outputs) |asm_output, i| {
if (i + 1 < asm_node.outputs.len) {
const next_asm_output = asm_node.outputs[i + 1];
try renderAsmOutput(gpa, ais, tree, asm_output, .none);
const comma = tree.firstToken(next_asm_output) - 1;
try renderToken(ais, tree, comma, .newline); // ,
try renderExtraNewlineToken(ais, tree, tree.firstToken(next_asm_output));
} else if (asm_node.inputs.len == 0 and asm_node.first_clobber == null) {
try renderAsmOutput(gpa, ais, tree, asm_output, .comma);
ais.popIndent();
ais.setIndentDelta(indent_delta);
ais.popIndent();
return renderToken(ais, tree, asm_node.ast.rparen, space); // rparen
} else {
try renderAsmOutput(gpa, ais, tree, asm_output, .comma);
const comma_or_colon = tree.lastToken(asm_output) + 1;
ais.popIndent();
break :colon2 switch (token_tags[comma_or_colon]) {
.comma => comma_or_colon + 1,
else => comma_or_colon,
};
}
} else unreachable;
};
const colon3 = if (asm_node.inputs.len == 0) colon3: {
try renderToken(ais, tree, colon2, .newline); // :
break :colon3 colon2 + 1;
} else colon3: {
try renderToken(ais, tree, colon2, .space); // :
ais.pushIndent();
for (asm_node.inputs) |asm_input, i| {
if (i + 1 < asm_node.inputs.len) {
const next_asm_input = asm_node.inputs[i + 1];
try renderAsmInput(gpa, ais, tree, asm_input, .none);
const first_token = tree.firstToken(next_asm_input);
try renderToken(ais, tree, first_token - 1, .newline); // ,
try renderExtraNewlineToken(ais, tree, first_token);
} else if (asm_node.first_clobber == null) {
try renderAsmInput(gpa, ais, tree, asm_input, .comma);
ais.popIndent();
ais.setIndentDelta(indent_delta);
ais.popIndent();
return renderToken(ais, tree, asm_node.ast.rparen, space); // rparen
} else {
try renderAsmInput(gpa, ais, tree, asm_input, .comma);
const comma_or_colon = tree.lastToken(asm_input) + 1;
ais.popIndent();
break :colon3 switch (token_tags[comma_or_colon]) {
.comma => comma_or_colon + 1,
else => comma_or_colon,
};
}
}
unreachable;
};
try renderToken(ais, tree, colon3, .space); // :
const first_clobber = asm_node.first_clobber.?;
var tok_i = first_clobber;
while (true) {
switch (token_tags[tok_i + 1]) {
.r_paren => {
ais.setIndentDelta(indent_delta);
ais.popIndent();
try renderToken(ais, tree, tok_i, .newline);
return renderToken(ais, tree, tok_i + 1, space);
},
.comma => {
try renderToken(ais, tree, tok_i, .none);
try renderToken(ais, tree, tok_i + 1, .space);
tok_i += 2;
},
else => unreachable,
}
} else unreachable; // TODO shouldn't need this on while(true)
}
fn renderCall(
gpa: *Allocator,
ais: *Ais,
tree: ast.Tree,
call: ast.full.Call,
space: Space,
) Error!void {
const token_tags = tree.tokens.items(.tag);
if (call.async_token) |async_token| {
try renderToken(ais, tree, async_token, .space);
}
try renderExpression(gpa, ais, tree, call.ast.fn_expr, .none);
const lparen = call.ast.lparen;
const params = call.ast.params;
if (params.len == 0) {
ais.pushIndentNextLine();
try renderToken(ais, tree, lparen, .none);
ais.popIndent();
return renderToken(ais, tree, lparen + 1, space); // )
}
const last_param = params[params.len - 1];
const after_last_param_tok = tree.lastToken(last_param) + 1;
if (token_tags[after_last_param_tok] == .comma) {
ais.pushIndentNextLine();
try renderToken(ais, tree, lparen, .newline); // (
for (params) |param_node, i| {
if (i + 1 < params.len) {
try renderExpression(gpa, ais, tree, param_node, .none);
// Unindent the comma for multiline string literals.
const is_multiline_string =
token_tags[tree.firstToken(param_node)] == .multiline_string_literal_line;
if (is_multiline_string) ais.popIndent();
const comma = tree.lastToken(param_node) + 1;
try renderToken(ais, tree, comma, .newline); // ,
if (is_multiline_string) ais.pushIndent();
try renderExtraNewline(ais, tree, params[i + 1]);
} else {
try renderExpression(gpa, ais, tree, param_node, .comma);
}
}
ais.popIndent();
return renderToken(ais, tree, after_last_param_tok + 1, space); // )
}
try renderToken(ais, tree, lparen, .none); // (
for (params) |param_node, i| {
const first_param_token = tree.firstToken(param_node);
if (token_tags[first_param_token] == .multiline_string_literal_line or
hasSameLineComment(tree, first_param_token - 1))
{
ais.pushIndentOneShot();
}
try renderExpression(gpa, ais, tree, param_node, .none);
if (i + 1 < params.len) {
const comma = tree.lastToken(param_node) + 1;
const next_multiline_string =
token_tags[tree.firstToken(params[i + 1])] == .multiline_string_literal_line;
const comma_space: Space = if (next_multiline_string) .none else .space;
try renderToken(ais, tree, comma, comma_space);
}
}
return renderToken(ais, tree, after_last_param_tok, space); // )
}
/// Renders the given expression indented, popping the indent before rendering
/// any following line comments
fn renderExpressionIndented(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.Index, space: Space) Error!void {
const token_starts = tree.tokens.items(.start);
const token_tags = tree.tokens.items(.tag);
ais.pushIndent();
var last_token = tree.lastToken(node);
const punctuation = switch (space) {
.none, .space, .newline, .skip => false,
.comma => true,
.comma_space => token_tags[last_token + 1] == .comma,
.semicolon => token_tags[last_token + 1] == .semicolon,
};
try renderExpression(gpa, ais, tree, node, if (punctuation) .none else .skip);
switch (space) {
.none, .space, .newline, .skip => {},
.comma => {
if (token_tags[last_token + 1] == .comma) {
try renderToken(ais, tree, last_token + 1, .skip);
last_token += 1;
} else {
try ais.writer().writeByte(',');
}
},
.comma_space => if (token_tags[last_token + 1] == .comma) {
try renderToken(ais, tree, last_token + 1, .skip);
last_token += 1;
},
.semicolon => if (token_tags[last_token + 1] == .semicolon) {
try renderToken(ais, tree, last_token + 1, .skip);
last_token += 1;
},
}
ais.popIndent();
if (space == .skip) return;
const comment_start = token_starts[last_token] + tokenSliceForRender(tree, last_token).len;
const comment = try renderComments(ais, tree, comment_start, token_starts[last_token + 1]);
if (!comment) switch (space) {
.none => {},
.space,
.comma_space,
=> try ais.writer().writeByte(' '),
.newline,
.comma,
.semicolon,
=> try ais.insertNewline(),
.skip => unreachable,
};
}
/// Render an expression, and the comma that follows it, if it is present in the source.
fn renderExpressionComma(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.Index, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const maybe_comma = tree.lastToken(node) + 1;
if (token_tags[maybe_comma] == .comma) {
try renderExpression(gpa, ais, tree, node, .none);
return renderToken(ais, tree, maybe_comma, space);
} else {
return renderExpression(gpa, ais, tree, node, space);
}
}
fn renderTokenComma(ais: *Ais, tree: ast.Tree, token: ast.TokenIndex, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const maybe_comma = token + 1;
if (token_tags[maybe_comma] == .comma) {
try renderToken(ais, tree, token, .none);
return renderToken(ais, tree, maybe_comma, space);
} else {
return renderToken(ais, tree, token, space);
}
}
const Space = enum {
/// Output the token lexeme only.
none,
/// Output the token lexeme followed by a single space.
space,
/// Output the token lexeme followed by a newline.
newline,
/// If the next token is a comma, render it as well. If not, insert one.
/// In either case, a newline will be inserted afterwards.
comma,
/// Additionally consume the next token if it is a comma.
/// In either case, a space will be inserted afterwards.
comma_space,
/// Additionally consume the next token if it is a semicolon.
/// In either case, a newline will be inserted afterwards.
semicolon,
/// Skip rendering whitespace and comments. If this is used, the caller
/// *must* handle handle whitespace and comments manually.
skip,
};
fn renderToken(ais: *Ais, tree: ast.Tree, token_index: ast.TokenIndex, space: Space) Error!void {
const token_tags = tree.tokens.items(.tag);
const token_starts = tree.tokens.items(.start);
const token_start = token_starts[token_index];
const lexeme = tokenSliceForRender(tree, token_index);
try ais.writer().writeAll(lexeme);
if (space == .skip) return;
if (space == .comma and token_tags[token_index + 1] != .comma) {
try ais.writer().writeByte(',');
}
const comment = try renderComments(ais, tree, token_start + lexeme.len, token_starts[token_index + 1]);
switch (space) {
.none => {},
.space => if (!comment) try ais.writer().writeByte(' '),
.newline => if (!comment) try ais.insertNewline(),
.comma => if (token_tags[token_index + 1] == .comma) {
try renderToken(ais, tree, token_index + 1, .newline);
} else if (!comment) {
try ais.insertNewline();
},
.comma_space => if (token_tags[token_index + 1] == .comma) {
try renderToken(ais, tree, token_index + 1, .space);
} else if (!comment) {
try ais.writer().writeByte(' ');
},
.semicolon => if (token_tags[token_index + 1] == .semicolon) {
try renderToken(ais, tree, token_index + 1, .newline);
} else if (!comment) {
try ais.insertNewline();
},
.skip => unreachable,
}
}
/// Returns true if there exists a comment between any of the tokens from
/// `start_token` to `end_token`. This is used to determine if e.g. a
/// fn_proto should be wrapped and have a trailing comma inserted even if
/// there is none in the source.
fn hasComment(tree: ast.Tree, start_token: ast.TokenIndex, end_token: ast.TokenIndex) bool {
const token_starts = tree.tokens.items(.start);
var i = start_token;
while (i < end_token) : (i += 1) {
const start = token_starts[i] + tree.tokenSlice(i).len;
const end = token_starts[i + 1];
if (mem.indexOf(u8, tree.source[start..end], "//") != null) return true;
}
return false;
}
/// Returns true if there exists a multiline string literal between the start
/// of token `start_token` and the start of token `end_token`.
fn hasMultilineString(tree: ast.Tree, start_token: ast.TokenIndex, end_token: ast.TokenIndex) bool {
const token_tags = tree.tokens.items(.tag);
for (token_tags[start_token..end_token]) |tag| {
switch (tag) {
.multiline_string_literal_line => return true,
else => continue,
}
}
return false;
}
/// Assumes that start is the first byte past the previous token and
/// that end is the last byte before the next token.
fn renderComments(ais: *Ais, tree: ast.Tree, start: usize, end: usize) Error!bool {
var index: usize = start;
while (mem.indexOf(u8, tree.source[index..end], "//")) |offset| {
const comment_start = index + offset;
// If there is no newline, the comment ends with EOF
const newline_index = mem.indexOfScalar(u8, tree.source[comment_start..end], '\n');
const newline = if (newline_index) |i| comment_start + i else null;
const untrimmed_comment = tree.source[comment_start .. newline orelse tree.source.len];
const trimmed_comment = mem.trimRight(u8, untrimmed_comment, &std.ascii.spaces);
// Don't leave any whitespace at the start of the file
if (index != 0) {
if (index == start and mem.containsAtLeast(u8, tree.source[index..comment_start], 2, "\n")) {
// Leave up to one empty line before the first comment
try ais.insertNewline();
try ais.insertNewline();
} else if (mem.indexOfScalar(u8, tree.source[index..comment_start], '\n') != null) {
// Respect the newline directly before the comment.
// Note: This allows an empty line between comments
try ais.insertNewline();
} else if (index == start) {
// Otherwise if the first comment is on the same line as
// the token before it, prefix it with a single space.
try ais.writer().writeByte(' ');
}
}
index = 1 + (newline orelse end - 1);
const comment_content = mem.trimLeft(u8, trimmed_comment["//".len..], &std.ascii.spaces);
if (ais.disabled_offset != null and mem.eql(u8, comment_content, "zig fmt: on")) {
// Write the source for which formatting was disabled directly
// to the underlying writer, fixing up invaild whitespace.
const disabled_source = tree.source[ais.disabled_offset.?..comment_start];
try writeFixingWhitespace(ais.underlying_writer, disabled_source);
// Write with the canonical single space.
try ais.underlying_writer.writeAll("// zig fmt: on\n");
ais.disabled_offset = null;
} else if (ais.disabled_offset == null and mem.eql(u8, comment_content, "zig fmt: off")) {
// Write with the canonical single space.
try ais.writer().writeAll("// zig fmt: off\n");
ais.disabled_offset = index;
} else {
// Write the comment minus trailing whitespace.
try ais.writer().print("{s}\n", .{trimmed_comment});
}
}
if (index != start and mem.containsAtLeast(u8, tree.source[index - 1 .. end], 2, "\n")) {
try ais.insertNewline();
}
return index != start;
}
fn renderExtraNewline(ais: *Ais, tree: ast.Tree, node: ast.Node.Index) Error!void {
return renderExtraNewlineToken(ais, tree, tree.firstToken(node));
}
/// Check if there is an empty line immediately before the given token. If so, render it.
fn renderExtraNewlineToken(ais: *Ais, tree: ast.Tree, token_index: ast.TokenIndex) Error!void {
const token_starts = tree.tokens.items(.start);
const token_start = token_starts[token_index];
if (token_start == 0) return;
const prev_token_end = if (token_index == 0)
0
else
token_starts[token_index - 1] + tokenSliceForRender(tree, token_index - 1).len;
// If there is a comment present, it will handle the empty line
if (mem.indexOf(u8, tree.source[prev_token_end..token_start], "//") != null) return;
// Iterate backwards to the end of the previous token, stopping if a
// non-whitespace character is encountered or two newlines have been found.
var i = token_start - 1;
var newlines: u2 = 0;
while (std.ascii.isSpace(tree.source[i])) : (i -= 1) {
if (tree.source[i] == '\n') newlines += 1;
if (newlines == 2) return ais.insertNewline();
if (i == prev_token_end) break;
}
}
/// end_token is the token one past the last doc comment token. This function
/// searches backwards from there.
fn renderDocComments(ais: *Ais, tree: ast.Tree, end_token: ast.TokenIndex) Error!void {
// Search backwards for the first doc comment.
const token_tags = tree.tokens.items(.tag);
if (end_token == 0) return;
var tok = end_token - 1;
while (token_tags[tok] == .doc_comment) {
if (tok == 0) break;
tok -= 1;
} else {
tok += 1;
}
const first_tok = tok;
if (first_tok == end_token) return;
try renderExtraNewlineToken(ais, tree, first_tok);
while (token_tags[tok] == .doc_comment) : (tok += 1) {
try renderToken(ais, tree, tok, .newline);
}
}
/// start_token is first container doc comment token.
fn renderContainerDocComments(ais: *Ais, tree: ast.Tree, start_token: ast.TokenIndex) Error!void {
const token_tags = tree.tokens.items(.tag);
var tok = start_token;
while (token_tags[tok] == .container_doc_comment) : (tok += 1) {
try renderToken(ais, tree, tok, .newline);
}
// Render extra newline if there is one between final container doc comment and
// the next token. If the next token is a doc comment, that code path
// will have its own logic to insert a newline.
if (token_tags[tok] != .doc_comment) {
try renderExtraNewlineToken(ais, tree, tok);
}
}
fn tokenSliceForRender(tree: ast.Tree, token_index: ast.TokenIndex) []const u8 {
var ret = tree.tokenSlice(token_index);
if (tree.tokens.items(.tag)[token_index] == .multiline_string_literal_line) {
assert(ret[ret.len - 1] == '\n');
ret.len -= 1;
}
return ret;
}
fn hasSameLineComment(tree: ast.Tree, token_index: ast.TokenIndex) bool {
const token_starts = tree.tokens.items(.start);
const between_source = tree.source[token_starts[token_index]..token_starts[token_index + 1]];
for (between_source) |byte| switch (byte) {
'\n' => return false,
'/' => return true,
else => continue,
};
return false;
}
/// Returns `true` if and only if there are any tokens or line comments between
/// start_token and end_token.
fn anythingBetween(tree: ast.Tree, start_token: ast.TokenIndex, end_token: ast.TokenIndex) bool {
if (start_token + 1 != end_token) return true;
const token_starts = tree.tokens.items(.start);
const between_source = tree.source[token_starts[start_token]..token_starts[start_token + 1]];
for (between_source) |byte| switch (byte) {
'/' => return true,
else => continue,
};
return false;
}
fn writeFixingWhitespace(writer: std.ArrayList(u8).Writer, slice: []const u8) Error!void {
for (slice) |byte| switch (byte) {
'\t' => try writer.writeAll(" " ** 4),
'\r' => {},
else => try writer.writeByte(byte),
};
}
fn nodeIsBlock(tag: ast.Node.Tag) bool {
return switch (tag) {
.block,
.block_semicolon,
.block_two,
.block_two_semicolon,
.struct_init_dot,
.struct_init_dot_comma,
.struct_init_dot_two,
.struct_init_dot_two_comma,
.array_init_dot,
.array_init_dot_comma,
.array_init_dot_two,
.array_init_dot_two_comma,
=> true,
else => false,
};
}
fn nodeIsIfForWhileSwitch(tag: ast.Node.Tag) bool {
return switch (tag) {
.@"if",
.if_simple,
.@"for",
.for_simple,
.@"while",
.while_simple,
.while_cont,
.@"switch",
.switch_comma,
=> true,
else => false,
};
}
fn nodeCausesSliceOpSpace(tag: ast.Node.Tag) bool {
return switch (tag) {
.@"catch",
.add,
.add_wrap,
.array_cat,
.array_mult,
.assign,
.assign_bit_and,
.assign_bit_or,
.assign_bit_shift_left,
.assign_bit_shift_right,
.assign_bit_xor,
.assign_div,
.assign_sub,
.assign_sub_wrap,
.assign_mod,
.assign_add,
.assign_add_wrap,
.assign_mul,
.assign_mul_wrap,
.bang_equal,
.bit_and,
.bit_or,
.bit_shift_left,
.bit_shift_right,
.bit_xor,
.bool_and,
.bool_or,
.div,
.equal_equal,
.error_union,
.greater_or_equal,
.greater_than,
.less_or_equal,
.less_than,
.merge_error_sets,
.mod,
.mul,
.mul_wrap,
.sub,
.sub_wrap,
.@"orelse",
=> true,
else => false,
};
}
// Returns the number of nodes in `expr` that are on the same line as `rtoken`.
fn rowSize(tree: ast.Tree, exprs: []const ast.Node.Index, rtoken: ast.TokenIndex) usize {
const token_tags = tree.tokens.items(.tag);
const first_token = tree.firstToken(exprs[0]);
if (tree.tokensOnSameLine(first_token, rtoken)) {
const maybe_comma = rtoken - 1;
if (token_tags[maybe_comma] == .comma)
return 1;
return exprs.len; // no newlines
}
var count: usize = 1;
for (exprs) |expr, i| {
if (i + 1 < exprs.len) {
const expr_last_token = tree.lastToken(expr) + 1;
if (!tree.tokensOnSameLine(expr_last_token, tree.firstToken(exprs[i + 1]))) return count;
count += 1;
} else {
return count;
}
}
unreachable;
}
/// Automatically inserts indentation of written data by keeping
/// track of the current indentation level
fn AutoIndentingStream(comptime UnderlyingWriter: type) type {
return struct {
const Self = @This();
pub const WriteError = UnderlyingWriter.Error;
pub const Writer = std.io.Writer(*Self, WriteError, write);
underlying_writer: UnderlyingWriter,
/// Offset into the source at which formatting has been disabled with
/// a `zig fmt: off` comment.
///
/// If non-null, the AutoIndentingStream will not write any bytes
/// to the underlying writer. It will however continue to track the
/// indentation level.
disabled_offset: ?usize = null,
indent_count: usize = 0,
indent_delta: usize,
current_line_empty: bool = true,
/// automatically popped when applied
indent_one_shot_count: usize = 0,
/// the most recently applied indent
applied_indent: usize = 0,
/// not used until the next line
indent_next_line: usize = 0,
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
pub fn write(self: *Self, bytes: []const u8) WriteError!usize {
if (bytes.len == 0)
return @as(usize, 0);
try self.applyIndent();
return self.writeNoIndent(bytes);
}
// Change the indent delta without changing the final indentation level
pub fn setIndentDelta(self: *Self, new_indent_delta: usize) void {
if (self.indent_delta == new_indent_delta) {
return;
} else if (self.indent_delta > new_indent_delta) {
assert(self.indent_delta % new_indent_delta == 0);
self.indent_count = self.indent_count * (self.indent_delta / new_indent_delta);
} else {
// assert that the current indentation (in spaces) in a multiple of the new delta
assert((self.indent_count * self.indent_delta) % new_indent_delta == 0);
self.indent_count = self.indent_count / (new_indent_delta / self.indent_delta);
}
self.indent_delta = new_indent_delta;
}
fn writeNoIndent(self: *Self, bytes: []const u8) WriteError!usize {
if (bytes.len == 0)
return @as(usize, 0);
if (self.disabled_offset == null) try self.underlying_writer.writeAll(bytes);
if (bytes[bytes.len - 1] == '\n')
self.resetLine();
return bytes.len;
}
pub fn insertNewline(self: *Self) WriteError!void {
_ = try self.writeNoIndent("\n");
}
fn resetLine(self: *Self) void {
self.current_line_empty = true;
self.indent_next_line = 0;
}
/// Insert a newline unless the current line is blank
pub fn maybeInsertNewline(self: *Self) WriteError!void {
if (!self.current_line_empty)
try self.insertNewline();
}
/// Push default indentation
/// Doesn't actually write any indentation.
/// Just primes the stream to be able to write the correct indentation if it needs to.
pub fn pushIndent(self: *Self) void {
self.indent_count += 1;
}
/// Push an indent that is automatically popped after being applied
pub fn pushIndentOneShot(self: *Self) void {
self.indent_one_shot_count += 1;
self.pushIndent();
}
/// Turns all one-shot indents into regular indents
/// Returns number of indents that must now be manually popped
pub fn lockOneShotIndent(self: *Self) usize {
var locked_count = self.indent_one_shot_count;
self.indent_one_shot_count = 0;
return locked_count;
}
/// Push an indent that should not take effect until the next line
pub fn pushIndentNextLine(self: *Self) void {
self.indent_next_line += 1;
self.pushIndent();
}
pub fn popIndent(self: *Self) void {
assert(self.indent_count != 0);
self.indent_count -= 1;
if (self.indent_next_line > 0)
self.indent_next_line -= 1;
}
/// Writes ' ' bytes if the current line is empty
fn applyIndent(self: *Self) WriteError!void {
const current_indent = self.currentIndent();
if (self.current_line_empty and current_indent > 0) {
if (self.disabled_offset == null) {
try self.underlying_writer.writeByteNTimes(' ', current_indent);
}
self.applied_indent = current_indent;
}
self.indent_count -= self.indent_one_shot_count;
self.indent_one_shot_count = 0;
self.current_line_empty = false;
}
/// Checks to see if the most recent indentation exceeds the currently pushed indents
pub fn isLineOverIndented(self: *Self) bool {
if (self.current_line_empty) return false;
return self.applied_indent > self.currentIndent();
}
fn currentIndent(self: *Self) usize {
var indent_current: usize = 0;
if (self.indent_count > 0) {
const indent_count = self.indent_count - self.indent_next_line;
indent_current = indent_count * self.indent_delta;
}
return indent_current;
}
};
}
|
lib/std/zig/render.zig
|
const std = @import("std");
const testing = std.testing;
const process = std.process;
const fs = std.fs;
const ChildProcess = std.ChildProcess;
var a: *std.mem.Allocator = undefined;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var arg_it = process.args();
// skip my own exe name
_ = arg_it.skip();
a = &arena.allocator;
const zig_exe_rel = try (arg_it.next(a) orelse {
std.debug.warn("Expected first argument to be path to zig compiler\n", .{});
return error.InvalidArgs;
});
const cache_root = try (arg_it.next(a) orelse {
std.debug.warn("Expected second argument to be cache root directory path\n", .{});
return error.InvalidArgs;
});
const zig_exe = try fs.path.resolve(a, &[_][]const u8{zig_exe_rel});
const dir_path = try fs.path.join(a, &[_][]const u8{ cache_root, "clitest" });
defer fs.cwd().deleteTree(dir_path) catch {};
const TestFn = fn ([]const u8, []const u8) anyerror!void;
const test_fns = [_]TestFn{
testZigInitLib,
testZigInitExe,
testGodboltApi,
testMissingOutputPath,
testZigFmt,
};
for (test_fns) |testFn| {
try fs.cwd().deleteTree(dir_path);
try fs.cwd().makeDir(dir_path);
try testFn(zig_exe, dir_path);
}
}
fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 {
return arg catch |err| {
warn("Unable to parse command line: {}\n", .{err});
return err;
};
}
fn printCmd(cwd: []const u8, argv: []const []const u8) void {
std.debug.warn("cd {s} && ", .{cwd});
for (argv) |arg| {
std.debug.warn("{s} ", .{arg});
}
std.debug.warn("\n", .{});
}
fn exec(cwd: []const u8, expect_0: bool, argv: []const []const u8) !ChildProcess.ExecResult {
const max_output_size = 100 * 1024;
const result = ChildProcess.exec(.{
.allocator = a,
.argv = argv,
.cwd = cwd,
.max_output_bytes = max_output_size,
}) catch |err| {
std.debug.warn("The following command failed:\n", .{});
printCmd(cwd, argv);
return err;
};
switch (result.term) {
.Exited => |code| {
if ((code != 0) == expect_0) {
std.debug.warn("The following command exited with error code {}:\n", .{code});
printCmd(cwd, argv);
std.debug.warn("stderr:\n{s}\n", .{result.stderr});
return error.CommandFailed;
}
},
else => {
std.debug.warn("The following command terminated unexpectedly:\n", .{});
printCmd(cwd, argv);
std.debug.warn("stderr:\n{s}\n", .{result.stderr});
return error.CommandFailed;
},
}
return result;
}
fn testZigInitLib(zig_exe: []const u8, dir_path: []const u8) !void {
_ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-lib" });
const test_result = try exec(dir_path, true, &[_][]const u8{ zig_exe, "build", "test" });
try testing.expectStringEndsWith(test_result.stderr, "All 1 tests passed.\n");
}
fn testZigInitExe(zig_exe: []const u8, dir_path: []const u8) !void {
_ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-exe" });
const run_result = try exec(dir_path, true, &[_][]const u8{ zig_exe, "build", "run" });
try testing.expectEqualStrings("info: All your codebase are belong to us.\n", run_result.stderr);
}
fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {
if (std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64) return;
const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" });
const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" });
try fs.cwd().writeFile(example_zig_path,
\\// Type your code here, or load an example.
\\export fn square(num: i32) i32 {
\\ return num * num;
\\}
\\extern fn zig_panic() noreturn;
\\pub fn panic(msg: []const u8, error_return_trace: ?*@import("builtin").StackTrace) noreturn {
\\ zig_panic();
\\}
);
var args = std.ArrayList([]const u8).init(a);
try args.appendSlice(&[_][]const u8{
zig_exe, "build-obj",
"--cache-dir", dir_path,
"--name", "example",
"-fno-emit-bin", "-fno-emit-h",
"--strip", "-OReleaseFast",
example_zig_path,
});
const emit_asm_arg = try std.fmt.allocPrint(a, "-femit-asm={s}", .{example_s_path});
try args.append(emit_asm_arg);
_ = try exec(dir_path, true, args.items);
const out_asm = try std.fs.cwd().readFileAlloc(a, example_s_path, std.math.maxInt(usize));
try testing.expect(std.mem.indexOf(u8, out_asm, "square:") != null);
try testing.expect(std.mem.indexOf(u8, out_asm, "mov\teax, edi") != null);
try testing.expect(std.mem.indexOf(u8, out_asm, "imul\teax, edi") != null);
}
fn testMissingOutputPath(zig_exe: []const u8, dir_path: []const u8) !void {
_ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-exe" });
const output_path = try fs.path.join(a, &[_][]const u8{ "does", "not", "exist", "foo.exe" });
const output_arg = try std.fmt.allocPrint(a, "-femit-bin={s}", .{output_path});
const source_path = try fs.path.join(a, &[_][]const u8{ "src", "main.zig" });
const result = try exec(dir_path, false, &[_][]const u8{ zig_exe, "build-exe", source_path, output_arg });
const s = std.fs.path.sep_str;
const expected: []const u8 = "error: unable to open output directory 'does" ++ s ++ "not" ++ s ++ "exist': FileNotFound\n";
try testing.expectEqualStrings(expected, result.stderr);
}
fn testZigFmt(zig_exe: []const u8, dir_path: []const u8) !void {
_ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-exe" });
const unformatted_code = " // no reason for indent";
const fmt1_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "fmt1.zig" });
try fs.cwd().writeFile(fmt1_zig_path, unformatted_code);
const run_result1 = try exec(dir_path, true, &[_][]const u8{ zig_exe, "fmt", fmt1_zig_path });
// stderr should be file path + \n
try testing.expect(std.mem.startsWith(u8, run_result1.stdout, fmt1_zig_path));
try testing.expect(run_result1.stdout.len == fmt1_zig_path.len + 1 and run_result1.stdout[run_result1.stdout.len - 1] == '\n');
const fmt2_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "fmt2.zig" });
try fs.cwd().writeFile(fmt2_zig_path, unformatted_code);
const run_result2 = try exec(dir_path, true, &[_][]const u8{ zig_exe, "fmt", dir_path });
// running it on the dir, only the new file should be changed
try testing.expect(std.mem.startsWith(u8, run_result2.stdout, fmt2_zig_path));
try testing.expect(run_result2.stdout.len == fmt2_zig_path.len + 1 and run_result2.stdout[run_result2.stdout.len - 1] == '\n');
const run_result3 = try exec(dir_path, true, &[_][]const u8{ zig_exe, "fmt", dir_path });
// both files have been formatted, nothing should change now
try testing.expect(run_result3.stdout.len == 0);
// Check UTF-16 decoding
const fmt4_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "fmt4.zig" });
var unformatted_code_utf16 = "\xff\xfe \x00 \x00 \x00 \x00/\x00/\x00 \x00n\x00o\x00 \x00r\x00e\x00a\x00s\x00o\x00n\x00";
try fs.cwd().writeFile(fmt4_zig_path, unformatted_code_utf16);
const run_result4 = try exec(dir_path, true, &[_][]const u8{ zig_exe, "fmt", dir_path });
try testing.expect(std.mem.startsWith(u8, run_result4.stdout, fmt4_zig_path));
try testing.expect(run_result4.stdout.len == fmt4_zig_path.len + 1 and run_result4.stdout[run_result4.stdout.len - 1] == '\n');
}
|
test/cli.zig
|
const std = @import("std");
const sqlite = @import("sqlite");
pub const AWTFDB_BLAKE3_CONTEXT = "awtfdb Sun Mar 20 16:58:11 AM +00 2022 main hash key";
const HELPTEXT =
\\ awtfdb-manage: main program for awtfdb file management
\\
\\ usage:
\\ awtfdb-manage [global options..] <action> [action options...]
\\
\\ global options:
\\ -h prints this help and exits
\\ -V prints version and exits
\\ -v turns on verbosity (debug logging)
\\
\\ creating an awtfdb index file:
\\ awtfdb-manage create
\\
\\ migrating to new versions:
\\ awtfdb-manage migrate
\\
\\ getting statistics:
\\ awtfdb-manage stats
\\
\\ current running jobs:
\\ awtfdb-manage jobs
;
const MIGRATIONS = .{
.{
1, "initial table",
\\ -- we optimize table size by storing hashes in a dedicated table
\\ -- and then only using the int id (which is more efficiency) for
\\ -- references into other tables
\\ create table hashes (
\\ id integer primary key,
\\ hash_data blob
\\ constraint hashes_length check (length(hash_data) == 32)
\\ constraint hashes_unique unique
\\ ) strict;
\\
\\ -- uniquely identifies a tag in the ENTIRE UNIVERSE!!!
\\ -- since this uses random data for core_data, and core_hash is blake3
\\ --
\\ -- this is not randomly generated UUIDs, of which anyone can cook up 128-bit
\\ -- numbers out of thin air. using a cryptographic hash function lets us be
\\ -- sure that we have an universal tag for 'new york' or 'tree', while also
\\ -- enabling different language representations of the same tag
\\ -- (since they all reference the core!)
\\ create table tag_cores (
\\ core_hash int
\\ constraint tag_cores_hash_fk references hashes (id) on delete restrict
\\ constraint tag_cores_pk primary key,
\\ core_data blob not null
\\ ) strict;
\\
\\ -- files that are imported into the index are here
\\ -- this is how we learn that a certain path means a certain hash without
\\ -- having to recalculate the hash over and over.
\\ create table files (
\\ file_hash int not null
\\ constraint files_hash_fk references hashes (id) on delete restrict,
\\ local_path text not null,
\\ constraint files_pk primary key (file_hash, local_path)
\\ ) strict;
\\
\\ -- this is the main tag<->file mapping. to find out which tags a file has,
\\ -- execute your SELECT here.
\\ create table tag_files (
\\ file_hash int not null
\\ -- not referencing files (file_hash) so that it still works
\\ constraint tag_files_file_fk references hashes (id) on delete cascade,
\\ core_hash int not null
\\ constraint tag_files_core_fk references tag_cores (core_hash) on delete cascade,
\\ constraint tag_files_pk primary key (file_hash, core_hash)
\\ ) strict;
\\
\\ -- this is the main name<->tag mapping.
\\ create table tag_names (
\\ tag_text text not null,
\\ tag_language text not null,
\\ core_hash int not null
\\ constraint tag_names_core_fk references tag_cores (core_hash) on delete cascade,
\\ constraint tag_names_pk primary key (tag_text, tag_language, core_hash)
\\ ) strict;
},
// to do the new constraint, we need to reconstruct the table.
.{
2, "fix missing unqiue constraint for local paths",
\\ create table files_local_path_constraint_fix (
\\ file_hash int not null
\\ constraint files_hash_fk references hashes (id) on delete restrict,
\\ local_path text not null
\\ constraint files_local_path_uniq unique on conflict abort,
\\ constraint files_pk primary key (file_hash, local_path)
\\ ) strict;
\\
\\ insert into files_local_path_constraint_fix select * from files;
\\ drop table files;
\\ alter table files_local_path_constraint_fix rename to files;
},
};
const MIGRATION_LOG_TABLE =
\\ create table if not exists migration_logs (
\\ version int primary key,
\\ applied_at int,
\\ description text
\\ );
;
const log = std.log.scoped(.awtfdb_main);
pub const Context = struct {
home_path: ?[]const u8 = null,
db_path: ?[]const u8 = null,
args_it: *std.process.ArgIterator,
stdout: std.fs.File,
allocator: std.mem.Allocator,
/// Always call loadDatabase before using this attribute.
db: ?sqlite.Db = null,
const Self = @This();
pub const LoadDatabaseOptions = struct {
create: bool = false,
};
pub fn loadDatabase(self: *Self, options: LoadDatabaseOptions) !void {
if (self.db != null) return;
// try to create the file always. this is done because
// i give up. tried a lot of things to make sqlite create the db file
// itself but it just hates me (SQLITE_CANTOPEN my beloathed).
if (self.db_path == null) {
self.home_path = self.home_path orelse std.os.getenv("HOME");
const resolved_path = try std.fs.path.resolve(
self.allocator,
&[_][]const u8{ self.home_path.?, "awtf.db" },
);
if (options.create) {
var file = try std.fs.cwd().createFile(resolved_path, .{ .truncate = false });
defer file.close();
} else {
try std.fs.cwd().access(resolved_path, .{});
}
self.db_path = resolved_path;
}
const db_path_cstr = try std.cstr.addNullByte(self.allocator, self.db_path.?);
defer self.allocator.free(db_path_cstr);
var diags: sqlite.Diagnostics = undefined;
self.db = try sqlite.Db.init(.{
.mode = sqlite.Db.Mode{ .File = db_path_cstr },
.open_flags = .{
.write = true,
.create = true,
},
.threading_mode = .MultiThread,
.diags = &diags,
});
// ensure our database functions work
var result = try self.db.?.one(i32, "select 123;", .{}, .{});
if (result == null or result.? != 123) {
log.err("error on test statement: expected 123, got {d}", .{result});
return error.TestStatementFailed;
}
try self.db.?.exec("PRAGMA foreign_keys = ON", .{}, .{});
}
/// Convert the current connection into an in-memory database connection
/// so that operations are done non-destructively
///
/// This function is useful for '--dry-run' switches in CLI applications.
pub fn turnIntoMemoryDb(self: *Self) !void {
// first, make sure our current connection can't do shit
try self.db.?.exec("PRAGMA query_only = ON;", .{}, .{});
// open a new one in memory
var new_db = try sqlite.Db.init(.{
.mode = sqlite.Db.Mode{ .Memory = {} },
.open_flags = .{
.write = true,
.create = true,
},
.threading_mode = .MultiThread,
});
// backup the one we have into the memory one
const maybe_backup = sqlite.c.sqlite3_backup_init(new_db.db, "main", self.db.?.db, "main");
defer if (maybe_backup) |backup| {
const result = sqlite.c.sqlite3_backup_finish(backup);
if (result != sqlite.c.SQLITE_OK) {
std.debug.panic("unexpected result code from backup finish: {d}", .{result});
}
};
if (maybe_backup) |backup| {
const result = sqlite.c.sqlite3_backup_step(backup, -1);
if (result != sqlite.c.SQLITE_DONE) {
return sqlite.errorFromResultCode(result);
}
}
// then, close the db
self.db.?.deinit();
// then, make this new db the real db
self.db = new_db;
}
pub fn deinit(self: *Self) void {
if (self.db_path) |db_path| self.allocator.free(db_path);
if (self.db) |*db| {
log.info("possibly optimizing database...", .{});
// The results of analysis are not as good when only part of each index is examined,
// but the results are usually good enough. Setting N to 100 or 1000 allows
// the ANALYZE command to run very quickly, even on multi-gigabyte database files.
_ = db.one(i64, "PRAGMA analysis_limit=1000;", .{}, .{}) catch {};
_ = db.exec("PRAGMA optimize;", .{}, .{}) catch {};
db.deinit();
}
}
pub const Blake3Hash = [std.crypto.hash.Blake3.digest_length]u8;
pub const Blake3HashHex = [std.crypto.hash.Blake3.digest_length * 2]u8;
const NamedTagValue = struct {
text: []const u8,
language: []const u8,
};
pub const Tag = struct {
core: Hash,
kind: union(enum) {
Named: NamedTagValue,
},
pub fn format(
self: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
// TODO better format logic (add switch case)
return std.fmt.format(writer, "{s}", .{self.kind.Named.text});
}
/// Deletes all the tags reffering to this core
pub fn deleteAll(self: @This(), db: *sqlite.Db) !usize {
try db.exec(
\\ delete from tag_names
\\ where core_hash = ?
,
.{},
.{self.core.id},
);
const deleted_tag_count = db.rowsAffected();
try db.exec("delete from tag_cores where core_hash = ?", .{}, .{self.core.id});
std.debug.assert(db.rowsAffected() == 1);
try db.exec("delete from hashes where id = ?", .{}, .{self.core.id});
std.debug.assert(db.rowsAffected() == 1);
return deleted_tag_count;
}
};
const OwnedTagList = struct {
allocator: std.mem.Allocator,
items: []Tag,
pub fn deinit(self: @This()) void {
for (self.items) |tag| {
switch (tag.kind) {
.Named => |named_tag| {
self.allocator.free(named_tag.text);
self.allocator.free(named_tag.language);
},
}
}
self.allocator.free(self.items);
}
};
const TagList = std.ArrayList(Tag);
/// Caller owns returned memory.
pub fn fetchTagsFromCore(self: *Self, allocator: std.mem.Allocator, core_hash: Hash) !OwnedTagList {
var stmt = try self.db.?.prepare("select tag_text, tag_language from tag_names where core_hash = ?");
defer stmt.deinit();
var named_tag_values = try stmt.all(
NamedTagValue,
allocator,
.{},
.{core_hash.id},
);
defer allocator.free(named_tag_values);
var list = TagList.init(allocator);
defer list.deinit();
for (named_tag_values) |named_tag| {
try list.append(Tag{
.core = core_hash,
.kind = .{ .Named = named_tag },
});
}
return OwnedTagList{
.allocator = allocator,
.items = list.toOwnedSlice(),
};
}
pub const HashWithBlob = struct {
id: i64,
hash_data: sqlite.Blob,
pub fn toRealHash(self: @This()) Hash {
var hash_value: [32]u8 = undefined;
std.mem.copy(u8, &hash_value, self.hash_data.data);
return Hash{ .id = self.id, .hash_data = hash_value };
}
};
pub fn fetchNamedTag(self: *Self, text: []const u8, language: []const u8) !?Tag {
var maybe_core_hash = try self.db.?.oneAlloc(
HashWithBlob,
self.allocator,
\\ select hashes.id, hashes.hash_data
\\ from tag_names
\\ join hashes
\\ on tag_names.core_hash = hashes.id
\\ where tag_text = ? and tag_language = ?
,
.{},
.{ text, language },
);
defer if (maybe_core_hash) |hash| self.allocator.free(hash.hash_data.data);
if (maybe_core_hash) |core_hash| {
return Tag{
.core = core_hash.toRealHash(),
.kind = .{ .Named = .{ .text = text, .language = language } },
};
} else {
return null;
}
}
/// Caller owns the returned memory.
fn randomCoreData(self: *Self, core_output: []u8) void {
_ = self;
const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp()));
var r = std.rand.DefaultPrng.init(seed);
for (core_output) |_, index| {
var random_byte = r.random().uintAtMost(u8, 255);
core_output[index] = random_byte;
}
}
pub const Hash = struct {
id: i64,
hash_data: [32]u8,
const HashSelf = @This();
pub fn toHex(self: HashSelf) Blake3HashHex {
var core_hash_text_buffer: Blake3HashHex = undefined;
_ = std.fmt.bufPrint(
&core_hash_text_buffer,
"{x}",
.{std.fmt.fmtSliceHexLower(&self.hash_data)},
) catch unreachable;
return core_hash_text_buffer;
}
pub fn format(
self: HashSelf,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
_ = fmt;
return std.fmt.format(writer, "{s}", .{&self.toHex()});
}
};
pub fn createNamedTag(self: *Self, text: []const u8, language: []const u8, maybe_core: ?Hash) !Tag {
var core_hash: Hash = undefined;
if (maybe_core) |existing_core_hash| {
core_hash = existing_core_hash;
} else {
var core_data: [128]u8 = undefined;
self.randomCoreData(&core_data);
var core_hash_bytes: Blake3Hash = undefined;
var hasher = std.crypto.hash.Blake3.initKdf(AWTFDB_BLAKE3_CONTEXT, .{});
hasher.update(&core_data);
hasher.final(&core_hash_bytes);
var savepoint = try self.db.?.savepoint("named_tag");
errdefer savepoint.rollback();
defer savepoint.commit();
const hash_blob = sqlite.Blob{ .data = &core_hash_bytes };
const core_hash_id = (try self.db.?.one(
i64,
"insert into hashes (hash_data) values (?) returning id",
.{},
.{hash_blob},
)).?;
// core_hash_bytes is passed by reference here, so we don't
// have to worry about losing it to undefined memory hell.
core_hash = .{ .id = core_hash_id, .hash_data = core_hash_bytes };
const core_data_blob = sqlite.Blob{ .data = &core_data };
try self.db.?.exec(
"insert into tag_cores (core_hash, core_data) values (?, ?)",
.{},
.{ core_hash.id, core_data_blob },
);
log.debug("created tag core with hash {s}", .{core_hash});
}
try self.db.?.exec(
"insert into tag_names (core_hash, tag_text, tag_language) values (?, ?, ?)",
.{},
.{ core_hash.id, text, language },
);
log.debug("created name tag with value {s} language {s} core {s}", .{ text, language, core_hash });
return Tag{
.core = core_hash,
.kind = .{ .Named = .{ .text = text, .language = language } },
};
}
pub const HashList = std.ArrayList(Hash);
pub const File = struct {
ctx: *Context,
local_path: []const u8,
hash: Hash,
const FileSelf = @This();
pub fn deinit(self: FileSelf) void {
self.ctx.allocator.free(self.local_path);
}
pub fn addTag(self: *FileSelf, core_hash: Hash) !void {
try self.ctx.db.?.exec(
"insert into tag_files (core_hash, file_hash) values (?, ?) on conflict do nothing",
.{},
.{ core_hash.id, self.hash.id },
);
log.debug("link file {s} (hash {s}) with tag core hash {s}", .{ self.local_path, self.hash, core_hash });
}
// Copies ownership of given new_local_path
pub fn setLocalPath(self: *FileSelf, new_local_path: []const u8) !void {
try self.ctx.db.?.exec(
"update files set local_path = ? where file_hash = ? and local_path = ?",
.{},
.{ new_local_path, self.hash.id, self.local_path },
);
self.ctx.allocator.free(self.local_path);
self.local_path = try self.ctx.allocator.dupe(u8, new_local_path);
}
pub fn delete(self: FileSelf) !void {
log.info("deleted file {d} {s}", .{ self.hash.id, self.local_path });
try self.ctx.db.?.exec(
"delete from files where file_hash = ? and local_path = ?",
.{},
.{ self.hash.id, self.local_path },
);
try self.ctx.db.?.exec(
"delete from hashes where id = ?",
.{},
.{self.hash.id},
);
}
/// Returns all tag core hashes for the file.
pub fn fetchTags(self: FileSelf, allocator: std.mem.Allocator) ![]Hash {
var stmt = try self.ctx.db.?.prepare(
\\ select hashes.id, hashes.hash_data
\\ from tag_files
\\ join hashes
\\ on tag_files.core_hash = hashes.id
\\ where tag_files.file_hash = ?
);
defer stmt.deinit();
const internal_hashes = try stmt.all(
HashWithBlob,
allocator,
.{},
.{self.hash.id},
);
defer {
for (internal_hashes) |hash| allocator.free(hash.hash_data.data);
allocator.free(internal_hashes);
}
var list = HashList.init(allocator);
defer list.deinit();
for (internal_hashes) |hash| {
try list.append(hash.toRealHash());
}
return list.toOwnedSlice();
}
pub fn printTagsTo(
self: FileSelf,
allocator: std.mem.Allocator,
writer: anytype,
) !void {
var tag_cores = try self.fetchTags(allocator);
defer allocator.free(tag_cores);
for (tag_cores) |tag_core| {
var tags = try self.ctx.fetchTagsFromCore(allocator, tag_core);
defer tags.deinit();
for (tags.items) |tag| {
try writer.print(" '{s}'", .{tag});
}
}
}
};
/// Caller owns returned memory.
pub fn createFileFromPath(self: *Self, local_path: []const u8) !File {
const absolute_local_path = try std.fs.realpathAlloc(self.allocator, local_path);
var possible_file_entry = try self.fetchFileByPath(absolute_local_path);
if (possible_file_entry) |file_entry| {
// fetchFileByPath dupes the string so we need to free it here
defer self.allocator.free(absolute_local_path);
return file_entry;
}
var file = try std.fs.openFileAbsolute(absolute_local_path, .{ .mode = .read_only });
defer file.close();
var file_hash: Hash = try self.calculateHash(file, .{});
return try self.insertFile(file_hash, absolute_local_path);
}
pub const CalculateHashOptions = struct {
insert_new_hash: bool = true,
};
/// if the file is not indexed and options.insert_new_hash is false,
/// do not rely on the returned hash's id object making any sense.
pub fn calculateHash(self: *Self, file: std.fs.File, options: CalculateHashOptions) !Hash {
var data_chunk_buffer: [8192]u8 = undefined;
var hasher = std.crypto.hash.Blake3.initKdf(AWTFDB_BLAKE3_CONTEXT, .{});
while (true) {
const bytes_read = try file.read(&data_chunk_buffer);
if (bytes_read == 0) break;
const data_chunk = data_chunk_buffer[0..bytes_read];
hasher.update(data_chunk);
}
var file_hash: Hash = undefined;
hasher.final(&file_hash.hash_data);
const hash_blob = sqlite.Blob{ .data = &file_hash.hash_data };
const maybe_hash_id = try self.db.?.one(
i64,
"select id from hashes where hash_data = ?",
.{},
.{hash_blob},
);
if (maybe_hash_id) |hash_id| {
file_hash.id = hash_id;
} else {
if (options.insert_new_hash) {
file_hash.id = (try self.db.?.one(
i64,
"insert into hashes (hash_data) values (?) returning id",
.{},
.{hash_blob},
)).?;
} else {
file_hash.id = -1;
}
}
return file_hash;
}
pub fn calculateHashFromMemory(self: *Self, block: []const u8, options: CalculateHashOptions) !Hash {
var hasher = std.crypto.hash.Blake3.initKdf(AWTFDB_BLAKE3_CONTEXT, .{});
hasher.update(block);
var hash_entry: Hash = undefined;
hasher.final(&hash_entry.hash_data);
const hash_blob = sqlite.Blob{ .data = &hash_entry.hash_data };
const maybe_hash_id = try self.db.?.one(
i64,
"select id from hashes where hash_data = ?",
.{},
.{hash_blob},
);
if (maybe_hash_id) |hash_id| {
hash_entry.id = hash_id;
} else {
if (options.insert_new_hash) {
hash_entry.id = (try self.db.?.one(
i64,
"insert into hashes (hash_data) values (?) returning id",
.{},
.{hash_blob},
)).?;
} else {
hash_entry.id = -1;
}
}
return hash_entry;
}
fn insertFile(
self: *Self,
file_hash: Hash,
absolute_local_path: []const u8,
) !File {
try self.db.?.exec(
"insert into files (file_hash, local_path) values (?, ?) on conflict do nothing",
.{},
.{ file_hash.id, absolute_local_path },
);
log.debug("created file entry hash={s} path={s}", .{
absolute_local_path,
file_hash,
});
return File{
.ctx = self,
.local_path = absolute_local_path,
.hash = file_hash,
};
}
pub fn createFileFromDir(self: *Self, dir: std.fs.Dir, dir_path: []const u8) !File {
var file = try dir.openFile(dir_path, .{ .mode = .read_only });
defer file.close();
const absolute_local_path = try dir.realpathAlloc(self.allocator, dir_path);
var possible_file_entry = try self.fetchFileByPath(absolute_local_path);
if (possible_file_entry) |file_entry| {
// fetchFileByPath dupes the string so we need to free it here
defer self.allocator.free(absolute_local_path);
return file_entry;
}
var file_hash: Hash = try self.calculateHash(file, .{});
return try self.insertFile(file_hash, absolute_local_path);
}
// TODO create fetchFileFromHash that receives full hash object and automatically
// prefers hash instead of id-search
pub fn fetchFile(self: *Self, hash_id: i64) !?File {
var maybe_local_path = try self.db.?.oneAlloc(
struct {
local_path: []const u8,
hash_data: sqlite.Blob,
},
self.allocator,
\\ select local_path, hashes.hash_data
\\ from files
\\ join hashes
\\ on files.file_hash = hashes.id
\\ where files.file_hash = ?
,
.{},
.{hash_id},
);
if (maybe_local_path) |*local_path| {
// string memory is passed to client
defer self.allocator.free(local_path.hash_data.data);
const almost_good_hash = HashWithBlob{
.id = hash_id,
.hash_data = local_path.hash_data,
};
return File{
.ctx = self,
.local_path = local_path.local_path,
.hash = almost_good_hash.toRealHash(),
};
} else {
return null;
}
}
pub fn fetchFileExact(self: *Self, hash_id: i64, given_local_path: []const u8) !?File {
var maybe_local_path = try self.db.?.oneAlloc(
struct {
local_path: []const u8,
hash_data: sqlite.Blob,
},
self.allocator,
\\ select files.local_path, hashes.hash_data
\\ from files
\\ join hashes
\\ on files.file_hash = hashes.id
\\ where files.file_hash = ? and files.local_path = ?
,
.{},
.{ hash_id, given_local_path },
);
if (maybe_local_path) |*local_path| {
// string memory is passed to client
defer self.allocator.free(local_path.hash_data.data);
const almost_good_hash = HashWithBlob{
.id = hash_id,
.hash_data = local_path.hash_data,
};
return File{
.ctx = self,
.local_path = local_path.local_path,
.hash = almost_good_hash.toRealHash(),
};
} else {
return null;
}
}
pub fn fetchFileByHash(self: *Self, hash_data: [32]u8) !?File {
const hash_blob = sqlite.Blob{ .data = &hash_data };
var maybe_local_path = try self.db.?.oneAlloc(
struct {
local_path: []const u8,
hash_id: i64,
},
self.allocator,
\\ select local_path, hashes.id
\\ from files
\\ join hashes
\\ on files.file_hash = hashes.id
\\ where hashes.hash_data = ?
,
.{},
.{hash_blob},
);
if (maybe_local_path) |*local_path| {
return File{
.ctx = self,
.local_path = local_path.local_path,
.hash = Hash{
.id = local_path.hash_id,
.hash_data = hash_data,
},
};
} else {
return null;
}
}
pub fn fetchFileByPath(self: *Self, absolute_local_path: []const u8) !?File {
var maybe_hash = try self.db.?.oneAlloc(
HashWithBlob,
self.allocator,
\\ select hashes.id, hashes.hash_data
\\ from files
\\ join hashes
\\ on files.file_hash = hashes.id
\\ where files.local_path = ?
,
.{},
.{absolute_local_path},
);
if (maybe_hash) |hash| {
// string memory is passed to client
defer self.allocator.free(hash.hash_data.data);
return File{
.ctx = self,
.local_path = try self.allocator.dupe(u8, absolute_local_path),
.hash = hash.toRealHash(),
};
} else {
return null;
}
}
pub fn createCommand(self: *Self) !void {
try self.loadDatabase(.{ .create = true });
try self.migrateCommand();
}
pub fn migrateCommand(self: *Self) !void {
try self.loadDatabase(.{});
// migration log table is forever
try self.db.?.exec(MIGRATION_LOG_TABLE, .{}, .{});
const current_version: i32 = (try self.db.?.one(i32, "select max(version) from migration_logs", .{}, .{})) orelse 0;
log.info("db version: {d}", .{current_version});
// before running migrations, copy the database over
if (self.db_path) |db_path| {
const backup_db_path = try std.fs.path.resolve(
self.allocator,
&[_][]const u8{ self.home_path.?, ".awtf.before-migration.db" },
);
defer self.allocator.free(backup_db_path);
log.info("starting transaction for backup from {s} to {s}", .{ db_path, backup_db_path });
try self.db.?.exec("begin exclusive transaction", .{}, .{});
errdefer {
self.db.?.exec("rollback transaction", .{}, .{}) catch |err| {
const detailed_error = self.db.?.getDetailedError();
std.debug.panic(
"unable to rollback transaction, error: {}, message: {s}\n",
.{ err, detailed_error },
);
};
}
defer {
self.db.?.exec("commit transaction", .{}, .{}) catch |err| {
const detailed_error = self.db.?.getDetailedError();
std.debug.panic(
"unable to commit transaction, error: {}, message: {s}\n",
.{ err, detailed_error },
);
};
}
log.info("copying database to {s}", .{backup_db_path});
try std.fs.copyFileAbsolute(db_path, backup_db_path, .{});
}
{
var savepoint = try self.db.?.savepoint("migrations");
errdefer savepoint.rollback();
defer savepoint.commit();
inline for (MIGRATIONS) |migration_decl| {
const decl_version = migration_decl.@"0";
const decl_name = migration_decl.@"1";
const decl_sql = migration_decl.@"2";
if (current_version < decl_version) {
log.info("running migration {d}", .{decl_version});
var diags = sqlite.Diagnostics{};
self.db.?.execMulti(decl_sql, .{ .diags = &diags }) catch |err| {
log.err("unable to prepare statement, got error {s}. diagnostics: {s}", .{ err, diags });
return err;
};
try self.db.?.exec(
"INSERT INTO migration_logs (version, applied_at, description) values (?, ?, ?);",
.{},
.{
.version = decl_version,
.applied_at = std.time.timestamp(),
.description = decl_name,
},
);
}
}
}
const val = try self.db.?.one(i64, "PRAGMA integrity_check", .{}, .{});
log.debug("integrity check returned {d}", .{val});
try self.db.?.exec("PRAGMA foreign_key_check", .{}, .{});
}
pub fn statsCommand(self: *Self) !void {
try self.loadDatabase(.{});
}
pub fn jobsCommand(self: *Self) !void {
try self.loadDatabase(.{});
}
};
pub export fn sqliteLog(_: ?*anyopaque, level: c_int, message: ?[*:0]const u8) callconv(.C) void {
log.info("sqlite logged level={d} msg={s}", .{ level, message });
}
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var allocator = gpa.allocator();
const rc = sqlite.c.sqlite3_config(sqlite.c.SQLITE_CONFIG_LOG, sqliteLog, @as(?*anyopaque, null));
if (rc != sqlite.c.SQLITE_OK) {
log.err("failed to configure: {d} '{s}'", .{
rc, sqlite.c.sqlite3_errstr(rc),
});
return error.ConfigFail;
}
var args_it = std.process.args();
_ = args_it.skip();
const stdout = std.io.getStdOut();
const Args = struct {
help: bool = false,
verbose: bool = false,
version: bool = false,
maybe_action: ?[]const u8 = null,
};
var given_args = Args{};
while (args_it.next()) |arg| {
if (std.mem.eql(u8, arg, "-h")) {
given_args.help = true;
} else if (std.mem.eql(u8, arg, "-v")) {
given_args.verbose = true;
} else if (std.mem.eql(u8, arg, "-V")) {
given_args.version = true;
} else {
given_args.maybe_action = arg;
}
}
if (given_args.help) {
try stdout.writer().print(HELPTEXT, .{});
return;
} else if (given_args.version) {
try stdout.writer().print("awtfdb-manage 0.0.1\n", .{});
return;
}
if (given_args.verbose) {
std.debug.todo("lmao help");
}
if (given_args.maybe_action == null) {
log.err("action argument is required", .{});
return error.MissingActionArgument;
}
var ctx = Context{
.home_path = null,
.args_it = &args_it,
.stdout = stdout,
.allocator = allocator,
.db = null,
};
defer ctx.deinit();
const action = given_args.maybe_action.?;
if (std.mem.eql(u8, action, "create")) {
try ctx.createCommand();
} else if (std.mem.eql(u8, action, "migrate")) {
try ctx.migrateCommand();
} else {
log.err("unknown action {s}", .{action});
return error.UnknownAction;
}
}
pub var test_db_path_buffer: [std.os.PATH_MAX]u8 = undefined;
pub fn makeTestContext() !Context {
const homepath = try std.fs.cwd().realpath(".", &test_db_path_buffer);
var ctx = Context{
.args_it = undefined,
.stdout = undefined,
.db = null,
.allocator = std.testing.allocator,
.home_path = homepath,
.db_path = null,
};
ctx.db = try sqlite.Db.init(.{
.mode = sqlite.Db.Mode{ .Memory = {} },
.open_flags = .{
.write = true,
.create = true,
},
.threading_mode = .MultiThread,
});
try ctx.createCommand();
return ctx;
}
/// Create a test context backed up by a real file, rather than memory.
pub fn makeTestContextRealFile() !Context {
var tmp = std.testing.tmpDir(.{});
// lol, lmao, etc
//defer tmp.cleanup();
const homepath = try tmp.dir.realpath(".", &test_db_path_buffer);
var file = try tmp.dir.createFile("test.db", .{});
defer file.close();
const dbpath = try tmp.dir.realpath("test.db", test_db_path_buffer[homepath.len..]);
var ctx = Context{
.args_it = undefined,
.stdout = undefined,
.db = null,
.allocator = std.testing.allocator,
.home_path = homepath,
.db_path = try std.testing.allocator.dupe(u8, dbpath),
};
try ctx.createCommand();
return ctx;
}
test "basic db initialization" {
var ctx = try makeTestContext();
defer ctx.deinit();
}
test "tag creation" {
var ctx = try makeTestContext();
defer ctx.deinit();
var tag = try ctx.createNamedTag("test_tag", "en", null);
var fetched_tag = (try ctx.fetchNamedTag("test_tag", "en")).?;
try std.testing.expectEqualStrings("test_tag", tag.kind.Named.text);
try std.testing.expectEqualStrings("en", tag.kind.Named.language);
try std.testing.expectEqualStrings("test_tag", fetched_tag.kind.Named.text);
try std.testing.expectEqualStrings("en", fetched_tag.kind.Named.language);
try std.testing.expectEqual(tag.core.id, fetched_tag.core.id);
try std.testing.expectEqualStrings(tag.core.hash_data[0..], fetched_tag.core.hash_data[0..]);
var same_core_tag = try ctx.createNamedTag("another_test_tag", "en", tag.core);
var fetched_same_core_tag = (try ctx.fetchNamedTag("another_test_tag", "en")).?;
try std.testing.expectEqualStrings(tag.core.hash_data[0..], same_core_tag.core.hash_data[0..]);
try std.testing.expectEqualStrings(fetched_tag.core.hash_data[0..], fetched_same_core_tag.core.hash_data[0..]);
var tags_from_core = try ctx.fetchTagsFromCore(std.testing.allocator, tag.core);
defer tags_from_core.deinit();
try std.testing.expectEqual(@as(usize, 2), tags_from_core.items.len);
try std.testing.expectEqualStrings(tag.core.hash_data[0..], tags_from_core.items[0].core.hash_data[0..]);
try std.testing.expectEqualStrings(tag.core.hash_data[0..], tags_from_core.items[1].core.hash_data[0..]);
const deleted_tags = try tag.deleteAll(&ctx.db.?);
try std.testing.expectEqual(@as(usize, 2), deleted_tags);
var tags_from_core_after_deletion = try ctx.fetchTagsFromCore(std.testing.allocator, tag.core);
defer tags_from_core_after_deletion.deinit();
try std.testing.expectEqual(@as(usize, 0), tags_from_core_after_deletion.items.len);
}
test "file creation" {
var ctx = try makeTestContext();
defer ctx.deinit();
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var file = try tmp.dir.createFile("test_file", .{});
defer file.close();
_ = try file.write("awooga");
var indexed_file = try ctx.createFileFromDir(tmp.dir, "test_file");
defer indexed_file.deinit();
try std.testing.expect(std.mem.endsWith(u8, indexed_file.local_path, "/test_file"));
// also try to create indexed file via absolute path
const full_tmp_file = try tmp.dir.realpathAlloc(std.testing.allocator, "test_file");
defer std.testing.allocator.free(full_tmp_file);
var path_indexed_file = try ctx.createFileFromPath(full_tmp_file);
defer path_indexed_file.deinit();
try std.testing.expectStringEndsWith(path_indexed_file.local_path, "/test_file");
try std.testing.expectEqual(indexed_file.hash.id, path_indexed_file.hash.id);
try std.testing.expectEqualStrings(indexed_file.hash.hash_data[0..], path_indexed_file.hash.hash_data[0..]);
var fetched_file = (try ctx.fetchFile(indexed_file.hash.id)).?;
defer fetched_file.deinit();
try std.testing.expectStringEndsWith(fetched_file.local_path, "/test_file");
try std.testing.expectEqual(indexed_file.hash.id, fetched_file.hash.id);
try std.testing.expectEqualStrings(indexed_file.hash.hash_data[0..], fetched_file.hash.hash_data[0..]);
var fetched_by_path_file = (try ctx.fetchFileByPath(indexed_file.local_path)).?;
defer fetched_by_path_file.deinit();
try std.testing.expectStringEndsWith(fetched_by_path_file.local_path, "/test_file");
try std.testing.expectEqual(indexed_file.hash.id, fetched_by_path_file.hash.id);
try std.testing.expectEqualStrings(indexed_file.hash.hash_data[0..], fetched_by_path_file.hash.hash_data[0..]);
var fetched_by_exact_combo = (try ctx.fetchFileExact(indexed_file.hash.id, indexed_file.local_path)).?;
defer fetched_by_exact_combo.deinit();
try std.testing.expectEqual(indexed_file.hash.id, fetched_by_exact_combo.hash.id);
try std.testing.expectEqualStrings(indexed_file.hash.hash_data[0..], fetched_by_exact_combo.hash.hash_data[0..]);
try indexed_file.delete();
try std.testing.expectEqual(@as(?Context.File, null), try ctx.fetchFile(indexed_file.hash.id));
}
test "file and tags" {
var ctx = try makeTestContext();
defer ctx.deinit();
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var file = try tmp.dir.createFile("test_file", .{});
defer file.close();
_ = try file.write("awooga");
var indexed_file = try ctx.createFileFromDir(tmp.dir, "test_file");
defer indexed_file.deinit();
var tag = try ctx.createNamedTag("test_tag", "en", null);
try indexed_file.addTag(tag.core);
var tag_cores = try indexed_file.fetchTags(std.testing.allocator);
defer std.testing.allocator.free(tag_cores);
var saw_correct_tag_core = false;
for (tag_cores) |core| {
if (std.mem.eql(u8, &tag.core.hash_data, &core.hash_data))
saw_correct_tag_core = true;
}
try std.testing.expect(saw_correct_tag_core);
}
test "in memory database" {
var ctx = try makeTestContextRealFile();
defer ctx.deinit();
var tag1 = try ctx.createNamedTag("test_tag", "en", null);
_ = tag1;
try ctx.turnIntoMemoryDb();
var tag1_inmem = try ctx.fetchNamedTag("test_tag", "en");
try std.testing.expect(tag1_inmem != null);
var tag2 = try ctx.createNamedTag("test_tag2", "en", null);
_ = tag2;
var tag2_inmem = try ctx.fetchNamedTag("test_tag2", "en");
try std.testing.expect(tag2_inmem != null);
ctx.db.?.deinit();
ctx.db = null;
try ctx.loadDatabase(.{});
var tag2_infile = try ctx.fetchNamedTag("test_tag2", "en");
try std.testing.expect(tag2_infile == null);
}
test "everyone else" {
std.testing.refAllDecls(@import("./include_main.zig"));
std.testing.refAllDecls(@import("./rename_watcher_main.zig"));
std.testing.refAllDecls(@import("./find_main.zig"));
std.testing.refAllDecls(@import("./ls_main.zig"));
std.testing.refAllDecls(@import("./rm_main.zig"));
std.testing.refAllDecls(@import("./hydrus_api_main.zig"));
std.testing.refAllDecls(@import("./tags_main.zig"));
}
|
src/main.zig
|
const std = @import("../../index.zig");
const enum3 = @import("enum3.zig").enum3;
const enum3_data = @import("enum3.zig").enum3_data;
const lookup_table = @import("lookup.zig").lookup_table;
const HP = @import("lookup.zig").HP;
const math = std.math;
const mem = std.mem;
const assert = std.debug.assert;
pub const FloatDecimal = struct {
digits: []u8,
exp: i32,
};
pub const RoundMode = enum {
// Round only the fractional portion (e.g. 1234.23 has precision 2)
Decimal,
// Round the entire whole/fractional portion (e.g. 1.23423e3 has precision 5)
Scientific,
};
/// Round a FloatDecimal as returned by errol3 to the specified fractional precision.
/// All digits after the specified precision should be considered invalid.
pub fn roundToPrecision(float_decimal: *FloatDecimal, precision: usize, mode: RoundMode) void {
// The round digit refers to the index which we should look at to determine
// whether we need to round to match the specified precision.
var round_digit: usize = 0;
switch (mode) {
RoundMode.Decimal => {
if (float_decimal.exp >= 0) {
round_digit = precision + @intCast(usize, float_decimal.exp);
} else {
// if a small negative exp, then adjust we need to offset by the number
// of leading zeros that will occur.
const min_exp_required = @intCast(usize, -float_decimal.exp);
if (precision > min_exp_required) {
round_digit = precision - min_exp_required;
}
}
},
RoundMode.Scientific => {
round_digit = 1 + precision;
},
}
// It suffices to look at just this digit. We don't round and propagate say 0.04999 to 0.05
// first, and then to 0.1 in the case of a {.1} single precision.
// Find the digit which will signify the round point and start rounding backwards.
if (round_digit < float_decimal.digits.len and float_decimal.digits[round_digit] - '0' >= 5) {
assert(round_digit >= 0);
var i = round_digit;
while (true) {
if (i == 0) {
// Rounded all the way past the start. This was of the form 9.999...
// Slot the new digit in place and increase the exponent.
float_decimal.exp += 1;
// Re-size the buffer to use the reserved leading byte.
const one_before = @intToPtr([*]u8, @ptrToInt(&float_decimal.digits[0]) - 1);
float_decimal.digits = one_before[0 .. float_decimal.digits.len + 1];
float_decimal.digits[0] = '1';
return;
}
i -= 1;
const new_value = (float_decimal.digits[i] - '0' + 1) % 10;
float_decimal.digits[i] = new_value + '0';
// must continue rounding until non-9
if (new_value != 0) {
return;
}
}
}
}
/// Corrected Errol3 double to ASCII conversion.
pub fn errol3(value: f64, buffer: []u8) FloatDecimal {
const bits = @bitCast(u64, value);
const i = tableLowerBound(bits);
if (i < enum3.len and enum3[i] == bits) {
const data = enum3_data[i];
const digits = buffer[1 .. data.str.len + 1];
mem.copy(u8, digits, data.str);
return FloatDecimal{
.digits = digits,
.exp = data.exp,
};
}
return errol3u(value, buffer);
}
/// Uncorrected Errol3 double to ASCII conversion.
fn errol3u(val: f64, buffer: []u8) FloatDecimal {
// check if in integer or fixed range
if (val > 9.007199254740992e15 and val < 3.40282366920938e+38) {
return errolInt(val, buffer);
} else if (val >= 16.0 and val < 9.007199254740992e15) {
return errolFixed(val, buffer);
}
// normalize the midpoint
const e = math.frexp(val).exponent;
var exp = @floatToInt(i16, math.floor(307 + @intToFloat(f64, e) * 0.30103));
if (exp < 20) {
exp = 20;
} else if (@intCast(usize, exp) >= lookup_table.len) {
exp = @intCast(i16, lookup_table.len - 1);
}
var mid = lookup_table[@intCast(usize, exp)];
mid = hpProd(mid, val);
const lten = lookup_table[@intCast(usize, exp)].val;
exp -= 307;
var ten: f64 = 1.0;
while (mid.val > 10.0 or (mid.val == 10.0 and mid.off >= 0.0)) {
exp += 1;
hpDiv10(&mid);
ten /= 10.0;
}
while (mid.val < 1.0 or (mid.val == 1.0 and mid.off < 0.0)) {
exp -= 1;
hpMul10(&mid);
ten *= 10.0;
}
// compute boundaries
var high = HP{
.val = mid.val,
.off = mid.off + (fpnext(val) - val) * lten * ten / 2.0,
};
var low = HP{
.val = mid.val,
.off = mid.off + (fpprev(val) - val) * lten * ten / 2.0,
};
hpNormalize(&high);
hpNormalize(&low);
// normalized boundaries
while (high.val > 10.0 or (high.val == 10.0 and high.off >= 0.0)) {
exp += 1;
hpDiv10(&high);
hpDiv10(&low);
}
while (high.val < 1.0 or (high.val == 1.0 and high.off < 0.0)) {
exp -= 1;
hpMul10(&high);
hpMul10(&low);
}
// digit generation
// We generate digits starting at index 1. If rounding a buffer later then it may be
// required to generate a preceeding digit in some cases (9.999) in which case we use
// the 0-index for this extra digit.
var buf_index: usize = 1;
while (true) {
var hdig = @floatToInt(u8, math.floor(high.val));
if ((high.val == @intToFloat(f64, hdig)) and (high.off < 0)) hdig -= 1;
var ldig = @floatToInt(u8, math.floor(low.val));
if ((low.val == @intToFloat(f64, ldig)) and (low.off < 0)) ldig -= 1;
if (ldig != hdig) break;
buffer[buf_index] = hdig + '0';
buf_index += 1;
high.val -= @intToFloat(f64, hdig);
low.val -= @intToFloat(f64, ldig);
hpMul10(&high);
hpMul10(&low);
}
const tmp = (high.val + low.val) / 2.0;
var mdig = @floatToInt(u8, math.floor(tmp + 0.5));
if ((@intToFloat(f64, mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1;
buffer[buf_index] = mdig + '0';
buf_index += 1;
return FloatDecimal{
.digits = buffer[1..buf_index],
.exp = exp,
};
}
fn tableLowerBound(k: u64) usize {
var i = enum3.len;
var j: usize = 0;
while (j < enum3.len) {
if (enum3[j] < k) {
j = 2 * j + 2;
} else {
i = j;
j = 2 * j + 1;
}
}
return i;
}
/// Compute the product of an HP number and a double.
/// @in: The HP number.
/// @val: The double.
/// &returns: The HP number.
fn hpProd(in: *const HP, val: f64) HP {
var hi: f64 = undefined;
var lo: f64 = undefined;
split(in.val, &hi, &lo);
var hi2: f64 = undefined;
var lo2: f64 = undefined;
split(val, &hi2, &lo2);
const p = in.val * val;
const e = ((hi * hi2 - p) + lo * hi2 + hi * lo2) + lo * lo2;
return HP{
.val = p,
.off = in.off * val + e,
};
}
/// Split a double into two halves.
/// @val: The double.
/// @hi: The high bits.
/// @lo: The low bits.
fn split(val: f64, hi: *f64, lo: *f64) void {
hi.* = gethi(val);
lo.* = val - hi.*;
}
fn gethi(in: f64) f64 {
const bits = @bitCast(u64, in);
const new_bits = bits & 0xFFFFFFFFF8000000;
return @bitCast(f64, new_bits);
}
/// Normalize the number by factoring in the error.
/// @hp: The float pair.
fn hpNormalize(hp: *HP) void {
// Required to avoid segfaults causing buffer overrun during errol3 digit output termination.
@setFloatMode(this, @import("builtin").FloatMode.Strict);
const val = hp.val;
hp.val += hp.off;
hp.off += val - hp.val;
}
/// Divide the high-precision number by ten.
/// @hp: The high-precision number
fn hpDiv10(hp: *HP) void {
var val = hp.val;
hp.val /= 10.0;
hp.off /= 10.0;
val -= hp.val * 8.0;
val -= hp.val * 2.0;
hp.off += val / 10.0;
hpNormalize(hp);
}
/// Multiply the high-precision number by ten.
/// @hp: The high-precision number
fn hpMul10(hp: *HP) void {
const val = hp.val;
hp.val *= 10.0;
hp.off *= 10.0;
var off = hp.val;
off -= val * 8.0;
off -= val * 2.0;
hp.off -= off;
hpNormalize(hp);
}
/// Integer conversion algorithm, guaranteed correct, optimal, and best.
/// @val: The val.
/// @buf: The output buffer.
/// &return: The exponent.
fn errolInt(val: f64, buffer: []u8) FloatDecimal {
const pow19 = u128(1e19);
assert((val > 9.007199254740992e15) and val < (3.40282366920938e38));
var mid = @floatToInt(u128, val);
var low: u128 = mid - fpeint((fpnext(val) - val) / 2.0);
var high: u128 = mid + fpeint((val - fpprev(val)) / 2.0);
if (@bitCast(u64, val) & 0x1 != 0) {
high -= 1;
} else {
low -= 1;
}
var l64 = @intCast(u64, low % pow19);
const lf = @intCast(u64, (low / pow19) % pow19);
var h64 = @intCast(u64, high % pow19);
const hf = @intCast(u64, (high / pow19) % pow19);
if (lf != hf) {
l64 = lf;
h64 = hf;
mid = mid / (pow19 / 10);
}
var mi: i32 = mismatch10(l64, h64);
var x: u64 = 1;
{
var i: i32 = @boolToInt(lf == hf);
while (i < mi) : (i += 1) {
x *= 10;
}
}
const m64 = @truncate(u64, @divTrunc(mid, x));
if (lf != hf) mi += 19;
var buf_index = u64toa(m64, buffer) - 1;
if (mi != 0) {
buffer[buf_index - 1] += @boolToInt(buffer[buf_index] >= '5');
} else {
buf_index += 1;
}
return FloatDecimal{
.digits = buffer[0..buf_index],
.exp = @intCast(i32, buf_index) + mi,
};
}
/// Fixed point conversion algorithm, guaranteed correct, optimal, and best.
/// @val: The val.
/// @buf: The output buffer.
/// &return: The exponent.
fn errolFixed(val: f64, buffer: []u8) FloatDecimal {
assert((val >= 16.0) and (val < 9.007199254740992e15));
const u = @floatToInt(u64, val);
const n = @intToFloat(f64, u);
var mid = val - n;
var lo = ((fpprev(val) - n) + mid) / 2.0;
var hi = ((fpnext(val) - n) + mid) / 2.0;
var buf_index = u64toa(u, buffer);
var exp = @intCast(i32, buf_index);
var j = buf_index;
buffer[j] = 0;
if (mid != 0.0) {
while (mid != 0.0) {
lo *= 10.0;
const ldig = @floatToInt(i32, lo);
lo -= @intToFloat(f64, ldig);
mid *= 10.0;
const mdig = @floatToInt(i32, mid);
mid -= @intToFloat(f64, mdig);
hi *= 10.0;
const hdig = @floatToInt(i32, hi);
hi -= @intToFloat(f64, hdig);
buffer[j] = @intCast(u8, mdig + '0');
j += 1;
if (hdig != ldig or j > 50) break;
}
if (mid > 0.5) {
buffer[j - 1] += 1;
} else if ((mid == 0.5) and (buffer[j - 1] & 0x1) != 0) {
buffer[j - 1] += 1;
}
} else {
while (buffer[j - 1] == '0') {
buffer[j - 1] = 0;
j -= 1;
}
}
buffer[j] = 0;
return FloatDecimal{
.digits = buffer[0..j],
.exp = exp,
};
}
fn fpnext(val: f64) f64 {
return @bitCast(f64, @bitCast(u64, val) +% 1);
}
fn fpprev(val: f64) f64 {
return @bitCast(f64, @bitCast(u64, val) -% 1);
}
pub const c_digits_lut = []u8{
'0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6',
'0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3',
'1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0',
'2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7',
'2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4',
'3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1',
'4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8',
'4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5',
'5', '6', '5', '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2',
'6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9',
'7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6',
'7', '7', '7', '8', '7', '9', '8', '0', '8', '1', '8', '2', '8', '3',
'8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0',
'9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7',
'9', '8', '9', '9',
};
fn u64toa(value_param: u64, buffer: []u8) usize {
var value = value_param;
const kTen8: u64 = 100000000;
const kTen9: u64 = kTen8 * 10;
const kTen10: u64 = kTen8 * 100;
const kTen11: u64 = kTen8 * 1000;
const kTen12: u64 = kTen8 * 10000;
const kTen13: u64 = kTen8 * 100000;
const kTen14: u64 = kTen8 * 1000000;
const kTen15: u64 = kTen8 * 10000000;
const kTen16: u64 = kTen8 * kTen8;
var buf_index: usize = 0;
if (value < kTen8) {
const v = @intCast(u32, value);
if (v < 10000) {
const d1: u32 = (v / 100) << 1;
const d2: u32 = (v % 100) << 1;
if (v >= 1000) {
buffer[buf_index] = c_digits_lut[d1];
buf_index += 1;
}
if (v >= 100) {
buffer[buf_index] = c_digits_lut[d1 + 1];
buf_index += 1;
}
if (v >= 10) {
buffer[buf_index] = c_digits_lut[d2];
buf_index += 1;
}
buffer[buf_index] = c_digits_lut[d2 + 1];
buf_index += 1;
} else {
// value = bbbbcccc
const b: u32 = v / 10000;
const c: u32 = v % 10000;
const d1: u32 = (b / 100) << 1;
const d2: u32 = (b % 100) << 1;
const d3: u32 = (c / 100) << 1;
const d4: u32 = (c % 100) << 1;
if (value >= 10000000) {
buffer[buf_index] = c_digits_lut[d1];
buf_index += 1;
}
if (value >= 1000000) {
buffer[buf_index] = c_digits_lut[d1 + 1];
buf_index += 1;
}
if (value >= 100000) {
buffer[buf_index] = c_digits_lut[d2];
buf_index += 1;
}
buffer[buf_index] = c_digits_lut[d2 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d3];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d3 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d4];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d4 + 1];
buf_index += 1;
}
} else if (value < kTen16) {
const v0: u32 = @intCast(u32, value / kTen8);
const v1: u32 = @intCast(u32, value % kTen8);
const b0: u32 = v0 / 10000;
const c0: u32 = v0 % 10000;
const d1: u32 = (b0 / 100) << 1;
const d2: u32 = (b0 % 100) << 1;
const d3: u32 = (c0 / 100) << 1;
const d4: u32 = (c0 % 100) << 1;
const b1: u32 = v1 / 10000;
const c1: u32 = v1 % 10000;
const d5: u32 = (b1 / 100) << 1;
const d6: u32 = (b1 % 100) << 1;
const d7: u32 = (c1 / 100) << 1;
const d8: u32 = (c1 % 100) << 1;
if (value >= kTen15) {
buffer[buf_index] = c_digits_lut[d1];
buf_index += 1;
}
if (value >= kTen14) {
buffer[buf_index] = c_digits_lut[d1 + 1];
buf_index += 1;
}
if (value >= kTen13) {
buffer[buf_index] = c_digits_lut[d2];
buf_index += 1;
}
if (value >= kTen12) {
buffer[buf_index] = c_digits_lut[d2 + 1];
buf_index += 1;
}
if (value >= kTen11) {
buffer[buf_index] = c_digits_lut[d3];
buf_index += 1;
}
if (value >= kTen10) {
buffer[buf_index] = c_digits_lut[d3 + 1];
buf_index += 1;
}
if (value >= kTen9) {
buffer[buf_index] = c_digits_lut[d4];
buf_index += 1;
}
if (value >= kTen8) {
buffer[buf_index] = c_digits_lut[d4 + 1];
buf_index += 1;
}
buffer[buf_index] = c_digits_lut[d5];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d5 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d6];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d6 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d7];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d7 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d8];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d8 + 1];
buf_index += 1;
} else {
const a = @intCast(u32, value / kTen16); // 1 to 1844
value %= kTen16;
if (a < 10) {
buffer[buf_index] = '0' + @intCast(u8, a);
buf_index += 1;
} else if (a < 100) {
const i: u32 = a << 1;
buffer[buf_index] = c_digits_lut[i];
buf_index += 1;
buffer[buf_index] = c_digits_lut[i + 1];
buf_index += 1;
} else if (a < 1000) {
buffer[buf_index] = '0' + @intCast(u8, a / 100);
buf_index += 1;
const i: u32 = (a % 100) << 1;
buffer[buf_index] = c_digits_lut[i];
buf_index += 1;
buffer[buf_index] = c_digits_lut[i + 1];
buf_index += 1;
} else {
const i: u32 = (a / 100) << 1;
const j: u32 = (a % 100) << 1;
buffer[buf_index] = c_digits_lut[i];
buf_index += 1;
buffer[buf_index] = c_digits_lut[i + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[j];
buf_index += 1;
buffer[buf_index] = c_digits_lut[j + 1];
buf_index += 1;
}
const v0 = @intCast(u32, value / kTen8);
const v1 = @intCast(u32, value % kTen8);
const b0: u32 = v0 / 10000;
const c0: u32 = v0 % 10000;
const d1: u32 = (b0 / 100) << 1;
const d2: u32 = (b0 % 100) << 1;
const d3: u32 = (c0 / 100) << 1;
const d4: u32 = (c0 % 100) << 1;
const b1: u32 = v1 / 10000;
const c1: u32 = v1 % 10000;
const d5: u32 = (b1 / 100) << 1;
const d6: u32 = (b1 % 100) << 1;
const d7: u32 = (c1 / 100) << 1;
const d8: u32 = (c1 % 100) << 1;
buffer[buf_index] = c_digits_lut[d1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d1 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d2];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d2 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d3];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d3 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d4];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d4 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d5];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d5 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d6];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d6 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d7];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d7 + 1];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d8];
buf_index += 1;
buffer[buf_index] = c_digits_lut[d8 + 1];
buf_index += 1;
}
return buf_index;
}
fn fpeint(from: f64) u128 {
const bits = @bitCast(u64, from);
assert((bits & ((1 << 52) - 1)) == 0);
return u128(1) << @truncate(u7, (bits >> 52) -% 1023);
}
/// Given two different integers with the same length in terms of the number
/// of decimal digits, index the digits from the right-most position starting
/// from zero, find the first index where the digits in the two integers
/// divergent starting from the highest index.
/// @a: Integer a.
/// @b: Integer b.
/// &returns: An index within [0, 19).
fn mismatch10(a: u64, b: u64) i32 {
const pow10 = 10000000000;
const af = a / pow10;
const bf = b / pow10;
var i: i32 = 0;
var a_copy = a;
var b_copy = b;
if (af != bf) {
i = 10;
a_copy = af;
b_copy = bf;
}
while (true) : (i += 1) {
a_copy /= 10;
b_copy /= 10;
if (a_copy == b_copy) return i;
}
}
|
std/fmt/errol/index.zig
|
const std = @import("../index.zig");
const math = std.math;
const assert = std.debug.assert;
fn modf_result(comptime T: type) type {
return struct {
fpart: T,
ipart: T,
};
}
pub const modf32_result = modf_result(f32);
pub const modf64_result = modf_result(f64);
pub fn modf(x: var) modf_result(@typeOf(x)) {
const T = @typeOf(x);
return switch (T) {
f32 => modf32(x),
f64 => modf64(x),
else => @compileError("modf not implemented for " ++ @typeName(T)),
};
}
fn modf32(x: f32) modf32_result {
var result: modf32_result = undefined;
const u = @bitCast(u32, x);
const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F;
const us = u & 0x80000000;
// TODO: Shouldn't need this.
if (math.isInf(x)) {
result.ipart = x;
result.fpart = math.nan(f32);
return result;
}
// no fractional part
if (e >= 23) {
result.ipart = x;
if (e == 0x80 and u << 9 != 0) { // nan
result.fpart = x;
} else {
result.fpart = @bitCast(f32, us);
}
return result;
}
// no integral part
if (e < 0) {
result.ipart = @bitCast(f32, us);
result.fpart = x;
return result;
}
const mask = u32(0x007FFFFF) >> @intCast(u5, e);
if (u & mask == 0) {
result.ipart = x;
result.fpart = @bitCast(f32, us);
return result;
}
const uf = @bitCast(f32, u & ~mask);
result.ipart = uf;
result.fpart = x - uf;
return result;
}
fn modf64(x: f64) modf64_result {
var result: modf64_result = undefined;
const u = @bitCast(u64, x);
const e = @intCast(i32, (u >> 52) & 0x7FF) - 0x3FF;
const us = u & (1 << 63);
if (math.isInf(x)) {
result.ipart = x;
result.fpart = math.nan(f64);
return result;
}
// no fractional part
if (e >= 52) {
result.ipart = x;
if (e == 0x400 and u << 12 != 0) { // nan
result.fpart = x;
} else {
result.fpart = @bitCast(f64, us);
}
return result;
}
// no integral part
if (e < 0) {
result.ipart = @bitCast(f64, us);
result.fpart = x;
return result;
}
const mask = u64(@maxValue(u64) >> 12) >> @intCast(u6, e);
if (u & mask == 0) {
result.ipart = x;
result.fpart = @bitCast(f64, us);
return result;
}
const uf = @bitCast(f64, u & ~mask);
result.ipart = uf;
result.fpart = x - uf;
return result;
}
test "math.modf" {
const a = modf(f32(1.0));
const b = modf32(1.0);
// NOTE: No struct comparison on generic return type function? non-named, makes sense, but still.
assert(a.ipart == b.ipart and a.fpart == b.fpart);
const c = modf(f64(1.0));
const d = modf64(1.0);
assert(a.ipart == b.ipart and a.fpart == b.fpart);
}
test "math.modf32" {
const epsilon = 0.000001;
var r: modf32_result = undefined;
r = modf32(1.0);
assert(math.approxEq(f32, r.ipart, 1.0, epsilon));
assert(math.approxEq(f32, r.fpart, 0.0, epsilon));
r = modf32(2.545);
assert(math.approxEq(f32, r.ipart, 2.0, epsilon));
assert(math.approxEq(f32, r.fpart, 0.545, epsilon));
r = modf32(3.978123);
assert(math.approxEq(f32, r.ipart, 3.0, epsilon));
assert(math.approxEq(f32, r.fpart, 0.978123, epsilon));
r = modf32(43874.3);
assert(math.approxEq(f32, r.ipart, 43874, epsilon));
assert(math.approxEq(f32, r.fpart, 0.300781, epsilon));
r = modf32(1234.340780);
assert(math.approxEq(f32, r.ipart, 1234, epsilon));
assert(math.approxEq(f32, r.fpart, 0.340820, epsilon));
}
test "math.modf64" {
const epsilon = 0.000001;
var r: modf64_result = undefined;
r = modf64(1.0);
assert(math.approxEq(f64, r.ipart, 1.0, epsilon));
assert(math.approxEq(f64, r.fpart, 0.0, epsilon));
r = modf64(2.545);
assert(math.approxEq(f64, r.ipart, 2.0, epsilon));
assert(math.approxEq(f64, r.fpart, 0.545, epsilon));
r = modf64(3.978123);
assert(math.approxEq(f64, r.ipart, 3.0, epsilon));
assert(math.approxEq(f64, r.fpart, 0.978123, epsilon));
r = modf64(43874.3);
assert(math.approxEq(f64, r.ipart, 43874, epsilon));
assert(math.approxEq(f64, r.fpart, 0.3, epsilon));
r = modf64(1234.340780);
assert(math.approxEq(f64, r.ipart, 1234, epsilon));
assert(math.approxEq(f64, r.fpart, 0.340780, epsilon));
}
test "math.modf32.special" {
var r: modf32_result = undefined;
r = modf32(math.inf(f32));
assert(math.isPositiveInf(r.ipart) and math.isNan(r.fpart));
r = modf32(-math.inf(f32));
assert(math.isNegativeInf(r.ipart) and math.isNan(r.fpart));
r = modf32(math.nan(f32));
assert(math.isNan(r.ipart) and math.isNan(r.fpart));
}
test "math.modf64.special" {
var r: modf64_result = undefined;
r = modf64(math.inf(f64));
assert(math.isPositiveInf(r.ipart) and math.isNan(r.fpart));
r = modf64(-math.inf(f64));
assert(math.isNegativeInf(r.ipart) and math.isNan(r.fpart));
r = modf64(math.nan(f64));
assert(math.isNan(r.ipart) and math.isNan(r.fpart));
}
|
std/math/modf.zig
|
const std = @import("std");
const File = std.fs.File;
const stdout = &std.io.getStdOut().writer();
const opt = @import("opt.zig");
const warn = std.debug.warn;
const BUFSIZ: u16 = 4096;
// Reads first n lines of file and
// prints to stdout
pub fn head(n: u32, file: std.fs.File, is_stdin: bool, is_bytes: bool) !void {
// Check if user inputs illegal line number
if (n <= 0) {
try stdout.print("Error: illegal line count: {}\n", .{n});
return;
}
// Init read buffer, used to store BUFSIZ input from readFull
var buffer: [BUFSIZ]u8 = undefined;
// Init linecount
var line_count: u8 = 0;
var fast: u32 = 0;
var slow: u32 = 0;
var bytes_read: usize = 0;
// Read first chunk of stream & loop
var size = try file.readAll(&buffer);
while (size > 0) : ({
size = (try file.readAll(&buffer));
fast = 0;
slow = 0;
}) {
// if is_bytes check size
if (is_bytes) {
if (size + bytes_read > n) {
var left = n - bytes_read;
try stdout.print("{s}", .{buffer[0..left]});
bytes_read += size;
} else {
bytes_read += size;
try stdout.print("{s}", .{buffer[0..size]});
}
continue;
}
// search for \n over characters and dump lines when found
while (fast < size) : (fast += 1) {
if (buffer[fast] == '\n') {
try stdout.print("{s}\n", .{buffer[slow..fast]});
slow = fast + 1;
line_count += 1;
if (line_count >= n) return;
}
}
// print leftover
try stdout.print("{s}", .{buffer[slow..fast]});
}
}
const HeadFlags = enum {
Lines,
Bytes,
Help,
Version,
};
var flags = [_]opt.Flag(HeadFlags){
.{
.name = HeadFlags.Help,
.long = "help",
},
.{
.name = HeadFlags.Version,
.long = "version",
},
.{
.name = HeadFlags.Bytes,
.short = 'c',
.kind = opt.ArgTypeTag.String,
.mandatory = true,
},
.{
.name = HeadFlags.Lines,
.short = 'n',
.kind = opt.ArgTypeTag.String,
.mandatory = true,
},
};
const PrintOptions = enum {
Full,
Lines,
Bytes,
};
// Testing... For now here is usage
// ./head FILE n
pub fn main(args: [][]u8) anyerror!u8 {
const r: u8 = 1;
var opts: PrintOptions = PrintOptions.Full;
var length: []u8 = undefined;
var it = opt.FlagIterator(HeadFlags).init(flags[0..], args);
while (it.next_flag() catch {
return 1;
}) |flag| {
switch (flag.name) {
HeadFlags.Help => {
warn("(help screen here)\n", .{});
return 1;
},
HeadFlags.Version => {
warn("(version info here)\n", .{});
return 1;
},
HeadFlags.Bytes => {
opts = PrintOptions.Bytes;
length = flag.value.String.?;
},
HeadFlags.Lines => {
opts = PrintOptions.Lines;
length = flag.value.String.?;
},
}
}
var n: u32 = 10;
if (opts != PrintOptions.Full)
n = std.fmt.parseInt(u32, length[0..], 10) catch |err| {
try stdout.print("Error: second arg must be a number!\n", .{});
return r;
};
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 {s}\n", .{file_name});
return 1;
};
if (files.items.len >= 2) try stdout.print("==> {s} <==\n", .{file_name});
// run command
head(n, file, false, opts == PrintOptions.Bytes) catch |err| {
try stdout.print("Error: {}\n", .{err});
return 1;
};
file.close();
}
} else {
head(n, std.io.getStdIn(), true, opts == PrintOptions.Bytes) catch |err| {
try stdout.print("Error: {}\n", .{err});
return 1;
};
}
return 0;
}
|
src/head.zig
|
const std = @import("std");
const builtin = @import("builtin");
pub const TypeId = builtin.TypeId;
pub const printf = std.io.stdout.printf;
pub const assert = std.debug.assert;
pub const e = 2.7182818284590452354; // e
pub const log2_e = 1.4426950408889634074; // log_2(e)
pub const log10_e = 0.43429448190325182765; // log_10(e)
pub const ln_2 = 0.69314718055994530942; // log_e(2)
pub const ln_10 = 2.30258509299404568402; // log_e(10)
pub const pi = 3.14159265358979323846; // pi
pub const pi_2 = 1.57079632679489661923; // pi/2
pub const pi_4 = 0.78539816339744830962; // pi/4
pub const r1_pi = 0.31830988618379067154; // 1/pi
pub const r2_pi = 0.63661977236758134308; // 2/pi
pub const r2_sqrtpi = 1.12837916709551257390; // 2/sqrt(pi)
pub const sqrt2 = 1.41421356237309504880; // sqrt(2)
pub const r1_sqrt2 = 0.70710678118654752440; // 1/sqrt(2)
// float.h details
pub const f64_true_min = 4.94065645841246544177e-324;
pub const f64_min = 2.22507385850720138309e-308;
pub const f64_max = 1.79769313486231570815e+308;
pub const f64_epsilon = 2.22044604925031308085e-16;
pub const f64_toint = 1.0 / f64_epsilon;
pub const f32_true_min = 1.40129846432481707092e-45;
pub const f32_min = 1.17549435082228750797e-38;
pub const f32_max = 3.40282346638528859812e+38;
pub const f32_epsilon = 1.1920928955078125e-07;
pub const f32_toint = 1.0 / f32_epsilon;
pub const nan_u32 = u32(0x7F800001);
pub const nan_f32 = @bitCast(f32, nan_u32);
pub const inf_u32 = u32(0x7F800000);
pub const inf_f32 = @bitCast(f32, inf_u32);
pub const nan_u64 = u64(0x7FF << 52) | 1;
pub const nan_f64 = @bitCast(f64, nan_u64);
pub const inf_u64 = u64(0x7FF << 52);
pub const inf_f64 = @bitCast(f64, inf_u64);
pub const nan = @import("nan.zig").nan;
pub const inf = @import("inf.zig").inf;
pub fn forceEval(value: var) {
const T = @typeOf(value);
switch (T) {
f32 => {
var x: f32 = undefined;
const p = @ptrCast(&volatile f32, &x);
*p = x;
},
f64 => {
var x: f64 = undefined;
const p = @ptrCast(&volatile f64, &x);
*p = x;
},
else => {
@compileError("forceEval not implemented for " ++ @typeName(T));
},
}
}
pub fn approxEq(comptime T: type, x: T, y: T, epsilon: T) -> bool {
assert(@typeId(T) == TypeId.Float);
fabs(x - y) < epsilon
}
pub fn raiseInvalid() {
// Raise INVALID fpu exception
}
pub fn raiseUnderflow() {
// Raise UNDERFLOW fpu exception
}
pub fn raiseOverflow() {
// Raise OVERFLOW fpu exception
}
pub fn raiseInexact() {
// Raise INEXACT fpu exception
}
pub fn raiseDivByZero() {
// Raise INEXACT fpu exception
}
pub const io = @import("io.zig");
pub const isNan = @import("isnan.zig").isNan;
pub const fabs = @import("fabs.zig").fabs;
pub const ceil = @import("ceil.zig").ceil;
pub const floor = @import("floor.zig").floor;
pub const trunc = @import("floor.zig").trunc;
pub const round = @import("round.zig").round;
pub const frexp = @import("frexp.zig").frexp;
pub const frexp32_result = @import("frexp.zig").frexp32_result;
pub const frexp64_result = @import("frexp.zig").frexp64_result;
pub const fmod = @import("fmod.zig").fmod;
pub const modf = @import("modf.zig").modf;
pub const modf32_result = @import("modf.zig").modf32_result;
pub const modf64_result = @import("modf.zig").modf64_result;
pub const copysign = @import("copysign.zig").copysign;
pub const isFinite = @import("isfinite.zig").isFinite;
pub const isInf = @import("isinf.zig").isInf;
pub const isPositiveInf = @import("isinf.zig").isPositiveInf;
pub const isNegativeInf = @import("isinf.zig").isNegativeInf;
pub const isNormal = @import("isnormal.zig").isNormal;
pub const signbit = @import("signbit.zig").signbit;
pub const scalbn = @import("scalbn.zig").scalbn;
pub const pow = @import("pow.zig").pow;
pub const sqrt = @import("sqrt.zig").sqrt;
pub const cbrt = @import("cbrt.zig").cbrt;
pub const acos = @import("acos.zig").acos;
pub const asin = @import("asin.zig").asin;
pub const atan = @import("atan.zig").atan;
pub const atan2 = @import("atan2.zig").atan2;
pub const hypot = @import("hypot.zig").hypot;
pub const exp = @import("exp.zig").exp;
pub const exp2 = @import("exp2.zig").exp2;
pub const expm1 = @import("expm1.zig").expm1;
pub const ilogb = @import("ilogb.zig").ilogb;
pub const log = @import("log.zig").log;
pub const log2 = @import("log2.zig").log2;
pub const log10 = @import("log10.zig").log10;
pub const log1p = @import("log1p.zig").log1p;
pub const fma = @import("fma.zig").fma;
pub const asinh = @import("asinh.zig").asinh;
pub const acosh = @import("acosh.zig").acosh;
pub const atanh = @import("atanh.zig").atanh;
pub const sinh = @import("sinh.zig").sinh;
pub const cosh = @import("cosh.zig").cosh;
pub const tanh = @import("tanh.zig").tanh;
pub const cos = @import("cos.zig").cos;
pub const sin = @import("sin.zig").sin;
pub const tan = @import("tan.zig").tan;
test "fmath" {
_ = @import("io.zig");
_ = @import("nan.zig");
_ = @import("isnan.zig");
_ = @import("fabs.zig");
_ = @import("ceil.zig");
_ = @import("floor.zig");
_ = @import("trunc.zig");
_ = @import("round.zig");
_ = @import("frexp.zig");
_ = @import("fmod.zig");
_ = @import("modf.zig");
_ = @import("copysign.zig");
_ = @import("isfinite.zig");
_ = @import("isinf.zig");
_ = @import("isnormal.zig");
_ = @import("signbit.zig");
_ = @import("scalbn.zig");
_ = @import("pow.zig");
_ = @import("sqrt.zig");
_ = @import("cbrt.zig");
_ = @import("acos.zig");
_ = @import("asin.zig");
_ = @import("atan.zig");
_ = @import("atan2.zig");
_ = @import("hypot.zig");
_ = @import("exp.zig");
_ = @import("exp2.zig");
_ = @import("expm1.zig");
_ = @import("ilogb.zig");
_ = @import("log.zig");
_ = @import("log2.zig");
_ = @import("log10.zig");
_ = @import("log1p.zig");
_ = @import("fma.zig");
_ = @import("asinh.zig");
_ = @import("acosh.zig");
_ = @import("atanh.zig");
_ = @import("sinh.zig");
_ = @import("cosh.zig");
_ = @import("tanh.zig");
_ = @import("sin.zig");
_ = @import("cos.zig");
_ = @import("tan.zig");
}
|
src/index.zig
|
pub const WAIT_OBJECT_0 = @as(u32, 0);
pub const WAIT_ABANDONED = @as(u32, 128);
pub const WAIT_ABANDONED_0 = @as(u32, 128);
pub const WAIT_IO_COMPLETION = @as(u32, 192);
pub const PRIVATE_NAMESPACE_FLAG_DESTROY = @as(u32, 1);
pub const PROC_THREAD_ATTRIBUTE_REPLACE_VALUE = @as(u32, 1);
pub const THREAD_POWER_THROTTLING_CURRENT_VERSION = @as(u32, 1);
pub const THREAD_POWER_THROTTLING_EXECUTION_SPEED = @as(u32, 1);
pub const THREAD_POWER_THROTTLING_VALID_FLAGS = @as(u32, 1);
pub const PME_CURRENT_VERSION = @as(u32, 1);
pub const PME_FAILFAST_ON_COMMIT_FAIL_DISABLE = @as(u32, 0);
pub const PME_FAILFAST_ON_COMMIT_FAIL_ENABLE = @as(u32, 1);
pub const PROCESS_POWER_THROTTLING_CURRENT_VERSION = @as(u32, 1);
pub const PROCESS_POWER_THROTTLING_EXECUTION_SPEED = @as(u32, 1);
pub const PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION = @as(u32, 4);
pub const PROCESS_LEAP_SECOND_INFO_FLAG_ENABLE_SIXTY_SECOND = @as(u32, 1);
pub const PROCESS_LEAP_SECOND_INFO_VALID_FLAGS = @as(u32, 1);
pub const INIT_ONCE_CHECK_ONLY = @as(u32, 1);
pub const INIT_ONCE_ASYNC = @as(u32, 2);
pub const INIT_ONCE_INIT_FAILED = @as(u32, 4);
pub const INIT_ONCE_CTX_RESERVED_BITS = @as(u32, 2);
pub const CONDITION_VARIABLE_LOCKMODE_SHARED = @as(u32, 1);
pub const MUTEX_MODIFY_STATE = @as(u32, 1);
pub const CREATE_MUTEX_INITIAL_OWNER = @as(u32, 1);
pub const CREATE_WAITABLE_TIMER_MANUAL_RESET = @as(u32, 1);
pub const CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = @as(u32, 2);
pub const SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY = @as(u32, 1);
pub const SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY = @as(u32, 2);
pub const SYNCHRONIZATION_BARRIER_FLAGS_NO_DELETE = @as(u32, 4);
//--------------------------------------------------------------------------------
// Section: Types (84)
//--------------------------------------------------------------------------------
pub const THREAD_CREATION_FLAGS = enum(u32) {
THREAD_CREATE_RUN_IMMEDIATELY = 0,
THREAD_CREATE_SUSPENDED = 4,
STACK_SIZE_PARAM_IS_A_RESERVATION = 65536,
_,
pub fn initFlags(o: struct {
THREAD_CREATE_RUN_IMMEDIATELY: u1 = 0,
THREAD_CREATE_SUSPENDED: u1 = 0,
STACK_SIZE_PARAM_IS_A_RESERVATION: u1 = 0,
}) THREAD_CREATION_FLAGS {
return @intToEnum(THREAD_CREATION_FLAGS,
(if (o.THREAD_CREATE_RUN_IMMEDIATELY == 1) @enumToInt(THREAD_CREATION_FLAGS.THREAD_CREATE_RUN_IMMEDIATELY) else 0)
| (if (o.THREAD_CREATE_SUSPENDED == 1) @enumToInt(THREAD_CREATION_FLAGS.THREAD_CREATE_SUSPENDED) else 0)
| (if (o.STACK_SIZE_PARAM_IS_A_RESERVATION == 1) @enumToInt(THREAD_CREATION_FLAGS.STACK_SIZE_PARAM_IS_A_RESERVATION) else 0)
);
}
};
pub const THREAD_CREATE_RUN_IMMEDIATELY = THREAD_CREATION_FLAGS.THREAD_CREATE_RUN_IMMEDIATELY;
pub const THREAD_CREATE_SUSPENDED = THREAD_CREATION_FLAGS.THREAD_CREATE_SUSPENDED;
pub const STACK_SIZE_PARAM_IS_A_RESERVATION = THREAD_CREATION_FLAGS.STACK_SIZE_PARAM_IS_A_RESERVATION;
pub const THREAD_PRIORITY = enum(i32) {
MODE_BACKGROUND_BEGIN = 65536,
MODE_BACKGROUND_END = 131072,
PRIORITY_ABOVE_NORMAL = 1,
PRIORITY_BELOW_NORMAL = -1,
PRIORITY_HIGHEST = 2,
PRIORITY_IDLE = -15,
PRIORITY_MIN = -2,
// PRIORITY_LOWEST = -2, this enum value conflicts with PRIORITY_MIN
PRIORITY_NORMAL = 0,
PRIORITY_TIME_CRITICAL = 15,
};
pub const THREAD_MODE_BACKGROUND_BEGIN = THREAD_PRIORITY.MODE_BACKGROUND_BEGIN;
pub const THREAD_MODE_BACKGROUND_END = THREAD_PRIORITY.MODE_BACKGROUND_END;
pub const THREAD_PRIORITY_ABOVE_NORMAL = THREAD_PRIORITY.PRIORITY_ABOVE_NORMAL;
pub const THREAD_PRIORITY_BELOW_NORMAL = THREAD_PRIORITY.PRIORITY_BELOW_NORMAL;
pub const THREAD_PRIORITY_HIGHEST = THREAD_PRIORITY.PRIORITY_HIGHEST;
pub const THREAD_PRIORITY_IDLE = THREAD_PRIORITY.PRIORITY_IDLE;
pub const THREAD_PRIORITY_MIN = THREAD_PRIORITY.PRIORITY_MIN;
pub const THREAD_PRIORITY_LOWEST = THREAD_PRIORITY.PRIORITY_MIN;
pub const THREAD_PRIORITY_NORMAL = THREAD_PRIORITY.PRIORITY_NORMAL;
pub const THREAD_PRIORITY_TIME_CRITICAL = THREAD_PRIORITY.PRIORITY_TIME_CRITICAL;
pub const WORKER_THREAD_FLAGS = enum(u32) {
EXECUTEDEFAULT = 0,
EXECUTEINIOTHREAD = 1,
EXECUTEINPERSISTENTTHREAD = 128,
EXECUTEINWAITTHREAD = 4,
EXECUTELONGFUNCTION = 16,
EXECUTEONLYONCE = 8,
TRANSFER_IMPERSONATION = 256,
EXECUTEINTIMERTHREAD = 32,
_,
pub fn initFlags(o: struct {
EXECUTEDEFAULT: u1 = 0,
EXECUTEINIOTHREAD: u1 = 0,
EXECUTEINPERSISTENTTHREAD: u1 = 0,
EXECUTEINWAITTHREAD: u1 = 0,
EXECUTELONGFUNCTION: u1 = 0,
EXECUTEONLYONCE: u1 = 0,
TRANSFER_IMPERSONATION: u1 = 0,
EXECUTEINTIMERTHREAD: u1 = 0,
}) WORKER_THREAD_FLAGS {
return @intToEnum(WORKER_THREAD_FLAGS,
(if (o.EXECUTEDEFAULT == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEDEFAULT) else 0)
| (if (o.EXECUTEINIOTHREAD == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEINIOTHREAD) else 0)
| (if (o.EXECUTEINPERSISTENTTHREAD == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEINPERSISTENTTHREAD) else 0)
| (if (o.EXECUTEINWAITTHREAD == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEINWAITTHREAD) else 0)
| (if (o.EXECUTELONGFUNCTION == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTELONGFUNCTION) else 0)
| (if (o.EXECUTEONLYONCE == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEONLYONCE) else 0)
| (if (o.TRANSFER_IMPERSONATION == 1) @enumToInt(WORKER_THREAD_FLAGS.TRANSFER_IMPERSONATION) else 0)
| (if (o.EXECUTEINTIMERTHREAD == 1) @enumToInt(WORKER_THREAD_FLAGS.EXECUTEINTIMERTHREAD) else 0)
);
}
};
pub const WT_EXECUTEDEFAULT = WORKER_THREAD_FLAGS.EXECUTEDEFAULT;
pub const WT_EXECUTEINIOTHREAD = WORKER_THREAD_FLAGS.EXECUTEINIOTHREAD;
pub const WT_EXECUTEINPERSISTENTTHREAD = WORKER_THREAD_FLAGS.EXECUTEINPERSISTENTTHREAD;
pub const WT_EXECUTEINWAITTHREAD = WORKER_THREAD_FLAGS.EXECUTEINWAITTHREAD;
pub const WT_EXECUTELONGFUNCTION = WORKER_THREAD_FLAGS.EXECUTELONGFUNCTION;
pub const WT_EXECUTEONLYONCE = WORKER_THREAD_FLAGS.EXECUTEONLYONCE;
pub const WT_TRANSFER_IMPERSONATION = WORKER_THREAD_FLAGS.TRANSFER_IMPERSONATION;
pub const WT_EXECUTEINTIMERTHREAD = WORKER_THREAD_FLAGS.EXECUTEINTIMERTHREAD;
pub const CREATE_EVENT = enum(u32) {
INITIAL_SET = 2,
MANUAL_RESET = 1,
_,
pub fn initFlags(o: struct {
INITIAL_SET: u1 = 0,
MANUAL_RESET: u1 = 0,
}) CREATE_EVENT {
return @intToEnum(CREATE_EVENT,
(if (o.INITIAL_SET == 1) @enumToInt(CREATE_EVENT.INITIAL_SET) else 0)
| (if (o.MANUAL_RESET == 1) @enumToInt(CREATE_EVENT.MANUAL_RESET) else 0)
);
}
};
pub const CREATE_EVENT_INITIAL_SET = CREATE_EVENT.INITIAL_SET;
pub const CREATE_EVENT_MANUAL_RESET = CREATE_EVENT.MANUAL_RESET;
pub const CREATE_PROCESS_LOGON_FLAGS = enum(u32) {
WITH_PROFILE = 1,
NETCREDENTIALS_ONLY = 2,
};
pub const LOGON_WITH_PROFILE = CREATE_PROCESS_LOGON_FLAGS.WITH_PROFILE;
pub const LOGON_NETCREDENTIALS_ONLY = CREATE_PROCESS_LOGON_FLAGS.NETCREDENTIALS_ONLY;
pub const PROCESS_AFFINITY_AUTO_UPDATE_FLAGS = enum(u32) {
DISABLE_AUTO_UPDATE = 0,
ENABLE_AUTO_UPDATE = 1,
};
pub const PROCESS_AFFINITY_DISABLE_AUTO_UPDATE = PROCESS_AFFINITY_AUTO_UPDATE_FLAGS.DISABLE_AUTO_UPDATE;
pub const PROCESS_AFFINITY_ENABLE_AUTO_UPDATE = PROCESS_AFFINITY_AUTO_UPDATE_FLAGS.ENABLE_AUTO_UPDATE;
pub const PROCESS_DEP_FLAGS = enum(u32) {
ENABLE = 1,
DISABLE_ATL_THUNK_EMULATION = 2,
NONE = 0,
_,
pub fn initFlags(o: struct {
ENABLE: u1 = 0,
DISABLE_ATL_THUNK_EMULATION: u1 = 0,
NONE: u1 = 0,
}) PROCESS_DEP_FLAGS {
return @intToEnum(PROCESS_DEP_FLAGS,
(if (o.ENABLE == 1) @enumToInt(PROCESS_DEP_FLAGS.ENABLE) else 0)
| (if (o.DISABLE_ATL_THUNK_EMULATION == 1) @enumToInt(PROCESS_DEP_FLAGS.DISABLE_ATL_THUNK_EMULATION) else 0)
| (if (o.NONE == 1) @enumToInt(PROCESS_DEP_FLAGS.NONE) else 0)
);
}
};
pub const PROCESS_DEP_ENABLE = PROCESS_DEP_FLAGS.ENABLE;
pub const PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION = PROCESS_DEP_FLAGS.DISABLE_ATL_THUNK_EMULATION;
pub const PROCESS_DEP_NONE = PROCESS_DEP_FLAGS.NONE;
pub const PROCESS_NAME_FORMAT = enum(u32) {
WIN32 = 0,
NATIVE = 1,
};
pub const PROCESS_NAME_WIN32 = PROCESS_NAME_FORMAT.WIN32;
pub const PROCESS_NAME_NATIVE = PROCESS_NAME_FORMAT.NATIVE;
pub const PROCESSOR_FEATURE_ID = enum(u32) {
ARM_64BIT_LOADSTORE_ATOMIC = 25,
ARM_DIVIDE_INSTRUCTION_AVAILABLE = 24,
ARM_EXTERNAL_CACHE_AVAILABLE = 26,
ARM_FMAC_INSTRUCTIONS_AVAILABLE = 27,
ARM_VFP_32_REGISTERS_AVAILABLE = 18,
@"3DNOW_INSTRUCTIONS_AVAILABLE" = 7,
CHANNELS_ENABLED = 16,
COMPARE_EXCHANGE_DOUBLE = 2,
COMPARE_EXCHANGE128 = 14,
COMPARE64_EXCHANGE128 = 15,
FASTFAIL_AVAILABLE = 23,
FLOATING_POINT_EMULATED = 1,
FLOATING_POINT_PRECISION_ERRATA = 0,
MMX_INSTRUCTIONS_AVAILABLE = 3,
NX_ENABLED = 12,
PAE_ENABLED = 9,
RDTSC_INSTRUCTION_AVAILABLE = 8,
RDWRFSGSBASE_AVAILABLE = 22,
SECOND_LEVEL_ADDRESS_TRANSLATION = 20,
SSE3_INSTRUCTIONS_AVAILABLE = 13,
VIRT_FIRMWARE_ENABLED = 21,
XMMI_INSTRUCTIONS_AVAILABLE = 6,
XMMI64_INSTRUCTIONS_AVAILABLE = 10,
XSAVE_ENABLED = 17,
ARM_V8_INSTRUCTIONS_AVAILABLE = 29,
ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE = 30,
ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE = 31,
ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE = 34,
};
pub const PF_ARM_64BIT_LOADSTORE_ATOMIC = PROCESSOR_FEATURE_ID.ARM_64BIT_LOADSTORE_ATOMIC;
pub const PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_DIVIDE_INSTRUCTION_AVAILABLE;
pub const PF_ARM_EXTERNAL_CACHE_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_EXTERNAL_CACHE_AVAILABLE;
pub const PF_ARM_FMAC_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_FMAC_INSTRUCTIONS_AVAILABLE;
pub const PF_ARM_VFP_32_REGISTERS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_VFP_32_REGISTERS_AVAILABLE;
pub const PF_3DNOW_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.@"3DNOW_INSTRUCTIONS_AVAILABLE";
pub const PF_CHANNELS_ENABLED = PROCESSOR_FEATURE_ID.CHANNELS_ENABLED;
pub const PF_COMPARE_EXCHANGE_DOUBLE = PROCESSOR_FEATURE_ID.COMPARE_EXCHANGE_DOUBLE;
pub const PF_COMPARE_EXCHANGE128 = PROCESSOR_FEATURE_ID.COMPARE_EXCHANGE128;
pub const PF_COMPARE64_EXCHANGE128 = PROCESSOR_FEATURE_ID.COMPARE64_EXCHANGE128;
pub const PF_FASTFAIL_AVAILABLE = PROCESSOR_FEATURE_ID.FASTFAIL_AVAILABLE;
pub const PF_FLOATING_POINT_EMULATED = PROCESSOR_FEATURE_ID.FLOATING_POINT_EMULATED;
pub const PF_FLOATING_POINT_PRECISION_ERRATA = PROCESSOR_FEATURE_ID.FLOATING_POINT_PRECISION_ERRATA;
pub const PF_MMX_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.MMX_INSTRUCTIONS_AVAILABLE;
pub const PF_NX_ENABLED = PROCESSOR_FEATURE_ID.NX_ENABLED;
pub const PF_PAE_ENABLED = PROCESSOR_FEATURE_ID.PAE_ENABLED;
pub const PF_RDTSC_INSTRUCTION_AVAILABLE = PROCESSOR_FEATURE_ID.RDTSC_INSTRUCTION_AVAILABLE;
pub const PF_RDWRFSGSBASE_AVAILABLE = PROCESSOR_FEATURE_ID.RDWRFSGSBASE_AVAILABLE;
pub const PF_SECOND_LEVEL_ADDRESS_TRANSLATION = PROCESSOR_FEATURE_ID.SECOND_LEVEL_ADDRESS_TRANSLATION;
pub const PF_SSE3_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.SSE3_INSTRUCTIONS_AVAILABLE;
pub const PF_VIRT_FIRMWARE_ENABLED = PROCESSOR_FEATURE_ID.VIRT_FIRMWARE_ENABLED;
pub const PF_XMMI_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.XMMI_INSTRUCTIONS_AVAILABLE;
pub const PF_XMMI64_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.XMMI64_INSTRUCTIONS_AVAILABLE;
pub const PF_XSAVE_ENABLED = PROCESSOR_FEATURE_ID.XSAVE_ENABLED;
pub const PF_ARM_V8_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_V8_INSTRUCTIONS_AVAILABLE;
pub const PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE;
pub const PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE;
pub const PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE = PROCESSOR_FEATURE_ID.ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE;
pub const GET_GUI_RESOURCES_FLAGS = enum(u32) {
GDIOBJECTS = 0,
GDIOBJECTS_PEAK = 2,
USEROBJECTS = 1,
USEROBJECTS_PEAK = 4,
};
pub const GR_GDIOBJECTS = GET_GUI_RESOURCES_FLAGS.GDIOBJECTS;
pub const GR_GDIOBJECTS_PEAK = GET_GUI_RESOURCES_FLAGS.GDIOBJECTS_PEAK;
pub const GR_USEROBJECTS = GET_GUI_RESOURCES_FLAGS.USEROBJECTS;
pub const GR_USEROBJECTS_PEAK = GET_GUI_RESOURCES_FLAGS.USEROBJECTS_PEAK;
pub const STARTUPINFOW_FLAGS = enum(u32) {
FORCEONFEEDBACK = 64,
FORCEOFFFEEDBACK = 128,
PREVENTPINNING = 8192,
RUNFULLSCREEN = 32,
TITLEISAPPID = 4096,
TITLEISLINKNAME = 2048,
UNTRUSTEDSOURCE = 32768,
USECOUNTCHARS = 8,
USEFILLATTRIBUTE = 16,
USEHOTKEY = 512,
USEPOSITION = 4,
USESHOWWINDOW = 1,
USESIZE = 2,
USESTDHANDLES = 256,
_,
pub fn initFlags(o: struct {
FORCEONFEEDBACK: u1 = 0,
FORCEOFFFEEDBACK: u1 = 0,
PREVENTPINNING: u1 = 0,
RUNFULLSCREEN: u1 = 0,
TITLEISAPPID: u1 = 0,
TITLEISLINKNAME: u1 = 0,
UNTRUSTEDSOURCE: u1 = 0,
USECOUNTCHARS: u1 = 0,
USEFILLATTRIBUTE: u1 = 0,
USEHOTKEY: u1 = 0,
USEPOSITION: u1 = 0,
USESHOWWINDOW: u1 = 0,
USESIZE: u1 = 0,
USESTDHANDLES: u1 = 0,
}) STARTUPINFOW_FLAGS {
return @intToEnum(STARTUPINFOW_FLAGS,
(if (o.FORCEONFEEDBACK == 1) @enumToInt(STARTUPINFOW_FLAGS.FORCEONFEEDBACK) else 0)
| (if (o.FORCEOFFFEEDBACK == 1) @enumToInt(STARTUPINFOW_FLAGS.FORCEOFFFEEDBACK) else 0)
| (if (o.PREVENTPINNING == 1) @enumToInt(STARTUPINFOW_FLAGS.PREVENTPINNING) else 0)
| (if (o.RUNFULLSCREEN == 1) @enumToInt(STARTUPINFOW_FLAGS.RUNFULLSCREEN) else 0)
| (if (o.TITLEISAPPID == 1) @enumToInt(STARTUPINFOW_FLAGS.TITLEISAPPID) else 0)
| (if (o.TITLEISLINKNAME == 1) @enumToInt(STARTUPINFOW_FLAGS.TITLEISLINKNAME) else 0)
| (if (o.UNTRUSTEDSOURCE == 1) @enumToInt(STARTUPINFOW_FLAGS.UNTRUSTEDSOURCE) else 0)
| (if (o.USECOUNTCHARS == 1) @enumToInt(STARTUPINFOW_FLAGS.USECOUNTCHARS) else 0)
| (if (o.USEFILLATTRIBUTE == 1) @enumToInt(STARTUPINFOW_FLAGS.USEFILLATTRIBUTE) else 0)
| (if (o.USEHOTKEY == 1) @enumToInt(STARTUPINFOW_FLAGS.USEHOTKEY) else 0)
| (if (o.USEPOSITION == 1) @enumToInt(STARTUPINFOW_FLAGS.USEPOSITION) else 0)
| (if (o.USESHOWWINDOW == 1) @enumToInt(STARTUPINFOW_FLAGS.USESHOWWINDOW) else 0)
| (if (o.USESIZE == 1) @enumToInt(STARTUPINFOW_FLAGS.USESIZE) else 0)
| (if (o.USESTDHANDLES == 1) @enumToInt(STARTUPINFOW_FLAGS.USESTDHANDLES) else 0)
);
}
};
pub const STARTF_FORCEONFEEDBACK = STARTUPINFOW_FLAGS.FORCEONFEEDBACK;
pub const STARTF_FORCEOFFFEEDBACK = STARTUPINFOW_FLAGS.FORCEOFFFEEDBACK;
pub const STARTF_PREVENTPINNING = STARTUPINFOW_FLAGS.PREVENTPINNING;
pub const STARTF_RUNFULLSCREEN = STARTUPINFOW_FLAGS.RUNFULLSCREEN;
pub const STARTF_TITLEISAPPID = STARTUPINFOW_FLAGS.TITLEISAPPID;
pub const STARTF_TITLEISLINKNAME = STARTUPINFOW_FLAGS.TITLEISLINKNAME;
pub const STARTF_UNTRUSTEDSOURCE = STARTUPINFOW_FLAGS.UNTRUSTEDSOURCE;
pub const STARTF_USECOUNTCHARS = STARTUPINFOW_FLAGS.USECOUNTCHARS;
pub const STARTF_USEFILLATTRIBUTE = STARTUPINFOW_FLAGS.USEFILLATTRIBUTE;
pub const STARTF_USEHOTKEY = STARTUPINFOW_FLAGS.USEHOTKEY;
pub const STARTF_USEPOSITION = STARTUPINFOW_FLAGS.USEPOSITION;
pub const STARTF_USESHOWWINDOW = STARTUPINFOW_FLAGS.USESHOWWINDOW;
pub const STARTF_USESIZE = STARTUPINFOW_FLAGS.USESIZE;
pub const STARTF_USESTDHANDLES = STARTUPINFOW_FLAGS.USESTDHANDLES;
pub const MEMORY_PRIORITY = enum(u32) {
VERY_LOW = 1,
LOW = 2,
MEDIUM = 3,
BELOW_NORMAL = 4,
NORMAL = 5,
};
pub const MEMORY_PRIORITY_VERY_LOW = MEMORY_PRIORITY.VERY_LOW;
pub const MEMORY_PRIORITY_LOW = MEMORY_PRIORITY.LOW;
pub const MEMORY_PRIORITY_MEDIUM = MEMORY_PRIORITY.MEDIUM;
pub const MEMORY_PRIORITY_BELOW_NORMAL = MEMORY_PRIORITY.BELOW_NORMAL;
pub const MEMORY_PRIORITY_NORMAL = MEMORY_PRIORITY.NORMAL;
pub const PROCESS_PROTECTION_LEVEL = enum(u32) {
WINTCB_LIGHT = 0,
WINDOWS = 1,
WINDOWS_LIGHT = 2,
ANTIMALWARE_LIGHT = 3,
LSA_LIGHT = 4,
WINTCB = 5,
CODEGEN_LIGHT = 6,
AUTHENTICODE = 7,
PPL_APP = 8,
NONE = 4294967294,
};
pub const PROTECTION_LEVEL_WINTCB_LIGHT = PROCESS_PROTECTION_LEVEL.WINTCB_LIGHT;
pub const PROTECTION_LEVEL_WINDOWS = PROCESS_PROTECTION_LEVEL.WINDOWS;
pub const PROTECTION_LEVEL_WINDOWS_LIGHT = PROCESS_PROTECTION_LEVEL.WINDOWS_LIGHT;
pub const PROTECTION_LEVEL_ANTIMALWARE_LIGHT = PROCESS_PROTECTION_LEVEL.ANTIMALWARE_LIGHT;
pub const PROTECTION_LEVEL_LSA_LIGHT = PROCESS_PROTECTION_LEVEL.LSA_LIGHT;
pub const PROTECTION_LEVEL_WINTCB = PROCESS_PROTECTION_LEVEL.WINTCB;
pub const PROTECTION_LEVEL_CODEGEN_LIGHT = PROCESS_PROTECTION_LEVEL.CODEGEN_LIGHT;
pub const PROTECTION_LEVEL_AUTHENTICODE = PROCESS_PROTECTION_LEVEL.AUTHENTICODE;
pub const PROTECTION_LEVEL_PPL_APP = PROCESS_PROTECTION_LEVEL.PPL_APP;
pub const PROTECTION_LEVEL_NONE = PROCESS_PROTECTION_LEVEL.NONE;
pub const POWER_REQUEST_CONTEXT_FLAGS = enum(u32) {
DETAILED_STRING = 2,
SIMPLE_STRING = 1,
};
pub const POWER_REQUEST_CONTEXT_DETAILED_STRING = POWER_REQUEST_CONTEXT_FLAGS.DETAILED_STRING;
pub const POWER_REQUEST_CONTEXT_SIMPLE_STRING = POWER_REQUEST_CONTEXT_FLAGS.SIMPLE_STRING;
pub const THREAD_ACCESS_RIGHTS = enum(u32) {
TERMINATE = 1,
SUSPEND_RESUME = 2,
GET_CONTEXT = 8,
SET_CONTEXT = 16,
SET_INFORMATION = 32,
QUERY_INFORMATION = 64,
SET_THREAD_TOKEN = 128,
IMPERSONATE = 256,
DIRECT_IMPERSONATION = 512,
SET_LIMITED_INFORMATION = 1024,
QUERY_LIMITED_INFORMATION = 2048,
RESUME = 4096,
ALL_ACCESS = 2097151,
DELETE = 65536,
READ_CONTROL = 131072,
WRITE_DAC = 262144,
WRITE_OWNER = 524288,
SYNCHRONIZE = 1048576,
STANDARD_RIGHTS_REQUIRED = 983040,
_,
pub fn initFlags(o: struct {
TERMINATE: u1 = 0,
SUSPEND_RESUME: u1 = 0,
GET_CONTEXT: u1 = 0,
SET_CONTEXT: u1 = 0,
SET_INFORMATION: u1 = 0,
QUERY_INFORMATION: u1 = 0,
SET_THREAD_TOKEN: u1 = 0,
IMPERSONATE: u1 = 0,
DIRECT_IMPERSONATION: u1 = 0,
SET_LIMITED_INFORMATION: u1 = 0,
QUERY_LIMITED_INFORMATION: u1 = 0,
RESUME: u1 = 0,
ALL_ACCESS: u1 = 0,
DELETE: u1 = 0,
READ_CONTROL: u1 = 0,
WRITE_DAC: u1 = 0,
WRITE_OWNER: u1 = 0,
SYNCHRONIZE: u1 = 0,
STANDARD_RIGHTS_REQUIRED: u1 = 0,
}) THREAD_ACCESS_RIGHTS {
return @intToEnum(THREAD_ACCESS_RIGHTS,
(if (o.TERMINATE == 1) @enumToInt(THREAD_ACCESS_RIGHTS.TERMINATE) else 0)
| (if (o.SUSPEND_RESUME == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SUSPEND_RESUME) else 0)
| (if (o.GET_CONTEXT == 1) @enumToInt(THREAD_ACCESS_RIGHTS.GET_CONTEXT) else 0)
| (if (o.SET_CONTEXT == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SET_CONTEXT) else 0)
| (if (o.SET_INFORMATION == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SET_INFORMATION) else 0)
| (if (o.QUERY_INFORMATION == 1) @enumToInt(THREAD_ACCESS_RIGHTS.QUERY_INFORMATION) else 0)
| (if (o.SET_THREAD_TOKEN == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SET_THREAD_TOKEN) else 0)
| (if (o.IMPERSONATE == 1) @enumToInt(THREAD_ACCESS_RIGHTS.IMPERSONATE) else 0)
| (if (o.DIRECT_IMPERSONATION == 1) @enumToInt(THREAD_ACCESS_RIGHTS.DIRECT_IMPERSONATION) else 0)
| (if (o.SET_LIMITED_INFORMATION == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SET_LIMITED_INFORMATION) else 0)
| (if (o.QUERY_LIMITED_INFORMATION == 1) @enumToInt(THREAD_ACCESS_RIGHTS.QUERY_LIMITED_INFORMATION) else 0)
| (if (o.RESUME == 1) @enumToInt(THREAD_ACCESS_RIGHTS.RESUME) else 0)
| (if (o.ALL_ACCESS == 1) @enumToInt(THREAD_ACCESS_RIGHTS.ALL_ACCESS) else 0)
| (if (o.DELETE == 1) @enumToInt(THREAD_ACCESS_RIGHTS.DELETE) else 0)
| (if (o.READ_CONTROL == 1) @enumToInt(THREAD_ACCESS_RIGHTS.READ_CONTROL) else 0)
| (if (o.WRITE_DAC == 1) @enumToInt(THREAD_ACCESS_RIGHTS.WRITE_DAC) else 0)
| (if (o.WRITE_OWNER == 1) @enumToInt(THREAD_ACCESS_RIGHTS.WRITE_OWNER) else 0)
| (if (o.SYNCHRONIZE == 1) @enumToInt(THREAD_ACCESS_RIGHTS.SYNCHRONIZE) else 0)
| (if (o.STANDARD_RIGHTS_REQUIRED == 1) @enumToInt(THREAD_ACCESS_RIGHTS.STANDARD_RIGHTS_REQUIRED) else 0)
);
}
};
pub const THREAD_TERMINATE = THREAD_ACCESS_RIGHTS.TERMINATE;
pub const THREAD_SUSPEND_RESUME = THREAD_ACCESS_RIGHTS.SUSPEND_RESUME;
pub const THREAD_GET_CONTEXT = THREAD_ACCESS_RIGHTS.GET_CONTEXT;
pub const THREAD_SET_CONTEXT = THREAD_ACCESS_RIGHTS.SET_CONTEXT;
pub const THREAD_SET_INFORMATION = THREAD_ACCESS_RIGHTS.SET_INFORMATION;
pub const THREAD_QUERY_INFORMATION = THREAD_ACCESS_RIGHTS.QUERY_INFORMATION;
pub const THREAD_SET_THREAD_TOKEN = THREAD_ACCESS_RIGHTS.SET_THREAD_TOKEN;
pub const THREAD_IMPERSONATE = THREAD_ACCESS_RIGHTS.IMPERSONATE;
pub const THREAD_DIRECT_IMPERSONATION = THREAD_ACCESS_RIGHTS.DIRECT_IMPERSONATION;
pub const THREAD_SET_LIMITED_INFORMATION = THREAD_ACCESS_RIGHTS.SET_LIMITED_INFORMATION;
pub const THREAD_QUERY_LIMITED_INFORMATION = THREAD_ACCESS_RIGHTS.QUERY_LIMITED_INFORMATION;
pub const THREAD_RESUME = THREAD_ACCESS_RIGHTS.RESUME;
pub const THREAD_ALL_ACCESS = THREAD_ACCESS_RIGHTS.ALL_ACCESS;
pub const THREAD_DELETE = THREAD_ACCESS_RIGHTS.DELETE;
pub const THREAD_READ_CONTROL = THREAD_ACCESS_RIGHTS.READ_CONTROL;
pub const THREAD_WRITE_DAC = THREAD_ACCESS_RIGHTS.WRITE_DAC;
pub const THREAD_WRITE_OWNER = THREAD_ACCESS_RIGHTS.WRITE_OWNER;
pub const THREAD_SYNCHRONIZE = THREAD_ACCESS_RIGHTS.SYNCHRONIZE;
pub const THREAD_STANDARD_RIGHTS_REQUIRED = THREAD_ACCESS_RIGHTS.STANDARD_RIGHTS_REQUIRED;
pub const PROCESS_CREATION_FLAGS = enum(u32) {
DEBUG_PROCESS = 1,
DEBUG_ONLY_THIS_PROCESS = 2,
CREATE_SUSPENDED = 4,
DETACHED_PROCESS = 8,
CREATE_NEW_CONSOLE = 16,
NORMAL_PRIORITY_CLASS = 32,
IDLE_PRIORITY_CLASS = 64,
HIGH_PRIORITY_CLASS = 128,
REALTIME_PRIORITY_CLASS = 256,
CREATE_NEW_PROCESS_GROUP = 512,
CREATE_UNICODE_ENVIRONMENT = 1024,
CREATE_SEPARATE_WOW_VDM = 2048,
CREATE_SHARED_WOW_VDM = 4096,
CREATE_FORCEDOS = 8192,
BELOW_NORMAL_PRIORITY_CLASS = 16384,
ABOVE_NORMAL_PRIORITY_CLASS = 32768,
INHERIT_PARENT_AFFINITY = 65536,
INHERIT_CALLER_PRIORITY = 131072,
CREATE_PROTECTED_PROCESS = 262144,
EXTENDED_STARTUPINFO_PRESENT = 524288,
PROCESS_MODE_BACKGROUND_BEGIN = 1048576,
PROCESS_MODE_BACKGROUND_END = 2097152,
CREATE_SECURE_PROCESS = 4194304,
CREATE_BREAKAWAY_FROM_JOB = 16777216,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 33554432,
CREATE_DEFAULT_ERROR_MODE = 67108864,
CREATE_NO_WINDOW = 134217728,
PROFILE_USER = 268435456,
PROFILE_KERNEL = 536870912,
PROFILE_SERVER = 1073741824,
CREATE_IGNORE_SYSTEM_DEFAULT = 2147483648,
_,
pub fn initFlags(o: struct {
DEBUG_PROCESS: u1 = 0,
DEBUG_ONLY_THIS_PROCESS: u1 = 0,
CREATE_SUSPENDED: u1 = 0,
DETACHED_PROCESS: u1 = 0,
CREATE_NEW_CONSOLE: u1 = 0,
NORMAL_PRIORITY_CLASS: u1 = 0,
IDLE_PRIORITY_CLASS: u1 = 0,
HIGH_PRIORITY_CLASS: u1 = 0,
REALTIME_PRIORITY_CLASS: u1 = 0,
CREATE_NEW_PROCESS_GROUP: u1 = 0,
CREATE_UNICODE_ENVIRONMENT: u1 = 0,
CREATE_SEPARATE_WOW_VDM: u1 = 0,
CREATE_SHARED_WOW_VDM: u1 = 0,
CREATE_FORCEDOS: u1 = 0,
BELOW_NORMAL_PRIORITY_CLASS: u1 = 0,
ABOVE_NORMAL_PRIORITY_CLASS: u1 = 0,
INHERIT_PARENT_AFFINITY: u1 = 0,
INHERIT_CALLER_PRIORITY: u1 = 0,
CREATE_PROTECTED_PROCESS: u1 = 0,
EXTENDED_STARTUPINFO_PRESENT: u1 = 0,
PROCESS_MODE_BACKGROUND_BEGIN: u1 = 0,
PROCESS_MODE_BACKGROUND_END: u1 = 0,
CREATE_SECURE_PROCESS: u1 = 0,
CREATE_BREAKAWAY_FROM_JOB: u1 = 0,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL: u1 = 0,
CREATE_DEFAULT_ERROR_MODE: u1 = 0,
CREATE_NO_WINDOW: u1 = 0,
PROFILE_USER: u1 = 0,
PROFILE_KERNEL: u1 = 0,
PROFILE_SERVER: u1 = 0,
CREATE_IGNORE_SYSTEM_DEFAULT: u1 = 0,
}) PROCESS_CREATION_FLAGS {
return @intToEnum(PROCESS_CREATION_FLAGS,
(if (o.DEBUG_PROCESS == 1) @enumToInt(PROCESS_CREATION_FLAGS.DEBUG_PROCESS) else 0)
| (if (o.DEBUG_ONLY_THIS_PROCESS == 1) @enumToInt(PROCESS_CREATION_FLAGS.DEBUG_ONLY_THIS_PROCESS) else 0)
| (if (o.CREATE_SUSPENDED == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_SUSPENDED) else 0)
| (if (o.DETACHED_PROCESS == 1) @enumToInt(PROCESS_CREATION_FLAGS.DETACHED_PROCESS) else 0)
| (if (o.CREATE_NEW_CONSOLE == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_NEW_CONSOLE) else 0)
| (if (o.NORMAL_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.NORMAL_PRIORITY_CLASS) else 0)
| (if (o.IDLE_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.IDLE_PRIORITY_CLASS) else 0)
| (if (o.HIGH_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.HIGH_PRIORITY_CLASS) else 0)
| (if (o.REALTIME_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.REALTIME_PRIORITY_CLASS) else 0)
| (if (o.CREATE_NEW_PROCESS_GROUP == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_NEW_PROCESS_GROUP) else 0)
| (if (o.CREATE_UNICODE_ENVIRONMENT == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_UNICODE_ENVIRONMENT) else 0)
| (if (o.CREATE_SEPARATE_WOW_VDM == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_SEPARATE_WOW_VDM) else 0)
| (if (o.CREATE_SHARED_WOW_VDM == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_SHARED_WOW_VDM) else 0)
| (if (o.CREATE_FORCEDOS == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_FORCEDOS) else 0)
| (if (o.BELOW_NORMAL_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.BELOW_NORMAL_PRIORITY_CLASS) else 0)
| (if (o.ABOVE_NORMAL_PRIORITY_CLASS == 1) @enumToInt(PROCESS_CREATION_FLAGS.ABOVE_NORMAL_PRIORITY_CLASS) else 0)
| (if (o.INHERIT_PARENT_AFFINITY == 1) @enumToInt(PROCESS_CREATION_FLAGS.INHERIT_PARENT_AFFINITY) else 0)
| (if (o.INHERIT_CALLER_PRIORITY == 1) @enumToInt(PROCESS_CREATION_FLAGS.INHERIT_CALLER_PRIORITY) else 0)
| (if (o.CREATE_PROTECTED_PROCESS == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_PROTECTED_PROCESS) else 0)
| (if (o.EXTENDED_STARTUPINFO_PRESENT == 1) @enumToInt(PROCESS_CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT) else 0)
| (if (o.PROCESS_MODE_BACKGROUND_BEGIN == 1) @enumToInt(PROCESS_CREATION_FLAGS.PROCESS_MODE_BACKGROUND_BEGIN) else 0)
| (if (o.PROCESS_MODE_BACKGROUND_END == 1) @enumToInt(PROCESS_CREATION_FLAGS.PROCESS_MODE_BACKGROUND_END) else 0)
| (if (o.CREATE_SECURE_PROCESS == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_SECURE_PROCESS) else 0)
| (if (o.CREATE_BREAKAWAY_FROM_JOB == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_BREAKAWAY_FROM_JOB) else 0)
| (if (o.CREATE_PRESERVE_CODE_AUTHZ_LEVEL == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_PRESERVE_CODE_AUTHZ_LEVEL) else 0)
| (if (o.CREATE_DEFAULT_ERROR_MODE == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE) else 0)
| (if (o.CREATE_NO_WINDOW == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_NO_WINDOW) else 0)
| (if (o.PROFILE_USER == 1) @enumToInt(PROCESS_CREATION_FLAGS.PROFILE_USER) else 0)
| (if (o.PROFILE_KERNEL == 1) @enumToInt(PROCESS_CREATION_FLAGS.PROFILE_KERNEL) else 0)
| (if (o.PROFILE_SERVER == 1) @enumToInt(PROCESS_CREATION_FLAGS.PROFILE_SERVER) else 0)
| (if (o.CREATE_IGNORE_SYSTEM_DEFAULT == 1) @enumToInt(PROCESS_CREATION_FLAGS.CREATE_IGNORE_SYSTEM_DEFAULT) else 0)
);
}
};
pub const DEBUG_PROCESS = PROCESS_CREATION_FLAGS.DEBUG_PROCESS;
pub const DEBUG_ONLY_THIS_PROCESS = PROCESS_CREATION_FLAGS.DEBUG_ONLY_THIS_PROCESS;
pub const CREATE_SUSPENDED = PROCESS_CREATION_FLAGS.CREATE_SUSPENDED;
pub const DETACHED_PROCESS = PROCESS_CREATION_FLAGS.DETACHED_PROCESS;
pub const CREATE_NEW_CONSOLE = PROCESS_CREATION_FLAGS.CREATE_NEW_CONSOLE;
pub const NORMAL_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.NORMAL_PRIORITY_CLASS;
pub const IDLE_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.IDLE_PRIORITY_CLASS;
pub const HIGH_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.HIGH_PRIORITY_CLASS;
pub const REALTIME_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.REALTIME_PRIORITY_CLASS;
pub const CREATE_NEW_PROCESS_GROUP = PROCESS_CREATION_FLAGS.CREATE_NEW_PROCESS_GROUP;
pub const CREATE_UNICODE_ENVIRONMENT = PROCESS_CREATION_FLAGS.CREATE_UNICODE_ENVIRONMENT;
pub const CREATE_SEPARATE_WOW_VDM = PROCESS_CREATION_FLAGS.CREATE_SEPARATE_WOW_VDM;
pub const CREATE_SHARED_WOW_VDM = PROCESS_CREATION_FLAGS.CREATE_SHARED_WOW_VDM;
pub const CREATE_FORCEDOS = PROCESS_CREATION_FLAGS.CREATE_FORCEDOS;
pub const BELOW_NORMAL_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.BELOW_NORMAL_PRIORITY_CLASS;
pub const ABOVE_NORMAL_PRIORITY_CLASS = PROCESS_CREATION_FLAGS.ABOVE_NORMAL_PRIORITY_CLASS;
pub const INHERIT_PARENT_AFFINITY = PROCESS_CREATION_FLAGS.INHERIT_PARENT_AFFINITY;
pub const INHERIT_CALLER_PRIORITY = PROCESS_CREATION_FLAGS.INHERIT_CALLER_PRIORITY;
pub const CREATE_PROTECTED_PROCESS = PROCESS_CREATION_FLAGS.CREATE_PROTECTED_PROCESS;
pub const EXTENDED_STARTUPINFO_PRESENT = PROCESS_CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT;
pub const PROCESS_MODE_BACKGROUND_BEGIN = PROCESS_CREATION_FLAGS.PROCESS_MODE_BACKGROUND_BEGIN;
pub const PROCESS_MODE_BACKGROUND_END = PROCESS_CREATION_FLAGS.PROCESS_MODE_BACKGROUND_END;
pub const CREATE_SECURE_PROCESS = PROCESS_CREATION_FLAGS.CREATE_SECURE_PROCESS;
pub const CREATE_BREAKAWAY_FROM_JOB = PROCESS_CREATION_FLAGS.CREATE_BREAKAWAY_FROM_JOB;
pub const CREATE_PRESERVE_CODE_AUTHZ_LEVEL = PROCESS_CREATION_FLAGS.CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
pub const CREATE_DEFAULT_ERROR_MODE = PROCESS_CREATION_FLAGS.CREATE_DEFAULT_ERROR_MODE;
pub const CREATE_NO_WINDOW = PROCESS_CREATION_FLAGS.CREATE_NO_WINDOW;
pub const PROFILE_USER = PROCESS_CREATION_FLAGS.PROFILE_USER;
pub const PROFILE_KERNEL = PROCESS_CREATION_FLAGS.PROFILE_KERNEL;
pub const PROFILE_SERVER = PROCESS_CREATION_FLAGS.PROFILE_SERVER;
pub const CREATE_IGNORE_SYSTEM_DEFAULT = PROCESS_CREATION_FLAGS.CREATE_IGNORE_SYSTEM_DEFAULT;
pub const PROCESS_ACCESS_RIGHTS = enum(u32) {
TERMINATE = 1,
CREATE_THREAD = 2,
SET_SESSIONID = 4,
VM_OPERATION = 8,
VM_READ = 16,
VM_WRITE = 32,
DUP_HANDLE = 64,
CREATE_PROCESS = 128,
SET_QUOTA = 256,
SET_INFORMATION = 512,
QUERY_INFORMATION = 1024,
SUSPEND_RESUME = 2048,
QUERY_LIMITED_INFORMATION = 4096,
SET_LIMITED_INFORMATION = 8192,
ALL_ACCESS = 2097151,
DELETE = 65536,
READ_CONTROL = 131072,
WRITE_DAC = 262144,
WRITE_OWNER = 524288,
SYNCHRONIZE = 1048576,
STANDARD_RIGHTS_REQUIRED = 983040,
_,
pub fn initFlags(o: struct {
TERMINATE: u1 = 0,
CREATE_THREAD: u1 = 0,
SET_SESSIONID: u1 = 0,
VM_OPERATION: u1 = 0,
VM_READ: u1 = 0,
VM_WRITE: u1 = 0,
DUP_HANDLE: u1 = 0,
CREATE_PROCESS: u1 = 0,
SET_QUOTA: u1 = 0,
SET_INFORMATION: u1 = 0,
QUERY_INFORMATION: u1 = 0,
SUSPEND_RESUME: u1 = 0,
QUERY_LIMITED_INFORMATION: u1 = 0,
SET_LIMITED_INFORMATION: u1 = 0,
ALL_ACCESS: u1 = 0,
DELETE: u1 = 0,
READ_CONTROL: u1 = 0,
WRITE_DAC: u1 = 0,
WRITE_OWNER: u1 = 0,
SYNCHRONIZE: u1 = 0,
STANDARD_RIGHTS_REQUIRED: u1 = 0,
}) PROCESS_ACCESS_RIGHTS {
return @intToEnum(PROCESS_ACCESS_RIGHTS,
(if (o.TERMINATE == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.TERMINATE) else 0)
| (if (o.CREATE_THREAD == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.CREATE_THREAD) else 0)
| (if (o.SET_SESSIONID == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SET_SESSIONID) else 0)
| (if (o.VM_OPERATION == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.VM_OPERATION) else 0)
| (if (o.VM_READ == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.VM_READ) else 0)
| (if (o.VM_WRITE == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.VM_WRITE) else 0)
| (if (o.DUP_HANDLE == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.DUP_HANDLE) else 0)
| (if (o.CREATE_PROCESS == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.CREATE_PROCESS) else 0)
| (if (o.SET_QUOTA == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SET_QUOTA) else 0)
| (if (o.SET_INFORMATION == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SET_INFORMATION) else 0)
| (if (o.QUERY_INFORMATION == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.QUERY_INFORMATION) else 0)
| (if (o.SUSPEND_RESUME == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SUSPEND_RESUME) else 0)
| (if (o.QUERY_LIMITED_INFORMATION == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.QUERY_LIMITED_INFORMATION) else 0)
| (if (o.SET_LIMITED_INFORMATION == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SET_LIMITED_INFORMATION) else 0)
| (if (o.ALL_ACCESS == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.ALL_ACCESS) else 0)
| (if (o.DELETE == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.DELETE) else 0)
| (if (o.READ_CONTROL == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.READ_CONTROL) else 0)
| (if (o.WRITE_DAC == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.WRITE_DAC) else 0)
| (if (o.WRITE_OWNER == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.WRITE_OWNER) else 0)
| (if (o.SYNCHRONIZE == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.SYNCHRONIZE) else 0)
| (if (o.STANDARD_RIGHTS_REQUIRED == 1) @enumToInt(PROCESS_ACCESS_RIGHTS.STANDARD_RIGHTS_REQUIRED) else 0)
);
}
};
pub const PROCESS_TERMINATE = PROCESS_ACCESS_RIGHTS.TERMINATE;
pub const PROCESS_CREATE_THREAD = PROCESS_ACCESS_RIGHTS.CREATE_THREAD;
pub const PROCESS_SET_SESSIONID = PROCESS_ACCESS_RIGHTS.SET_SESSIONID;
pub const PROCESS_VM_OPERATION = PROCESS_ACCESS_RIGHTS.VM_OPERATION;
pub const PROCESS_VM_READ = PROCESS_ACCESS_RIGHTS.VM_READ;
pub const PROCESS_VM_WRITE = PROCESS_ACCESS_RIGHTS.VM_WRITE;
pub const PROCESS_DUP_HANDLE = PROCESS_ACCESS_RIGHTS.DUP_HANDLE;
pub const PROCESS_CREATE_PROCESS = PROCESS_ACCESS_RIGHTS.CREATE_PROCESS;
pub const PROCESS_SET_QUOTA = PROCESS_ACCESS_RIGHTS.SET_QUOTA;
pub const PROCESS_SET_INFORMATION = PROCESS_ACCESS_RIGHTS.SET_INFORMATION;
pub const PROCESS_QUERY_INFORMATION = PROCESS_ACCESS_RIGHTS.QUERY_INFORMATION;
pub const PROCESS_SUSPEND_RESUME = PROCESS_ACCESS_RIGHTS.SUSPEND_RESUME;
pub const PROCESS_QUERY_LIMITED_INFORMATION = PROCESS_ACCESS_RIGHTS.QUERY_LIMITED_INFORMATION;
pub const PROCESS_SET_LIMITED_INFORMATION = PROCESS_ACCESS_RIGHTS.SET_LIMITED_INFORMATION;
pub const PROCESS_ALL_ACCESS = PROCESS_ACCESS_RIGHTS.ALL_ACCESS;
pub const PROCESS_DELETE = PROCESS_ACCESS_RIGHTS.DELETE;
pub const PROCESS_READ_CONTROL = PROCESS_ACCESS_RIGHTS.READ_CONTROL;
pub const PROCESS_WRITE_DAC = PROCESS_ACCESS_RIGHTS.WRITE_DAC;
pub const PROCESS_WRITE_OWNER = PROCESS_ACCESS_RIGHTS.WRITE_OWNER;
pub const PROCESS_SYNCHRONIZE = PROCESS_ACCESS_RIGHTS.SYNCHRONIZE;
pub const PROCESS_STANDARD_RIGHTS_REQUIRED = PROCESS_ACCESS_RIGHTS.STANDARD_RIGHTS_REQUIRED;
pub const TP_CALLBACK_INSTANCE = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_WORK = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_TIMER = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_WAIT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_IO = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
// TODO: this type has a FreeFunc 'DeleteTimerQueueEx', what can Zig do with this information?
pub const TimerQueueHandle = isize;
// TODO: this type has a FreeFunc 'CloseThreadpool', what can Zig do with this information?
pub const PTP_POOL = isize;
// TODO: this type has a FreeFunc 'ClosePrivateNamespace', what can Zig do with this information?
pub const NamespaceHandle = isize;
// TODO: this type has a FreeFunc 'DeleteBoundaryDescriptor', what can Zig do with this information?
pub const BoundaryDescriptorHandle = isize;
pub const LPPROC_THREAD_ATTRIBUTE_LIST = *anyopaque;
pub const REASON_CONTEXT = extern struct {
Version: u32,
Flags: POWER_REQUEST_CONTEXT_FLAGS,
Reason: extern union {
Detailed: extern struct {
LocalizedReasonModule: ?HINSTANCE,
LocalizedReasonId: u32,
ReasonStringCount: u32,
ReasonStrings: ?*?PWSTR,
},
SimpleReasonString: ?PWSTR,
},
};
pub const LPTHREAD_START_ROUTINE = fn(
lpThreadParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PINIT_ONCE_FN = fn(
InitOnce: ?*RTL_RUN_ONCE,
Parameter: ?*anyopaque,
Context: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PTIMERAPCROUTINE = fn(
lpArgToCompletionRoutine: ?*anyopaque,
dwTimerLowValue: u32,
dwTimerHighValue: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PROCESS_INFORMATION = extern struct {
hProcess: ?HANDLE,
hThread: ?HANDLE,
dwProcessId: u32,
dwThreadId: u32,
};
pub const STARTUPINFOA = extern struct {
cb: u32,
lpReserved: ?PSTR,
lpDesktop: ?PSTR,
lpTitle: ?PSTR,
dwX: u32,
dwY: u32,
dwXSize: u32,
dwYSize: u32,
dwXCountChars: u32,
dwYCountChars: u32,
dwFillAttribute: u32,
dwFlags: STARTUPINFOW_FLAGS,
wShowWindow: u16,
cbReserved2: u16,
lpReserved2: ?*u8,
hStdInput: ?HANDLE,
hStdOutput: ?HANDLE,
hStdError: ?HANDLE,
};
pub const STARTUPINFOW = extern struct {
cb: u32,
lpReserved: ?PWSTR,
lpDesktop: ?PWSTR,
lpTitle: ?PWSTR,
dwX: u32,
dwY: u32,
dwXSize: u32,
dwYSize: u32,
dwXCountChars: u32,
dwYCountChars: u32,
dwFillAttribute: u32,
dwFlags: STARTUPINFOW_FLAGS,
wShowWindow: u16,
cbReserved2: u16,
lpReserved2: ?*u8,
hStdInput: ?HANDLE,
hStdOutput: ?HANDLE,
hStdError: ?HANDLE,
};
pub const QUEUE_USER_APC_FLAGS = enum(i32) {
NONE = 0,
SPECIAL_USER_APC = 1,
};
pub const QUEUE_USER_APC_FLAGS_NONE = QUEUE_USER_APC_FLAGS.NONE;
pub const QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC = QUEUE_USER_APC_FLAGS.SPECIAL_USER_APC;
pub const THREAD_INFORMATION_CLASS = enum(i32) {
MemoryPriority = 0,
AbsoluteCpuPriority = 1,
DynamicCodePolicy = 2,
PowerThrottling = 3,
InformationClassMax = 4,
};
pub const ThreadMemoryPriority = THREAD_INFORMATION_CLASS.MemoryPriority;
pub const ThreadAbsoluteCpuPriority = THREAD_INFORMATION_CLASS.AbsoluteCpuPriority;
pub const ThreadDynamicCodePolicy = THREAD_INFORMATION_CLASS.DynamicCodePolicy;
pub const ThreadPowerThrottling = THREAD_INFORMATION_CLASS.PowerThrottling;
pub const ThreadInformationClassMax = THREAD_INFORMATION_CLASS.InformationClassMax;
pub const MEMORY_PRIORITY_INFORMATION = extern struct {
MemoryPriority: MEMORY_PRIORITY,
};
pub const THREAD_POWER_THROTTLING_STATE = extern struct {
Version: u32,
ControlMask: u32,
StateMask: u32,
};
pub const PROCESS_INFORMATION_CLASS = enum(i32) {
MemoryPriority = 0,
MemoryExhaustionInfo = 1,
AppMemoryInfo = 2,
InPrivateInfo = 3,
PowerThrottling = 4,
ReservedValue1 = 5,
TelemetryCoverageInfo = 6,
ProtectionLevelInfo = 7,
LeapSecondInfo = 8,
MachineTypeInfo = 9,
InformationClassMax = 10,
};
pub const ProcessMemoryPriority = PROCESS_INFORMATION_CLASS.MemoryPriority;
pub const ProcessMemoryExhaustionInfo = PROCESS_INFORMATION_CLASS.MemoryExhaustionInfo;
pub const ProcessAppMemoryInfo = PROCESS_INFORMATION_CLASS.AppMemoryInfo;
pub const ProcessInPrivateInfo = PROCESS_INFORMATION_CLASS.InPrivateInfo;
pub const ProcessPowerThrottling = PROCESS_INFORMATION_CLASS.PowerThrottling;
pub const ProcessReservedValue1 = PROCESS_INFORMATION_CLASS.ReservedValue1;
pub const ProcessTelemetryCoverageInfo = PROCESS_INFORMATION_CLASS.TelemetryCoverageInfo;
pub const ProcessProtectionLevelInfo = PROCESS_INFORMATION_CLASS.ProtectionLevelInfo;
pub const ProcessLeapSecondInfo = PROCESS_INFORMATION_CLASS.LeapSecondInfo;
pub const ProcessMachineTypeInfo = PROCESS_INFORMATION_CLASS.MachineTypeInfo;
pub const ProcessInformationClassMax = PROCESS_INFORMATION_CLASS.InformationClassMax;
pub const APP_MEMORY_INFORMATION = extern struct {
AvailableCommit: u64,
PrivateCommitUsage: u64,
PeakPrivateCommitUsage: u64,
TotalCommitUsage: u64,
};
pub const MACHINE_ATTRIBUTES = enum(u32) {
UserEnabled = 1,
KernelEnabled = 2,
Wow64Container = 4,
_,
pub fn initFlags(o: struct {
UserEnabled: u1 = 0,
KernelEnabled: u1 = 0,
Wow64Container: u1 = 0,
}) MACHINE_ATTRIBUTES {
return @intToEnum(MACHINE_ATTRIBUTES,
(if (o.UserEnabled == 1) @enumToInt(MACHINE_ATTRIBUTES.UserEnabled) else 0)
| (if (o.KernelEnabled == 1) @enumToInt(MACHINE_ATTRIBUTES.KernelEnabled) else 0)
| (if (o.Wow64Container == 1) @enumToInt(MACHINE_ATTRIBUTES.Wow64Container) else 0)
);
}
};
pub const UserEnabled = MACHINE_ATTRIBUTES.UserEnabled;
pub const KernelEnabled = MACHINE_ATTRIBUTES.KernelEnabled;
pub const Wow64Container = MACHINE_ATTRIBUTES.Wow64Container;
pub const PROCESS_MACHINE_INFORMATION = extern struct {
ProcessMachine: u16,
Res0: u16,
MachineAttributes: MACHINE_ATTRIBUTES,
};
pub const PROCESS_MEMORY_EXHAUSTION_TYPE = enum(i32) {
FailFastOnCommitFailure = 0,
Max = 1,
};
pub const PMETypeFailFastOnCommitFailure = PROCESS_MEMORY_EXHAUSTION_TYPE.FailFastOnCommitFailure;
pub const PMETypeMax = PROCESS_MEMORY_EXHAUSTION_TYPE.Max;
pub const PROCESS_MEMORY_EXHAUSTION_INFO = extern struct {
Version: u16,
Reserved: u16,
Type: PROCESS_MEMORY_EXHAUSTION_TYPE,
Value: usize,
};
pub const PROCESS_POWER_THROTTLING_STATE = extern struct {
Version: u32,
ControlMask: u32,
StateMask: u32,
};
pub const PROCESS_PROTECTION_LEVEL_INFORMATION = extern struct {
ProtectionLevel: PROCESS_PROTECTION_LEVEL,
};
pub const PROCESS_LEAP_SECOND_INFO = extern struct {
Flags: u32,
Reserved: u32,
};
pub const PTP_WIN32_IO_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*anyopaque,
Overlapped: ?*anyopaque,
IoResult: u32,
NumberOfBytesTransferred: usize,
Io: ?*TP_IO,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PROCESS_DYNAMIC_EH_CONTINUATION_TARGET = extern struct {
TargetAddress: usize,
Flags: usize,
};
pub const PROCESS_DYNAMIC_EH_CONTINUATION_TARGETS_INFORMATION = extern struct {
NumberOfTargets: u16,
Reserved: u16,
Reserved2: u32,
Targets: ?*PROCESS_DYNAMIC_EH_CONTINUATION_TARGET,
};
pub const PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE = extern struct {
BaseAddress: usize,
Size: usize,
Flags: u32,
};
pub const PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION = extern struct {
NumberOfRanges: u16,
Reserved: u16,
Reserved2: u32,
Ranges: ?*PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE,
};
pub const IO_COUNTERS = extern struct {
ReadOperationCount: u64,
WriteOperationCount: u64,
OtherOperationCount: u64,
ReadTransferCount: u64,
WriteTransferCount: u64,
OtherTransferCount: u64,
};
pub const PROCESS_MITIGATION_POLICY = enum(i32) {
ProcessDEPPolicy = 0,
ProcessASLRPolicy = 1,
ProcessDynamicCodePolicy = 2,
ProcessStrictHandleCheckPolicy = 3,
ProcessSystemCallDisablePolicy = 4,
ProcessMitigationOptionsMask = 5,
ProcessExtensionPointDisablePolicy = 6,
ProcessControlFlowGuardPolicy = 7,
ProcessSignaturePolicy = 8,
ProcessFontDisablePolicy = 9,
ProcessImageLoadPolicy = 10,
ProcessSystemCallFilterPolicy = 11,
ProcessPayloadRestrictionPolicy = 12,
ProcessChildProcessPolicy = 13,
ProcessSideChannelIsolationPolicy = 14,
ProcessUserShadowStackPolicy = 15,
ProcessRedirectionTrustPolicy = 16,
MaxProcessMitigationPolicy = 17,
};
pub const ProcessDEPPolicy = PROCESS_MITIGATION_POLICY.ProcessDEPPolicy;
pub const ProcessASLRPolicy = PROCESS_MITIGATION_POLICY.ProcessASLRPolicy;
pub const ProcessDynamicCodePolicy = PROCESS_MITIGATION_POLICY.ProcessDynamicCodePolicy;
pub const ProcessStrictHandleCheckPolicy = PROCESS_MITIGATION_POLICY.ProcessStrictHandleCheckPolicy;
pub const ProcessSystemCallDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessSystemCallDisablePolicy;
pub const ProcessMitigationOptionsMask = PROCESS_MITIGATION_POLICY.ProcessMitigationOptionsMask;
pub const ProcessExtensionPointDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessExtensionPointDisablePolicy;
pub const ProcessControlFlowGuardPolicy = PROCESS_MITIGATION_POLICY.ProcessControlFlowGuardPolicy;
pub const ProcessSignaturePolicy = PROCESS_MITIGATION_POLICY.ProcessSignaturePolicy;
pub const ProcessFontDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessFontDisablePolicy;
pub const ProcessImageLoadPolicy = PROCESS_MITIGATION_POLICY.ProcessImageLoadPolicy;
pub const ProcessSystemCallFilterPolicy = PROCESS_MITIGATION_POLICY.ProcessSystemCallFilterPolicy;
pub const ProcessPayloadRestrictionPolicy = PROCESS_MITIGATION_POLICY.ProcessPayloadRestrictionPolicy;
pub const ProcessChildProcessPolicy = PROCESS_MITIGATION_POLICY.ProcessChildProcessPolicy;
pub const ProcessSideChannelIsolationPolicy = PROCESS_MITIGATION_POLICY.ProcessSideChannelIsolationPolicy;
pub const ProcessUserShadowStackPolicy = PROCESS_MITIGATION_POLICY.ProcessUserShadowStackPolicy;
pub const ProcessRedirectionTrustPolicy = PROCESS_MITIGATION_POLICY.ProcessRedirectionTrustPolicy;
pub const MaxProcessMitigationPolicy = PROCESS_MITIGATION_POLICY.MaxProcessMitigationPolicy;
pub const RTL_RUN_ONCE = extern union {
Ptr: ?*anyopaque,
};
pub const RTL_BARRIER = extern struct {
Reserved1: u32,
Reserved2: u32,
Reserved3: [2]usize,
Reserved4: u32,
Reserved5: u32,
};
pub const RTL_UMS_THREAD_INFO_CLASS = enum(i32) {
InvalidInfoClass = 0,
UserContext = 1,
Priority = 2,
Affinity = 3,
Teb = 4,
IsSuspended = 5,
IsTerminated = 6,
MaxInfoClass = 7,
};
pub const UmsThreadInvalidInfoClass = RTL_UMS_THREAD_INFO_CLASS.InvalidInfoClass;
pub const UmsThreadUserContext = RTL_UMS_THREAD_INFO_CLASS.UserContext;
pub const UmsThreadPriority = RTL_UMS_THREAD_INFO_CLASS.Priority;
pub const UmsThreadAffinity = RTL_UMS_THREAD_INFO_CLASS.Affinity;
pub const UmsThreadTeb = RTL_UMS_THREAD_INFO_CLASS.Teb;
pub const UmsThreadIsSuspended = RTL_UMS_THREAD_INFO_CLASS.IsSuspended;
pub const UmsThreadIsTerminated = RTL_UMS_THREAD_INFO_CLASS.IsTerminated;
pub const UmsThreadMaxInfoClass = RTL_UMS_THREAD_INFO_CLASS.MaxInfoClass;
pub const PRTL_UMS_SCHEDULER_ENTRY_POINT = fn(
Reason: RTL_UMS_SCHEDULER_REASON,
ActivationPayload: usize,
SchedulerParam: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RTL_CRITICAL_SECTION_DEBUG = extern struct {
Type: u16,
CreatorBackTraceIndex: u16,
CriticalSection: ?*RTL_CRITICAL_SECTION,
ProcessLocksList: LIST_ENTRY,
EntryCount: u32,
ContentionCount: u32,
Flags: u32,
CreatorBackTraceIndexHigh: u16,
SpareWORD: u16,
};
pub const RTL_CRITICAL_SECTION = extern struct {
DebugInfo: ?*RTL_CRITICAL_SECTION_DEBUG,
LockCount: i32,
RecursionCount: i32,
OwningThread: ?HANDLE,
LockSemaphore: ?HANDLE,
SpinCount: usize,
};
pub const RTL_SRWLOCK = extern struct {
Ptr: ?*anyopaque,
};
pub const RTL_CONDITION_VARIABLE = extern struct {
Ptr: ?*anyopaque,
};
pub const WAITORTIMERCALLBACK = fn(
param0: ?*anyopaque,
param1: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFLS_CALLBACK_FUNCTION = fn(
lpFlsData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PTP_SIMPLE_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const TP_CALLBACK_PRIORITY = enum(i32) {
HIGH = 0,
NORMAL = 1,
LOW = 2,
INVALID = 3,
// COUNT = 3, this enum value conflicts with INVALID
};
pub const TP_CALLBACK_PRIORITY_HIGH = TP_CALLBACK_PRIORITY.HIGH;
pub const TP_CALLBACK_PRIORITY_NORMAL = TP_CALLBACK_PRIORITY.NORMAL;
pub const TP_CALLBACK_PRIORITY_LOW = TP_CALLBACK_PRIORITY.LOW;
pub const TP_CALLBACK_PRIORITY_INVALID = TP_CALLBACK_PRIORITY.INVALID;
pub const TP_CALLBACK_PRIORITY_COUNT = TP_CALLBACK_PRIORITY.INVALID;
pub const TP_POOL_STACK_INFORMATION = extern struct {
StackReserve: usize,
StackCommit: usize,
};
pub const PTP_CLEANUP_GROUP_CANCEL_CALLBACK = fn(
ObjectContext: ?*anyopaque,
CleanupContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const TP_CALLBACK_ENVIRON_V3 = extern struct {
pub const _ACTIVATION_CONTEXT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
Version: u32,
Pool: PTP_POOL,
CleanupGroup: isize,
CleanupGroupCancelCallback: ?PTP_CLEANUP_GROUP_CANCEL_CALLBACK,
RaceDll: ?*anyopaque,
ActivationContext: isize,
FinalizationCallback: ?PTP_SIMPLE_CALLBACK,
u: extern union {
Flags: u32,
s: extern struct {
_bitfield: u32,
},
},
CallbackPriority: TP_CALLBACK_PRIORITY,
Size: u32,
};
pub const PTP_WORK_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*anyopaque,
Work: ?*TP_WORK,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PTP_TIMER_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*anyopaque,
Timer: ?*TP_TIMER,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PTP_WAIT_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*anyopaque,
Wait: ?*TP_WAIT,
WaitResult: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const LPFIBER_START_ROUTINE = fn(
lpFiberParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const UMS_SCHEDULER_STARTUP_INFO = extern struct {
UmsVersion: u32,
CompletionList: ?*anyopaque,
SchedulerProc: ?PRTL_UMS_SCHEDULER_ENTRY_POINT,
SchedulerParam: ?*anyopaque,
};
pub const UMS_SYSTEM_THREAD_INFORMATION = extern struct {
UmsVersion: u32,
Anonymous: extern union {
Anonymous: extern struct {
_bitfield: u32,
},
ThreadUmsFlags: u32,
},
};
pub const STARTUPINFOEXA = extern struct {
StartupInfo: STARTUPINFOA,
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
};
pub const STARTUPINFOEXW = extern struct {
StartupInfo: STARTUPINFOW,
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
};
pub const PEB_LDR_DATA = extern struct {
Reserved1: [8]u8,
Reserved2: [3]?*anyopaque,
InMemoryOrderModuleList: LIST_ENTRY,
};
pub const RTL_USER_PROCESS_PARAMETERS = extern struct {
Reserved1: [16]u8,
Reserved2: [10]?*anyopaque,
ImagePathName: UNICODE_STRING,
CommandLine: UNICODE_STRING,
};
pub const PPS_POST_PROCESS_INIT_ROUTINE = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const PEB = extern struct {
Reserved1: [2]u8,
BeingDebugged: u8,
Reserved2: [1]u8,
Reserved3: [2]?*anyopaque,
Ldr: ?*PEB_LDR_DATA,
ProcessParameters: ?*RTL_USER_PROCESS_PARAMETERS,
Reserved4: [3]?*anyopaque,
AtlThunkSListPtr: ?*anyopaque,
Reserved5: ?*anyopaque,
Reserved6: u32,
Reserved7: ?*anyopaque,
Reserved8: u32,
AtlThunkSListPtr32: u32,
Reserved9: [45]?*anyopaque,
Reserved10: [96]u8,
PostProcessInitRoutine: ?PPS_POST_PROCESS_INIT_ROUTINE,
Reserved11: [128]u8,
Reserved12: [1]?*anyopaque,
SessionId: u32,
};
pub const PROCESS_BASIC_INFORMATION = extern struct {
Reserved1: ?*anyopaque,
PebBaseAddress: ?*PEB,
Reserved2: [2]?*anyopaque,
UniqueProcessId: usize,
Reserved3: ?*anyopaque,
};
pub const PROCESSINFOCLASS = enum(i32) {
BasicInformation = 0,
DebugPort = 7,
Wow64Information = 26,
ImageFileName = 27,
BreakOnTermination = 29,
};
pub const ProcessBasicInformation = PROCESSINFOCLASS.BasicInformation;
pub const ProcessDebugPort = PROCESSINFOCLASS.DebugPort;
pub const ProcessWow64Information = PROCESSINFOCLASS.Wow64Information;
pub const ProcessImageFileName = PROCESSINFOCLASS.ImageFileName;
pub const ProcessBreakOnTermination = PROCESSINFOCLASS.BreakOnTermination;
pub const THREADINFOCLASS = enum(i32) {
IsIoPending = 16,
NameInformation = 38,
};
pub const ThreadIsIoPending = THREADINFOCLASS.IsIoPending;
pub const ThreadNameInformation = THREADINFOCLASS.NameInformation;
//--------------------------------------------------------------------------------
// Section: Functions (284)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessWorkingSetSize(
hProcess: ?HANDLE,
lpMinimumWorkingSetSize: ?*usize,
lpMaximumWorkingSetSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetProcessWorkingSetSize(
hProcess: ?HANDLE,
dwMinimumWorkingSetSize: usize,
dwMaximumWorkingSetSize: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FlsAlloc(
lpCallback: ?PFLS_CALLBACK_FUNCTION,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FlsGetValue(
dwFlsIndex: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FlsSetValue(
dwFlsIndex: u32,
lpFlsData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FlsFree(
dwFlsIndex: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn IsThreadAFiber(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitializeSRWLock(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ReleaseSRWLockExclusive(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ReleaseSRWLockShared(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn AcquireSRWLockExclusive(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn AcquireSRWLockShared(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn TryAcquireSRWLockExclusive(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn TryAcquireSRWLockShared(
SRWLock: ?*RTL_SRWLOCK,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InitializeCriticalSection(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn EnterCriticalSection(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LeaveCriticalSection(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InitializeCriticalSectionAndSpinCount(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
dwSpinCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitializeCriticalSectionEx(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
dwSpinCount: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetCriticalSectionSpinCount(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
dwSpinCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TryEnterCriticalSection(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeleteCriticalSection(
lpCriticalSection: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitOnceInitialize(
InitOnce: ?*RTL_RUN_ONCE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitOnceExecuteOnce(
InitOnce: ?*RTL_RUN_ONCE,
InitFn: ?PINIT_ONCE_FN,
Parameter: ?*anyopaque,
Context: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitOnceBeginInitialize(
lpInitOnce: ?*RTL_RUN_ONCE,
dwFlags: u32,
fPending: ?*BOOL,
lpContext: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitOnceComplete(
lpInitOnce: ?*RTL_RUN_ONCE,
dwFlags: u32,
lpContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitializeConditionVariable(
ConditionVariable: ?*RTL_CONDITION_VARIABLE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WakeConditionVariable(
ConditionVariable: ?*RTL_CONDITION_VARIABLE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WakeAllConditionVariable(
ConditionVariable: ?*RTL_CONDITION_VARIABLE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SleepConditionVariableCS(
ConditionVariable: ?*RTL_CONDITION_VARIABLE,
CriticalSection: ?*RTL_CRITICAL_SECTION,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SleepConditionVariableSRW(
ConditionVariable: ?*RTL_CONDITION_VARIABLE,
SRWLock: ?*RTL_SRWLOCK,
dwMilliseconds: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetEvent(
hEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ResetEvent(
hEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ReleaseSemaphore(
hSemaphore: ?HANDLE,
lReleaseCount: i32,
lpPreviousCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ReleaseMutex(
hMutex: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn WaitForSingleObject(
hHandle: ?HANDLE,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SleepEx(
dwMilliseconds: u32,
bAlertable: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn WaitForSingleObjectEx(
hHandle: ?HANDLE,
dwMilliseconds: u32,
bAlertable: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn WaitForMultipleObjectsEx(
nCount: u32,
lpHandles: [*]const ?HANDLE,
bWaitAll: BOOL,
dwMilliseconds: u32,
bAlertable: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateMutexA(
lpMutexAttributes: ?*SECURITY_ATTRIBUTES,
bInitialOwner: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateMutexW(
lpMutexAttributes: ?*SECURITY_ATTRIBUTES,
bInitialOwner: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenMutexW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateEventA(
lpEventAttributes: ?*SECURITY_ATTRIBUTES,
bManualReset: BOOL,
bInitialState: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateEventW(
lpEventAttributes: ?*SECURITY_ATTRIBUTES,
bManualReset: BOOL,
bInitialState: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenEventA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenEventW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenSemaphoreW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenWaitableTimerW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpTimerName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn SetWaitableTimerEx(
hTimer: ?HANDLE,
lpDueTime: ?*const LARGE_INTEGER,
lPeriod: i32,
pfnCompletionRoutine: ?PTIMERAPCROUTINE,
lpArgToCompletionRoutine: ?*anyopaque,
WakeContext: ?*REASON_CONTEXT,
TolerableDelay: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetWaitableTimer(
hTimer: ?HANDLE,
lpDueTime: ?*const LARGE_INTEGER,
lPeriod: i32,
pfnCompletionRoutine: ?PTIMERAPCROUTINE,
lpArgToCompletionRoutine: ?*anyopaque,
fResume: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CancelWaitableTimer(
hTimer: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateMutexExA(
lpMutexAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u8,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateMutexExW(
lpMutexAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u16,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateEventExA(
lpEventAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u8,
dwFlags: CREATE_EVENT,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateEventExW(
lpEventAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u16,
dwFlags: CREATE_EVENT,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateSemaphoreExW(
lpSemaphoreAttributes: ?*SECURITY_ATTRIBUTES,
lInitialCount: i32,
lMaximumCount: i32,
lpName: ?[*:0]const u16,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateWaitableTimerExW(
lpTimerAttributes: ?*SECURITY_ATTRIBUTES,
lpTimerName: ?[*:0]const u16,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn EnterSynchronizationBarrier(
lpBarrier: ?*RTL_BARRIER,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn InitializeSynchronizationBarrier(
lpBarrier: ?*RTL_BARRIER,
lTotalThreads: i32,
lSpinCount: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn DeleteSynchronizationBarrier(
lpBarrier: ?*RTL_BARRIER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn Sleep(
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "vertdll" fn WaitOnAddress(
// TODO: what to do with BytesParamIndex 2?
Address: ?*anyopaque,
// TODO: what to do with BytesParamIndex 2?
CompareAddress: ?*anyopaque,
AddressSize: usize,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "vertdll" fn WakeByAddressSingle(
Address: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "vertdll" fn WakeByAddressAll(
Address: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn WaitForMultipleObjects(
nCount: u32,
lpHandles: [*]const ?HANDLE,
bWaitAll: BOOL,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateSemaphoreW(
lpSemaphoreAttributes: ?*SECURITY_ATTRIBUTES,
lInitialCount: i32,
lMaximumCount: i32,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateWaitableTimerW(
lpTimerAttributes: ?*SECURITY_ATTRIBUTES,
bManualReset: BOOL,
lpTimerName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InitializeSListHead(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InterlockedPopEntrySList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InterlockedPushEntrySList(
ListHead: ?*SLIST_HEADER,
ListEntry: ?*SLIST_ENTRY,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn InterlockedPushListSListEx(
ListHead: ?*SLIST_HEADER,
List: ?*SLIST_ENTRY,
ListEnd: ?*SLIST_ENTRY,
Count: u32,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn InterlockedFlushSList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn QueryDepthSList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn QueueUserAPC(
pfnAPC: ?PAPCFUNC,
hThread: ?HANDLE,
dwData: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn QueueUserAPC2(
ApcRoutine: ?PAPCFUNC,
Thread: ?HANDLE,
Data: usize,
Flags: QUEUE_USER_APC_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessTimes(
hProcess: ?HANDLE,
lpCreationTime: ?*FILETIME,
lpExitTime: ?*FILETIME,
lpKernelTime: ?*FILETIME,
lpUserTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCurrentProcess(
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCurrentProcessId(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ExitProcess(
uExitCode: u32,
) callconv(@import("std").os.windows.WINAPI) noreturn;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TerminateProcess(
hProcess: ?HANDLE,
uExitCode: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetExitCodeProcess(
hProcess: ?HANDLE,
lpExitCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SwitchToThread(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateThread(
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
dwStackSize: usize,
lpStartAddress: ?LPTHREAD_START_ROUTINE,
lpParameter: ?*anyopaque,
dwCreationFlags: THREAD_CREATION_FLAGS,
lpThreadId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateRemoteThread(
hProcess: ?HANDLE,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
dwStackSize: usize,
lpStartAddress: ?LPTHREAD_START_ROUTINE,
lpParameter: ?*anyopaque,
dwCreationFlags: u32,
lpThreadId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCurrentThread(
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCurrentThreadId(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenThread(
dwDesiredAccess: THREAD_ACCESS_RIGHTS,
bInheritHandle: BOOL,
dwThreadId: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetThreadPriority(
hThread: ?HANDLE,
nPriority: THREAD_PRIORITY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetThreadPriorityBoost(
hThread: ?HANDLE,
bDisablePriorityBoost: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetThreadPriorityBoost(
hThread: ?HANDLE,
pDisablePriorityBoost: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetThreadPriority(
hThread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ExitThread(
dwExitCode: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TerminateThread(
hThread: ?HANDLE,
dwExitCode: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetExitCodeThread(
hThread: ?HANDLE,
lpExitCode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SuspendThread(
hThread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ResumeThread(
hThread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TlsAlloc(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TlsGetValue(
dwTlsIndex: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TlsSetValue(
dwTlsIndex: u32,
lpTlsValue: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TlsFree(
dwTlsIndex: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateProcessA(
lpApplicationName: ?[*:0]const u8,
lpCommandLine: ?PSTR,
lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
bInheritHandles: BOOL,
dwCreationFlags: PROCESS_CREATION_FLAGS,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u8,
lpStartupInfo: ?*STARTUPINFOA,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateProcessW(
lpApplicationName: ?[*:0]const u16,
lpCommandLine: ?PWSTR,
lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
bInheritHandles: BOOL,
dwCreationFlags: PROCESS_CREATION_FLAGS,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u16,
lpStartupInfo: ?*STARTUPINFOW,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetProcessShutdownParameters(
dwLevel: u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessVersion(
ProcessId: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetStartupInfoW(
lpStartupInfo: ?*STARTUPINFOW,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CreateProcessAsUserW(
hToken: ?HANDLE,
lpApplicationName: ?[*:0]const u16,
lpCommandLine: ?PWSTR,
lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
bInheritHandles: BOOL,
dwCreationFlags: u32,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u16,
lpStartupInfo: ?*STARTUPINFOW,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn SetThreadToken(
Thread: ?*?HANDLE,
Token: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn OpenProcessToken(
ProcessHandle: ?HANDLE,
DesiredAccess: TOKEN_ACCESS_MASK,
TokenHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn OpenThreadToken(
ThreadHandle: ?HANDLE,
DesiredAccess: TOKEN_ACCESS_MASK,
OpenAsSelf: BOOL,
TokenHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetPriorityClass(
hProcess: ?HANDLE,
dwPriorityClass: PROCESS_CREATION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetPriorityClass(
hProcess: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetThreadStackGuarantee(
StackSizeInBytes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetProcessId(
Process: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetThreadId(
Thread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FlushProcessWriteBuffers(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetProcessIdOfThread(
Thread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn InitializeProcThreadAttributeList(
// TODO: what to do with BytesParamIndex 3?
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
dwAttributeCount: u32,
dwFlags: u32,
lpSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn DeleteProcThreadAttributeList(
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn UpdateProcThreadAttribute(
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
dwFlags: u32,
Attribute: usize,
// TODO: what to do with BytesParamIndex 4?
lpValue: ?*anyopaque,
cbSize: usize,
// TODO: what to do with BytesParamIndex 4?
lpPreviousValue: ?*anyopaque,
lpReturnSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetProcessDynamicEHContinuationTargets(
Process: ?HANDLE,
NumberOfTargets: u16,
Targets: [*]PROCESS_DYNAMIC_EH_CONTINUATION_TARGET,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetProcessDynamicEnforcedCetCompatibleRanges(
Process: ?HANDLE,
NumberOfRanges: u16,
Ranges: [*]PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetProcessAffinityUpdateMode(
hProcess: ?HANDLE,
dwFlags: PROCESS_AFFINITY_AUTO_UPDATE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryProcessAffinityUpdateMode(
hProcess: ?HANDLE,
lpdwFlags: ?*PROCESS_AFFINITY_AUTO_UPDATE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn CreateRemoteThreadEx(
hProcess: ?HANDLE,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
dwStackSize: usize,
lpStartAddress: ?LPTHREAD_START_ROUTINE,
lpParameter: ?*anyopaque,
dwCreationFlags: u32,
lpAttributeList: ?LPPROC_THREAD_ATTRIBUTE_LIST,
lpThreadId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetCurrentThreadStackLimits(
LowLimit: ?*usize,
HighLimit: ?*usize,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetProcessMitigationPolicy(
hProcess: ?HANDLE,
MitigationPolicy: PROCESS_MITIGATION_POLICY,
// TODO: what to do with BytesParamIndex 3?
lpBuffer: ?*anyopaque,
dwLength: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetProcessMitigationPolicy(
MitigationPolicy: PROCESS_MITIGATION_POLICY,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*anyopaque,
dwLength: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetThreadTimes(
hThread: ?HANDLE,
lpCreationTime: ?*FILETIME,
lpExitTime: ?*FILETIME,
lpKernelTime: ?*FILETIME,
lpUserTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenProcess(
dwDesiredAccess: PROCESS_ACCESS_RIGHTS,
bInheritHandle: BOOL,
dwProcessId: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn IsProcessorFeaturePresent(
ProcessorFeature: PROCESSOR_FEATURE_ID,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetProcessHandleCount(
hProcess: ?HANDLE,
pdwHandleCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetCurrentProcessorNumber(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn SetThreadIdealProcessorEx(
hThread: ?HANDLE,
lpIdealProcessor: ?*PROCESSOR_NUMBER,
lpPreviousIdealProcessor: ?*PROCESSOR_NUMBER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetThreadIdealProcessorEx(
hThread: ?HANDLE,
lpIdealProcessor: ?*PROCESSOR_NUMBER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetCurrentProcessorNumberEx(
ProcNumber: ?*PROCESSOR_NUMBER,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessPriorityBoost(
hProcess: ?HANDLE,
pDisablePriorityBoost: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetProcessPriorityBoost(
hProcess: ?HANDLE,
bDisablePriorityBoost: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetThreadIOPendingFlag(
hThread: ?HANDLE,
lpIOIsPending: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetSystemTimes(
lpIdleTime: ?*FILETIME,
lpKernelTime: ?*FILETIME,
lpUserTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetThreadInformation(
hThread: ?HANDLE,
ThreadInformationClass: THREAD_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
ThreadInformation: ?*anyopaque,
ThreadInformationSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetThreadInformation(
hThread: ?HANDLE,
ThreadInformationClass: THREAD_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
ThreadInformation: ?*anyopaque,
ThreadInformationSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn IsProcessCritical(
hProcess: ?HANDLE,
Critical: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn SetProtectedPolicy(
PolicyGuid: ?*const Guid,
PolicyValue: usize,
OldPolicyValue: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn QueryProtectedPolicy(
PolicyGuid: ?*const Guid,
PolicyValue: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetThreadIdealProcessor(
hThread: ?HANDLE,
dwIdealProcessor: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetProcessInformation(
hProcess: ?HANDLE,
ProcessInformationClass: PROCESS_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
ProcessInformation: ?*anyopaque,
ProcessInformationSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetProcessInformation(
hProcess: ?HANDLE,
ProcessInformationClass: PROCESS_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
ProcessInformation: ?*anyopaque,
ProcessInformationSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetProcessDefaultCpuSets(
Process: ?HANDLE,
CpuSetIds: ?[*]u32,
CpuSetIdCount: u32,
RequiredIdCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetProcessDefaultCpuSets(
Process: ?HANDLE,
CpuSetIds: ?[*]const u32,
CpuSetIdCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetThreadSelectedCpuSets(
Thread: ?HANDLE,
CpuSetIds: ?[*]u32,
CpuSetIdCount: u32,
RequiredIdCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetThreadSelectedCpuSets(
Thread: ?HANDLE,
CpuSetIds: [*]const u32,
CpuSetIdCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CreateProcessAsUserA(
hToken: ?HANDLE,
lpApplicationName: ?[*:0]const u8,
lpCommandLine: ?PSTR,
lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
bInheritHandles: BOOL,
dwCreationFlags: u32,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u8,
lpStartupInfo: ?*STARTUPINFOA,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessShutdownParameters(
lpdwLevel: ?*u32,
lpdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetProcessDefaultCpuSetMasks(
Process: ?HANDLE,
CpuSetMasks: ?[*]GROUP_AFFINITY,
CpuSetMaskCount: u16,
RequiredMaskCount: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetProcessDefaultCpuSetMasks(
Process: ?HANDLE,
CpuSetMasks: ?[*]GROUP_AFFINITY,
CpuSetMaskCount: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetThreadSelectedCpuSetMasks(
Thread: ?HANDLE,
CpuSetMasks: ?[*]GROUP_AFFINITY,
CpuSetMaskCount: u16,
RequiredMaskCount: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetThreadSelectedCpuSetMasks(
Thread: ?HANDLE,
CpuSetMasks: ?[*]GROUP_AFFINITY,
CpuSetMaskCount: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetMachineTypeAttributes(
Machine: u16,
MachineTypeAttributes: ?*MACHINE_ATTRIBUTES,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "KERNEL32" fn SetThreadDescription(
hThread: ?HANDLE,
lpThreadDescription: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "KERNEL32" fn GetThreadDescription(
hThread: ?HANDLE,
ppszThreadDescription: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn QueueUserWorkItem(
Function: ?LPTHREAD_START_ROUTINE,
Context: ?*anyopaque,
Flags: WORKER_THREAD_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn UnregisterWaitEx(
WaitHandle: ?HANDLE,
CompletionEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateTimerQueue(
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateTimerQueueTimer(
phNewTimer: ?*?HANDLE,
TimerQueue: ?HANDLE,
Callback: ?WAITORTIMERCALLBACK,
Parameter: ?*anyopaque,
DueTime: u32,
Period: u32,
Flags: WORKER_THREAD_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ChangeTimerQueueTimer(
TimerQueue: ?HANDLE,
Timer: ?HANDLE,
DueTime: u32,
Period: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeleteTimerQueueTimer(
TimerQueue: ?HANDLE,
Timer: ?HANDLE,
CompletionEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeleteTimerQueue(
TimerQueue: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeleteTimerQueueEx(
TimerQueue: ?HANDLE,
CompletionEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpool(
reserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) PTP_POOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetThreadpoolThreadMaximum(
ptpp: PTP_POOL,
cthrdMost: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetThreadpoolThreadMinimum(
ptpp: PTP_POOL,
cthrdMic: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn SetThreadpoolStackInformation(
ptpp: PTP_POOL,
ptpsi: ?*TP_POOL_STACK_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn QueryThreadpoolStackInformation(
ptpp: PTP_POOL,
ptpsi: ?*TP_POOL_STACK_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpool(
ptpp: PTP_POOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpoolCleanupGroup(
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolCleanupGroupMembers(
ptpcg: isize,
fCancelPendingCallbacks: BOOL,
pvCleanupContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolCleanupGroup(
ptpcg: isize,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetEventWhenCallbackReturns(
pci: ?*TP_CALLBACK_INSTANCE,
evt: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ReleaseSemaphoreWhenCallbackReturns(
pci: ?*TP_CALLBACK_INSTANCE,
sem: ?HANDLE,
crel: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ReleaseMutexWhenCallbackReturns(
pci: ?*TP_CALLBACK_INSTANCE,
mut: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn LeaveCriticalSectionWhenCallbackReturns(
pci: ?*TP_CALLBACK_INSTANCE,
pcs: ?*RTL_CRITICAL_SECTION,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn FreeLibraryWhenCallbackReturns(
pci: ?*TP_CALLBACK_INSTANCE,
mod: ?HINSTANCE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CallbackMayRunLong(
pci: ?*TP_CALLBACK_INSTANCE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn DisassociateCurrentThreadFromCallback(
pci: ?*TP_CALLBACK_INSTANCE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn TrySubmitThreadpoolCallback(
pfns: ?PTP_SIMPLE_CALLBACK,
pv: ?*anyopaque,
pcbe: ?*TP_CALLBACK_ENVIRON_V3,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpoolWork(
pfnwk: ?PTP_WORK_CALLBACK,
pv: ?*anyopaque,
pcbe: ?*TP_CALLBACK_ENVIRON_V3,
) callconv(@import("std").os.windows.WINAPI) ?*TP_WORK;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SubmitThreadpoolWork(
pwk: ?*TP_WORK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WaitForThreadpoolWorkCallbacks(
pwk: ?*TP_WORK,
fCancelPendingCallbacks: BOOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolWork(
pwk: ?*TP_WORK,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpoolTimer(
pfnti: ?PTP_TIMER_CALLBACK,
pv: ?*anyopaque,
pcbe: ?*TP_CALLBACK_ENVIRON_V3,
) callconv(@import("std").os.windows.WINAPI) ?*TP_TIMER;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetThreadpoolTimer(
pti: ?*TP_TIMER,
pftDueTime: ?*FILETIME,
msPeriod: u32,
msWindowLength: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn IsThreadpoolTimerSet(
pti: ?*TP_TIMER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WaitForThreadpoolTimerCallbacks(
pti: ?*TP_TIMER,
fCancelPendingCallbacks: BOOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolTimer(
pti: ?*TP_TIMER,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpoolWait(
pfnwa: ?PTP_WAIT_CALLBACK,
pv: ?*anyopaque,
pcbe: ?*TP_CALLBACK_ENVIRON_V3,
) callconv(@import("std").os.windows.WINAPI) ?*TP_WAIT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetThreadpoolWait(
pwa: ?*TP_WAIT,
h: ?HANDLE,
pftTimeout: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WaitForThreadpoolWaitCallbacks(
pwa: ?*TP_WAIT,
fCancelPendingCallbacks: BOOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolWait(
pwa: ?*TP_WAIT,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateThreadpoolIo(
fl: ?HANDLE,
pfnio: ?PTP_WIN32_IO_CALLBACK,
pv: ?*anyopaque,
pcbe: ?*TP_CALLBACK_ENVIRON_V3,
) callconv(@import("std").os.windows.WINAPI) ?*TP_IO;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn StartThreadpoolIo(
pio: ?*TP_IO,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CancelThreadpoolIo(
pio: ?*TP_IO,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn WaitForThreadpoolIoCallbacks(
pio: ?*TP_IO,
fCancelPendingCallbacks: BOOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CloseThreadpoolIo(
pio: ?*TP_IO,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetThreadpoolTimerEx(
pti: ?*TP_TIMER,
pftDueTime: ?*FILETIME,
msPeriod: u32,
msWindowLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn SetThreadpoolWaitEx(
pwa: ?*TP_WAIT,
h: ?HANDLE,
pftTimeout: ?*FILETIME,
Reserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn IsWow64Process(
hProcess: ?HANDLE,
Wow64Process: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "api-ms-win-core-wow64-l1-1-1" fn Wow64SetThreadDefaultGuestMachine(
Machine: u16,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows10.0.10586'
pub extern "KERNEL32" fn IsWow64Process2(
hProcess: ?HANDLE,
pProcessMachine: ?*u16,
pNativeMachine: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn Wow64SuspendThread(
hThread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn CreatePrivateNamespaceW(
lpPrivateNamespaceAttributes: ?*SECURITY_ATTRIBUTES,
lpBoundaryDescriptor: ?*anyopaque,
lpAliasPrefix: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) NamespaceHandle;
pub extern "KERNEL32" fn OpenPrivateNamespaceW(
lpBoundaryDescriptor: ?*anyopaque,
lpAliasPrefix: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) NamespaceHandle;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ClosePrivateNamespace(
Handle: NamespaceHandle,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "KERNEL32" fn CreateBoundaryDescriptorW(
Name: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BoundaryDescriptorHandle;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn AddSIDToBoundaryDescriptor(
BoundaryDescriptor: ?*?HANDLE,
RequiredSid: ?PSID,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn DeleteBoundaryDescriptor(
BoundaryDescriptor: BoundaryDescriptorHandle,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetNumaHighestNodeNumber(
HighestNodeNumber: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNumaNodeProcessorMaskEx(
Node: u16,
ProcessorMask: ?*GROUP_AFFINITY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetNumaNodeProcessorMask2(
NodeNumber: u16,
ProcessorMasks: ?[*]GROUP_AFFINITY,
ProcessorMaskCount: u16,
RequiredMaskCount: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNumaProximityNodeEx(
ProximityId: u32,
NodeNumber: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetProcessGroupAffinity(
hProcess: ?HANDLE,
GroupCount: ?*u16,
GroupArray: [*:0]u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetThreadGroupAffinity(
hThread: ?HANDLE,
GroupAffinity: ?*GROUP_AFFINITY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn SetThreadGroupAffinity(
hThread: ?HANDLE,
GroupAffinity: ?*const GROUP_AFFINITY,
PreviousGroupAffinity: ?*GROUP_AFFINITY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn AttachThreadInput(
idAttach: u32,
idAttachTo: u32,
fAttach: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn WaitForInputIdle(
hProcess: ?HANDLE,
dwMilliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn GetGuiResources(
hProcess: ?HANDLE,
uiFlags: GET_GUI_RESOURCES_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn IsImmersiveProcess(
hProcess: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn SetProcessRestrictionExemption(
fEnableExemption: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessAffinityMask(
hProcess: ?HANDLE,
lpProcessAffinityMask: ?*usize,
lpSystemAffinityMask: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetProcessAffinityMask(
hProcess: ?HANDLE,
dwProcessAffinityMask: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessIoCounters(
hProcess: ?HANDLE,
lpIoCounters: ?*IO_COUNTERS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SwitchToFiber(
lpFiber: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeleteFiber(
lpFiber: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ConvertFiberToThread(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateFiberEx(
dwStackCommitSize: usize,
dwStackReserveSize: usize,
dwFlags: u32,
lpStartAddress: ?LPFIBER_START_ROUTINE,
lpParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn ConvertThreadToFiberEx(
lpParameter: ?*anyopaque,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateFiber(
dwStackSize: usize,
lpStartAddress: ?LPFIBER_START_ROUTINE,
lpParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ConvertThreadToFiber(
lpParameter: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn CreateUmsCompletionList(
UmsCompletionList: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn DequeueUmsCompletionListItems(
UmsCompletionList: ?*anyopaque,
WaitTimeOut: u32,
UmsThreadList: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetUmsCompletionListEvent(
UmsCompletionList: ?*anyopaque,
UmsCompletionEvent: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn ExecuteUmsThread(
UmsThread: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn UmsThreadYield(
SchedulerParam: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn DeleteUmsCompletionList(
UmsCompletionList: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetCurrentUmsThread(
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNextUmsListItem(
UmsContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn QueryUmsThreadInformation(
UmsThread: ?*anyopaque,
UmsThreadInfoClass: RTL_UMS_THREAD_INFO_CLASS,
// TODO: what to do with BytesParamIndex 3?
UmsThreadInformation: ?*anyopaque,
UmsThreadInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn SetUmsThreadInformation(
UmsThread: ?*anyopaque,
UmsThreadInfoClass: RTL_UMS_THREAD_INFO_CLASS,
UmsThreadInformation: ?*anyopaque,
UmsThreadInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn DeleteUmsThreadContext(
UmsThread: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn CreateUmsThreadContext(
lpUmsThread: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn EnterUmsSchedulingMode(
SchedulerStartupInfo: ?*UMS_SCHEDULER_STARTUP_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetUmsSystemThreadInformation(
ThreadHandle: ?HANDLE,
SystemThreadInfo: ?*UMS_SYSTEM_THREAD_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetThreadAffinityMask(
hThread: ?HANDLE,
dwThreadAffinityMask: usize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetProcessDEPPolicy(
dwFlags: PROCESS_DEP_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetProcessDEPPolicy(
hProcess: ?HANDLE,
lpFlags: ?*u32,
lpPermanent: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn PulseEvent(
hEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn WinExec(
lpCmdLine: ?[*:0]const u8,
uCmdShow: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateSemaphoreA(
lpSemaphoreAttributes: ?*SECURITY_ATTRIBUTES,
lInitialCount: i32,
lMaximumCount: i32,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateSemaphoreExA(
lpSemaphoreAttributes: ?*SECURITY_ATTRIBUTES,
lInitialCount: i32,
lMaximumCount: i32,
lpName: ?[*:0]const u8,
dwFlags: u32,
dwDesiredAccess: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryFullProcessImageNameA(
hProcess: ?HANDLE,
dwFlags: PROCESS_NAME_FORMAT,
lpExeName: [*:0]u8,
lpdwSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn QueryFullProcessImageNameW(
hProcess: ?HANDLE,
dwFlags: PROCESS_NAME_FORMAT,
lpExeName: [*:0]u16,
lpdwSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetStartupInfoA(
lpStartupInfo: ?*STARTUPINFOA,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn CreateProcessWithLogonW(
lpUsername: ?[*:0]const u16,
lpDomain: ?[*:0]const u16,
lpPassword: ?[*:0]const u16,
dwLogonFlags: CREATE_PROCESS_LOGON_FLAGS,
lpApplicationName: ?[*:0]const u16,
lpCommandLine: ?PWSTR,
dwCreationFlags: u32,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u16,
lpStartupInfo: ?*STARTUPINFOW,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn CreateProcessWithTokenW(
hToken: ?HANDLE,
dwLogonFlags: CREATE_PROCESS_LOGON_FLAGS,
lpApplicationName: ?[*:0]const u16,
lpCommandLine: ?PWSTR,
dwCreationFlags: u32,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?[*:0]const u16,
lpStartupInfo: ?*STARTUPINFOW,
lpProcessInformation: ?*PROCESS_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn RegisterWaitForSingleObject(
phNewWaitObject: ?*?HANDLE,
hObject: ?HANDLE,
Callback: ?WAITORTIMERCALLBACK,
Context: ?*anyopaque,
dwMilliseconds: u32,
dwFlags: WORKER_THREAD_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn UnregisterWait(
WaitHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetTimerQueueTimer(
TimerQueue: ?HANDLE,
Callback: ?WAITORTIMERCALLBACK,
Parameter: ?*anyopaque,
DueTime: u32,
Period: u32,
PreferIo: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreatePrivateNamespaceA(
lpPrivateNamespaceAttributes: ?*SECURITY_ATTRIBUTES,
lpBoundaryDescriptor: ?*anyopaque,
lpAliasPrefix: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) NamespaceHandle;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn OpenPrivateNamespaceA(
lpBoundaryDescriptor: ?*anyopaque,
lpAliasPrefix: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) NamespaceHandle;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateBoundaryDescriptorA(
Name: ?[*:0]const u8,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BoundaryDescriptorHandle;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn AddIntegrityLabelToBoundaryDescriptor(
BoundaryDescriptor: ?*?HANDLE,
IntegrityLabel: ?PSID,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetActiveProcessorGroupCount(
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetMaximumProcessorGroupCount(
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetActiveProcessorCount(
GroupNumber: u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetMaximumProcessorCount(
GroupNumber: u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetNumaProcessorNode(
Processor: u8,
NodeNumber: ?*u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNumaNodeNumberFromHandle(
hFile: ?HANDLE,
NodeNumber: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNumaProcessorNodeEx(
Processor: ?*PROCESSOR_NUMBER,
NodeNumber: ?*u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetNumaNodeProcessorMask(
Node: u8,
ProcessorMask: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetNumaAvailableMemoryNode(
Node: u8,
AvailableBytes: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "KERNEL32" fn GetNumaAvailableMemoryNodeEx(
Node: u16,
AvailableBytes: ?*u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetNumaProximityNode(
ProximityId: u32,
NodeNumber: ?*u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "ntdll" fn NtQueryInformationProcess(
ProcessHandle: ?HANDLE,
ProcessInformationClass: PROCESSINFOCLASS,
ProcessInformation: ?*anyopaque,
ProcessInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtQueryInformationThread(
ThreadHandle: ?HANDLE,
ThreadInformationClass: THREADINFOCLASS,
ThreadInformation: ?*anyopaque,
ThreadInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "ntdll" fn NtSetInformationThread(
ThreadHandle: ?HANDLE,
ThreadInformationClass: THREADINFOCLASS,
// TODO: what to do with BytesParamIndex 3?
ThreadInformation: ?*anyopaque,
ThreadInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (16)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const STARTUPINFO = thismodule.STARTUPINFOA;
pub const STARTUPINFOEX = thismodule.STARTUPINFOEXA;
pub const CreateMutex = thismodule.CreateMutexA;
pub const CreateEvent = thismodule.CreateEventA;
pub const OpenEvent = thismodule.OpenEventA;
pub const CreateMutexEx = thismodule.CreateMutexExA;
pub const CreateEventEx = thismodule.CreateEventExA;
pub const CreateSemaphoreEx = thismodule.CreateSemaphoreExA;
pub const CreateSemaphore = thismodule.CreateSemaphoreA;
pub const CreateProcess = thismodule.CreateProcessA;
pub const GetStartupInfo = thismodule.GetStartupInfoA;
pub const CreateProcessAsUser = thismodule.CreateProcessAsUserA;
pub const CreatePrivateNamespace = thismodule.CreatePrivateNamespaceA;
pub const OpenPrivateNamespace = thismodule.OpenPrivateNamespaceA;
pub const CreateBoundaryDescriptor = thismodule.CreateBoundaryDescriptorA;
pub const QueryFullProcessImageName = thismodule.QueryFullProcessImageNameA;
},
.wide => struct {
pub const STARTUPINFO = thismodule.STARTUPINFOW;
pub const STARTUPINFOEX = thismodule.STARTUPINFOEXW;
pub const CreateMutex = thismodule.CreateMutexW;
pub const CreateEvent = thismodule.CreateEventW;
pub const OpenEvent = thismodule.OpenEventW;
pub const CreateMutexEx = thismodule.CreateMutexExW;
pub const CreateEventEx = thismodule.CreateEventExW;
pub const CreateSemaphoreEx = thismodule.CreateSemaphoreExW;
pub const CreateSemaphore = thismodule.CreateSemaphoreW;
pub const CreateProcess = thismodule.CreateProcessW;
pub const GetStartupInfo = thismodule.GetStartupInfoW;
pub const CreateProcessAsUser = thismodule.CreateProcessAsUserW;
pub const CreatePrivateNamespace = thismodule.CreatePrivateNamespaceW;
pub const OpenPrivateNamespace = thismodule.OpenPrivateNamespaceW;
pub const CreateBoundaryDescriptor = thismodule.CreateBoundaryDescriptorW;
pub const QueryFullProcessImageName = thismodule.QueryFullProcessImageNameW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const STARTUPINFO = *opaque{};
pub const STARTUPINFOEX = *opaque{};
pub const CreateMutex = *opaque{};
pub const CreateEvent = *opaque{};
pub const OpenEvent = *opaque{};
pub const CreateMutexEx = *opaque{};
pub const CreateEventEx = *opaque{};
pub const CreateSemaphoreEx = *opaque{};
pub const CreateSemaphore = *opaque{};
pub const CreateProcess = *opaque{};
pub const GetStartupInfo = *opaque{};
pub const CreateProcessAsUser = *opaque{};
pub const CreatePrivateNamespace = *opaque{};
pub const OpenPrivateNamespace = *opaque{};
pub const CreateBoundaryDescriptor = *opaque{};
pub const QueryFullProcessImageName = *opaque{};
} else struct {
pub const STARTUPINFO = @compileError("'STARTUPINFO' requires that UNICODE be set to true or false in the root module");
pub const STARTUPINFOEX = @compileError("'STARTUPINFOEX' requires that UNICODE be set to true or false in the root module");
pub const CreateMutex = @compileError("'CreateMutex' requires that UNICODE be set to true or false in the root module");
pub const CreateEvent = @compileError("'CreateEvent' requires that UNICODE be set to true or false in the root module");
pub const OpenEvent = @compileError("'OpenEvent' requires that UNICODE be set to true or false in the root module");
pub const CreateMutexEx = @compileError("'CreateMutexEx' requires that UNICODE be set to true or false in the root module");
pub const CreateEventEx = @compileError("'CreateEventEx' requires that UNICODE be set to true or false in the root module");
pub const CreateSemaphoreEx = @compileError("'CreateSemaphoreEx' requires that UNICODE be set to true or false in the root module");
pub const CreateSemaphore = @compileError("'CreateSemaphore' requires that UNICODE be set to true or false in the root module");
pub const CreateProcess = @compileError("'CreateProcess' requires that UNICODE be set to true or false in the root module");
pub const GetStartupInfo = @compileError("'GetStartupInfo' requires that UNICODE be set to true or false in the root module");
pub const CreateProcessAsUser = @compileError("'CreateProcessAsUser' requires that UNICODE be set to true or false in the root module");
pub const CreatePrivateNamespace = @compileError("'CreatePrivateNamespace' requires that UNICODE be set to true or false in the root module");
pub const OpenPrivateNamespace = @compileError("'OpenPrivateNamespace' requires that UNICODE be set to true or false in the root module");
pub const CreateBoundaryDescriptor = @compileError("'CreateBoundaryDescriptor' requires that UNICODE be set to true or false in the root module");
pub const QueryFullProcessImageName = @compileError("'QueryFullProcessImageName' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (22)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const FILETIME = @import("../foundation.zig").FILETIME;
const GROUP_AFFINITY = @import("../system/system_information.zig").GROUP_AFFINITY;
const HANDLE = @import("../foundation.zig").HANDLE;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HRESULT = @import("../foundation.zig").HRESULT;
const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER;
const LIST_ENTRY = @import("../system/kernel.zig").LIST_ENTRY;
const NTSTATUS = @import("../foundation.zig").NTSTATUS;
const PAPCFUNC = @import("../foundation.zig").PAPCFUNC;
const PROCESSOR_NUMBER = @import("../system/kernel.zig").PROCESSOR_NUMBER;
const PSID = @import("../foundation.zig").PSID;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RTL_UMS_SCHEDULER_REASON = @import("../system/system_services.zig").RTL_UMS_SCHEDULER_REASON;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
const SLIST_ENTRY = @import("../system/kernel.zig").SLIST_ENTRY;
const SLIST_HEADER = @import("../system/kernel.zig").SLIST_HEADER;
const TOKEN_ACCESS_MASK = @import("../security.zig").TOKEN_ACCESS_MASK;
const UNICODE_STRING = @import("../foundation.zig").UNICODE_STRING;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "LPTHREAD_START_ROUTINE")) { _ = LPTHREAD_START_ROUTINE; }
if (@hasDecl(@This(), "PINIT_ONCE_FN")) { _ = PINIT_ONCE_FN; }
if (@hasDecl(@This(), "PTIMERAPCROUTINE")) { _ = PTIMERAPCROUTINE; }
if (@hasDecl(@This(), "PTP_WIN32_IO_CALLBACK")) { _ = PTP_WIN32_IO_CALLBACK; }
if (@hasDecl(@This(), "PRTL_UMS_SCHEDULER_ENTRY_POINT")) { _ = PRTL_UMS_SCHEDULER_ENTRY_POINT; }
if (@hasDecl(@This(), "WAITORTIMERCALLBACK")) { _ = WAITORTIMERCALLBACK; }
if (@hasDecl(@This(), "PFLS_CALLBACK_FUNCTION")) { _ = PFLS_CALLBACK_FUNCTION; }
if (@hasDecl(@This(), "PTP_SIMPLE_CALLBACK")) { _ = PTP_SIMPLE_CALLBACK; }
if (@hasDecl(@This(), "PTP_CLEANUP_GROUP_CANCEL_CALLBACK")) { _ = PTP_CLEANUP_GROUP_CANCEL_CALLBACK; }
if (@hasDecl(@This(), "PTP_WORK_CALLBACK")) { _ = PTP_WORK_CALLBACK; }
if (@hasDecl(@This(), "PTP_TIMER_CALLBACK")) { _ = PTP_TIMER_CALLBACK; }
if (@hasDecl(@This(), "PTP_WAIT_CALLBACK")) { _ = PTP_WAIT_CALLBACK; }
if (@hasDecl(@This(), "LPFIBER_START_ROUTINE")) { _ = LPFIBER_START_ROUTINE; }
if (@hasDecl(@This(), "PPS_POST_PROCESS_INIT_ROUTINE")) { _ = PPS_POST_PROCESS_INIT_ROUTINE; }
@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/system/threading.zig
|
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const L = std.unicode.utf8ToUtf16LeStringLiteral;
const zwin32 = @import("zwin32");
const w = zwin32.base;
const d3d12 = zwin32.d3d12;
const hrPanic = zwin32.hrPanic;
const hrPanicOnFail = zwin32.hrPanicOnFail;
const zd3d12 = @import("zd3d12");
const common = @import("common");
const c = common.c;
const GuiRenderer = common.GuiRenderer;
const zm = @import("zmath");
pub export const D3D12SDKVersion: u32 = 4;
pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\";
const content_dir = @import("build_options").content_dir;
const window_name = "zig-gamedev: rasterization";
const window_width = 1920;
const window_height = 1080;
// Compute shader group size in 'csClearPixels' and 'csDrawPixels' (rasterization.hlsl).
const compute_group_size = 32;
const Pso_DrawConst = struct {
object_to_world: [16]f32,
};
const Pso_FrameConst = struct {
world_to_clip: [16]f32,
camera_position: [3]f32,
};
const Pso_Pixel = struct {
position: [2]f32,
color: [3]f32,
};
const Pso_Vertex = struct {
position: [3]f32,
normal: [3]f32,
texcoord: [2]f32,
tangent: [4]f32,
};
const DemoState = struct {
gctx: zd3d12.GraphicsContext,
guictx: GuiRenderer,
frame_stats: common.FrameStats,
z_pre_pass_pso: zd3d12.PipelineHandle,
record_pixels_pso: zd3d12.PipelineHandle,
draw_pixels_pso: zd3d12.PipelineHandle,
clear_pixels_pso: zd3d12.PipelineHandle,
draw_mesh_pso: zd3d12.PipelineHandle,
vertex_buffer: zd3d12.ResourceHandle,
index_buffer: zd3d12.ResourceHandle,
depth_texture: zd3d12.ResourceHandle,
depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE,
pixel_buffer: zd3d12.ResourceHandle,
pixel_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
pixel_buffer_uav: d3d12.CPU_DESCRIPTOR_HANDLE,
pixel_texture: zd3d12.ResourceHandle,
pixel_texture_uav: d3d12.CPU_DESCRIPTOR_HANDLE,
pixel_texture_rtv: d3d12.CPU_DESCRIPTOR_HANDLE,
mesh_num_vertices: u32,
mesh_num_indices: u32,
draw_wireframe: bool,
num_pixel_groups: u32,
raster_speed: i32,
mesh_textures: [4]zd3d12.ResourceHandle,
camera: struct {
position: [3]f32,
forward: [3]f32,
pitch: f32,
yaw: f32,
},
mouse: struct {
cursor_prev_x: i32,
cursor_prev_y: i32,
},
};
fn init(gpa_allocator: std.mem.Allocator) DemoState {
const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable;
var arena_allocator_state = std.heap.ArenaAllocator.init(gpa_allocator);
defer arena_allocator_state.deinit();
const arena_allocator = arena_allocator_state.allocator();
var gctx = zd3d12.GraphicsContext.init(gpa_allocator, window);
// Enable vsync.
gctx.present_flags = 0;
gctx.present_interval = 1;
const z_pre_pass_pso = blk: {
const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{
d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0),
};
var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault();
pso_desc.InputLayout = .{
.pInputElementDescs = &input_layout_desc,
.NumElements = input_layout_desc.len,
};
pso_desc.DSVFormat = .D32_FLOAT;
pso_desc.PrimitiveTopologyType = .TRIANGLE;
pso_desc.RasterizerState.CullMode = .NONE;
break :blk gctx.createGraphicsShaderPipeline(
arena_allocator,
&pso_desc,
content_dir ++ "shaders/draw_mesh.vs.cso",
null,
);
};
const record_pixels_pso = blk: {
const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{
d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0),
d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0),
d3d12.INPUT_ELEMENT_DESC.init("_Texcoord", 0, .R32G32_FLOAT, 0, 24, .PER_VERTEX_DATA, 0),
d3d12.INPUT_ELEMENT_DESC.init("_Tangent", 0, .R32G32B32A32_FLOAT, 0, 32, .PER_VERTEX_DATA, 0),
};
var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault();
pso_desc.InputLayout = .{
.pInputElementDescs = &input_layout_desc,
.NumElements = input_layout_desc.len,
};
pso_desc.DSVFormat = .D32_FLOAT;
pso_desc.DepthStencilState.DepthFunc = .LESS_EQUAL;
pso_desc.DepthStencilState.DepthWriteMask = .ZERO;
pso_desc.PrimitiveTopologyType = .TRIANGLE;
pso_desc.RasterizerState.CullMode = .NONE;
break :blk gctx.createGraphicsShaderPipeline(
arena_allocator,
&pso_desc,
content_dir ++ "shaders/record_pixels.vs.cso",
content_dir ++ "shaders/record_pixels.ps.cso",
);
};
const draw_mesh_pso = blk: {
const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{
d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0),
};
var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault();
pso_desc.InputLayout = .{
.pInputElementDescs = &input_layout_desc,
.NumElements = input_layout_desc.len,
};
pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM;
pso_desc.NumRenderTargets = 1;
pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf;
pso_desc.DSVFormat = .D32_FLOAT;
pso_desc.PrimitiveTopologyType = .TRIANGLE;
pso_desc.RasterizerState.FillMode = .WIREFRAME;
pso_desc.RasterizerState.CullMode = .NONE;
pso_desc.DepthStencilState.DepthFunc = .LESS_EQUAL;
pso_desc.DepthStencilState.DepthWriteMask = .ZERO;
pso_desc.RasterizerState.AntialiasedLineEnable = w.TRUE;
break :blk gctx.createGraphicsShaderPipeline(
arena_allocator,
&pso_desc,
content_dir ++ "shaders/draw_mesh.vs.cso",
content_dir ++ "shaders/draw_mesh.ps.cso",
);
};
const draw_pixels_pso = gctx.createComputeShaderPipeline(
arena_allocator,
&d3d12.COMPUTE_PIPELINE_STATE_DESC.initDefault(),
content_dir ++ "shaders/draw_pixels.cs.cso",
);
const clear_pixels_pso = gctx.createComputeShaderPipeline(
arena_allocator,
&d3d12.COMPUTE_PIPELINE_STATE_DESC.initDefault(),
content_dir ++ "shaders/clear_pixels.cs.cso",
);
var mesh_indices = std.ArrayList(u32).init(arena_allocator);
var mesh_positions = std.ArrayList([3]f32).init(arena_allocator);
var mesh_normals = std.ArrayList([3]f32).init(arena_allocator);
var mesh_texcoords = std.ArrayList([2]f32).init(arena_allocator);
var mesh_tangents = std.ArrayList([4]f32).init(arena_allocator);
{
const data = common.parseAndLoadGltfFile(content_dir ++ "SciFiHelmet/SciFiHelmet.gltf");
defer c.cgltf_free(data);
common.appendMeshPrimitive(
data,
0,
0,
&mesh_indices,
&mesh_positions,
&mesh_normals,
&mesh_texcoords,
&mesh_tangents,
);
}
const mesh_num_indices = @intCast(u32, mesh_indices.items.len);
const mesh_num_vertices = @intCast(u32, mesh_positions.items.len);
const vertex_buffer = gctx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_NONE,
&d3d12.RESOURCE_DESC.initBuffer(mesh_num_vertices * @sizeOf(Pso_Vertex)),
d3d12.RESOURCE_STATE_COPY_DEST,
null,
) catch |err| hrPanic(err);
const index_buffer = gctx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_NONE,
&d3d12.RESOURCE_DESC.initBuffer(mesh_num_indices * @sizeOf(u32)),
d3d12.RESOURCE_STATE_COPY_DEST,
null,
) catch |err| hrPanic(err);
const depth_texture = gctx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_NONE,
&blk: {
var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, gctx.viewport_width, gctx.viewport_height, 1);
desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE;
break :blk desc;
},
d3d12.RESOURCE_STATE_DEPTH_WRITE,
&d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0),
) catch |err| hrPanic(err);
const depth_texture_dsv = gctx.allocateCpuDescriptors(.DSV, 1);
gctx.device.CreateDepthStencilView(
gctx.lookupResource(depth_texture).?, // Get the D3D12 resource from a handle.
null,
depth_texture_dsv,
);
const pixel_buffer = gctx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_ALLOW_SHADER_ATOMICS,
&blk: {
var desc = d3d12.RESOURCE_DESC.initBuffer(
(gctx.viewport_width * gctx.viewport_height + 1) * @sizeOf(Pso_Pixel),
);
desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
break :blk desc;
},
d3d12.RESOURCE_STATE_UNORDERED_ACCESS,
null,
) catch |err| hrPanic(err);
const pixel_buffer_srv = gctx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
const pixel_buffer_uav = gctx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
gctx.device.CreateShaderResourceView(
gctx.lookupResource(pixel_buffer).?,
&d3d12.SHADER_RESOURCE_VIEW_DESC.initStructuredBuffer(
1, // FirstElement
gctx.viewport_width * gctx.viewport_height, // NumElements
@sizeOf(Pso_Pixel), // StructureByteStride
),
pixel_buffer_srv,
);
gctx.device.CreateUnorderedAccessView(
gctx.lookupResource(pixel_buffer).?,
gctx.lookupResource(pixel_buffer).?,
&d3d12.UNORDERED_ACCESS_VIEW_DESC.initStructuredBuffer(
1,
gctx.viewport_width * gctx.viewport_height,
@sizeOf(Pso_Pixel),
0, // CounterOffsetInBytes
),
pixel_buffer_uav,
);
const pixel_texture = gctx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_NONE,
&blk: {
var desc = d3d12.RESOURCE_DESC.initTex2d(.R8G8B8A8_UNORM, gctx.viewport_width, gctx.viewport_height, 1);
desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | d3d12.RESOURCE_FLAG_ALLOW_RENDER_TARGET;
break :blk desc;
},
d3d12.RESOURCE_STATE_UNORDERED_ACCESS,
&d3d12.CLEAR_VALUE.initColor(.R8G8B8A8_UNORM, &.{ 0.2, 0.4, 0.8, 1.0 }),
) catch |err| hrPanic(err);
const pixel_texture_uav = gctx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
gctx.device.CreateUnorderedAccessView(
gctx.lookupResource(pixel_texture).?,
null,
null,
pixel_texture_uav,
);
const pixel_texture_rtv = gctx.allocateCpuDescriptors(.RTV, 1);
gctx.device.CreateRenderTargetView(
gctx.lookupResource(pixel_texture).?,
null,
pixel_texture_rtv,
);
gctx.beginFrame();
var guictx = GuiRenderer.init(arena_allocator, &gctx, 1, content_dir);
const mesh_textures = [_]zd3d12.ResourceHandle{
gctx.createAndUploadTex2dFromFile(
content_dir ++ "SciFiHelmet/SciFiHelmet_AmbientOcclusion.png",
.{},
) catch |err| hrPanic(err),
gctx.createAndUploadTex2dFromFile(
content_dir ++ "SciFiHelmet/SciFiHelmet_BaseColor.png",
.{},
) catch |err| hrPanic(err),
gctx.createAndUploadTex2dFromFile(
content_dir ++ "SciFiHelmet/SciFiHelmet_MetallicRoughness.png",
.{},
) catch |err| hrPanic(err),
gctx.createAndUploadTex2dFromFile(
content_dir ++ "SciFiHelmet/SciFiHelmet_Normal.png",
.{},
) catch |err| hrPanic(err),
};
for (mesh_textures) |texture| {
const descriptor = gctx.allocatePersistentGpuDescriptors(1);
gctx.device.CreateShaderResourceView(gctx.lookupResource(texture).?, null, descriptor.cpu_handle);
}
// Generate mipmaps.
{
var mipgen = zd3d12.MipmapGenerator.init(arena_allocator, &gctx, .R8G8B8A8_UNORM, content_dir);
defer mipgen.deinit(&gctx);
for (mesh_textures) |texture| {
mipgen.generateMipmaps(&gctx, texture);
gctx.addTransitionBarrier(texture, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
}
gctx.finishGpuCommands(); // Wait for the GPU so that we can release the generator.
}
// Fill vertex buffer with vertex data.
{
const verts = gctx.allocateUploadBufferRegion(Pso_Vertex, mesh_num_vertices);
for (mesh_positions.items) |_, i| {
verts.cpu_slice[i].position = mesh_positions.items[i];
verts.cpu_slice[i].normal = mesh_normals.items[i];
verts.cpu_slice[i].texcoord = mesh_texcoords.items[i];
verts.cpu_slice[i].tangent = mesh_tangents.items[i];
}
gctx.cmdlist.CopyBufferRegion(
gctx.lookupResource(vertex_buffer).?,
0,
verts.buffer,
verts.buffer_offset,
verts.cpu_slice.len * @sizeOf(@TypeOf(verts.cpu_slice[0])),
);
}
// Fill index buffer with index data.
{
const indices = gctx.allocateUploadBufferRegion(u32, mesh_num_indices);
for (mesh_indices.items) |_, i| {
indices.cpu_slice[i] = mesh_indices.items[i];
}
gctx.cmdlist.CopyBufferRegion(
gctx.lookupResource(index_buffer).?,
0,
indices.buffer,
indices.buffer_offset,
indices.cpu_slice.len * @sizeOf(@TypeOf(indices.cpu_slice[0])),
);
}
gctx.addTransitionBarrier(vertex_buffer, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
gctx.addTransitionBarrier(index_buffer, d3d12.RESOURCE_STATE_INDEX_BUFFER);
gctx.flushResourceBarriers();
gctx.endFrame();
gctx.finishGpuCommands();
return .{
.gctx = gctx,
.guictx = guictx,
.frame_stats = common.FrameStats.init(),
.z_pre_pass_pso = z_pre_pass_pso,
.record_pixels_pso = record_pixels_pso,
.draw_pixels_pso = draw_pixels_pso,
.clear_pixels_pso = clear_pixels_pso,
.draw_mesh_pso = draw_mesh_pso,
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.depth_texture = depth_texture,
.depth_texture_dsv = depth_texture_dsv,
.pixel_buffer = pixel_buffer,
.pixel_buffer_srv = pixel_buffer_srv,
.pixel_buffer_uav = pixel_buffer_uav,
.pixel_texture = pixel_texture,
.pixel_texture_uav = pixel_texture_uav,
.pixel_texture_rtv = pixel_texture_rtv,
.mesh_textures = mesh_textures,
.mesh_num_vertices = mesh_num_vertices,
.mesh_num_indices = mesh_num_indices,
.draw_wireframe = true,
.num_pixel_groups = 0,
.raster_speed = 4,
.camera = .{
.position = [3]f32{ 3.0, 0.0, -3.0 },
.forward = [3]f32{ 0.0, 0.0, 0.0 },
.pitch = 0.0 * math.pi,
.yaw = -0.25 * math.pi,
},
.mouse = .{
.cursor_prev_x = 0,
.cursor_prev_y = 0,
},
};
}
fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void {
demo.gctx.finishGpuCommands();
demo.guictx.deinit(&demo.gctx);
demo.gctx.deinit(gpa_allocator);
common.deinitWindow(gpa_allocator);
demo.* = undefined;
}
fn update(demo: *DemoState) void {
demo.frame_stats.update(demo.gctx.window, window_name);
const dt = demo.frame_stats.delta_time;
common.newImGuiFrame(dt);
c.igSetNextWindowPos(
c.ImVec2{ .x = @intToFloat(f32, demo.gctx.viewport_width) - 600.0 - 20, .y = 20.0 },
c.ImGuiCond_FirstUseEver,
c.ImVec2{ .x = 0.0, .y = 0.0 },
);
c.igSetNextWindowSize(.{ .x = 600.0, .y = -1 }, c.ImGuiCond_Always);
_ = c.igBegin(
"Demo Settings",
null,
c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoSavedSettings,
);
if (demo.draw_wireframe) {
c.igBulletText("", "");
c.igSameLine(0, -1);
c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "Right Mouse Button + Drag", "");
c.igSameLine(0, -1);
c.igText(" : rotate camera", "");
c.igBulletText("", "");
c.igSameLine(0, -1);
c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "W, A, S, D", "");
c.igSameLine(0, -1);
c.igText(" : move camera", "");
}
if (c.igButton(
if (demo.draw_wireframe) " Freeze & Rasterize " else " Clear & Unfreeze ",
.{ .x = 0, .y = 0 },
)) {
demo.draw_wireframe = !demo.draw_wireframe;
demo.num_pixel_groups = 0;
}
if (!demo.draw_wireframe) {
_ = c.igSliderInt("Rasterization speed", &demo.raster_speed, 4, 32, null, c.ImGuiSliderFlags_None);
}
c.igEnd();
if (demo.draw_wireframe) {
// Handle camera rotation with mouse.
{
var pos: w.POINT = undefined;
_ = w.GetCursorPos(&pos);
const delta_x = @intToFloat(f32, pos.x) - @intToFloat(f32, demo.mouse.cursor_prev_x);
const delta_y = @intToFloat(f32, pos.y) - @intToFloat(f32, demo.mouse.cursor_prev_y);
demo.mouse.cursor_prev_x = pos.x;
demo.mouse.cursor_prev_y = pos.y;
if (w.GetAsyncKeyState(w.VK_RBUTTON) < 0) {
demo.camera.pitch += 0.0025 * delta_y;
demo.camera.yaw += 0.0025 * delta_x;
demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi);
demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi);
demo.camera.yaw = zm.modAngle(demo.camera.yaw);
}
}
// Handle camera movement with 'WASD' keys.
{
const speed = zm.f32x4s(1.0);
const delta_time = zm.f32x4s(demo.frame_stats.delta_time);
const transform = zm.mul(zm.rotationX(demo.camera.pitch), zm.rotationY(demo.camera.yaw));
var forward = zm.normalize3(zm.mul(zm.f32x4(0.0, 0.0, 1.0, 0.0), transform));
zm.store(demo.camera.forward[0..], forward, 3);
const right = speed * delta_time * zm.normalize3(zm.cross3(zm.f32x4(0.0, 1.0, 0.0, 0.0), forward));
forward = speed * delta_time * forward;
var cpos = zm.load(demo.camera.position[0..], zm.Vec, 3);
if (w.GetAsyncKeyState('W') < 0) {
cpos += forward;
} else if (w.GetAsyncKeyState('S') < 0) {
cpos -= forward;
}
if (w.GetAsyncKeyState('D') < 0) {
cpos += right;
} else if (w.GetAsyncKeyState('A') < 0) {
cpos -= right;
}
zm.store(demo.camera.position[0..], cpos, 3);
}
}
}
fn draw(demo: *DemoState) void {
var gctx = &demo.gctx;
const cam_world_to_view = zm.lookToLh(
zm.load(demo.camera.position[0..], zm.Vec, 3),
zm.load(demo.camera.forward[0..], zm.Vec, 3),
zm.f32x4(0.0, 1.0, 0.0, 0.0),
);
const cam_view_to_clip = zm.perspectiveFovLh(
0.25 * math.pi,
@intToFloat(f32, gctx.viewport_width) / @intToFloat(f32, gctx.viewport_height),
0.01,
200.0,
);
const cam_world_to_clip = zm.mul(cam_world_to_view, cam_view_to_clip);
gctx.beginFrame();
// Set input assembler (IA) state.
gctx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST);
gctx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{
.BufferLocation = gctx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(),
.SizeInBytes = demo.mesh_num_vertices * @sizeOf(Pso_Vertex),
.StrideInBytes = @sizeOf(Pso_Vertex),
}});
gctx.cmdlist.IASetIndexBuffer(&.{
.BufferLocation = gctx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(),
.SizeInBytes = demo.mesh_num_indices * @sizeOf(u32),
.Format = .R32_UINT,
});
if (demo.draw_wireframe) {
gctx.cmdlist.OMSetRenderTargets(
0,
null,
w.TRUE,
&demo.depth_texture_dsv,
);
gctx.cmdlist.ClearDepthStencilView(demo.depth_texture_dsv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null);
//
// Z pre pass for wireframe mesh.
//
gctx.setCurrentPipeline(demo.z_pre_pass_pso);
// Upload per-frame constant data (camera xform).
{
const mem = gctx.allocateUploadMemory(Pso_FrameConst, 1);
zm.storeMat(mem.cpu_slice[0].world_to_clip[0..], zm.transpose(cam_world_to_clip));
gctx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base);
}
// Upload per-draw constant data (object to world xform) and draw.
{
const object_to_world = zm.translation(0.0, 0.0, 0.0);
const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1);
zm.storeMat(mem.cpu_slice[0].object_to_world[0..], zm.transpose(object_to_world));
gctx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base);
}
gctx.cmdlist.DrawIndexedInstanced(demo.mesh_num_indices, 1, 0, 0, 0);
gctx.addTransitionBarrier(demo.pixel_texture, d3d12.RESOURCE_STATE_RENDER_TARGET);
gctx.flushResourceBarriers();
gctx.cmdlist.OMSetRenderTargets(
1,
&[_]d3d12.CPU_DESCRIPTOR_HANDLE{demo.pixel_texture_rtv},
w.TRUE,
&demo.depth_texture_dsv,
);
gctx.cmdlist.ClearRenderTargetView(
demo.pixel_texture_rtv,
&[4]f32{ 0.2, 0.4, 0.8, 1.0 },
0,
null,
);
//
// Draw wireframe mesh.
//
gctx.setCurrentPipeline(demo.draw_mesh_pso);
// Upload per-frame constant data (camera xform).
{
const mem = gctx.allocateUploadMemory(Pso_FrameConst, 1);
zm.storeMat(mem.cpu_slice[0].world_to_clip[0..], zm.transpose(cam_world_to_clip));
gctx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base);
}
// Upload per-draw constant data (object to world xform) and draw.
{
const object_to_world = zm.translation(0.0, 0.0, 0.0);
const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1);
zm.storeMat(mem.cpu_slice[0].object_to_world[0..], zm.transpose(object_to_world));
gctx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base);
}
gctx.cmdlist.DrawIndexedInstanced(demo.mesh_num_indices, 1, 0, 0, 0);
} else {
// Check if we need to regenerate our pixel buffer.
if (demo.num_pixel_groups == 0) {
// Reset pixel buffer atomic counter.
{
const param = [_]d3d12.WRITEBUFFERIMMEDIATE_PARAMETER{.{
.Dest = gctx.lookupResource(demo.pixel_buffer).?.GetGPUVirtualAddress(),
.Value = 0,
}};
gctx.addTransitionBarrier(demo.pixel_buffer, d3d12.RESOURCE_STATE_COPY_DEST);
gctx.flushResourceBarriers();
gctx.cmdlist.WriteBufferImmediate(param.len, ¶m, null);
gctx.addTransitionBarrier(demo.pixel_buffer, d3d12.RESOURCE_STATE_UNORDERED_ACCESS);
gctx.flushResourceBarriers();
}
// Clear pixel buffer.
gctx.setCurrentPipeline(demo.clear_pixels_pso);
gctx.cmdlist.SetComputeRootDescriptorTable(
0,
gctx.copyDescriptorsToGpuHeap(1, demo.pixel_buffer_uav),
);
gctx.cmdlist.Dispatch(gctx.viewport_width * gctx.viewport_height / compute_group_size, 1, 1);
gctx.cmdlist.ResourceBarrier(
1,
&[_]d3d12.RESOURCE_BARRIER{
d3d12.RESOURCE_BARRIER.initUav(gctx.lookupResource(demo.pixel_buffer).?),
},
);
gctx.cmdlist.OMSetRenderTargets(0, null, w.TRUE, &demo.depth_texture_dsv);
gctx.cmdlist.ClearDepthStencilView(demo.depth_texture_dsv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null);
//
// Z pre pass.
//
gctx.setCurrentPipeline(demo.z_pre_pass_pso);
// Upload per-frame constant data (camera xform).
{
const mem = gctx.allocateUploadMemory(Pso_FrameConst, 1);
zm.storeMat(mem.cpu_slice[0].world_to_clip[0..], zm.transpose(cam_world_to_clip));
gctx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base);
}
// Upload per-draw constant data (object to world xform) and draw.
{
const object_to_world = zm.translation(0.0, 0.0, 0.0);
const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1);
zm.storeMat(mem.cpu_slice[0].object_to_world[0..], zm.transpose(object_to_world));
gctx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base);
}
gctx.cmdlist.DrawIndexedInstanced(demo.mesh_num_indices, 1, 0, 0, 0);
//
// Record pixels to linear pixel buffer
//
gctx.setCurrentPipeline(demo.record_pixels_pso);
// Bind pixel buffer UAV.
gctx.cmdlist.SetGraphicsRootDescriptorTable(
2,
gctx.copyDescriptorsToGpuHeap(1, demo.pixel_buffer_uav),
);
// Upload per-frame constant data (camera xform).
{
const mem = gctx.allocateUploadMemory(Pso_FrameConst, 1);
zm.storeMat(mem.cpu_slice[0].world_to_clip[0..], zm.transpose(cam_world_to_clip));
mem.cpu_slice[0].camera_position = demo.camera.position;
gctx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base);
}
// Upload per-draw constant data (object to world xform) and draw.
{
const object_to_world = zm.translation(0.0, 0.0, 0.0);
const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1);
zm.storeMat(mem.cpu_slice[0].object_to_world[0..], zm.transpose(object_to_world));
gctx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base);
}
gctx.cmdlist.DrawIndexedInstanced(demo.mesh_num_indices, 1, 0, 0, 0);
}
// Increase number of drawn pixels to achieve animation effect.
demo.num_pixel_groups += @intCast(u32, demo.raster_speed);
if (demo.num_pixel_groups > gctx.viewport_width * gctx.viewport_height / compute_group_size) {
demo.num_pixel_groups = gctx.viewport_width * gctx.viewport_height / compute_group_size;
}
gctx.addTransitionBarrier(demo.pixel_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
gctx.addTransitionBarrier(demo.pixel_texture, d3d12.RESOURCE_STATE_UNORDERED_ACCESS);
gctx.flushResourceBarriers();
//
// Draw pixels to the pixel texture.
//
gctx.setCurrentPipeline(demo.draw_pixels_pso);
gctx.cmdlist.SetComputeRootDescriptorTable(
0,
blk: {
const table = gctx.copyDescriptorsToGpuHeap(1, demo.pixel_buffer_srv);
_ = gctx.copyDescriptorsToGpuHeap(1, demo.pixel_texture_uav);
break :blk table;
},
);
gctx.cmdlist.Dispatch(demo.num_pixel_groups, 1, 1);
}
const back_buffer = gctx.getBackBuffer();
// Copy pixel texture to the back buffer.
gctx.addTransitionBarrier(demo.pixel_texture, d3d12.RESOURCE_STATE_COPY_SOURCE);
gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_COPY_DEST);
gctx.flushResourceBarriers();
gctx.cmdlist.CopyResource(
gctx.lookupResource(back_buffer.resource_handle).?,
gctx.lookupResource(demo.pixel_texture).?,
);
gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET);
gctx.addTransitionBarrier(demo.pixel_texture, d3d12.RESOURCE_STATE_UNORDERED_ACCESS);
gctx.flushResourceBarriers();
// Set back buffer as a render target (for UI and Direct2D).
gctx.cmdlist.OMSetRenderTargets(
1,
&[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle},
w.TRUE,
null,
);
demo.guictx.draw(gctx);
gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT);
gctx.flushResourceBarriers();
gctx.endFrame();
}
pub fn main() !void {
common.init();
defer common.deinit();
var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const leaked = gpa_allocator_state.deinit();
std.debug.assert(leaked == false);
}
const gpa_allocator = gpa_allocator_state.allocator();
var demo = init(gpa_allocator);
defer deinit(&demo, gpa_allocator);
while (true) {
var message = std.mem.zeroes(w.user32.MSG);
const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch false;
if (has_message) {
_ = w.user32.translateMessage(&message);
_ = w.user32.dispatchMessageA(&message);
if (message.message == w.user32.WM_QUIT) {
break;
}
} else {
update(&demo);
draw(&demo);
}
}
}
|
samples/rasterization/src/rasterization.zig
|
const std = @import("std");
const max_line_length = 60;
const im = 139968;
const ia = 3877;
const ic = 29573;
var seed: u32 = 42;
fn nextRandom(max: f64) f64 {
seed = (seed * ia + ic) % im;
return max * @intToFloat(f64, seed) / @intToFloat(f64, im);
}
const AminoAcid = struct {
l: u8,
p: f64,
};
fn repeatAndWrap(out: anytype, comptime sequence: []const u8, count: usize) void {
var padded_sequence: [sequence.len + max_line_length]u8 = undefined;
for (padded_sequence) |*e, i| {
e.* = sequence[i % sequence.len];
}
var off: usize = 0;
var idx: usize = 0;
while (idx < count) {
const rem = count - idx;
const line_length = std.math.min(@as(usize, max_line_length), rem);
_ = out.write(padded_sequence[off .. off + line_length]) catch unreachable;
_ = out.writeByte('\n') catch unreachable;
off += line_length;
if (off > sequence.len) {
off -= sequence.len;
}
idx += line_length;
}
}
fn generateAndWrap(out: anytype, comptime nucleotides: []const AminoAcid, count: usize) void {
var cum_prob: f64 = 0;
var cum_prob_total: [nucleotides.len]f64 = undefined;
for (nucleotides) |n, i| {
cum_prob += n.p;
cum_prob_total[i] = cum_prob * im;
}
var line: [max_line_length + 1]u8 = undefined;
line[max_line_length] = '\n';
var idx: usize = 0;
while (idx < count) {
const rem = count - idx;
const line_length = std.math.min(@as(usize, max_line_length), rem);
for (line[0..line_length]) |*col| {
const r = nextRandom(im);
var c: usize = 0;
for (cum_prob_total) |n| {
if (n <= r) {
c += 1;
}
}
col.* = nucleotides[c].l;
}
line[line_length] = '\n';
_ = out.write(line[0 .. line_length + 1]) catch unreachable;
idx += line_length;
}
}
var buffer: [256]u8 = undefined;
var fixed_allocator = std.heap.FixedBufferAllocator.init(buffer[0..]);
var allocator = &fixed_allocator.allocator;
pub fn main() !void {
var buffered_stdout = std.io.bufferedWriter(std.io.getStdOut().writer());
defer buffered_stdout.flush() catch unreachable;
const stdout = buffered_stdout.writer();
const n = try get_n();
const homo_sapiens_alu = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTC" ++
"AGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCG" ++
"TGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGG" ++
"AGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
_ = try stdout.write(">ONE Homo sapiens alu\n");
repeatAndWrap(stdout, homo_sapiens_alu, 2 * n);
const iub_nucleotide_info = &[_]AminoAcid{
AminoAcid{ .l = 'a', .p = 0.27 },
AminoAcid{ .l = 'c', .p = 0.12 },
AminoAcid{ .l = 'g', .p = 0.12 },
AminoAcid{ .l = 't', .p = 0.27 },
AminoAcid{ .l = 'B', .p = 0.02 },
AminoAcid{ .l = 'D', .p = 0.02 },
AminoAcid{ .l = 'H', .p = 0.02 },
AminoAcid{ .l = 'K', .p = 0.02 },
AminoAcid{ .l = 'M', .p = 0.02 },
AminoAcid{ .l = 'N', .p = 0.02 },
AminoAcid{ .l = 'R', .p = 0.02 },
AminoAcid{ .l = 'S', .p = 0.02 },
AminoAcid{ .l = 'V', .p = 0.02 },
AminoAcid{ .l = 'W', .p = 0.02 },
AminoAcid{ .l = 'Y', .p = 0.02 },
};
_ = try stdout.write(">TWO IUB ambiguity codes\n");
generateAndWrap(stdout, iub_nucleotide_info, 3 * n);
const homo_sapien_nucleotide_info = &[_]AminoAcid{
AminoAcid{ .l = 'a', .p = 0.3029549426680 },
AminoAcid{ .l = 'c', .p = 0.1979883004921 },
AminoAcid{ .l = 'g', .p = 0.1975473066391 },
AminoAcid{ .l = 't', .p = 0.3015094502008 },
};
_ = try stdout.write(">THREE Homo sapiens frequency\n");
generateAndWrap(stdout, homo_sapien_nucleotide_info, 5 * n);
}
fn get_n() !usize {
var arg_it = std.process.args();
_ = arg_it.skip();
const arg = arg_it.next() orelse return 10;
return try std.fmt.parseInt(u64, arg, 10);
}
|
bench/algorithm/fasta/1.zig
|
const std = @import("std");
const builtin = @import("builtin");
const arch = builtin.cpu.arch;
const os = builtin.os.tag;
// Ported from llvm-project d32170dbd5b0d54436537b6b75beaf44324e0c28
// The compiler generates calls to __clear_cache() when creating
// trampoline functions on the stack for use with nested functions.
// It is expected to invalidate the instruction cache for the
// specified range.
pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
const x86 = switch (arch) {
.i386, .x86_64 => true,
else => false,
};
const arm32 = switch (arch) {
.arm, .armeb, .thumb, .thumbeb => true,
else => false,
};
const arm64 = switch (arch) {
.aarch64, .aarch64_be, .aarch64_32 => true,
else => false,
};
const mips = switch (arch) {
.mips, .mipsel, .mips64, .mips64el => true,
else => false,
};
const riscv = switch (arch) {
.riscv32, .riscv64 => true,
else => false,
};
const powerpc64 = switch (arch) {
.powerpc64, .powerpc64le => true,
else => false,
};
const sparc = switch (arch) {
.sparc, .sparc64, .sparcel => true,
else => false,
};
const apple = switch (os) {
.ios, .macos, .watchos, .tvos => true,
else => false,
};
if (x86) {
// Intel processors have a unified instruction and data cache
// so there is nothing to do
exportIt();
} else if (os == .windows and (arm32 or arm64)) {
// TODO
// FlushInstructionCache(GetCurrentProcess(), start, end - start);
// exportIt();
} else if (arm32 and !apple) {
switch (os) {
.freebsd, .netbsd => {
var arg = arm_sync_icache_args{
.addr = start,
.len = end - start,
};
const result = sysarch(ARM_SYNC_ICACHE, @ptrToInt(&arg));
std.debug.assert(result == 0);
exportIt();
},
.linux => {
const result = std.os.linux.syscall3(.cacheflush, start, end, 0);
std.debug.assert(result == 0);
exportIt();
},
else => {},
}
} else if (os == .linux and mips) {
const flags = 3; // ICACHE | DCACHE
const result = std.os.linux.syscall3(.cacheflush, start, end - start, flags);
std.debug.assert(result == 0);
exportIt();
} else if (mips and os == .openbsd) {
// TODO
//cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE);
// exportIt();
} else if (os == .linux and riscv) {
const result = std.os.linux.syscall3(.riscv_flush_icache, start, end - start, 0);
std.debug.assert(result == 0);
exportIt();
} else if (arm64 and !apple) {
// Get Cache Type Info.
// TODO memoize this?
var ctr_el0: u64 = 0;
asm volatile (
\\mrs %[x], ctr_el0
\\
: [x] "=r" (ctr_el0),
);
// The DC and IC instructions must use 64-bit registers so we don't use
// uintptr_t in case this runs in an IPL32 environment.
var addr: u64 = undefined;
// If CTR_EL0.IDC is set, data cache cleaning to the point of unification
// is not required for instruction to data coherence.
if (((ctr_el0 >> 28) & 0x1) == 0x0) {
const dcache_line_size: usize = @as(usize, 4) << @intCast(u6, (ctr_el0 >> 16) & 15);
addr = start & ~(dcache_line_size - 1);
while (addr < end) : (addr += dcache_line_size) {
asm volatile ("dc cvau, %[addr]"
:
: [addr] "r" (addr),
);
}
}
asm volatile ("dsb ish");
// If CTR_EL0.DIC is set, instruction cache invalidation to the point of
// unification is not required for instruction to data coherence.
if (((ctr_el0 >> 29) & 0x1) == 0x0) {
const icache_line_size: usize = @as(usize, 4) << @intCast(u6, (ctr_el0 >> 0) & 15);
addr = start & ~(icache_line_size - 1);
while (addr < end) : (addr += icache_line_size) {
asm volatile ("ic ivau, %[addr]"
:
: [addr] "r" (addr),
);
}
}
asm volatile ("isb sy");
exportIt();
} else if (powerpc64) {
// TODO
//const size_t line_size = 32;
//const size_t len = (uintptr_t)end - (uintptr_t)start;
//
//const uintptr_t mask = ~(line_size - 1);
//const uintptr_t start_line = ((uintptr_t)start) & mask;
//const uintptr_t end_line = ((uintptr_t)start + len + line_size - 1) & mask;
//
//for (uintptr_t line = start_line; line < end_line; line += line_size)
// __asm__ volatile("dcbf 0, %0" : : "r"(line));
//__asm__ volatile("sync");
//
//for (uintptr_t line = start_line; line < end_line; line += line_size)
// __asm__ volatile("icbi 0, %0" : : "r"(line));
//__asm__ volatile("isync");
// exportIt();
} else if (sparc) {
// TODO
//const size_t dword_size = 8;
//const size_t len = (uintptr_t)end - (uintptr_t)start;
//
//const uintptr_t mask = ~(dword_size - 1);
//const uintptr_t start_dword = ((uintptr_t)start) & mask;
//const uintptr_t end_dword = ((uintptr_t)start + len + dword_size - 1) & mask;
//
//for (uintptr_t dword = start_dword; dword < end_dword; dword += dword_size)
// __asm__ volatile("flush %0" : : "r"(dword));
// exportIt();
} else if (apple) {
// On Darwin, sys_icache_invalidate() provides this functionality
sys_icache_invalidate(start, end - start);
exportIt();
}
}
const linkage = if (builtin.is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Weak;
fn exportIt() void {
@export(clear_cache, .{ .name = "__clear_cache", .linkage = linkage });
}
// Darwin-only
extern fn sys_icache_invalidate(start: usize, len: usize) void;
// BSD-only
const arm_sync_icache_args = extern struct {
addr: usize, // Virtual start address
len: usize, // Region size
};
const ARM_SYNC_ICACHE = 0;
extern "c" fn sysarch(number: i32, args: usize) i32;
|
lib/compiler_rt/clear_cache.zig
|
// Possible TODOs:
// - Parse source to ensure all dependencies are actually used
// - Allow multiple packages in one repo
// - Fetch packages at build time
const std = @import("std");
const builtin = @import("builtin");
update_step: std.build.Step,
b: *std.build.Builder,
dir: []const u8,
deps: std.StringArrayHashMapUnmanaged(Dep) = .{},
import_set: std.StringArrayHashMapUnmanaged(void) = .{},
const Deps = @This();
pub const Dep = union(enum) {
managed: struct { // Fully managed dependency - we download these
url: []const u8, // Git URL for the package
path: []const u8, // Path to package directory
main_path: []const u8, // Path to package main file
deps: []const []const u8, // Dependency names of this package
},
tracked: struct { // Partially managed - we add dependencies to these
main_path: []const u8, // Path to package main file
deps: []const []const u8, // Dependency names of this package
},
unmanaged: struct { // Unmanaged - we just allow these as deps of other deps
main_path: std.build.FileSource, // Path to package main file
deps: ?[]const std.build.Pkg, // Dependencies of this package
},
};
pub fn init(b: *std.build.Builder) *Deps {
const self = initNoStep(b);
const step = b.step("update", "Update all dependencies to the latest allowed version");
step.dependOn(&self.update_step);
return self;
}
pub fn initNoStep(b: *std.build.Builder) *Deps {
const dir = std.os.getenv("DEPS_ZIG_CACHE") orelse switch (builtin.os.tag) {
.windows => b.fmt("{s}\\Temp\\deps-zig", .{std.os.getenv("LOCALAPPDATA").?}),
.macos => b.fmt("{s}/Library/Caches/deps-zig", .{std.os.getenv("HOME").?}),
else => if (std.os.getenv("XDG_CACHE_HOME")) |cache|
b.fmt("{s}/deps-zig", .{cache})
else
b.fmt("{s}/.cache/deps-zig", .{std.os.getenv("HOME").?}),
};
std.fs.cwd().makeDir(dir) catch {};
var dirh = std.fs.cwd().openDir(dir, .{}) catch |err| {
std.debug.print("Could not open packages dir '{}': {s}\n", .{ std.fmt.fmtSliceEscapeLower(dir), @errorName(err) });
std.os.exit(1);
};
defer dirh.close();
// Purposefully leak the file descriptor - it will be unlocked when the process exits
_ = dirh.createFile(".lock", .{ .lock = .Exclusive, .lock_nonblocking = true }) catch |err| {
std.debug.print("Failed to aqcuire package lock: {s}\n", .{@errorName(err)});
std.os.exit(1);
};
const self = b.allocator.create(Deps) catch unreachable;
self.* = .{
.update_step = std.build.Step.init(.custom, "update-deps", b.allocator, makeUpdate),
.b = b,
.dir = dir,
};
return self;
}
pub fn addTo(self: Deps, step: *std.build.LibExeObjStep) void {
var it = self.deps.iterator();
while (it.next()) |entry| {
step.addPackage(self.createPkg(entry.key_ptr.*, entry.value_ptr.*));
}
}
fn createPkg(self: Deps, name: []const u8, dependency: Dep) std.build.Pkg {
return switch (dependency) {
.managed => |dep| .{
.name = name,
.path = .{ .path = dep.main_path },
.dependencies = self.createPkgDeps(dep.deps),
},
.tracked => |dep| .{
.name = name,
.path = .{ .path = dep.main_path },
.dependencies = self.createPkgDeps(dep.deps),
},
.unmanaged => |dep| .{
.name = name,
.path = dep.main_path,
.dependencies = dep.deps,
},
};
}
fn createPkgDeps(self: Deps, dep_names: []const []const u8) ?[]const std.build.Pkg {
if (dep_names.len == 0) return null;
const deps = self.b.allocator.alloc(std.build.Pkg, dep_names.len) catch unreachable;
var i: usize = 0;
for (dep_names) |dname| {
if (self.deps.get(dname)) |ddep| {
deps[i] = self.createPkg(dname, ddep);
i += 1;
}
// If we don't have the dep, ignore it and let the compiler error
}
return deps[0..i];
}
pub fn add(self: *Deps, url: []const u8, version: []const u8) void {
const name = trimEnds(
std.fs.path.basenamePosix(url),
&.{"zig-"},
&.{ ".git", ".zig", "-zig" },
);
const path = self.fetchPkg(name, url, version);
const main_file = blk: {
var dirh = std.fs.cwd().openDir(path, .{}) catch {
std.debug.print("Failed to open package dir: {s}\n", .{path});
std.os.exit(1);
};
for ([_][]const u8{
self.b.fmt("{s}.zig", .{name}),
"main.zig",
self.b.fmt("src{c}{s}.zig", .{ std.fs.path.sep, name }),
"src" ++ [_]u8{std.fs.path.sep} ++ "main.zig",
}) |p| {
if (dirh.access(p, .{})) |_| {
dirh.close();
break :blk p;
} else |_| {}
}
dirh.close();
std.debug.print("Could not find package entrypoint, attempted {s}.zig, main.zig, src{c}{[0]s}.zig and src{[1]c}main.zig\n", .{ name, std.fs.path.sep });
std.os.exit(1);
};
const main_path = std.fs.path.join(self.b.allocator, &.{ path, main_file }) catch unreachable;
const deps = self.parsePackageDeps(main_path) catch |err| switch (err) {
error.InvalidSyntax => &[_][]const u8{},
else => {
std.debug.print("Failed to parse package dependencies for {s}: {s}\n", .{ main_file, @errorName(err) });
std.os.exit(1);
},
};
const dep = Dep{ .managed = .{
.url = url,
.path = path,
.main_path = main_path,
.deps = deps,
} };
if (self.deps.fetchPut(self.b.allocator, name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(name)});
std.os.exit(1);
}
}
pub fn addPackagePath(self: *Deps, name: []const u8, main_path: []const u8) void {
const deps = self.parsePackageDeps(main_path) catch |err| switch (err) {
error.InvalidSyntax => &[_][]const u8{},
else => {
std.debug.print("Failed to parse package dependencies for {s}: {s}\n", .{ name, @errorName(err) });
std.os.exit(1);
},
};
const dep = Dep{ .tracked = .{
.main_path = main_path,
.deps = deps,
} };
if (self.deps.fetchPut(self.b.allocator, name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(name)});
std.os.exit(1);
}
}
pub fn addPackage(self: *Deps, package: std.build.Pkg) void {
const dep = Dep{ .unmanaged = .{
.main_path = package.path,
.deps = package.dependencies,
} };
if (self.deps.fetchPut(self.b.allocator, package.name, dep) catch unreachable) |_| {
std.debug.print("Duplicate dependency '{s}'\n", .{std.fmt.fmtSliceEscapeLower(package.name)});
std.os.exit(1);
}
}
fn fetchPkg(self: Deps, name: []const u8, url: []const u8, version: []const u8) []const u8 {
const path = self.b.allocator.alloc(u8, self.dir.len + 1 + url.len + 1 + version.len) catch unreachable;
// Base dir
var i: usize = 0;
std.mem.copy(u8, path[i..], self.dir);
i += self.dir.len;
// Path separator
path[i] = std.fs.path.sep;
i += 1;
// Encoded URL (/ replaced with : so it's a valid path)
std.mem.copy(u8, path[i..], url);
std.mem.replaceScalar(u8, path[i .. i + url.len], '/', ':');
i += url.len;
// Version separator
path[i] = '@';
i += 1;
// Version
std.mem.copy(u8, path[i..], version);
i += version.len;
std.debug.assert(i == path.len);
// If we don't have the dep already, clone it
std.fs.cwd().access(path, .{}) catch self.updateDep(name, path, url, version);
return path;
}
fn parsePackageDeps(self: *Deps, main_file: []const u8) ![]const []const u8 {
defer self.import_set.clearRetainingCapacity();
var npkg = try self.collectImports(std.fs.cwd(), main_file);
const pkgs = try self.b.allocator.alloc([]const u8, npkg);
for (self.import_set.keys()) |key| {
if (isPkg(key)) {
npkg -= 1;
pkgs[npkg] = key;
}
}
return pkgs;
}
fn collectImports(self: *Deps, dir: std.fs.Dir, import: []const u8) CollectImportsError!usize {
const data = dir.readFileAllocOptions(self.b.allocator, import, 4 << 30, null, 1, 0) catch |err| switch (err) {
error.FileTooBig => {
// If you have a 4GiB source file, you have a problem
// However, we probably shouldn't outright error in this situation, so instead we'll warn and skip this file
std.debug.print("Could not parse exceptionally large source file '{s}', skipping\n", .{std.fmt.fmtSliceEscapeLower(import)});
return 0;
},
else => |e| return e,
};
var subdir = try dir.openDir(std.fs.path.dirname(import) orelse ".", .{});
defer subdir.close();
var toks = std.zig.Tokenizer.init(data);
var npkg: usize = 0;
while (true) {
const tok = toks.next();
if (tok.tag == .eof) break;
if (tok.tag == .builtin and std.mem.eql(u8, data[tok.loc.start..tok.loc.end], "@import")) {
if (toks.next().tag != .l_paren) return error.InvalidSyntax;
const name_tok = toks.next();
if (name_tok.tag != .string_literal) return error.InvalidSyntax;
if (toks.next().tag != .r_paren) return error.InvalidSyntax;
const name = std.zig.string_literal.parseAlloc(
self.b.allocator,
data[name_tok.loc.start..name_tok.loc.end],
) catch |err| switch (err) {
error.InvalidStringLiteral => return error.InvalidSyntax,
else => |e| return e,
};
if (try self.import_set.fetchPut(self.b.allocator, name, {})) |_| {
// Do nothing, the entry is already in the set
} else if (isPkg(name)) {
npkg += 1;
} else if (std.mem.endsWith(u8, name, ".zig")) {
npkg += try self.collectImports(subdir, name);
}
}
}
return npkg;
}
const CollectImportsError =
std.fs.Dir.OpenError ||
std.fs.File.OpenError ||
std.fs.File.ReadError ||
std.fs.File.SeekError ||
std.mem.Allocator.Error ||
error{InvalidSyntax};
fn makeUpdate(step: *std.build.Step) !void {
const self = @fieldParentPtr(Deps, "update_step", step);
var it = self.deps.iterator();
while (it.next()) |entry| {
switch (entry.value_ptr.*) {
.managed => |dep| {
const version_idx = 1 + std.mem.lastIndexOfScalar(u8, dep.path, '@').?;
const version = dep.path[version_idx..];
self.updateDep(entry.key_ptr.*, dep.path, dep.url, version);
},
else => {},
}
}
}
fn updateDep(self: Deps, name: []const u8, path: []const u8, url: []const u8, version: []const u8) void {
std.fs.cwd().access(path, .{}) catch self.exec(&.{
"git",
"clone",
"--depth=1",
"--no-single-branch",
"--shallow-submodules",
"--",
url,
path,
}, null);
self.exec(&.{ "git", "fetch", "--all", "-Ppqt" }, path);
// Check if there are changes - we don't want to clobber them
if (self.execOk(&.{ "git", "diff", "--quiet", "HEAD" }, path)) {
// Clean; check if version is a branch
if (self.execOk(&.{
"git",
"show-ref",
"--verify",
"--",
self.b.fmt("refs/remotes/origin/{s}", .{version}),
}, path)) {
// It is, so switch to it and pull
self.exec(&.{ "git", "switch", "-q", "--", version }, path);
self.exec(&.{ "git", "pull", "-q", "--ff-only" }, path);
} else {
// It isn't, check out detached
self.exec(&.{ "git", "switch", "-dq", "--", version }, path);
}
} else {
// Dirty; print a warning
std.debug.print("WARNING: package {s} contains uncommitted changes, not attempting to update\n", .{name});
}
}
fn isPkg(name: []const u8) bool {
if (std.mem.endsWith(u8, name, ".zig")) return false;
if (std.mem.eql(u8, name, "std")) return false;
if (std.mem.eql(u8, name, "root")) return false;
return true;
}
/// Remove each prefix, then each suffix, in order
fn trimEnds(haystack: []const u8, prefixes: []const []const u8, suffixes: []const []const u8) []const u8 {
var s = haystack;
for (prefixes) |prefix| {
if (std.mem.startsWith(u8, s, prefix)) {
s = s[prefix.len..];
}
}
for (suffixes) |suffix| {
if (std.mem.endsWith(u8, s, suffix)) {
s = s[0 .. s.len - suffix.len];
}
}
return s;
}
fn exec(self: Deps, argv: []const []const u8, cwd: ?[]const u8) void {
if (!self.execInternal(argv, cwd, .Inherit)) {
std.debug.print("Command failed: {s}", .{argv[0]});
for (argv[1..]) |arg| {
std.debug.print(" {s}", .{arg});
}
std.debug.print("\n", .{});
std.os.exit(1);
}
}
fn execOk(self: Deps, argv: []const []const u8, cwd: ?[]const u8) bool {
return self.execInternal(argv, cwd, .Ignore);
}
fn execInternal(self: Deps, argv: []const []const u8, cwd: ?[]const u8, io: std.ChildProcess.StdIo) bool {
const child = std.ChildProcess.init(argv, self.b.allocator) catch unreachable;
defer child.deinit();
child.cwd = cwd;
child.stdin_behavior = .Ignore;
child.stdout_behavior = io;
child.stderr_behavior = io;
child.env_map = self.b.env_map;
const term = child.spawnAndWait() catch |err| {
std.debug.print("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) });
return false;
};
switch (term) {
.Exited => |code| if (code != 0) {
return false;
},
.Signal, .Stopped, .Unknown => {
return false;
},
}
return true;
}
|
example/Deps.zig
|
const std = @import("std");
const col = @import("../term/colors.zig");
const r = col.reset();
const Cmd = @import("../cli.zig").Cmd;
pub const intro_msg = col.Color.dim(.blue, .normal_fg) ++
\\
\\ Oh wow, uh, this cli is...
++ col.reset();
pub const intro_img = col.Color.bold(.green, .bright_fg) ++
\\
\\ ___ ~~ ___ ___ ___ ~~
\\ ~~ ~/ _ `\ / __`\ / __`\~/ _ `\~
\\ ~~ /\ \/\ \/\ __//\ \_\ \\ \/\ \
\\------------\ \_\ \_\ \____\ \____/ \_\ \_\---------------------
\\ \/_/\/_/\/____/\/___/ \/_/\/_/
\\
\\
++ col.reset();
pub const subc_title = col.Color.green.bold(.bright_fg) ++
\\
\\ SUBCOMMANDS DESCRIPTION
++ col.reset();
pub const args_title = col.Color.yellow.bold(.bright_fg) ++
\\
\\ ARGUMENTS DESCRIPTION
++ col.reset();
pub fn print_usage() void {
std.debug.print("\n\n", .{});
const usage_msg = col.Color.blue.bold(.bright_fg) ++
\\
\\ USAGE: izi <SUBCMD> [TARGET] [--args]
\\
++ col.reset();
const subc =
\\
\\ - new | n Create a new Idl file/project/anything!
\\ - check | c See an overview of your resources
\\ - build | b Build/eval a .is or .il file
\\ - run | r Run a specified .is or .il file
\\ - shell | s Start a shell or REPL session
\\ - lsp | l Start a (nonexistent) LSP server
\\ - auth | a Authorize with (nonexistent) servers
\\ - id | I Perform identity-related operations
\\ - init | i Begin a new project type
\\ - test | t Test (kinda) your files
\\ - about | A Information about the Idl project
\\ - guide | G A small tutorial to show you the ropes
\\ - help | h Print the usage info for iz
\\
++ col.reset();
const args =
\\
\\ --debug | -d Enable verbose output for ops
\\ --version | -d Print out the current version
\\ --curr-user | -U Print out the current user info
\\ --curr-base | -B Information about the active kbase
\\ --env-info | -E Information about usage, storage, ...
\\ --sync | -s Check if workspace(s) are synced anywhere
\\
\\
;
const full = intro_msg ++ intro_img ++ usage_msg ++ subc_title ++ subc ++ args_title ++ args;
std.debug.print(full, .{});
}
pub fn printCmdUsage(cmd: Cmd) void {
const msg = switch (cmd) {
.run => run_cmd: {
const run_usage = col.Fg.Br.green ++
\\
\\ RUN subcommand usage:
\\
\\ idl run <FILE.is> -o [TARGET] [--args]
\\
++ r();
const run_opts_d = col.Color.white.finish(.normal_fg) ++
\\ --verbose | -v Enables verbose and debug run output
\\ --base | -b Select a specific base by ID to select
\\ --tags | -t Associate tag metadata with this run
\\
++ r();
break :run_cmd intro_msg ++ run_usage ++ args_title ++ run_opts_d;
},
.id => id_cmd: {
const id_usage = col.Fg.Br.blue ++
\\
\\ ID subcommand usage:
\\
\\ idl id [SUBCOMMAND] <OPERATION> [--args]
\\
++ r();
const id_opts = col.Color.white.finish(.normal_fg) ++
\\ --verbose | -v Enables verbose and debug run output
\\ --base | -b Select a specific base by ID to select
\\ --tags | -t Associate tag metadata with this run
\\
++ r();
break :id_cmd intro_msg ++ id_usage ++ args_title ++ id_opts;
},
else => std.debug.print("\x1b[32;1bStill working on the docs!\x1b[0m"),
};
std.debug.print("{s}", .{msg});
}
const testing = std.testing;
test "help message prints" {
print_usage();
try testing.expect(true);
}
|
src/cli/help.zig
|
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day07.txt");
const Input = struct {
positions: std.ArrayList(u11) = std.ArrayList(u11).init(std.testing.allocator),
pub fn init() !@This() {
var instance = Input{};
try instance.positions.ensureTotalCapacity(2000);
return instance;
}
pub fn deinit(self: @This()) void {
self.positions.deinit();
}
};
fn parseInput(input_text: []const u8) !Input {
var input = try Input.init();
errdefer input.deinit();
var positions = std.mem.tokenize(u8, input_text, ",\r\n");
while (positions.next()) |pos| {
try input.positions.append(try parseInt(u11, pos, 10));
}
return input;
}
fn part1(input: Input) i64 {
var crabs_at_pos: [2048]i64 = .{0} ** 2048;
const total_crab_count: i64 = @intCast(i64, input.positions.items.len);
for (input.positions.items) |pos| {
crabs_at_pos[pos] += 1;
}
var crabs_left: i64 = 0;
var crabs_right: i64 = total_crab_count;
var min_balance: i64 = std.math.maxInt(i64);
var pos_for_min_balance: usize = undefined;
for (crabs_at_pos) |count, pos| {
crabs_right -= count;
const balance = std.math.absInt(crabs_left - crabs_right) catch unreachable;
if (balance < min_balance) {
min_balance = balance;
pos_for_min_balance = pos;
}
crabs_left += count;
if (crabs_right == 0) {
break;
}
}
crabs_right = 0;
var fuel: i64 = 0;
for (crabs_at_pos) |count, pos| {
crabs_right -= count;
const distance = std.math.absInt(@intCast(i64, pos) - @intCast(i64, pos_for_min_balance)) catch unreachable;
fuel += crabs_at_pos[pos] * distance;
if (crabs_right == 0) {
break;
}
}
return fuel;
}
fn part2(input: Input) i64 {
var crabs_at_pos: [2048]i64 = .{0} ** 2048;
const total_crab_count: i64 = @intCast(i64, input.positions.items.len);
for (input.positions.items) |pos| {
crabs_at_pos[pos] += 1;
}
// Just brute-force it!
var min_fuel: i64 = std.math.maxInt(i64);
var pos_for_min_fuel: usize = undefined;
var target_pos: usize = 0;
var crabs_remaining: i64 = total_crab_count;
while (target_pos < crabs_at_pos.len) : (target_pos += 1) {
var fuel: i64 = 0;
for (crabs_at_pos) |count, pos| {
const distance = std.math.absInt(@intCast(i64, pos) - @intCast(i64, target_pos)) catch unreachable;
fuel += count * @divFloor(distance * (distance + 1), 2);
}
if (fuel < min_fuel) {
min_fuel = fuel;
pos_for_min_fuel = target_pos;
}
crabs_remaining -= crabs_at_pos[target_pos];
if (crabs_remaining == 0) {
break;
}
}
return min_fuel;
}
const test_data = "16,1,2,0,4,2,7,1,2,14";
const part1_test_solution: ?i64 = 37;
const part1_solution: ?i64 = 348664;
const part2_test_solution: ?i64 = 168;
const part2_solution: ?i64 = 100220525;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try parseInput(test_data);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var input = try parseInput(data);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
}
}
fn testPart2() !void {
var test_input = try parseInput(test_data);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var input = try parseInput(data);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert;
|
src/day07.zig
|
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Commit = opaque {
pub fn deinit(self: *Commit) void {
log.debug("Commit.deinit called", .{});
c.git_commit_free(@ptrCast(*c.git_commit, self));
log.debug("Commit freed successfully", .{});
}
pub fn noteIterator(self: *Commit) !*git.NoteIterator {
log.debug("Commit.noteIterator called", .{});
var ret: *git.NoteIterator = undefined;
try internal.wrapCall("git_note_commit_iterator_new", .{
@ptrCast(*?*c.git_note_iterator, &ret),
@ptrCast(*c.git_commit, self),
});
return ret;
}
pub fn id(self: *const Commit) *const git.Oid {
log.debug("Commit.id called", .{});
const ret = @ptrCast(
*const git.Oid,
c.git_commit_id(@ptrCast(*const c.git_commit, self)),
);
// This check is to prevent formating the oid when we are not going to print anything
if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) {
var buf: [git.Oid.hex_buffer_size]u8 = undefined;
if (ret.formatHex(&buf)) |slice| {
log.debug("successfully fetched commit id: {s}", .{slice});
} else |_| {
log.debug("successfully fetched commit id, but unable to format it", .{});
}
}
return ret;
}
pub fn getOwner(self: *const Commit) *git.Repository {
log.debug("Commit.getOwner called", .{});
const ret = @ptrCast(
*git.Repository,
c.git_commit_owner(@ptrCast(*const c.git_commit, self)),
);
log.debug("successfully fetched owning repository: {*}", .{ret});
return ret;
}
pub fn getMessageEncoding(self: *const Commit) ?[:0]const u8 {
log.debug("Commit.getMessageEncoding called", .{});
const ret = c.git_commit_message_encoding(@ptrCast(*const c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit message encoding: {s}", .{slice});
return slice;
}
log.debug("commit has no message encoding", .{});
return null;
}
/// Get the full message of a commit.
///
/// The returned message will be slightly prettified by removing any potential leading newlines.
pub fn getMessage(self: *const Commit) ?[:0]const u8 {
log.debug("Commit.getMessage called", .{});
const ret = c.git_commit_message(@ptrCast(*const c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit message: {s}", .{slice});
return slice;
}
log.debug("commit has no message", .{});
return null;
}
/// Get the full raw message of a commit.
pub fn getMessageRaw(self: *const Commit) ?[:0]const u8 {
log.debug("Commit.getMessageRaw called", .{});
const ret = c.git_commit_message_raw(@ptrCast(*const c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit message: {s}", .{slice});
return slice;
}
log.debug("commit has no message", .{});
return null;
}
/// Get the full raw text of the commit header.
pub fn getHeaderRaw(self: *const Commit) ?[:0]const u8 {
log.debug("Commit.getHeaderRaw called", .{});
const ret = c.git_commit_raw_header(@ptrCast(*const c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit header: {s}", .{slice});
return slice;
}
log.debug("commit has no header", .{});
return null;
}
/// Get the short "summary" of the git commit message.
///
/// The returned message is the summary of the commit, comprising the first paragraph of the message with whitespace trimmed
/// and squashed.
pub fn getSummary(self: *Commit) ?[:0]const u8 {
log.debug("Commit.getSummary called", .{});
const ret = c.git_commit_summary(@ptrCast(*c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit summary: {s}", .{slice});
return slice;
}
log.debug("commit has no summary", .{});
return null;
}
/// Get the long "body" of the git commit message.
///
/// The returned message is the body of the commit, comprising everything but the first paragraph of the message. Leading and
/// trailing whitespaces are trimmed.
pub fn getBody(self: *Commit) ?[:0]const u8 {
log.debug("Commit.getBody called", .{});
const ret = c.git_commit_body(@ptrCast(*c.git_commit, self));
if (ret) |c_str| {
const slice = std.mem.sliceTo(c_str, 0);
log.debug("commit body: {s}", .{slice});
return slice;
}
log.debug("commit has no body", .{});
return null;
}
/// Get the commit time (i.e. committer time) of a commit.
pub fn getTime(self: *const Commit) i64 {
log.debug("Commit.getTime called", .{});
const ret = c.git_commit_time(@ptrCast(*const c.git_commit, self));
log.debug("commit time: {}", .{ret});
return ret;
}
/// Get the commit timezone offset (i.e. committer's preferred timezone) of a commit.
pub fn getTimeOffset(self: *const Commit) i32 {
log.debug("Commit.getTimeOffset called", .{});
const ret = c.git_commit_time_offset(@ptrCast(*const c.git_commit, self));
log.debug("commit time offset: {}", .{ret});
return ret;
}
pub fn getCommitter(self: *const Commit) *const git.Signature {
log.debug("Commit.getCommitter called", .{});
const ret = @ptrCast(
*const git.Signature,
c.git_commit_committer(@ptrCast(*const c.git_commit, self)),
);
log.debug("commit committer: {s} {s}", .{ ret.z_name, ret.z_email });
return ret;
}
pub fn getAuthor(self: *const Commit) *const git.Signature {
log.debug("Commit.getAuthor called", .{});
const ret = @ptrCast(
*const git.Signature,
c.git_commit_author(@ptrCast(*const c.git_commit, self)),
);
log.debug("commit author: {s} {s}", .{ ret.z_name, ret.z_email });
return ret;
}
pub fn committerWithMailmap(self: *const Commit, mail_map: ?*const git.Mailmap) !*git.Signature {
log.debug("Commit.committerWithMailmap called, mail_map: {*}", .{mail_map});
var signature: *git.Signature = undefined;
try internal.wrapCall("git_commit_committer_with_mailmap", .{
@ptrCast(*?*c.git_signature, &signature),
@ptrCast(*const c.git_commit, self),
@ptrCast(?*const c.git_mailmap, self),
});
log.debug("commit committer: {s} {s}", .{ signature.z_name, signature.z_email });
return signature;
}
pub fn authorWithMailmap(self: *const Commit, mail_map: ?*const git.Mailmap) !*git.Signature {
log.debug("Commit.authorWithMailmap called, mail_map: {*}", .{mail_map});
var signature: *git.Signature = undefined;
try internal.wrapCall("git_commit_author_with_mailmap", .{
@ptrCast(*?*c.git_signature, &signature),
@ptrCast(*const c.git_commit, self),
@ptrCast(?*const c.git_mailmap, mail_map),
});
log.debug("commit author: {s} {s}", .{ signature.z_name, signature.z_email });
return signature;
}
pub fn getTree(self: *const Commit) !*git.Tree {
log.debug("Commit.getTree called", .{});
var tree: *git.Tree = undefined;
try internal.wrapCall("git_commit_tree", .{
@ptrCast(*?*c.git_tree, &tree),
@ptrCast(*const c.git_commit, self),
});
log.debug("commit tree: {*}", .{tree});
return tree;
}
pub fn getTreeId(self: *const Commit) !*const git.Oid {
log.debug("Commit.getTreeId called", .{});
const ret = @ptrCast(
*const git.Oid,
c.git_commit_tree_id(@ptrCast(*const c.git_commit, self)),
);
// This check is to prevent formating the oid when we are not going to print anything
if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) {
var buf: [git.Oid.hex_buffer_size]u8 = undefined;
if (ret.formatHex(&buf)) |slice| {
log.debug("successfully fetched commit tree id: {s}", .{slice});
} else |_| {
log.debug("successfully fetched commit tree id, but unable to format it", .{});
}
}
return ret;
}
pub fn getParentCount(self: *const Commit) u32 {
log.debug("Commit.getParentCount called", .{});
const ret = c.git_commit_parentcount(@ptrCast(*const c.git_commit, self));
log.debug("commit parent count: {}", .{ret});
return ret;
}
pub fn getParent(self: *const Commit, parent_number: u32) !*Commit {
log.debug("Commit.getParent called, parent_number: {}", .{parent_number});
var commit: *Commit = undefined;
try internal.wrapCall("git_commit_parent", .{
@ptrCast(*?*c.git_commit, &commit),
@ptrCast(*const c.git_commit, self),
parent_number,
});
log.debug("parent commit: {*}", .{commit});
return commit;
}
pub fn getParentId(self: *const Commit, parent_number: u32) ?*const git.Oid {
log.debug("Commit.getParentId called", .{});
return @ptrCast(
?*const git.Oid,
c.git_commit_parent_id(
@ptrCast(*const c.git_commit, self),
parent_number,
),
);
}
pub fn getAncestor(self: *const Commit, ancestor_number: u32) !*Commit {
log.debug("Commit.getAncestor called, ancestor_number: {}", .{ancestor_number});
var commit: *Commit = undefined;
try internal.wrapCall("git_commit_nth_gen_ancestor", .{
@ptrCast(*?*c.git_commit, &commit),
@ptrCast(*const c.git_commit, self),
ancestor_number,
});
log.debug("ancestor commit: {*}", .{commit});
return commit;
}
pub fn getHeaderField(self: *const Commit, field: [:0]const u8) !git.Buf {
log.debug("Commit.getHeaderField called, field: {s}", .{field});
var buf: git.Buf = .{};
try internal.wrapCall("git_commit_header_field", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*const c.git_commit, self),
field.ptr,
});
log.debug("header field: {s}", .{buf.toSlice()});
return buf;
}
pub fn amend(
self: *const Commit,
update_ref: ?[:0]const u8,
author: ?*const git.Signature,
committer: ?*const git.Signature,
message_encoding: ?[:0]const u8,
message: ?[:0]const u8,
tree: ?*const git.Tree,
) !git.Oid {
log.debug("Commit.amend called, update_ref: {s}, author: {*}, committer: {*}, message_encoding: {s}, message: {s}, tree: {*}", .{
update_ref,
author,
committer,
message_encoding,
message,
tree,
});
var ret: git.Oid = undefined;
const update_ref_temp = if (update_ref) |slice| slice.ptr else null;
const encoding_temp = if (message_encoding) |slice| slice.ptr else null;
const message_temp = if (message) |slice| slice.ptr else null;
try internal.wrapCall("git_commit_amend", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*const c.git_commit, self),
update_ref_temp,
@ptrCast(?*const c.git_signature, author),
@ptrCast(?*const c.git_signature, committer),
encoding_temp,
message_temp,
@ptrCast(?*const c.git_tree, tree),
});
// This check is to prevent formating the oid when we are not going to print anything
if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) {
var buf: [git.Oid.hex_buffer_size]u8 = undefined;
const slice = try ret.formatHex(&buf);
log.debug("successfully amended commit: {s}", .{slice});
}
return ret;
}
pub fn duplicate(self: *Commit) !*Commit {
log.debug("Commit.duplicate called", .{});
var commit: *Commit = undefined;
try internal.wrapCall("git_commit_dup", .{
@ptrCast(*?*c.git_commit, &commit),
@ptrCast(*c.git_commit, self),
});
log.debug("duplicated commit", .{});
return commit;
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Options for revert
pub const RevertOptions = struct {
/// For merge commits, the "mainline" is treated as the parent.
mainline: bool = false,
/// Options for the merging
merge_options: git.MergeOptions = .{},
/// Options for the checkout
checkout_options: git.CheckoutOptions = .{},
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
|
src/commit.zig
|
const std = @import("std");
const Compiler = @import("Compiler.zig");
const Context = @import("Context.zig");
const Lexer = @import("Lexer.zig");
const Node = @import("Node.zig");
const Parser = @import("Parser.zig");
fn printUsage() !void {
std.log.err("Usage: zedc <your_program_file.zed>", .{});
return error.InvalidUsage;
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
// Command line args.
var args = try std.process.argsWithAllocator(arena.allocator());
_ = args.skip(); // skip program name.
// Program file.
const program_filename = args.next() orelse return printUsage();
var program_file = try std.fs.cwd().openFile(program_filename, .{});
defer program_file.close();
const program_src = try program_file.readToEndAlloc(arena.allocator(), 1024 * 64); // 64K
// Context
const ctx = Context{ .filename = program_filename, .src = program_src };
// Frontend
// Lex
var lexer = Lexer{ .allocator = arena.allocator(), .ctx = ctx };
const tokens = try lexer.lex();
// Parse
var parser = Parser{
.allocator = arena.allocator(),
.ctx = ctx,
.tokens = tokens,
};
const program = try parser.parse();
// Backend / Compile to bytecode
var compiler = try Compiler.init(arena.allocator(), ctx);
const compiled = try compiler.compileProgram(arena.allocator(), program);
// Output
var buf = try std.ArrayList(u8).initCapacity(arena.allocator(), program_filename.len + 4);
if (std.mem.endsWith(u8, program_filename, ".zed")) {
_ = try buf.writer().print("{s}.zbc", .{program_filename[0 .. program_filename.len - 4]});
} else {
_ = try buf.writer().print("{s}.zbc", .{program_filename});
}
var bytecode_file = try std.fs.cwd().createFile(buf.items, .{});
var out_buf = std.io.bufferedWriter(bytecode_file.writer());
var writer = out_buf.writer();
for (compiled) |bytes| {
const len_bytes = std.mem.sliceAsBytes(&[1]u16{@intCast(u16, bytes.len)});
try writer.writeAll(len_bytes);
try writer.writeAll(bytes);
}
try out_buf.flush();
}
|
src/zedc.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const input = @embedFile("../in02.txt");
pub fn main() !void {
var inputit = std.mem.tokenize(input, "\n");
var valids: usize = 0;
while (inputit.next()) |line| {
var lineit = std.mem.tokenize(line, " -:");
var minlets = lineit.next() orelse @panic("no minlet");
var minleti = try std.fmt.parseInt(usize, minlets, 10);
var maxlets = lineit.next() orelse @panic("no maxlet");
var maxleti = try std.fmt.parseInt(usize, maxlets, 10);
var let = lineit.next() orelse @panic("no letter");
var password = lineit.next() orelse @panic("no password");
var count: usize = 0;
for (password) |c| {
if (let[0] == c) count += 1;
}
if (count < minleti) continue;
if (count > maxleti) continue;
valids += 1;
}
print("Found {} valid passwords according to the old rules\n", .{valids});
inputit = std.mem.tokenize(input, "\n");
var newvalids: usize = 0;
while (inputit.next()) |line| {
var lineit = std.mem.tokenize(line, " -:");
var minlets = lineit.next() orelse @panic("no minlet");
var minleti = try std.fmt.parseInt(usize, minlets, 10);
var maxlets = lineit.next() orelse @panic("no maxlet");
var maxleti = try std.fmt.parseInt(usize, maxlets, 10);
var let = lineit.next() orelse @panic("no letter");
var password = lineit.next() orelse @panic("no password");
var count: usize = 0;
if (password.len >= minleti and password[minleti - 1] == let[0]) count += 1;
if (password.len >= maxleti and password[maxleti - 1] == let[0]) count += 1;
print("found {} occurances of {c} between positions {} and {} in {}\n", .{ count, let[0], minleti, maxleti, password });
if (count != 1) continue;
newvalids += 1;
print("that makes {}\n", .{newvalids});
}
print("Found {} valid passwords according to the new rules\n", .{newvalids});
}
|
src/day02.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
pub const Game = struct {
const BOARD_SIZE = 10;
const Player = struct {
name: usize,
pos: usize,
score: usize,
pub fn init(name: usize, start: usize) Player {
var self = Player{
.name = name,
.pos = start - 1,
.score = 0,
};
return self;
}
pub fn won(self: Player, needed: usize) bool {
return self.score >= needed;
}
pub fn move_by(self: *Player, amount: usize) void {
self.pos = (self.pos + amount) % 10;
self.score += self.pos + 1;
// std.debug.warn("PLAYER {} moved to {}, score now is {}\n", .{ self.name, self.pos + 1, self.score });
}
};
const Deterministic = struct {
const DIE_SIZE = 100;
face: usize,
rolls: usize,
pub fn init() Deterministic {
var self = Deterministic{
.face = 1,
.rolls = 0,
};
return self;
}
pub fn roll(self: *Deterministic) usize {
const num = self.face;
self.face = self.face % DIE_SIZE + 1;
self.rolls += 1;
// std.debug.warn("ROLL #{}: {}\n", .{ self.rolls, num });
return num;
}
pub fn multi_roll(self: *Deterministic, rolls: usize) usize {
var num: usize = 0;
var r: usize = 0;
while (r < rolls) : (r += 1) {
num += self.roll();
}
return num;
}
};
pub const Dirac = struct {
const NEEDED = 21;
const Roll = struct {
value: usize,
mult: usize,
};
const Rolls = [_]Roll{
Roll{ .value = 3, .mult = 1 },
Roll{ .value = 4, .mult = 3 },
Roll{ .value = 5, .mult = 6 },
Roll{ .value = 6, .mult = 7 },
Roll{ .value = 7, .mult = 6 },
Roll{ .value = 8, .mult = 3 },
Roll{ .value = 9, .mult = 1 },
};
pub fn init() Dirac {
var self = Dirac{};
return self;
}
fn walk(self: *Dirac, pos0: usize, score0: usize, win0: *usize, pos1: usize, score1: usize, win1: *usize, mult: usize) void {
if (score1 >= NEEDED) {
win1.* += mult;
return;
}
for (Rolls) |roll| {
const next_pos = (pos0 + roll.value) % BOARD_SIZE;
const next_score = score0 + next_pos + 1;
self.walk(pos1, score1, win1, next_pos, next_score, win0, mult * roll.mult);
}
}
pub fn count_wins(self: *Dirac, pos0: usize, pos1: usize, win0: *usize, win1: *usize) void {
self.walk(pos0, 0, win0, pos1, 0, win1, 1);
// std.debug.warn("WINS 0 = {} -- 1 = {}\n", .{ win0.*, win1.* });
}
};
players: [2]Player,
winner: usize,
deterministic: Deterministic,
dirac: Dirac,
pub fn init() Game {
var self = Game{
.players = undefined,
.winner = std.math.maxInt(usize),
.deterministic = Deterministic.init(),
.dirac = Dirac.init(),
};
return self;
}
pub fn deinit(_: *Game) void {}
pub fn process_line(self: *Game, data: []const u8) !void {
var num: usize = 0;
var pos: usize = 0;
var p: usize = 0;
var it = std.mem.split(u8, data, " ");
while (it.next()) |str| : (p += 1) {
if (p == 1) {
num = std.fmt.parseInt(usize, str, 10) catch unreachable;
continue;
}
if (p == 4) {
pos = std.fmt.parseInt(usize, str, 10) catch unreachable;
self.players[num - 1] = Player.init(num, pos);
continue;
}
}
}
pub fn deterministic_play_until_win(self: *Game, winning_score: usize) void {
var p: usize = 0;
while (true) {
const roll = self.deterministic.multi_roll(3);
self.players[p].move_by(roll);
if (self.players[p].won(winning_score)) {
self.winner = p;
break;
}
p = 1 - p;
}
}
pub fn deterministic_weigthed_score_looser(self: *Game) usize {
const looser = 1 - self.winner;
const score = self.players[looser].score * self.deterministic.rolls;
return score;
}
pub fn dirac_count_wins(self: *Game, win0: *usize, win1: *usize) void {
self.dirac.walk(self.players[0].pos, 0, win0, self.players[1].pos, 0, win1, 1);
}
pub fn dirac_best_score(self: *Game) usize {
var win0: usize = 0;
var win1: usize = 0;
self.dirac_count_wins(&win0, &win1);
const best = if (win0 > win1) win0 else win1;
return best;
}
};
test "sample part a" {
const data: []const u8 =
\\Player 1 starting position: 4
\\Player 2 starting position: 8
;
var game = Game.init();
defer game.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try game.process_line(line);
}
game.deterministic_play_until_win(1000);
const score = game.deterministic_weigthed_score_looser();
try testing.expect(score == 739785);
}
test "sample part b" {
const data: []const u8 =
\\Player 1 starting position: 4
\\Player 2 starting position: 8
;
var game = Game.init();
defer game.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try game.process_line(line);
}
var win0: usize = 0;
var win1: usize = 0;
game.dirac_count_wins(&win0, &win1);
try testing.expect(win0 == 444356092776315);
try testing.expect(win1 == 341960390180808);
}
|
2021/p21/game.zig
|
//! Types may implement a custom serialization or deserialization routine with a
//! function named `serialize` or `deserialize` in the form of:
//! ```
//! pub fn deserialize(self: *Self, deserializer: anytype) !void
//! ```
//! or
//! ```
//! pub fn serialize(self: *Self, serializer: anytype) !void
//! ```
//! these functions will be called when the serializer or deserializer is used to
//! serialize or deserialize that type. It will pass a pointer to the type instance
//! to serialize or deserialize into and a pointer to the (de)serializer struct.
//! Serialization method:
//! If `packing` is set to `Byte`:
//! -Integer and Float types are serialized in the specified
//! endianess using the minimum number of bytes required to fit
//! all of the integer's bits.
//! -Booleans are serialized as a single byte integer.
//! -Structs are serialized field-by-field in the order specified
//! by the struct source definition. Field serialization is
//! dependant on type. Packed structs will be serialized
//! as though `Bit` packing was specified, and then aligned
//! to the nearest byte. Comptime fields are ignored.
//! -Unions are serialized by first serializing the active tag
//! integer, then the payload. The amount of bytes used to
//! serialize the union is dependent on the active payload type.
//! Untagged unions are not handled by the serializer and must
//! employ a custom serializer/deserializer routine.
//! -Enums and Errors are serialized as their integer values.
//! -Optionals are serialized as a single `0` value integer
//! if they are null. If the optional is not null, then a
//! `1` value integer is serialized, followed by the serialization
//! of the payload. As with unions, the number of bytes consumed is
//! dependant on the payload type.
//! -All other types are not handled and require a custom
//! serializer/deserializer routine.
//!
//! If `packing` is set to `Bit`:
//! -Integer and Float types are serialized in the specified
//! endianess using the number of bits specified by the integer
//! type.
//! -Booleans are serialized as a single bit integer.
//! -Structs are serialized field-by-field in the order specified
//! by the struct source definition. Field serialization is
//! dependant on type. Comptime fields are ignored.
//! -Unions are serialized by first serializing the active tag
//! integer, then the payload. The amount of bits used to
//! serialize the union is dependent on the active payload type.
//! Untagged unions are not handled by the serializer and must
//! employ a custom serializer/deserializer routine.
//! -Enums and Errors are serialized as their integer values.
//! -Optionals are serialized as a single `0` value integer
//! if they are null. If the optional is not null, then a
//! `1` value integer is serialized, followed by the serialization
//! of the payload. As with unions, the number of bytes consumed is
//! dependant on the payload type.
//! -All other types are not handled and require a custom
//! serializer/deserializer routine.
const std = @import("std");
const builtin = std.builtin;
const io = std.io;
const assert = std.debug.assert;
const math = std.math;
const meta = std.meta;
const trait = meta.trait;
const testing = std.testing;
pub const Packing = enum {
/// Pack data to byte alignment
Byte,
/// Pack data to bit alignment
Bit,
};
/// Creates a deserializer that deserializes types from any stream.
/// Types may implement a custom deserialization routine with a
/// function named `deserialize` in the form of:
/// ```
/// pub fn deserialize(self: *Self, deserializer: anytype) !void
/// ```
/// which will be called when the deserializer is used to deserialize
/// that type. It will pass a pointer to the type instance to deserialize
/// into and a pointer to the deserializer struct.
pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime Reader: type) type {
return struct {
reader: if (packing == .Bit) io.BitReader(endian, Reader) else Reader,
const Self = @This();
pub fn init(reader: Reader) Self {
return Self{
.reader = switch (packing) {
.Bit => io.bitReader(endian, reader),
.Byte => reader,
},
};
}
pub fn alignToByte(self: *Self) void {
if (packing == .Byte) return;
self.reader.alignToByte();
}
//@BUG: inferred error issue. See: #1386
fn deserializeInt(self: *Self, comptime T: type) (Reader.Error || error{EndOfStream})!T {
comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
const u8_bit_count = 8;
const t_bit_count = @bitSizeOf(T);
const U = std.meta.Int(.unsigned, t_bit_count);
const Log2U = math.Log2Int(U);
const int_size = (t_bit_count + 7) / 8;
if (packing == .Bit) {
const result = try self.reader.readBitsNoEof(U, t_bit_count);
return @bitCast(T, result);
}
var buffer: [int_size]u8 = undefined;
const read_size = try self.reader.read(buffer[0..]);
if (read_size < int_size) return error.EndOfStream;
if (int_size == 1) {
if (t_bit_count == 8) return @bitCast(T, buffer[0]);
const PossiblySignedByte = std.meta.Int(@typeInfo(T).Int.signedness, 8);
return @truncate(T, @bitCast(PossiblySignedByte, buffer[0]));
}
var result = @as(U, 0);
for (buffer) |byte, i| {
switch (endian) {
.Big => {
result = (result << u8_bit_count) | byte;
},
.Little => {
result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
},
}
}
return @bitCast(T, result);
}
/// Deserializes and returns data of the specified type from the stream
pub fn deserialize(self: *Self, comptime T: type) !T {
var value: T = undefined;
try self.deserializeInto(&value);
return value;
}
/// Deserializes data into the type pointed to by `ptr`
pub fn deserializeInto(self: *Self, ptr: anytype) !void {
const T = @TypeOf(ptr);
comptime assert(trait.is(.Pointer)(T));
if (comptime trait.isSlice(T) or trait.isPtrTo(.Array)(T)) {
for (ptr) |*v|
try self.deserializeInto(v);
return;
}
comptime assert(trait.isSingleItemPtr(T));
const C = comptime meta.Child(T);
const child_type_id = @typeInfo(C);
//custom deserializer: fn(self: *Self, deserializer: anytype) !void
if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self);
if (comptime trait.isPacked(C) and packing != .Bit) {
var packed_deserializer = deserializer(endian, .Bit, self.reader);
return packed_deserializer.deserializeInto(ptr);
}
switch (child_type_id) {
.Void => return,
.Bool => ptr.* = (try self.deserializeInt(u1)) > 0,
.Float, .Int => ptr.* = try self.deserializeInt(C),
.Struct => {
const info = @typeInfo(C).Struct;
inline for (info.fields) |*field_info| {
if (field_info.is_comptime) continue;
const name = field_info.name;
const FieldType = field_info.field_type;
if (FieldType == void or FieldType == u0) continue;
//it doesn't make any sense to read pointers
if (comptime trait.is(.Pointer)(FieldType)) {
@compileError("Will not " ++ "read field " ++ name ++ " of struct " ++
@typeName(C) ++ " because it " ++ "is of pointer-type " ++
@typeName(FieldType) ++ ".");
}
try self.deserializeInto(&@field(ptr, name));
}
},
.Union => {
const info = @typeInfo(C).Union;
if (info.tag_type) |TagType| {
//we avoid duplicate iteration over the enum tags
// by getting the int directly and casting it without
// safety. If it is bad, it will be caught anyway.
const TagInt = std.meta.Tag(TagType);
const tag = try self.deserializeInt(TagInt);
inline for (info.fields) |field_info| {
if (@enumToInt(@field(TagType, field_info.name)) == tag) {
const name = field_info.name;
ptr.* = @unionInit(C, name, undefined);
try self.deserializeInto(&@field(ptr, name));
return;
}
}
//This is reachable if the enum data is bad
return error.InvalidEnumTag;
}
@compileError("Cannot meaningfully deserialize " ++ @typeName(C) ++
" because it is an untagged union. Use a custom deserialize().");
},
.Optional => {
const OC = comptime meta.Child(C);
const exists = (try self.deserializeInt(u1)) > 0;
if (!exists) {
ptr.* = null;
return;
}
ptr.* = @as(OC, undefined); //make it non-null so the following .? is guaranteed safe
const val_ptr = &ptr.*.?;
try self.deserializeInto(val_ptr);
},
.Enum => {
var value = try self.deserializeInt(std.meta.Tag(C));
ptr.* = try meta.intToEnum(C, value);
},
else => {
@compileError("Cannot deserialize " ++ @tagName(child_type_id) ++ " types (unimplemented).");
},
}
}
};
}
/// Generate a Deserializer instance with the specified attributes using the
/// specified `reader`.
pub fn deserializer(
comptime endian: builtin.Endian,
comptime packing: Packing,
reader: anytype,
) Deserializer(endian, packing, @TypeOf(reader)) {
return Deserializer(endian, packing, @TypeOf(reader)).init(reader);
}
/// Creates a serializer that serializes types to any stream.
/// Note that the you must call `serializer.flush()` when you are done
/// writing bit-packed data in order ensure any unwritten bits are committed.
/// Types may implement a custom serialization routine with a
/// function named `serialize` in the form of:
/// ```
/// pub fn serialize(self: Self, serializer: anytype) !void
/// ```
/// which will be called when the serializer is used to serialize that type. It will
/// pass a const pointer to the type instance to be serialized and a pointer
/// to the serializer struct.
pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime Writer: type) type {
return struct {
writer: if (packing == .Bit) io.BitWriter(endian, Writer) else Writer,
const Self = @This();
pub const Error = Writer.Error;
pub fn init(writer: Writer) Self {
return Self{
.writer = switch (packing) {
.Bit => io.bitWriter(endian, writer),
.Byte => writer,
},
};
}
/// Flushes any unwritten bits to the stream
pub fn flush(self: *Self) Error!void {
if (packing == .Bit) return self.writer.flushBits();
}
fn serializeInt(self: *Self, value: anytype) Error!void {
const T = @TypeOf(value);
comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
const t_bit_count = @bitSizeOf(T);
const u8_bit_count = @bitSizeOf(u8);
const U = std.meta.Int(.unsigned, t_bit_count);
const Log2U = math.Log2Int(U);
const int_size = (t_bit_count + 7) / 8;
const u_value = @bitCast(U, value);
if (packing == .Bit) return self.writer.writeBits(u_value, t_bit_count);
var buffer: [int_size]u8 = undefined;
if (int_size == 1) buffer[0] = u_value;
for (buffer) |*byte, i| {
const idx = switch (endian) {
.Big => int_size - i - 1,
.Little => i,
};
const shift = @intCast(Log2U, idx * u8_bit_count);
const v = u_value >> shift;
byte.* = if (t_bit_count < u8_bit_count) v else @truncate(u8, v);
}
try self.writer.writeAll(&buffer);
}
/// Serializes the passed value into the stream
pub fn serialize(self: *Self, value: anytype) Error!void {
const T = comptime @TypeOf(value);
if (comptime trait.isIndexable(T)) {
for (value) |v|
try self.serialize(v);
return;
}
//custom serializer: fn(self: Self, serializer: anytype) !void
if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
if (comptime trait.isPacked(T) and packing != .Bit) {
var packed_serializer = Serializer(endian, .Bit, Writer).init(self.writer);
try packed_serializer.serialize(value);
try packed_serializer.flush();
return;
}
switch (@typeInfo(T)) {
.Void => return,
.Bool => try self.serializeInt(@as(u1, @boolToInt(value))),
.Float, .Int => try self.serializeInt(value),
.Struct => {
const info = @typeInfo(T);
inline for (info.Struct.fields) |*field_info| {
if (field_info.is_comptime) continue;
const name = field_info.name;
const FieldType = field_info.field_type;
if (FieldType == void or FieldType == u0) continue;
//It doesn't make sense to write pointers
if (comptime trait.is(.Pointer)(FieldType)) {
@compileError("Will not " ++ "serialize field " ++ name ++
" of struct " ++ @typeName(T) ++ " because it " ++
"is of pointer-type " ++ @typeName(FieldType) ++ ".");
}
try self.serialize(@field(value, name));
}
},
.Union => {
const info = @typeInfo(T).Union;
if (info.tag_type) |TagType| {
const active_tag = meta.activeTag(value);
try self.serialize(active_tag);
//This inline loop is necessary because active_tag is a runtime
// value, but @field requires a comptime value. Our alternative
// is to check each field for a match
inline for (info.fields) |field_info| {
if (@field(TagType, field_info.name) == active_tag) {
const name = field_info.name;
try self.serialize(@field(value, name));
return;
}
}
unreachable;
}
@compileError("Cannot meaningfully serialize " ++ @typeName(T) ++
" because it is an untagged union. Use a custom serialize().");
},
.Optional => {
if (value == null) {
try self.serializeInt(@as(u1, @boolToInt(false)));
return;
}
try self.serializeInt(@as(u1, @boolToInt(true)));
const val_ptr = &value.?;
try self.serialize(val_ptr.*);
},
.Enum => {
try self.serializeInt(@enumToInt(value));
},
else => @compileError("Cannot serialize " ++ @tagName(@typeInfo(T)) ++ " types (unimplemented)."),
}
}
};
}
/// Generate a Serializer instance with the specified attributes using the
/// specified `writer`.
pub fn serializer(
comptime endian: builtin.Endian,
comptime packing: Packing,
writer: anytype,
) Serializer(endian, packing, @TypeOf(writer)) {
return Serializer(endian, packing, @TypeOf(writer)).init(writer);
}
fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: Packing) !void {
@setEvalBranchQuota(1500);
//@NOTE: if this test is taking too long, reduce the maximum tested bitsize
const max_test_bitsize = 128;
const total_bytes = comptime blk: {
var bytes = 0;
comptime var i = 0;
while (i <= max_test_bitsize) : (i += 1) bytes += (i / 8) + @boolToInt(i % 8 > 0);
break :blk bytes * 2;
};
var data_mem: [total_bytes]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var _serializer = serializer(endian, packing, out.writer());
var in = io.fixedBufferStream(&data_mem);
var _deserializer = deserializer(endian, packing, in.reader());
comptime var i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = std.meta.Int(.unsigned, i);
const S = std.meta.Int(.signed, i);
try _serializer.serializeInt(@as(U, i));
if (i != 0) try _serializer.serializeInt(@as(S, -1)) else try _serializer.serialize(@as(S, 0));
}
try _serializer.flush();
i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = std.meta.Int(.unsigned, i);
const S = std.meta.Int(.signed, i);
const x = try _deserializer.deserializeInt(U);
const y = try _deserializer.deserializeInt(S);
try testing.expect(x == @as(U, i));
try (if (i != 0) testing.expect(y == @as(S, -1)) else testing.expect(y == 0));
}
const u8_bit_count = @bitSizeOf(u8);
//0 + 1 + 2 + ... n = (n * (n + 1)) / 2
//and we have each for unsigned and signed, so * 2
const total_bits = (max_test_bitsize * (max_test_bitsize + 1));
const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
try testing.expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
//Verify that empty error set works with serializer.
//deserializer is covered by FixedBufferStream
var null_serializer = serializer(endian, packing, std.io.null_writer);
try null_serializer.serialize(data_mem[0..]);
try null_serializer.flush();
}
test "Serializer/Deserializer Int" {
try testIntSerializerDeserializer(.Big, .Byte);
try testIntSerializerDeserializer(.Little, .Byte);
try testIntSerializerDeserializer(.Big, .Bit);
try testIntSerializerDeserializer(.Little, .Bit);
}
fn testIntSerializerDeserializerInfNaN(
comptime endian: builtin.Endian,
comptime packing: Packing,
) !void {
const mem_size = (16 * 2 + 32 * 2 + 64 * 2 + 128 * 2) / @bitSizeOf(u8);
var data_mem: [mem_size]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var _serializer = serializer(endian, packing, out.writer());
var in = io.fixedBufferStream(&data_mem);
var _deserializer = deserializer(endian, packing, in.reader());
try _serializer.serialize(std.math.nan(f16));
try _serializer.serialize(std.math.inf(f16));
try _serializer.serialize(std.math.nan(f32));
try _serializer.serialize(std.math.inf(f32));
try _serializer.serialize(std.math.nan(f64));
try _serializer.serialize(std.math.inf(f64));
try _serializer.serialize(std.math.nan(f128));
try _serializer.serialize(std.math.inf(f128));
const nan_check_f16 = try _deserializer.deserialize(f16);
const inf_check_f16 = try _deserializer.deserialize(f16);
const nan_check_f32 = try _deserializer.deserialize(f32);
_deserializer.alignToByte();
const inf_check_f32 = try _deserializer.deserialize(f32);
const nan_check_f64 = try _deserializer.deserialize(f64);
const inf_check_f64 = try _deserializer.deserialize(f64);
const nan_check_f128 = try _deserializer.deserialize(f128);
const inf_check_f128 = try _deserializer.deserialize(f128);
try testing.expect(std.math.isNan(nan_check_f16));
try testing.expect(std.math.isInf(inf_check_f16));
try testing.expect(std.math.isNan(nan_check_f32));
try testing.expect(std.math.isInf(inf_check_f32));
try testing.expect(std.math.isNan(nan_check_f64));
try testing.expect(std.math.isInf(inf_check_f64));
try testing.expect(std.math.isNan(nan_check_f128));
try testing.expect(std.math.isInf(inf_check_f128));
}
test "Serializer/Deserializer Int: Inf/NaN" {
try testIntSerializerDeserializerInfNaN(.Big, .Byte);
try testIntSerializerDeserializerInfNaN(.Little, .Byte);
try testIntSerializerDeserializerInfNaN(.Big, .Bit);
try testIntSerializerDeserializerInfNaN(.Little, .Bit);
}
fn testAlternateSerializer(self: anytype, _serializer: anytype) !void {
try _serializer.serialize(self.f_f16);
}
fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: Packing) !void {
const ColorType = enum(u4) {
RGB8 = 1,
RA16 = 2,
R32 = 3,
};
const TagAlign = union(enum(u32)) {
A: u8,
B: u8,
C: u8,
};
const Color = union(ColorType) {
RGB8: struct {
r: u8,
g: u8,
b: u8,
a: u8,
},
RA16: struct {
r: u16,
a: u16,
},
R32: u32,
};
const PackedStruct = packed struct {
f_i3: i3,
f_u2: u2,
};
//to test custom serialization
const Custom = struct {
f_f16: f16,
f_unused_u32: u32,
pub fn deserialize(self: *@This(), _deserializer: anytype) !void {
try _deserializer.deserializeInto(&self.f_f16);
self.f_unused_u32 = 47;
}
pub const serialize = testAlternateSerializer;
};
const MyStruct = struct {
f_i3: i3,
f_u8: u8,
f_tag_align: TagAlign,
comptime f_comptime_field: u22 = 12345,
f_u24: u24,
f_i19: i19,
f_void: void,
f_f32: f32,
f_f128: f128,
f_packed_0: PackedStruct,
f_i7arr: [10]i7,
f_of64n: ?f64,
f_of64v: ?f64,
f_color_type: ColorType,
f_packed_1: PackedStruct,
f_custom: Custom,
f_color: Color,
};
const my_inst = MyStruct{
.f_i3 = -1,
.f_u8 = 8,
.f_tag_align = .{ .B = 148 },
.f_comptime_field = 12345,
.f_u24 = 24,
.f_i19 = 19,
.f_void = {},
.f_f32 = 32.32,
.f_f128 = 128.128,
.f_packed_0 = .{ .f_i3 = -1, .f_u2 = 2 },
.f_i7arr = [10]i7{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
.f_of64n = null,
.f_of64v = 64.64,
.f_color_type = .R32,
.f_packed_1 = .{ .f_i3 = 1, .f_u2 = 1 },
.f_custom = .{ .f_f16 = 38.63, .f_unused_u32 = 47 },
.f_color = .{ .R32 = 123822 },
};
var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var _serializer = serializer(endian, packing, out.writer());
var in = io.fixedBufferStream(&data_mem);
var _deserializer = deserializer(endian, packing, in.reader());
try _serializer.serialize(my_inst);
const my_copy = try _deserializer.deserialize(MyStruct);
try testing.expect(meta.eql(my_copy, my_inst));
}
test "Serializer/Deserializer generic" {
try testSerializerDeserializer(builtin.Endian.Big, .Byte);
try testSerializerDeserializer(builtin.Endian.Little, .Byte);
try testSerializerDeserializer(builtin.Endian.Big, .Bit);
try testSerializerDeserializer(builtin.Endian.Little, .Bit);
}
fn testBadData(comptime endian: builtin.Endian, comptime packing: Packing) !void {
const E = enum(u14) {
One = 1,
Two = 2,
};
const A = struct {
e: E,
};
const C = union(E) {
One: u14,
Two: f16,
};
var data_mem: [4]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var _serializer = serializer(endian, packing, out.writer());
var in = io.fixedBufferStream(&data_mem);
var _deserializer = deserializer(endian, packing, in.reader());
try _serializer.serialize(@as(u14, 3));
try testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(A));
out.pos = 0;
try _serializer.serialize(@as(u14, 3));
try _serializer.serialize(@as(u14, 88));
try testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(C));
}
test "Deserializer bad data" {
try testBadData(.Big, .Byte);
try testBadData(.Little, .Byte);
try testBadData(.Big, .Bit);
try testBadData(.Little, .Bit);
}
|
serialization.zig
|
const std = @import("std");
const panic = std.debug.panic;
const print = std.debug.print;
const fmt = std.fmt;
const ascii = std.ascii;
const alloc = std.heap.page_allocator;
const ArrayList = std.ArrayList;
const HashMap = std.AutoHashMap;
const Error = error{InfiteLoop};
const Kind = enum {
Jmp,
Acc,
Nop,
pub fn from_slice(slice: []const u8) @This() {
if (ascii.eqlIgnoreCase(slice, "jmp")) {
return .Jmp;
} else if (ascii.eqlIgnoreCase(slice, "acc")) {
return .Acc;
} else if (ascii.eqlIgnoreCase(slice, "nop")) {
return .Nop;
}
panic("Operation unvalid.\n", .{});
}
};
const Operation = struct {
kind: Kind,
value: i32,
done: bool = false,
const Self = @This();
pub fn try_run(self: *Self, list: *ArrayList(Self), idx: i32, acc: *i32) Error!void {
if (self.done) {
return Error.InfiteLoop;
}
var next_op_index = idx + 1;
switch (self.kind) {
.Acc => {
acc.* += self.value;
},
.Jmp => {
next_op_index = idx + self.value;
},
else => {},
}
self.done = true;
if (next_op_index >= list.items.len - 1) {
return;
}
var next_op = &list.items[@intCast(usize, next_op_index)];
try next_op.try_run(list, next_op_index, acc);
return;
}
pub fn fix(self: *Self, list: *ArrayList(Self), idx: i32) void {
if (idx >= list.items.len - 1) {
return;
}
if (self.kind == .Jmp or self.kind == .Nop) {
var try_list = ArrayList(Operation).init(alloc);
defer try_list.deinit();
try_list.appendSlice(list.items) catch unreachable;
var current_index = @intCast(usize, idx);
var node = &try_list.items[current_index];
// swap.
if (node.kind == .Jmp) node.kind = .Nop else node.kind = .Jmp;
var acc: i32 = 0;
var fixed_found = true;
try_list.items[0].try_run(&try_list, 0, &acc) catch {
fixed_found = false;
};
if (fixed_found) {
if (self.kind == .Jmp) self.kind = .Nop else self.kind = .Jmp;
return;
}
}
var next_op_index = idx + 1;
switch (self.kind) {
.Jmp => {
next_op_index = idx + self.value;
},
else => {},
}
var n = &list.items[@intCast(usize, next_op_index)];
n.fix(list, next_op_index);
}
};
pub fn main() !void {
var bootcode = ArrayList(Operation).init(alloc);
defer bootcode.deinit();
var it = std.mem.tokenize(@embedFile("../inputs/day_08"), "\n");
while (it.next()) |line| {
for (line) |c, i| {
if (ascii.isSpace(c)) {
var kind = Kind.from_slice(line[0..i]);
var value = try fmt.parseInt(i32, line[i + 1 ..], 0);
try bootcode.append(.{ .kind = kind, .value = value });
}
}
}
var bootcode_copy = ArrayList(Operation).init(alloc);
try bootcode_copy.appendSlice(bootcode.items);
defer bootcode_copy.deinit();
var acc: i32 = 0;
bootcode.items[0].try_run(&bootcode, 0, &acc) catch {
print("ANSWER PART 1: {}\n", .{acc});
};
acc = 0;
bootcode_copy.items[0].fix(&bootcode_copy, 0);
bootcode_copy.items[0].try_run(&bootcode_copy, 0, &acc) catch unreachable;
print("ANSWER PART 2: {}\n", .{acc});
}
|
src/08.zig
|
const std = @import("std");
const bigint = std.math.big.int;
const fact_table_size_128 = 35;
const fact_table_size_64 = 21;
const fact_table64 =
comptime blk: {
var tbl64: [fact_table_size_64]u64 = undefined;
tbl64[0] = 1;
var n: u64 = 1;
while (n < fact_table_size_64) : (n += 1) {
tbl64[n] = tbl64[n - 1] * n;
}
break :blk tbl64;
};
const fact_table128 =
comptime blk: {
var tbl128: [fact_table_size_128]u128 = undefined;
tbl128[0] = 1;
var n: u128 = 1;
while (n < fact_table_size_128) : (n += 1) {
tbl128[n] = tbl128[n - 1] * n;
}
break :blk tbl128;
};
fn factorial(comptime T: type, n: anytype) !T {
const TI = @typeInfo(T);
return try switch (TI) {
.Int => if (TI.Int.bits <= 64)
factorialLookup(T, n, fact_table64, fact_table_size_64)
else if (TI.Int.bits <= 128)
factorialLookup(T, n, fact_table128, fact_table_size_128)
else
@compileError("factorial not implemented for integer type " ++ @typeName(T)),
else => @compileError("factorial not implemented for non-integer type " ++ @typeName(T)),
};
}
fn factorialBig(n: anytype, allocator: *std.mem.Allocator) !bigint.Managed {
if (n > std.math.maxInt(usize)) return error.NTooBig;
var result = try bigint.Managed.init(allocator);
errdefer result.deinit();
if (n < fact_table_size_128) {
try result.set(fact_table128[n]);
} else {
var index = @as(usize, n);
try result.set(fact_table128[fact_table_size_128 - 1]);
var a = try bigint.Managed.init(allocator);
defer a.deinit();
while (index >= fact_table_size_128) : (index -= 1) {
try a.set(index);
try result.ensureMulCapacity(a.toConst(), result.toConst());
try result.mul(a.toConst(), result.toConst());
}
}
return result;
}
fn factorialLookup(comptime T: type, n: anytype, table: anytype, limit: anytype) !T {
if (n < 0) return error.Domain;
if (n > limit) return error.Overflow;
if (n >= table.len) return error.OutOfBoundsAccess;
const TI = @typeInfo(T);
const TUnsigned = std.meta.Int(.unsigned, std.math.min(TI.Int.bits, 64));
const f = table[@intCast(TUnsigned, n)];
return @intCast(T, f);
}
test "factorial" {
inline for (.{
.{ i8, 5, 120 },
.{ u8, 5, 120 },
.{ i16, 7, 5040 },
.{ u16, 8, 40320 },
.{ i32, 12, 479001600 },
.{ u32, 12, 479001600 },
.{ i64, 20, 2432902008176640000 },
.{ u64, 20, 2432902008176640000 },
.{ isize, 20, 2432902008176640000 },
.{ usize, 20, 2432902008176640000 },
.{ i128, 33, 8683317618811886495518194401280000000 },
.{ u128, 34, 295232799039604140847618609643520000000 },
}) |s| {
const T = s[0];
const max = s[1];
const expected = s[2];
const actual = try factorial(T, @as(usize, max));
try std.testing.expectEqual(@as(T, expected), actual);
}
}
test "factorialBig" {
// from table
{
var f = try factorialBig(34, std.testing.allocator);
defer f.deinit();
try std.testing.expectEqual(fact_table128[fact_table_size_128 - 1], try f.to(u128));
}
// beyond table
{
const expected_factorials = .{
.{ 35, 10333147966386144929666651337523200000000 },
.{ 36, 371993326789901217467999448150835200000000 },
.{ 37, 13763753091226345046315979581580902400000000 },
.{ 38, 523022617466601111760007224100074291200000000 },
.{ 39, 20397882081197443358640281739902897356800000000 },
.{ 40, 815915283247897734345611269596115894272000000000 },
.{ 41, 33452526613163807108170062053440751665152000000000 },
.{ 42, 1405006117752879898543142606244511569936384000000000 },
.{ 43, 60415263063373835637355132068513997507264512000000000 },
.{ 44, 2658271574788448768043625811014615890319638528000000000 },
.{ 45, 119622220865480194561963161495657715064383733760000000000 },
};
inline for (expected_factorials) |n_ex| {
const N = n_ex[0];
const EXPECTED = n_ex[1];
var f = try factorialBig(N, std.testing.allocator);
defer f.deinit();
var expected = try bigint.Managed.initSet(std.testing.allocator, EXPECTED);
defer expected.deinit();
try std.testing.expect(expected.toConst().eq(f.toConst()));
}
}
}
/// for sets of length 35 and less
pub fn nthperm(a: anytype, n: u128) !void {
if (a.len == 0) return;
var f = try factorial(u128, a.len);
if (n > f) return error.ArgumentBounds;
var i: usize = 0;
var nmut = @as(u128, n);
while (i < a.len) : (i += 1) {
f = f / (a.len - i);
var j = nmut / f;
nmut -= j * f;
j += i;
const jidx = @intCast(usize, j);
if (jidx >= a.len) return error.OutOfBoundsAccess;
const elt = a[jidx];
var d = jidx;
while (d >= i + 1) : (d -= 1)
a[d] = a[d - 1];
a[i] = elt;
}
}
const expecteds: []const []const u8 = &.{
"ABCA",
"ABAC",
"ACBA",
"ACAB",
"AABC",
"AACB",
"BACA",
"BAAC",
"BCAA",
"BCAA",
"BAAC",
"BACA",
"CABA",
"CAAB",
"CBAA",
"CBAA",
"CAAB",
"CABA",
"AABC",
"AACB",
"ABAC",
"ABCA",
"ACAB",
"ACBA",
};
test "nthperm" {
{
const init = "ABCA";
var buf = init.*;
for (expecteds) |expected, i| {
std.mem.copy(u8, &buf, init);
try nthperm(&buf, @intCast(u6, i));
try std.testing.expectEqualStrings(expected, &buf);
}
// n > (1 << buf.len) should error
try std.testing.expectError(
error.ArgumentBounds,
nthperm(&buf, std.math.maxInt(u6)),
);
}
{
const init = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi";
try std.testing.expectEqual(35, init.len);
var buf = init.*;
try std.testing.expectError(error.OutOfBoundsAccess, nthperm(&buf, 1));
// std.debug.print("init len {}\n", .{init.len});
try nthperm(buf[0 .. buf.len - 1], 1 << init.len * 2);
}
}
/// for sets of any size
pub fn nthpermBig(a: anytype, n: usize, allocator: *std.mem.Allocator) !void {
if (a.len == 0) return;
var f = try factorialBig(a.len, allocator);
var temp = try bigint.Managed.initSet(allocator, n);
defer {
f.deinit();
temp.deinit();
}
if (f.toConst().order(temp.toConst()) != .gt) return error.ArgumentBounds;
var i: usize = 0;
var nmut = try bigint.Managed.initSet(allocator, n);
var j = try bigint.Managed.init(allocator);
defer {
nmut.deinit();
j.deinit();
}
while (i < a.len) : (i += 1) {
// f = f / (a.len - i);
try temp.set(a.len - i);
try f.divTrunc(&temp, f.toConst(), temp.toConst());
// var j = nmut / f;
try j.divTrunc(&temp, nmut.toConst(), f.toConst());
// nmut -= j * f;
try temp.set(try j.to(usize));
try temp.ensureMulCapacity(temp.toConst(), f.toConst());
try temp.mul(temp.toConst(), f.toConst());
try nmut.sub(nmut.toConst(), temp.toConst());
// j += i;
try temp.set(i);
try j.add(j.toConst(), temp.toConst());
const jidx = try j.to(usize);
if (jidx >= a.len) return error.OutOfBoundsAccess;
const elt = a[jidx];
var d = jidx;
while (d >= i + 1) : (d -= 1)
a[d] = a[d - 1];
a[i] = elt;
}
}
const initial_state_big = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij";
test "nthpermBig" {
try std.testing.expectEqual(fact_table_size_128 + 1, initial_state_big.len);
var buf = initial_state_big.*;
try nthpermBig(&buf, std.math.maxInt(usize) - 1, std.testing.allocator);
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOWbdTSjUYVaPhZfQRXgeci", &buf);
// n > (1 << buf.len) should error
try std.testing.expectError(
error.ArgumentBounds,
nthpermBig(buf[0..10], std.math.maxInt(usize), std.testing.allocator),
);
}
/// for sets of length 35 and less
pub fn Permutations(comptime T: type) type {
return struct {
i: usize,
initial_state: []const u8,
/// must be at least as long as initial state.
/// initial_state will be copied to this buffer each time next() is called.
buf: []T,
const Self = @This();
pub fn init(initial_state: []const T, buf: []T) Self {
return .{ .i = 0, .initial_state = initial_state, .buf = buf };
}
pub fn next(self: *Self) ?[]const T {
std.mem.copy(u8, self.buf, self.initial_state);
nthperm(self.buf, @intCast(u6, self.i)) catch return null;
self.i += 1;
return self.buf;
}
};
}
test "Permutations iterator" {
var buf: [4]u8 = undefined;
var it = Permutations(u8).init("ABCA", &buf);
var i: u8 = 0;
while (it.next()) |actual| : (i += 1) {
const expected = expecteds[i];
try std.testing.expectEqualStrings(expected, actual);
}
}
/// for sets of any size,
pub fn PermutationsBig(comptime T: type) type {
return struct {
i: usize,
initial_state: []const u8,
buf: []T,
allocator: *std.mem.Allocator,
const Self = @This();
pub fn init(initial_state: []const T, buf: []T, allocator: *std.mem.Allocator) Self {
return .{ .i = 0, .initial_state = initial_state, .buf = buf, .allocator = allocator };
}
pub fn next(self: *Self) !?[]const T {
std.mem.copy(u8, self.buf, self.initial_state);
try nthpermBig(self.buf, @intCast(u6, self.i), self.allocator);
self.i += 1;
return self.buf;
}
};
}
const expecteds_big: []const []const u8 = &.{
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghji",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgihj",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgijh",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjhi",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjih",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhgij",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhgji",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhigj",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhijg",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhjgi",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefhjig",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefighj",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefigjh",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefihgj",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefihjg",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefijgh",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefijhg",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefjghi",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefjgih",
};
test "PermutationsBig iterator" {
var buf = initial_state_big.*;
var it = PermutationsBig(u8).init(initial_state_big, &buf, std.testing.allocator);
var i: u8 = 0;
while (try it.next()) |actual| : (i += 1) {
const expected = expecteds_big[i];
try std.testing.expectEqualStrings(expected, actual);
if (i >= expecteds_big.len - 1) break;
}
}
|
src/permutations.zig
|
const std = @import("std");
const tht = @import("tenhourtime.zig");
const PrintMode = enum {
Raw,
Formatted,
};
const TimeToGet = union(enum) {
Current: void,
MsSinceEpoch: u64,
MsSinceDayStart: u64,
};
// stdout shouldn't be var here, that doesn't make sense vvvv
fn printTime(stdout: var, timeToGet: TimeToGet, mode: PrintMode) !void {
const timeNum = tht.tenHourTime(switch (timeToGet) {
.Current => tht.msSinceDayStart(tht.getTime()),
.MsSinceEpoch => |ms| tht.msSinceDayStart(ms),
.MsSinceDayStart => |ms| ms,
});
switch (mode) {
.Formatted => {
const timeData = tht.formatTime(timeNum);
try stdout.print("{}", .{timeData});
},
.Raw => {
try stdout.print("{}", .{timeNum});
},
}
}
pub fn main() !void {
var timeToGet: TimeToGet = .Current;
var mode: PrintMode = .Formatted;
var lifetime: enum {
Once,
Forever,
} = .Once;
const stdout = std.io.getStdOut().outStream();
{
var args = std.process.args();
_ = args.skip();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
while (args.next(allocator)) |argValue| {
const arg = try argValue;
if (std.mem.eql(u8, arg, "--help")) {
try stdout.print("tenhourtime\n" ++
"--help | show help\n" ++
"-m | select mode\n" ++
"-m raw | print raw value, eg: `19079284`\n" ++
"-m format | [default] print formatted time, eg: `19LL 07cc 92ii 84qm`\n" ++
"--ms 1234 | get the time of a specific ms duration\n" ++
"--time 84 | get the time of a specific ms since epoch\n" ++
"--update | run until ctrl+c\n", .{});
return;
} else if (std.mem.eql(u8, arg, "-m")) {
var modeStr = try (args.next(allocator) orelse {
std.debug.warn("Missing -m option. Must be: raw | format\n", .{});
return error.MissingMode;
});
if (std.mem.eql(u8, modeStr, "raw")) {
mode = .Raw;
} else if (std.mem.eql(u8, modeStr, "format")) {
mode = .Formatted;
} else {
std.debug.warn("Invalid -m option. Must be: raw | format\n", .{});
return error.InvalidMode;
}
} else if (std.mem.eql(u8, arg, "--update")) {
lifetime = .Forever;
} else if (std.mem.eql(u8, arg, "--ms")) {
var nextStr = try (args.next(allocator) orelse {
std.debug.warn("missing --ms time", .{});
return error.MissingMSTime;
});
timeToGet = TimeToGet{ .MsSinceDayStart = try std.fmt.parseUnsigned(u64, nextStr, 10) };
} else if (std.mem.eql(u8, arg, "--time")) {
var nextStr = try (args.next(allocator) orelse {
std.debug.warn("missing --time time", .{});
return error.MissingTimeTime;
});
timeToGet = TimeToGet{ .MsSinceEpoch = try std.fmt.parseUnsigned(u64, nextStr, 10) };
} else {
std.debug.warn("Invalid argument {}. See --help\n", .{arg});
return error.InvalidArgument;
}
}
}
switch (lifetime) {
.Forever => while (true) {
try stdout.print("\r", .{});
try printTime(stdout, timeToGet, mode);
try stdout.print("\x1b[0K", .{});
std.time.sleep(100);
},
.Once => {
try printTime(stdout, timeToGet, mode);
try stdout.print("\n", .{});
},
}
}
|
src/cli.zig
|
const std = @import("std");
const path = std.fs.path;
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const glslc_command = if (std.builtin.os.tag == .windows) "tools/win/glslc.exe" else "glslc";
pub fn build(b: *Builder) void {
const exe = b.addExecutable("zig-gltf", "src/main.zig");
setDependencies(b, exe);
exe.install();
const run_step = b.step("run", "Run the project");
const run_cmd = exe.run();
run_step.dependOn(&run_cmd.step);
const tests = b.addTest("src/all_tests.zig");
setDependencies(b, tests);
const vscode_exe = b.addExecutable("vscode", "src/main.zig");
setDependencies(b, vscode_exe);
const vscode_install = b.addInstallArtifact(vscode_exe);
const vscode_step = b.step("vscode", "Build for VSCode");
vscode_step.dependOn(&vscode_install.step);
const run_tests = b.step("test", "Run all tests");
run_tests.dependOn(&tests.step);
}
fn setDependencies(b: *Builder, step: *LibExeObjStep) void {
const mode = b.standardReleaseOptions();
step.setBuildMode(mode);
step.linkLibC();
step.addPackagePath("imgui", "include/imgui.zig");
step.addPackagePath("vk", "include/vk.zig");
step.addPackagePath("glfw", "include/glfw.zig");
step.addPackagePath("cgltf", "include/cgltf.zig");
step.addPackagePath("enet", "include/enet.zig");
if (std.builtin.os.tag == .windows) {
if (mode == .Debug) {
step.linkSystemLibrary("lib/win/cimguid");
step.linkSystemLibrary("lib/win/enetd");
} else {
step.linkSystemLibrary("lib/win/cimgui");
step.linkSystemLibrary("lib/win/enet");
}
step.linkSystemLibrary("lib/win/glfw3");
step.linkSystemLibrary("lib/win/vulkan-1");
step.linkSystemLibrary("gdi32");
step.linkSystemLibrary("shell32");
step.linkSystemLibrary("winmm");
step.linkSystemLibrary("ws2_32");
} else {
step.linkSystemLibrary("glfw");
step.linkSystemLibrary("vulkan");
@compileError("TODO: Build and link cimgui for non-windows platforms");
@compileError("TODO: Build and link enet for non-windows platforms");
}
step.addCSourceFile("c_src/cgltf.c", &[_][]const u8{ "-std=c99", "-DCGLTF_IMPLEMENTATION", "-D_CRT_SECURE_NO_WARNINGS" });
}
fn addShader(b: *Builder, exe: anytype, in_file: []const u8, out_file: []const u8) !void {
// example:
// glslc -o shaders/vert.spv shaders/shader.vert
const dirname = "shaders";
const full_in = try path.join(b.allocator, &[_][]const u8{ dirname, in_file });
const full_out = try path.join(b.allocator, &[_][]const u8{ dirname, out_file });
const run_cmd = b.addSystemCommand(&[_][]const u8{
glslc_command,
"-o",
full_out,
full_in,
});
exe.step.dependOn(&run_cmd.step);
}
|
build.zig
|
const std = @import("std");
const gl = @import("../deps/zgl/zgl.zig");
const datauri = @import("datauri.zig");
const util = @import("util.zig");
const zm = @import("zm.zig");
pub const File = struct {
arena: std.heap.ArenaAllocator,
scene: ?*Scene,
scenes: []Scene,
nodes: []Node,
meshes: []Mesh,
buffers: []Buffer,
buffer_views: []BufferView,
accessors: []Accessor,
// Load a glTF file from the raw JSON data, loading necessary files from workdir
pub fn initGltf(allocator: *std.mem.Allocator, json: []const u8, workdir: ?std.fs.Dir) !File {
return File.init(allocator, json, &.{ .dir = workdir });
}
fn init(allocator: *std.mem.Allocator, json: []const u8, loader: *DataLoader) !File {
var tmp_arena = std.heap.ArenaAllocator.init(allocator);
defer tmp_arena.deinit();
var tmp = try std.json.parse(FileI, &std.json.TokenStream.init(json), .{
.allocator = &tmp_arena.allocator,
.ignore_unknown_fields = true,
});
return tmp.convert(std.heap.ArenaAllocator.init(allocator), loader);
}
pub fn deinit(self: File) void {
self.arena.deinit();
}
};
pub const Scene = struct {
nodes: []*Node,
};
pub const Node = struct {
children: []*Node,
matrix: [4 * 4]f32,
mesh: ?*Mesh,
};
pub const Mesh = struct {
primitives: []Primitive,
pub const Primitive = struct {
attributes: Attributes,
indices: ?u32,
material: ?u32,
mode: gl.PrimitiveType,
};
pub const Attributes = struct {
position: ?u32,
normal: ?u32,
color_0: ?u32,
};
};
pub const Buffer = []const u8;
pub const BufferView = struct {
buffer: usize,
byte_offset: usize,
byte_length: usize,
byte_stride: usize,
target: gl.BufferTarget,
};
pub const Accessor = struct {
buffer_view: u32,
byte_offset: usize,
components: u5,
component_type: gl.Type,
count: u32,
normalized: bool,
};
// TODO
// pub const Camera = 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 {};
////// Internal types //////
const DataLoader = struct {
dir: ?std.fs.Dir = null,
glb: ?[]const u8 = null,
/// allocator must be the same one used to allocate glb
fn load(self: *DataLoader, allocator: *std.mem.Allocator, uri: ?[]const u8) ![]const u8 {
if (uri) |u| {
if (std.mem.startsWith(u8, u, "data:")) {
return datauri.parse(allocator, u);
} else if (self.dir) |dir| {
// Open file
const f = try dir.openFile(u, .{});
defer f.close();
return try f.readToEndAlloc(allocator, std.math.maxInt(u64));
} else {
return error.WorkDirRequired;
}
} else {
const data = self.glb orelse return error.NoGlbData;
self.glb = null;
return data;
}
}
};
const FileI = struct {
scene: ?usize = null,
scenes: []SceneI = &.{},
nodes: []NodeI = &.{},
meshes: []MeshI = &.{},
buffers: []BufferI = &.{},
bufferViews: []BufferViewI = &.{},
accessors: []AccessorI = &.{},
fn convert(self: FileI, arena: std.heap.ArenaAllocator, loader: *DataLoader) !File {
var res: File = undefined;
res.arena = arena;
const allocator = &res.arena.allocator;
res.accessors = try allocator.alloc(Accessor, self.accessors.len);
for (self.accessors) |accessor, i| {
res.accessors[i] = try accessor.convert(self.bufferViews);
}
res.buffer_views = try allocator.alloc(BufferView, self.bufferViews.len);
for (self.bufferViews) |buffer_view, i| {
res.buffer_views[i] = try buffer_view.convert();
}
res.buffers = try allocator.alloc(Buffer, self.buffers.len);
for (self.buffers) |buffer, i| {
res.buffers[i] = try buffer.convert(allocator, loader);
}
res.meshes = try allocator.alloc(Mesh, self.meshes.len);
for (self.meshes) |mesh, i| {
res.meshes[i] = try mesh.convert(allocator);
}
res.nodes = try allocator.alloc(Node, self.nodes.len);
for (self.nodes) |node, i| {
res.nodes[i] = try node.convert(allocator, res.nodes, res.meshes);
}
res.scenes = try allocator.alloc(Scene, self.scenes.len);
for (self.scenes) |scene, i| {
res.scenes[i] = try scene.convert(allocator, res.nodes);
}
if (self.scene) |idx| {
res.scene = &res.scenes[idx];
}
return res;
}
};
const SceneI = struct {
nodes: []usize = &.{},
fn convert(self: SceneI, allocator: *std.mem.Allocator, all_nodes: []Node) !Scene {
const nodes = try allocator.alloc(*Node, self.nodes.len);
for (self.nodes) |node_idx, i| {
nodes[i] = &all_nodes[node_idx];
}
return Scene{ .nodes = nodes };
}
};
const NodeI = struct {
children: []usize = &.{},
mesh: ?usize,
matrix: [4 * 4]f32 = .{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
},
translation: [3]f32 = .{ 0, 0, 0 },
rotation: [4]f32 = .{ 0, 0, 0, 1 },
scale: [3]f32 = .{ 1, 1, 1 },
fn convert(self: NodeI, allocator: *std.mem.Allocator, nodes: []Node, meshes: []Mesh) !Node {
const matrix = zm.translate(self.translation)
.mul(zm.rotate(self.rotation))
.mul(zm.scale(self.scale))
.mul(zm.mat(4, 4, self.matrix))
.toArray();
const children = try allocator.alloc(*Node, self.children.len);
for (self.children) |child_idx, i| {
children[i] = &nodes[child_idx];
}
return Node{
.children = children,
.matrix = matrix,
.mesh = if (self.mesh) |i| &meshes[i] else null,
};
}
};
const MeshI = struct {
primitives: []PrimitiveI,
fn convert(self: MeshI, allocator: *std.mem.Allocator) !Mesh {
const primitives = try allocator.alloc(Mesh.Primitive, self.primitives.len);
errdefer allocator.free(primitives);
for (self.primitives) |p, i| {
primitives[i] = .{
.attributes = .{
.position = p.attributes.POSITION,
.normal = p.attributes.NORMAL,
.color_0 = p.attributes.COLOR_0,
},
.indices = p.indices,
.material = p.material,
.mode = try std.meta.intToEnum(gl.PrimitiveType, p.mode),
};
}
return Mesh{ .primitives = primitives };
}
const PrimitiveI = struct {
attributes: struct {
POSITION: ?u32,
NORMAL: ?u32,
COLOR_0: ?u32,
},
indices: ?u32 = null,
material: ?u32 = null,
mode: u32 = 4,
};
};
const BufferI = struct {
byteLength: usize,
uri: ?[]const u8 = null,
fn convert(self: BufferI, allocator: *std.mem.Allocator, loader: *DataLoader) !Buffer {
const data = try loader.load(allocator, self.uri);
if (self.byteLength > data.len) {
return error.NotEnoughData;
}
return data[0..self.byteLength];
}
};
const BufferViewI = struct {
buffer: usize,
byteOffset: usize = 0,
byteLength: usize,
byteStride: ?usize = null,
target: ?u32 = null,
fn convert(self: BufferViewI) !BufferView {
return BufferView{
.buffer = self.buffer,
.byte_offset = self.byteOffset,
.byte_length = self.byteLength,
.byte_stride = self.byteStride orelse 0,
.target = if (self.target) |t|
try std.meta.intToEnum(gl.BufferTarget, t)
else
.array_buffer,
};
}
};
const AccessorI = struct {
bufferView: u32,
byteOffset: usize = 0,
componentType: u32,
normalized: bool = false,
count: u32,
type: []const u8,
// TODO: sparse accessors
fn convert(self: AccessorI, viewsi: []BufferViewI) !Accessor {
const component_type = try std.meta.intToEnum(gl.Type, self.componentType);
const components = try parseType(self.type);
if (viewsi[self.bufferView].byteStride == null) {
viewsi[self.bufferView].byteStride = components * util.glSizeOf(component_type);
}
return Accessor{
.buffer_view = self.bufferView,
.byte_offset = self.byteOffset,
.component_type = component_type,
.components = components,
.normalized = self.normalized,
.count = self.count,
};
}
fn parseType(type_name: []const u8) !u5 {
if (std.mem.eql(u8, type_name, "SCALAR")) {
return 1;
} else if (std.mem.eql(u8, type_name, "VEC2")) {
return 2;
} else if (std.mem.eql(u8, type_name, "VEC3")) {
return 3;
} else if (std.mem.eql(u8, type_name, "VEC4")) {
return 4;
} else if (std.mem.eql(u8, type_name, "MAT2")) {
return 2 * 2;
} else if (std.mem.eql(u8, type_name, "MAT3")) {
return 3 * 3;
} else if (std.mem.eql(u8, type_name, "MAT4")) {
return 4 * 4;
} else {
return error.InvalidType;
}
}
};
|
src/gltf.zig
|
const std = @import("std");
const assert = std.debug.assert;
const c = @cImport({
@cInclude("SDL2/SDL.h");
});
const raytracer = @import("raytracer.zig");
const f32_3 = raytracer.f32_3;
const PixelFormatBGRASizeInBytes: u32 = 4;
const ImageCpuBitDepth: u32 = 32;
fn linear_to_srgb(color: f32_3) f32_3 {
// FIXME not technically correct but close enough
const gamma: f32 = 1.0 / 2.2;
return .{
std.math.pow(f32, color[0], gamma),
std.math.pow(f32, color[1], gamma),
std.math.pow(f32, color[2], gamma),
};
}
fn process_pixel(scene_color: raytracer.f32_4) [4]u8 {
const sample_count = @maximum(1.0, scene_color[3]);
const swapchain_pixel = linear_to_srgb(f32_3{ scene_color[0], scene_color[1], scene_color[2] } / @splat(3, sample_count));
return [4]u8{ @floatToInt(u8, @minimum(1.0, swapchain_pixel[0]) * 255.0), @floatToInt(u8, @minimum(1.0, swapchain_pixel[1]) * 255.0), @floatToInt(u8, @minimum(1.0, swapchain_pixel[2]) * 255.0), 255 };
}
fn fill_image_buffer(imageOutput: []u8, rt: *raytracer.RaytracerState) void {
var j: u32 = 0;
while (j < rt.frame_extent[1]) : (j += 1) {
var i: u32 = 0;
while (i < rt.frame_extent[0]) : (i += 1) {
const pixelIndexFlatDst = j * rt.frame_extent[0] + i;
const pixelOutputOffsetInBytes = pixelIndexFlatDst * PixelFormatBGRASizeInBytes;
const primaryColorBGRA = process_pixel(rt.framebuffer[i][j]);
imageOutput[pixelOutputOffsetInBytes + 0] = primaryColorBGRA[0];
imageOutput[pixelOutputOffsetInBytes + 1] = primaryColorBGRA[1];
imageOutput[pixelOutputOffsetInBytes + 2] = primaryColorBGRA[2];
imageOutput[pixelOutputOffsetInBytes + 3] = primaryColorBGRA[3];
}
}
}
pub fn execute_main_loop(allocator: std.mem.Allocator, rt: *raytracer.RaytracerState) !void {
const width = rt.frame_extent[0];
const height = rt.frame_extent[1];
const stride = width * PixelFormatBGRASizeInBytes; // No extra space between lines
const image_size_bytes = stride * height;
var image_cpu = try allocator.alloc(u8, image_size_bytes);
defer allocator.free(image_cpu);
if (c.SDL_Init(c.SDL_INIT_EVERYTHING) != 0) {
c.SDL_Log("Unable to initialize SDL: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
defer c.SDL_Quit();
const window = c.SDL_CreateWindow("", c.SDL_WINDOWPOS_UNDEFINED, c.SDL_WINDOWPOS_UNDEFINED, @intCast(c_int, width), @intCast(c_int, height), c.SDL_WINDOW_SHOWN) orelse {
c.SDL_Log("Unable to create window: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyWindow(window);
if (c.SDL_SetHint(c.SDL_HINT_RENDER_VSYNC, "1") == c.SDL_FALSE) {
c.SDL_Log("Unable to set hint: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
const renderer = c.SDL_CreateRenderer(window, -1, c.SDL_RENDERER_ACCELERATED) orelse {
c.SDL_Log("Unable to create renderer: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyRenderer(renderer);
const is_big_endian = c.SDL_BYTEORDER == c.SDL_BIG_ENDIAN;
var rmask: u32 = if (is_big_endian) 0xff000000 else 0x000000ff;
var gmask: u32 = if (is_big_endian) 0x00ff0000 else 0x0000ff00;
var bmask: u32 = if (is_big_endian) 0x0000ff00 else 0x00ff0000;
var amask: u32 = if (is_big_endian) 0x000000ff else 0xff000000;
var pitch: u32 = stride;
const render_surface = c.SDL_CreateRGBSurfaceFrom(@ptrCast(*anyopaque, &image_cpu[0]), @intCast(c_int, width), @intCast(c_int, height), @intCast(c_int, ImageCpuBitDepth), @intCast(c_int, pitch), rmask, gmask, bmask, amask) orelse {
c.SDL_Log("Unable to create surface: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_FreeSurface(render_surface);
var shouldExit = false;
var last_frame_time_ms: u32 = c.SDL_GetTicks();
while (!shouldExit) {
const current_frame_time_ms: u32 = c.SDL_GetTicks();
// const frame_delta_secs = @intToFloat(f32, current_frame_time_ms - last_frame_time_ms) * 0.001;
// Poll events
var sdlEvent: c.SDL_Event = undefined;
while (c.SDL_PollEvent(&sdlEvent) > 0) {
switch (sdlEvent.type) {
c.SDL_QUIT => {
shouldExit = true;
},
c.SDL_KEYDOWN => {
if (sdlEvent.key.keysym.sym == c.SDLK_ESCAPE)
shouldExit = true;
},
else => {},
}
}
const work_finished = raytracer.render_workload(rt, 4);
if (work_finished) {
raytracer.add_fullscreen_workload(rt);
}
// Set window title
const string = try std.fmt.allocPrintZ(allocator, "Raytracer {d}x{d} w:{d}", .{ rt.frame_extent[0], rt.frame_extent[1], rt.work_queue_size });
defer allocator.free(string);
c.SDL_SetWindowTitle(window, string.ptr);
// Render
fill_image_buffer(image_cpu, rt);
const render_texture = c.SDL_CreateTextureFromSurface(renderer, render_surface) orelse {
c.SDL_Log("Unable to create texture from surface: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyTexture(render_texture);
_ = c.SDL_RenderClear(renderer);
_ = c.SDL_RenderCopy(renderer, render_texture, null, null);
// Present
c.SDL_RenderPresent(renderer);
last_frame_time_ms = current_frame_time_ms;
}
}
|
src/sdl2_backend.zig
|
const std = @import("std");
const io = @import("io.zig");
const config = @import("config.zig");
const parseTask = @import("task_parser.zig").parseTask;
const Arguments = @import("args.zig");
const Todo = @import("todo.zig");
const Date = @import("date.zig");
const util = @import("util.zig");
const Allocator = std.mem.Allocator;
pub const Styles = struct {
pub const BOLD = "\x1B[1m";
pub const UNDERLINE = "\x1B[4m";
pub const FAIL = "\x1B[91m" ++ BOLD;
pub const SUCCESS = "\x1B[32m" ++ BOLD;
pub const HASHTAG = "\x1B[36m" ++ BOLD ++ UNDERLINE;
pub const NORMAL = "\x1B[37m" ++ BOLD;
pub const STRIKE = "\x1B[9m";
pub const RESET = "\x1B[0m";
};
const Command = struct {
names: []const [:0]const u8,
commandFn: fn (*Allocator, *Arguments) anyerror!void,
};
const Commands = &[_]Command {
Command {
.names = &[_][:0]const u8{"add", "a"},
.commandFn = addTask,
},
Command {
.names = &[_][:0]const u8{"list", "l"},
.commandFn = list,
},
Command {
.names = &[_][:0]const u8{"remove", "rem", "r", "erase"},
.commandFn = removeTask,
},
Command {
.names = &[_][:0]const u8{"complete", "comp", "c"},
.commandFn = completeTask,
},
Command {
.names = &[_][:0]const u8{"count"},
.commandFn = countHashtags,
},
Command {
.names = &[_][:0]const u8{"cleareverythingwithoutasking"}, // Clear all tasks, used for debug.
.commandFn = clearAllTasks,
},
Command {
.names = &[_][:0]const u8{"now"},
.commandFn = now,
},
Command {
.names = &[_][:0]const u8{"utc"},
.commandFn = utc,
},
Command {
.names = &[_][:0]const u8{"daylight"},
.commandFn = daylight,
},
Command {
.names = &[_][:0]const u8{"help"},
.commandFn = help,
}
};
pub fn execute(alloc: *Allocator, raw_args: [][:0]const u8) !void {
var args = Arguments {
.args = raw_args,
};
if (args.peek()) |arg| {
try runCommand(alloc, &args);
} else {
try noArgs(alloc, &args);
}
}
fn runCommand(alloc: *Allocator, args: *Arguments) !void {
const arg = args.peek().?;
var buffer: [40]u8 = undefined;
std.mem.copy(u8, &buffer, arg[0..arg.len]);
const str = buffer[0..arg.len];
util.toLowerStr(str);
inline for (Commands) |command| {
inline for (command.names) |n| {
if (std.mem.eql(u8, str, n)) {
try command.commandFn(alloc, args);
return;
}
}
}
try commandDoesNotExist(arg);
}
fn commandDoesNotExist(commandName: []const u8) !void {
try printFail("Command {s} does not exist.\n", .{commandName});
}
fn noArgs(alloc: *Allocator, args: *Arguments) !void {
try printFail("No arguments passed. Running help command...\n", .{});
try help(alloc, args);
}
fn list(alloc: *Allocator, args: *Arguments) !void {
const noTasks = struct {
pub fn noTasks() !void {
try printNormal("There are no tasks available.\n", .{});
}
}.noTasks;
var todo = (try io.read(alloc)) orelse {
try noTasks();
return;
}; defer todo.deinit();
if (util.tailQueueLen(todo.tasks) == 0) {
try noTasks();
}
todo.updateIndicies();
// Read arguments
_ = args.next(); // skip -list
while (args.next()) |a| {
todo.filterTasks(a);
}
var it = todo.tasks.first;
var index: usize = 1;
while (it) |node| : (it = node.next) {
try printNormal("{d}. ", .{node.data.index.?});
try TaskPrinter.p(todo, node.data, true);
try newline();
index += 1;
}
}
fn addTask(alloc: *Allocator, args: *Arguments) !void {
_ = args.next();
var todo: Todo = (try io.read(alloc)) orelse Todo.init(alloc);
defer todo.deinit();
var buffer: [config.MAX_LINE]u8 = undefined;
const task = parseTask(&buffer, todo.timezone, args) catch |err| {
switch (err) {
error.InvalidDate => try printFail("Invalid date.\n", .{}),
error.AmbiguousAbbr => try printFail("Month name is ambiguous.\n", .{}),
else => try printFail("Something went wrong...{any}\n", .{err}),
}
return;
};
try todo.add(task);
try io.save(todo);
try printSuccess("Added task.\n", .{});
try TaskPrinter.p(todo, task, false);
try newline();
}
/// Removes a task. First task is index 1.
fn removeTask(alloc: *Allocator, args: *Arguments) !void {
_ = args.next(); // Skip the argument
const number = (try nextArgIndex(usize, args)) orelse return;
var todo = (try io.read(alloc)) orelse {
try printFail("Cannot delete tasks. Todo list is empty.\n", .{});
return;
}; defer todo.deinit();
if (number < 1) {
try printFail("Index cannot be less than 1.\n", .{});
return;
}
const removed = todo.remove(number - 1) orelse {
try printFail("Task does not exist.\n", .{});
return;
}; defer alloc.destroy(removed);
try printSuccess("Removed task\n", .{});
try TaskPrinter.p(todo, removed.data, true);
try newline();
try io.save(todo);
}
/// Completes a task. Index starts at 1.
fn completeTask(alloc: *Allocator, args: *Arguments) !void {
_ = args.next(); // Skips the -c argument
const number = (try nextArgIndex(usize, args)) orelse return;
var todo = (try io.read(alloc)) orelse {
try printFail("Could not complete task. Todo list is empty.\n", .{});
return;
}; defer todo.deinit();
var node = todo.get(number - 1) orelse {
try printFail("Task does not exist.\n", .{});
return;
};
node.data.completed = !node.data.completed;
try TaskPrinter.p(todo, node.data, true);
try newline();
try io.save(todo);
}
fn countHashtags(alloc: *Allocator, args: *Arguments) !void {
var c_names = [_][]u8{undefined} ** config.MAX_LINE;
var c_counter: [config.MAX_LINE]util.Pair(u64) = undefined;
var c = Todo.Task.HashtagCounter {
.names = &c_names,
.counter = &c_counter,
};
const todo = (try io.read(alloc)) orelse {
try printFail("Todo list is empty.\n", .{});
return;
}; defer todo.deinit();
var hashtag_names: [config.MAX_LINE][]const u8 = undefined;
var hashtag_counter: [config.MAX_LINE]util.Pair(u64) = undefined;
var it = todo.tasks.first;
while (it) |node| : (it = node.next) {
var tags = node.data.hashtags(&hashtag_names, &hashtag_counter);
while (tags.next()) |tag| {
_ = c.add(tag, node.data);
}
}
for (c.names[0..c.len]) |n, i| {
try print(Styles.HASHTAG, "{s}", .{n});
try printNormal(": {d} total | {d} uncompleted | {d} completed\n", .{c.counter[i].a + c.counter[i].b, c.counter[i].b, c.counter[i].a});
alloc.free(n);
}
}
fn clearAllTasks(alloc: *Allocator, args: *Arguments) !void {
const todo = Todo.init(alloc);
defer todo.deinit();
try io.save(todo);
try printSuccess("👍 Deleted all tasks.\n", .{});
}
fn now(alloc: *Allocator, args: *Arguments) !void {
const todo = (try io.read(alloc)) orelse Todo.init(alloc);
const date = (Date.DateWithTimezone {
.date = Date.now(),
.timezone = todo.timezone,
}).dateWithTimezone();
const daylight_str: []const u8 = if (todo.timezone.daylight) "(daylight)"[0..] else " "[0..];
try printNormal("Now: {any} {d:0>2}h{d:0>2}:{d:0>2}, UTC{d:2} {s}", .{
date, @intCast(u8, date.hours), @intCast(u8, date.minutes), @intCast(u8, date.seconds),
todo.timezone.offset.hours + if (todo.timezone.daylight) @as(i64, 1) else @as(i64, 0),
daylight_str});
}
fn utc(alloc: *Allocator, args: *Arguments) !void {
_ = args.next();
var todo = (try io.read(alloc)) orelse Todo.init(alloc);
const arg = args.next() orelse {
try printFail("Expected an integer\n", .{});
return;
};
const input = std.fmt.parseInt(i64, arg, 10) catch {
try printFail("Expected an integer\n", .{});
return;
};
todo.timezone.offset.hours = input;
try io.save(todo);
try now(alloc, args);
}
fn daylight(alloc: *Allocator, args: *Arguments) !void {
_ = args.next();
var todo = (try io.read(alloc)) orelse Todo.init(alloc);
const arg = args.next() orelse {
try printFail("Expected an integer\n", .{});
return;
};
const input = std.fmt.parseInt(i64, arg, 10) catch {
try printFail("Expected an integer\n", .{});
return;
};
todo.timezone.daylight = (input != 0);
try io.save(todo);
try now(alloc, args);
}
fn help(alloc: *Allocator, args: *Arguments) !void {
try printSuccess("Add tasks: ", .{});
try printNormal("todo add adding a new task\n", .{});
try printSuccess("Add tasks with a due date: ", .{});
try printNormal("todo add this task is due on may 24 ; may 24\n", .{});
try printSuccess("Other ways to add tasks: ", .{});
try printNormal("todo add this is due tomorrow (today) (next week) (this month)... ; tomorrow\n", .{});
try printSuccess("List tasks: ", .{});
try printNormal("todo list\n", .{});
try printSuccess("Search tasks: ", .{});
try printNormal("todo list keyword1 keyword2...\n", .{});
try printSuccess("Complete tasks: ", .{});
try printNormal("todo complete 3\n", .{});
try printSuccess("Remove tasks: ", .{});
try printNormal("todo remove 3\n", .{});
try printSuccess("Set the timezone: ", .{});
try printNormal("todo utc -5\n", .{});
try printSuccess("Enable daylight savings: ", .{});
try printNormal("todo daylight 1\n", .{});
try printSuccess("Display current time: ", .{});
try printNormal("todo now\n", .{});
try printSuccess("Display hashtags: ", .{});
try printNormal("todo count\n", .{});
}
// ======= HELPER FUNCTIONS =======
fn getWriter() std.fs.File.Writer {
return std.io.getStdOut().writer();
}
fn newline() !void {
try printNormal("\n", .{});
}
/// Prints a failed statement.
pub fn printFail(comptime str: []const u8, args: anytype) !void {
try print(Styles.FAIL, str, args);
}
pub fn printSuccess(comptime str: []const u8, args: anytype) !void {
try print(Styles.SUCCESS, str, args);
}
pub fn printNormal(comptime str: []const u8, args: anytype) !void {
try print(Styles.NORMAL, str, args);
}
fn print(style: []const u8, comptime str: []const u8, args: anytype) !void {
const writer = getWriter();
try writer.print("{s}", .{style});
try writer.print(str, args);
try writer.print("{s}", .{Styles.RESET});
}
fn nextArgIndex(comptime T: type, args: *Arguments) !?T {
const str_num = args.next() orelse return 1;
return std.fmt.parseInt(T, str_num, 10) catch |err| blk: {
try printFail("{s} is not a number.", .{str_num});
break :blk null;
};
}
// ======= PRINTING OBJECTS =====
const TaskPrinter = struct {
pub fn p(todo: Todo, task: Todo.Task, checkmark: bool) !void {
const completed_str = blk: {
if (checkmark) {
break :blk if (task.completed) "✅ " else "❌ ";
} else break :blk "";
};
try printNormal("{s}", .{completed_str});
try pretty_content(task);
if (task.due) |date| {
try printNormal("📅 {any}", .{(Date.DateWithTimezone {.date = date, .timezone = todo.timezone,}).flatten()});
}
}
/// Colors hashtags
fn pretty_content(task: Todo.Task) !void {
var words = std.mem.tokenize(task.content, " ");
while (words.next()) |word| {
if (Todo.Task.isHashtag(word)) {
try print(Styles.HASHTAG, "{s}", .{word});
try printNormal(" ", .{});
} else {
try printNormal("{s} ", .{word});
}
}
}
};
|
src/cli.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const webgpu = @import("../../webgpu.zig");
const dummy = @import("./dummy.zig");
pub const Device = struct {
const vtable = webgpu.Device.VTable{
.destroy_fn = destroy,
.create_buffer_fn = createBuffer,
.create_texture_fn = createTexture,
.create_sampler_fn = createSampler,
.create_bind_group_layout_fn = createBindGroupLayout,
.create_pipeline_layout_fn = createPipelineLayout,
.create_bind_group_fn = createBindGroup,
.create_shader_module_fn = createShaderModule,
.create_compute_pipeline_fn = createComputePipeline,
.create_render_pipeline_fn = createRenderPipeline,
.create_command_encoder_fn = createCommandEncoder,
.create_render_bundle_encoder_fn = createRenderBundleEncoder,
};
super: webgpu.Device,
allocator: Allocator,
queue: *Queue,
pub fn create(adapter: *dummy.Adapter, descriptor: webgpu.DeviceDescriptor) webgpu.Adapter.RequestDeviceError!*Device {
var instance = @fieldParentPtr(dummy.Instance, "super", adapter.super.instance);
_ = descriptor;
var device = try instance.allocator.create(Device);
errdefer instance.allocator.destroy(device);
device.super = .{
.__vtable = &vtable,
.instance = &instance.super,
.adapter = &adapter.super,
.features = .{},
.limits = .{},
.queue = undefined,
};
device.allocator = instance.allocator;
device.queue = try Queue.create(device);
errdefer device.queue.destroy(device);
device.super.queue = &device.queue.super;
return device;
}
fn destroy(super: *webgpu.Device) void {
var device = @fieldParentPtr(Device, "super", super);
device.queue.destroy(device);
device.allocator.destroy(device);
}
fn createBuffer(super: *webgpu.Device, descriptor: webgpu.BufferDescriptor) webgpu.Device.CreateBufferError!*webgpu.Buffer {
var device = @fieldParentPtr(Device, "super", super);
var buffer = try dummy.Buffer.create(device, descriptor);
return &buffer.super;
}
fn createTexture(super: *webgpu.Device, descriptor: webgpu.TextureDescriptor) webgpu.Device.CreateTextureError!*webgpu.Texture {
var device = @fieldParentPtr(Device, "super", super);
var texture = try dummy.Texture.create(device, descriptor);
return &texture.super;
}
fn createSampler(super: *webgpu.Device, descriptor: webgpu.SamplerDescriptor) webgpu.Device.CreateSamplerError!*webgpu.Sampler {
var device = @fieldParentPtr(Device, "super", super);
var sampler = try dummy.Sampler.create(device, descriptor);
return &sampler.super;
}
fn createBindGroupLayout(super: *webgpu.Device, descriptor: webgpu.BindGroupLayoutDescriptor) webgpu.Device.CreateBindGroupLayoutError!*webgpu.BindGroupLayout {
var device = @fieldParentPtr(Device, "super", super);
var bind_group_layout = try dummy.BindGroupLayout.create(device, descriptor);
return &bind_group_layout.super;
}
fn createPipelineLayout(super: *webgpu.Device, descriptor: webgpu.PipelineLayoutDescriptor) webgpu.Device.CreatePipelineLayoutError!*webgpu.PipelineLayout {
var device = @fieldParentPtr(Device, "super", super);
var pipeline_layout = try dummy.PipelineLayout.create(device, descriptor);
return &pipeline_layout.super;
}
fn createBindGroup(super: *webgpu.Device, descriptor: webgpu.BindGroupDescriptor) webgpu.Device.CreateBindGroupError!*webgpu.BindGroup {
var device = @fieldParentPtr(Device, "super", super);
var bind_group = try dummy.BindGroup.create(device, descriptor);
return &bind_group.super;
}
fn createShaderModule(super: *webgpu.Device, descriptor: webgpu.ShaderModuleDescriptor) webgpu.Device.CreateShaderModuleError!*webgpu.ShaderModule {
var device = @fieldParentPtr(Device, "super", super);
var shader_module = try dummy.ShaderModule.create(device, descriptor);
return &shader_module.super;
}
fn createComputePipeline(super: *webgpu.Device, descriptor: webgpu.ComputePipelineDescriptor) webgpu.Device.CreateComputePipelineError!*webgpu.ComputePipeline {
var device = @fieldParentPtr(Device, "super", super);
var compute_pipeline = try dummy.ComputePipeline.create(device, descriptor);
return &compute_pipeline.super;
}
fn createRenderPipeline(super: *webgpu.Device, descriptor: webgpu.RenderPipelineDescriptor) webgpu.Device.CreateRenderPipelineError!*webgpu.RenderPipeline {
var device = @fieldParentPtr(Device, "super", super);
var render_pipeline = try dummy.RenderPipeline.create(device, descriptor);
return &render_pipeline.super;
}
fn createCommandEncoder(super: *webgpu.Device, descriptor: webgpu.CommandEncoderDescriptor) webgpu.Device.CreateCommandEncoderError!*webgpu.CommandEncoder {
var device = @fieldParentPtr(Device, "super", super);
var command_encoder = try dummy.CommandEncoder.create(device, descriptor);
return &command_encoder.super;
}
fn createRenderBundleEncoder(super: *webgpu.Device, descriptor: webgpu.RenderBundleEncoderDescriptor) webgpu.Device.CreateRenderBundleEncoderError!*webgpu.RenderBundleEncoder {
var device = @fieldParentPtr(Device, "super", super);
var render_bundle_encoder = try dummy.RenderBundleEncoder.create(device, descriptor);
return &render_bundle_encoder.super;
}
};
pub const Queue = struct {
const vtable = webgpu.Queue.VTable{
.submit_fn = submit,
.on_submitted_work_done_fn = onSubmittedWorkDone,
.write_buffer_fn = writeBuffer,
.write_texture_fn = writeTexture,
};
super: webgpu.Queue,
pub fn create(device: *Device) webgpu.Adapter.RequestDeviceError!*Queue {
var queue = try device.allocator.create(Queue);
errdefer device.allocator.destroy(queue);
queue.super = .{
.__vtable = &vtable,
};
return queue;
}
pub fn destroy(queue: *Queue, device: *Device) void {
device.allocator.destroy(queue);
}
fn submit(super: *webgpu.Queue, command_buffers: []webgpu.CommandBuffer) webgpu.Queue.SubmitError!void {
_ = super;
_ = command_buffers;
}
fn onSubmittedWorkDone(super: *webgpu.Queue) void {
_ = super;
}
fn writeBuffer(super: *webgpu.Queue, buffer: *webgpu.Buffer, buffer_offset: usize, data: []const u8) webgpu.Queue.WriteBufferError!void {
_ = super;
_ = buffer;
_ = buffer_offset;
_ = data;
}
fn writeTexture(super: *webgpu.Queue, destination: webgpu.ImageCopyTexture, data: []const u8, data_layout: webgpu.TextureDataLayout, write_size: webgpu.Extend3D) webgpu.Queue.WriteTextureError!void {
_ = super;
_ = destination;
_ = data;
_ = data_layout;
_ = write_size;
}
};
|
src/backends/dummy/device.zig
|
const neg = @import("negXi2.zig");
const testing = @import("std").testing;
fn test__negdi2(a: i64, expected: i64) !void {
var result = neg.__negdi2(a);
try testing.expectEqual(expected, result);
}
test "negdi2" {
// TODO ensuring that math.minInt(i64); returns error
try test__negdi2(-3, 3);
try test__negdi2(-2, 2);
try test__negdi2(-1, 1);
try test__negdi2(0, 0); // special case for 2s complement
try test__negdi2(1, -1);
try test__negdi2(2, -2);
try test__negdi2(3, -3);
// max_usable == MAX(i32) == -MIN(i32)
// == 9223372036854775807 == 7fffffffffffffff
// divTrunc: max_usable / i, i=1,2,3,5,100
// 7fffffffffffffff / i
try test__negdi2(-3074457345618258602, 3074457345618258602);
try test__negdi2(3074457345618258602, -3074457345618258602);
try test__negdi2(-1844674407370955161, 1844674407370955161);
try test__negdi2(1844674407370955161, -1844674407370955161);
try test__negdi2(-922337203685477580, 922337203685477580);
try test__negdi2(922337203685477580, -922337203685477580);
// shifting: max_usable >> i, i=0..bitsize-4
// 7fffffffffffffff >> i
// 7fffffffffffffff >> i + 1
// 7fffffffffffffff >> i + 3
// 7fffffffffffffff >> i + 7
try test__negdi2(-9223372036854775807, 9223372036854775807);
try test__negdi2(9223372036854775807, -9223372036854775807);
try test__negdi2(-9223372036854775806, 9223372036854775806);
try test__negdi2(9223372036854775806, -9223372036854775806);
try test__negdi2(-9223372036854775804, 9223372036854775804);
try test__negdi2(9223372036854775804, -9223372036854775804);
try test__negdi2(-9223372036854775800, 9223372036854775800);
try test__negdi2(9223372036854775800, -9223372036854775800);
try test__negdi2(-4611686018427387903, 4611686018427387903);
try test__negdi2(4611686018427387903, -4611686018427387903);
try test__negdi2(-4611686018427387902, 4611686018427387902);
try test__negdi2(4611686018427387902, -4611686018427387902);
try test__negdi2(-4611686018427387900, 4611686018427387900);
try test__negdi2(4611686018427387900, -4611686018427387900);
try test__negdi2(-4611686018427387896, 4611686018427387896);
try test__negdi2(4611686018427387896, -4611686018427387896);
try test__negdi2(-2305843009213693951, 2305843009213693951);
try test__negdi2(2305843009213693951, -2305843009213693951);
try test__negdi2(-2305843009213693950, 2305843009213693950);
try test__negdi2(2305843009213693950, -2305843009213693950);
try test__negdi2(-2305843009213693948, 2305843009213693948);
try test__negdi2(2305843009213693948, -2305843009213693948);
try test__negdi2(-2305843009213693944, 2305843009213693944);
try test__negdi2(2305843009213693944, -2305843009213693944);
try test__negdi2(-1152921504606846975, 1152921504606846975);
try test__negdi2(1152921504606846975, -1152921504606846975);
try test__negdi2(-1152921504606846974, 1152921504606846974);
try test__negdi2(1152921504606846974, -1152921504606846974);
try test__negdi2(-1152921504606846972, 1152921504606846972);
try test__negdi2(1152921504606846972, -1152921504606846972);
try test__negdi2(-1152921504606846968, 1152921504606846968);
try test__negdi2(1152921504606846968, -1152921504606846968);
try test__negdi2(-576460752303423487, 576460752303423487);
try test__negdi2(576460752303423487, -576460752303423487);
try test__negdi2(-576460752303423486, 576460752303423486);
try test__negdi2(576460752303423486, -576460752303423486);
try test__negdi2(-576460752303423484, 576460752303423484);
try test__negdi2(576460752303423484, -576460752303423484);
try test__negdi2(-576460752303423480, 576460752303423480);
try test__negdi2(576460752303423480, -576460752303423480);
try test__negdi2(-288230376151711743, 288230376151711743);
try test__negdi2(288230376151711743, -288230376151711743);
try test__negdi2(-288230376151711742, 288230376151711742);
try test__negdi2(288230376151711742, -288230376151711742);
try test__negdi2(-288230376151711740, 288230376151711740);
try test__negdi2(288230376151711740, -288230376151711740);
try test__negdi2(-288230376151711736, 288230376151711736);
try test__negdi2(288230376151711736, -288230376151711736);
try test__negdi2(-144115188075855871, 144115188075855871);
try test__negdi2(144115188075855871, -144115188075855871);
try test__negdi2(-144115188075855870, 144115188075855870);
try test__negdi2(144115188075855870, -144115188075855870);
try test__negdi2(-144115188075855868, 144115188075855868);
try test__negdi2(144115188075855868, -144115188075855868);
try test__negdi2(-144115188075855864, 144115188075855864);
try test__negdi2(144115188075855864, -144115188075855864);
try test__negdi2(-72057594037927935, 72057594037927935);
try test__negdi2(72057594037927935, -72057594037927935);
try test__negdi2(-72057594037927934, 72057594037927934);
try test__negdi2(72057594037927934, -72057594037927934);
try test__negdi2(-72057594037927932, 72057594037927932);
try test__negdi2(72057594037927932, -72057594037927932);
try test__negdi2(-72057594037927928, 72057594037927928);
try test__negdi2(72057594037927928, -72057594037927928);
try test__negdi2(-36028797018963967, 36028797018963967);
try test__negdi2(36028797018963967, -36028797018963967);
try test__negdi2(-36028797018963966, 36028797018963966);
try test__negdi2(36028797018963966, -36028797018963966);
try test__negdi2(-36028797018963964, 36028797018963964);
try test__negdi2(36028797018963964, -36028797018963964);
try test__negdi2(-36028797018963960, 36028797018963960);
try test__negdi2(36028797018963960, -36028797018963960);
try test__negdi2(-18014398509481983, 18014398509481983);
try test__negdi2(18014398509481983, -18014398509481983);
try test__negdi2(-18014398509481982, 18014398509481982);
try test__negdi2(18014398509481982, -18014398509481982);
try test__negdi2(-18014398509481980, 18014398509481980);
try test__negdi2(18014398509481980, -18014398509481980);
try test__negdi2(-18014398509481976, 18014398509481976);
try test__negdi2(18014398509481976, -18014398509481976);
try test__negdi2(-9007199254740991, 9007199254740991);
try test__negdi2(9007199254740991, -9007199254740991);
try test__negdi2(-9007199254740990, 9007199254740990);
try test__negdi2(9007199254740990, -9007199254740990);
try test__negdi2(-9007199254740988, 9007199254740988);
try test__negdi2(9007199254740988, -9007199254740988);
try test__negdi2(-9007199254740984, 9007199254740984);
try test__negdi2(9007199254740984, -9007199254740984);
try test__negdi2(-4503599627370495, 4503599627370495);
try test__negdi2(4503599627370495, -4503599627370495);
try test__negdi2(-4503599627370494, 4503599627370494);
try test__negdi2(4503599627370494, -4503599627370494);
try test__negdi2(-4503599627370492, 4503599627370492);
try test__negdi2(4503599627370492, -4503599627370492);
try test__negdi2(-4503599627370488, 4503599627370488);
try test__negdi2(4503599627370488, -4503599627370488);
try test__negdi2(-2251799813685247, 2251799813685247);
try test__negdi2(2251799813685247, -2251799813685247);
try test__negdi2(-2251799813685246, 2251799813685246);
try test__negdi2(2251799813685246, -2251799813685246);
try test__negdi2(-2251799813685244, 2251799813685244);
try test__negdi2(2251799813685244, -2251799813685244);
try test__negdi2(-2251799813685240, 2251799813685240);
try test__negdi2(2251799813685240, -2251799813685240);
try test__negdi2(-1125899906842623, 1125899906842623);
try test__negdi2(1125899906842623, -1125899906842623);
try test__negdi2(-1125899906842622, 1125899906842622);
try test__negdi2(1125899906842622, -1125899906842622);
try test__negdi2(-1125899906842620, 1125899906842620);
try test__negdi2(1125899906842620, -1125899906842620);
try test__negdi2(-1125899906842616, 1125899906842616);
try test__negdi2(1125899906842616, -1125899906842616);
try test__negdi2(-562949953421311, 562949953421311);
try test__negdi2(562949953421311, -562949953421311);
try test__negdi2(-562949953421310, 562949953421310);
try test__negdi2(562949953421310, -562949953421310);
try test__negdi2(-562949953421308, 562949953421308);
try test__negdi2(562949953421308, -562949953421308);
try test__negdi2(-562949953421304, 562949953421304);
try test__negdi2(562949953421304, -562949953421304);
try test__negdi2(-281474976710655, 281474976710655);
try test__negdi2(281474976710655, -281474976710655);
try test__negdi2(-281474976710654, 281474976710654);
try test__negdi2(281474976710654, -281474976710654);
try test__negdi2(-281474976710652, 281474976710652);
try test__negdi2(281474976710652, -281474976710652);
try test__negdi2(-281474976710648, 281474976710648);
try test__negdi2(281474976710648, -281474976710648);
try test__negdi2(-140737488355327, 140737488355327);
try test__negdi2(140737488355327, -140737488355327);
try test__negdi2(-140737488355326, 140737488355326);
try test__negdi2(140737488355326, -140737488355326);
try test__negdi2(-140737488355324, 140737488355324);
try test__negdi2(140737488355324, -140737488355324);
try test__negdi2(-140737488355320, 140737488355320);
try test__negdi2(140737488355320, -140737488355320);
try test__negdi2(-70368744177663, 70368744177663);
try test__negdi2(70368744177663, -70368744177663);
try test__negdi2(-70368744177662, 70368744177662);
try test__negdi2(70368744177662, -70368744177662);
try test__negdi2(-70368744177660, 70368744177660);
try test__negdi2(70368744177660, -70368744177660);
try test__negdi2(-70368744177656, 70368744177656);
try test__negdi2(70368744177656, -70368744177656);
try test__negdi2(-35184372088831, 35184372088831);
try test__negdi2(35184372088831, -35184372088831);
try test__negdi2(-35184372088830, 35184372088830);
try test__negdi2(35184372088830, -35184372088830);
try test__negdi2(-35184372088828, 35184372088828);
try test__negdi2(35184372088828, -35184372088828);
try test__negdi2(-35184372088824, 35184372088824);
try test__negdi2(35184372088824, -35184372088824);
try test__negdi2(-17592186044415, 17592186044415);
try test__negdi2(17592186044415, -17592186044415);
try test__negdi2(-17592186044414, 17592186044414);
try test__negdi2(17592186044414, -17592186044414);
try test__negdi2(-17592186044412, 17592186044412);
try test__negdi2(17592186044412, -17592186044412);
try test__negdi2(-17592186044408, 17592186044408);
try test__negdi2(17592186044408, -17592186044408);
try test__negdi2(-8796093022207, 8796093022207);
try test__negdi2(8796093022207, -8796093022207);
try test__negdi2(-8796093022206, 8796093022206);
try test__negdi2(8796093022206, -8796093022206);
try test__negdi2(-8796093022204, 8796093022204);
try test__negdi2(8796093022204, -8796093022204);
try test__negdi2(-8796093022200, 8796093022200);
try test__negdi2(8796093022200, -8796093022200);
try test__negdi2(-4398046511103, 4398046511103);
try test__negdi2(4398046511103, -4398046511103);
try test__negdi2(-4398046511102, 4398046511102);
try test__negdi2(4398046511102, -4398046511102);
try test__negdi2(-4398046511100, 4398046511100);
try test__negdi2(4398046511100, -4398046511100);
try test__negdi2(-4398046511096, 4398046511096);
try test__negdi2(4398046511096, -4398046511096);
try test__negdi2(-2199023255551, 2199023255551);
try test__negdi2(2199023255551, -2199023255551);
try test__negdi2(-2199023255550, 2199023255550);
try test__negdi2(2199023255550, -2199023255550);
try test__negdi2(-2199023255548, 2199023255548);
try test__negdi2(2199023255548, -2199023255548);
try test__negdi2(-2199023255544, 2199023255544);
try test__negdi2(2199023255544, -2199023255544);
try test__negdi2(-1099511627775, 1099511627775);
try test__negdi2(1099511627775, -1099511627775);
try test__negdi2(-1099511627774, 1099511627774);
try test__negdi2(1099511627774, -1099511627774);
try test__negdi2(-1099511627772, 1099511627772);
try test__negdi2(1099511627772, -1099511627772);
try test__negdi2(-1099511627768, 1099511627768);
try test__negdi2(1099511627768, -1099511627768);
try test__negdi2(-549755813887, 549755813887);
try test__negdi2(549755813887, -549755813887);
try test__negdi2(-549755813886, 549755813886);
try test__negdi2(549755813886, -549755813886);
try test__negdi2(-549755813884, 549755813884);
try test__negdi2(549755813884, -549755813884);
try test__negdi2(-549755813880, 549755813880);
try test__negdi2(549755813880, -549755813880);
try test__negdi2(-274877906943, 274877906943);
try test__negdi2(274877906943, -274877906943);
try test__negdi2(-274877906942, 274877906942);
try test__negdi2(274877906942, -274877906942);
try test__negdi2(-274877906940, 274877906940);
try test__negdi2(274877906940, -274877906940);
try test__negdi2(-274877906936, 274877906936);
try test__negdi2(274877906936, -274877906936);
try test__negdi2(-137438953471, 137438953471);
try test__negdi2(137438953471, -137438953471);
try test__negdi2(-137438953470, 137438953470);
try test__negdi2(137438953470, -137438953470);
try test__negdi2(-137438953468, 137438953468);
try test__negdi2(137438953468, -137438953468);
try test__negdi2(-137438953464, 137438953464);
try test__negdi2(137438953464, -137438953464);
try test__negdi2(-68719476735, 68719476735);
try test__negdi2(68719476735, -68719476735);
try test__negdi2(-68719476734, 68719476734);
try test__negdi2(68719476734, -68719476734);
try test__negdi2(-68719476732, 68719476732);
try test__negdi2(68719476732, -68719476732);
try test__negdi2(-68719476728, 68719476728);
try test__negdi2(68719476728, -68719476728);
try test__negdi2(-34359738367, 34359738367);
try test__negdi2(34359738367, -34359738367);
try test__negdi2(-34359738366, 34359738366);
try test__negdi2(34359738366, -34359738366);
try test__negdi2(-34359738364, 34359738364);
try test__negdi2(34359738364, -34359738364);
try test__negdi2(-34359738360, 34359738360);
try test__negdi2(34359738360, -34359738360);
try test__negdi2(-17179869183, 17179869183);
try test__negdi2(17179869183, -17179869183);
try test__negdi2(-17179869182, 17179869182);
try test__negdi2(17179869182, -17179869182);
try test__negdi2(-17179869180, 17179869180);
try test__negdi2(17179869180, -17179869180);
try test__negdi2(-17179869176, 17179869176);
try test__negdi2(17179869176, -17179869176);
try test__negdi2(-8589934591, 8589934591);
try test__negdi2(8589934591, -8589934591);
try test__negdi2(-8589934590, 8589934590);
try test__negdi2(8589934590, -8589934590);
try test__negdi2(-8589934588, 8589934588);
try test__negdi2(8589934588, -8589934588);
try test__negdi2(-8589934584, 8589934584);
try test__negdi2(8589934584, -8589934584);
try test__negdi2(-4294967295, 4294967295);
try test__negdi2(4294967295, -4294967295);
try test__negdi2(-4294967294, 4294967294);
try test__negdi2(4294967294, -4294967294);
try test__negdi2(-4294967292, 4294967292);
try test__negdi2(4294967292, -4294967292);
try test__negdi2(-4294967288, 4294967288);
try test__negdi2(4294967288, -4294967288);
try test__negdi2(-2147483647, 2147483647);
try test__negdi2(2147483647, -2147483647);
try test__negdi2(-2147483646, 2147483646);
try test__negdi2(2147483646, -2147483646);
try test__negdi2(-2147483644, 2147483644);
try test__negdi2(2147483644, -2147483644);
try test__negdi2(-2147483640, 2147483640);
try test__negdi2(2147483640, -2147483640);
try test__negdi2(-1073741823, 1073741823);
try test__negdi2(1073741823, -1073741823);
try test__negdi2(-1073741822, 1073741822);
try test__negdi2(1073741822, -1073741822);
try test__negdi2(-1073741820, 1073741820);
try test__negdi2(1073741820, -1073741820);
try test__negdi2(-1073741816, 1073741816);
try test__negdi2(1073741816, -1073741816);
try test__negdi2(-536870911, 536870911);
try test__negdi2(536870911, -536870911);
try test__negdi2(-536870910, 536870910);
try test__negdi2(536870910, -536870910);
try test__negdi2(-536870908, 536870908);
try test__negdi2(536870908, -536870908);
try test__negdi2(-536870904, 536870904);
try test__negdi2(536870904, -536870904);
try test__negdi2(-268435455, 268435455);
try test__negdi2(268435455, -268435455);
try test__negdi2(-268435454, 268435454);
try test__negdi2(268435454, -268435454);
try test__negdi2(-268435452, 268435452);
try test__negdi2(268435452, -268435452);
try test__negdi2(-268435448, 268435448);
try test__negdi2(268435448, -268435448);
try test__negdi2(-134217727, 134217727);
try test__negdi2(134217727, -134217727);
try test__negdi2(-134217726, 134217726);
try test__negdi2(134217726, -134217726);
try test__negdi2(-134217724, 134217724);
try test__negdi2(134217724, -134217724);
try test__negdi2(-134217720, 134217720);
try test__negdi2(134217720, -134217720);
try test__negdi2(-67108863, 67108863);
try test__negdi2(67108863, -67108863);
try test__negdi2(-67108862, 67108862);
try test__negdi2(67108862, -67108862);
try test__negdi2(-67108860, 67108860);
try test__negdi2(67108860, -67108860);
try test__negdi2(-67108856, 67108856);
try test__negdi2(67108856, -67108856);
try test__negdi2(-33554431, 33554431);
try test__negdi2(33554431, -33554431);
try test__negdi2(-33554430, 33554430);
try test__negdi2(33554430, -33554430);
try test__negdi2(-33554428, 33554428);
try test__negdi2(33554428, -33554428);
try test__negdi2(-33554424, 33554424);
try test__negdi2(33554424, -33554424);
try test__negdi2(-16777215, 16777215);
try test__negdi2(16777215, -16777215);
try test__negdi2(-16777214, 16777214);
try test__negdi2(16777214, -16777214);
try test__negdi2(-16777212, 16777212);
try test__negdi2(16777212, -16777212);
try test__negdi2(-16777208, 16777208);
try test__negdi2(16777208, -16777208);
try test__negdi2(-8388607, 8388607);
try test__negdi2(8388607, -8388607);
try test__negdi2(-8388606, 8388606);
try test__negdi2(8388606, -8388606);
try test__negdi2(-8388604, 8388604);
try test__negdi2(8388604, -8388604);
try test__negdi2(-8388600, 8388600);
try test__negdi2(8388600, -8388600);
try test__negdi2(-4194303, 4194303);
try test__negdi2(4194303, -4194303);
try test__negdi2(-4194302, 4194302);
try test__negdi2(4194302, -4194302);
try test__negdi2(-4194300, 4194300);
try test__negdi2(4194300, -4194300);
try test__negdi2(-4194296, 4194296);
try test__negdi2(4194296, -4194296);
try test__negdi2(-2097151, 2097151);
try test__negdi2(2097151, -2097151);
try test__negdi2(-2097150, 2097150);
try test__negdi2(2097150, -2097150);
try test__negdi2(-2097148, 2097148);
try test__negdi2(2097148, -2097148);
try test__negdi2(-2097144, 2097144);
try test__negdi2(2097144, -2097144);
try test__negdi2(-1048575, 1048575);
try test__negdi2(1048575, -1048575);
try test__negdi2(-1048574, 1048574);
try test__negdi2(1048574, -1048574);
try test__negdi2(-1048572, 1048572);
try test__negdi2(1048572, -1048572);
try test__negdi2(-1048568, 1048568);
try test__negdi2(1048568, -1048568);
try test__negdi2(-524287, 524287);
try test__negdi2(524287, -524287);
try test__negdi2(-524286, 524286);
try test__negdi2(524286, -524286);
try test__negdi2(-524284, 524284);
try test__negdi2(524284, -524284);
try test__negdi2(-524280, 524280);
try test__negdi2(524280, -524280);
try test__negdi2(-262143, 262143);
try test__negdi2(262143, -262143);
try test__negdi2(-262142, 262142);
try test__negdi2(262142, -262142);
try test__negdi2(-262140, 262140);
try test__negdi2(262140, -262140);
try test__negdi2(-262136, 262136);
try test__negdi2(262136, -262136);
try test__negdi2(-131071, 131071);
try test__negdi2(131071, -131071);
try test__negdi2(-131070, 131070);
try test__negdi2(131070, -131070);
try test__negdi2(-131068, 131068);
try test__negdi2(131068, -131068);
try test__negdi2(-131064, 131064);
try test__negdi2(131064, -131064);
try test__negdi2(-65535, 65535);
try test__negdi2(65535, -65535);
try test__negdi2(-65534, 65534);
try test__negdi2(65534, -65534);
try test__negdi2(-65532, 65532);
try test__negdi2(65532, -65532);
try test__negdi2(-65528, 65528);
try test__negdi2(65528, -65528);
try test__negdi2(-32767, 32767);
try test__negdi2(32767, -32767);
try test__negdi2(-32766, 32766);
try test__negdi2(32766, -32766);
try test__negdi2(-32764, 32764);
try test__negdi2(32764, -32764);
try test__negdi2(-32760, 32760);
try test__negdi2(32760, -32760);
try test__negdi2(-16383, 16383);
try test__negdi2(16383, -16383);
try test__negdi2(-16382, 16382);
try test__negdi2(16382, -16382);
try test__negdi2(-16380, 16380);
try test__negdi2(16380, -16380);
try test__negdi2(-16376, 16376);
try test__negdi2(16376, -16376);
try test__negdi2(-8191, 8191);
try test__negdi2(8191, -8191);
try test__negdi2(-8190, 8190);
try test__negdi2(8190, -8190);
try test__negdi2(-8188, 8188);
try test__negdi2(8188, -8188);
try test__negdi2(-8184, 8184);
try test__negdi2(8184, -8184);
try test__negdi2(-4095, 4095);
try test__negdi2(4095, -4095);
try test__negdi2(-4094, 4094);
try test__negdi2(4094, -4094);
try test__negdi2(-4092, 4092);
try test__negdi2(4092, -4092);
try test__negdi2(-4088, 4088);
try test__negdi2(4088, -4088);
try test__negdi2(-2047, 2047);
try test__negdi2(2047, -2047);
try test__negdi2(-2046, 2046);
try test__negdi2(2046, -2046);
try test__negdi2(-2044, 2044);
try test__negdi2(2044, -2044);
try test__negdi2(-2040, 2040);
try test__negdi2(2040, -2040);
try test__negdi2(-1023, 1023);
try test__negdi2(1023, -1023);
try test__negdi2(-1022, 1022);
try test__negdi2(1022, -1022);
try test__negdi2(-1020, 1020);
try test__negdi2(1020, -1020);
try test__negdi2(-1016, 1016);
try test__negdi2(1016, -1016);
try test__negdi2(-511, 511);
try test__negdi2(511, -511);
try test__negdi2(-510, 510);
try test__negdi2(510, -510);
try test__negdi2(-508, 508);
try test__negdi2(508, -508);
try test__negdi2(-504, 504);
try test__negdi2(504, -504);
try test__negdi2(-255, 255);
try test__negdi2(255, -255);
try test__negdi2(-254, 254);
try test__negdi2(254, -254);
try test__negdi2(-252, 252);
try test__negdi2(252, -252);
try test__negdi2(-248, 248);
try test__negdi2(248, -248);
try test__negdi2(-127, 127);
try test__negdi2(127, -127);
try test__negdi2(-126, 126);
try test__negdi2(126, -126);
try test__negdi2(-124, 124);
try test__negdi2(124, -124);
try test__negdi2(-120, 120);
try test__negdi2(120, -120);
try test__negdi2(-63, 63);
try test__negdi2(63, -63);
try test__negdi2(-62, 62);
try test__negdi2(62, -62);
try test__negdi2(-60, 60);
try test__negdi2(60, -60);
try test__negdi2(-56, 56);
try test__negdi2(56, -56);
try test__negdi2(-31, 31);
try test__negdi2(31, -31);
try test__negdi2(-30, 30);
try test__negdi2(30, -30);
try test__negdi2(-28, 28);
try test__negdi2(28, -28);
try test__negdi2(-24, 24);
try test__negdi2(24, -24);
try test__negdi2(-15, 15);
try test__negdi2(15, -15);
try test__negdi2(-14, 14);
try test__negdi2(14, -14);
try test__negdi2(-12, 12);
try test__negdi2(12, -12);
try test__negdi2(-8, 8);
try test__negdi2(8, -8);
}
|
lib/std/special/compiler_rt/negdi2_test.zig
|
const std = @import("std");
const builtin = @import("builtin");
const os = std.os;
const linux = os.linux;
const assert = std.debug.assert;
const supported_os = switch(builtin.os) {
builtin.os.linux => true,
builtin.os.macosx => true,
else => @compileError("unsupported os"),
};
const supported_architecture = switch(builtin.arch) {
builtin.Arch.x86_64 => true,
builtin.Arch.i386 => true,
builtin.Arch.aarch64v8 => true,
else => @compileError("unsupported arch"), // NCCS can change
};
pub const pid_t = c_int;
pub const cc_t = u8;
pub const tcflag_t = c_uint;
pub const speed_t = c_uint;
const NCCS = 32;
pub const Termios = packed struct {
c_iflag: tcflag_t,
c_oflag: tcflag_t,
c_cflag: tcflag_t,
c_lflag: tcflag_t,
c_line: cc_t,
c_cc: [NCCS]cc_t,
__c_ispeed: speed_t,
__c_ospeed: speed_t,
};
pub fn cfgetospeed(tio: *const Termios) speed_t {
return tio.c_cflag & speed_t(CBAUD);
}
pub fn cfgetispeed(tio: *const Termios) speed_t {
return cfgetospeed(tio);
}
pub fn cfmakeraw(tio: *Termios) void {
tio.c_iflag &= ~ @as(tcflag_t, IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
tio.c_oflag &= ~ @as(tcflag_t, OPOST);
tio.c_lflag &= ~ @as(tcflag_t, ECHO|ECHONL|ICANON|ISIG|IEXTEN);
tio.c_cflag &= ~ @as(tcflag_t, CSIZE|PARENB);
tio.c_cflag |= @as(tcflag_t, CS8);
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 0;
}
pub fn cfsetospeed(tio: *Termios, speed: speed_t) !void {
if (speed & ~speed_t(CBAUD) != 0) {
return error.UnexpectedBits;
}
tio.c_cflag &= ~speed_t(CBAUD);
tio.c_cflag |= speed;
}
pub fn cfsetispeed(tio: *Termios, speed: speed_t) !void {
if (speed != 0) return try cfsetospeed(tio, speed);
}
//TODO: weak linkage?
pub const cfsetspeed = cfsetospeed;
pub fn tcdrain(fd: i32) !void {
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TCSBRK, 1);
const err = os.linux.getErrno(rc);
return switch (err) {
0 => {},
else => error.TCSBRK_Failed,
};
}
pub fn tcflow(fd: i32, action: i32) !void {
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TCXONC, @bitCast(usize, isize(action)));
const err = os.linux.getErrno(rc);
return switch (err) {
0 => {},
else => error.TCXONC_Failed,
};
}
pub fn tcflush(fd: i32, queue: i32) !void {
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TCFLSH, @bitCast(usize, isize(queue)));
const err = os.linux.getErrno(rc);
switch (err) {
0 => {},
else => return error.TCXONC_Failed,
}
}
pub fn tcgetattr(fd: i32, tio: *Termios) !void {
const tio_usize = @ptrToInt(tio);
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TCGETS, tio_usize);
const err = os.linux.getErrno(rc);
return switch (err) {
0 => {},
else => error.TCGETS_Failed,
};
}
pub fn tcgetsid(fd: i32) !pid_t {
var sid: pid_t = undefined;
const sid_usize = @ptrToInt(&sid);
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TIOCGSID, sid_usize);
const err = os.linux.getErrno(rc);
return switch (err) {
0 => sid,
else => error.TIOCGSID_Failed,
};
}
pub fn tcsendbreak(fd: i32, dur: i32) !void {
// ignore dur, implementation defined, use 0 instead
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), linux.TCSBRK, 0);
const err = os.linux.getErrno(rc);
return switch (err) {
0 => {},
else => error.TCSBRK_Failed,
};
}
pub fn tcsetattr(fd: i32, act: u32, tio: *const Termios) !void {
if (act > 2) return error.TCSETS_EINVAL;
const tio_usize = @ptrToInt(tio);
const rc = linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, fd)), (linux.TCSETS + act), tio_usize);
const err = os.linux.getErrno(rc);
return switch (err) {
0 => {},
else => error.TCSETS_Failed,
};
}
pub const VINTR = 0;
pub const VQUIT = 1;
pub const VERASE = 2;
pub const VKILL = 3;
pub const VEOF = 4;
pub const VTIME = 5;
pub const VMIN = 6;
pub const VSWTC = 7;
pub const VSTART = 8;
pub const VSTOP = 9;
pub const VSUSP = 10;
pub const VEOL = 11;
pub const VREPRINT = 12;
pub const VDISCARD = 13;
pub const VWERASE = 14;
pub const VLNEXT = 15;
pub const VEOL2 = 16;
pub const IGNBRK = 0o000001;
pub const BRKINT = 0o000002;
pub const IGNPAR = 0o000004;
pub const PARMRK = 0o000010;
pub const INPCK = 0o000020;
pub const ISTRIP = 0o000040;
pub const INLCR = 0o000100;
pub const IGNCR = 0o000200;
pub const ICRNL = 0o000400;
pub const IUCLC = 0o001000;
pub const IXON = 0o002000;
pub const IXANY = 0o004000;
pub const IXOFF = 0o010000;
pub const IMAXBEL = 0o020000;
pub const IUTF8 = 0o040000;
pub const OPOST = 0o000001;
pub const OLCUC = 0o000002;
pub const ONLCR = 0o000004;
pub const OCRNL = 0o000010;
pub const ONOCR = 0o000020;
pub const ONLRET = 0o000040;
pub const OFILL = 0o000100;
pub const OFDEL = 0o000200;
pub const NLDLY = 0o000400;
pub const NL0 = 0o000000;
pub const NL1 = 0o000400;
pub const CRDLY = 0o003000;
pub const CR0 = 0o000000;
pub const CR1 = 0o001000;
pub const CR2 = 0o002000;
pub const CR3 = 0o003000;
pub const TABDLY = 0o014000;
pub const TAB0 = 0o000000;
pub const TAB1 = 0o004000;
pub const TAB2 = 0o010000;
pub const TAB3 = 0o014000;
pub const BSDLY = 0o020000;
pub const BS0 = 0o000000;
pub const BS1 = 0o020000;
pub const FFDLY = 0o100000;
pub const FF0 = 0o000000;
pub const FF1 = 0o100000;
pub const VTDLY = 0o040000;
pub const VT0 = 0o000000;
pub const VT1 = 0o040000;
pub const B0 = 0o000000;
pub const B50 = 0o000001;
pub const B75 = 0o000002;
pub const B110 = 0o000003;
pub const B134 = 0o000004;
pub const B150 = 0o000005;
pub const B200 = 0o000006;
pub const B300 = 0o000007;
pub const B600 = 0o000010;
pub const B1200 = 0o000011;
pub const B1800 = 0o000012;
pub const B2400 = 0o000013;
pub const B4800 = 0o000014;
pub const B9600 = 0o000015;
pub const B19200 = 0o000016;
pub const B38400 = 0o000017;
pub const B57600 = 0o010001;
pub const B115200 = 0o010002;
pub const B230400 = 0o010003;
pub const B460800 = 0o010004;
pub const B500000 = 0o010005;
pub const B576000 = 0o010006;
pub const B921600 = 0o010007;
pub const B1000000 = 0o010010;
pub const B1152000 = 0o010011;
pub const B1500000 = 0o010012;
pub const B2000000 = 0o010013;
pub const B2500000 = 0o010014;
pub const B3000000 = 0o010015;
pub const B3500000 = 0o010016;
pub const B4000000 = 0o010017;
pub const CSIZE = 0o000060;
pub const CS5 = 0o000000;
pub const CS6 = 0o000020;
pub const CS7 = 0o000040;
pub const CS8 = 0o000060;
pub const CSTOPB = 0o000100;
pub const CREAD = 0o000200;
pub const PARENB = 0o000400;
pub const PARODD = 0o001000;
pub const HUPCL = 0o002000;
pub const CLOCAL = 0o004000;
pub const ISIG = 0o000001;
pub const ICANON = 0o000002;
pub const ECHO = 0o000010;
pub const ECHOE = 0o000020;
pub const ECHOK = 0o000040;
pub const ECHONL = 0o000100;
pub const NOFLSH = 0o000200;
pub const TOSTOP = 0o000400;
pub const IEXTEN = 0o100000;
pub const TCOOFF = 0;
pub const TCOON = 1;
pub const TCIOFF = 2;
pub const TCION = 3;
pub const TCIFLUSH = 0;
pub const TCOFLUSH = 1;
pub const TCIOFLUSH = 2;
pub const TCSANOW = 0;
pub const TCSADRAIN = 1;
pub const TCSAFLUSH = 2;
pub const EXTA = 0o000016;
pub const EXTB = 0o000017;
pub const CBAUD = 0o010017;
pub const CBAUDEX = 0o010000;
pub const CIBAUD = 0o02003600000;
pub const CMSPAR = 0o10000000000;
pub const CRTSCTS = 0o20000000000;
pub const XCASE = 0o000004;
pub const ECHOCTL = 0o001000;
pub const ECHOPRT = 0o002000;
pub const ECHOKE = 0o004000;
pub const FLUSHO = 0o010000;
pub const PENDIN = 0o040000;
pub const EXTPROC = 0o200000;
pub const XTABS = 0o014000;
|
src/termios.zig
|
const std = @import("std");
const hzzp = @import("hzzp");
pub const FileServer = hzzp.base.Server.BaseServer(std.fs.File.Reader, std.fs.File.Writer);
const HandlerFn = fn (*FileServer) void;
const HandlerMap = std.StringHashMap(HandlerFn);
pub const Options = struct {
port: u16 = 8080,
};
pub const Server = struct {
allocator: *std.mem.Allocator,
handlers: HandlerMap,
options: Options,
const Self = @This();
pub fn init(allocator: *std.mem.Allocator, options: Options) @This() {
return .{
.allocator = allocator,
.options = options,
.handlers = HandlerMap.init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.handlers.deinit();
}
pub fn addHandler(self: *Self, comptime route: []const u8, handler: HandlerFn) !void {
try self.handlers.put(route, handler);
}
pub fn run(self: *Self) !void {
std.debug.warn("port: {}\n", .{self.options.port});
var addr = try std.net.Address.parseIp("127.0.0.1", self.options.port);
var stream_server = std.net.StreamServer.init(.{ .reuse_address = true });
defer stream_server.deinit();
try stream_server.listen(addr);
while (true) {
var buffer: [1024]u8 = undefined;
var conn = try stream_server.accept();
defer conn.file.close();
var client = hzzp.base.Server.create(&buffer, conn.file.reader(), conn.file.writer());
var status_event = (try client.readEvent()).?;
std.testing.expect(status_event == .status);
std.debug.warn("http: got status: {} {}\n", .{ status_event.status.method, status_event.status.path });
var handler_opt = self.handlers.get(status_event.status.path);
if (handler_opt) |handler| {
handler(&client);
} else {
try client.writeHead(404, "Not Found");
try client.writeHeaderValue("Server", "zeb/0.1");
try client.writeHeadComplete();
}
}
}
};
|
src/server.zig
|
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const window = @import("Window.zig");
const c = @import("c.zig").c;
const expect = std.testing.expect;
const loadFile = @import("../Files.zig").loadFile;
const builtin = @import("builtin");
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
var bound_shader: u32 = 0;
const shader_type_gl = [_]c_uint{
c.GL_VERTEX_SHADER,
c.GL_FRAGMENT_SHADER,
};
pub const ShaderType = enum(u32) {
Vertex = 0,
Fragment = 1,
};
pub const ShaderObject = struct {
id: u32,
shaderType: ShaderType,
// STRING INPUTS MUST BE NULL TERMINATED
pub fn init(source_strings: []const ([]const u8), sType: ShaderType, allocator: *std.mem.Allocator) !ShaderObject {
var id: u32 = c.glCreateShader(shader_type_gl[@enumToInt(sType)]);
if (id == 0) {
return error.OpenGLError;
}
errdefer c.glDeleteShader(id);
// Upload shader source
var string_pointers: []([*c]const u8) = try allocator.alloc(([*c]const u8), source_strings.len);
var i: u32 = 0;
while (i < source_strings.len) : (i += 1) {
if (source_strings[i][source_strings[i].len - 1] != 0) {
assert(false);
return error.SourceStringNotNullTerminated;
}
string_pointers[i] = source_strings[i].ptr;
}
c.glShaderSource(id, @intCast(c_int, source_strings.len), &string_pointers[0], 0);
allocator.free(string_pointers);
// Compile
c.glCompileShader(id);
// Check for errors
var status: u32 = 0;
c.glGetShaderiv(id, c.GL_COMPILE_STATUS, @ptrCast([*c]c_int, &status));
if (status == 0) {
warn("ShaderObject.init: Shader compilation failed\n", .{});
var logSize: c_int = 0;
c.glGetShaderiv(id, c.GL_INFO_LOG_LENGTH, &logSize);
if (logSize > 0) {
var log: []u8 = try allocator.alloc(u8, @intCast(usize, logSize) + 1);
defer allocator.free(log);
c.glGetShaderInfoLog(id, logSize, 0, log.ptr);
log[log.len - 1] = 0;
warn("Log: ###\n{}\n###\nShader that failed:\n###\n", .{log});
for (source_strings) |a| {
warn("{}", .{a[0 .. a.len - 1]});
}
warn("###\n", .{});
}
return error.OpenGLError;
}
return ShaderObject{
.id = id,
.shaderType = sType,
};
}
pub fn free(self: *ShaderObject) void {
if (self.id == 0) {
assert(false);
return;
}
c.glDeleteShader(self.id);
self.id = 0;
}
};
pub const ShaderProgram = struct {
ref_count: ReferenceCounter = ReferenceCounter{},
id: u32,
// Vertex attribute strings must be null terminated
pub fn init(vs: *const ShaderObject, fs: ?*const ShaderObject, vertexAttributes: []const ([]const u8), allocator: *std.mem.Allocator) !ShaderProgram {
if (vs.shaderType != ShaderType.Vertex or (fs != null and fs.?.shaderType != ShaderType.Fragment) or vs.id == 0 or (fs != null and fs.?.id == 0)) {
assert(false);
return error.InvalidParameter;
}
// Attach shaders
const id: u32 = c.glCreateProgram();
errdefer c.glDeleteProgram(id);
if (id == 0) {
return error.OpenGLError;
}
c.glAttachShader(id, vs.id);
if (fs != null) {
c.glAttachShader(id, fs.?.id);
}
// Set vertex attributes
var i: u32 = 0;
for (vertexAttributes) |a| {
if (a[a.len - 1] != 0) {
return error.StringNotNullTerminated;
}
c.glBindAttribLocation(id, i, a.ptr);
i += 1;
}
// Link
c.glLinkProgram(id);
var s = ShaderProgram{ .id = id };
// Error check and validate
var status: u32 = 0;
c.glGetProgramiv(id, c.GL_LINK_STATUS, @ptrCast([*c]c_int, &status));
if (status == 0) {
warn("ShaderProgram.init: Shader linking failed\n", .{});
s.printLog(allocator);
return error.OpenGLError;
}
return s;
}
fn printLog(self: ShaderProgram, allocator: *std.mem.Allocator) void {
var logSize: c_int = 0;
c.glGetProgramiv(self.id, c.GL_INFO_LOG_LENGTH, &logSize);
if (logSize > 0) {
var log: []u8 = allocator.alloc(u8, @intCast(usize, logSize) + 1) catch return;
defer allocator.free(log);
c.glGetProgramInfoLog(self.id, logSize, 0, log.ptr);
log[log.len - 1] = 0;
warn("Log: {}\n", .{log});
}
}
pub fn validate(self: ShaderProgram, allocator: *std.mem.Allocator) void {
if (builtin.mode == builtin.Mode.Debug) {
if (self.id == 0) {
assert(false);
return;
}
c.glValidateProgram(self.id);
var status: c_int = 0;
c.glGetProgramiv(self.id, c.GL_VALIDATE_STATUS, &status);
if (status == 0) {
warn("ShaderProgram.init: Shader validation failed\n", .{});
self.printLog(allocator);
}
}
}
pub fn bind(self: ShaderProgram) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
if (bound_shader != self.id) {
c.glUseProgram(self.id);
bound_shader = self.id;
}
}
pub fn free(self: *ShaderProgram) void {
if (self.id == 0) {
assert(false);
return;
}
self.ref_count.deinit();
c.glDeleteProgram(self.id);
}
pub fn getUniformLocation(self: *ShaderProgram, name: [*]const u8) !i32 {
if (self.id == 0) {
assert(false);
return error.ObjectNotCreated;
}
var loc: i32 = c.glGetUniformLocation(self.id, name);
if (loc == -1) {
return error.UniformNotFound;
}
return loc;
}
pub fn setUniform1i(self: ShaderProgram, location: i32, data: i32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform1i(location, @intCast(c_int, data));
}
pub fn setUniform1f(self: ShaderProgram, location: i32, data: f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform1f(location, data);
}
pub fn setUniform2f(self: ShaderProgram, location: i32, data: [2]f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform2f(location, data[0], data[1]);
}
pub fn setUniform3f(self: ShaderProgram, location: i32, data: [3]f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform3f(location, data[0], data[1], data[2]);
}
pub fn setUniform4f(self: ShaderProgram, location: i32, data: [4]f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform4f(location, data[0], data[1], data[2], data[3]);
}
pub fn setUniform2i(self: ShaderProgram, location: i32, data: [2]i32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform2i(location, data[0], data[1]);
}
pub fn setUniform3i(self: ShaderProgram, location: i32, data: [3]i32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform3i(location, data[0], data[1], data[2]);
}
pub fn setUniform4i(self: ShaderProgram, location: i32, data: [4]i32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform4i(location, data[0], data[1], data[2], data[3]);
}
pub fn setUniformMat2(self: ShaderProgram, location: i32, count: i32, data: []const f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (count <= 0) {
assert(false);
return error.InvalidParameter;
}
if (@intCast(i32, data.len) != count * 4) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniformMatrix2fv(location, count, 0, data.ptr);
}
pub fn setUniformMat3(self: ShaderProgram, location: i32, count: i32, data: []const f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (count <= 0) {
assert(false);
return error.InvalidParameter;
}
if (@intCast(i32, data.len) != count * 9) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniformMatrix3fv(location, count, 0, data.ptr);
}
pub fn setUniformMat4(self: ShaderProgram, location: i32, count: i32, data: []const f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (count <= 0) {
assert(false);
return error.InvalidParameter;
}
if (@intCast(i32, data.len) != count * 16) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniformMatrix4fv(location, count, 0, data.ptr);
}
// data.len == count*4*3
pub fn setUniformMat4x3(self: ShaderProgram, location: i32, count: i32, data: []f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (count <= 0) {
assert(false);
return error.InvalidParameter;
}
if (@intCast(i32, data.len) != count * 4 * 3) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniformMatrix4x3fv(location, count, 0, data.ptr);
}
pub fn setUniform1iv(self: ShaderProgram, location: i32, data: []const i32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (data.len == 0) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform1iv(location, @intCast(c_int, data.len), @ptrCast([*c]const c_int, data.ptr));
}
pub fn setUniform1fv(self: ShaderProgram, location: i32, data: []const f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (data.len == 0) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform1fv(location, @intCast(c_int, data.len), @ptrCast([*c]const f32, data.ptr));
}
pub fn setUniform2fv(self: ShaderProgram, location: i32, data: []const f32) !void {
if (location == -1) {
assert(false);
return error.InvalidParameter;
}
if (data.len == 0 or data.len % 2 != 0) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glUniform2fv(location, @intCast(c_int, data.len / 2), @ptrCast([*c]const f32, data.ptr));
}
pub fn getUniformBlockIndex(self: ShaderProgram, name: [*]const u8) !u32 {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
const index = c.glGetUniformBlockIndex(self.id, name);
if (index == 0xffffffff) {
return error.OpenGLError;
}
return @intCast(u32, index);
}
pub fn setUniformBlockBinding(self: ShaderProgram, block_index: u32, binding: u32) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
c.glUniformBlockBinding(self.id, block_index, binding);
}
pub fn getBinary(self: ShaderProgram, data: *([]u8), binary_format: *u32, allocator: *std.mem.Allocator) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
if (c.GLAD_GL_ARB_get_program_binary == 0) {
return error.NotSupported;
}
var binary_size: c_int = 0;
c.glGetProgramiv(self.id, c.GL_PROGRAM_BINARY_LENGTH, &binary_size);
if (binary_size < 1 or binary_size > 100 * 1024 * 1024) {
return error.OpenGLError;
}
data.* = try allocator.alloc(u8, @intCast(usize, binary_size));
c.glGetProgramBinary(self.id, binary_size, null, @ptrCast([*c]c_uint, binary_format), data.*.ptr);
}
pub fn saveBinary(self: ShaderProgram, file_path: []const u8, allocator: *std.mem.Allocator) !void {
var data: []u8 = undefined;
var binary_format: [1]u32 = undefined;
try self.getBinary(&data, &binary_format[0], allocator);
var file = try std.fs.cwd().openFile(file_path, std.fs.File.OpenFlags{ .write = true });
defer file.close();
_ = try file.write(std.mem.sliceAsBytes(binary_format[0..]));
_ = try file.write(data[0..]);
allocator.free(data);
}
pub fn loadFromBinary(binary_format: u32, data: []const u8) !ShaderProgram {
if (c.GLAD_GL_ARB_get_program_binary == 0) {
return error.NotSupported;
}
const id: u32 = c.glCreateProgram();
errdefer c.glDeleteProgram(id);
if (id == 0) {
return error.OpenGLError;
}
c.glProgramBinary(id, binary_format, data[0..].ptr, @intCast(c_int, data.len));
var status: u32 = 0;
c.glGetProgramiv(id, c.GL_LINK_STATUS, @ptrCast([*c]c_int, &status));
if (status == 0) {
return error.OpenGLError;
}
return ShaderProgram{ .id = id };
}
pub fn loadFromBinaryFile(file_path: []const u8, allocator: *std.mem.Allocator) !ShaderProgram {
if (c.GLAD_GL_ARB_get_program_binary == 0) {
return error.NotSupported;
}
var data = try loadFile(file_path, allocator);
const binary_format = std.mem.bytesAsSlice(u32, data[0..4])[0];
return loadFromBinary(binary_format, data[4..]);
}
};
test "shader" {
try window.createWindow(false, 200, 200, "test", true, 0);
defer window.closeWindow();
var a = std.heap.page_allocator;
const vsSrc = "uniform mat4 matrix; in vec4 coords; in vec4 colour; out vec4 pass_colour; void main() { gl_Position = matrix * coords; pass_colour = colour; }\n#ifdef TEST\nsyntax error\n#endif\n\x00";
const fsSrc = "#version 140\n in vec4 pass_colour; out vec4 outColour; void main() { outColour = pass_colour; }\n\x00";
var vs: ShaderObject = try ShaderObject.init(([_]([]const u8){ "#version 140\n#define TEST_\n\x00", vsSrc })[0..], ShaderType.Vertex, a);
var fs: ShaderObject = try ShaderObject.init(([_]([]const u8){fsSrc})[0..], ShaderType.Fragment, a);
var program: ShaderProgram = try ShaderProgram.init(&vs, &fs, &[_]([]const u8){ "coords\x00", "colour\x00" }, a);
vs.free();
fs.free();
var binary_data: []u8 = undefined;
var binary_format: u32 = 0;
try program.getBinary(&binary_data, &binary_format, std.heap.page_allocator);
defer std.heap.page_allocator.free(binary_data);
program.free();
program = try ShaderProgram.loadFromBinary(binary_format, binary_data);
var uniformId = try program.getUniformLocation("matrix");
expect(uniformId != -1);
}
|
src/WindowGraphicsInput/Shader.zig
|
const std = @import("std");
const grail = @import("grailsort.zig");
const testing = std.testing;
const print = std.debug.print;
var gpa_storage = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &gpa_storage.allocator;
const verify_sorted = false;
pub fn main() void {
doIntTests(u8);
doIntTests(i32);
doIntTests(u32);
doIntTests(usize);
}
fn doIntTests(comptime T: type) void {
doAllKeyCases("std.sort" , "unique", T, std.sort.sort, comptime std.sort.asc(T) , comptime doIntCast(T));
doAllKeyCases("grailsort", "unique", T, grail.sort , comptime std.sort.asc(T) , comptime doIntCast(T));
doAllKeyCases("std.sort" , "x2" , T, std.sort.sort, comptime removeBits(T, 1), comptime doIntCast(T));
doAllKeyCases("grailsort", "x2" , T, grail.sort , comptime removeBits(T, 1), comptime doIntCast(T));
doAllKeyCases("std.sort" , "x8" , T, std.sort.sort, comptime removeBits(T, 3), comptime doIntCast(T));
doAllKeyCases("grailsort", "x8" , T, grail.sort , comptime removeBits(T, 3), comptime doIntCast(T));
doAllKeyCases("std.sort" , "x32" , T, std.sort.sort, comptime removeBits(T, 5), comptime doIntCast(T));
doAllKeyCases("grailsort", "x32" , T, grail.sort , comptime removeBits(T, 5), comptime doIntCast(T));
}
fn doAllKeyCases(sort: []const u8, benchmark: []const u8, comptime T: type, comptime sortFn: anytype, comptime lessThan: fn(void, T, T) bool, comptime fromInt: fn(usize) T) void {
const max_len = 10_000_000;
const array = gpa.alloc(T, max_len) catch unreachable;
const golden = gpa.alloc(T, max_len) catch unreachable;
defer gpa.free(array);
defer gpa.free(golden);
var extern_array = gpa.alloc(T, grail.findOptimalBufferLength(max_len));
var seed_rnd = std.rand.DefaultPrng.init(42);
for (golden) |*v, i| v.* = fromInt(i);
checkSorted(T, golden, lessThan);
print(" --------------- {: >9} {} {} ---------------- \n", .{sort, @typeName(T), benchmark});
print(" Items : Average | Max | Min\n", .{});
var array_len: usize = 10;
while (array_len <= max_len) : (array_len *= 10) {
const runs = 100_000_000 / array_len;
var run_rnd = std.rand.DefaultPrng.init(seed_rnd.random.int(u64));
var min_time: u64 = ~@as(u64, 0);
var max_time: u64 = 0;
var total_time: u64 = 0;
var run_id: usize = 0;
while (run_id < runs) : (run_id += 1) {
const seed = run_rnd.random.int(u64);
const part = array[0..array_len];
setRandom(T, part, golden[0..array_len], seed);
var time = std.time.Timer.start() catch unreachable;
sortFn(T, part, {}, lessThan);
const elapsed = time.read();
checkSorted(T, part, lessThan);
if (elapsed < min_time) min_time = elapsed;
if (elapsed > max_time) max_time = elapsed;
total_time += elapsed;
}
const avg_time = total_time / runs;
print("{: >9} : {d: >9.3} | {d: >9.3} | {d: >9.3}\n", .{ array_len, millis(avg_time), millis(max_time), millis(min_time) });
}
}
fn millis(nanos: u64) f64 {
return @intToFloat(f64, nanos) / 1_000_000.0;
}
fn checkSorted(comptime T: type, array: []T, comptime lessThan: fn(void, T, T) bool) void {
if (verify_sorted) {
for (array[1..]) |v, i| {
testing.expect(!lessThan({}, v, array[i]));
}
} else {
// clobber the memory
asm volatile("" : : [g]"r"(array.ptr) : "memory");
}
}
fn setRandom(comptime T: type, array: []T, golden: []const T, seed: u64) void {
std.mem.copy(T, array, golden);
var rnd = std.rand.DefaultPrng.init(seed);
rnd.random.shuffle(T, array);
}
fn doIntCast(comptime T: type) fn(usize) T {
return struct {
fn doCast(v: usize) T {
return @intCast(T, v);
}
}.doCast;
}
fn removeBits(comptime T: type, comptime bits: comptime_int) fn(void, T, T) bool {
return struct {
fn shiftLess(_: void, a: T, b: T) bool {
return (a >> bits) < (b >> bits);
}
}.shiftLess;
}
|
Zig/SpexGuy/src/benchmark.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
//;
const builtins = @import("builtins.zig");
//;
// stack 0 is top
// once you parse something to values
// you can get rid of the original text string
// the vm deep copies strings
// values returned from parse
// dont need to stay around for the life of the vm
// the vm deep copies slices
// tokenizer syntax: " # : ;
// parser syntax: { } float int
// i think thats all you need,
// as in fancy 'defining syntax at runtime' like forth isnt neccessary
// error handling within orth is just result types
// pass errors like type errors and div/0 errors to zig
// with info about where it happened
// { ... } drop is 'multiline comment'
// envs/libraries are ways of naming units of code and controlling scope
// slices can current be used to name units of code,
// even if any definitions inside just get put in global env
// lexically scoped envs
// would let u have private scope and import with renaming
// local environments for slices can be done and would be a better start to envs than anything else
// each slice needs to have locals slots
// slice evaluation 'tracks' which envs to use, based on the tree of slices
// threads can have local environments
// you can eval with a new thread, and get then env out of it when its done and move it into global env
// unicode is currently not supported but i would like to have it in the future
// shouldnt be hard
// unicode chars
// string_indent need to be updated
// updare rc strings
//;
// TODO need
// write some tests
// access records from within zig easily
// maps can use any type of key
// threads as an orthtype
// cooperative multithreading built into vm ?
// modular scheduler thing not part of vm
// scheduler can probably be done in orth
// yeild and resume
// make #t #f and #sentinel syntax
// all words that start with # are builtin
// TODO want
// error reporting
// use error_info
// dont know if i need to
// could just use the thread's stack
// push error info to the stack, crash the thread
// tokenize with col_num and line_num
// parse with them too somehow?
// better number parsing
// floats
// ignore nan and inf
// 1234f 1234i
// intern slices
// print contents of return stack
// get rid of sentinel type
// use "//" for comments instead of ";" ?
// prevent invalid symbols
// cant be parseable as numbers
// cant start with #
// symbols can't have spaces
// what about string>symbol ?
// parser
// could do multiline strings like zig
// would make the logic easier
// u64 type ?
// dlsym ffi would be cool
// look into factor's 'fried quotations' to see if that would work for macros
//;
pub const StackError = error{
StackOverflow,
StackUnderflow,
OutOfBounds,
} || Allocator.Error;
pub fn Stack(comptime T: type) type {
return struct {
const Self = @This();
data: ArrayList(T),
max: usize,
pub fn init(allocator: *Allocator) Self {
return .{
.data = ArrayList(T).init(allocator),
.max = 0,
};
}
pub fn deinit(self: *Self) void {
self.data.deinit();
}
//;
pub fn push(self: *Self, obj: T) Allocator.Error!void {
try self.data.append(obj);
self.max = std.math.max(self.max, self.data.items.len);
}
pub fn pop(self: *Self) StackError!T {
if (self.data.items.len == 0) {
return error.StackUnderflow;
}
const ret = self.data.items[self.data.items.len - 1];
self.data.items.len -= 1;
return ret;
}
pub fn peek(self: *Self) StackError!T {
return (try self.index(0)).*;
}
pub fn index(self: *Self, idx: usize) StackError!*T {
if (idx >= self.data.items.len) {
return error.OutOfBounds;
}
return &self.data.items[self.data.items.len - idx - 1];
}
pub fn clear(self: *Self) void {
self.data.items.len = 0;
}
pub fn resetMax(self: *Self) void {
self.max = 0;
}
};
}
//;
pub const StringFixer = struct {
const Self = @This();
const Error = error{InvalidStringEscape};
str: []const u8,
indent: usize,
first_line: bool,
char_at: usize,
line_at: usize,
col_at: usize,
in_escape: bool,
pub fn init(str: []const u8, indent: usize) Self {
return .{
.str = str,
.indent = indent,
.first_line = true,
.char_at = 0,
.line_at = 0,
.col_at = 0,
.in_escape = false,
};
}
pub fn reset(self: *Self) void {
self.* = init(self.str, self.indent);
}
// TODO codepoints i.e. \x01, dont have \0
// escapes like \#space , which use char escaper
pub fn parseStringEscape(ch: u8) Error!u8 {
return switch (ch) {
'n' => '\n',
't' => '\t',
'0' => 0,
'\\', '"' => ch,
else => error.InvalidStringEscape,
};
}
pub fn next(self: *Self) Error!?u8 {
while (self.char_at < self.str.len) {
const ch = self.str[self.char_at];
self.char_at += 1;
var ret: u8 = undefined;
if (self.in_escape) {
self.in_escape = false;
ret = try parseStringEscape(ch);
} else {
if (ch == '\\') {
self.in_escape = true;
continue;
}
if (self.first_line) {
ret = ch;
} else {
if (self.col_at >= self.indent) {
ret = ch;
} else {
continue;
}
}
}
if (ch == '\n') {
self.first_line = false;
self.line_at += 1;
self.col_at = 0;
} else {
self.col_at += 1;
}
return ret;
}
return null;
}
};
//;
pub const Token = struct {
pub const Data = union(enum) {
String: struct {
str: []const u8,
indent: usize,
},
CharEscape: u8,
IntEscape: i64,
Symbol: []const u8,
Word: []const u8,
};
data: Data,
};
pub const Tokenizer = struct {
const Self = @This();
pub const Error = error{
InvalidString,
UnfinishedString,
InvalidCharEscape,
InvalidIntEscape,
InvalidSymbol,
InvalidWord,
};
// TODO use this correctly
pub const ErrorInfo = struct {
line_number: usize,
};
pub const State = enum {
Empty,
InComment,
InString,
MaybeInEscape,
InCharEscape,
InIntEscape,
InSymbol,
InWord,
};
buf: []const u8,
state: State,
error_info: ErrorInfo,
line_at: usize,
col_at: usize,
start_char: usize,
end_char: usize,
in_string_escape: bool,
string_indent: usize,
pub fn init(buf: []const u8) Self {
return .{
.buf = buf,
.state = .Empty,
.error_info = undefined,
.line_at = 0,
.col_at = 0,
.start_char = 0,
.end_char = 0,
.in_string_escape = false,
.string_indent = 0,
};
}
pub fn charIsWhitespace(ch: u8) bool {
return ch == ' ' or ch == '\n';
}
pub fn charIsDelimiter(ch: u8) bool {
return charIsWhitespace(ch) or ch == ';';
}
pub fn charIsWordValid(ch: u8) bool {
return ch != '"' and ch != ':';
}
pub fn parseCharEscape(str: []const u8) Error!u8 {
if (str.len == 1) {
return str[0];
} else {
// TODO star, heart
if (std.mem.eql(u8, str, "space")) {
return ' ';
} else if (std.mem.eql(u8, str, "tab")) {
return '\t';
} else if (std.mem.eql(u8, str, "newline")) {
return '\n';
} else {
return error.InvalidCharEscape;
}
}
}
pub fn parseIntEscape(str: []const u8) Error!i64 {
switch (str[0]) {
'b' => return std.fmt.parseInt(i64, str[1..], 2) catch error.InvalidIntEscape,
'x' => return std.fmt.parseInt(i64, str[1..], 16) catch error.InvalidIntEscape,
else => return error.InvalidIntEscape,
}
}
pub fn next(self: *Self) Error!?Token {
while (self.end_char < self.buf.len) {
const ch = self.buf[self.end_char];
self.end_char += 1;
if (ch == '\n') {
self.line_at += 1;
self.col_at = 0;
} else {
self.col_at += 1;
}
switch (self.state) {
.Empty => {
if (charIsWhitespace(ch)) {
continue;
}
self.state = switch (ch) {
';' => .InComment,
'"' => blk: {
self.string_indent = self.col_at;
break :blk .InString;
},
'#' => .MaybeInEscape,
':' => .InSymbol,
// TODO check charIsWordValid
else => .InWord,
};
self.start_char = self.end_char - 1;
},
.InComment => {
if (ch == '\n') {
self.state = .Empty;
}
},
.InString => {
if (self.in_string_escape) {
_ = StringFixer.parseStringEscape(ch) catch {
return error.InvalidString;
};
self.in_string_escape = false;
} else {
if (ch == '\\') {
self.in_string_escape = true;
} else if (ch == '"') {
self.state = .Empty;
return Token{
.data = .{
.String = .{
.str = self.buf[(self.start_char + 1)..(self.end_char - 1)],
.indent = self.string_indent,
},
},
};
}
}
},
.MaybeInEscape => {
self.state = switch (ch) {
'\\' => .InCharEscape,
'x', 'b' => .InIntEscape,
// TODO
else => .InWord,
};
},
.InCharEscape => {
if (charIsDelimiter(ch)) {
self.state = .Empty;
return Token{
.data = .{
.CharEscape = try parseCharEscape(
self.buf[(self.start_char + 2)..(self.end_char - 1)],
),
},
};
}
},
.InIntEscape => {
if (charIsDelimiter(ch)) {
self.state = .Empty;
return Token{
.data = .{
.IntEscape = try parseIntEscape(
self.buf[(self.start_char + 1)..(self.end_char - 1)],
),
},
};
}
},
.InSymbol => {
if (charIsDelimiter(ch)) {
self.state = .Empty;
const name = self.buf[(self.start_char + 1)..(self.end_char - 1)];
if (name.len == 0) return error.InvalidSymbol;
return Token{
.data = .{ .Symbol = name },
};
} else if (!charIsWordValid(ch)) {
self.error_info.line_number = self.line_at - 1;
return error.InvalidSymbol;
}
},
.InWord => {
if (charIsDelimiter(ch)) {
self.state = .Empty;
return Token{
.data = .{
.Word = self.buf[self.start_char..(self.end_char - 1)],
},
};
} else if (!charIsWordValid(ch)) {
self.error_info.line_number = self.line_at - 1;
return error.InvalidWord;
}
},
}
} else if (self.end_char == self.buf.len) {
switch (self.state) {
.Empty,
.InComment,
=> {
return null;
},
.InString => {
self.error_info.line_number = self.line_at - 1;
return error.UnfinishedString;
},
.MaybeInEscape => return error.InvalidCharEscape,
.InCharEscape => {
self.state = .Empty;
return Token{
.data = .{
.CharEscape = try parseCharEscape(
self.buf[(self.start_char + 2)..self.end_char],
),
},
};
},
.InIntEscape => {
self.state = .Empty;
return Token{
.data = .{
.IntEscape = try parseIntEscape(
self.buf[(self.start_char + 1)..(self.end_char - 1)],
),
},
};
},
.InSymbol => {
self.state = .Empty;
const name = self.buf[(self.start_char + 1)..self.end_char];
if (name.len == 0) return error.InvalidSymbol;
return Token{
.data = .{ .Symbol = name },
};
},
.InWord => {
self.state = .Empty;
return Token{
.data = .{
.Word = self.buf[self.start_char..self.end_char],
},
};
},
}
}
unreachable;
}
};
//;
pub const FFI_Fn = struct {
pub const Function = fn (*Thread) Thread.Error!void;
name_id: usize,
func: Function,
};
pub const UnmanagedPtr = struct {
const Self = @This();
pub const Ptr = opaque {};
type_id: usize,
ptr: *Ptr,
pub fn cast(self: Self, comptime T: type) *T {
return @ptrCast(*T, @alignCast(@alignOf(T), self.ptr));
}
};
pub const Value = union(enum) {
Int: i64,
Float: f64,
Char: u8,
Boolean: bool,
Sentinel,
String: []const u8,
Word: usize,
Symbol: usize,
Slice: []const Value,
FFI_Fn: FFI_Fn,
RcPtr: RcPtr,
UnmanagedPtr: UnmanagedPtr,
};
pub const ValueType = @TagType(Value);
//;
pub const Rc = struct {
const Self = @This();
pub const Ptr = opaque {};
type_id: usize,
ptr: *Ptr,
ref_ct: usize,
pub fn makeOne(allocator: *Allocator, type_id: usize, ptr: anytype) Allocator.Error!*Self {
var rc = try allocator.create(Self);
rc.* = .{
.type_id = type_id,
.ptr = @ptrCast(*Ptr, ptr),
.ref_ct = 1,
};
return rc;
}
pub fn inc(self: *Self) void {
self.ref_ct += 1;
}
// returns if the obj is alive or not
pub fn dec(self: *Self) bool {
std.debug.assert(self.ref_ct > 0);
self.ref_ct -= 1;
return self.ref_ct != 0;
}
pub fn cast(self: Self, comptime T: type) *T {
return @ptrCast(*T, @alignCast(@alignOf(T), self.ptr));
}
};
pub const RcPtr = struct {
const Self = @This();
rc: *Rc,
is_weak: bool,
};
pub const RcType = struct {
equivalent_fn: fn (*Thread, RcPtr, Value) bool = defaultEquivalent,
finalize_fn: fn (*VM, RcPtr) void = defaultFinalize,
fn defaultEquivalent(t: *Thread, ptr: RcPtr, val: Value) bool {
return false;
}
fn defaultFinalize(t: *VM, ptr: RcPtr) void {}
};
pub const UnmanagedType = struct {
equivalent_fn: fn (*Thread, UnmanagedPtr, Value) bool = defaultEquivalent,
// TODO can this throw errors
dup_fn: fn (*VM, UnmanagedPtr) UnmanagedPtr = defaultDup,
drop_fn: fn (*VM, UnmanagedPtr) void = defaultDrop,
fn defaultEquivalent(t: *Thread, ptr: UnmanagedPtr, val: Value) bool {
return false;
}
fn defaultDup(t: *VM, ptr: UnmanagedPtr) UnmanagedPtr {
return ptr;
}
fn defaultDrop(t: *VM, ptr: UnmanagedPtr) void {}
};
pub const OrthType = struct {
pub const Type = union(enum) {
Primitive,
Rc: RcType,
Unmanaged: UnmanagedType,
};
ty: Type,
name_id: usize = undefined,
};
//;
pub const orth_base = @embedFile("base.orth");
pub const ReturnValue = struct {
value: Value,
restore_ct: usize,
};
pub const DefinedWord = struct {
value: Value,
eval_on_lookup: bool,
};
pub const VM = struct {
const Self = @This();
allocator: *Allocator,
symbol_table: ArrayList([]const u8),
word_table: ArrayList(?DefinedWord),
type_table: ArrayList(OrthType),
string_literals: ArrayList([]const u8),
// note: this coud be a Stack([]const Value)
// but there is a zig bug
// just going to use a Value that will always be a Value.Slice
slice_literals: ArrayList(Value),
pub fn init(allocator: *Allocator) Allocator.Error!Self {
var ret = Self{
.allocator = allocator,
.symbol_table = ArrayList([]const u8).init(allocator),
.word_table = ArrayList(?DefinedWord).init(allocator),
.type_table = ArrayList(OrthType).init(allocator),
.string_literals = ArrayList([]const u8).init(allocator),
.slice_literals = ArrayList(Value).init(allocator),
};
const PrimitiveTypeData = struct {
id: ValueType,
name: []const u8,
};
const primitive_types = [_]PrimitiveTypeData{
.{ .id = .Int, .name = "int" },
.{ .id = .Float, .name = "float" },
.{ .id = .Char, .name = "char" },
.{ .id = .Boolean, .name = "boolean" },
.{ .id = .Sentinel, .name = "sentinel" },
.{ .id = .String, .name = "string-literal" },
.{ .id = .Word, .name = "word" },
.{ .id = .Symbol, .name = "symbol" },
.{ .id = .Slice, .name = "slice" },
.{ .id = .FFI_Fn, .name = "ffi-fn" },
.{ .id = .RcPtr, .name = "rc-ptr" },
.{ .id = .UnmanagedPtr, .name = "unmanaged-ptr" },
};
for (primitive_types) |p| {
std.debug.assert(@enumToInt(p.id) ==
try ret.installType(
p.name,
.{ .ty = .{ .Primitive = {} } },
));
}
return ret;
}
pub fn deinit(self: *Self) void {
for (self.word_table.items) |dword| {
if (dword) |w| {
self.dropValue(w.value);
}
}
for (self.slice_literals.items) |val| {
for (val.Slice) |v| {
self.dropValue(v);
}
}
for (self.slice_literals.items) |val| {
self.allocator.free(val.Slice);
}
self.slice_literals.deinit();
for (self.string_literals.items) |str| {
self.allocator.free(str);
}
self.string_literals.deinit();
self.type_table.deinit();
self.word_table.deinit();
for (self.symbol_table.items) |sym| {
self.allocator.free(sym);
}
self.symbol_table.deinit();
}
//;
pub fn installBaseLib(self: *Self) Allocator.Error!void {
try self.defineWord("#t", .{
.value = .{ .Boolean = true },
.eval_on_lookup = false,
});
try self.defineWord("#f", .{
.value = .{ .Boolean = false },
.eval_on_lookup = false,
});
try self.defineWord("#sentinel", .{
.value = .{ .Sentinel = {} },
.eval_on_lookup = false,
});
for (builtins.builtins) |bi| {
const idx = try self.internSymbol(bi.name);
self.word_table.items[idx] = .{
.value = .{
.FFI_Fn = .{
.name_id = idx,
.func = bi.func,
},
},
.eval_on_lookup = true,
};
}
try builtins.ft_record.install(self);
try builtins.ft_vec.install(self);
try builtins.ft_string.install(self);
try builtins.ft_map.install(self);
try builtins.ft_file.install(self);
var t = self.loadString(orth_base) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
// TODO print errors
else => unreachable,
};
defer t.deinit();
while (t.step() catch |err| {
switch (err) {
error.OutOfMemory => return error.OutOfMemory,
// TODO print errors
else => unreachable,
}
}) {}
}
pub fn loadString(self: *Self, str: []const u8) (Allocator.Error || Tokenizer.Error)!Thread {
var tk = Tokenizer.init(str);
var tokens = std.ArrayList(Token).init(self.allocator);
defer tokens.deinit();
while (try tk.next()) |tok| {
try tokens.append(tok);
}
const values = try self.parse(tokens.items);
return Thread.init(self, values);
}
// parse ===
// TODO make a version of this that doesnt duplicate the string
pub fn internSymbol(self: *Self, str: []const u8) Allocator.Error!usize {
for (self.symbol_table.items) |st_str, i| {
if (std.mem.eql(u8, str, st_str)) {
return i;
}
}
const idx = self.symbol_table.items.len;
try self.symbol_table.append(try self.allocator.dupe(u8, str));
try self.word_table.append(null);
return idx;
}
// TODO handle memory if theres an error
// possible errors are allocator errors and slice errors
pub fn parse(self: *Self, tokens: []const Token) Allocator.Error![]Value {
var ret = ArrayList(Value).init(self.allocator);
var slice_stack = Stack(ArrayList(Value)).init(self.allocator);
defer slice_stack.deinit();
for (tokens) |token| {
const append_to: *ArrayList(Value) = if (slice_stack.data.items.len > 0) blk: {
break :blk slice_stack.index(0) catch unreachable;
} else &ret;
switch (token.data) {
.String => |str_data| {
var ct: usize = 0;
var fixer = StringFixer.init(str_data.str, str_data.indent);
while (fixer.next() catch unreachable) |_| {
ct += 1;
}
const buf = try self.allocator.alloc(u8, ct);
fixer.reset();
ct = 0;
while (fixer.next() catch unreachable) |ch| {
buf[ct] = ch;
ct += 1;
}
try self.string_literals.append(buf);
try append_to.append(.{ .String = buf });
},
.CharEscape => |ch| {
try append_to.append(.{ .Char = ch });
},
.IntEscape => |i| {
try append_to.append(.{ .Int = i });
},
.Symbol => |sym| {
try append_to.append(.{ .Symbol = try self.internSymbol(sym) });
},
.Word => |word| {
if (std.mem.eql(u8, word, "{")) {
try slice_stack.push(ArrayList(Value).init(self.allocator));
} else if (std.mem.eql(u8, word, "}")) {
// TODO handle this error for stack underflow
var slice_arraylist = slice_stack.pop() catch unreachable;
const slice = .{ .Slice = slice_arraylist.toOwnedSlice() };
try self.slice_literals.append(slice);
if (slice_stack.data.items.len > 0) {
try (slice_stack.index(0) catch unreachable).append(slice);
} else {
try ret.append(slice);
}
} else {
const try_parse_float =
!std.mem.eql(u8, word, "+") and
!std.mem.eql(u8, word, "-") and
!std.mem.eql(u8, word, ".");
const fl = std.fmt.parseFloat(f32, word) catch null;
if (std.fmt.parseInt(i32, word, 10) catch null) |i| {
try append_to.append(.{ .Int = i });
} else if (try_parse_float and (fl != null)) {
try append_to.append(.{ .Float = fl.? });
} else {
try append_to.append(.{ .Word = try self.internSymbol(word) });
}
}
},
}
}
// TODO if literals_stack still has stuff on it thats an error
return ret.toOwnedSlice();
}
// eval ===
pub fn dupValue(self: *Self, val: Value) Value {
switch (val) {
.RcPtr => |ptr| {
if (!ptr.is_weak) {
ptr.rc.inc();
}
return val;
},
.UnmanagedPtr => |ptr| return .{
.UnmanagedPtr = self.type_table.items[ptr.type_id].ty.Unmanaged.dup_fn(self, ptr),
},
else => return val,
}
}
pub fn dropValue(self: *Self, val: Value) void {
switch (val) {
.RcPtr => |ptr| {
if (!ptr.is_weak and !ptr.rc.dec()) {
self.type_table.items[ptr.rc.type_id].ty.Rc.finalize_fn(self, ptr);
self.allocator.destroy(ptr.rc);
}
},
.UnmanagedPtr => |ptr| {
self.type_table.items[ptr.type_id].ty.Unmanaged.drop_fn(self, ptr);
},
else => {},
}
}
//;
pub fn lookupDefinedWord(self: *Self, id: usize) ?*DefinedWord {
if (self.word_table.items[id]) |*dword| {
return dword;
} else {
return null;
}
}
// TODO check types dont have same name?
// returns type id
pub fn installType(self: *Self, name: []const u8, ty: OrthType) Allocator.Error!usize {
const idx = self.type_table.items.len;
try self.type_table.append(ty);
self.type_table.items[idx].name_id = try self.internSymbol(name);
return idx;
}
// TODO dupValue here?
// this is designed to be used from within zig not in ffi_fns
pub fn defineWord(self: *Self, name: []const u8, dword: DefinedWord) Allocator.Error!void {
const idx = try self.internSymbol(name);
self.word_table.items[idx] = dword;
}
};
pub const Trace = struct {
name: ?usize,
eval: union(enum) {
Slice: []const Value,
FFI_Fn: FFI_Fn,
},
};
pub const Thread = struct {
const Self = @This();
pub const Error = error{
WordNotFound,
TypeError,
DivideByZero,
NegativeDenominator,
Panic,
InvalidReturnValue,
InternalError,
} || StackError || Allocator.Error;
// TODO use this
pub const ErrorInfo = struct {
line_number: usize,
word_not_found: []const u8,
};
vm: *VM,
error_info: ErrorInfo,
code: []Value,
current_execution: []const Value,
restore_ct: usize,
enable_tco: bool,
stack: Stack(Value),
return_stack: Stack(ReturnValue),
restore_stack: Stack(Value),
trace_stack: Stack(Trace),
// TODO takes ownership of values
// frees using the vm allocator
// is that right?
// only way to make threads in the api might be from vm so it might be fine
pub fn init(vm: *VM, values: []Value) Self {
var ret = .{
.vm = vm,
.error_info = undefined,
.code = values,
.current_execution = values,
.restore_ct = 0,
.enable_tco = true,
.stack = Stack(Value).init(vm.allocator),
.return_stack = Stack(ReturnValue).init(vm.allocator),
.restore_stack = Stack(Value).init(vm.allocator),
.trace_stack = Stack(Trace).init(vm.allocator),
};
return ret;
}
pub fn deinit(self: *Self) void {
for (self.restore_stack.data.items) |val| {
self.vm.dropValue(val);
}
for (self.return_stack.data.items) |rv| {
self.vm.dropValue(rv.value);
}
for (self.stack.data.items) |val| {
self.vm.dropValue(val);
}
self.trace_stack.deinit();
self.restore_stack.deinit();
self.return_stack.deinit();
self.stack.deinit();
self.vm.allocator.free(self.code);
}
//;
pub fn printStackTrace(self: *Self) void {
const len = self.trace_stack.data.items.len;
for (self.trace_stack.data.items) |trace, i| {
std.debug.print("{}: ", .{len - i - 1});
if (trace.name) |idx| {
var name = self.vm.symbol_table.items[idx];
switch (trace.eval) {
.Slice => |s| std.debug.print("slice({})", .{name}),
.FFI_Fn => |fp| std.debug.print("ffi({})", .{name}),
}
} else {
switch (trace.eval) {
.Slice => |s| std.debug.print("anon(slice({}))", .{s}),
.FFI_Fn => |fp| std.debug.print("anon(ffi({}))", .{self.vm.symbol_table.items[fp.name_id]}),
}
}
std.debug.print("\n", .{});
}
}
//;
// NOTE: just moves value, does not dup it
pub fn evaluateValue(self: *Self, name: ?usize, value: Value, restore_ct: usize) Error!void {
switch (value) {
.Word => |idx| {
const found_word = self.vm.word_table.items[idx];
if (found_word) |dword| {
if (dword.eval_on_lookup) {
// found_word can't be a word or this may loop
//TODO make a different error for this
if (dword.value == .Word) return error.InternalError;
try self.evaluateValue(idx, self.vm.dupValue(dword.value), 0);
} else {
try self.stack.push(self.vm.dupValue(dword.value));
}
} else {
self.error_info.word_not_found = self.vm.symbol_table.items[idx];
return error.WordNotFound;
}
},
.Slice => |slc| {
if (!self.enable_tco or !(self.current_execution.len == 0 and self.restore_ct == 0)) {
try self.return_stack.push(.{
.value = .{ .Slice = self.current_execution },
.restore_ct = self.restore_ct,
});
try self.trace_stack.push(.{
.name = name,
.eval = .{ .Slice = slc },
});
}
self.current_execution = slc;
self.restore_ct = restore_ct;
},
.FFI_Fn => |fp| {
try self.trace_stack.push(.{
.name = name,
.eval = .{ .FFI_Fn = fp },
});
try fp.func(self);
_ = try self.trace_stack.pop();
},
else => try self.stack.push(value),
}
}
pub fn readValue(self: *Self, value: Value) Error!void {
switch (value) {
.Word => |idx| try self.evaluateValue(idx, value, 0),
else => |val| try self.stack.push(val),
}
}
pub fn step(self: *Self) Error!bool {
while (self.current_execution.len != 0) {
var value = self.current_execution[0];
self.current_execution.ptr += 1;
self.current_execution.len -= 1;
// TODO handle thread errors here, any errors besides allocator errors
// readValue() shouldnt handle errors as `read` from within orth might do something different with them
try self.readValue(value);
return true;
}
var i: usize = 0;
while (i < self.restore_ct) : (i += 1) {
try self.stack.push(try self.restore_stack.pop());
}
if (self.return_stack.data.items.len > 0) {
const rv = self.return_stack.pop() catch unreachable;
_ = try self.trace_stack.pop();
if (rv.restore_ct == std.math.maxInt(usize)) {
// TODO this can happen with invalid restore count
// or a word leaving things on the return stack
return error.InvalidReturnValue;
}
// TODO checking current_execution len here could be used for tco
self.current_execution = rv.value.Slice;
self.restore_ct = rv.restore_ct;
return true;
} else {
return false;
}
}
};
|
src/lib.zig
|
const std = @import("std");
usingnamespace @import("kiragine").kira.log;
const engine = @import("kiragine");
usingnamespace @import("kiragine").kira.log;
const Ship = struct {
firerate: f32 = 0.5,
firetimer: f32 = 0,
firecount: u32 = 0,
position: engine.Vec2f = engine.Vec2f{},
speed: engine.Vec2f = engine.Vec2f{},
size: engine.Vec2f = engine.Vec2f{},
colour: engine.Colour = engine.Colour.rgba(255, 255, 255, 255),
pub fn draw(self: Ship) !void {
const triangle = [3]engine.Vec2f{
.{ .x = self.position.x, .y = self.position.y },
.{ .x = self.position.x + (self.size.x / 2), .y = self.position.y - self.size.y },
.{ .x = self.position.x + self.size.x, .y = self.position.y },
};
try engine.drawTriangle(triangle[0], triangle[1], triangle[2], self.colour);
}
};
const Bullet = struct {
position: engine.Vec2f = engine.Vec2f{},
velocity: engine.Vec2f = engine.Vec2f{},
size: engine.Vec2f = engine.Vec2f{},
colour: engine.Colour = engine.Colour.rgba(255, 255, 255, 255),
alive: bool = false,
pub fn draw(self: Bullet) !void {
try engine.drawRectangle(.{ .x = self.position.x, .y = self.position.y, .width = self.size.x, .height = self.size.y }, self.colour);
}
};
const BulletFactory = struct {
pub const maxcount: u32 = 500;
list: [maxcount]Bullet = undefined,
pub fn clear(self: *BulletFactory) void {
var i: u32 = 0;
while (i < maxcount) : (i += 1) {
self.list[i].alive = false;
}
}
pub fn draw(self: BulletFactory) !void {
var i: u32 = 0;
while (i < maxcount) : (i += 1) {
if (self.list[i].alive) {
try self.list[i].draw();
}
}
}
pub fn update(self: *BulletFactory, fixedtime: f32) void {
var i: u32 = 0;
while (i < maxcount) : (i += 1) {
if (self.list[i].alive) {
self.list[i].position = self.list[i].position.addValues(self.list[i].velocity.x * fixedtime, self.list[i].velocity.y * fixedtime);
if (self.list[i].velocity.y > 0.1 and self.list[i].position.y > 1000 or self.list[i].velocity.y < -0.1 and self.list[i].position.y < -100) {
self.list[i].alive = false;
}
}
}
}
pub fn add(self: *BulletFactory, bullet: Bullet) !void {
var i: u32 = 0;
while (i < maxcount) : (i += 1) {
if (!self.list[i].alive) {
self.list[i] = bullet;
self.list[i].alive = true;
return;
}
}
try engine.check(true, "Unable to add bullet(filled list)!", .{});
}
};
const windowWidth = 1024;
const windowHeight = 768;
var input: *engine.Input = undefined;
var player = Ship{
.firerate = 0.1,
.firetimer = 0.0,
.firecount = 100,
.position = .{ .x = 1024 / 2 - 15, .y = 768 - 30 * 2 },
.speed = .{ .x = 0, .y = 0 },
.size = .{ .x = 30, .y = 30 },
.colour = engine.Colour.rgba(30, 70, 230, 255),
};
var playerbulletfactory = BulletFactory{};
fn update(deltatime: f32) !void {
{
const keyF = try input.keyState('F');
const bullet = Bullet{
.size = .{ .x = 10, .y = 10 },
.position = .{ .x = player.position.x + player.size.x / 2 - 5, .y = player.position.y - player.size.y },
.velocity = .{ .x = 0, .y = -200 },
.colour = engine.Colour.rgba(200, 150, 50, 255),
};
if (player.firetimer < player.firerate) {
player.firetimer += 1 * deltatime;
} else if (player.firecount > 0) {
if (keyF == engine.Input.State.down) {
player.firetimer = 0.0;
player.firecount -= 1;
std.log.notice("player: fire({})", .{player.firecount});
playerbulletfactory.add(bullet) catch |err| {
if (err == engine.Error.CheckFailed) {
player.firecount += 1;
}
};
}
}
}
}
fn fixedUpdate(fixedtime: f32) !void {
{
const keyA = try input.keyState('A');
const keyD = try input.keyState('D');
const acc = 50.0;
const maxspd = 300.0;
const friction = 10.0;
if (keyD == engine.Input.State.down and player.speed.x <= maxspd) {
player.speed.x += acc;
}
if (keyA == engine.Input.State.down and player.speed.x >= -maxspd) {
player.speed.x -= acc;
}
if (player.speed.x > 0.1) {
player.speed.x -= friction;
} else if (player.speed.x < -0.1) {
player.speed.x += friction;
}
if (player.position.x > @intToFloat(f32, windowWidth) - player.size.x or player.position.x <= 0) player.speed.x = -player.speed.x;
player.position.x += player.speed.x * fixedtime;
}
playerbulletfactory.update(fixedtime);
}
fn draw() !void {
engine.clearScreen(0.1, 0.1, 0.1, 1.0);
try engine.pushBatch2D(engine.Renderer2DBatchTag.triangles);
try playerbulletfactory.draw();
try player.draw();
try engine.popBatch2D();
}
pub fn main() !void {
const callbacks = engine.Callbacks{
.draw = draw,
.update = update,
.fixed = fixedUpdate,
};
try engine.init(callbacks, windowWidth, windowHeight, "simpleshooter", 0, std.heap.page_allocator);
input = engine.getInput();
try input.bindKey('D');
try input.bindKey('A');
try input.bindKey('F');
try engine.open();
try engine.update();
try engine.deinit();
}
|
examples/simpleshooter.zig
|
const std = @import("std");
pub const Product = enum(u16) {
/// Base product
essence,
/// Company of Heroes
coho,
_,
};
pub const SGAHeader = struct {
/// Version | Title
/// ------- | -----
/// 4 | Company of Heroes 1
/// 5 | Dawn of War II - Broken
/// 6 | Unknown
/// 7 | Company of Heroes 2
/// 8 | Unknown
/// 9 | Dawn of War III
/// 10 | Company of Heroes 3, Age of Empires IV
version: u16,
product: Product,
/// Nice name for the archive; unicode
nice_name: [64]u16,
// Hashes - only present in version < 6 because why not that's totally a great idea; thanks Relic!!
file_md5: ?[16]u8,
header_md5: ?[16]u8,
// Offsets and lengths
/// Base offset, every other offset here except for `data_offset` can be accessed at `offset + other_offset`
/// Where toc_data_offset .. hash_length are stored
offset: u64,
/// Offset for raw file data
data_offset: u64,
/// Archive signature
signature: [256]u8 = [_]u8{ 00, 00, 00, 00, 00, 00, 00, 00 } ** 32,
/// Where ToC data is stored (relative to `offset`)
toc_data_offset: u32,
/// Number of ToC entries
toc_data_count: u32,
/// Where folder data is stored (relative to `offset`)
folder_data_offset: u32,
/// Number of folder entries
folder_data_count: u32,
/// Where file data is stored (relative to `offset`)
file_data_offset: u32,
/// Number of file entries
file_data_count: u32,
/// Where strings (file & folder names, etc.) are stored (relative to `offset`)
string_offset: u32,
/// Length of the string section
string_length: u32,
/// Where file hashes are stored (relative to `offset`?)
hash_offset: ?u32 = null,
/// Length of file hashes
hash_length: ?u32 = null,
/// Size of a data block; use unknown - maybe this was used in the olden days where block padding was needed??
/// Typically 262144 (~256kb)
block_size: ?u32 = 262144,
pub fn readIndex(self: SGAHeader, reader: anytype) !u32 {
return if (self.version <= 4)
try reader.readIntLittle(u16)
else
try reader.readIntLittle(u32);
}
pub fn writeIndex(self: SGAHeader, writer: anytype, index: u32) !void {
if (self.version <= 4)
try writer.writeIntLittle(u16, @intCast(u16, index))
else
try writer.writeIntLittle(u32, index);
}
/// Calculate header.offset, useful for "lazy" unbroken `encode`s.
pub fn calcOffset(self: SGAHeader) usize {
return 8 + 2 + 2 + (if (self.version < 6) @as(usize, 32) else @as(usize, 0)) + 128 + (if (self.version >= 9)
@as(usize, 8)
else if (self.version >= 8)
@as(usize, 4)
else
0) + 4 + (if (self.version >= 9)
16
else
4 +
(if (self.version >= 8) @as(usize, 4) else @as(usize, 0))) + 4 + (if (self.version >= 8) @as(usize, 256) else @as(usize, 0));
}
/// Calculate the length of the data at header.offset, useful for "lazy" unbroken `encode`s
pub fn calcOffsetLength(self: SGAHeader) usize {
return 16 + (if (self.version <= 4)
@as(usize, 2)
else
@as(usize, 4)) * 4 + if (self.version >= 7) 8 +
if (self.version >= 8) 4;
}
pub fn decode(reader: anytype) !SGAHeader {
var header: SGAHeader = undefined;
var magic: [8]u8 = undefined;
_ = try reader.readAll(&magic);
if (!std.mem.eql(u8, &magic, "_ARCHIVE"))
return error.InvalidHeader;
header.version = try reader.readIntLittle(u16);
header.product = @intToEnum(Product, try reader.readIntLittle(u16));
if (header.version < 4 or header.version > 10 or header.product != Product.essence)
return error.UnsupportedVersion;
if (header.version < 6) _ = try reader.readAll(&(header.file_md5.?));
_ = try reader.readAll(@ptrCast(*[128]u8, &header.nice_name));
if (header.version < 6) _ = try reader.readAll(&(header.header_md5.?));
var nullable_1: ?u64 = if (header.version >= 9) // nullable1, header offset
try reader.readIntLittle(u64)
else if (header.version >= 8)
@as(u64, try reader.readIntLittle(u32))
else
null;
var header_blob_offset = try reader.readIntLittle(u32); // num1, used pretty much nowhere, typically points to EoF
_ = header_blob_offset;
var data_blob_offset: ?u64 = null; // nullable2, used pretty much nowhere, typically points to header.offset
header.data_offset = 0; // Used to read file data
if (header.version >= 9) {
header.data_offset = try reader.readIntLittle(u64);
data_blob_offset = try reader.readIntLittle(u64);
} else {
header.data_offset = try reader.readIntLittle(u32);
if (header.version >= 8)
data_blob_offset = try reader.readIntLittle(u32);
}
var num2 = try reader.readIntLittle(u32); // num2, no use, typically = 1
_ = num2;
if (header.version >= 8)
_ = try reader.readAll(&header.signature);
header.offset = if (nullable_1) |val| val else try reader.context.getPos();
try reader.context.seekTo(header.offset);
header.toc_data_offset = try reader.readIntLittle(u32); // num3
header.toc_data_count = try header.readIndex(reader); // num4
header.folder_data_offset = try reader.readIntLittle(u32); // num5
header.folder_data_count = try header.readIndex(reader); // num6
header.file_data_offset = try reader.readIntLittle(u32); // num7
header.file_data_count = try header.readIndex(reader); // num8
header.string_offset = try reader.readIntLittle(u32); // num9
header.string_length = try header.readIndex(reader); // num10
if (header.version >= 7) {
header.hash_offset = try reader.readIntLittle(u32); // num11
if (header.version >= 8) {
header.hash_length = try reader.readIntLittle(u32); // num12
}
header.block_size = try reader.readIntLittle(u32);
}
return header;
}
pub fn encode(self: SGAHeader, writer: anytype) !void {
try writer.writeAll("_ARCHIVE");
try writer.writeIntLittle(u16, self.version);
try writer.writeIntLittle(u16, @enumToInt(self.product));
if (self.version < 4 or self.version > 10 or self.product != Product.essence)
return error.UnsupportedVersion;
if (self.version < 6) try writer.writeAll(&(self.file_md5.?));
_ = try writer.writeAll(@ptrCast(*const [128]u8, &self.nice_name));
if (self.version < 6) _ = try writer.writeAll(&(self.header_md5.?));
// nullable1, header offset
if (self.version >= 9)
try writer.writeIntLittle(u64, self.offset)
else if (self.version >= 8)
try writer.writeIntLittle(u32, @intCast(u32, self.offset));
try writer.writeIntLittle(u32, 0); // num1, used pretty much nowhere, typically points to EoF
var data_blob_offset: u64 = self.offset; // nullable2, used pretty much nowhere, typically points to header.offset
if (self.version >= 9) {
try writer.writeIntLittle(u64, self.data_offset);
try writer.writeIntLittle(u64, data_blob_offset);
} else {
try writer.writeIntLittle(u32, @intCast(u32, self.data_offset));
if (self.version >= 8)
try writer.writeIntLittle(u32, @intCast(u32, data_blob_offset));
}
try writer.writeIntLittle(u32, 1); // num2, no use, typically = 1
if (self.version >= 8)
try writer.writeAll(&self.signature);
try writer.context.seekTo(self.offset);
try writer.writeIntLittle(u32, self.toc_data_offset); // num3
try self.writeIndex(writer, self.toc_data_count); // num4
try writer.writeIntLittle(u32, self.folder_data_offset); // num5
try self.writeIndex(writer, self.folder_data_count); // num6
try writer.writeIntLittle(u32, self.file_data_offset); // num7
try self.writeIndex(writer, self.file_data_count); // num8
try writer.writeIntLittle(u32, self.string_offset); // num9
try self.writeIndex(writer, self.string_length); // num10
if (self.version >= 7) {
try writer.writeIntLittle(u32, self.hash_offset.?); // num11
if (self.version >= 8) {
try writer.writeIntLittle(u32, self.hash_length.?); // num12
}
try writer.writeIntLittle(u32, self.block_size.?);
}
}
};
/// Seems to document sections, named based on the type of the contents (data - scripts, assets, reflect - databases, attrib - unit, map attributes),
/// I have never seen more than one per archive and it seems Essence.Core pretty much doesn't care about more than one of these per archive
/// Could also be related to game's protocols when loading files (data: - maybe there's an attrib: protocol);
/// see AoE4 logs by running the game with the `-dev` option
pub const TOCEntry = struct {
alias: [64]u8,
name: [64]u8,
// Folders within these indexes are children of this TOC section
folder_start_index: u32,
folder_end_index: u32,
// Files within these indexes are children of this TOC section
file_start_index: u32,
file_end_index: u32,
/// This section's root (top) folder
folder_root_index: u32,
pub fn decode(reader: anytype, header: SGAHeader) !TOCEntry {
var entry: TOCEntry = undefined;
_ = try reader.readAll(&entry.alias);
_ = try reader.readAll(&entry.name);
entry.folder_start_index = try header.readIndex(reader);
entry.folder_end_index = try header.readIndex(reader);
entry.file_start_index = try header.readIndex(reader);
entry.file_end_index = try header.readIndex(reader);
entry.folder_root_index = try header.readIndex(reader);
return entry;
}
pub fn encode(self: TOCEntry, writer: anytype, header: SGAHeader) !void {
try writer.writeAll(self.alias);
try writer.writeAll(self.name);
try header.writeIndex(writer, self.folder_start_index);
try header.writeIndex(writer, self.folder_end_index);
try header.writeIndex(writer, self.file_start_index);
try header.writeIndex(writer, self.file_end_index);
try header.writeIndex(writer, self.folder_root_index);
}
};
pub const FolderEntry = struct {
/// Offset of the folder's name (offset + string_offset + name_offset)
name_offset: u32,
// Folders within these indexes are children of this folder
folder_start_index: u32,
folder_end_index: u32,
// Files within these indexes are children of this folder
file_start_index: u32,
file_end_index: u32,
pub fn decode(reader: anytype, header: SGAHeader) !FolderEntry {
var entry: FolderEntry = undefined;
entry.name_offset = try reader.readIntLittle(u32);
entry.folder_start_index = try header.readIndex(reader);
entry.folder_end_index = try header.readIndex(reader);
entry.file_start_index = try header.readIndex(reader);
entry.file_end_index = try header.readIndex(reader);
return entry;
}
pub fn encode(self: FolderEntry, writer: anytype, header: SGAHeader) !void {
try writer.writeIntLittle(u32, self.name_offset);
try header.writeIndex(writer, self.folder_start_index);
try header.writeIndex(writer, self.folder_end_index);
try header.writeIndex(writer, self.file_start_index);
try header.writeIndex(writer, self.file_end_index);
}
};
pub const FileVerificationType = enum(u8) {
none,
crc,
crc_blocks,
md5_blocks,
sha1_blocks,
};
pub const FileStorageType = enum(u8) {
/// Uncompressed
store,
/// Deflate stream
stream_compress,
/// Also deflate stream 🤷
buffer_compress,
};
pub const FileEntry = struct {
/// Offset of the file's name (offset + string_offset + name_offset)
name_offset: u32,
/// Offset of the file's data (data_offset + data_offset)
data_offset: u64,
/// Length in the archive as compressed
compressed_length: u32,
/// Length after decompression
uncompressed_length: u32,
/// What hashing algorithm is used to check the file's integrity
verification_type: FileVerificationType,
/// How the file is stored (compressed)
storage_type: FileStorageType,
/// CRC of the (potentially) compressed file data at data_offset; present version >= 6
crc: ?u32 = null,
/// Hash of the uncompressed file; present version >= 7, though in version == 7 the hash
/// is located at the end whereas in version > 7 it's located after name_offset
/// (offset + header.hash_offset + file.hash_offset)
hash_offset: ?u32 = null,
pub fn decode(reader: anytype, header: SGAHeader) !FileEntry {
var entry: FileEntry = undefined;
entry.name_offset = try reader.readIntLittle(u32);
if (header.version > 7)
entry.hash_offset = try reader.readIntLittle(u32);
entry.data_offset = if (header.version < 9) try reader.readIntLittle(u32) else try reader.readIntLittle(u64);
entry.compressed_length = try reader.readIntLittle(u32);
entry.uncompressed_length = try reader.readIntLittle(u32);
if (header.version < 10)
_ = try reader.readIntLittle(u32); // num13 - seems to be padding?
entry.verification_type = @intToEnum(FileVerificationType, try reader.readByte());
entry.storage_type = @intToEnum(FileStorageType, try reader.readByte());
if (header.version >= 6)
entry.crc = try reader.readIntLittle(u32);
if (header.version == 7)
entry.hash_offset = try reader.readIntLittle(u32);
return entry;
}
pub fn encode(self: FileEntry, writer: anytype, header: SGAHeader) !void {
try writer.writeIntLittle(u32, self.name_offset);
if (header.version > 7)
try writer.writeIntLittle(u32, self.hash_offset orelse 0);
if (header.version < 9)
try writer.writeIntLittle(u32, self.data_offset)
else
try writer.writeIntLittle(u64, self.data_offset);
try writer.writeIntLittle(u32, self.compressed_length);
try writer.writeIntLittle(u32, self.uncompressed_length);
if (header.version < 10)
_ = try writer.writeIntLittle(u32, 0); // num13 - seems to be padding?
try writer.writeByte(@enumToInt(self.verification_type));
try writer.writeByte(@enumToInt(self.storage_type));
if (header.version >= 6)
try writer.writeIntLittle(u32, self.crc.?);
if (header.version == 7)
try writer.writeIntLittle(u32, self.hash_offset orelse 0);
}
};
// Higher level constructs
pub const Node = union(enum) {
toc: TOC,
folder: Folder,
file: File,
pub fn getName(self: Node) []const u8 {
return switch (self) {
.toc => |f| f.name,
.folder => |f| f.name,
.file => |f| f.name,
};
}
pub fn getChildren(self: Node) ?std.ArrayListUnmanaged(Node) {
return switch (self) {
.toc => |f| f.children,
.folder => |f| f.children,
.file => null,
};
}
pub fn propagateParent(self: *Node, children: []Node) void {
for (children) |*child| {
if (child.* != .folder) {
if (child.* == .file) {
std.log.info("PARENT: {s}, CHILD: {s}", .{ self.getName(), child.getName() });
child.file.parent = self;
}
} else {
std.log.info("PARENT: {s}, CHILD: {s}", .{ self.getName(), child.getName() });
child.folder.parent = self;
}
std.log.info("PARENT {s}", .{child.getParent()});
}
}
pub fn printTree(self: Node, level: usize) anyerror!void {
var l: usize = 0;
while (l < level * 4) : (l += 1)
try std.io.getStdOut().writer().print(" ", .{});
var name = self.getName();
try std.io.getStdOut().writer().print("{s}\n", .{name});
if (self.getChildren()) |children|
for (children.items) |child|
try child.printTree(level + 1);
}
};
pub const TOC = struct {
name: []const u8,
alt_name: []const u8,
children: std.ArrayListUnmanaged(Node),
header: *const SGAHeader,
entry: *const TOCEntry,
pub fn init(name: []const u8, alt_name: []const u8, children: std.ArrayListUnmanaged(Node), header: *const SGAHeader, entry: *const TOCEntry) TOC {
var toc: TOC = undefined;
toc.name = name;
toc.alt_name = alt_name;
toc.children = children;
toc.header = header;
toc.entry = entry;
return toc;
}
};
pub const Folder = struct {
name: []const u8,
children: std.ArrayListUnmanaged(Node),
header: *const SGAHeader,
entry: *const FolderEntry,
pub fn init(name: []const u8, children: std.ArrayListUnmanaged(Node), header: *const SGAHeader, entry: *const FolderEntry) Folder {
var folder: Folder = undefined;
folder.name = name;
folder.children = children;
folder.header = header;
folder.entry = entry;
return folder;
}
};
pub const File = struct {
name: []const u8,
header: *const SGAHeader,
entry: *const FileEntry,
pub fn init(name: []const u8, header: *const SGAHeader, entry: *const FileEntry) File {
var file: File = undefined;
file.name = name;
file.header = header;
file.entry = entry;
return file;
}
};
pub const Archive = struct {
arena: std.heap.ArenaAllocator,
header: SGAHeader,
root_nodes: std.ArrayListUnmanaged(Node),
pub fn fromFile(allocator: std.mem.Allocator, file: std.fs.File) !Archive {
return fromReader(allocator, file.reader());
}
pub fn fromReader(raw_allocator: std.mem.Allocator, reader: anytype) !Archive {
var archive: Archive = undefined;
archive.arena = std.heap.ArenaAllocator.init(raw_allocator);
const allocator = archive.arena.allocator();
var header = try SGAHeader.decode(reader);
archive.header = header;
// TOC
try reader.context.seekTo(header.offset + header.toc_data_offset);
var toc_entries = try std.ArrayList(TOCEntry).initCapacity(allocator, header.toc_data_count);
var toc_index: usize = 0;
while (toc_index < header.toc_data_count) : (toc_index += 1)
try toc_entries.append(try TOCEntry.decode(reader, header));
// Folders
try reader.context.seekTo(header.offset + header.folder_data_offset);
var folder_entries = try std.ArrayList(FolderEntry).initCapacity(allocator, header.folder_data_count);
var folder_index: usize = 0;
while (folder_index < header.folder_data_count) : (folder_index += 1)
try folder_entries.append(try FolderEntry.decode(reader, header));
// Files
try reader.context.seekTo(header.offset + header.file_data_offset);
var file_entries = try std.ArrayList(FileEntry).initCapacity(allocator, header.file_data_count);
var file_index: usize = 0;
while (file_index < header.file_data_count) : (file_index += 1)
try file_entries.append(try FileEntry.decode(reader, header));
// Make the tree
var name_buf = std.ArrayListUnmanaged(u8){};
// var data_buf = std.ArrayList(u8).init(allocator);
archive.root_nodes = try std.ArrayListUnmanaged(Node).initCapacity(allocator, toc_entries.items.len);
for (toc_entries.items) |toc| {
var children = try createChildren(allocator, reader, &header, folder_entries, file_entries, toc.folder_root_index, toc.folder_root_index + 1, 0, 0, &name_buf);
var toc_node = try archive.root_nodes.addOne(allocator);
toc_node.* = Node{ .toc = TOC.init(try allocator.dupe(u8, dezero(&toc.name)), try allocator.dupe(u8, dezero(&toc.alias)), children, &header, &toc) };
}
return archive;
}
pub fn deinit(self: *Archive) void {
self.arena.deinit();
self.* = undefined;
}
};
// TODO: Fix memory management; doesn't matter much because memory is freed on exit anyways
// but it'd still be cool if this program wasn't as totally garbage as the original
// TODO: Make sga strings []const u8s, "fixed length" really means "maximum length"
pub fn dezero(str: []const u8) []const u8 {
return std.mem.span(@ptrCast([*:0]const u8, str));
}
pub fn readDynamicString(reader: anytype, writer: anytype) !void {
while (true) {
var byte = try reader.readByte();
if (byte == 0)
return;
try writer.writeByte(byte);
}
}
pub fn writeDynamicString(writer: anytype, str: []const u8) !void {
try writer.writeAll(str);
try writer.writeByte(0);
}
fn readDynamicStringFromOffset(allocator: std.mem.Allocator, reader: anytype, name_buf: *std.ArrayListUnmanaged(u8), offset: usize) ![]u8 {
var old_pos = try reader.context.getPos();
try reader.context.seekTo(offset);
name_buf.items.len = 0;
try readDynamicString(reader, name_buf.*.writer(allocator));
try reader.context.seekTo(old_pos);
return allocator.dupe(u8, name_buf.items);
}
pub fn createChildren(
allocator: std.mem.Allocator,
//
reader: anytype,
header: *const SGAHeader,
//
folder_entries: std.ArrayList(FolderEntry),
file_entries: std.ArrayList(FileEntry),
//
folder_start_index: u32,
folder_end_index: u32,
//
file_start_index: u32,
file_end_index: u32,
//
name_buf: *std.ArrayListUnmanaged(u8),
) anyerror!std.ArrayListUnmanaged(Node) {
var node_list = try std.ArrayListUnmanaged(Node).initCapacity(allocator, folder_end_index - folder_start_index + file_end_index - file_start_index);
var folder_index: usize = folder_start_index;
while (folder_index < folder_end_index) : (folder_index += 1) {
var name = try readDynamicStringFromOffset(allocator, reader, name_buf, header.offset + header.string_offset + folder_entries.items[folder_index].name_offset);
var maybe_index = std.mem.lastIndexOfAny(u8, name, &[_]u8{ '/', '\\' });
if (maybe_index) |index|
name = name[index + 1 ..];
var children = try createChildren(allocator, reader, header, folder_entries, file_entries, folder_entries.items[folder_index].folder_start_index, folder_entries.items[folder_index].folder_end_index, folder_entries.items[folder_index].file_start_index, folder_entries.items[folder_index].file_end_index, name_buf);
if (name.len > 0) {
// var folder = Folder.init(name, children, header, &folder_entries.items[folder_index]);
// var folder_node = Node{ .folder = folder };
// folder_node.propagateParent(children.items);
// try node_list.append(allocator, folder_node);
var folder = Folder.init(name, children, header, &folder_entries.items[folder_index]);
var folder_node = try node_list.addOne(allocator);
folder_node.* = Node{ .folder = folder };
} else {
try node_list.appendSlice(allocator, children.toOwnedSlice(allocator));
}
}
var file_index: usize = file_start_index;
while (file_index < file_end_index) : (file_index += 1) {
// var file_offset = header.data_offset + file_entries.items[file_index].data_offset;
var name = try readDynamicStringFromOffset(allocator, reader, name_buf, header.offset + header.string_offset + file_entries.items[file_index].name_offset);
// if (name == null && this.Version < (ushort) 6)
// {
// long offset = fileOffset - 260L;
// name = this.m_fileStream.Seek(offset, SeekOrigin.Begin) != offset ? string.Format("File_{0}.dat", (object) index) : this.ReadFixedString(reader, 256, 1);
// } TODO: handle this nasty case
try node_list.append(allocator, Node{ .file = File.init(name, header, &file_entries.items[file_index]) });
}
return node_list;
}
const tora1 = @embedFile("../samples/tora1.sga");
test "Low-level decode" {
var reader = std.io.fixedBufferStream(tora1).reader();
var header = try SGAHeader.decode(reader);
try std.testing.expectEqual(@as(u16, 10), header.version);
var name_buf: [128]u8 = undefined;
_ = try std.unicode.utf16leToUtf8(&name_buf, &header.nice_name);
try std.testing.expectEqualSlices(u8, "data", name_buf[0..4]);
try std.testing.expectEqualSlices(u8, &[_]u8{ 8, 0, 0, 0, 0, 0, 0, 0 } ** 32, &header.signature);
try std.testing.expectEqual(@as(u32, 1), header.toc_data_count);
try reader.context.seekTo(header.offset + header.toc_data_offset);
var toc = try TOCEntry.decode(reader, header);
try std.testing.expectEqualSlices(u8, "data", toc.name[0..4]);
try std.testing.expectEqual(@as(u32, 2), header.folder_data_count); // data, scar
try std.testing.expectEqual(@as(u32, 1), header.file_data_count); // somescript.scar
}
test "High-level decode" {
var reader = std.io.fixedBufferStream(tora1).reader();
var archive = try Archive.fromReader(std.testing.allocator, reader);
defer archive.deinit();
try std.testing.expectEqual(@as(usize, 1), archive.root_nodes.items[0].toc.children.items.len);
}
|
lib/sga.zig
|
const cpu = @import("mk20dx256.zig");
pub fn enable() void {
asm volatile ("CPSIE i"
:
:
: "memory"
);
}
pub fn disable() void {
asm volatile ("CPSID i"
:
:
: "memory"
);
}
pub fn trigger_pendsv() void {
cpu.SystemControl.ICSR = 0x10000000;
}
extern fn xPortPendSVHandler() callconv(.C) void;
extern fn xPortSysTickHandler() callconv(.C) void;
extern fn vPortSVCHandler() callconv(.C) void;
extern fn USBOTG_IRQHandler() callconv(.C) void;
pub export fn isr_panic() void {
while (true) {}
}
pub export fn isr_ignore() void {}
pub const isr_non_maskable: fn () callconv(.C) void = isr_panic;
pub const isr_hard_fault: fn () callconv(.C) void = isr_panic;
pub const isr_memmanage_fault: fn () callconv(.C) void = isr_panic;
pub const isr_bus_fault: fn () callconv(.C) void = isr_panic;
pub const isr_usage_fault: fn () callconv(.C) void = isr_panic;
pub const isr_svcall: fn () callconv(.C) void = vPortSVCHandler;
pub const isr_debug_monitor: fn () callconv(.C) void = isr_ignore;
pub const isr_pendablesrvreq: fn () callconv(.C) void = xPortPendSVHandler;
pub const isr_systick: fn () callconv(.C) void = xPortSysTickHandler;
pub const isr_dma_ch0_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch1_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch2_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch3_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch4_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch5_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch6_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch7_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch8_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch9_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch10_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch11_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch12_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch13_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch14_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_ch15_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_dma_error: fn () callconv(.C) void = isr_ignore;
pub const isr_flash_cmd_complete: fn () callconv(.C) void = isr_ignore;
pub const isr_flash_read_collision: fn () callconv(.C) void = isr_ignore;
pub const isr_low_voltage_warning: fn () callconv(.C) void = isr_ignore;
pub const isr_low_voltage_wakeup: fn () callconv(.C) void = isr_ignore;
pub const isr_wdog_or_emw: fn () callconv(.C) void = isr_ignore;
pub const isr_i2c0: fn () callconv(.C) void = isr_ignore;
pub const isr_i2c1: fn () callconv(.C) void = isr_ignore;
pub const isr_spi0: fn () callconv(.C) void = isr_ignore;
pub const isr_spi1: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_or_msg_buf: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_bus_off: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_error: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_transmit_warn: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_receive_warn: fn () callconv(.C) void = isr_ignore;
pub const isr_can0_wakeup: fn () callconv(.C) void = isr_ignore;
pub const isr_i2s0_transmit: fn () callconv(.C) void = isr_ignore;
pub const isr_i2s0_receive: fn () callconv(.C) void = isr_ignore;
pub const isr_uart0_lon: fn () callconv(.C) void = isr_ignore;
pub const isr_uart0_status: fn () callconv(.C) void = isr_ignore;
pub const isr_uart0_error: fn () callconv(.C) void = isr_ignore;
pub const isr_uart1_status: fn () callconv(.C) void = isr_ignore;
pub const isr_uart1_error: fn () callconv(.C) void = isr_ignore;
pub const isr_uart2_status: fn () callconv(.C) void = isr_ignore;
pub const isr_uart2_error: fn () callconv(.C) void = isr_ignore;
pub const isr_adc0: fn () callconv(.C) void = isr_ignore;
pub const isr_adc1: fn () callconv(.C) void = isr_ignore;
pub const isr_cmp0: fn () callconv(.C) void = isr_ignore;
pub const isr_cmp1: fn () callconv(.C) void = isr_ignore;
pub const isr_cmp2: fn () callconv(.C) void = isr_ignore;
pub const isr_ftm0: fn () callconv(.C) void = isr_ignore;
pub const isr_ftm1: fn () callconv(.C) void = isr_ignore;
pub const isr_ftm2: fn () callconv(.C) void = isr_ignore;
pub const isr_cmt: fn () callconv(.C) void = isr_ignore;
pub const isr_rtc_alarm: fn () callconv(.C) void = isr_ignore;
pub const isr_rtc_seconds: fn () callconv(.C) void = isr_ignore;
pub const isr_pit_ch0: fn () callconv(.C) void = isr_ignore;
pub const isr_pit_ch1: fn () callconv(.C) void = isr_ignore;
pub const isr_pit_ch2: fn () callconv(.C) void = isr_ignore;
pub const isr_pit_ch3: fn () callconv(.C) void = isr_ignore;
pub const isr_pdb: fn () callconv(.C) void = isr_ignore;
pub const isr_usb_otg: fn () callconv(.C) void = USBOTG_IRQHandler;
pub const isr_usb_charger: fn () callconv(.C) void = isr_ignore;
pub const isr_dac0: fn () callconv(.C) void = isr_ignore;
pub const isr_tsi: fn () callconv(.C) void = isr_ignore;
pub const isr_mcg: fn () callconv(.C) void = isr_ignore;
pub const isr_lpt: fn () callconv(.C) void = isr_ignore;
pub const isr_port_a: fn () callconv(.C) void = isr_ignore;
pub const isr_port_b: fn () callconv(.C) void = isr_ignore;
pub const isr_port_c: fn () callconv(.C) void = isr_ignore;
pub const isr_port_d: fn () callconv(.C) void = isr_ignore;
pub const isr_port_e: fn () callconv(.C) void = isr_ignore;
pub const isr_software: fn () callconv(.C) void = isr_ignore;
|
src/teensy3_2/interrupt.zig
|
const std = @import("std");
const Fundude = @import("main.zig");
const Matrix = @import("util.zig").Matrix;
const MatrixSlice = @import("util.zig").MatrixSlice;
const EnumArray = @import("util.zig").EnumArray;
const SCREEN_WIDTH = 160;
const SCREEN_HEIGHT = 144;
const DOTS_PER_LINE = 456;
const BUFFER_LINES = 10;
const RENDER_LINES = SCREEN_HEIGHT + BUFFER_LINES;
const DOTS_PER_FRAME = (SCREEN_HEIGHT + BUFFER_LINES) * DOTS_PER_LINE;
pub const Io = packed struct {
LCDC: packed struct {
bg_enable: bool,
obj_enable: bool,
obj_size: enum(u1) {
Small = 0,
Large = 1,
},
bg_tile_map: TileMapAddressing,
bg_window_tile_data: TileAddressing,
window_enable: bool,
window_tile_map: TileMapAddressing,
lcd_enable: bool,
},
STAT: packed struct {
mode: LcdcMode,
coincidence: bool,
irq_hblank: bool,
irq_vblank: bool,
irq_oam: bool,
irq_coincidence: bool,
_pad: u1,
},
SCY: u8, // $FF42
SCX: u8, // $FF43
LY: u8, // $FF44
LYC: u8, // $FF45
DMA: u8, // $FF46
BGP: ColorPalette, // $FF47
OBP0: ColorPalette, // $FF48
OBP1: ColorPalette, // $FF49
WY: u8, // $FF4A
WX: u8, // $FF4B
};
const LcdcMode = packed enum(u2) {
hblank = 0,
vblank = 1,
searching = 2,
transferring = 3,
};
const Color = extern enum(u8) {
_0 = 0,
_1 = 1,
_2 = 2,
_3 = 3,
};
const Shade = extern enum(u8) {
White = 0,
Light = 1,
Dark = 2,
Black = 3,
fn asOpaque(self: Shade) Pixel {
const value: u5 = switch (self) {
.White => 31,
.Light => 21,
.Dark => 11,
.Black => 0,
};
return .{
.r = value,
.g = value,
.b = value,
.@"opaque" = true,
};
}
fn asPixel(self: Shade) Pixel {
var result = self.asOpaque();
result.@"opaque" = self != .White;
return result;
}
};
const Pixel = packed struct {
r: u5 align(2),
g: u5,
b: u5,
@"opaque": bool,
};
const ColorPalette = packed struct {
_: u8,
fn lookup(self: ColorPalette) EnumArray(Color, Shade) {
var result: EnumArray(Color, Shade) = undefined;
result.set(._0, @intToEnum(Shade, self._ >> (0 * 2) & 0b11));
// I have no idea why these two values are reversed
result.set(._1, @intToEnum(Shade, self._ >> (2 * 2) & 0b11));
result.set(._2, @intToEnum(Shade, self._ >> (1 * 2) & 0b11));
result.set(._3, @intToEnum(Shade, self._ >> (3 * 2) & 0b11));
return result;
}
};
const RawPattern = packed struct {
_: [8]u16,
};
pub const SpriteAttr = packed struct {
y_pos: u8,
x_pos: u8,
pattern: u8,
flags: packed struct {
_pad: u4,
palette: SpritePalette,
x_flip: bool,
y_flip: bool,
priority: bool,
},
};
const SpritePalette = packed enum(u1) {
OBP0 = 0,
OBP1 = 1,
};
const TileAddressing = packed enum(u1) {
_8800 = 0,
_8000 = 1,
pub fn translate(self: TileAddressing, idx: u8) u9 {
return if (idx >= 128 or self == ._8000) idx else idx + @as(u9, 256);
}
};
const TileMapAddressing = packed enum(u1) {
_9800 = 0,
_9C00 = 1,
};
pub const Vram = packed struct {
patterns: [3 * 128]RawPattern,
tile_maps: packed struct {
_9800: Matrix(u8, 32, 32), // $9800-9BFF
_9C00: Matrix(u8, 32, 32), // $9C00-9FFF
pub fn get(self: @This(), addressing: TileMapAddressing) Matrix(u8, 32, 32) {
return switch (addressing) {
._9800 => self._9800,
._9C00 => self._9C00,
};
}
},
};
pub const Video = struct {
buffers: [2]Matrix(Pixel, SCREEN_WIDTH, SCREEN_HEIGHT),
draw_index: u1,
clock: extern struct {
line: u32,
offset: u32,
},
cache: struct {
const CachedPattern = Matrix(Color, 8, 8);
const TilesCache = struct {
data: Matrix(Pixel, 256, 256),
dirty: bool,
fn run(self: *@This(), mmu: Fundude.Mmu, patternsData: []CachedPattern, tile_map_addr: TileMapAddressing) void {
if (!self.dirty) return;
self.dirty = false;
const tile_map = mmu.dyn.vram.tile_maps.get(tile_map_addr);
const tile_addressing = mmu.dyn.io.video.LCDC.bg_window_tile_data;
const palette = mmu.dyn.io.video.BGP.lookup();
// O(n^4)...
var i: u16 = 0;
while (i < tile_map.width) : (i += 1) {
var j: u16 = 0;
while (j < tile_map.height) : (j += 1) {
const idx = tile_addressing.translate(tile_map.get(i, j));
const pattern = patternsData[idx];
var x: usize = 0;
while (x < pattern.width) : (x += 1) {
const xbg = x + i * pattern.width;
var y: usize = 0;
while (y < pattern.height) : (y += 1) {
const ybg = y + j * pattern.height;
const color = pattern.get(x, y);
const shade = palette.get(color);
self.data.set(xbg, ybg, shade.asPixel());
}
}
}
}
}
};
patterns: struct {
data: [3 * 128]CachedPattern,
dirty: bool,
// TODO: this is pretty brutal
pub fn toMatrixSlice(self: *@This()) MatrixSlice(u8) {
return .{
.ptr = @ptrCast([*]u8, &self.data),
.width = CachedPattern.width,
.height = CachedPattern.height * self.data.len,
};
}
fn run(self: *@This(), mmu: Fundude.Mmu) void {
if (!self.dirty) return;
self.dirty = false;
for (mmu.dyn.vram.patterns) |raw_pattern, i| {
var patterns = &self.data[i];
var y: usize = 0;
while (y < patterns.height) : (y += 1) {
const line = raw_pattern._[y];
var x: usize = 0;
while (x < patterns.width) : (x += 1) {
const bit = @intCast(u4, patterns.width - x - 1);
const hi = @intCast(u2, line >> bit & 1);
const lo = @intCast(u2, line >> (bit + 8) & 1);
patterns.set(x, y, @intToEnum(Color, hi << 1 | lo));
}
}
}
}
},
sprites: struct {
const SpriteMeta = extern struct {
in_front: bool = true,
};
data: Matrix(Pixel, 256 + 2 * 8, 256 + 2 * 16),
meta: Matrix(SpriteMeta, 256 + 2 * 8, 256 + 2 * 16),
dirty: bool,
prev_oam: [40]SpriteAttr,
fn oamLessThan(context: void, lhs: SpriteAttr, rhs: SpriteAttr) bool {
return lhs.x_pos < rhs.x_pos;
}
fn run(self: *@This(), mmu: Fundude.Mmu, patternsData: []CachedPattern) void {
if (!self.dirty) return;
self.dirty = false;
const width = 8;
const height: usize = switch (mmu.dyn.io.video.LCDC.obj_size) {
.Small => 8,
.Large => 16,
};
for (self.prev_oam) |prev, i| {
const curr = mmu.dyn.oam[i];
if (@bitCast(u32, prev) == @bitCast(u32, curr)) continue;
var y: usize = 0;
while (y < height) : (y += 1) {
const ys = prev.y_pos + y;
const slice = self.data.sliceLine(prev.x_pos, ys);
std.mem.set(Pixel, slice[0..width], Shade.White.asPixel());
}
}
std.mem.copy(SpriteAttr, &self.prev_oam, &mmu.dyn.oam);
var sorted = mmu.dyn.oam;
std.sort.insertionSort(SpriteAttr, &sorted, {}, oamLessThan);
// Lower == higher priority, so we need to iterate backwards for painters algorithm
// TODO: ignore sprites > 10
std.mem.reverse(SpriteAttr, &sorted);
const obp0 = mmu.dyn.io.video.OBP0.lookup();
const obp1 = mmu.dyn.io.video.OBP1.lookup();
const mask: u8 = switch (mmu.dyn.io.video.LCDC.obj_size) {
.Small => 0xFF,
.Large => 0xFE,
};
for (sorted) |sprite_attr, i| {
const palette = switch (sprite_attr.flags.palette) {
.OBP0 => obp0,
.OBP1 => obp1,
};
var pattern = patternsData[sprite_attr.pattern & mask].toSlice();
// Large sprites are right next to each other in memory
// So we can simply expand this height
pattern.height = height;
var x: usize = 0;
while (x < pattern.width) : (x += 1) {
const xs = sprite_attr.x_pos +
if (sprite_attr.flags.x_flip) pattern.width - x - 1 else x;
var y: usize = 0;
while (y < pattern.height) : (y += 1) {
const ys = sprite_attr.y_pos +
if (sprite_attr.flags.y_flip) pattern.height - y - 1 else y;
const color = pattern.get(x, y);
if (color != ._0) {
const shade = palette.get(color);
self.data.set(xs, ys, shade.asOpaque());
self.meta.set(xs, ys, .{
// TODO: why was this redundant check here?
// .opaque = color != ._0,
.in_front = !sprite_attr.flags.priority,
});
}
}
}
}
}
},
background: TilesCache,
window: TilesCache,
},
pub fn screen(self: *Video) *Matrix(Pixel, SCREEN_WIDTH, SCREEN_HEIGHT) {
return &self.buffers[self.draw_index ^ 1];
}
pub fn reset(self: *Video) void {
self.buffers[0].reset(Shade.White.asPixel());
self.draw_index = 0;
self.clock.offset = 0;
self.clock.line = 0;
self.resetCache();
}
pub fn resetCache(self: *Video) void {
self.cache.sprites.dirty = true;
self.cache.sprites.data.reset(Shade.White.asPixel());
self.cache.patterns.dirty = true;
self.cache.window.dirty = true;
self.cache.background.dirty = true;
}
pub fn updatedVram(self: *Video, mmu: *Fundude.Mmu, addr: u16, val: u8) void {
self.cache.patterns.dirty = true;
self.cache.window.dirty = true;
self.cache.background.dirty = true;
if (addr < 0x9800) {
self.cache.sprites.dirty = true;
}
}
pub fn updatedOam(self: *Video, mmu: *Fundude.Mmu, addr: u16, val: u8) void {
self.cache.sprites.dirty = true;
}
pub fn updatedIo(self: *Video, mmu: *Fundude.Mmu, addr: u16, val: u8) void {
switch (addr) {
0xFF40, 0xFF47 => {
self.cache.window.dirty = true;
self.cache.background.dirty = true;
},
0xFF46, 0xFF48, 0xFF49 => {
self.cache.sprites.dirty = true;
},
else => {},
}
}
pub fn tick(self: *Video, mmu: *Fundude.Mmu, catchup: bool) void {
// FIXME: this isn't how DMA works
if (mmu.dyn.io.video.DMA != 0) {
const addr = @intCast(u16, mmu.dyn.io.video.DMA) << 8;
const oam = std.mem.asBytes(&mmu.dyn.oam);
std.mem.copy(u8, oam, std.mem.asBytes(&mmu.dyn)[addr..][0..oam.len]);
mmu.dyn.io.video.DMA = 0;
self.cache.sprites.dirty = true;
}
if (!mmu.dyn.io.video.LCDC.lcd_enable) {
if (self.clock.line != 0 or self.clock.offset != 0) {
mmu.dyn.io.video.STAT.mode = .hblank;
self.reset();
}
return;
}
self.clock.offset += 4;
// Manually wrapping this reduces overhead by ~20%
// compared to using division + modulus
if (self.clock.offset >= DOTS_PER_LINE) {
self.clock.offset -= DOTS_PER_LINE;
self.clock.line += 1;
if (self.clock.line >= RENDER_LINES) {
self.clock.line -= RENDER_LINES;
}
}
const line_num = self.clock.line;
const line_offset = self.clock.offset;
if (mmu.dyn.io.video.LY != line_num) {
mmu.dyn.io.video.LY = @intCast(u8, line_num);
mmu.dyn.io.video.STAT.coincidence = line_num == mmu.dyn.io.video.LYC;
if (mmu.dyn.io.video.STAT.irq_coincidence and mmu.dyn.io.video.STAT.coincidence) {
mmu.dyn.io.IF.lcd_stat = true;
}
}
const new_mode: LcdcMode = if (line_num >= SCREEN_HEIGHT)
.vblank
else
@as(LcdcMode, switch (line_offset) {
0...79 => .searching,
80...291 => .transferring,
else => .hblank,
});
if (mmu.dyn.io.video.STAT.mode == new_mode) {
return;
}
mmu.dyn.io.video.STAT.mode = new_mode;
switch (new_mode) {
.searching => {
// TODO: ready the pixel gun here
if (mmu.dyn.io.video.STAT.irq_oam) {
mmu.dyn.io.IF.lcd_stat = true;
}
},
.transferring => {
if (!catchup) {
@call(Fundude.profiling_call, self.render, .{ mmu.*, line_num });
}
},
.hblank => {
if (mmu.dyn.io.video.STAT.irq_hblank) {
mmu.dyn.io.IF.lcd_stat = true;
}
},
.vblank => {
self.draw_index ^= 1;
mmu.dyn.io.IF.vblank = true;
if (mmu.dyn.io.video.STAT.irq_vblank) {
mmu.dyn.io.IF.lcd_stat = true;
}
},
}
}
// TODO: audit this function
fn render(self: *Video, mmu: Fundude.Mmu, y: usize) void {
// TODO: Cache specific lines instead of doing it all at once
@call(Fundude.profiling_call, self.cache.patterns.run, .{mmu});
@call(Fundude.profiling_call, self.cache.sprites.run, .{ mmu, &self.cache.patterns.data });
@call(Fundude.profiling_call, self.cache.background.run, .{ mmu, &self.cache.patterns.data, mmu.dyn.io.video.LCDC.bg_tile_map });
@call(Fundude.profiling_call, self.cache.window.run, .{ mmu, &self.cache.patterns.data, mmu.dyn.io.video.LCDC.window_tile_map });
const line = self.buffers[self.draw_index].sliceLine(0, y);
if (mmu.dyn.io.video.LCDC.bg_enable) {
const xbg = mmu.dyn.io.video.SCX % self.cache.background.data.width;
const ybg = (mmu.dyn.io.video.SCY + y) % self.cache.background.data.height;
const bg_line = self.cache.background.data.sliceLine(0, ybg);
const bg_start = bg_line[xbg..];
const split_idx = std.math.min(bg_start.len, line.len);
std.mem.copy(Pixel, line, bg_start[0..split_idx]);
std.mem.copy(Pixel, line[split_idx..], bg_line[0 .. line.len - split_idx]);
} else {
std.mem.set(Pixel, line, Shade.White.asPixel());
}
if (mmu.dyn.io.video.LCDC.window_enable and y >= mmu.dyn.io.video.WY) {
const win_line = self.cache.window.data.sliceLine(0, y - mmu.dyn.io.video.WY);
if (mmu.dyn.io.video.WX < 7) {
// TODO: add hardware bugs
const xw = 7 - mmu.dyn.io.video.WX;
std.mem.copy(Pixel, line, win_line[xw..][0..line.len]);
} else {
const xw = mmu.dyn.io.video.WX - 7;
std.mem.copy(Pixel, line[xw..], win_line[0 .. line.len - xw]);
}
}
if (mmu.dyn.io.video.LCDC.obj_enable) {
const sprites = self.cache.sprites.data.sliceLine(8, y + 16)[0..SCREEN_WIDTH];
const metas = self.cache.sprites.meta.sliceLine(8, y + 16);
// TODO: use real vectors
for (std.mem.bytesAsSlice(u64, std.mem.sliceAsBytes(sprites))) |chunk, i| {
if (chunk == 0) continue;
for (@bitCast([4]Pixel, chunk)) |pixel, j| {
const x = 4 * i + j;
if (pixel.@"opaque" and (metas[x].in_front or !line[x].@"opaque")) {
line[x] = pixel;
}
}
}
}
}
};
|
src/video.zig
|
const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
const Tag = std.meta.Tag;
test "@tagName" {
try expect(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
comptime try expect(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
}
fn testEnumTagNameBare(n: anytype) []const u8 {
return @tagName(n);
}
const BareNumber = enum { One, Two, Three };
test "@tagName non-exhaustive enum" {
try expect(mem.eql(u8, testEnumTagNameBare(NonExhaustive.B), "B"));
comptime try expect(mem.eql(u8, testEnumTagNameBare(NonExhaustive.B), "B"));
}
const NonExhaustive = enum(u8) { A, B, _ };
test "@tagName is null-terminated" {
const S = struct {
fn doTheTest(n: BareNumber) !void {
try expect(@tagName(n)[3] == 0);
}
};
try S.doTheTest(.Two);
try comptime S.doTheTest(.Two);
}
test "tag name with assigned enum values" {
const LocalFoo = enum(u8) {
A = 1,
B = 0,
};
var b = LocalFoo.B;
try expect(mem.eql(u8, @tagName(b), "B"));
}
test "@tagName on enum literals" {
try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
comptime try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
}
const Bar = enum { A, B, C, D };
test "enum literal casting to optional" {
var bar: ?Bar = undefined;
bar = .B;
try expect(bar.? == Bar.B);
}
const A = enum(u3) { One, Two, Three, Four, One2, Two2, Three2, Four2 };
const B = enum(u3) { One3, Two3, Three3, Four3, One23, Two23, Three23, Four23 };
const C = enum(u2) { One4, Two4, Three4, Four4 };
const BitFieldOfEnums = packed struct {
a: A,
b: B,
c: C,
};
const bit_field_1 = BitFieldOfEnums{
.a = A.Two,
.b = B.Three3,
.c = C.Four4,
};
test "bit field access with enum fields" {
var data = bit_field_1;
try expect(getA(&data) == A.Two);
try expect(getB(&data) == B.Three3);
try expect(getC(&data) == C.Four4);
comptime try expect(@sizeOf(BitFieldOfEnums) == 1);
data.b = B.Four3;
try expect(data.b == B.Four3);
data.a = A.Three;
try expect(data.a == A.Three);
try expect(data.b == B.Four3);
}
fn getA(data: *const BitFieldOfEnums) A {
return data.a;
}
fn getB(data: *const BitFieldOfEnums) B {
return data.b;
}
fn getC(data: *const BitFieldOfEnums) C {
return data.c;
}
test "enum literal in array literal" {
const Items = enum { one, two };
const array = [_]Items{ .one, .two };
try expect(array[0] == .one);
try expect(array[1] == .two);
}
|
test/behavior/enum_llvm.zig
|
const std = @import("../std.zig");
const mem = std.mem;
const math = std.math;
const RoundParam = struct {
a: usize,
b: usize,
c: usize,
d: usize,
e: usize,
i: u32,
};
fn roundParam(a: usize, b: usize, c: usize, d: usize, e: usize, i: u32) RoundParam {
return RoundParam{
.a = a,
.b = b,
.c = c,
.d = d,
.e = e,
.i = i,
};
}
/// The SHA-1 function is now considered cryptographically broken.
/// Namely, it is feasible to find multiple inputs producing the same hash.
/// For a fast-performing, cryptographically secure hash function, see SHA512/256, BLAKE2 or BLAKE3.
pub const Sha1 = struct {
const Self = @This();
pub const block_length = 64;
pub const digest_length = 20;
pub const Options = struct {};
s: [5]u32,
// Streaming Cache
buf: [64]u8 = undefined,
buf_len: u8 = 0,
total_len: u64 = 0,
pub fn init(options: Options) Self {
return Self{
.s = [_]u32{
0x67452301,
0xEFCDAB89,
0x98BADCFE,
0x10325476,
0xC3D2E1F0,
},
};
}
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
var d = Sha1.init(options);
d.update(b);
d.final(out);
}
pub fn update(d: *Self, b: []const u8) void {
var off: usize = 0;
// Partial buffer exists from previous update. Copy into buffer then hash.
if (d.buf_len != 0 and d.buf_len + b.len >= 64) {
off += 64 - d.buf_len;
mem.copy(u8, d.buf[d.buf_len..], b[0..off]);
d.round(d.buf[0..]);
d.buf_len = 0;
}
// Full middle blocks.
while (off + 64 <= b.len) : (off += 64) {
d.round(b[off..][0..64]);
}
// Copy any remainder for next pass.
mem.copy(u8, d.buf[d.buf_len..], b[off..]);
d.buf_len += @intCast(u8, b[off..].len);
d.total_len += b.len;
}
pub fn final(d: *Self, out: *[digest_length]u8) void {
// The buffer here will never be completely full.
mem.set(u8, d.buf[d.buf_len..], 0);
// Append padding bits.
d.buf[d.buf_len] = 0x80;
d.buf_len += 1;
// > 448 mod 512 so need to add an extra round to wrap around.
if (64 - d.buf_len < 8) {
d.round(d.buf[0..]);
mem.set(u8, d.buf[0..], 0);
}
// Append message length.
var i: usize = 1;
var len = d.total_len >> 5;
d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3;
while (i < 8) : (i += 1) {
d.buf[63 - i] = @intCast(u8, len & 0xff);
len >>= 8;
}
d.round(d.buf[0..]);
for (d.s) |s, j| {
mem.writeIntBig(u32, out[4 * j ..][0..4], s);
}
}
fn round(d: *Self, b: *const [64]u8) void {
var s: [16]u32 = undefined;
var v: [5]u32 = [_]u32{
d.s[0],
d.s[1],
d.s[2],
d.s[3],
d.s[4],
};
const round0a = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 0),
roundParam(4, 0, 1, 2, 3, 1),
roundParam(3, 4, 0, 1, 2, 2),
roundParam(2, 3, 4, 0, 1, 3),
roundParam(1, 2, 3, 4, 0, 4),
roundParam(0, 1, 2, 3, 4, 5),
roundParam(4, 0, 1, 2, 3, 6),
roundParam(3, 4, 0, 1, 2, 7),
roundParam(2, 3, 4, 0, 1, 8),
roundParam(1, 2, 3, 4, 0, 9),
roundParam(0, 1, 2, 3, 4, 10),
roundParam(4, 0, 1, 2, 3, 11),
roundParam(3, 4, 0, 1, 2, 12),
roundParam(2, 3, 4, 0, 1, 13),
roundParam(1, 2, 3, 4, 0, 14),
roundParam(0, 1, 2, 3, 4, 15),
};
inline for (round0a) |r| {
s[r.i] = (@as(u32, b[r.i * 4 + 0]) << 24) | (@as(u32, b[r.i * 4 + 1]) << 16) | (@as(u32, b[r.i * 4 + 2]) << 8) | (@as(u32, b[r.i * 4 + 3]) << 0);
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round0b = comptime [_]RoundParam{
roundParam(4, 0, 1, 2, 3, 16),
roundParam(3, 4, 0, 1, 2, 17),
roundParam(2, 3, 4, 0, 1, 18),
roundParam(1, 2, 3, 4, 0, 19),
};
inline for (round0b) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round1 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 20),
roundParam(4, 0, 1, 2, 3, 21),
roundParam(3, 4, 0, 1, 2, 22),
roundParam(2, 3, 4, 0, 1, 23),
roundParam(1, 2, 3, 4, 0, 24),
roundParam(0, 1, 2, 3, 4, 25),
roundParam(4, 0, 1, 2, 3, 26),
roundParam(3, 4, 0, 1, 2, 27),
roundParam(2, 3, 4, 0, 1, 28),
roundParam(1, 2, 3, 4, 0, 29),
roundParam(0, 1, 2, 3, 4, 30),
roundParam(4, 0, 1, 2, 3, 31),
roundParam(3, 4, 0, 1, 2, 32),
roundParam(2, 3, 4, 0, 1, 33),
roundParam(1, 2, 3, 4, 0, 34),
roundParam(0, 1, 2, 3, 4, 35),
roundParam(4, 0, 1, 2, 3, 36),
roundParam(3, 4, 0, 1, 2, 37),
roundParam(2, 3, 4, 0, 1, 38),
roundParam(1, 2, 3, 4, 0, 39),
};
inline for (round1) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round2 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 40),
roundParam(4, 0, 1, 2, 3, 41),
roundParam(3, 4, 0, 1, 2, 42),
roundParam(2, 3, 4, 0, 1, 43),
roundParam(1, 2, 3, 4, 0, 44),
roundParam(0, 1, 2, 3, 4, 45),
roundParam(4, 0, 1, 2, 3, 46),
roundParam(3, 4, 0, 1, 2, 47),
roundParam(2, 3, 4, 0, 1, 48),
roundParam(1, 2, 3, 4, 0, 49),
roundParam(0, 1, 2, 3, 4, 50),
roundParam(4, 0, 1, 2, 3, 51),
roundParam(3, 4, 0, 1, 2, 52),
roundParam(2, 3, 4, 0, 1, 53),
roundParam(1, 2, 3, 4, 0, 54),
roundParam(0, 1, 2, 3, 4, 55),
roundParam(4, 0, 1, 2, 3, 56),
roundParam(3, 4, 0, 1, 2, 57),
roundParam(2, 3, 4, 0, 1, 58),
roundParam(1, 2, 3, 4, 0, 59),
};
inline for (round2) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x8F1BBCDC +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d]));
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round3 = comptime [_]RoundParam{
roundParam(0, 1, 2, 3, 4, 60),
roundParam(4, 0, 1, 2, 3, 61),
roundParam(3, 4, 0, 1, 2, 62),
roundParam(2, 3, 4, 0, 1, 63),
roundParam(1, 2, 3, 4, 0, 64),
roundParam(0, 1, 2, 3, 4, 65),
roundParam(4, 0, 1, 2, 3, 66),
roundParam(3, 4, 0, 1, 2, 67),
roundParam(2, 3, 4, 0, 1, 68),
roundParam(1, 2, 3, 4, 0, 69),
roundParam(0, 1, 2, 3, 4, 70),
roundParam(4, 0, 1, 2, 3, 71),
roundParam(3, 4, 0, 1, 2, 72),
roundParam(2, 3, 4, 0, 1, 73),
roundParam(1, 2, 3, 4, 0, 74),
roundParam(0, 1, 2, 3, 4, 75),
roundParam(4, 0, 1, 2, 3, 76),
roundParam(3, 4, 0, 1, 2, 77),
roundParam(2, 3, 4, 0, 1, 78),
roundParam(1, 2, 3, 4, 0, 79),
};
inline for (round3) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0xCA62C1D6 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
d.s[0] +%= v[0];
d.s[1] +%= v[1];
d.s[2] +%= v[2];
d.s[3] +%= v[3];
d.s[4] +%= v[4];
}
};
const htest = @import("test.zig");
test "sha1 single" {
htest.assertEqualHash(Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709", "");
htest.assertEqualHash(Sha1, "a9993e364706816aba3e25717850c26c9cd0d89d", "abc");
htest.assertEqualHash(Sha1, "a49b2446a02c645bf419f995b67091253a04a259", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha1 streaming" {
var h = Sha1.init(.{});
var out: [20]u8 = undefined;
h.final(&out);
htest.assertEqual("da39a3ee5e6b4b0d3255bfef95601890afd80709", out[0..]);
h = Sha1.init(.{});
h.update("abc");
h.final(&out);
htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
h = Sha1.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(&out);
htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
}
test "sha1 aligned final" {
var block = [_]u8{0} ** Sha1.block_length;
var out: [Sha1.digest_length]u8 = undefined;
var h = Sha1.init(.{});
h.update(&block);
h.final(out[0..]);
}
|
lib/std/crypto/sha1.zig
|
const std = @import("std");
const Builder = std.build.Builder;
const builtin = std.builtin;
const CrossTarget = std.zig.CrossTarget;
const debug = std.debug;
const LibExeObjStep = std.build.LibExeObjStep;
const NativePaths = std.zig.system.NativePaths;
const Target = std.Target;
const global = @import("src/global.zig");
pub fn build(b: *Builder) anyerror!void {
b.setPreferredReleaseMode(.ReleaseFast);
const main_exe = b.addExecutable(global.name, "src/main.zig");
main_exe.setBuildMode(b.standardReleaseOptions());
main_exe.force_pic = true;
main_exe.addPackagePath("thirdparty/clap", "lib/zig-clap/clap.zig");
main_exe.linkLibC();
main_exe.linkSystemLibrary("argon2");
if (main_exe.is_linking_libc) {
switch (Target.current.os.tag) {
.linux => {
const use_glibc = b.option(bool, "use-glibc", "use glibc as standard c library (linux only)") orelse false;
const use_musl = b.option(bool, "use-musl", "use musl as standard c library (linux only)") orelse false;
const cross_abi = abi: {
if (use_glibc and !use_musl)
break :abi Target.Abi.gnu
else if (use_musl and !use_glibc)
break :abi Target.Abi.musl
else if (!use_glibc and !use_musl)
break :abi Target.current.abi
else {
debug.warn("Multiple libc modes (of -Duse-glibc and -Duse-musl)", .{});
b.invalid_user_input = true;
break :abi Target.current.abi;
}
};
main_exe.setTarget(CrossTarget.fromTarget(Target{
.cpu = Target.current.cpu,
.os = Target.current.os,
.abi = cross_abi,
}));
// Workaround for zig 0.6.0 nightly, or else the compiler will complain about
// "explicit_bzero" being unreferenced.
var native_paths = try NativePaths.detect(b.allocator);
defer native_paths.deinit();
for (native_paths.include_dirs.items) |include_dir|
main_exe.addIncludeDir(include_dir);
for (native_paths.lib_dirs.items) |lib_dir|
main_exe.addLibPath(lib_dir);
},
else => {},
}
}
switch (main_exe.build_mode) {
.ReleaseFast, .ReleaseSmall => {
main_exe.strip = true;
main_exe.single_threaded = true;
//main_exe.is_dynamic = false;
main_exe.rdynamic = false;
},
else => {},
}
main_exe.install();
b.getInstallStep().dependOn(&main_exe.step);
}
|
build.zig
|
const std = @import("std");
const mem = std.mem;
const Emoji = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 35,
hi: u21 = 129750,
pub fn init(allocator: *mem.Allocator) !Emoji {
var instance = Emoji{
.allocator = allocator,
.array = try allocator.alloc(bool, 129716),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[7] = true;
index = 13;
while (index <= 22) : (index += 1) {
instance.array[index] = true;
}
instance.array[134] = true;
instance.array[139] = true;
instance.array[8217] = true;
instance.array[8230] = true;
instance.array[8447] = true;
instance.array[8470] = true;
index = 8561;
while (index <= 8566) : (index += 1) {
instance.array[index] = true;
}
index = 8582;
while (index <= 8583) : (index += 1) {
instance.array[index] = true;
}
index = 8951;
while (index <= 8952) : (index += 1) {
instance.array[index] = true;
}
instance.array[8965] = true;
instance.array[9132] = true;
index = 9158;
while (index <= 9161) : (index += 1) {
instance.array[index] = true;
}
index = 9162;
while (index <= 9163) : (index += 1) {
instance.array[index] = true;
}
instance.array[9164] = true;
instance.array[9165] = true;
index = 9166;
while (index <= 9167) : (index += 1) {
instance.array[index] = true;
}
instance.array[9168] = true;
index = 9173;
while (index <= 9175) : (index += 1) {
instance.array[index] = true;
}
instance.array[9375] = true;
index = 9607;
while (index <= 9608) : (index += 1) {
instance.array[index] = true;
}
instance.array[9619] = true;
instance.array[9629] = true;
index = 9688;
while (index <= 9691) : (index += 1) {
instance.array[index] = true;
}
index = 9693;
while (index <= 9694) : (index += 1) {
instance.array[index] = true;
}
index = 9695;
while (index <= 9696) : (index += 1) {
instance.array[index] = true;
}
instance.array[9697] = true;
instance.array[9707] = true;
instance.array[9710] = true;
index = 9713;
while (index <= 9714) : (index += 1) {
instance.array[index] = true;
}
instance.array[9717] = true;
instance.array[9722] = true;
instance.array[9725] = true;
index = 9727;
while (index <= 9728) : (index += 1) {
instance.array[index] = true;
}
instance.array[9731] = true;
instance.array[9735] = true;
instance.array[9739] = true;
instance.array[9740] = true;
index = 9749;
while (index <= 9750) : (index += 1) {
instance.array[index] = true;
}
instance.array[9751] = true;
instance.array[9757] = true;
instance.array[9759] = true;
index = 9765;
while (index <= 9776) : (index += 1) {
instance.array[index] = true;
}
instance.array[9788] = true;
instance.array[9789] = true;
instance.array[9792] = true;
index = 9794;
while (index <= 9795) : (index += 1) {
instance.array[index] = true;
}
instance.array[9797] = true;
instance.array[9816] = true;
instance.array[9819] = true;
instance.array[9820] = true;
instance.array[9839] = true;
instance.array[9840] = true;
instance.array[9841] = true;
instance.array[9842] = true;
index = 9843;
while (index <= 9844) : (index += 1) {
instance.array[index] = true;
}
instance.array[9846] = true;
index = 9848;
while (index <= 9849) : (index += 1) {
instance.array[index] = true;
}
index = 9853;
while (index <= 9854) : (index += 1) {
instance.array[index] = true;
}
instance.array[9860] = true;
index = 9863;
while (index <= 9864) : (index += 1) {
instance.array[index] = true;
}
index = 9869;
while (index <= 9870) : (index += 1) {
instance.array[index] = true;
}
index = 9882;
while (index <= 9883) : (index += 1) {
instance.array[index] = true;
}
index = 9889;
while (index <= 9890) : (index += 1) {
instance.array[index] = true;
}
instance.array[9893] = true;
instance.array[9899] = true;
instance.array[9900] = true;
instance.array[9902] = true;
instance.array[9904] = true;
instance.array[9905] = true;
instance.array[9926] = true;
instance.array[9927] = true;
index = 9933;
while (index <= 9934) : (index += 1) {
instance.array[index] = true;
}
index = 9935;
while (index <= 9936) : (index += 1) {
instance.array[index] = true;
}
instance.array[9937] = true;
instance.array[9938] = true;
index = 9940;
while (index <= 9942) : (index += 1) {
instance.array[index] = true;
}
instance.array[9943] = true;
instance.array[9946] = true;
instance.array[9951] = true;
instance.array[9954] = true;
index = 9957;
while (index <= 9961) : (index += 1) {
instance.array[index] = true;
}
instance.array[9962] = true;
instance.array[9964] = true;
instance.array[9967] = true;
instance.array[9969] = true;
instance.array[9971] = true;
instance.array[9978] = true;
instance.array[9982] = true;
instance.array[9989] = true;
index = 10000;
while (index <= 10001) : (index += 1) {
instance.array[index] = true;
}
instance.array[10017] = true;
instance.array[10020] = true;
instance.array[10025] = true;
instance.array[10027] = true;
index = 10032;
while (index <= 10034) : (index += 1) {
instance.array[index] = true;
}
instance.array[10036] = true;
instance.array[10048] = true;
instance.array[10049] = true;
index = 10098;
while (index <= 10100) : (index += 1) {
instance.array[index] = true;
}
instance.array[10110] = true;
instance.array[10125] = true;
instance.array[10140] = true;
index = 10513;
while (index <= 10514) : (index += 1) {
instance.array[index] = true;
}
index = 10978;
while (index <= 10980) : (index += 1) {
instance.array[index] = true;
}
index = 11000;
while (index <= 11001) : (index += 1) {
instance.array[index] = true;
}
instance.array[11053] = true;
instance.array[11058] = true;
instance.array[12301] = true;
instance.array[12314] = true;
instance.array[12916] = true;
instance.array[12918] = true;
instance.array[126945] = true;
instance.array[127148] = true;
index = 127309;
while (index <= 127310) : (index += 1) {
instance.array[index] = true;
}
index = 127323;
while (index <= 127324) : (index += 1) {
instance.array[index] = true;
}
instance.array[127339] = true;
index = 127342;
while (index <= 127351) : (index += 1) {
instance.array[index] = true;
}
index = 127427;
while (index <= 127452) : (index += 1) {
instance.array[index] = true;
}
index = 127454;
while (index <= 127455) : (index += 1) {
instance.array[index] = true;
}
instance.array[127479] = true;
instance.array[127500] = true;
index = 127503;
while (index <= 127511) : (index += 1) {
instance.array[index] = true;
}
index = 127533;
while (index <= 127534) : (index += 1) {
instance.array[index] = true;
}
index = 127709;
while (index <= 127721) : (index += 1) {
instance.array[index] = true;
}
index = 127722;
while (index <= 127723) : (index += 1) {
instance.array[index] = true;
}
instance.array[127724] = true;
instance.array[127725] = true;
instance.array[127726] = true;
instance.array[127727] = true;
index = 127728;
while (index <= 127730) : (index += 1) {
instance.array[index] = true;
}
index = 127731;
while (index <= 127733) : (index += 1) {
instance.array[index] = true;
}
instance.array[127734] = true;
instance.array[127735] = true;
instance.array[127736] = true;
instance.array[127737] = true;
index = 127738;
while (index <= 127739) : (index += 1) {
instance.array[index] = true;
}
index = 127740;
while (index <= 127741) : (index += 1) {
instance.array[index] = true;
}
instance.array[127742] = true;
index = 127745;
while (index <= 127753) : (index += 1) {
instance.array[index] = true;
}
index = 127754;
while (index <= 127756) : (index += 1) {
instance.array[index] = true;
}
index = 127757;
while (index <= 127758) : (index += 1) {
instance.array[index] = true;
}
index = 127759;
while (index <= 127760) : (index += 1) {
instance.array[index] = true;
}
index = 127761;
while (index <= 127762) : (index += 1) {
instance.array[index] = true;
}
instance.array[127763] = true;
index = 127764;
while (index <= 127783) : (index += 1) {
instance.array[index] = true;
}
instance.array[127784] = true;
index = 127785;
while (index <= 127788) : (index += 1) {
instance.array[index] = true;
}
instance.array[127789] = true;
index = 127790;
while (index <= 127832) : (index += 1) {
instance.array[index] = true;
}
instance.array[127833] = true;
instance.array[127834] = true;
index = 127835;
while (index <= 127836) : (index += 1) {
instance.array[index] = true;
}
index = 127837;
while (index <= 127856) : (index += 1) {
instance.array[index] = true;
}
index = 127859;
while (index <= 127860) : (index += 1) {
instance.array[index] = true;
}
index = 127862;
while (index <= 127864) : (index += 1) {
instance.array[index] = true;
}
index = 127867;
while (index <= 127868) : (index += 1) {
instance.array[index] = true;
}
index = 127869;
while (index <= 127905) : (index += 1) {
instance.array[index] = true;
}
instance.array[127906] = true;
instance.array[127907] = true;
instance.array[127908] = true;
instance.array[127909] = true;
instance.array[127910] = true;
instance.array[127911] = true;
index = 127912;
while (index <= 127915) : (index += 1) {
instance.array[index] = true;
}
index = 127916;
while (index <= 127920) : (index += 1) {
instance.array[index] = true;
}
index = 127921;
while (index <= 127932) : (index += 1) {
instance.array[index] = true;
}
index = 127933;
while (index <= 127936) : (index += 1) {
instance.array[index] = true;
}
instance.array[127937] = true;
index = 127938;
while (index <= 127949) : (index += 1) {
instance.array[index] = true;
}
instance.array[127952] = true;
instance.array[127953] = true;
instance.array[127954] = true;
instance.array[127956] = true;
index = 127957;
while (index <= 127972) : (index += 1) {
instance.array[index] = true;
}
instance.array[127973] = true;
index = 127974;
while (index <= 127976) : (index += 1) {
instance.array[index] = true;
}
index = 127977;
while (index <= 127979) : (index += 1) {
instance.array[index] = true;
}
index = 127980;
while (index <= 127981) : (index += 1) {
instance.array[index] = true;
}
index = 127982;
while (index <= 127983) : (index += 1) {
instance.array[index] = true;
}
instance.array[127984] = true;
instance.array[127985] = true;
instance.array[127986] = true;
instance.array[127987] = true;
index = 127988;
while (index <= 128006) : (index += 1) {
instance.array[index] = true;
}
instance.array[128007] = true;
index = 128008;
while (index <= 128027) : (index += 1) {
instance.array[index] = true;
}
instance.array[128028] = true;
instance.array[128029] = true;
instance.array[128030] = true;
index = 128031;
while (index <= 128065) : (index += 1) {
instance.array[index] = true;
}
instance.array[128066] = true;
index = 128067;
while (index <= 128072) : (index += 1) {
instance.array[index] = true;
}
index = 128073;
while (index <= 128074) : (index += 1) {
instance.array[index] = true;
}
index = 128075;
while (index <= 128137) : (index += 1) {
instance.array[index] = true;
}
instance.array[128138] = true;
index = 128139;
while (index <= 128146) : (index += 1) {
instance.array[index] = true;
}
index = 128147;
while (index <= 128148) : (index += 1) {
instance.array[index] = true;
}
index = 128149;
while (index <= 128200) : (index += 1) {
instance.array[index] = true;
}
index = 128201;
while (index <= 128202) : (index += 1) {
instance.array[index] = true;
}
instance.array[128203] = true;
instance.array[128204] = true;
index = 128205;
while (index <= 128209) : (index += 1) {
instance.array[index] = true;
}
instance.array[128210] = true;
index = 128211;
while (index <= 128212) : (index += 1) {
instance.array[index] = true;
}
instance.array[128213] = true;
index = 128214;
while (index <= 128217) : (index += 1) {
instance.array[index] = true;
}
instance.array[128218] = true;
index = 128220;
while (index <= 128223) : (index += 1) {
instance.array[index] = true;
}
instance.array[128224] = true;
index = 128225;
while (index <= 128228) : (index += 1) {
instance.array[index] = true;
}
instance.array[128229] = true;
instance.array[128230] = true;
index = 128231;
while (index <= 128241) : (index += 1) {
instance.array[index] = true;
}
instance.array[128242] = true;
index = 128243;
while (index <= 128264) : (index += 1) {
instance.array[index] = true;
}
index = 128265;
while (index <= 128266) : (index += 1) {
instance.array[index] = true;
}
index = 128267;
while (index <= 128282) : (index += 1) {
instance.array[index] = true;
}
index = 128294;
while (index <= 128295) : (index += 1) {
instance.array[index] = true;
}
index = 128296;
while (index <= 128299) : (index += 1) {
instance.array[index] = true;
}
index = 128301;
while (index <= 128312) : (index += 1) {
instance.array[index] = true;
}
index = 128313;
while (index <= 128324) : (index += 1) {
instance.array[index] = true;
}
index = 128332;
while (index <= 128333) : (index += 1) {
instance.array[index] = true;
}
index = 128336;
while (index <= 128342) : (index += 1) {
instance.array[index] = true;
}
instance.array[128343] = true;
instance.array[128356] = true;
index = 128359;
while (index <= 128362) : (index += 1) {
instance.array[index] = true;
}
instance.array[128365] = true;
index = 128370;
while (index <= 128371) : (index += 1) {
instance.array[index] = true;
}
instance.array[128385] = true;
instance.array[128386] = true;
instance.array[128389] = true;
index = 128398;
while (index <= 128399) : (index += 1) {
instance.array[index] = true;
}
instance.array[128409] = true;
index = 128415;
while (index <= 128417) : (index += 1) {
instance.array[index] = true;
}
index = 128430;
while (index <= 128432) : (index += 1) {
instance.array[index] = true;
}
index = 128441;
while (index <= 128443) : (index += 1) {
instance.array[index] = true;
}
instance.array[128446] = true;
instance.array[128448] = true;
instance.array[128453] = true;
instance.array[128460] = true;
instance.array[128464] = true;
instance.array[128471] = true;
index = 128472;
while (index <= 128476) : (index += 1) {
instance.array[index] = true;
}
instance.array[128477] = true;
index = 128478;
while (index <= 128483) : (index += 1) {
instance.array[index] = true;
}
index = 128484;
while (index <= 128485) : (index += 1) {
instance.array[index] = true;
}
index = 128486;
while (index <= 128490) : (index += 1) {
instance.array[index] = true;
}
instance.array[128491] = true;
instance.array[128492] = true;
instance.array[128493] = true;
instance.array[128494] = true;
index = 128495;
while (index <= 128497) : (index += 1) {
instance.array[index] = true;
}
instance.array[128498] = true;
instance.array[128499] = true;
instance.array[128500] = true;
instance.array[128501] = true;
instance.array[128502] = true;
instance.array[128503] = true;
instance.array[128504] = true;
index = 128505;
while (index <= 128507) : (index += 1) {
instance.array[index] = true;
}
instance.array[128508] = true;
index = 128509;
while (index <= 128514) : (index += 1) {
instance.array[index] = true;
}
index = 128515;
while (index <= 128516) : (index += 1) {
instance.array[index] = true;
}
index = 128517;
while (index <= 128520) : (index += 1) {
instance.array[index] = true;
}
instance.array[128521] = true;
instance.array[128522] = true;
index = 128523;
while (index <= 128524) : (index += 1) {
instance.array[index] = true;
}
index = 128525;
while (index <= 128528) : (index += 1) {
instance.array[index] = true;
}
instance.array[128529] = true;
instance.array[128530] = true;
instance.array[128531] = true;
index = 128532;
while (index <= 128541) : (index += 1) {
instance.array[index] = true;
}
index = 128542;
while (index <= 128545) : (index += 1) {
instance.array[index] = true;
}
index = 128546;
while (index <= 128556) : (index += 1) {
instance.array[index] = true;
}
instance.array[128605] = true;
index = 128606;
while (index <= 128607) : (index += 1) {
instance.array[index] = true;
}
index = 128608;
while (index <= 128610) : (index += 1) {
instance.array[index] = true;
}
instance.array[128611] = true;
instance.array[128612] = true;
instance.array[128613] = true;
instance.array[128614] = true;
index = 128615;
while (index <= 128616) : (index += 1) {
instance.array[index] = true;
}
instance.array[128617] = true;
instance.array[128618] = true;
instance.array[128619] = true;
instance.array[128620] = true;
instance.array[128621] = true;
index = 128622;
while (index <= 128624) : (index += 1) {
instance.array[index] = true;
}
instance.array[128625] = true;
instance.array[128626] = true;
instance.array[128627] = true;
instance.array[128628] = true;
instance.array[128629] = true;
index = 128630;
while (index <= 128631) : (index += 1) {
instance.array[index] = true;
}
index = 128632;
while (index <= 128638) : (index += 1) {
instance.array[index] = true;
}
instance.array[128639] = true;
instance.array[128640] = true;
index = 128641;
while (index <= 128642) : (index += 1) {
instance.array[index] = true;
}
instance.array[128643] = true;
index = 128644;
while (index <= 128650) : (index += 1) {
instance.array[index] = true;
}
index = 128651;
while (index <= 128654) : (index += 1) {
instance.array[index] = true;
}
instance.array[128655] = true;
index = 128656;
while (index <= 128658) : (index += 1) {
instance.array[index] = true;
}
instance.array[128659] = true;
index = 128660;
while (index <= 128661) : (index += 1) {
instance.array[index] = true;
}
index = 128662;
while (index <= 128667) : (index += 1) {
instance.array[index] = true;
}
instance.array[128668] = true;
instance.array[128669] = true;
index = 128670;
while (index <= 128674) : (index += 1) {
instance.array[index] = true;
}
instance.array[128680] = true;
instance.array[128681] = true;
index = 128682;
while (index <= 128684) : (index += 1) {
instance.array[index] = true;
}
instance.array[128685] = true;
index = 128686;
while (index <= 128687) : (index += 1) {
instance.array[index] = true;
}
instance.array[128690] = true;
index = 128691;
while (index <= 128692) : (index += 1) {
instance.array[index] = true;
}
index = 128701;
while (index <= 128706) : (index += 1) {
instance.array[index] = true;
}
instance.array[128710] = true;
index = 128712;
while (index <= 128713) : (index += 1) {
instance.array[index] = true;
}
instance.array[128717] = true;
instance.array[128720] = true;
index = 128721;
while (index <= 128723) : (index += 1) {
instance.array[index] = true;
}
index = 128724;
while (index <= 128725) : (index += 1) {
instance.array[index] = true;
}
instance.array[128726] = true;
instance.array[128727] = true;
index = 128728;
while (index <= 128729) : (index += 1) {
instance.array[index] = true;
}
index = 128957;
while (index <= 128968) : (index += 1) {
instance.array[index] = true;
}
instance.array[129257] = true;
index = 129258;
while (index <= 129260) : (index += 1) {
instance.array[index] = true;
}
index = 129261;
while (index <= 129269) : (index += 1) {
instance.array[index] = true;
}
index = 129270;
while (index <= 129275) : (index += 1) {
instance.array[index] = true;
}
instance.array[129276] = true;
index = 129277;
while (index <= 129284) : (index += 1) {
instance.array[index] = true;
}
index = 129285;
while (index <= 129292) : (index += 1) {
instance.array[index] = true;
}
instance.array[129293] = true;
index = 129294;
while (index <= 129295) : (index += 1) {
instance.array[index] = true;
}
index = 129296;
while (index <= 129303) : (index += 1) {
instance.array[index] = true;
}
index = 129305;
while (index <= 129307) : (index += 1) {
instance.array[index] = true;
}
instance.array[129308] = true;
index = 129309;
while (index <= 129314) : (index += 1) {
instance.array[index] = true;
}
index = 129316;
while (index <= 129320) : (index += 1) {
instance.array[index] = true;
}
instance.array[129321] = true;
index = 129322;
while (index <= 129324) : (index += 1) {
instance.array[index] = true;
}
index = 129325;
while (index <= 129339) : (index += 1) {
instance.array[index] = true;
}
index = 129340;
while (index <= 129352) : (index += 1) {
instance.array[index] = true;
}
index = 129353;
while (index <= 129357) : (index += 1) {
instance.array[index] = true;
}
instance.array[129358] = true;
instance.array[129359] = true;
index = 129360;
while (index <= 129363) : (index += 1) {
instance.array[index] = true;
}
index = 129364;
while (index <= 129365) : (index += 1) {
instance.array[index] = true;
}
instance.array[129367] = true;
instance.array[129368] = true;
index = 129369;
while (index <= 129372) : (index += 1) {
instance.array[index] = true;
}
index = 129373;
while (index <= 129377) : (index += 1) {
instance.array[index] = true;
}
index = 129378;
while (index <= 129390) : (index += 1) {
instance.array[index] = true;
}
index = 129391;
while (index <= 129396) : (index += 1) {
instance.array[index] = true;
}
index = 129397;
while (index <= 129407) : (index += 1) {
instance.array[index] = true;
}
index = 129408;
while (index <= 129409) : (index += 1) {
instance.array[index] = true;
}
index = 129410;
while (index <= 129415) : (index += 1) {
instance.array[index] = true;
}
index = 129416;
while (index <= 129418) : (index += 1) {
instance.array[index] = true;
}
index = 129419;
while (index <= 129420) : (index += 1) {
instance.array[index] = true;
}
index = 129421;
while (index <= 129430) : (index += 1) {
instance.array[index] = true;
}
index = 129431;
while (index <= 129436) : (index += 1) {
instance.array[index] = true;
}
instance.array[129437] = true;
index = 129438;
while (index <= 129439) : (index += 1) {
instance.array[index] = true;
}
index = 129440;
while (index <= 129447) : (index += 1) {
instance.array[index] = true;
}
instance.array[129448] = true;
index = 129450;
while (index <= 129452) : (index += 1) {
instance.array[index] = true;
}
index = 129453;
while (index <= 129475) : (index += 1) {
instance.array[index] = true;
}
index = 129476;
while (index <= 129500) : (index += 1) {
instance.array[index] = true;
}
index = 129613;
while (index <= 129616) : (index += 1) {
instance.array[index] = true;
}
instance.array[129617] = true;
index = 129621;
while (index <= 129623) : (index += 1) {
instance.array[index] = true;
}
index = 129629;
while (index <= 129631) : (index += 1) {
instance.array[index] = true;
}
index = 129632;
while (index <= 129635) : (index += 1) {
instance.array[index] = true;
}
index = 129645;
while (index <= 129650) : (index += 1) {
instance.array[index] = true;
}
index = 129651;
while (index <= 129669) : (index += 1) {
instance.array[index] = true;
}
index = 129677;
while (index <= 129683) : (index += 1) {
instance.array[index] = true;
}
index = 129693;
while (index <= 129695) : (index += 1) {
instance.array[index] = true;
}
index = 129709;
while (index <= 129715) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *Emoji) void {
self.allocator.free(self.array);
}
// isEmoji checks if cp is of the kind Emoji.
pub fn isEmoji(self: Emoji, 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/emoji-data/Emoji.zig
|
const std = @import("std");
const mem = std.mem;
const unicode = std.unicode;
const ascii = @import("ascii.zig");
pub const Context = @import("Context.zig");
pub const Letter = @import("components/aggregate/Letter.zig");
pub const Mark = @import("components/aggregate/Mark.zig");
pub const Number = @import("components/aggregate/Number.zig");
pub const Punct = @import("components/aggregate/Punct.zig");
pub const Space = @import("components/aggregate/Space.zig");
pub const Symbol = @import("components/aggregate/Symbol.zig");
/// Zigstr is a UTF-8 string type.
pub const Zigstr = @import("zigstr/Zigstr.zig");
pub const GraphemeIterator = Zigstr.GraphemeIterator;
/// Ziglyph consolidates frequently-used Unicode utility functions in one place.
pub const Ziglyph = struct {
context: *Context,
letter: Letter,
mark: Mark,
number: Number,
punct: Punct,
symbol: Symbol,
space: Space,
const Self = @This();
pub fn new(ctx: *Context) !Self {
return Self{
.context = ctx,
.letter = Letter.new(ctx),
.mark = Mark.new(ctx),
.number = Number.new(ctx),
.punct = Punct.new(ctx),
.symbol = Symbol.new(ctx),
.space = Space.new(ctx),
};
}
pub fn isAlphabetic(self: Self, cp: u21) !bool {
const alphabetic = try self.context.getAlphabetic();
return alphabetic.isAlphabetic(cp);
}
pub fn isAsciiAlphabetic(cp: u21) bool {
return if (cp < 128) ascii.isAlpha(@intCast(u8, cp)) else false;
}
pub fn isAlphaNum(self: Self, cp: u21) !bool {
return (try self.isAlphabetic(cp)) or (try self.isNumber(cp));
}
pub fn isAsciiAlphaNum(cp: u21) bool {
return if (cp < 128) ascii.isAlNum(@intCast(u8, cp)) else false;
}
/// isCased detects cased code points, usually letters.
pub fn isCased(self: Self, cp: u21) !bool {
return self.letter.isCased(cp);
}
/// isDecimal detects all Unicode decimal numbers.
pub fn isDecimal(self: Self, cp: u21) !bool {
return self.number.isDecimal(cp);
}
/// isDigit detects all Unicode digits, which curiosly don't include the ASCII digits.
pub fn isDigit(self: Self, cp: u21) !bool {
return self.number.isDigit(cp);
}
pub fn isAsciiDigit(cp: u21) bool {
return if (cp < 128) ascii.isDigit(@intCast(u8, cp)) else false;
}
/// isGraphic detects any code point that can be represented graphically, including spaces.
pub fn isGraphic(self: Self, cp: u21) !bool {
return (try self.isPrint(cp)) or (try self.isSpace(cp));
}
pub fn isAsciiGraphic(cp: u21) bool {
return if (cp < 128) ascii.isGraph(@intCast(u8, cp)) else false;
}
// isHex detects hexadecimal code points.
pub fn isHexDigit(self: Self, cp: u21) !bool {
return self.number.isHexDigit(cp);
}
pub fn isAsciiHexDigit(cp: u21) bool {
return if (cp < 128) ascii.isXDigit(@intCast(u8, cp)) else false;
}
/// isPrint detects any code point that can be printed, excluding spaces.
pub fn isPrint(self: Self, cp: u21) !bool {
return (try self.isAlphaNum(cp)) or (try self.isMark(cp)) or (try self.isPunct(cp)) or
(try self.isSymbol(cp)) or (try self.isWhiteSpace(cp));
}
pub fn isAsciiPrint(cp: u21) bool {
return if (cp < 128) ascii.isPrint(@intCast(u8, cp)) else false;
}
pub fn isControl(self: Self, cp: u21) !bool {
const control = try self.context.getControl();
return control.isControl(cp);
}
pub fn isAsciiControl(cp: u21) bool {
return if (cp < 128) ascii.isCntrl(@intCast(u8, cp)) else false;
}
pub fn isLetter(self: Self, cp: u21) !bool {
return self.letter.isLetter(cp);
}
pub fn isAsciiLetter(cp: u21) bool {
return if (cp < 128) ascii.isAlpha(@intCast(u8, cp)) else false;
}
/// isLower detects code points that are lowercase.
pub fn isLower(self: Self, cp: u21) !bool {
return self.letter.isLower(cp);
}
pub fn isAsciiLower(cp: u21) bool {
return if (cp < 128) ascii.isLower(@intCast(u8, cp)) else false;
}
/// isMark detects special code points that serve as marks in different alphabets.
pub fn isMark(self: Self, cp: u21) !bool {
return self.mark.isMark(cp);
}
pub fn isNumber(self: Self, cp: u21) !bool {
return self.number.isNumber(cp);
}
pub fn isAsciiNumber(cp: u21) bool {
return if (cp < 128) ascii.isDigit(@intCast(u8, cp)) else false;
}
/// isPunct detects punctuation characters. Note some punctuation may be considered as symbols by Unicode.
pub fn isPunct(self: Self, cp: u21) !bool {
return self.punct.isPunct(cp);
}
pub fn isAsciiPunct(cp: u21) bool {
return if (cp < 128) ascii.isPunct(@intCast(u8, cp)) else false;
}
/// isSpace detects code points that are Unicode space separators.
pub fn isSpace(self: Self, cp: u21) !bool {
return self.space.isSpace(cp);
}
/// isWhiteSpace detects code points that have the Unicode *WhiteSpace* property.
pub fn isWhiteSpace(self: Self, cp: u21) !bool {
return self.space.isWhiteSpace(cp);
}
pub fn isAsciiWhiteSpace(cp: u21) bool {
return if (cp < 128) ascii.isSpace(@intCast(u8, cp)) else false;
}
// isSymbol detects symbols which may include code points commonly considered punctuation.
pub fn isSymbol(self: Self, cp: u21) !bool {
return self.symbol.isSymbol(cp);
}
pub fn isAsciiSymbol(cp: u21) bool {
return if (cp < 128) ascii.isSymbol(@intCast(u8, cp)) else false;
}
/// isTitle detects code points in titlecase.
pub fn isTitle(self: Self, cp: u21) !bool {
return self.letter.isTitle(cp);
}
/// isUpper detects code points in uppercase.
pub fn isUpper(self: Self, cp: u21) !bool {
return self.letter.isUpper(cp);
}
pub fn isAsciiUpper(cp: u21) bool {
return if (cp < 128) ascii.isUpper(@intCast(u8, cp)) else false;
}
/// toLower returns the lowercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toLower(self: Self, cp: u21) !u21 {
return self.letter.toLower(cp);
}
pub fn toAsciiLower(cp: u21) u21 {
return if (cp < 128) ascii.toLower(@intCast(u8, cp)) else cp;
}
/// toTitle returns the titlecase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toTitle(self: Self, cp: u21) !u21 {
return self.letter.toTitle(cp);
}
/// toUpper returns the uppercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toUpper(self: Self, cp: u21) !u21 {
return self.letter.toUpper(cp);
}
pub fn toAsciiUpper(cp: u21) u21 {
return if (cp < 128) ascii.toUpper(@intCast(u8, cp)) else false;
}
};
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "Ziglyph ASCII methods" {
const z = 'F';
expect(Ziglyph.isAsciiAlphabetic(z));
expect(Ziglyph.isAsciiAlphaNum(z));
expect(Ziglyph.isAsciiHexDigit(z));
expect(Ziglyph.isAsciiGraphic(z));
expect(Ziglyph.isAsciiPrint(z));
expect(Ziglyph.isAsciiUpper(z));
expect(!Ziglyph.isAsciiControl(z));
expect(!Ziglyph.isAsciiDigit(z));
expect(!Ziglyph.isAsciiNumber(z));
expect(!Ziglyph.isAsciiLower(z));
expectEqual(Ziglyph.toAsciiLower(z), 'f');
expect(Ziglyph.isAsciiLower(Ziglyph.toAsciiLower(z)));
}
test "Ziglyph struct" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
const z = 'z';
expect(try ziglyph.isAlphaNum(z));
expect(!try ziglyph.isControl(z));
expect(!try ziglyph.isDecimal(z));
expect(!try ziglyph.isDigit(z));
expect(!try ziglyph.isHexDigit(z));
expect(try ziglyph.isGraphic(z));
expect(try ziglyph.isLetter(z));
expect(try ziglyph.isLower(z));
expect(!try ziglyph.isMark(z));
expect(!try ziglyph.isNumber(z));
expect(try ziglyph.isPrint(z));
expect(!try ziglyph.isPunct(z));
expect(!try ziglyph.isWhiteSpace(z));
expect(!try ziglyph.isSymbol(z));
expect(!try ziglyph.isTitle(z));
expect(!try ziglyph.isUpper(z));
const uz = try ziglyph.toUpper(z);
expect(try ziglyph.isUpper(uz));
expectEqual(uz, 'Z');
const lz = try ziglyph.toLower(uz);
expect(try ziglyph.isLower(lz));
expectEqual(lz, 'z');
const tz = try ziglyph.toTitle(lz);
expect(try ziglyph.isUpper(tz));
expectEqual(tz, 'Z');
}
test "Ziglyph isGraphic" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
expect(try ziglyph.isGraphic('A'));
expect(try ziglyph.isGraphic('\u{20E4}'));
expect(try ziglyph.isGraphic('1'));
expect(try ziglyph.isGraphic('?'));
expect(try ziglyph.isGraphic(' '));
expect(try ziglyph.isGraphic('='));
expect(!try ziglyph.isGraphic('\u{0003}'));
}
test "Ziglyph isHexDigit" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
expect(try ziglyph.isHexDigit(cp));
}
cp = 'A';
while (cp <= 'F') : (cp += 1) {
expect(try ziglyph.isHexDigit(cp));
}
cp = 'a';
while (cp <= 'f') : (cp += 1) {
expect(try ziglyph.isHexDigit(cp));
}
expect(!try ziglyph.isHexDigit('\u{0003}'));
expect(!try ziglyph.isHexDigit('Z'));
}
test "Ziglyph isPrint" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
expect(try ziglyph.isPrint('A'));
expect(try ziglyph.isPrint('\u{20E4}'));
expect(try ziglyph.isPrint('1'));
expect(try ziglyph.isPrint('?'));
expect(try ziglyph.isPrint('='));
expect(try ziglyph.isPrint(' '));
expect(try ziglyph.isPrint('\t'));
expect(!try ziglyph.isPrint('\u{0003}'));
}
test "Ziglyph isAlphaNum" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
expect(try ziglyph.isAlphaNum(cp));
}
cp = 'a';
while (cp <= 'z') : (cp += 1) {
expect(try ziglyph.isAlphaNum(cp));
}
cp = 'A';
while (cp <= 'Z') : (cp += 1) {
expect(try ziglyph.isAlphaNum(cp));
}
expect(!try ziglyph.isAlphaNum('='));
}
test "Ziglyph isControl" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var ziglyph = try Ziglyph.new(&ctx);
expect(try ziglyph.isControl('\n'));
expect(try ziglyph.isControl('\r'));
expect(try ziglyph.isControl('\t'));
expect(try ziglyph.isControl('\u{0003}'));
expect(try ziglyph.isControl('\u{0012}'));
expect(!try ziglyph.isControl('A'));
}
|
src/ziglyph.zig
|
const zang = @import("zang");
const common = @import("common.zig");
const c = @import("common/c.zig");
const Module = @import("modules.zig").NiceInstrument;
pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb;
pub const AUDIO_SAMPLE_RATE = 48000;
pub const AUDIO_BUFFER_SIZE = 1024;
pub const DESCRIPTION =
\\example_polyphony2
\\
\\Play an instrument with the keyboard. There are 3
\\voice slots.
;
const a4 = 220.0;
const polyphony = 3;
pub const MainModule = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const output_audio = common.AudioOut{ .mono = 0 };
pub const output_visualize = 0;
const Voice = struct {
module: Module,
trigger: zang.Trigger(Module.Params),
};
dispatcher: zang.Notes(Module.Params).PolyphonyDispatcher(polyphony),
voices: [polyphony]Voice,
note_ids: [common.key_bindings.len]?usize,
next_note_id: usize,
iq: zang.Notes(Module.Params).ImpulseQueue,
pub fn init() MainModule {
var self: MainModule = .{
.note_ids = [1]?usize{null} ** common.key_bindings.len,
.next_note_id = 1,
.iq = zang.Notes(Module.Params).ImpulseQueue.init(),
.dispatcher = zang.Notes(Module.Params).PolyphonyDispatcher(polyphony).init(),
.voices = undefined,
};
var i: usize = 0;
while (i < polyphony) : (i += 1) {
self.voices[i] = .{
.module = Module.init(0.3),
.trigger = zang.Trigger(Module.Params).init(),
};
}
return self;
}
pub fn paint(self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32) void {
const iap = self.iq.consume();
const poly_iap = self.dispatcher.dispatch(iap);
for (self.voices) |*voice, i| {
var ctr = voice.trigger.counter(span, poly_iap[i]);
while (voice.trigger.next(&ctr)) |result| {
voice.module.paint(result.span, outputs, temps, result.note_id_changed, result.params);
}
}
}
pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool {
for (common.key_bindings) |kb, i| {
if (kb.key != key) {
continue;
}
const params: Module.Params = .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq = a4 * kb.rel_freq,
.note_on = down,
};
if (down) {
self.iq.push(impulse_frame, self.next_note_id, params);
self.note_ids[i] = self.next_note_id;
self.next_note_id += 1;
} else if (self.note_ids[i]) |note_id| {
self.iq.push(impulse_frame, note_id, params);
self.note_ids[i] = null;
}
}
return true;
}
};
|
examples/example_polyphony2.zig
|
const GBA = @import("core.zig").GBA;
pub const Background = struct {
pub const Palette = @intToPtr([*]GBA.PaletteBank, @ptrToInt(GBA.BG_PALETTE_RAM));
pub const BackgroundControl = packed struct {
priority: u2 = 0,
characterBaseBlock: u2 = 0,
dummy: u2 = 0,
mosaic: bool = false,
paletteMode: GBA.PaletteMode = .Color16,
screenBaseBlock: u5 = 0,
dummy2: u1 = 0,
screenSize: packed enum(u2) {
Text32x32,
Text64x32,
Text32x64,
Text64x64,
} = .Text32x32,
};
pub const Background0Control = @intToPtr(*volatile BackgroundControl, 0x4000008);
pub const Background1Control = @intToPtr(*volatile BackgroundControl, 0x400000A);
pub const Background2Control = @intToPtr(*volatile BackgroundControl, 0x400000C);
pub const Background3Control = @intToPtr(*volatile BackgroundControl, 0x400000E);
pub fn setupBackground(background: *volatile BackgroundControl, settings: BackgroundControl) callconv(.Inline) void {
background.* = settings;
}
pub const Scroll = packed struct {
x: u9 = 0,
dummy: u7 = 0,
y: u9 = 0,
dummy2: u7 = 0,
const Self = @This();
pub fn setPosition(self: *volatile Self, x: i32, y: i32) callconv(.Inline) void {
@setRuntimeSafety(false);
const Mask = (1 << 9) - 1;
self.x = @intCast(u9, x & Mask);
self.y = @intCast(u9, y & Mask);
}
};
pub const Background0Scroll = @intToPtr(*volatile Scroll, 0x4000010);
pub const Background1Scroll = @intToPtr(*volatile Scroll, 0x4000014);
pub const Background2Scroll = @intToPtr(*volatile Scroll, 0x4000018);
pub const Background3Scroll = @intToPtr(*volatile Scroll, 0x400001C);
pub const TextScreenEntry = packed struct {
tileIndex: u10 = 0,
horizontalFlip: bool = false,
verticalFlip: bool = false,
paletteIndex: u4 = 0,
};
pub const AffineScreenEntry = packed struct {
tileIndex: u8 = 0,
};
pub const TextScreenBlock = [1024]TextScreenEntry;
pub const ScreenBlockMemory = @intToPtr([*]align(4) volatile TextScreenBlock, @ptrToInt(GBA.VRAM));
pub const Tile = packed struct { data: [8]u32 };
pub const CharacterBlock = [512]Tile;
pub const TileMemory = @intToPtr([*]align(4) volatile CharacterBlock, @ptrToInt(GBA.VRAM));
pub const Tile8 = packed struct { data: [16]u32 };
pub const CharacterBlock8 = [256]Tile8;
pub const Tile8Memory = @intToPtr([*]align(4) volatile CharacterBlock8, @ptrToInt(GBA.VRAM));
};
|
GBA/background.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Game = struct {
pub const SIZE = 1_000_000;
size: usize, // actual size used
cups: *[SIZE]usize, // value at each position
next: *[SIZE]usize, // position for next value (linked list)
vals: *[SIZE + 1]usize, // position where each value is -- THIS IS WITH ZERO OFFSET!
curr: usize, // position of current value
turn: usize, // turns played so far
pub fn init(str: []const u8, size: usize) Game {
var self = Game{
.size = size,
.cups = undefined,
.next = undefined,
.vals = undefined,
.curr = 0,
.turn = 0,
};
self.cups = allocator.create([SIZE]usize) catch unreachable;
self.next = allocator.create([SIZE]usize) catch unreachable;
self.vals = allocator.create([SIZE + 1]usize) catch unreachable;
if (size == 0) self.size = str.len;
self.vals[0] = std.math.maxInt(usize);
var top: usize = 0;
for (str) |c, p| {
const n = c - '0';
self.cups[p] = n;
self.vals[n] = p;
self.next[p] = p + 1;
if (top < n) top = n;
}
var p: usize = str.len;
while (p < self.size) : (p += 1) {
top += 1;
self.cups[p] = top;
self.vals[top] = p;
self.next[p] = p + 1;
}
self.next[self.size - 1] = 0;
return self;
}
pub fn deinit(self: *Game) void {
allocator.free(self.vals);
allocator.free(self.next);
allocator.free(self.cups);
}
pub fn show(self: Game) void {
std.debug.warn("GAME ", .{});
var p = self.curr;
const top = (self.size * self.turn - self.turn) % self.size;
var c: usize = 0;
while (c < top) : (c += 1) {
p = self.next[p];
}
c = 0;
while (c < self.size) : (c += 1) {
if (p == self.curr) {
std.debug.warn(" ({})", .{self.cups[p]});
} else {
std.debug.warn(" {}", .{self.cups[p]});
}
p = self.next[p];
}
std.debug.warn("\n", .{});
}
pub fn play(self: *Game, turns: usize) void {
var turn: usize = 0;
while (turn < turns) : (turn += 1) {
self.play_one_turn();
// if (turn % 1000 == 0) std.debug.warn("-- move {} --\n", .{turn + 1});
// std.debug.warn("-- move {} --\n", .{self.turn});
// self.show();
}
}
fn play_one_turn(self: *Game) void {
var pos = self.curr;
var first_taken: usize = 0;
var last_taken: usize = 0;
var first_kept: usize = 0;
var p: usize = 0;
while (p < 4) : (p += 1) {
pos = self.next[pos];
if (p < 1) first_taken = pos;
if (p < 3) last_taken = pos;
if (p < 4) first_kept = pos;
}
// find destination value, starting at current value
var dest_val = self.cups[self.curr];
while (true) {
// "subtract one" from current value
if (dest_val == 1) {
dest_val = self.size;
} else {
dest_val -= 1;
}
// check if it is one of the taken values
var good = true;
pos = first_taken;
while (pos != first_kept) : (pos = self.next[pos]) {
if (self.cups[pos] == dest_val) {
good = false;
break;
}
}
if (good) break;
}
var dest_pos = self.vals[dest_val];
// std.debug.warn("destination {} at position {}\n", .{ dest_val, dest_pos });
// rearrange next values
self.next[self.curr] = first_kept;
self.next[last_taken] = self.next[dest_pos];
self.next[dest_pos] = first_taken;
self.curr = first_kept;
self.turn += 1;
}
pub fn get_state(self: *Game) usize {
var p: usize = 0;
while (p < self.size) : (p += 1) {
if (self.cups[p] == 1) break;
}
var state: usize = 0;
var q: usize = 0;
while (q < self.size - 1) : (q += 1) {
p = self.next[p];
state *= 10;
state += self.cups[p];
}
return state;
}
pub fn find_stars(self: *Game) usize {
var product: usize = 1;
var pos = self.vals[1];
var c: usize = 0;
while (c < 2) : (c += 1) {
pos = self.next[pos];
product *= pos + 1; // positions are offset ZERO, we want offset ONE
}
return product;
}
};
test "sample part a" {
const data: []const u8 = "389125467";
var game = Game.init(data, 0);
defer game.deinit();
// game.show();
game.play(10);
try testing.expect(game.get_state() == 92658374);
game.play(90);
try testing.expect(game.get_state() == 67384529);
}
test "sample part b" {
const data: []const u8 = "389125467";
var game = Game.init(data, Game.SIZE);
defer game.deinit();
// game.show();
game.play(10_000_000);
try testing.expect(game.find_stars() == 149245887792);
}
|
2020/p23/game.zig
|
const std = @import("std");
const builtin = @import("builtin");
// XXX TODO "build_options" doesn't reach here from build.zig.
// pub const enable = if (builtin.is_test) false else @import("build_options").enable_tracy;
pub const enable = false;
extern fn ___tracy_emit_frame_mark_start(name: ?[*:0]const u8) void;
extern fn ___tracy_emit_frame_mark_end(name: ?[*:0]const u8) void;
//extern fn ___tracy_set_thread_name(name: ?[*:0]const u8) void;
extern fn ___tracy_emit_zone_begin_callstack(
srcloc: *const ___tracy_source_location_data,
depth: c_int,
active: c_int,
) ___tracy_c_zone_context;
extern fn ___tracy_alloc_srcloc(line: u32, source: ?[*:0]const u8, sourceSz: usize, function: ?[*:0]const u8, functionSz: usize) u64;
extern fn ___tracy_alloc_srcloc_name(line: u32, source: ?[*:0]const u8, sourceSz: usize, function: ?[*:0]const u8, functionSz: usize, name: ?[*:0]const u8, nameSz: usize) u64;
extern fn ___tracy_emit_zone_begin_alloc_callstack(srcloc: u64, depth: c_int, active: c_int) ___tracy_c_zone_context;
extern fn ___tracy_emit_zone_begin_alloc(srcloc: u64, active: c_int) ___tracy_c_zone_context;
extern fn ___tracy_emit_zone_end(ctx: ___tracy_c_zone_context) void;
extern fn ___tracy_startup_profiler() void;
extern fn ___tracy_shutdown_profiler() void;
fn empty() void {}
pub const startup_profiler = if (enable) ___tracy_startup_profiler else empty;
pub const shutdown_profiler = if (enable) ___tracy_shutdown_profiler else empty;
pub const ___tracy_source_location_data = extern struct {
name: ?[*:0]const u8,
function: [*:0]const u8,
file: [*:0]const u8,
line: u32,
color: u32,
};
pub const ___tracy_c_zone_context = extern struct {
id: u32,
active: c_int,
pub fn end(self: ___tracy_c_zone_context) void {
___tracy_emit_zone_end(self);
}
};
pub const Ctx = if (enable) ___tracy_c_zone_context else struct {
pub fn end(self: Ctx) void {
_ = self;
}
};
pub inline fn trace(comptime src: std.builtin.SourceLocation) Ctx {
if (!enable) return .{};
const loc: ___tracy_source_location_data = .{
.name = null,
.function = src.fn_name.ptr,
.file = src.file.ptr,
.line = src.line,
.color = 0,
};
return ___tracy_emit_zone_begin_callstack(&loc, 1, 1);
}
const TraceOptions = struct { name: ?[:0]const u8 = null, color: u32 = 0, callstack: bool = false };
pub inline fn traceEx(comptime src: std.builtin.SourceLocation, opt: TraceOptions) Ctx {
if (!enable) return .{};
const srcloc = if (opt.name) |name|
___tracy_alloc_srcloc_name(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len, name.ptr, name.len)
else
___tracy_alloc_srcloc(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len);
if (opt.callstack)
return ___tracy_emit_zone_begin_alloc_callstack(srcloc, 7, 1)
else
return ___tracy_emit_zone_begin_alloc(srcloc, 1);
}
pub const ___tracy_c_frame_context = extern struct {
name: ?[*:0]const u8,
pub fn end(self: ___tracy_c_frame_context) void {
___tracy_emit_frame_mark_end(self.name);
}
};
pub const FrameCtx = if (enable) ___tracy_c_frame_context else struct {
pub fn end(self: FrameCtx) void {
_ = self;
}
};
pub fn traceFrame(name: ?[*:0]const u8) FrameCtx {
if (!enable) return .{};
___tracy_emit_frame_mark_start(name);
return ___tracy_c_frame_context{ .name = name };
}
|
common/tracy.zig
|
const georgios = @import("georgios");
const utils = @import("utils");
const io = @import("io.zig");
const print = @import("print.zig");
const Allocator = @import("memory.zig").Allocator;
const List = @import("list.zig").List;
const debug = false;
const dump_segments = false;
pub const Error = georgios.elf.Error;
// TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64)
const SectionHeader = packed struct {
name_index: u32, // sh_name
kind: u32, // sh_type
flags: u32, // sh_flags
address: usize, // sh_addr
offset: isize, // sh_offset
size: u32, // sh_size
link: u32, // sh_link
info: u32, // sh_info
addralign: u32, // sh_addralign
entsize: u32, // sh_entsize
};
// TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64)
const ProgramHeader = packed struct {
kind: u32, // p_type
offset: isize, // p_offset
virtual_address: usize, // p_vaddr
physical_address: usize, // p_paddr
size_in_file: u32, // p_filesz
size_in_memory: u32, // p_memsz
flags: u32, // p_flags
address_align: u32, // p_align
};
// TODO: Create Seperate 32 and 64 bit Versions ([ui]size -> [ui]32, [ui]64)
const Header = packed struct {
const Magic = [4]u8;
const expected_magic: Magic = [_]u8 {0x7f, 'E', 'L', 'F'};
pub const Class = enum(u8) {
Invalid = 0, // ELFCLASSNONE
Is32 = 1, // ELFCLASS32
Is64 = 2, // ELFCLASS64
};
pub const Data = enum(u8) {
Invalid = 0, // ELFDATANONE
Little = 1, // ELFDATA2LSB
Big = 2, // ELFDATA2MSB
};
pub const HeaderVersion = enum(u8) {
Invalid = 0, // EV_NONE
Current = 1, // EV_CURRENT
};
pub const ObjectType = enum(u16) {
None = 0, // ET_NONE
Relocatable = 1, // ET_REL
Executable = 2, // ET_EXEC
Shared = 3, // ET_DYN
CoreDump = 4, // ET_CORE
};
pub const Machine = enum(u16) {
None = 0x00, // ET_NONE
X86_32 = 0x03, // ET_386
X86_64 = 0x3e,
Arm32 = 0x28,
Arm64 = 0xb7,
RiscV = 0xf3,
// There are others, but I'm not going to put them in.
};
pub const ObjectVersion = enum(u32) {
Invalid = 0, // EV_NONE
Current = 1, // EV_CURRENT
};
// e_ident
magic: Magic, // EI_MAG0 - EI_MAG3
class: Class, // EI_CLASS
data: Data, // EI_DATA
header_version: HeaderVersion, // EI_VERSION
unused_abi_os: u8, // EI_OSABI
unused_abi_version: u8, //EI_ABIVERSION
// TODO: This adds 8 to the size of the struct, not 7. Retest with zig master.
// reserved: [7]u8, // EI_PAD
reserved0: u8,
reserved1: u8,
reserved2: u8,
reserved3: u8,
reserved4: u8,
reserved5: u8,
reserved6: u8,
object_type: ObjectType, // e_type
machine: Machine, // e_machine
object_version: ObjectVersion, // e_version
entry: usize, // e_entry
program_header_offset: isize, // e_phoff
section_header_offset: isize, // e_shoff
flags: u32, // e_flags
header_size: u16, // e_ehsize
program_header_entry_size: u16, // e_phentsize
program_header_entry_count: u16, // e_phnum
section_header_entry_size: u16, // e_shentsize
section_header_entry_count: u16, // e_shnum
section_header_string_table_index: u16, // e_shstrndx
pub fn verify_elf(self: *const Header) Error!void {
const invalid =
!utils.memory_compare(self.magic[0..], expected_magic[0..]) or
!utils.valid_enum(Class, self.class) or
self.class == .Invalid or
!utils.valid_enum(Data, self.data) or
self.data == .Invalid or
!utils.valid_enum(HeaderVersion, self.header_version) or
self.header_version == .Invalid or
!utils.valid_enum(ObjectVersion, self.object_version) or
self.object_version == .Invalid;
if (invalid) {
return Error.InvalidElfFile;
}
}
pub fn verify_compatible(self: *const Header) Error!void {
// TODO: Make machine depend on platform and other checks
if (self.machine != .X86_32) {
return Error.InvalidElfPlatform;
}
}
pub fn verify_executable(self: *const Header) Error!void {
try self.verify_elf();
if (self.object_type != .Executable) {
return Error.InvalidElfObjectType;
}
try self.verify_compatible();
}
};
pub const Object = struct {
pub const Segment = struct {
const WhatKind = enum {
Data,
UndefinedMemory,
};
const What = union(WhatKind) {
Data: []u8,
UndefinedMemory: usize,
};
what: What = undefined,
address: usize,
pub fn teardown(self: *Segment, alloc: *Allocator) !void {
switch (self.what) {
.Data => |data| try alloc.free_array(data),
else => {},
}
}
};
pub const Segments = List(Segment);
alloc: *Allocator,
data_alloc: *Allocator,
header: Header = undefined,
section_headers: []SectionHeader = undefined,
program_headers: []ProgramHeader = undefined,
segments: Segments = undefined,
pub fn from_file(alloc: *Allocator, data_alloc: *Allocator, file: *io.File) !Object {
var object = Object{.alloc = alloc, .data_alloc = data_alloc};
object.segments = Segments{.alloc = alloc};
// Read Header
_ = try file.read(utils.to_bytes(&object.header));
if (debug) print.format("Header Size: {}\n", .{@as(usize, @sizeOf(Header))});
try object.header.verify_executable();
if (debug) print.format("Entry: {:a}\n", .{@as(usize, @sizeOf(Header))});
// Read Section Headers
if (debug) print.format("Section Header Count: {}\n",
.{object.header.section_header_entry_count});
{
_ = try file.seek(
@intCast(isize, object.header.section_header_offset), .FromStart);
const count = @intCast(usize, object.header.section_header_entry_count);
const size = @intCast(usize, object.header.section_header_entry_size);
const skip = @intCast(isize, size - @sizeOf(SectionHeader));
object.section_headers = try alloc.alloc_array(SectionHeader, count);
for (object.section_headers) |*section_header| {
_ = try file.read(utils.to_bytes(section_header));
_ = try file.seek(skip, .FromHere);
}
}
for (object.section_headers) |*section_header| {
if (debug) print.format("section: kind: {} offset: {:x} size: {:x}\n", .{
section_header.kind,
@bitCast(usize, section_header.offset),
section_header.size});
}
// Read Program Headers
if (debug) print.format("Program Header Count: {}\n",
.{object.header.program_header_entry_count});
{
_ = try file.seek(@intCast(isize, object.header.program_header_offset), .FromStart);
const count = @intCast(usize, object.header.program_header_entry_count);
const size = @intCast(usize, object.header.program_header_entry_size);
const skip = @intCast(isize, size - @sizeOf(ProgramHeader));
object.program_headers = try alloc.alloc_array(ProgramHeader, count);
for (object.program_headers) |*program_header| {
_ = try file.read(utils.to_bytes(program_header));
_ = try file.seek(skip, .FromHere);
}
}
for (object.program_headers) |*program_header| {
if (debug) print.format("program: kind: {} offset: {:x} " ++
"size in file: {:x} size in memory: {:x}\n", .{
program_header.kind,
@bitCast(usize, program_header.offset),
program_header.size_in_file,
program_header.size_in_memory});
// Read the Program
// TODO: Remove/Make More Proper?
if (program_header.kind == 0x1) {
if (debug) print.format(
"segment at {} kind {} file size {} memory size {}\n", .{
program_header.virtual_address, program_header.kind,
program_header.size_in_file, program_header.size_in_memory,
});
var segment = Segment{.address = program_header.virtual_address};
const nonzero = program_header.size_in_memory > 0;
if (nonzero and program_header.size_in_memory == program_header.size_in_file) {
segment.what = Segment.What{
.Data = try data_alloc.alloc_array(u8, program_header.size_in_file)};
_ = try file.seek(@intCast(isize, program_header.offset), .FromStart);
_ = try file.read_or_error(segment.what.Data);
if (dump_segments) print.dump_bytes(segment.what.Data);
} else if (nonzero and program_header.size_in_file == 0) {
segment.what = Segment.What{
.UndefinedMemory = program_header.size_in_memory};
} else {
@panic("elf unexpected situation with program header sizes");
}
try object.segments.push_back(segment);
}
}
if (object.segments.len == 0) @panic("No LOADs in ELF!");
return object;
}
pub fn teardown(self: *Object) !void {
try self.alloc.free_array(self.section_headers);
try self.alloc.free_array(self.program_headers);
var iter = self.segments.iterator();
while (iter.next()) |*segment| {
try segment.teardown(self.data_alloc);
}
try self.segments.clear();
}
};
|
kernel/elf.zig
|
const std = @import("std");
const Crc32 = std.hash.Crc32;
const warn = std.debug.warn;
const RawDeflateReader = @import("./raw_deflate_reader.zig").RawDeflateReader;
pub fn GzipInStream(comptime InStreamType: type) type {
return struct {
const Self = @This();
const RawDeflateReaderType = RawDeflateReader(InStreamType);
crc: Crc32 = Crc32.init(),
bytes_accumulated: usize = 0,
did_read_footer: bool = false,
raw_deflate_reader: RawDeflateReaderType,
read_stream: InStreamType,
pub fn init(read_stream: InStreamType) Self {
const raw_deflate_reader = RawDeflateReaderType.init(read_stream);
return .{
.read_stream = read_stream,
.raw_deflate_reader = raw_deflate_reader,
};
}
pub fn readHeader(self: *Self) !void {
var read_stream = self.read_stream;
// GZip fields are in Little-Endian.
// FTEXT: File is probably ASCII text (not relevant)
const FTEXT = 0x01;
// FHCRC: File has a 16-bit header CRC
// (2 LSBs of 32-bit CRC up to but excluding the compressed data)
const FHCRC = 0x02;
// FEXTRA: File has extra fields
const FEXTRA = 0x04;
// FNAME: File has an original filename in ISO 8859-1 (LATIN-1) encoding
const FNAME = 0x08;
// FCOMMENT: File has a comment
const FCOMMENT = 0x10;
// And these are the flags which are valid.
const VALID_FLAGS = FTEXT | FHCRC | FEXTRA | FNAME | FCOMMENT;
// GZip header magic number
const magic0: u8 = try read_stream.readByte();
const magic1: u8 = try read_stream.readByte();
if (magic0 != 0x1F) {
return error.Failed;
}
if (magic1 != 0x8B) {
return error.Failed;
}
// Compression method: 0x08 = deflate
const magic2: u8 = try read_stream.readByte();
if (magic2 != 0x08) {
return error.Failed;
}
// Flags
const flags: u8 = try read_stream.readByte();
// Modification time
const mtime: u32 = try read_stream.readIntLittle(u32);
// eXtra FLags
const xfl: u8 = try read_stream.readByte();
// Operating System used
const gzip_os: u8 = try read_stream.readByte();
// FEXTRA if present
if ((flags & FEXTRA) != 0) {
const fextra_len: u16 = try read_stream.readIntLittle(u16);
// TODO: Parse if relevant
try read_stream.skipBytes(fextra_len);
}
// FNAME if present
if ((flags & FNAME) != 0) {
warn("original file name: \"", .{});
while (true) {
const char = try read_stream.readByte();
if (char == 0) {
break;
}
warn("{c}", .{char});
}
warn("\"\n", .{});
}
// FCOMMENT if present
if ((flags & FCOMMENT) != 0) {
try read_stream.skipUntilDelimiterOrEof(0);
}
// FHCRC if present
if ((flags & FHCRC) != 0) {
warn("Has 16-bit header CRC\n", .{});
_ = try read_stream.readIntLittle(u16);
}
}
pub fn read(self: *Self, buffer: []u8) !usize {
// Read the data
const bytes_just_read = try self.raw_deflate_reader.read(buffer);
// Process CRC32
self.crc.update(buffer[0..bytes_just_read]);
// Process byte count
self.bytes_accumulated += bytes_just_read;
// If we hit stream EOF, read the CRC32 and ISIZE fields
if (bytes_just_read == 0) {
if (!self.did_read_footer) {
self.did_read_footer = true;
//self.read_bit_stream.alignToByte();
const crc_finished: u32 = self.crc.final();
const crc_expected: u32 = try self.read_stream.readIntLittle(u32);
const bytes_expected: u32 = try self.read_stream.readIntLittle(u32);
if (crc_finished != crc_expected) {
warn("CRC mismatch: got {}, expected {}\n", .{ crc_finished, crc_expected });
return error.Failed;
}
if (self.bytes_accumulated != bytes_expected) {
warn("Size mismatch: got {}, expected {}\n", .{ self.bytes_accumulated, bytes_expected });
return error.Failed;
}
}
}
return bytes_just_read;
}
};
}
pub fn gzipInStream(
underlying_stream: var,
) GzipInStream(@TypeOf(underlying_stream)) {
return GzipInStream(@TypeOf(underlying_stream)).init(underlying_stream);
}
|
src/gzip.zig
|
const std = @import("std");
const rom_header_begin = 0x0100;
const rom_header_end = 0x0150;
comptime {
std.debug.assert(@sizeOf(RomHeader) == rom_header_end - rom_header_begin);
}
pub const RomHeader = packed struct {
// 0x0100 .. 0x0103
entry_point: [4]u8,
// 0x0104 .. 0x0133
nintendo_logo: [48]u8,
// 0x0134 .. 0x0142
title: [15]u8,
// 0x0143
cgb_flag: u8,
// 0x0144 .. 0x0145
new_licensee_code: [2]u8,
// 0x0146
sgb_flag: u8,
// 0x0147
cartridge_type: u8,
// 0x0148
rom_size: u8,
// 0x0149
ram_size: u8,
// 0x014A
destination_code: u8,
// 0x014B
old_licensee_code: u8,
// 0x014C
mask_rom_version_number: u8,
// 0x014D
header_checksum: u8,
// 0x014E .. 0x014F
global_checksum: [2]u8,
pub fn debugPrint(header: *const RomHeader) void {
// NOTE: Evaluation exceeded 1000 backwards branches if all one printf.
std.debug.warn(
\\entry point : {X}
\\title : {}
\\cgb_flag : {X} = {}
\\new_licensee_code : {X}
\\sgb_flag : {X} = {}
\\cartridge_type : {X} = {}
\\
,
header.entry_point,
header.title,
header.cgb_flag,
Format.cgbFlag(header.cgb_flag),
header.new_licensee_code,
header.sgb_flag,
Format.sgbFlag(header.sgb_flag),
header.cartridge_type,
Format.cartridgeType(header.cartridge_type),
);
std.debug.warn(
\\rom_size : {X} = {}
\\ram_size : {X} = {}
\\destination code : {X} = {}
\\old_licensee code : {X}
\\mask_rom_version_number : {X}
\\header checksum : {X}
\\global checksum : {X}
\\
,
header.rom_size,
Format.romSize(header.rom_size),
header.ram_size,
Format.ramSize(header.ram_size),
header.destination_code,
Format.destinationCode(header.destination_code),
header.old_licensee_code,
header.mask_rom_version_number,
header.header_checksum,
header.global_checksum,
);
}
};
pub const Rom = struct {
// Maximum 32Kb for now (no banking).
content: []u8,
header: *const RomHeader,
pub fn load(rom_binary: []u8) !Rom {
var rom: Rom = undefined;
rom.content = rom_binary;
rom.header = @ptrCast(*const RomHeader, &rom.content[rom_header_begin]);
try verifyRom(&rom);
return rom;
}
fn verifyRom(rom: *Rom) !void {
// Only handle ROM ONLY cartridges
if (rom.header.cartridge_type != 0x00) {
return error.UnsupportedCartridgeType;
}
// Only handle 32Kb ROM size only
if (rom.header.rom_size != 0x00) {
return error.UnsupportedRomSize;
}
if (rom.content.len != 32 * 1024) {
return error.InvalidRomSize;
}
}
};
const Format = struct {
fn cgbFlag(value: u8) []const u8 {
return switch (value) {
0x80 => "CGB plus old gameboys",
0xC0 => "CGB only",
else => "Part of Title",
};
}
fn sgbFlag(value: u8) []const u8 {
return switch (value) {
0x03 => "SGB support",
else => "No SGB support",
};
}
fn cartridgeType(value: u8) ![]const u8 {
return switch (value) {
0x00 => "ROM ONLY",
0x01 => "MBC1",
0x02 => "MBC1+RAM",
0x03 => "MBC1+RAM+BATTERY",
0x05 => "MBC2",
0x06 => "MBC2+BATTERY",
0x08 => "ROM+RAM",
0x09 => "ROM+RAM+BATTERY",
0x0B => "MMM01",
0x0C => "MMM01+SRAM",
0x0D => "MMM01+SRAM+BATTERY",
0x0F => "MBC3+TIMER+BATTERY",
0x10 => "MBC3+TIMER+RAM+BATTERY",
0x11 => "MBC3",
0x12 => "MBC3+RAM",
0x13 => "MBC3+RAM+BATTERY",
0x15 => "MBC4",
0x16 => "MBC4+RAM",
0x17 => "MBC14+RAM+BATTERY",
0x19 => "MBC5",
0x1A => "MBC5+RAM",
0x1B => "MBC5+RAM+BATTERY",
0x1C => "MBC5+RUMBLE",
0x1D => "MBC5+RUMBLE+RAM",
0x1E => "MBC5+RUMBLE+RAM+BATTERY",
0x1F => "POCKET CAMERA",
0xFD => "BANDAI TAMA5",
0xFE => "HuC3",
0xFF => "HuC1+RAM+BATTERY",
else => error.InvalidCartridgeType,
};
}
fn romSize(value: u8) ![]const u8 {
return switch (value) {
0x00 => "32Kb (no rom banks)",
0x01 => "64Kb (4 banks)",
0x02 => "128Kb (8 banks)",
0x03 => "256Kb (16 banks)",
0x04 => "512Kb (32 banks)",
0x05 => "1Mb (64 banks)",
0x06 => "2Mb (128 banks)",
0x07 => "4Mb (256 banks)",
0x52 => "1.1Mb (72 banks)",
0x53 => "1.2Mb (80 banks)",
0x54 => "1.5Mb (96 banks)",
else => error.InvalidRomSize,
};
}
fn ramSize(value: u8) ![]const u8 {
return switch (value) {
0x00 => "None",
0x01 => "2Kb",
0x02 => "8Kb",
0x03 => "32Kb",
else => error.InvalidRamSize,
};
}
fn destinationCode(value: u8) ![]const u8 {
return switch (value) {
0x00 => "Japanese",
0x01 => "Non-Japanese",
else => error.InvalidDestinationCode,
};
}
};
|
src/rom.zig
|
const std = @import("std");
const path = std.fs.path;
const assert = std.debug.assert;
const target_util = @import("target.zig");
const Compilation = @import("Compilation.zig");
const build_options = @import("build_options");
const trace = @import("tracy.zig").trace;
pub fn buildStaticLib(comp: *Compilation) !void {
if (!build_options.have_llvm) {
return error.ZigCompilerNotBuiltWithLLVMExtensions;
}
const tracy = trace(@src());
defer tracy.end();
var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
defer arena_allocator.deinit();
const arena = &arena_allocator.allocator;
const root_name = "unwind";
const output_mode = .Lib;
const link_mode = .Static;
const target = comp.getTarget();
const basename = try std.zig.binNameAlloc(arena, .{
.root_name = root_name,
.target = target,
.output_mode = output_mode,
.link_mode = link_mode,
});
const emit_bin = Compilation.EmitLoc{
.directory = null, // Put it in the cache directory.
.basename = basename,
};
const unwind_src_list = [_][]const u8{
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "libunwind.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-EHABI.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-seh.cpp",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindLevel1.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindLevel1-gcc-ext.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "Unwind-sjlj.c",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindRegistersRestore.S",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "UnwindRegistersSave.S",
"libunwind" ++ path.sep_str ++ "src" ++ path.sep_str ++ "gcc_personality_v0.c",
};
var c_source_files: [unwind_src_list.len]Compilation.CSourceFile = undefined;
for (unwind_src_list) |unwind_src, i| {
var cflags = std.ArrayList([]const u8).init(arena);
switch (Compilation.classifyFileExt(unwind_src)) {
.c => {
try cflags.append("-std=c99");
},
.cpp => {
try cflags.appendSlice(&[_][]const u8{
"-fno-rtti",
"-I",
try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxx", "include" }),
});
},
.assembly => {},
else => unreachable, // You can see the entire list of files just above.
}
try cflags.append("-I");
try cflags.append(try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libunwind", "include" }));
if (target_util.supports_fpic(target)) {
try cflags.append("-fPIC");
}
try cflags.append("-D_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS");
try cflags.append("-Wa,--noexecstack");
try cflags.append("-fvisibility=hidden");
try cflags.append("-fvisibility-inlines-hidden");
// This is intentionally always defined because the macro definition means, should it only
// build for the target specified by compiler defines. Since we pass -target the compiler
// defines will be correct.
try cflags.append("-D_LIBUNWIND_IS_NATIVE_ONLY");
if (comp.bin_file.options.optimize_mode == .Debug) {
try cflags.append("-D_DEBUG");
}
if (comp.bin_file.options.single_threaded) {
try cflags.append("-D_LIBUNWIND_HAS_NO_THREADS");
}
if (target.cpu.arch.isARM() and target.abi.floatAbi() == .hard) {
try cflags.append("-DCOMPILER_RT_ARMHF_TARGET");
}
try cflags.append("-Wno-bitwise-conditional-parentheses");
try cflags.append("-Wno-visibility");
try cflags.append("-Wno-incompatible-pointer-types");
c_source_files[i] = .{
.src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{unwind_src}),
.extra_flags = cflags.items,
};
}
const sub_compilation = try Compilation.create(comp.gpa, .{
.local_cache_directory = comp.global_cache_directory,
.global_cache_directory = comp.global_cache_directory,
.zig_lib_directory = comp.zig_lib_directory,
.target = target,
.root_name = root_name,
.root_pkg = null,
.output_mode = output_mode,
.thread_pool = comp.thread_pool,
.libc_installation = comp.bin_file.options.libc_installation,
.emit_bin = emit_bin,
.optimize_mode = comp.compilerRtOptMode(),
.link_mode = link_mode,
.want_sanitize_c = false,
.want_stack_check = false,
.want_red_zone = comp.bin_file.options.red_zone,
.want_valgrind = false,
.want_tsan = false,
.want_pic = comp.bin_file.options.pic,
.want_pie = comp.bin_file.options.pie,
.want_lto = comp.bin_file.options.lto,
.function_sections = comp.bin_file.options.function_sections,
.emit_h = null,
.strip = comp.compilerRtStrip(),
.is_native_os = comp.bin_file.options.is_native_os,
.is_native_abi = comp.bin_file.options.is_native_abi,
.self_exe_path = comp.self_exe_path,
.c_source_files = &c_source_files,
.verbose_cc = comp.verbose_cc,
.verbose_link = comp.bin_file.options.verbose_link,
.verbose_air = comp.verbose_air,
.verbose_llvm_ir = comp.verbose_llvm_ir,
.verbose_cimport = comp.verbose_cimport,
.verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
.clang_passthrough_mode = comp.clang_passthrough_mode,
.link_libc = true,
.skip_linker_dependencies = true,
});
defer sub_compilation.destroy();
try sub_compilation.updateSubCompilation();
assert(comp.libunwind_static_lib == null);
comp.libunwind_static_lib = Compilation.CRTFile{
.full_object_path = try sub_compilation.bin_file.options.emit.?.directory.join(
comp.gpa,
&[_][]const u8{basename},
),
.lock = sub_compilation.bin_file.toOwnedLock(),
};
}
|
src/libunwind.zig
|
pub usingnamespace @import("ingble.zig");
var session_complete: bool = true;
const print = platform_printf;
pub var all_services_discoverer: AllServicesDiscoverer = undefined;
const AllServicesDiscoverer = struct {
status: u8 = 0,
frame: ? (anyframe -> ?gatt_client_service_t)= null,
service: gatt_client_service_t = undefined,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_SERVICE_QUERY_RESULT => {
var result = gatt_event_service_query_result_parse(packet);
all_services_discoverer.service = result.*.service;
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
all_services_discoverer.status = gatt_event_query_complete_parse(packet).*.status;
},
else => { return; }
}
if (all_services_discoverer.frame) |f| {
resume f;
}
}
pub fn start(self: *AllServicesDiscoverer, conn_handle: hci_con_handle_t) bool {
if (!session_complete) return false;
self.frame = null;
session_complete = false;
if (0 == gatt_client_discover_primary_services(callback, conn_handle)) {
return !session_complete;
} else {
session_complete = true;
return false;
}
}
pub fn next(self: *AllServicesDiscoverer) ?gatt_client_service_t {
if (session_complete) return null;
suspend {
self.frame = @frame();
}
if (session_complete) {
return null;
} else {
return self.service;
}
}
};
pub var service_discoverer: ServiceDiscoverer = undefined;
const ServiceDiscoverer = struct {
status: u8 = 0,
frame: ? (anyframe -> ?gatt_client_service_t)= null,
service: ?gatt_client_service_t = undefined,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_SERVICE_QUERY_RESULT => {
var result = gatt_event_service_query_result_parse(packet);
service_discoverer.service = result.*.service;
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
service_discoverer.status = gatt_event_query_complete_parse(packet).*.status;
if (service_discoverer.frame) |f| {
resume f;
}
},
else => { }
}
}
pub fn discover_16(self: *ServiceDiscoverer, conn_handle: hci_con_handle_t, uuid: u16) ?gatt_client_service_t {
if (!session_complete) return null;
self.frame = null;
self.service = null;
session_complete = false;
if (0 != gatt_client_discover_primary_services_by_uuid16(callback, conn_handle, uuid)) {
session_complete = true;
return null;
}
suspend {
self.frame = @frame();
}
return self.service;
}
pub fn discover_128(self: *ServiceDiscoverer, conn_handle: hci_con_handle_t, uuid: [*c] const u8) ?gatt_client_service_t {
if (!session_complete) return null;
self.frame = null;
self.service = null;
session_complete = false;
if (0 != gatt_client_discover_primary_services_by_uuid128(callback, conn_handle, uuid)) {
session_complete = true;
return null;
}
suspend {
self.frame = @frame();
}
return self.service;
}
};
pub var all_characteristics_discoverer: AllCharacteristicsDiscoverer = undefined;
const AllCharacteristicsDiscoverer = struct {
status: u8 = 0,
frame: ?(anyframe -> ?gatt_client_characteristic_t) = null,
characteristic: gatt_client_characteristic_t = undefined,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_CHARACTERISTIC_QUERY_RESULT => {
var result = gatt_event_characteristic_query_result_parse(packet);
all_characteristics_discoverer.characteristic = result.*.characteristic;
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
all_characteristics_discoverer.status = gatt_event_query_complete_parse(packet).*.status;
},
else => { }
}
if (all_characteristics_discoverer.frame) |f| {
resume f;
}
}
pub fn start(self: *AllCharacteristicsDiscoverer, conn_handle: hci_con_handle_t,
start_group_handle: u16, end_group_handle: u16) bool {
if (!session_complete) return false;
self.frame = null;
session_complete = false;
if (0 == gatt_client_discover_characteristics_for_service(callback, conn_handle,
start_group_handle,
end_group_handle)) {
return !session_complete;
} else {
session_complete = true;
return false;
}
}
pub fn next(self: *AllCharacteristicsDiscoverer) ?gatt_client_characteristic_t {
if (session_complete) return null;
suspend {
self.frame = @frame();
}
if (session_complete) {
return null;
} else {
return self.characteristic;
}
}
};
pub var characteristics_discoverer: CharacteristicsDiscoverer = undefined;
const CharacteristicsDiscoverer = struct {
status: u8 = 0,
frame: ? (anyframe -> ?gatt_client_characteristic_t)= null,
characteristic: ?gatt_client_characteristic_t = undefined,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_CHARACTERISTIC_QUERY_RESULT => {
var result = gatt_event_characteristic_query_result_parse(packet);
characteristics_discoverer.characteristic = result.*.characteristic;
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
characteristics_discoverer.status = gatt_event_query_complete_parse(packet).*.status;
if (characteristics_discoverer.frame) |f| {
resume f;
}
},
else => { }
}
}
pub fn discover_16(self: *CharacteristicsDiscoverer, conn_handle: hci_con_handle_t,
start_handle: u16, end_handle: u16, uuid: u16) ?gatt_client_characteristic_t {
if (!session_complete) return null;
self.frame = null;
self.characteristic = null;
session_complete = false;
if (0 != gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, conn_handle,
start_handle, end_handle, uuid)) {
session_complete = true;
return null;
}
suspend {
self.frame = @frame();
}
return self.characteristic;
}
pub fn discover_128(self: *CharacteristicsDiscoverer, conn_handle: hci_con_handle_t,
start_handle: u16, end_handle: u16, uuid: [*c] const u8) ?gatt_client_characteristic_t {
if (!session_complete) return null;
self.frame = null;
self.characteristic = null;
session_complete = false;
if (0 != gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, conn_handle,
start_handle, end_handle, uuid)) {
session_complete = true;
return null;
}
suspend {
self.frame = @frame();
}
return self.characteristic;
}
};
pub var all_descriptors_discoverer: AllDescriptorsDiscoverer = undefined;
const AllDescriptorsDiscoverer = struct {
status: u8 = 0,
frame: ? (anyframe -> ?gatt_client_characteristic_descriptor_t) = null,
descriptor: gatt_client_characteristic_descriptor_t = undefined,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT => {
var result = gatt_event_all_characteristic_descriptors_query_result_parse(packet);
all_descriptors_discoverer.descriptor = result.*.descriptor;
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
all_descriptors_discoverer.status = gatt_event_query_complete_parse(packet).*.status;
},
else => { }
}
if (all_descriptors_discoverer.frame) |f| {
resume f;
}
}
pub fn start(self: *AllDescriptorsDiscoverer, conn_handle: hci_con_handle_t,
characteristic: *gatt_client_characteristic_t) bool {
if (!session_complete) return false;
self.frame = null;
session_complete = false;
if (0 == gatt_client_discover_characteristic_descriptors(callback,
conn_handle,
characteristic)) {
return !session_complete;
} else {
session_complete = true;
return false;
}
}
pub fn next(self: *AllDescriptorsDiscoverer) ?gatt_client_characteristic_descriptor_t {
if (session_complete) return null;
suspend {
self.frame = @frame();
}
if (session_complete) {
return null;
} else {
return self.descriptor;
}
}
};
pub var value_of_characteristic_reader: ValueOfCharacteristicReader = undefined;
extern fn gatt_helper_value_query_result_parse(packet: [*c] const u8, size: u16, value_size: [*c]u16) [*c] const u8;
const ValueOfCharacteristicReader = struct {
status: u8 = 0,
frame: ? (anyframe -> ?[*c] const u8) = null,
value_size: u16,
value: ?[*c] const u8,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT => {
value_of_characteristic_reader.value = gatt_helper_value_query_result_parse(packet, size,
&value_of_characteristic_reader.value_size);
},
GATT_EVENT_QUERY_COMPLETE => {
session_complete = true;
value_of_characteristic_reader.status = gatt_event_query_complete_parse(packet).*.status;
if (value_of_characteristic_reader.frame) |f| {
resume f;
}
},
else => { }
}
}
pub fn read(self: *ValueOfCharacteristicReader, conn_handle: hci_con_handle_t, value_handle: u16, value_size: *u16) ?[*c] const u8 {
value_size.* = 0;
self.value_size = 0;
self.value = null;
if (!session_complete) return null;
session_complete = false;
if (0 != gatt_client_read_value_of_characteristic_using_value_handle(
callback,
conn_handle,
value_handle)) {
session_complete = true;
return null;
}
if (session_complete) return null;
suspend {
self.frame = @frame();
}
self.frame = null;
value_size.* = self.value_size;
return self.value;
}
};
pub var value_of_characteristic_writer: ValueOfCharacteristicWriter = undefined;
const ValueOfCharacteristicWriter = struct {
status: u8 = 0,
frame: ? (anyframe -> bool) = null,
fn callback(packet_type: u8, _: u16, packet: [*c] const u8, size: u16) callconv(.C) void {
switch (packet[0]) {
GATT_EVENT_QUERY_COMPLETE => {
value_of_characteristic_writer.status = gatt_event_query_complete_parse(packet).*.status;
if (value_of_characteristic_writer.frame) |f| {
resume f;
}
},
else => { }
}
}
pub fn write(self: *ValueOfCharacteristicWriter, conn_handle: hci_con_handle_t, value_handle: u16,
value_size: u16, value: [*c] u8) bool {
if (!session_complete) return false;
session_complete = false;
if (0 != gatt_client_write_value_of_characteristic(
callback,
conn_handle,
value_handle,
value_size,
value)) {
session_complete = true;
return false;
}
if (session_complete) return false;
suspend {
self.frame = @frame();
}
self.frame = null;
return self.status == 0;
}
};
|
examples-gcc/central_fota/src/gatt_client_async.zig
|
const std = @import("std");
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
const Writer = std.io.Writer;
const Dir = std.fs.Dir;
const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES;
const AccessError = std.os.AccessError;
const Findup = struct { program: []u8, target: ?[]u8, cwd: Dir, printHelp: bool, printVersion: bool };
const FindupError = error{NoFileSpecified};
const VERSION = "findup 1.1-rc\n";
const USAGE =
\\USAGE:
\\ findup FILE
\\
\\FLAGS:
\\ -h, --help Prints help information
\\ -V, --version Prints version information
\\
\\Finds a directory containing FILE. Tested by filename with exact string equality. Starts searching at the current working directory and recurses "up" through parent directories.
\\
\\The first directory containing FILE will be printed. If no directory contains FILE, nothing is printed and the program exits with an exit code of 1.
\\
;
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var alloc = arena.allocator();
defer arena.deinit();
var buf: [MAX_PATH_BYTES]u8 = undefined;
const findup = initFindup(alloc) catch |err| {
try stderr.print("ERROR: {e}\n{s}", .{ err, USAGE });
std.os.exit(1);
};
if (findup.printHelp) {
try stdout.print("{s}\n{s}", .{ VERSION, USAGE });
std.os.exit(0);
} else if (findup.printVersion) {
try stdout.print(VERSION, .{});
std.os.exit(0);
}
const target = findup.target.?;
var cwd = findup.cwd;
const result = while (true) {
var cwdStr = try dirStr(cwd, buf[0..]);
if (try fileExists(cwd, target)) break cwdStr;
if (std.mem.eql(u8, "/", cwdStr)) break null;
try std.os.chdir("..");
cwd = std.fs.cwd();
} else unreachable;
if (result == null) std.os.exit(1);
try stdout.print("{s}\n", .{result.?});
}
fn initFindup(alloc: std.mem.Allocator) anyerror!Findup {
var args = std.process.args();
const program = try args.next(alloc).?;
const maybeTarget = args.next(alloc);
const target = if (maybeTarget == null) return FindupError.NoFileSpecified else try maybeTarget.?;
const cwd = std.fs.cwd();
var printHelp = std.mem.eql(u8, "-h", target) or std.mem.eql(u8, "--help", target);
var printVersion = std.mem.eql(u8, "-V", target) or std.mem.eql(u8, "--version", target);
return Findup{ .program = program, .target = target, .cwd = cwd, .printHelp = printHelp, .printVersion = printVersion };
}
fn dirStr(dir: Dir, buf: []u8) anyerror![]u8 {
return try dir.realpath(".", buf);
}
fn fileExists(dir: Dir, filename: []const u8) AccessError!bool {
dir.access(filename, .{}) catch |err| {
return switch (err) {
AccessError.FileNotFound => false,
else => err,
};
};
return true;
}
|
src/main.zig
|
const std = @import("std");
const index = @import("../index.zig");
const events = @import("events");
const waitpid = @import("waitpid");
const WaitResult = waitpid.WaitResult;
const Status = struct {
const normal = try waitpid.interpret_status(34175);
const exit = try waitpid.interpret_status(0);
// these are related to clone andmaybe futex;
const stop = try waitpid.interpret_status(4991);
// TODO find difference in how these numbers are generated,
// and what they mean.
// They both end up as sigtrap,
// but what other information do they contain?
const sigtrap = try waitpid.interpret_status(198015);
const sigtrap2 = try waitpid.interpret_status(66943);
};
const EventInfo = struct {
wait_result: WaitResult, // pid: int, status: int
syscall: std.os.SYS,
expected_action: events.EventAction,
};
test "clone and futex" {
const allocator = std.testing.allocator;
var tmap = events.TraceeMap.init(allocator);
defer tmap.deinit();
var context = events.Context{ .pid = undefined, .registers = undefined };
const inspections = events.Inspections{
.calls = &[_]std.os.SYS{ .fork, .getpid },
};
const test_events = [_]EventInfo{
.{ .wait_result = .{ .pid = 2, .status = Status.normal }, .syscall = .clone, .expected_action = .INSPECT },
.{ .wait_result = .{ .pid = 2, .status = Status.sigtrap2 }, .syscall = .clone, .expected_action = .CONT },
.{ .wait_result = .{ .pid = 3, .status = Status.stop }, .syscall = .clone, .expected_action = .CONT },
.{ .wait_result = .{ .pid = 2, .status = Status.normal }, .syscall = .wait4, .expected_action = .NORMAL },
};
for (test_events) |ei| {
// std.debug.warn("ei: {}\n", .{ei});
// Set orig_rax result of future "ptrace.getregs()" calls.
index.ptrace.orig_rax = @enumToInt(ei.syscall);
const action = try events.handle_wait_result(ei.wait_result, &tmap, &context, inspections);
if (action == .INSPECT) {
try events.resume_from_inspection(&tmap, context.pid);
}
std.testing.expectEqual(ei.expected_action, action);
std.testing.expectEqual(@enumToInt(ei.syscall), context.registers.syscall);
std.testing.expectEqual(ei.wait_result.pid, context.pid);
}
}
// TODO
// Check out Group-stop man page, especially the PTRACE_LISTEN portion.
// Also from man page of ptrace(2)
// PTRACE_EVENT stops
// If the tracer sets PTRACE_O_TRACE_* options, the tracee will enter ptrace-stops called PTRACE_EVENT stops.
//
// PTRACE_EVENT stops are observed by the tracer as waitpid(2) returning with WIFSTOPPED(status), and WSTOPSIG(status) returns SIGTRAP. An additional bit is set in the
// higher byte of the status word: the value status>>8 will be
//
// (SIGTRAP | PTRACE_EVENT_foo << 8).
//
// The following events exist: [...]
//
// PTRACE_EVENT_FORK
// Stop before return from fork(2) or clone(2) with the exit signal set to SIGCHLD.
//
// PTRACE_EVENT_CLONE
// Stop before return from clone(2).
// We might not be adding tracee's to the tracee_map on clone/thread/etc
// This guess is based on .EXIT being returned by next_event when we clone.
// Either that, or we are not properly handling the clone call, possibly related to the above man page excerpt
// TODO
// Fix issue in multithreaded/multiprocess environment where program stalls
// Known states of occurrance:
// [12805] starting clone
// > [12805] has received signal Signal.trap
// > [12805] Resuming process without changing tracee state
// [12805] finished clone
// > [12806] has received signal Signal.stop
// > [12806] Resuming process without changing tracee state
// [12806] [... finish at least some work ...]
// [12805] starting futex
// ^C
// [12808] starting clone
// > [12808] has received signal Signal.trap
// > [12808] Resuming process without changing tracee state
// [12808] finished clone
// > [12809] has received signal Signal.stop
// > [12809] Resuming process without changing tracee state
// [12808] starting futex // This is where, I suspect, main thread waits on alt thread. Maybe alt thread has not properly started
// ^C
|
tests/src/events.zig
|
const clap = @import("clap");
const format = @import("format");
const it = @import("ziter");
const std = @import("std");
const ston = @import("ston");
const util = @import("util");
const debug = std.debug;
const fmt = std.fmt;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const log = std.log;
const math = std.math;
const mem = std.mem;
const os = std.os;
const rand = std.rand;
const testing = std.testing;
const Program = @This();
allocator: mem.Allocator,
options: struct {
seed: u64,
same_total_stats: bool,
follow_evos: bool,
},
pokemons: Pokemons = Pokemons{},
pub const main = util.generateMain(Program);
pub const version = "0.0.0";
pub const description =
\\Randomizes Pokémon stats.
\\
;
pub const params = &[_]clap.Param(clap.Help){
clap.parseParam("-f, --follow-evos Evolution will use the none evolved form as a base for its own stats. ") catch unreachable,
clap.parseParam("-h, --help Display this help text and exit. ") catch unreachable,
clap.parseParam("-s, --seed <INT> The seed to use for random numbers. A random seed will be picked if this is not specified.") catch unreachable,
clap.parseParam("-t, --same-total-stats Pokémons will have the same total stats after randomization. ") catch unreachable,
clap.parseParam("-v, --version Output version information and exit. ") catch unreachable,
};
pub fn init(allocator: mem.Allocator, args: anytype) !Program {
return Program{
.allocator = allocator,
.options = .{
.seed = try util.getSeed(args),
.same_total_stats = args.flag("--same-total-stats"),
.follow_evos = args.flag("--follow-evos"),
},
};
}
pub fn run(
program: *Program,
comptime Reader: type,
comptime Writer: type,
stdio: util.CustomStdIoStreams(Reader, Writer),
) anyerror!void {
try format.io(program.allocator, stdio.in, stdio.out, program, useGame);
program.randomize();
try program.output(stdio.out);
}
fn output(program: *Program, writer: anytype) !void {
for (program.pokemons.values()) |pokemon, i| {
const species = program.pokemons.keys()[i];
inline for (@typeInfo(format.Stats(u8)).Union.fields) |field, j| {
if (pokemon.output[j]) {
try ston.serialize(writer, .{ .pokemons = ston.index(species, .{
.stats = ston.field(field.name, pokemon.stats[j]),
}) });
}
}
}
}
fn useGame(program: *Program, parsed: format.Game) !void {
const allocator = program.allocator;
switch (parsed) {
.pokemons => |mons| {
const pokemon = (try program.pokemons.getOrPutValue(allocator, mons.index, .{}))
.value_ptr;
switch (mons.value) {
.stats => |stats| {
switch (stats) {
.hp => |hp| pokemon.stats[0] = hp,
.attack => |attack| pokemon.stats[1] = attack,
.defense => |defense| pokemon.stats[2] = defense,
.speed => |speed| pokemon.stats[3] = speed,
.sp_attack => |sp_attack| pokemon.stats[4] = sp_attack,
.sp_defense => |sp_defense| pokemon.stats[5] = sp_defense,
}
pokemon.output[@enumToInt(stats)] = true;
return;
},
.evos => |evos| switch (evos.value) {
.target => |target| {
const evo_from = (try program.pokemons.getOrPutValue(
allocator,
target,
.{},
)).value_ptr;
_ = try evo_from.evolves_from.put(allocator, mons.index, {});
return error.DidNotConsumeData;
},
.method,
.param,
=> return error.DidNotConsumeData,
},
.types,
.catch_rate,
.base_exp_yield,
.ev_yield,
.items,
.gender_ratio,
.egg_cycles,
.base_friendship,
.growth_rate,
.egg_groups,
.abilities,
.color,
.moves,
.tms,
.hms,
.name,
.pokedex_entry,
=> return error.DidNotConsumeData,
}
},
.version,
.game_title,
.gamecode,
.instant_text,
.starters,
.text_delays,
.trainers,
.moves,
.abilities,
.types,
.tms,
.hms,
.items,
.pokedex,
.maps,
.wild_pokemons,
.static_pokemons,
.given_pokemons,
.pokeball_items,
.hidden_hollows,
.text,
=> return error.DidNotConsumeData,
}
unreachable;
}
fn randomize(program: *Program) void {
const random = rand.DefaultPrng.init(program.options.seed).random();
for (program.pokemons.values()) |*pokemon| {
const old_total = it.fold(&pokemon.stats, @as(usize, 0), foldu8);
const max_total = pokemon.stats.len * math.maxInt(u8);
const new_random_total = random.intRangeAtMost(u64, 0, max_total);
const new_total = if (program.options.same_total_stats) old_total else new_random_total;
var weights: [pokemon.stats.len]f32 = undefined;
for (weights) |*w|
w.* = random.float(f32);
randomWithinSum(random, u8, &pokemon.stats, &weights, new_total);
}
if (!program.options.follow_evos)
return;
for (program.pokemons.values()) |*pokemon, i| {
const species = program.pokemons.keys()[i];
program.randomizeFromChildren(random, pokemon, species);
}
}
fn randomizeFromChildren(
program: *Program,
random: rand.Random,
pokemon: *Pokemon,
curr: usize,
) void {
if (pokemon.evolves_from.count() == 0)
return;
// Get the average stats of all the prevolutions
var stats = [_]u64{0} ** Pokemon.stats;
for (pokemon.evolves_from.values()) |_, i| {
const key = pokemon.evolves_from.keys()[i];
// If prevolution == curr, then we have a cycle.
if (key == curr)
continue;
const p = program.pokemons.getEntry(key) orelse unreachable;
// We should randomize prevolution by the same rules.
program.randomizeFromChildren(random, p.value_ptr, curr);
for (p.value_ptr.stats) |stat, j|
stats[j] += stat;
}
// Average calculated here
var average = [_]u8{0} ** Pokemon.stats;
for (average) |*stat, i| {
stat.* = math.cast(u8, stats[i] / math.max(pokemon.evolves_from.count(), 1)) catch
math.maxInt(u8);
}
const old_total = it.fold(&pokemon.stats, @as(usize, 0), foldu8);
const average_total = it.fold(&average, @as(usize, 0), foldu8);
const max_total = pokemon.stats.len * math.maxInt(u8);
const new_random_total = random.intRangeAtMost(u64, average_total, max_total);
const new_total = if (program.options.same_total_stats) old_total else new_random_total;
pokemon.stats = average;
var weights: [pokemon.stats.len]f32 = undefined;
for (weights) |*w|
w.* = random.float(f32);
randomUntilSum(random, u8, &pokemon.stats, &weights, new_total);
// After this, the Pokémons stats should be equal or above the average
for (average) |_, i|
debug.assert(average[i] <= pokemon.stats[i]);
}
fn randomWithinSum(
random: rand.Random,
comptime T: type,
buf: []T,
weights: []const f32,
sum: u64,
) void {
mem.set(T, buf, 0);
randomUntilSum(random, T, buf, weights, sum);
}
fn randomUntilSum(
random: rand.Random,
comptime T: type,
buf: []T,
weights: []const f32,
sum: u64,
) void {
debug.assert(buf.len == weights.len);
const curr = it.fold(buf, @as(usize, 0), foldu8);
const max = math.min(sum, buf.len * math.maxInt(T));
if (max < curr)
return;
const missing = max - curr;
const total_weigth = it.fold(weights, @as(f64, 0), foldf32);
for (buf) |*item, i| {
const to_add_f = @intToFloat(f64, missing) * (weights[i] / total_weigth);
const to_add_max = math.min(to_add_f, math.maxInt(u8));
item.* +|= @floatToInt(u8, to_add_max);
}
while (it.fold(buf, @as(usize, 0), foldu8) < max) {
const item = util.random.item(random, buf).?;
item.* +|= 1;
}
}
fn foldu8(a: usize, b: u8) usize {
return a + b;
}
fn foldf32(a: f64, b: f32) f64 {
return a + b;
}
const Evos = std.AutoArrayHashMapUnmanaged(u16, void);
const Pokemons = std.AutoArrayHashMapUnmanaged(u16, Pokemon);
const Pokemon = struct {
stats: [stats]u8 = [_]u8{0} ** stats,
output: [stats]bool = [_]bool{false} ** stats,
evolves_from: Evos = Evos{},
const stats = @typeInfo(format.Stats(u8)).Union.fields.len;
};
test "tm35-rand-stats" {
const result_prefix =
\\.pokemons[0].evos[0].target=1
\\.pokemons[1].evos[0].target=2
\\
;
const test_string = result_prefix ++
\\.pokemons[0].stats.hp=10
\\.pokemons[0].stats.attack=10
\\.pokemons[0].stats.defense=10
\\.pokemons[0].stats.speed=10
\\.pokemons[0].stats.sp_attack=10
\\.pokemons[0].stats.sp_defense=10
\\.pokemons[1].stats.hp=20
\\.pokemons[1].stats.attack=20
\\.pokemons[1].stats.defense=20
\\.pokemons[1].stats.speed=20
\\.pokemons[1].stats.sp_attack=20
\\.pokemons[1].stats.sp_defense=20
\\.pokemons[2].stats.hp=30
\\.pokemons[2].stats.attack=30
\\.pokemons[2].stats.defense=30
\\.pokemons[2].stats.speed=30
\\.pokemons[2].stats.sp_attack=30
\\.pokemons[2].stats.sp_defense=30
\\.pokemons[3].stats.hp=40
\\.pokemons[3].stats.attack=40
\\.pokemons[3].stats.defense=40
\\.pokemons[3].stats.speed=40
\\.pokemons[3].stats.sp_attack=40
\\.pokemons[3].stats.sp_defense=40
\\
;
try util.testing.testProgram(Program, &[_][]const u8{"--seed=0"}, test_string, result_prefix ++
\\.pokemons[0].stats.hp=115
\\.pokemons[0].stats.attack=139
\\.pokemons[0].stats.defense=35
\\.pokemons[0].stats.speed=102
\\.pokemons[0].stats.sp_attack=51
\\.pokemons[0].stats.sp_defense=54
\\.pokemons[1].stats.hp=121
\\.pokemons[1].stats.attack=36
\\.pokemons[1].stats.defense=9
\\.pokemons[1].stats.speed=95
\\.pokemons[1].stats.sp_attack=113
\\.pokemons[1].stats.sp_defense=107
\\.pokemons[2].stats.hp=3
\\.pokemons[2].stats.attack=35
\\.pokemons[2].stats.defense=13
\\.pokemons[2].stats.speed=49
\\.pokemons[2].stats.sp_attack=56
\\.pokemons[2].stats.sp_defense=43
\\.pokemons[3].stats.hp=20
\\.pokemons[3].stats.attack=93
\\.pokemons[3].stats.defense=101
\\.pokemons[3].stats.speed=174
\\.pokemons[3].stats.sp_attack=181
\\.pokemons[3].stats.sp_defense=24
\\
);
try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--follow-evos" }, test_string, result_prefix ++
\\.pokemons[0].stats.hp=115
\\.pokemons[0].stats.attack=139
\\.pokemons[0].stats.defense=35
\\.pokemons[0].stats.speed=102
\\.pokemons[0].stats.sp_attack=51
\\.pokemons[0].stats.sp_defense=54
\\.pokemons[1].stats.hp=134
\\.pokemons[1].stats.attack=171
\\.pokemons[1].stats.defense=128
\\.pokemons[1].stats.speed=255
\\.pokemons[1].stats.sp_attack=203
\\.pokemons[1].stats.sp_defense=144
\\.pokemons[2].stats.hp=161
\\.pokemons[2].stats.attack=198
\\.pokemons[2].stats.defense=158
\\.pokemons[2].stats.speed=255
\\.pokemons[2].stats.sp_attack=236
\\.pokemons[2].stats.sp_defense=168
\\.pokemons[3].stats.hp=20
\\.pokemons[3].stats.attack=93
\\.pokemons[3].stats.defense=101
\\.pokemons[3].stats.speed=174
\\.pokemons[3].stats.sp_attack=181
\\.pokemons[3].stats.sp_defense=24
\\
);
try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--same-total-stats" }, test_string, result_prefix ++
\\.pokemons[0].stats.hp=14
\\.pokemons[0].stats.attack=17
\\.pokemons[0].stats.defense=4
\\.pokemons[0].stats.speed=12
\\.pokemons[0].stats.sp_attack=6
\\.pokemons[0].stats.sp_defense=7
\\.pokemons[1].stats.hp=31
\\.pokemons[1].stats.attack=9
\\.pokemons[1].stats.defense=3
\\.pokemons[1].stats.speed=23
\\.pokemons[1].stats.sp_attack=28
\\.pokemons[1].stats.sp_defense=26
\\.pokemons[2].stats.hp=68
\\.pokemons[2].stats.attack=2
\\.pokemons[2].stats.defense=24
\\.pokemons[2].stats.speed=10
\\.pokemons[2].stats.sp_attack=35
\\.pokemons[2].stats.sp_defense=41
\\.pokemons[3].stats.hp=73
\\.pokemons[3].stats.attack=6
\\.pokemons[3].stats.defense=8
\\.pokemons[3].stats.speed=39
\\.pokemons[3].stats.sp_attack=42
\\.pokemons[3].stats.sp_defense=72
\\
);
try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--same-total-stats", "--follow-evos" }, test_string, result_prefix ++
\\.pokemons[0].stats.hp=14
\\.pokemons[0].stats.attack=17
\\.pokemons[0].stats.defense=4
\\.pokemons[0].stats.speed=12
\\.pokemons[0].stats.sp_attack=6
\\.pokemons[0].stats.sp_defense=7
\\.pokemons[1].stats.hp=22
\\.pokemons[1].stats.attack=29
\\.pokemons[1].stats.defense=7
\\.pokemons[1].stats.speed=16
\\.pokemons[1].stats.sp_attack=19
\\.pokemons[1].stats.sp_defense=27
\\.pokemons[2].stats.hp=28
\\.pokemons[2].stats.attack=37
\\.pokemons[2].stats.defense=13
\\.pokemons[2].stats.speed=30
\\.pokemons[2].stats.sp_attack=34
\\.pokemons[2].stats.sp_defense=38
\\.pokemons[3].stats.hp=73
\\.pokemons[3].stats.attack=6
\\.pokemons[3].stats.defense=8
\\.pokemons[3].stats.speed=39
\\.pokemons[3].stats.sp_attack=42
\\.pokemons[3].stats.sp_defense=72
\\
);
}
|
src/randomizers/tm35-rand-stats.zig
|
pub const LIBID_Accessibility = Guid.initString("1ea4dbf0-3c3b-11cf-810c-00aa00389b71");
pub const CLSID_AccPropServices = Guid.initString("b5f8350b-0548-48b1-a6ee-88bd00b4a5e7");
pub const IIS_IsOleaccProxy = Guid.initString("902697fa-80e4-4560-802a-a13f22a64709");
pub const IIS_ControlAccessible = Guid.initString("38c682a6-9731-43f2-9fae-e901e641b101");
pub const ANRUS_PRIORITY_AUDIO_DYNAMIC_DUCK = @as(u32, 16);
pub const MSAA_MENU_SIG = @as(i32, -1441927155);
pub const PROPID_ACC_NAME = Guid.initString("608d3df8-8128-4aa7-a428-f55e49267291");
pub const PROPID_ACC_VALUE = Guid.initString("123fe443-211a-4615-9527-c45a7e93717a");
pub const PROPID_ACC_DESCRIPTION = Guid.initString("4d48dfe4-bd3f-491f-a648-492d6f20c588");
pub const PROPID_ACC_ROLE = Guid.initString("cb905ff2-7bd1-4c05-b3c8-e6c241364d70");
pub const PROPID_ACC_STATE = Guid.initString("a8d4d5b0-0a21-42d0-a5c0-514e984f457b");
pub const PROPID_ACC_HELP = Guid.initString("c831e11f-44db-4a99-9768-cb8f978b7231");
pub const PROPID_ACC_KEYBOARDSHORTCUT = Guid.initString("7d9bceee-7d1e-4979-9382-5180f4172c34");
pub const PROPID_ACC_DEFAULTACTION = Guid.initString("180c072b-c27f-43c7-9922-f63562a4632b");
pub const PROPID_ACC_HELPTOPIC = Guid.initString("787d1379-8ede-440b-8aec-11f7bf9030b3");
pub const PROPID_ACC_FOCUS = Guid.initString("6eb335df-1c29-4127-b12c-dee9fd157f2b");
pub const PROPID_ACC_SELECTION = Guid.initString("b99d073c-d731-405b-9061-d95e8f842984");
pub const PROPID_ACC_PARENT = Guid.initString("474c22b6-ffc2-467a-b1b5-e958b4657330");
pub const PROPID_ACC_NAV_UP = Guid.initString("016e1a2b-1a4e-4767-8612-3386f66935ec");
pub const PROPID_ACC_NAV_DOWN = Guid.initString("031670ed-3cdf-48d2-9613-138f2dd8a668");
pub const PROPID_ACC_NAV_LEFT = Guid.initString("228086cb-82f1-4a39-8705-dcdc0fff92f5");
pub const PROPID_ACC_NAV_RIGHT = Guid.initString("cd211d9f-e1cb-4fe5-a77c-920b884d095b");
pub const PROPID_ACC_NAV_PREV = Guid.initString("776d3891-c73b-4480-b3f6-076a16a15af6");
pub const PROPID_ACC_NAV_NEXT = Guid.initString("1cdc5455-8cd9-4c92-a371-3939a2fe3eee");
pub const PROPID_ACC_NAV_FIRSTCHILD = Guid.initString("cfd02558-557b-4c67-84f9-2a09fce40749");
pub const PROPID_ACC_NAV_LASTCHILD = Guid.initString("302ecaa5-48d5-4f8d-b671-1a8d20a77832");
pub const PROPID_ACC_ROLEMAP = Guid.initString("f79acda2-140d-4fe6-8914-208476328269");
pub const PROPID_ACC_VALUEMAP = Guid.initString("da1c3d79-fc5c-420e-b399-9d1533549e75");
pub const PROPID_ACC_STATEMAP = Guid.initString("43946c5e-0ac0-4042-b525-07bbdbe17fa7");
pub const PROPID_ACC_DESCRIPTIONMAP = Guid.initString("1ff1435f-8a14-477b-b226-a0abe279975d");
pub const PROPID_ACC_DODEFAULTACTION = Guid.initString("1ba09523-2e3b-49a6-a059-59682a3c48fd");
pub const DISPID_ACC_PARENT = @as(i32, -5000);
pub const DISPID_ACC_CHILDCOUNT = @as(i32, -5001);
pub const DISPID_ACC_CHILD = @as(i32, -5002);
pub const DISPID_ACC_NAME = @as(i32, -5003);
pub const DISPID_ACC_VALUE = @as(i32, -5004);
pub const DISPID_ACC_DESCRIPTION = @as(i32, -5005);
pub const DISPID_ACC_ROLE = @as(i32, -5006);
pub const DISPID_ACC_STATE = @as(i32, -5007);
pub const DISPID_ACC_HELP = @as(i32, -5008);
pub const DISPID_ACC_HELPTOPIC = @as(i32, -5009);
pub const DISPID_ACC_KEYBOARDSHORTCUT = @as(i32, -5010);
pub const DISPID_ACC_FOCUS = @as(i32, -5011);
pub const DISPID_ACC_SELECTION = @as(i32, -5012);
pub const DISPID_ACC_DEFAULTACTION = @as(i32, -5013);
pub const DISPID_ACC_SELECT = @as(i32, -5014);
pub const DISPID_ACC_LOCATION = @as(i32, -5015);
pub const DISPID_ACC_NAVIGATE = @as(i32, -5016);
pub const DISPID_ACC_HITTEST = @as(i32, -5017);
pub const DISPID_ACC_DODEFAULTACTION = @as(i32, -5018);
pub const NAVDIR_MIN = @as(u32, 0);
pub const NAVDIR_UP = @as(u32, 1);
pub const NAVDIR_DOWN = @as(u32, 2);
pub const NAVDIR_LEFT = @as(u32, 3);
pub const NAVDIR_RIGHT = @as(u32, 4);
pub const NAVDIR_NEXT = @as(u32, 5);
pub const NAVDIR_PREVIOUS = @as(u32, 6);
pub const NAVDIR_FIRSTCHILD = @as(u32, 7);
pub const NAVDIR_LASTCHILD = @as(u32, 8);
pub const NAVDIR_MAX = @as(u32, 9);
pub const SELFLAG_NONE = @as(u32, 0);
pub const SELFLAG_TAKEFOCUS = @as(u32, 1);
pub const SELFLAG_TAKESELECTION = @as(u32, 2);
pub const SELFLAG_EXTENDSELECTION = @as(u32, 4);
pub const SELFLAG_ADDSELECTION = @as(u32, 8);
pub const SELFLAG_REMOVESELECTION = @as(u32, 16);
pub const SELFLAG_VALID = @as(u32, 31);
pub const STATE_SYSTEM_NORMAL = @as(u32, 0);
pub const STATE_SYSTEM_HASPOPUP = @as(u32, 1073741824);
pub const ROLE_SYSTEM_TITLEBAR = @as(u32, 1);
pub const ROLE_SYSTEM_MENUBAR = @as(u32, 2);
pub const ROLE_SYSTEM_SCROLLBAR = @as(u32, 3);
pub const ROLE_SYSTEM_GRIP = @as(u32, 4);
pub const ROLE_SYSTEM_SOUND = @as(u32, 5);
pub const ROLE_SYSTEM_CURSOR = @as(u32, 6);
pub const ROLE_SYSTEM_CARET = @as(u32, 7);
pub const ROLE_SYSTEM_ALERT = @as(u32, 8);
pub const ROLE_SYSTEM_WINDOW = @as(u32, 9);
pub const ROLE_SYSTEM_CLIENT = @as(u32, 10);
pub const ROLE_SYSTEM_MENUPOPUP = @as(u32, 11);
pub const ROLE_SYSTEM_MENUITEM = @as(u32, 12);
pub const ROLE_SYSTEM_TOOLTIP = @as(u32, 13);
pub const ROLE_SYSTEM_APPLICATION = @as(u32, 14);
pub const ROLE_SYSTEM_DOCUMENT = @as(u32, 15);
pub const ROLE_SYSTEM_PANE = @as(u32, 16);
pub const ROLE_SYSTEM_CHART = @as(u32, 17);
pub const ROLE_SYSTEM_DIALOG = @as(u32, 18);
pub const ROLE_SYSTEM_BORDER = @as(u32, 19);
pub const ROLE_SYSTEM_GROUPING = @as(u32, 20);
pub const ROLE_SYSTEM_SEPARATOR = @as(u32, 21);
pub const ROLE_SYSTEM_TOOLBAR = @as(u32, 22);
pub const ROLE_SYSTEM_STATUSBAR = @as(u32, 23);
pub const ROLE_SYSTEM_TABLE = @as(u32, 24);
pub const ROLE_SYSTEM_COLUMNHEADER = @as(u32, 25);
pub const ROLE_SYSTEM_ROWHEADER = @as(u32, 26);
pub const ROLE_SYSTEM_COLUMN = @as(u32, 27);
pub const ROLE_SYSTEM_ROW = @as(u32, 28);
pub const ROLE_SYSTEM_CELL = @as(u32, 29);
pub const ROLE_SYSTEM_LINK = @as(u32, 30);
pub const ROLE_SYSTEM_HELPBALLOON = @as(u32, 31);
pub const ROLE_SYSTEM_CHARACTER = @as(u32, 32);
pub const ROLE_SYSTEM_LIST = @as(u32, 33);
pub const ROLE_SYSTEM_LISTITEM = @as(u32, 34);
pub const ROLE_SYSTEM_OUTLINE = @as(u32, 35);
pub const ROLE_SYSTEM_OUTLINEITEM = @as(u32, 36);
pub const ROLE_SYSTEM_PAGETAB = @as(u32, 37);
pub const ROLE_SYSTEM_PROPERTYPAGE = @as(u32, 38);
pub const ROLE_SYSTEM_INDICATOR = @as(u32, 39);
pub const ROLE_SYSTEM_GRAPHIC = @as(u32, 40);
pub const ROLE_SYSTEM_STATICTEXT = @as(u32, 41);
pub const ROLE_SYSTEM_TEXT = @as(u32, 42);
pub const ROLE_SYSTEM_PUSHBUTTON = @as(u32, 43);
pub const ROLE_SYSTEM_CHECKBUTTON = @as(u32, 44);
pub const ROLE_SYSTEM_RADIOBUTTON = @as(u32, 45);
pub const ROLE_SYSTEM_COMBOBOX = @as(u32, 46);
pub const ROLE_SYSTEM_DROPLIST = @as(u32, 47);
pub const ROLE_SYSTEM_PROGRESSBAR = @as(u32, 48);
pub const ROLE_SYSTEM_DIAL = @as(u32, 49);
pub const ROLE_SYSTEM_HOTKEYFIELD = @as(u32, 50);
pub const ROLE_SYSTEM_SLIDER = @as(u32, 51);
pub const ROLE_SYSTEM_SPINBUTTON = @as(u32, 52);
pub const ROLE_SYSTEM_DIAGRAM = @as(u32, 53);
pub const ROLE_SYSTEM_ANIMATION = @as(u32, 54);
pub const ROLE_SYSTEM_EQUATION = @as(u32, 55);
pub const ROLE_SYSTEM_BUTTONDROPDOWN = @as(u32, 56);
pub const ROLE_SYSTEM_BUTTONMENU = @as(u32, 57);
pub const ROLE_SYSTEM_BUTTONDROPDOWNGRID = @as(u32, 58);
pub const ROLE_SYSTEM_WHITESPACE = @as(u32, 59);
pub const ROLE_SYSTEM_PAGETABLIST = @as(u32, 60);
pub const ROLE_SYSTEM_CLOCK = @as(u32, 61);
pub const ROLE_SYSTEM_SPLITBUTTON = @as(u32, 62);
pub const ROLE_SYSTEM_IPADDRESS = @as(u32, 63);
pub const ROLE_SYSTEM_OUTLINEBUTTON = @as(u32, 64);
pub const UIA_E_ELEMENTNOTENABLED = @as(u32, 2147746304);
pub const UIA_E_ELEMENTNOTAVAILABLE = @as(u32, 2147746305);
pub const UIA_E_NOCLICKABLEPOINT = @as(u32, 2147746306);
pub const UIA_E_PROXYASSEMBLYNOTLOADED = @as(u32, 2147746307);
pub const UIA_E_NOTSUPPORTED = @as(u32, 2147746308);
pub const UIA_E_INVALIDOPERATION = @as(u32, 2148734217);
pub const UIA_E_TIMEOUT = @as(u32, 2148734213);
pub const UiaAppendRuntimeId = @as(u32, 3);
pub const UiaRootObjectId = @as(i32, -25);
pub const RuntimeId_Property_GUID = Guid.initString("a39eebfa-7fba-4c89-b4d4-b99e2de7d160");
pub const BoundingRectangle_Property_GUID = Guid.initString("7bbfe8b2-3bfc-48dd-b729-c794b846e9a1");
pub const ProcessId_Property_GUID = Guid.initString("40499998-9c31-4245-a403-87320e59eaf6");
pub const ControlType_Property_GUID = Guid.initString("ca774fea-28ac-4bc2-94ca-acec6d6c10a3");
pub const LocalizedControlType_Property_GUID = Guid.initString("8763404f-a1bd-452a-89c4-3f01d3833806");
pub const Name_Property_GUID = Guid.initString("c3a6921b-4a99-44f1-bca6-61187052c431");
pub const AcceleratorKey_Property_GUID = Guid.initString("514865df-2557-4cb9-aeed-6ced084ce52c");
pub const AccessKey_Property_GUID = Guid.initString("06827b12-a7f9-4a15-917c-ffa5ad3eb0a7");
pub const HasKeyboardFocus_Property_GUID = Guid.initString("cf8afd39-3f46-4800-9656-b2bf12529905");
pub const IsKeyboardFocusable_Property_GUID = Guid.initString("f7b8552a-0859-4b37-b9cb-51e72092f29f");
pub const IsEnabled_Property_GUID = Guid.initString("2109427f-da60-4fed-bf1b-264bdce6eb3a");
pub const AutomationId_Property_GUID = Guid.initString("c82c0500-b60e-4310-a267-303c531f8ee5");
pub const ClassName_Property_GUID = Guid.initString("157b7215-894f-4b65-84e2-aac0da08b16b");
pub const HelpText_Property_GUID = Guid.initString("08555685-0977-45c7-a7a6-abaf5684121a");
pub const ClickablePoint_Property_GUID = Guid.initString("0196903b-b203-4818-a9f3-f08e675f2341");
pub const Culture_Property_GUID = Guid.initString("e2d74f27-3d79-4dc2-b88b-3044963a8afb");
pub const IsControlElement_Property_GUID = Guid.initString("95f35085-abcc-4afd-a5f4-dbb46c230fdb");
pub const IsContentElement_Property_GUID = Guid.initString("4bda64a8-f5d8-480b-8155-ef2e89adb672");
pub const LabeledBy_Property_GUID = Guid.initString("e5b8924b-fc8a-4a35-8031-cf78ac43e55e");
pub const IsPassword_Property_GUID = Guid.initString("e8482eb1-687c-497b-bebc-03be53ec1454");
pub const NewNativeWindowHandle_Property_GUID = Guid.initString("5196b33b-380a-4982-95e1-91f3ef60e024");
pub const ItemType_Property_GUID = Guid.initString("cdda434d-6222-413b-a68a-325dd1d40f39");
pub const IsOffscreen_Property_GUID = Guid.initString("03c3d160-db79-42db-a2ef-1c231eede507");
pub const Orientation_Property_GUID = Guid.initString("a01eee62-3884-4415-887e-678ec21e39ba");
pub const FrameworkId_Property_GUID = Guid.initString("dbfd9900-7e1a-4f58-b61b-7063120f773b");
pub const IsRequiredForForm_Property_GUID = Guid.initString("4f5f43cf-59fb-4bde-a270-602e5e1141e9");
pub const ItemStatus_Property_GUID = Guid.initString("51de0321-3973-43e7-8913-0b08e813c37f");
pub const AriaRole_Property_GUID = Guid.initString("dd207b95-be4a-4e0d-b727-63ace94b6916");
pub const AriaProperties_Property_GUID = Guid.initString("4213678c-e025-4922-beb5-e43ba08e6221");
pub const IsDataValidForForm_Property_GUID = Guid.initString("445ac684-c3fc-4dd9-acf8-845a579296ba");
pub const ControllerFor_Property_GUID = Guid.initString("51124c8a-a5d2-4f13-9be6-7fa8ba9d3a90");
pub const DescribedBy_Property_GUID = Guid.initString("7c5865b8-9992-40fd-8db0-6bf1d317f998");
pub const FlowsTo_Property_GUID = Guid.initString("e4f33d20-559a-47fb-a830-f9cb4ff1a70a");
pub const ProviderDescription_Property_GUID = Guid.initString("dca5708a-c16b-4cd9-b889-beb16a804904");
pub const OptimizeForVisualContent_Property_GUID = Guid.initString("6a852250-c75a-4e5d-b858-e381b0f78861");
pub const IsDockPatternAvailable_Property_GUID = Guid.initString("2600a4c4-2ff8-4c96-ae31-8fe619a13c6c");
pub const IsExpandCollapsePatternAvailable_Property_GUID = Guid.initString("929d3806-5287-4725-aa16-222afc63d595");
pub const IsGridItemPatternAvailable_Property_GUID = Guid.initString("5a43e524-f9a2-4b12-84c8-b48a3efedd34");
pub const IsGridPatternAvailable_Property_GUID = Guid.initString("5622c26c-f0ef-4f3b-97cb-714c0868588b");
pub const IsInvokePatternAvailable_Property_GUID = Guid.initString("4e725738-8364-4679-aa6c-f3f41931f750");
pub const IsMultipleViewPatternAvailable_Property_GUID = Guid.initString("ff0a31eb-8e25-469d-8d6e-e771a27c1b90");
pub const IsRangeValuePatternAvailable_Property_GUID = Guid.initString("fda4244a-eb4d-43ff-b5ad-ed36d373ec4c");
pub const IsScrollPatternAvailable_Property_GUID = Guid.initString("3ebb7b4a-828a-4b57-9d22-2fea1632ed0d");
pub const IsScrollItemPatternAvailable_Property_GUID = Guid.initString("1cad1a05-0927-4b76-97e1-0fcdb209b98a");
pub const IsSelectionItemPatternAvailable_Property_GUID = Guid.initString("8becd62d-0bc3-4109-bee2-8e6715290e68");
pub const IsSelectionPatternAvailable_Property_GUID = Guid.initString("f588acbe-c769-4838-9a60-2686dc1188c4");
pub const IsTablePatternAvailable_Property_GUID = Guid.initString("cb83575f-45c2-4048-9c76-159715a139df");
pub const IsTableItemPatternAvailable_Property_GUID = Guid.initString("eb36b40d-8ea4-489b-a013-e60d5951fe34");
pub const IsTextPatternAvailable_Property_GUID = Guid.initString("fbe2d69d-aff6-4a45-82e2-fc92a82f5917");
pub const IsTogglePatternAvailable_Property_GUID = Guid.initString("78686d53-fcd0-4b83-9b78-5832ce63bb5b");
pub const IsTransformPatternAvailable_Property_GUID = Guid.initString("a7f78804-d68b-4077-a5c6-7a5ea1ac31c5");
pub const IsValuePatternAvailable_Property_GUID = Guid.initString("0b5020a7-2119-473b-be37-5ceb98bbfb22");
pub const IsWindowPatternAvailable_Property_GUID = Guid.initString("e7a57bb1-5888-4155-98dc-b422fd57f2bc");
pub const IsLegacyIAccessiblePatternAvailable_Property_GUID = Guid.initString("d8ebd0c7-929a-4ee7-8d3a-d3d94413027b");
pub const IsItemContainerPatternAvailable_Property_GUID = Guid.initString("624b5ca7-fe40-4957-a019-20c4cf11920f");
pub const IsVirtualizedItemPatternAvailable_Property_GUID = Guid.initString("302cb151-2ac8-45d6-977b-d2b3a5a53f20");
pub const IsSynchronizedInputPatternAvailable_Property_GUID = Guid.initString("75d69cc5-d2bf-4943-876e-b45b62a6cc66");
pub const IsObjectModelPatternAvailable_Property_GUID = Guid.initString("6b21d89b-2841-412f-8ef2-15ca952318ba");
pub const IsAnnotationPatternAvailable_Property_GUID = Guid.initString("0b5b3238-6d5c-41b6-bcc4-5e807f6551c4");
pub const IsTextPattern2Available_Property_GUID = Guid.initString("41cf921d-e3f1-4b22-9c81-e1c3ed331c22");
pub const IsTextEditPatternAvailable_Property_GUID = Guid.initString("7843425c-8b32-484c-9ab5-e3200571ffda");
pub const IsCustomNavigationPatternAvailable_Property_GUID = Guid.initString("8f8e80d4-2351-48e0-874a-54aa7313889a");
pub const IsStylesPatternAvailable_Property_GUID = Guid.initString("27f353d3-459c-4b59-a490-50611dacafb5");
pub const IsSpreadsheetPatternAvailable_Property_GUID = Guid.initString("6ff43732-e4b4-4555-97bc-ecdbbc4d1888");
pub const IsSpreadsheetItemPatternAvailable_Property_GUID = Guid.initString("9fe79b2a-2f94-43fd-996b-549e316f4acd");
pub const IsTransformPattern2Available_Property_GUID = Guid.initString("25980b4b-be04-4710-ab4a-fda31dbd2895");
pub const IsTextChildPatternAvailable_Property_GUID = Guid.initString("559e65df-30ff-43b5-b5ed-5b283b80c7e9");
pub const IsDragPatternAvailable_Property_GUID = Guid.initString("e997a7b7-1d39-4ca7-be0f-277fcf5605cc");
pub const IsDropTargetPatternAvailable_Property_GUID = Guid.initString("0686b62e-8e19-4aaf-873d-384f6d3b92be");
pub const IsStructuredMarkupPatternAvailable_Property_GUID = Guid.initString("b0d4c196-2c0b-489c-b165-a405928c6f3d");
pub const IsPeripheral_Property_GUID = Guid.initString("da758276-7ed5-49d4-8e68-ecc9a2d300dd");
pub const PositionInSet_Property_GUID = Guid.initString("33d1dc54-641e-4d76-a6b1-13f341c1f896");
pub const SizeOfSet_Property_GUID = Guid.initString("1600d33c-3b9f-4369-9431-aa293f344cf1");
pub const Level_Property_GUID = Guid.initString("242ac529-cd36-400f-aad9-7876ef3af627");
pub const AnnotationTypes_Property_GUID = Guid.initString("64b71f76-53c4-4696-a219-20e940c9a176");
pub const AnnotationObjects_Property_GUID = Guid.initString("310910c8-7c6e-4f20-becd-4aaf6d191156");
pub const LandmarkType_Property_GUID = Guid.initString("454045f2-6f61-49f7-a4f8-b5f0cf82da1e");
pub const LocalizedLandmarkType_Property_GUID = Guid.initString("7ac81980-eafb-4fb2-bf91-f485bef5e8e1");
pub const FullDescription_Property_GUID = Guid.initString("0d4450ff-6aef-4f33-95dd-7befa72a4391");
pub const Value_Value_Property_GUID = Guid.initString("e95f5e64-269f-4a85-ba99-4092c3ea2986");
pub const Value_IsReadOnly_Property_GUID = Guid.initString("eb090f30-e24c-4799-a705-0d247bc037f8");
pub const RangeValue_Value_Property_GUID = Guid.initString("131f5d98-c50c-489d-abe5-ae220898c5f7");
pub const RangeValue_IsReadOnly_Property_GUID = Guid.initString("25fa1055-debf-4373-a79e-1f1a1908d3c4");
pub const RangeValue_Minimum_Property_GUID = Guid.initString("78cbd3b2-684d-4860-af93-d1f95cb022fd");
pub const RangeValue_Maximum_Property_GUID = Guid.initString("19319914-f979-4b35-a1a6-d37e05433473");
pub const RangeValue_LargeChange_Property_GUID = Guid.initString("a1f96325-3a3d-4b44-8e1f-4a46d9844019");
pub const RangeValue_SmallChange_Property_GUID = Guid.initString("81c2c457-3941-4107-9975-139760f7c072");
pub const Scroll_HorizontalScrollPercent_Property_GUID = Guid.initString("c7c13c0e-eb21-47ff-acc4-b5a3350f5191");
pub const Scroll_HorizontalViewSize_Property_GUID = Guid.initString("70c2e5d4-fcb0-4713-a9aa-af92ff79e4cd");
pub const Scroll_VerticalScrollPercent_Property_GUID = Guid.initString("6c8d7099-b2a8-4948-bff7-3cf9058bfefb");
pub const Scroll_VerticalViewSize_Property_GUID = Guid.initString("de6a2e22-d8c7-40c5-83ba-e5f681d53108");
pub const Scroll_HorizontallyScrollable_Property_GUID = Guid.initString("8b925147-28cd-49ae-bd63-f44118d2e719");
pub const Scroll_VerticallyScrollable_Property_GUID = Guid.initString("89164798-0068-4315-b89a-1e7cfbbc3dfc");
pub const Selection_Selection_Property_GUID = Guid.initString("aa6dc2a2-0e2b-4d38-96d5-34e470b81853");
pub const Selection_CanSelectMultiple_Property_GUID = Guid.initString("49d73da5-c883-4500-883d-8fcf8daf6cbe");
pub const Selection_IsSelectionRequired_Property_GUID = Guid.initString("b1ae4422-63fe-44e7-a5a5-a738c829b19a");
pub const Grid_RowCount_Property_GUID = Guid.initString("2a9505bf-c2eb-4fb6-b356-8245ae53703e");
pub const Grid_ColumnCount_Property_GUID = Guid.initString("fe96f375-44aa-4536-ac7a-2a75d71a3efc");
pub const GridItem_Row_Property_GUID = Guid.initString("6223972a-c945-4563-9329-fdc974af2553");
pub const GridItem_Column_Property_GUID = Guid.initString("c774c15c-62c0-4519-8bdc-47be573c8ad5");
pub const GridItem_RowSpan_Property_GUID = Guid.initString("4582291c-466b-4e93-8e83-3d1715ec0c5e");
pub const GridItem_ColumnSpan_Property_GUID = Guid.initString("583ea3f5-86d0-4b08-a6ec-2c5463ffc109");
pub const GridItem_Parent_Property_GUID = Guid.initString("9d912252-b97f-4ecc-8510-ea0e33427c72");
pub const Dock_DockPosition_Property_GUID = Guid.initString("6d67f02e-c0b0-4b10-b5b9-18d6ecf98760");
pub const ExpandCollapse_ExpandCollapseState_Property_GUID = Guid.initString("275a4c48-85a7-4f69-aba0-af157610002b");
pub const MultipleView_CurrentView_Property_GUID = Guid.initString("7a81a67a-b94f-4875-918b-65c8d2f998e5");
pub const MultipleView_SupportedViews_Property_GUID = Guid.initString("8d5db9fd-ce3c-4ae7-b788-400a3c645547");
pub const Window_CanMaximize_Property_GUID = Guid.initString("64fff53f-635d-41c1-950c-cb5adfbe28e3");
pub const Window_CanMinimize_Property_GUID = Guid.initString("b73b4625-5988-4b97-b4c2-a6fe6e78c8c6");
pub const Window_WindowVisualState_Property_GUID = Guid.initString("4ab7905f-e860-453e-a30a-f6431e5daad5");
pub const Window_WindowInteractionState_Property_GUID = Guid.initString("4fed26a4-0455-4fa2-b21c-c4da2db1ff9c");
pub const Window_IsModal_Property_GUID = Guid.initString("ff4e6892-37b9-4fca-8532-ffe674ecfeed");
pub const Window_IsTopmost_Property_GUID = Guid.initString("ef7d85d3-0937-4962-9241-b62345f24041");
pub const SelectionItem_IsSelected_Property_GUID = Guid.initString("f122835f-cd5f-43df-b79d-4b849e9e6020");
pub const SelectionItem_SelectionContainer_Property_GUID = Guid.initString("a4365b6e-9c1e-4b63-8b53-c2421dd1e8fb");
pub const Table_RowHeaders_Property_GUID = Guid.initString("d9e35b87-6eb8-4562-aac6-a8a9075236a8");
pub const Table_ColumnHeaders_Property_GUID = Guid.initString("aff1d72b-968d-42b1-b459-150b299da664");
pub const Table_RowOrColumnMajor_Property_GUID = Guid.initString("83be75c3-29fe-4a30-85e1-2a6277fd106e");
pub const TableItem_RowHeaderItems_Property_GUID = Guid.initString("b3f853a0-0574-4cd8-bcd7-ed5923572d97");
pub const TableItem_ColumnHeaderItems_Property_GUID = Guid.initString("967a56a3-74b6-431e-8de6-99c411031c58");
pub const Toggle_ToggleState_Property_GUID = Guid.initString("b23cdc52-22c2-4c6c-9ded-f5c422479ede");
pub const Transform_CanMove_Property_GUID = Guid.initString("1b75824d-208b-4fdf-bccd-f1f4e5741f4f");
pub const Transform_CanResize_Property_GUID = Guid.initString("bb98dca5-4c1a-41d4-a4f6-ebc128644180");
pub const Transform_CanRotate_Property_GUID = Guid.initString("10079b48-3849-476f-ac96-44a95c8440d9");
pub const LegacyIAccessible_ChildId_Property_GUID = Guid.initString("9a191b5d-9ef2-4787-a459-dcde885dd4e8");
pub const LegacyIAccessible_Name_Property_GUID = Guid.initString("caeb063d-40ae-4869-aa5a-1b8e5d666739");
pub const LegacyIAccessible_Value_Property_GUID = Guid.initString("b5c5b0b6-8217-4a77-97a5-190a85ed0156");
pub const LegacyIAccessible_Description_Property_GUID = Guid.initString("46448418-7d70-4ea9-9d27-b7e775cf2ad7");
pub const LegacyIAccessible_Role_Property_GUID = Guid.initString("6856e59f-cbaf-4e31-93e8-bcbf6f7e491c");
pub const LegacyIAccessible_State_Property_GUID = Guid.initString("df985854-2281-4340-ab9c-c60e2c5803f6");
pub const LegacyIAccessible_Help_Property_GUID = Guid.initString("94402352-161c-4b77-a98d-a872cc33947a");
pub const LegacyIAccessible_KeyboardShortcut_Property_GUID = Guid.initString("8f6909ac-00b8-4259-a41c-966266d43a8a");
pub const LegacyIAccessible_Selection_Property_GUID = Guid.initString("8aa8b1e0-0891-40cc-8b06-90d7d4166219");
pub const LegacyIAccessible_DefaultAction_Property_GUID = Guid.initString("3b331729-eaad-4502-b85f-92615622913c");
pub const Annotation_AnnotationTypeId_Property_GUID = Guid.initString("20ae484f-69ef-4c48-8f5b-c4938b206ac7");
pub const Annotation_AnnotationTypeName_Property_GUID = Guid.initString("9b818892-5ac9-4af9-aa96-f58a77b058e3");
pub const Annotation_Author_Property_GUID = Guid.initString("7a528462-9c5c-4a03-a974-8b307a9937f2");
pub const Annotation_DateTime_Property_GUID = Guid.initString("99b5ca5d-1acf-414b-a4d0-6b350b047578");
pub const Annotation_Target_Property_GUID = Guid.initString("b71b302d-2104-44ad-9c5c-092b4907d70f");
pub const Styles_StyleId_Property_GUID = Guid.initString("da82852f-3817-4233-82af-02279e72cc77");
pub const Styles_StyleName_Property_GUID = Guid.initString("1c12b035-05d1-4f55-9e8e-1489f3ff550d");
pub const Styles_FillColor_Property_GUID = Guid.initString("63eff97a-a1c5-4b1d-84eb-b765f2edd632");
pub const Styles_FillPatternStyle_Property_GUID = Guid.initString("81cf651f-482b-4451-a30a-e1545e554fb8");
pub const Styles_Shape_Property_GUID = Guid.initString("c71a23f8-778c-400d-8458-3b543e526984");
pub const Styles_FillPatternColor_Property_GUID = Guid.initString("939a59fe-8fbd-4e75-a271-ac4595195163");
pub const Styles_ExtendedProperties_Property_GUID = Guid.initString("f451cda0-ba0a-4681-b0b0-0dbdb53e58f3");
pub const SpreadsheetItem_Formula_Property_GUID = Guid.initString("e602e47d-1b47-4bea-87cf-3b0b0b5c15b6");
pub const SpreadsheetItem_AnnotationObjects_Property_GUID = Guid.initString("a3194c38-c9bc-4604-9396-ae3f9f457f7b");
pub const SpreadsheetItem_AnnotationTypes_Property_GUID = Guid.initString("c70c51d0-d602-4b45-afbc-b4712b96d72b");
pub const Transform2_CanZoom_Property_GUID = Guid.initString("f357e890-a756-4359-9ca6-86702bf8f381");
pub const LiveSetting_Property_GUID = Guid.initString("c12bcd8e-2a8e-4950-8ae7-3625111d58eb");
pub const Drag_IsGrabbed_Property_GUID = Guid.initString("45f206f3-75cc-4cca-a9b9-fcdfb982d8a2");
pub const Drag_GrabbedItems_Property_GUID = Guid.initString("77c1562c-7b86-4b21-9ed7-3cefda6f4c43");
pub const Drag_DropEffect_Property_GUID = Guid.initString("646f2779-48d3-4b23-8902-4bf100005df3");
pub const Drag_DropEffects_Property_GUID = Guid.initString("f5d61156-7ce6-49be-a836-9269dcec920f");
pub const DropTarget_DropTargetEffect_Property_GUID = Guid.initString("8bb75975-a0ca-4981-b818-87fc66e9509d");
pub const DropTarget_DropTargetEffects_Property_GUID = Guid.initString("bc1dd4ed-cb89-45f1-a592-e03b08ae790f");
pub const Transform2_ZoomLevel_Property_GUID = Guid.initString("eee29f1a-f4a2-4b5b-ac65-95cf93283387");
pub const Transform2_ZoomMinimum_Property_GUID = Guid.initString("742ccc16-4ad1-4e07-96fe-b122c6e6b22b");
pub const Transform2_ZoomMaximum_Property_GUID = Guid.initString("42ab6b77-ceb0-4eca-b82a-6cfa5fa1fc08");
pub const FlowsFrom_Property_GUID = Guid.initString("05c6844f-19de-48f8-95fa-880d5b0fd615");
pub const FillColor_Property_GUID = Guid.initString("6e0ec4d0-e2a8-4a56-9de7-953389933b39");
pub const OutlineColor_Property_GUID = Guid.initString("c395d6c0-4b55-4762-a073-fd303a634f52");
pub const FillType_Property_GUID = Guid.initString("c6fc74e4-8cb9-429c-a9e1-9bc4ac372b62");
pub const VisualEffects_Property_GUID = Guid.initString("e61a8565-aad9-46d7-9e70-4e8a8420d420");
pub const OutlineThickness_Property_GUID = Guid.initString("13e67cc7-dac2-4888-bdd3-375c62fa9618");
pub const CenterPoint_Property_GUID = Guid.initString("0cb00c08-540c-4edb-9445-26359ea69785");
pub const Rotation_Property_GUID = Guid.initString("767cdc7d-aec0-4110-ad32-30edd403492e");
pub const Size_Property_GUID = Guid.initString("2b5f761d-f885-4404-973f-9b1d98e36d8f");
pub const ToolTipOpened_Event_GUID = Guid.initString("3f4b97ff-2edc-451d-bca4-95a3188d5b03");
pub const ToolTipClosed_Event_GUID = Guid.initString("276d71ef-24a9-49b6-8e97-da98b401bbcd");
pub const StructureChanged_Event_GUID = Guid.initString("59977961-3edd-4b11-b13b-676b2a2a6ca9");
pub const MenuOpened_Event_GUID = Guid.initString("ebe2e945-66ca-4ed1-9ff8-2ad7df0a1b08");
pub const AutomationPropertyChanged_Event_GUID = Guid.initString("2527fba1-8d7a-4630-a4cc-e66315942f52");
pub const AutomationFocusChanged_Event_GUID = Guid.initString("b68a1f17-f60d-41a7-a3cc-b05292155fe0");
pub const ActiveTextPositionChanged_Event_GUID = Guid.initString("a5c09e9c-c77d-4f25-b491-e5bb7017cbd4");
pub const AsyncContentLoaded_Event_GUID = Guid.initString("5fdee11c-d2fa-4fb9-904e-5cbee894d5ef");
pub const MenuClosed_Event_GUID = Guid.initString("3cf1266e-1582-4041-acd7-88a35a965297");
pub const LayoutInvalidated_Event_GUID = Guid.initString("ed7d6544-a6bd-4595-9bae-3d28946cc715");
pub const Invoke_Invoked_Event_GUID = Guid.initString("dfd699f0-c915-49dd-b422-dde785c3d24b");
pub const SelectionItem_ElementAddedToSelectionEvent_Event_GUID = Guid.initString("3c822dd1-c407-4dba-91dd-79d4aed0aec6");
pub const SelectionItem_ElementRemovedFromSelectionEvent_Event_GUID = Guid.initString("097fa8a9-7079-41af-8b9c-0934d8305e5c");
pub const SelectionItem_ElementSelectedEvent_Event_GUID = Guid.initString("b9c7dbfb-4ebe-4532-aaf4-008cf647233c");
pub const Selection_InvalidatedEvent_Event_GUID = Guid.initString("cac14904-16b4-4b53-8e47-4cb1df267bb7");
pub const Text_TextSelectionChangedEvent_Event_GUID = Guid.initString("918edaa1-71b3-49ae-9741-79beb8d358f3");
pub const Text_TextChangedEvent_Event_GUID = Guid.initString("4a342082-f483-48c4-ac11-a84b435e2a84");
pub const Window_WindowOpened_Event_GUID = Guid.initString("d3e81d06-de45-4f2f-9633-de9e02fb65af");
pub const Window_WindowClosed_Event_GUID = Guid.initString("edf141f8-fa67-4e22-bbf7-944e05735ee2");
pub const MenuModeStart_Event_GUID = Guid.initString("18d7c631-166a-4ac9-ae3b-ef4b5420e681");
pub const MenuModeEnd_Event_GUID = Guid.initString("9ecd4c9f-80dd-47b8-8267-5aec06bb2cff");
pub const InputReachedTarget_Event_GUID = Guid.initString("93ed549a-0549-40f0-bedb-28e44f7de2a3");
pub const InputReachedOtherElement_Event_GUID = Guid.initString("ed201d8a-4e6c-415e-a874-2460c9b66ba8");
pub const InputDiscarded_Event_GUID = Guid.initString("7f36c367-7b18-417c-97e3-9d58ddc944ab");
pub const SystemAlert_Event_GUID = Guid.initString("d271545d-7a3a-47a7-8474-81d29a2451c9");
pub const LiveRegionChanged_Event_GUID = Guid.initString("102d5e90-e6a9-41b6-b1c5-a9b1929d9510");
pub const HostedFragmentRootsInvalidated_Event_GUID = Guid.initString("e6bdb03e-0921-4ec5-8dcf-eae877b0426b");
pub const Drag_DragStart_Event_GUID = Guid.initString("883a480b-3aa9-429d-95e4-d9c8d011f0dd");
pub const Drag_DragCancel_Event_GUID = Guid.initString("c3ede6fa-3451-4e0f-9e71-df9c280a4657");
pub const Drag_DragComplete_Event_GUID = Guid.initString("38e96188-ef1f-463e-91ca-3a7792c29caf");
pub const DropTarget_DragEnter_Event_GUID = Guid.initString("aad9319b-032c-4a88-961d-1cf579581e34");
pub const DropTarget_DragLeave_Event_GUID = Guid.initString("0f82eb15-24a2-4988-9217-de162aee272b");
pub const DropTarget_Dropped_Event_GUID = Guid.initString("622cead8-1edb-4a3d-abbc-be2211ff68b5");
pub const StructuredMarkup_CompositionComplete_Event_GUID = Guid.initString("c48a3c17-677a-4047-a68d-fc1257528aef");
pub const StructuredMarkup_Deleted_Event_GUID = Guid.initString("f9d0a020-e1c1-4ecf-b9aa-52efde7e41e1");
pub const StructuredMarkup_SelectionChanged_Event_GUID = Guid.initString("a7c815f7-ff9f-41c7-a3a7-ab6cbfdb4903");
pub const Invoke_Pattern_GUID = Guid.initString("d976c2fc-66ea-4a6e-b28f-c24c7546ad37");
pub const Selection_Pattern_GUID = Guid.initString("66e3b7e8-d821-4d25-8761-435d2c8b253f");
pub const Value_Pattern_GUID = Guid.initString("17faad9e-c877-475b-b933-77332779b637");
pub const RangeValue_Pattern_GUID = Guid.initString("18b00d87-b1c9-476a-bfbd-5f0bdb926f63");
pub const Scroll_Pattern_GUID = Guid.initString("895fa4b4-759d-4c50-8e15-03460672003c");
pub const ExpandCollapse_Pattern_GUID = Guid.initString("ae05efa2-f9d1-428a-834c-53a5c52f9b8b");
pub const Grid_Pattern_GUID = Guid.initString("260a2ccb-93a8-4e44-a4c1-3df397f2b02b");
pub const GridItem_Pattern_GUID = Guid.initString("f2d5c877-a462-4957-a2a5-2c96b303bc63");
pub const MultipleView_Pattern_GUID = Guid.initString("547a6ae4-113f-47c4-850f-db4dfa466b1d");
pub const Window_Pattern_GUID = Guid.initString("27901735-c760-4994-ad11-5919e606b110");
pub const SelectionItem_Pattern_GUID = Guid.initString("9bc64eeb-87c7-4b28-94bb-4d9fa437b6ef");
pub const Dock_Pattern_GUID = Guid.initString("9cbaa846-83c8-428d-827f-7e6063fe0620");
pub const Table_Pattern_GUID = Guid.initString("c415218e-a028-461e-aa92-8f925cf79351");
pub const TableItem_Pattern_GUID = Guid.initString("df1343bd-1888-4a29-a50c-b92e6de37f6f");
pub const Text_Pattern_GUID = Guid.initString("8615f05d-7de5-44fd-a679-2ca4b46033a8");
pub const Toggle_Pattern_GUID = Guid.initString("0b419760-e2f4-43ff-8c5f-9457c82b56e9");
pub const Transform_Pattern_GUID = Guid.initString("24b46fdb-587e-49f1-9c4a-d8e98b664b7b");
pub const ScrollItem_Pattern_GUID = Guid.initString("4591d005-a803-4d5c-b4d5-8d2800f906a7");
pub const LegacyIAccessible_Pattern_GUID = Guid.initString("54cc0a9f-3395-48af-ba8d-73f85690f3e0");
pub const ItemContainer_Pattern_GUID = Guid.initString("3d13da0f-8b9a-4a99-85fa-c5c9a69f1ed4");
pub const VirtualizedItem_Pattern_GUID = Guid.initString("f510173e-2e71-45e9-a6e5-62f6ed8289d5");
pub const SynchronizedInput_Pattern_GUID = Guid.initString("05c288a6-c47b-488b-b653-33977a551b8b");
pub const ObjectModel_Pattern_GUID = Guid.initString("3e04acfe-08fc-47ec-96bc-353fa3b34aa7");
pub const Annotation_Pattern_GUID = Guid.initString("f6c72ad7-356c-4850-9291-316f608a8c84");
pub const Text_Pattern2_GUID = Guid.initString("498479a2-5b22-448d-b6e4-647490860698");
pub const TextEdit_Pattern_GUID = Guid.initString("69f3ff89-5af9-4c75-9340-f2de292e4591");
pub const CustomNavigation_Pattern_GUID = Guid.initString("afea938a-621e-4054-bb2c-2f46114dac3f");
pub const Styles_Pattern_GUID = Guid.initString("1ae62655-da72-4d60-a153-e5aa6988e3bf");
pub const Spreadsheet_Pattern_GUID = Guid.initString("6a5b24c9-9d1e-4b85-9e44-c02e3169b10b");
pub const SpreadsheetItem_Pattern_GUID = Guid.initString("32cf83ff-f1a8-4a8c-8658-d47ba74e20ba");
pub const Tranform_Pattern2_GUID = Guid.initString("8afcfd07-a369-44de-988b-2f7ff49fb8a8");
pub const TextChild_Pattern_GUID = Guid.initString("7533cab7-3bfe-41ef-9e85-e2638cbe169e");
pub const Drag_Pattern_GUID = Guid.initString("c0bee21f-ccb3-4fed-995b-114f6e3d2728");
pub const DropTarget_Pattern_GUID = Guid.initString("0bcbec56-bd34-4b7b-9fd5-2659905ea3dc");
pub const StructuredMarkup_Pattern_GUID = Guid.initString("abbd0878-8665-4f5c-94fc-36e7d8bb706b");
pub const Button_Control_GUID = Guid.initString("5a78e369-c6a1-4f33-a9d7-79f20d0c788e");
pub const Calendar_Control_GUID = Guid.initString("8913eb88-00e5-46bc-8e4e-14a786e165a1");
pub const CheckBox_Control_GUID = Guid.initString("fb50f922-a3db-49c0-8bc3-06dad55778e2");
pub const ComboBox_Control_GUID = Guid.initString("54cb426c-2f33-4fff-aaa1-aef60dac5deb");
pub const Edit_Control_GUID = Guid.initString("6504a5c8-2c86-4f87-ae7b-1abddc810cf9");
pub const Hyperlink_Control_GUID = Guid.initString("8a56022c-b00d-4d15-8ff0-5b6b266e5e02");
pub const Image_Control_GUID = Guid.initString("2d3736e4-6b16-4c57-a962-f93260a75243");
pub const ListItem_Control_GUID = Guid.initString("7b3717f2-44d1-4a58-98a8-f12a9b8f78e2");
pub const List_Control_GUID = Guid.initString("9b149ee1-7cca-4cfc-9af1-cac7bddd3031");
pub const Menu_Control_GUID = Guid.initString("2e9b1440-0ea8-41fd-b374-c1ea6f503cd1");
pub const MenuBar_Control_GUID = Guid.initString("cc384250-0e7b-4ae8-95ae-a08f261b52ee");
pub const MenuItem_Control_GUID = Guid.initString("f45225d3-d0a0-49d8-9834-9a000d2aeddc");
pub const ProgressBar_Control_GUID = Guid.initString("228c9f86-c36c-47bb-9fb6-a5834bfc53a4");
pub const RadioButton_Control_GUID = Guid.initString("3bdb49db-fe2c-4483-b3e1-e57f219440c6");
pub const ScrollBar_Control_GUID = Guid.initString("daf34b36-5065-4946-b22f-92595fc0751a");
pub const Slider_Control_GUID = Guid.initString("b033c24b-3b35-4cea-b609-763682fa660b");
pub const Spinner_Control_GUID = Guid.initString("60cc4b38-3cb1-4161-b442-c6b726c17825");
pub const StatusBar_Control_GUID = Guid.initString("d45e7d1b-5873-475f-95a4-0433e1f1b00a");
pub const Tab_Control_GUID = Guid.initString("38cd1f2d-337a-4bd2-a5e3-adb469e30bd3");
pub const TabItem_Control_GUID = Guid.initString("2c6a634f-921b-4e6e-b26e-08fcb0798f4c");
pub const Text_Control_GUID = Guid.initString("ae9772dc-d331-4f09-be20-7e6dfaf07b0a");
pub const ToolBar_Control_GUID = Guid.initString("8f06b751-e182-4e98-8893-2284543a7dce");
pub const ToolTip_Control_GUID = Guid.initString("05ddc6d1-2137-4768-98ea-73f52f7134f3");
pub const Tree_Control_GUID = Guid.initString("7561349c-d241-43f4-9908-b5f091bee611");
pub const TreeItem_Control_GUID = Guid.initString("62c9feb9-8ffc-4878-a3a4-96b030315c18");
pub const Custom_Control_GUID = Guid.initString("f29ea0c3-adb7-430a-ba90-e52c7313e6ed");
pub const Group_Control_GUID = Guid.initString("ad50aa1c-e8c8-4774-ae1b-dd86df0b3bdc");
pub const Thumb_Control_GUID = Guid.initString("701ca877-e310-4dd6-b644-797e4faea213");
pub const DataGrid_Control_GUID = Guid.initString("84b783af-d103-4b0a-8415-e73942410f4b");
pub const DataItem_Control_GUID = Guid.initString("a0177842-d94f-42a5-814b-6068addc8da5");
pub const Document_Control_GUID = Guid.initString("3cd6bb6f-6f08-4562-b229-e4e2fc7a9eb4");
pub const SplitButton_Control_GUID = Guid.initString("7011f01f-4ace-4901-b461-920a6f1ca650");
pub const Window_Control_GUID = Guid.initString("e13a7242-f462-4f4d-aec1-53b28d6c3290");
pub const Pane_Control_GUID = Guid.initString("5c2b3f5b-9182-42a3-8dec-8c04c1ee634d");
pub const Header_Control_GUID = Guid.initString("5b90cbce-78fb-4614-82b6-554d74718e67");
pub const HeaderItem_Control_GUID = Guid.initString("e6bc12cb-7c8e-49cf-b168-4a93a32bebb0");
pub const Table_Control_GUID = Guid.initString("773bfa0e-5bc4-4deb-921b-de7b3206229e");
pub const TitleBar_Control_GUID = Guid.initString("98aa55bf-3bb0-4b65-836e-2ea30dbc171f");
pub const Separator_Control_GUID = Guid.initString("8767eba3-2a63-4ab0-ac8d-aa50e23de978");
pub const SemanticZoom_Control_GUID = Guid.initString("5fd34a43-061e-42c8-b589-9dccf74bc43a");
pub const AppBar_Control_GUID = Guid.initString("6114908d-cc02-4d37-875b-b530c7139554");
pub const Text_AnimationStyle_Attribute_GUID = Guid.initString("628209f0-7c9a-4d57-be64-1f1836571ff5");
pub const Text_BackgroundColor_Attribute_GUID = Guid.initString("fdc49a07-583d-4f17-ad27-77fc832a3c0b");
pub const Text_BulletStyle_Attribute_GUID = Guid.initString("c1097c90-d5c4-4237-9781-3bec8ba54e48");
pub const Text_CapStyle_Attribute_GUID = Guid.initString("fb059c50-92cc-49a5-ba8f-0aa872bba2f3");
pub const Text_Culture_Attribute_GUID = Guid.initString("c2025af9-a42d-4ced-a1fb-c6746315222e");
pub const Text_FontName_Attribute_GUID = Guid.initString("64e63ba8-f2e5-476e-a477-1734feaaf726");
pub const Text_FontSize_Attribute_GUID = Guid.initString("dc5eeeff-0506-4673-93f2-377e4a8e01f1");
pub const Text_FontWeight_Attribute_GUID = Guid.initString("6fc02359-b316-4f5f-b401-f1ce55741853");
pub const Text_ForegroundColor_Attribute_GUID = Guid.initString("72d1c95d-5e60-471a-96b1-6c1b3b77a436");
pub const Text_HorizontalTextAlignment_Attribute_GUID = Guid.initString("04ea6161-fba3-477a-952a-bb326d026a5b");
pub const Text_IndentationFirstLine_Attribute_GUID = Guid.initString("206f9ad5-c1d3-424a-8182-6da9a7f3d632");
pub const Text_IndentationLeading_Attribute_GUID = Guid.initString("5cf66bac-2d45-4a4b-b6c9-f7221d2815b0");
pub const Text_IndentationTrailing_Attribute_GUID = Guid.initString("97ff6c0f-1ce4-408a-b67b-94d83eb69bf2");
pub const Text_IsHidden_Attribute_GUID = Guid.initString("360182fb-bdd7-47f6-ab69-19e33f8a3344");
pub const Text_IsItalic_Attribute_GUID = Guid.initString("fce12a56-1336-4a34-9663-1bab47239320");
pub const Text_IsReadOnly_Attribute_GUID = Guid.initString("a738156b-ca3e-495e-9514-833c440feb11");
pub const Text_IsSubscript_Attribute_GUID = Guid.initString("f0ead858-8f53-413c-873f-1a7d7f5e0de4");
pub const Text_IsSuperscript_Attribute_GUID = Guid.initString("da706ee4-b3aa-4645-a41f-cd25157dea76");
pub const Text_MarginBottom_Attribute_GUID = Guid.initString("7ee593c4-72b4-4cac-9271-3ed24b0e4d42");
pub const Text_MarginLeading_Attribute_GUID = Guid.initString("9e9242d0-5ed0-4900-8e8a-eecc03835afc");
pub const Text_MarginTop_Attribute_GUID = Guid.initString("683d936f-c9b9-4a9a-b3d9-d20d33311e2a");
pub const Text_MarginTrailing_Attribute_GUID = Guid.initString("af522f98-999d-40af-a5b2-0169d0342002");
pub const Text_OutlineStyles_Attribute_GUID = Guid.initString("5b675b27-db89-46fe-970c-614d523bb97d");
pub const Text_OverlineColor_Attribute_GUID = Guid.initString("83ab383a-fd43-40da-ab3e-ecf8165cbb6d");
pub const Text_OverlineStyle_Attribute_GUID = Guid.initString("0a234d66-617e-427f-871d-e1ff1e0c213f");
pub const Text_StrikethroughColor_Attribute_GUID = Guid.initString("bfe15a18-8c41-4c5a-9a0b-04af0e07f487");
pub const Text_StrikethroughStyle_Attribute_GUID = Guid.initString("72913ef1-da00-4f01-899c-ac5a8577a307");
pub const Text_Tabs_Attribute_GUID = Guid.initString("2e68d00b-92fe-42d8-899a-a784aa4454a1");
pub const Text_TextFlowDirections_Attribute_GUID = Guid.initString("8bdf8739-f420-423e-af77-20a5d973a907");
pub const Text_UnderlineColor_Attribute_GUID = Guid.initString("bfa12c73-fde2-4473-bf64-1036d6aa0f45");
pub const Text_UnderlineStyle_Attribute_GUID = Guid.initString("5f3b21c0-ede4-44bd-9c36-3853038cbfeb");
pub const Text_AnnotationTypes_Attribute_GUID = Guid.initString("ad2eb431-ee4e-4be1-a7ba-5559155a73ef");
pub const Text_AnnotationObjects_Attribute_GUID = Guid.initString("ff41cf68-e7ab-40b9-8c72-72a8ed94017d");
pub const Text_StyleName_Attribute_GUID = Guid.initString("22c9e091-4d66-45d8-a828-737bab4c98a7");
pub const Text_StyleId_Attribute_GUID = Guid.initString("14c300de-c32b-449b-ab7c-b0e0789aea5d");
pub const Text_Link_Attribute_GUID = Guid.initString("b38ef51d-9e8d-4e46-9144-56ebe177329b");
pub const Text_IsActive_Attribute_GUID = Guid.initString("f5a4e533-e1b8-436b-935d-b57aa3f558c4");
pub const Text_SelectionActiveEnd_Attribute_GUID = Guid.initString("1f668cc3-9bbf-416b-b0a2-f89f86f6612c");
pub const Text_CaretPosition_Attribute_GUID = Guid.initString("b227b131-9889-4752-a91b-733efdc5c5a0");
pub const Text_CaretBidiMode_Attribute_GUID = Guid.initString("929ee7a6-51d3-4715-96dc-b694fa24a168");
pub const Text_BeforeParagraphSpacing_Attribute_GUID = Guid.initString("be7b0ab1-c822-4a24-85e9-c8f2650fc79c");
pub const Text_AfterParagraphSpacing_Attribute_GUID = Guid.initString("588cbb38-e62f-497c-b5d1-ccdf0ee823d8");
pub const Text_LineSpacing_Attribute_GUID = Guid.initString("63ff70ae-d943-4b47-8ab7-a7a033d3214b");
pub const Text_BeforeSpacing_Attribute_GUID = Guid.initString("be7b0ab1-c822-4a24-85e9-c8f2650fc79c");
pub const Text_AfterSpacing_Attribute_GUID = Guid.initString("588cbb38-e62f-497c-b5d1-ccdf0ee823d8");
pub const Text_SayAsInterpretAs_Attribute_GUID = Guid.initString("b38ad6ac-eee1-4b6e-88cc-014cefa93fcb");
pub const TextEdit_TextChanged_Event_GUID = Guid.initString("120b0308-ec22-4eb8-9c98-9867cda1b165");
pub const TextEdit_ConversionTargetChanged_Event_GUID = Guid.initString("3388c183-ed4f-4c8b-9baa-364d51d8847f");
pub const Changes_Event_GUID = Guid.initString("7df26714-614f-4e05-9488-716c5ba19436");
pub const Annotation_Custom_GUID = Guid.initString("9ec82750-3931-4952-85bc-1dbff78a43e3");
pub const Annotation_SpellingError_GUID = Guid.initString("ae85567e-9ece-423f-81b7-96c43d53e50e");
pub const Annotation_GrammarError_GUID = Guid.initString("757a048d-4518-41c6-854c-dc009b7cfb53");
pub const Annotation_Comment_GUID = Guid.initString("fd2fda30-26b3-4c06-8bc7-98f1532e46fd");
pub const Annotation_FormulaError_GUID = Guid.initString("95611982-0cab-46d5-a2f0-e30d1905f8bf");
pub const Annotation_TrackChanges_GUID = Guid.initString("21e6e888-dc14-4016-ac27-190553c8c470");
pub const Annotation_Header_GUID = Guid.initString("867b409b-b216-4472-a219-525e310681f8");
pub const Annotation_Footer_GUID = Guid.initString("cceab046-1833-47aa-8080-701ed0b0c832");
pub const Annotation_Highlighted_GUID = Guid.initString("757c884e-8083-4081-8b9c-e87f5072f0e4");
pub const Annotation_Endnote_GUID = Guid.initString("7565725c-2d99-4839-960d-33d3b866aba5");
pub const Annotation_Footnote_GUID = Guid.initString("3de10e21-4125-42db-8620-be8083080624");
pub const Annotation_InsertionChange_GUID = Guid.initString("0dbeb3a6-df15-4164-a3c0-e21a8ce931c4");
pub const Annotation_DeletionChange_GUID = Guid.initString("be3d5b05-951d-42e7-901d-adc8c2cf34d0");
pub const Annotation_MoveChange_GUID = Guid.initString("9da587eb-23e5-4490-b385-1a22ddc8b187");
pub const Annotation_FormatChange_GUID = Guid.initString("eb247345-d4f1-41ce-8e52-f79b69635e48");
pub const Annotation_UnsyncedChange_GUID = Guid.initString("1851116a-0e47-4b30-8cb5-d7dae4fbcd1b");
pub const Annotation_EditingLockedChange_GUID = Guid.initString("c31f3e1c-7423-4dac-8348-41f099ff6f64");
pub const Annotation_ExternalChange_GUID = Guid.initString("75a05b31-5f11-42fd-887d-dfa010db2392");
pub const Annotation_ConflictingChange_GUID = Guid.initString("98af8802-517c-459f-af13-016d3fab877e");
pub const Annotation_Author_GUID = Guid.initString("f161d3a7-f81b-4128-b17f-71f690914520");
pub const Annotation_AdvancedProofingIssue_GUID = Guid.initString("dac7b72c-c0f2-4b84-b90d-5fafc0f0ef1c");
pub const Annotation_DataValidationError_GUID = Guid.initString("c8649fa8-9775-437e-ad46-e709d93c2343");
pub const Annotation_CircularReferenceError_GUID = Guid.initString("25bd9cf4-1745-4659-ba67-727f0318c616");
pub const Annotation_Mathematics_GUID = Guid.initString("eaab634b-26d0-40c1-8073-57ca1c633c9b");
pub const Annotation_Sensitive_GUID = Guid.initString("37f4c04f-0f12-4464-929c-828fd15292e3");
pub const Changes_Summary_GUID = Guid.initString("313d65a6-e60f-4d62-9861-55afd728d207");
pub const StyleId_Custom_GUID = Guid.initString("ef2edd3e-a999-4b7c-a378-09bbd52a3516");
pub const StyleId_Heading1_GUID = Guid.initString("7f7e8f69-6866-4621-930c-9a5d0ca5961c");
pub const StyleId_Heading2_GUID = Guid.initString("baa9b241-5c69-469d-85ad-474737b52b14");
pub const StyleId_Heading3_GUID = Guid.initString("bf8be9d2-d8b8-4ec5-8c52-9cfb0d035970");
pub const StyleId_Heading4_GUID = Guid.initString("8436ffc0-9578-45fc-83a4-ff40053315dd");
pub const StyleId_Heading5_GUID = Guid.initString("909f424d-0dbf-406e-97bb-4e773d9798f7");
pub const StyleId_Heading6_GUID = Guid.initString("89d23459-5d5b-4824-a420-11d3ed82e40f");
pub const StyleId_Heading7_GUID = Guid.initString("a3790473-e9ae-422d-b8e3-3b675c6181a4");
pub const StyleId_Heading8_GUID = Guid.initString("2bc14145-a40c-4881-84ae-f2235685380c");
pub const StyleId_Heading9_GUID = Guid.initString("c70d9133-bb2a-43d3-8ac6-33657884b0f0");
pub const StyleId_Title_GUID = Guid.initString("15d8201a-ffcf-481f-b0a1-30b63be98f07");
pub const StyleId_Subtitle_GUID = Guid.initString("b5d9fc17-5d6f-4420-b439-7cb19ad434e2");
pub const StyleId_Normal_GUID = Guid.initString("cd14d429-e45e-4475-a1c5-7f9e6be96eba");
pub const StyleId_Emphasis_GUID = Guid.initString("ca6e7dbe-355e-4820-95a0-925f041d3470");
pub const StyleId_Quote_GUID = Guid.initString("5d1c21ea-8195-4f6c-87ea-5dabece64c1d");
pub const StyleId_BulletedList_GUID = Guid.initString("5963ed64-6426-4632-8caf-a32ad402d91a");
pub const StyleId_NumberedList_GUID = Guid.initString("1e96dbd5-64c3-43d0-b1ee-b53b06e3eddf");
pub const Notification_Event_GUID = Guid.initString("72c5a2f7-9788-480f-b8eb-4dee00f6186f");
pub const SID_IsUIAutomationObject = Guid.initString("b96fdb85-7204-4724-842b-c7059dedb9d0");
pub const SID_ControlElementProvider = Guid.initString("f4791d68-e254-4ba3-9a53-26a5c5497946");
pub const IsSelectionPattern2Available_Property_GUID = Guid.initString("490806fb-6e89-4a47-8319-d266e511f021");
pub const Selection2_FirstSelectedItem_Property_GUID = Guid.initString("cc24ea67-369c-4e55-9ff7-38da69540c29");
pub const Selection2_LastSelectedItem_Property_GUID = Guid.initString("cf7bda90-2d83-49f8-860c-9ce394cf89b4");
pub const Selection2_CurrentSelectedItem_Property_GUID = Guid.initString("34257c26-83b5-41a6-939c-ae841c136236");
pub const Selection2_ItemCount_Property_GUID = Guid.initString("bb49eb9f-456d-4048-b591-9c2026b84636");
pub const Selection_Pattern2_GUID = Guid.initString("fba25cab-ab98-49f7-a7dc-fe539dc15be7");
pub const HeadingLevel_Property_GUID = Guid.initString("29084272-aaaf-4a30-8796-3c12f62b6bbb");
pub const IsDialog_Property_GUID = Guid.initString("9d0dfb9b-8436-4501-bbbb-e534a4fb3b3f");
pub const UIA_IAFP_DEFAULT = @as(u32, 0);
pub const UIA_IAFP_UNWRAP_BRIDGE = @as(u32, 1);
pub const UIA_PFIA_DEFAULT = @as(u32, 0);
pub const UIA_PFIA_UNWRAP_BRIDGE = @as(u32, 1);
pub const UIA_ScrollPatternNoScroll = @as(f64, -1);
pub const UIA_InvokePatternId = @as(i32, 10000);
pub const UIA_SelectionPatternId = @as(i32, 10001);
pub const UIA_ValuePatternId = @as(i32, 10002);
pub const UIA_RangeValuePatternId = @as(i32, 10003);
pub const UIA_ScrollPatternId = @as(i32, 10004);
pub const UIA_ExpandCollapsePatternId = @as(i32, 10005);
pub const UIA_GridPatternId = @as(i32, 10006);
pub const UIA_GridItemPatternId = @as(i32, 10007);
pub const UIA_MultipleViewPatternId = @as(i32, 10008);
pub const UIA_WindowPatternId = @as(i32, 10009);
pub const UIA_SelectionItemPatternId = @as(i32, 10010);
pub const UIA_DockPatternId = @as(i32, 10011);
pub const UIA_TablePatternId = @as(i32, 10012);
pub const UIA_TableItemPatternId = @as(i32, 10013);
pub const UIA_TextPatternId = @as(i32, 10014);
pub const UIA_TogglePatternId = @as(i32, 10015);
pub const UIA_TransformPatternId = @as(i32, 10016);
pub const UIA_ScrollItemPatternId = @as(i32, 10017);
pub const UIA_LegacyIAccessiblePatternId = @as(i32, 10018);
pub const UIA_ItemContainerPatternId = @as(i32, 10019);
pub const UIA_VirtualizedItemPatternId = @as(i32, 10020);
pub const UIA_SynchronizedInputPatternId = @as(i32, 10021);
pub const UIA_ObjectModelPatternId = @as(i32, 10022);
pub const UIA_AnnotationPatternId = @as(i32, 10023);
pub const UIA_TextPattern2Id = @as(i32, 10024);
pub const UIA_StylesPatternId = @as(i32, 10025);
pub const UIA_SpreadsheetPatternId = @as(i32, 10026);
pub const UIA_SpreadsheetItemPatternId = @as(i32, 10027);
pub const UIA_TransformPattern2Id = @as(i32, 10028);
pub const UIA_TextChildPatternId = @as(i32, 10029);
pub const UIA_DragPatternId = @as(i32, 10030);
pub const UIA_DropTargetPatternId = @as(i32, 10031);
pub const UIA_TextEditPatternId = @as(i32, 10032);
pub const UIA_CustomNavigationPatternId = @as(i32, 10033);
pub const UIA_SelectionPattern2Id = @as(i32, 10034);
pub const UIA_ToolTipOpenedEventId = @as(i32, 20000);
pub const UIA_ToolTipClosedEventId = @as(i32, 20001);
pub const UIA_StructureChangedEventId = @as(i32, 20002);
pub const UIA_MenuOpenedEventId = @as(i32, 20003);
pub const UIA_AutomationPropertyChangedEventId = @as(i32, 20004);
pub const UIA_AutomationFocusChangedEventId = @as(i32, 20005);
pub const UIA_AsyncContentLoadedEventId = @as(i32, 20006);
pub const UIA_MenuClosedEventId = @as(i32, 20007);
pub const UIA_LayoutInvalidatedEventId = @as(i32, 20008);
pub const UIA_Invoke_InvokedEventId = @as(i32, 20009);
pub const UIA_SelectionItem_ElementAddedToSelectionEventId = @as(i32, 20010);
pub const UIA_SelectionItem_ElementRemovedFromSelectionEventId = @as(i32, 20011);
pub const UIA_SelectionItem_ElementSelectedEventId = @as(i32, 20012);
pub const UIA_Selection_InvalidatedEventId = @as(i32, 20013);
pub const UIA_Text_TextSelectionChangedEventId = @as(i32, 20014);
pub const UIA_Text_TextChangedEventId = @as(i32, 20015);
pub const UIA_Window_WindowOpenedEventId = @as(i32, 20016);
pub const UIA_Window_WindowClosedEventId = @as(i32, 20017);
pub const UIA_MenuModeStartEventId = @as(i32, 20018);
pub const UIA_MenuModeEndEventId = @as(i32, 20019);
pub const UIA_InputReachedTargetEventId = @as(i32, 20020);
pub const UIA_InputReachedOtherElementEventId = @as(i32, 20021);
pub const UIA_InputDiscardedEventId = @as(i32, 20022);
pub const UIA_SystemAlertEventId = @as(i32, 20023);
pub const UIA_LiveRegionChangedEventId = @as(i32, 20024);
pub const UIA_HostedFragmentRootsInvalidatedEventId = @as(i32, 20025);
pub const UIA_Drag_DragStartEventId = @as(i32, 20026);
pub const UIA_Drag_DragCancelEventId = @as(i32, 20027);
pub const UIA_Drag_DragCompleteEventId = @as(i32, 20028);
pub const UIA_DropTarget_DragEnterEventId = @as(i32, 20029);
pub const UIA_DropTarget_DragLeaveEventId = @as(i32, 20030);
pub const UIA_DropTarget_DroppedEventId = @as(i32, 20031);
pub const UIA_TextEdit_TextChangedEventId = @as(i32, 20032);
pub const UIA_TextEdit_ConversionTargetChangedEventId = @as(i32, 20033);
pub const UIA_ChangesEventId = @as(i32, 20034);
pub const UIA_NotificationEventId = @as(i32, 20035);
pub const UIA_ActiveTextPositionChangedEventId = @as(i32, 20036);
pub const UIA_RuntimeIdPropertyId = @as(i32, 30000);
pub const UIA_BoundingRectanglePropertyId = @as(i32, 30001);
pub const UIA_ProcessIdPropertyId = @as(i32, 30002);
pub const UIA_ControlTypePropertyId = @as(i32, 30003);
pub const UIA_LocalizedControlTypePropertyId = @as(i32, 30004);
pub const UIA_NamePropertyId = @as(i32, 30005);
pub const UIA_AcceleratorKeyPropertyId = @as(i32, 30006);
pub const UIA_AccessKeyPropertyId = @as(i32, 30007);
pub const UIA_HasKeyboardFocusPropertyId = @as(i32, 30008);
pub const UIA_IsKeyboardFocusablePropertyId = @as(i32, 30009);
pub const UIA_IsEnabledPropertyId = @as(i32, 30010);
pub const UIA_AutomationIdPropertyId = @as(i32, 30011);
pub const UIA_ClassNamePropertyId = @as(i32, 30012);
pub const UIA_HelpTextPropertyId = @as(i32, 30013);
pub const UIA_ClickablePointPropertyId = @as(i32, 30014);
pub const UIA_CulturePropertyId = @as(i32, 30015);
pub const UIA_IsControlElementPropertyId = @as(i32, 30016);
pub const UIA_IsContentElementPropertyId = @as(i32, 30017);
pub const UIA_LabeledByPropertyId = @as(i32, 30018);
pub const UIA_IsPasswordPropertyId = @as(i32, 30019);
pub const UIA_NativeWindowHandlePropertyId = @as(i32, 30020);
pub const UIA_ItemTypePropertyId = @as(i32, 30021);
pub const UIA_IsOffscreenPropertyId = @as(i32, 30022);
pub const UIA_OrientationPropertyId = @as(i32, 30023);
pub const UIA_FrameworkIdPropertyId = @as(i32, 30024);
pub const UIA_IsRequiredForFormPropertyId = @as(i32, 30025);
pub const UIA_ItemStatusPropertyId = @as(i32, 30026);
pub const UIA_IsDockPatternAvailablePropertyId = @as(i32, 30027);
pub const UIA_IsExpandCollapsePatternAvailablePropertyId = @as(i32, 30028);
pub const UIA_IsGridItemPatternAvailablePropertyId = @as(i32, 30029);
pub const UIA_IsGridPatternAvailablePropertyId = @as(i32, 30030);
pub const UIA_IsInvokePatternAvailablePropertyId = @as(i32, 30031);
pub const UIA_IsMultipleViewPatternAvailablePropertyId = @as(i32, 30032);
pub const UIA_IsRangeValuePatternAvailablePropertyId = @as(i32, 30033);
pub const UIA_IsScrollPatternAvailablePropertyId = @as(i32, 30034);
pub const UIA_IsScrollItemPatternAvailablePropertyId = @as(i32, 30035);
pub const UIA_IsSelectionItemPatternAvailablePropertyId = @as(i32, 30036);
pub const UIA_IsSelectionPatternAvailablePropertyId = @as(i32, 30037);
pub const UIA_IsTablePatternAvailablePropertyId = @as(i32, 30038);
pub const UIA_IsTableItemPatternAvailablePropertyId = @as(i32, 30039);
pub const UIA_IsTextPatternAvailablePropertyId = @as(i32, 30040);
pub const UIA_IsTogglePatternAvailablePropertyId = @as(i32, 30041);
pub const UIA_IsTransformPatternAvailablePropertyId = @as(i32, 30042);
pub const UIA_IsValuePatternAvailablePropertyId = @as(i32, 30043);
pub const UIA_IsWindowPatternAvailablePropertyId = @as(i32, 30044);
pub const UIA_ValueValuePropertyId = @as(i32, 30045);
pub const UIA_ValueIsReadOnlyPropertyId = @as(i32, 30046);
pub const UIA_RangeValueValuePropertyId = @as(i32, 30047);
pub const UIA_RangeValueIsReadOnlyPropertyId = @as(i32, 30048);
pub const UIA_RangeValueMinimumPropertyId = @as(i32, 30049);
pub const UIA_RangeValueMaximumPropertyId = @as(i32, 30050);
pub const UIA_RangeValueLargeChangePropertyId = @as(i32, 30051);
pub const UIA_RangeValueSmallChangePropertyId = @as(i32, 30052);
pub const UIA_ScrollHorizontalScrollPercentPropertyId = @as(i32, 30053);
pub const UIA_ScrollHorizontalViewSizePropertyId = @as(i32, 30054);
pub const UIA_ScrollVerticalScrollPercentPropertyId = @as(i32, 30055);
pub const UIA_ScrollVerticalViewSizePropertyId = @as(i32, 30056);
pub const UIA_ScrollHorizontallyScrollablePropertyId = @as(i32, 30057);
pub const UIA_ScrollVerticallyScrollablePropertyId = @as(i32, 30058);
pub const UIA_SelectionSelectionPropertyId = @as(i32, 30059);
pub const UIA_SelectionCanSelectMultiplePropertyId = @as(i32, 30060);
pub const UIA_SelectionIsSelectionRequiredPropertyId = @as(i32, 30061);
pub const UIA_GridRowCountPropertyId = @as(i32, 30062);
pub const UIA_GridColumnCountPropertyId = @as(i32, 30063);
pub const UIA_GridItemRowPropertyId = @as(i32, 30064);
pub const UIA_GridItemColumnPropertyId = @as(i32, 30065);
pub const UIA_GridItemRowSpanPropertyId = @as(i32, 30066);
pub const UIA_GridItemColumnSpanPropertyId = @as(i32, 30067);
pub const UIA_GridItemContainingGridPropertyId = @as(i32, 30068);
pub const UIA_DockDockPositionPropertyId = @as(i32, 30069);
pub const UIA_ExpandCollapseExpandCollapseStatePropertyId = @as(i32, 30070);
pub const UIA_MultipleViewCurrentViewPropertyId = @as(i32, 30071);
pub const UIA_MultipleViewSupportedViewsPropertyId = @as(i32, 30072);
pub const UIA_WindowCanMaximizePropertyId = @as(i32, 30073);
pub const UIA_WindowCanMinimizePropertyId = @as(i32, 30074);
pub const UIA_WindowWindowVisualStatePropertyId = @as(i32, 30075);
pub const UIA_WindowWindowInteractionStatePropertyId = @as(i32, 30076);
pub const UIA_WindowIsModalPropertyId = @as(i32, 30077);
pub const UIA_WindowIsTopmostPropertyId = @as(i32, 30078);
pub const UIA_SelectionItemIsSelectedPropertyId = @as(i32, 30079);
pub const UIA_SelectionItemSelectionContainerPropertyId = @as(i32, 30080);
pub const UIA_TableRowHeadersPropertyId = @as(i32, 30081);
pub const UIA_TableColumnHeadersPropertyId = @as(i32, 30082);
pub const UIA_TableRowOrColumnMajorPropertyId = @as(i32, 30083);
pub const UIA_TableItemRowHeaderItemsPropertyId = @as(i32, 30084);
pub const UIA_TableItemColumnHeaderItemsPropertyId = @as(i32, 30085);
pub const UIA_ToggleToggleStatePropertyId = @as(i32, 30086);
pub const UIA_TransformCanMovePropertyId = @as(i32, 30087);
pub const UIA_TransformCanResizePropertyId = @as(i32, 30088);
pub const UIA_TransformCanRotatePropertyId = @as(i32, 30089);
pub const UIA_IsLegacyIAccessiblePatternAvailablePropertyId = @as(i32, 30090);
pub const UIA_LegacyIAccessibleChildIdPropertyId = @as(i32, 30091);
pub const UIA_LegacyIAccessibleNamePropertyId = @as(i32, 30092);
pub const UIA_LegacyIAccessibleValuePropertyId = @as(i32, 30093);
pub const UIA_LegacyIAccessibleDescriptionPropertyId = @as(i32, 30094);
pub const UIA_LegacyIAccessibleRolePropertyId = @as(i32, 30095);
pub const UIA_LegacyIAccessibleStatePropertyId = @as(i32, 30096);
pub const UIA_LegacyIAccessibleHelpPropertyId = @as(i32, 30097);
pub const UIA_LegacyIAccessibleKeyboardShortcutPropertyId = @as(i32, 30098);
pub const UIA_LegacyIAccessibleSelectionPropertyId = @as(i32, 30099);
pub const UIA_LegacyIAccessibleDefaultActionPropertyId = @as(i32, 30100);
pub const UIA_AriaRolePropertyId = @as(i32, 30101);
pub const UIA_AriaPropertiesPropertyId = @as(i32, 30102);
pub const UIA_IsDataValidForFormPropertyId = @as(i32, 30103);
pub const UIA_ControllerForPropertyId = @as(i32, 30104);
pub const UIA_DescribedByPropertyId = @as(i32, 30105);
pub const UIA_FlowsToPropertyId = @as(i32, 30106);
pub const UIA_ProviderDescriptionPropertyId = @as(i32, 30107);
pub const UIA_IsItemContainerPatternAvailablePropertyId = @as(i32, 30108);
pub const UIA_IsVirtualizedItemPatternAvailablePropertyId = @as(i32, 30109);
pub const UIA_IsSynchronizedInputPatternAvailablePropertyId = @as(i32, 30110);
pub const UIA_OptimizeForVisualContentPropertyId = @as(i32, 30111);
pub const UIA_IsObjectModelPatternAvailablePropertyId = @as(i32, 30112);
pub const UIA_AnnotationAnnotationTypeIdPropertyId = @as(i32, 30113);
pub const UIA_AnnotationAnnotationTypeNamePropertyId = @as(i32, 30114);
pub const UIA_AnnotationAuthorPropertyId = @as(i32, 30115);
pub const UIA_AnnotationDateTimePropertyId = @as(i32, 30116);
pub const UIA_AnnotationTargetPropertyId = @as(i32, 30117);
pub const UIA_IsAnnotationPatternAvailablePropertyId = @as(i32, 30118);
pub const UIA_IsTextPattern2AvailablePropertyId = @as(i32, 30119);
pub const UIA_StylesStyleIdPropertyId = @as(i32, 30120);
pub const UIA_StylesStyleNamePropertyId = @as(i32, 30121);
pub const UIA_StylesFillColorPropertyId = @as(i32, 30122);
pub const UIA_StylesFillPatternStylePropertyId = @as(i32, 30123);
pub const UIA_StylesShapePropertyId = @as(i32, 30124);
pub const UIA_StylesFillPatternColorPropertyId = @as(i32, 30125);
pub const UIA_StylesExtendedPropertiesPropertyId = @as(i32, 30126);
pub const UIA_IsStylesPatternAvailablePropertyId = @as(i32, 30127);
pub const UIA_IsSpreadsheetPatternAvailablePropertyId = @as(i32, 30128);
pub const UIA_SpreadsheetItemFormulaPropertyId = @as(i32, 30129);
pub const UIA_SpreadsheetItemAnnotationObjectsPropertyId = @as(i32, 30130);
pub const UIA_SpreadsheetItemAnnotationTypesPropertyId = @as(i32, 30131);
pub const UIA_IsSpreadsheetItemPatternAvailablePropertyId = @as(i32, 30132);
pub const UIA_Transform2CanZoomPropertyId = @as(i32, 30133);
pub const UIA_IsTransformPattern2AvailablePropertyId = @as(i32, 30134);
pub const UIA_LiveSettingPropertyId = @as(i32, 30135);
pub const UIA_IsTextChildPatternAvailablePropertyId = @as(i32, 30136);
pub const UIA_IsDragPatternAvailablePropertyId = @as(i32, 30137);
pub const UIA_DragIsGrabbedPropertyId = @as(i32, 30138);
pub const UIA_DragDropEffectPropertyId = @as(i32, 30139);
pub const UIA_DragDropEffectsPropertyId = @as(i32, 30140);
pub const UIA_IsDropTargetPatternAvailablePropertyId = @as(i32, 30141);
pub const UIA_DropTargetDropTargetEffectPropertyId = @as(i32, 30142);
pub const UIA_DropTargetDropTargetEffectsPropertyId = @as(i32, 30143);
pub const UIA_DragGrabbedItemsPropertyId = @as(i32, 30144);
pub const UIA_Transform2ZoomLevelPropertyId = @as(i32, 30145);
pub const UIA_Transform2ZoomMinimumPropertyId = @as(i32, 30146);
pub const UIA_Transform2ZoomMaximumPropertyId = @as(i32, 30147);
pub const UIA_FlowsFromPropertyId = @as(i32, 30148);
pub const UIA_IsTextEditPatternAvailablePropertyId = @as(i32, 30149);
pub const UIA_IsPeripheralPropertyId = @as(i32, 30150);
pub const UIA_IsCustomNavigationPatternAvailablePropertyId = @as(i32, 30151);
pub const UIA_PositionInSetPropertyId = @as(i32, 30152);
pub const UIA_SizeOfSetPropertyId = @as(i32, 30153);
pub const UIA_LevelPropertyId = @as(i32, 30154);
pub const UIA_AnnotationTypesPropertyId = @as(i32, 30155);
pub const UIA_AnnotationObjectsPropertyId = @as(i32, 30156);
pub const UIA_LandmarkTypePropertyId = @as(i32, 30157);
pub const UIA_LocalizedLandmarkTypePropertyId = @as(i32, 30158);
pub const UIA_FullDescriptionPropertyId = @as(i32, 30159);
pub const UIA_FillColorPropertyId = @as(i32, 30160);
pub const UIA_OutlineColorPropertyId = @as(i32, 30161);
pub const UIA_FillTypePropertyId = @as(i32, 30162);
pub const UIA_VisualEffectsPropertyId = @as(i32, 30163);
pub const UIA_OutlineThicknessPropertyId = @as(i32, 30164);
pub const UIA_CenterPointPropertyId = @as(i32, 30165);
pub const UIA_RotationPropertyId = @as(i32, 30166);
pub const UIA_SizePropertyId = @as(i32, 30167);
pub const UIA_IsSelectionPattern2AvailablePropertyId = @as(i32, 30168);
pub const UIA_Selection2FirstSelectedItemPropertyId = @as(i32, 30169);
pub const UIA_Selection2LastSelectedItemPropertyId = @as(i32, 30170);
pub const UIA_Selection2CurrentSelectedItemPropertyId = @as(i32, 30171);
pub const UIA_Selection2ItemCountPropertyId = @as(i32, 30172);
pub const UIA_HeadingLevelPropertyId = @as(i32, 30173);
pub const UIA_IsDialogPropertyId = @as(i32, 30174);
pub const UIA_AnimationStyleAttributeId = @as(i32, 40000);
pub const UIA_BackgroundColorAttributeId = @as(i32, 40001);
pub const UIA_BulletStyleAttributeId = @as(i32, 40002);
pub const UIA_CapStyleAttributeId = @as(i32, 40003);
pub const UIA_CultureAttributeId = @as(i32, 40004);
pub const UIA_FontNameAttributeId = @as(i32, 40005);
pub const UIA_FontSizeAttributeId = @as(i32, 40006);
pub const UIA_FontWeightAttributeId = @as(i32, 40007);
pub const UIA_ForegroundColorAttributeId = @as(i32, 40008);
pub const UIA_HorizontalTextAlignmentAttributeId = @as(i32, 40009);
pub const UIA_IndentationFirstLineAttributeId = @as(i32, 40010);
pub const UIA_IndentationLeadingAttributeId = @as(i32, 40011);
pub const UIA_IndentationTrailingAttributeId = @as(i32, 40012);
pub const UIA_IsHiddenAttributeId = @as(i32, 40013);
pub const UIA_IsItalicAttributeId = @as(i32, 40014);
pub const UIA_IsReadOnlyAttributeId = @as(i32, 40015);
pub const UIA_IsSubscriptAttributeId = @as(i32, 40016);
pub const UIA_IsSuperscriptAttributeId = @as(i32, 40017);
pub const UIA_MarginBottomAttributeId = @as(i32, 40018);
pub const UIA_MarginLeadingAttributeId = @as(i32, 40019);
pub const UIA_MarginTopAttributeId = @as(i32, 40020);
pub const UIA_MarginTrailingAttributeId = @as(i32, 40021);
pub const UIA_OutlineStylesAttributeId = @as(i32, 40022);
pub const UIA_OverlineColorAttributeId = @as(i32, 40023);
pub const UIA_OverlineStyleAttributeId = @as(i32, 40024);
pub const UIA_StrikethroughColorAttributeId = @as(i32, 40025);
pub const UIA_StrikethroughStyleAttributeId = @as(i32, 40026);
pub const UIA_TabsAttributeId = @as(i32, 40027);
pub const UIA_TextFlowDirectionsAttributeId = @as(i32, 40028);
pub const UIA_UnderlineColorAttributeId = @as(i32, 40029);
pub const UIA_UnderlineStyleAttributeId = @as(i32, 40030);
pub const UIA_AnnotationTypesAttributeId = @as(i32, 40031);
pub const UIA_AnnotationObjectsAttributeId = @as(i32, 40032);
pub const UIA_StyleNameAttributeId = @as(i32, 40033);
pub const UIA_StyleIdAttributeId = @as(i32, 40034);
pub const UIA_LinkAttributeId = @as(i32, 40035);
pub const UIA_IsActiveAttributeId = @as(i32, 40036);
pub const UIA_SelectionActiveEndAttributeId = @as(i32, 40037);
pub const UIA_CaretPositionAttributeId = @as(i32, 40038);
pub const UIA_CaretBidiModeAttributeId = @as(i32, 40039);
pub const UIA_LineSpacingAttributeId = @as(i32, 40040);
pub const UIA_BeforeParagraphSpacingAttributeId = @as(i32, 40041);
pub const UIA_AfterParagraphSpacingAttributeId = @as(i32, 40042);
pub const UIA_SayAsInterpretAsAttributeId = @as(i32, 40043);
pub const UIA_ButtonControlTypeId = @as(i32, 50000);
pub const UIA_CalendarControlTypeId = @as(i32, 50001);
pub const UIA_CheckBoxControlTypeId = @as(i32, 50002);
pub const UIA_ComboBoxControlTypeId = @as(i32, 50003);
pub const UIA_EditControlTypeId = @as(i32, 50004);
pub const UIA_HyperlinkControlTypeId = @as(i32, 50005);
pub const UIA_ImageControlTypeId = @as(i32, 50006);
pub const UIA_ListItemControlTypeId = @as(i32, 50007);
pub const UIA_ListControlTypeId = @as(i32, 50008);
pub const UIA_MenuControlTypeId = @as(i32, 50009);
pub const UIA_MenuBarControlTypeId = @as(i32, 50010);
pub const UIA_MenuItemControlTypeId = @as(i32, 50011);
pub const UIA_ProgressBarControlTypeId = @as(i32, 50012);
pub const UIA_RadioButtonControlTypeId = @as(i32, 50013);
pub const UIA_ScrollBarControlTypeId = @as(i32, 50014);
pub const UIA_SliderControlTypeId = @as(i32, 50015);
pub const UIA_SpinnerControlTypeId = @as(i32, 50016);
pub const UIA_StatusBarControlTypeId = @as(i32, 50017);
pub const UIA_TabControlTypeId = @as(i32, 50018);
pub const UIA_TabItemControlTypeId = @as(i32, 50019);
pub const UIA_TextControlTypeId = @as(i32, 50020);
pub const UIA_ToolBarControlTypeId = @as(i32, 50021);
pub const UIA_ToolTipControlTypeId = @as(i32, 50022);
pub const UIA_TreeControlTypeId = @as(i32, 50023);
pub const UIA_TreeItemControlTypeId = @as(i32, 50024);
pub const UIA_CustomControlTypeId = @as(i32, 50025);
pub const UIA_GroupControlTypeId = @as(i32, 50026);
pub const UIA_ThumbControlTypeId = @as(i32, 50027);
pub const UIA_DataGridControlTypeId = @as(i32, 50028);
pub const UIA_DataItemControlTypeId = @as(i32, 50029);
pub const UIA_DocumentControlTypeId = @as(i32, 50030);
pub const UIA_SplitButtonControlTypeId = @as(i32, 50031);
pub const UIA_WindowControlTypeId = @as(i32, 50032);
pub const UIA_PaneControlTypeId = @as(i32, 50033);
pub const UIA_HeaderControlTypeId = @as(i32, 50034);
pub const UIA_HeaderItemControlTypeId = @as(i32, 50035);
pub const UIA_TableControlTypeId = @as(i32, 50036);
pub const UIA_TitleBarControlTypeId = @as(i32, 50037);
pub const UIA_SeparatorControlTypeId = @as(i32, 50038);
pub const UIA_SemanticZoomControlTypeId = @as(i32, 50039);
pub const UIA_AppBarControlTypeId = @as(i32, 50040);
pub const AnnotationType_Unknown = @as(i32, 60000);
pub const AnnotationType_SpellingError = @as(i32, 60001);
pub const AnnotationType_GrammarError = @as(i32, 60002);
pub const AnnotationType_Comment = @as(i32, 60003);
pub const AnnotationType_FormulaError = @as(i32, 60004);
pub const AnnotationType_TrackChanges = @as(i32, 60005);
pub const AnnotationType_Header = @as(i32, 60006);
pub const AnnotationType_Footer = @as(i32, 60007);
pub const AnnotationType_Highlighted = @as(i32, 60008);
pub const AnnotationType_Endnote = @as(i32, 60009);
pub const AnnotationType_Footnote = @as(i32, 60010);
pub const AnnotationType_InsertionChange = @as(i32, 60011);
pub const AnnotationType_DeletionChange = @as(i32, 60012);
pub const AnnotationType_MoveChange = @as(i32, 60013);
pub const AnnotationType_FormatChange = @as(i32, 60014);
pub const AnnotationType_UnsyncedChange = @as(i32, 60015);
pub const AnnotationType_EditingLockedChange = @as(i32, 60016);
pub const AnnotationType_ExternalChange = @as(i32, 60017);
pub const AnnotationType_ConflictingChange = @as(i32, 60018);
pub const AnnotationType_Author = @as(i32, 60019);
pub const AnnotationType_AdvancedProofingIssue = @as(i32, 60020);
pub const AnnotationType_DataValidationError = @as(i32, 60021);
pub const AnnotationType_CircularReferenceError = @as(i32, 60022);
pub const AnnotationType_Mathematics = @as(i32, 60023);
pub const AnnotationType_Sensitive = @as(i32, 60024);
pub const StyleId_Custom = @as(i32, 70000);
pub const StyleId_Heading1 = @as(i32, 70001);
pub const StyleId_Heading2 = @as(i32, 70002);
pub const StyleId_Heading3 = @as(i32, 70003);
pub const StyleId_Heading4 = @as(i32, 70004);
pub const StyleId_Heading5 = @as(i32, 70005);
pub const StyleId_Heading6 = @as(i32, 70006);
pub const StyleId_Heading7 = @as(i32, 70007);
pub const StyleId_Heading8 = @as(i32, 70008);
pub const StyleId_Heading9 = @as(i32, 70009);
pub const StyleId_Title = @as(i32, 70010);
pub const StyleId_Subtitle = @as(i32, 70011);
pub const StyleId_Normal = @as(i32, 70012);
pub const StyleId_Emphasis = @as(i32, 70013);
pub const StyleId_Quote = @as(i32, 70014);
pub const StyleId_BulletedList = @as(i32, 70015);
pub const StyleId_NumberedList = @as(i32, 70016);
pub const UIA_CustomLandmarkTypeId = @as(i32, 80000);
pub const UIA_FormLandmarkTypeId = @as(i32, 80001);
pub const UIA_MainLandmarkTypeId = @as(i32, 80002);
pub const UIA_NavigationLandmarkTypeId = @as(i32, 80003);
pub const UIA_SearchLandmarkTypeId = @as(i32, 80004);
pub const HeadingLevel_None = @as(i32, 80050);
pub const HeadingLevel1 = @as(i32, 80051);
pub const HeadingLevel2 = @as(i32, 80052);
pub const HeadingLevel3 = @as(i32, 80053);
pub const HeadingLevel4 = @as(i32, 80054);
pub const HeadingLevel5 = @as(i32, 80055);
pub const HeadingLevel6 = @as(i32, 80056);
pub const HeadingLevel7 = @as(i32, 80057);
pub const HeadingLevel8 = @as(i32, 80058);
pub const HeadingLevel9 = @as(i32, 80059);
pub const UIA_SummaryChangeId = @as(i32, 90000);
pub const UIA_SayAsInterpretAsMetadataId = @as(i32, 100000);
//--------------------------------------------------------------------------------
// Section: Types (241)
//--------------------------------------------------------------------------------
pub const STICKYKEYS_FLAGS = enum(u32) {
STICKYKEYSON = 1,
AVAILABLE = 2,
HOTKEYACTIVE = 4,
CONFIRMHOTKEY = 8,
HOTKEYSOUND = 16,
INDICATOR = 32,
AUDIBLEFEEDBACK = 64,
TRISTATE = 128,
TWOKEYSOFF = 256,
LALTLATCHED = 268435456,
LCTLLATCHED = 67108864,
LSHIFTLATCHED = 16777216,
RALTLATCHED = 536870912,
RCTLLATCHED = 134217728,
RSHIFTLATCHED = 33554432,
LWINLATCHED = 1073741824,
RWINLATCHED = 2147483648,
LALTLOCKED = 1048576,
LCTLLOCKED = 262144,
LSHIFTLOCKED = 65536,
RALTLOCKED = 2097152,
RCTLLOCKED = 524288,
RSHIFTLOCKED = 131072,
LWINLOCKED = 4194304,
RWINLOCKED = 8388608,
_,
pub fn initFlags(o: struct {
STICKYKEYSON: u1 = 0,
AVAILABLE: u1 = 0,
HOTKEYACTIVE: u1 = 0,
CONFIRMHOTKEY: u1 = 0,
HOTKEYSOUND: u1 = 0,
INDICATOR: u1 = 0,
AUDIBLEFEEDBACK: u1 = 0,
TRISTATE: u1 = 0,
TWOKEYSOFF: u1 = 0,
LALTLATCHED: u1 = 0,
LCTLLATCHED: u1 = 0,
LSHIFTLATCHED: u1 = 0,
RALTLATCHED: u1 = 0,
RCTLLATCHED: u1 = 0,
RSHIFTLATCHED: u1 = 0,
LWINLATCHED: u1 = 0,
RWINLATCHED: u1 = 0,
LALTLOCKED: u1 = 0,
LCTLLOCKED: u1 = 0,
LSHIFTLOCKED: u1 = 0,
RALTLOCKED: u1 = 0,
RCTLLOCKED: u1 = 0,
RSHIFTLOCKED: u1 = 0,
LWINLOCKED: u1 = 0,
RWINLOCKED: u1 = 0,
}) STICKYKEYS_FLAGS {
return @intToEnum(STICKYKEYS_FLAGS,
(if (o.STICKYKEYSON == 1) @enumToInt(STICKYKEYS_FLAGS.STICKYKEYSON) else 0)
| (if (o.AVAILABLE == 1) @enumToInt(STICKYKEYS_FLAGS.AVAILABLE) else 0)
| (if (o.HOTKEYACTIVE == 1) @enumToInt(STICKYKEYS_FLAGS.HOTKEYACTIVE) else 0)
| (if (o.CONFIRMHOTKEY == 1) @enumToInt(STICKYKEYS_FLAGS.CONFIRMHOTKEY) else 0)
| (if (o.HOTKEYSOUND == 1) @enumToInt(STICKYKEYS_FLAGS.HOTKEYSOUND) else 0)
| (if (o.INDICATOR == 1) @enumToInt(STICKYKEYS_FLAGS.INDICATOR) else 0)
| (if (o.AUDIBLEFEEDBACK == 1) @enumToInt(STICKYKEYS_FLAGS.AUDIBLEFEEDBACK) else 0)
| (if (o.TRISTATE == 1) @enumToInt(STICKYKEYS_FLAGS.TRISTATE) else 0)
| (if (o.TWOKEYSOFF == 1) @enumToInt(STICKYKEYS_FLAGS.TWOKEYSOFF) else 0)
| (if (o.LALTLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.LALTLATCHED) else 0)
| (if (o.LCTLLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.LCTLLATCHED) else 0)
| (if (o.LSHIFTLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.LSHIFTLATCHED) else 0)
| (if (o.RALTLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.RALTLATCHED) else 0)
| (if (o.RCTLLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.RCTLLATCHED) else 0)
| (if (o.RSHIFTLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.RSHIFTLATCHED) else 0)
| (if (o.LWINLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.LWINLATCHED) else 0)
| (if (o.RWINLATCHED == 1) @enumToInt(STICKYKEYS_FLAGS.RWINLATCHED) else 0)
| (if (o.LALTLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.LALTLOCKED) else 0)
| (if (o.LCTLLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.LCTLLOCKED) else 0)
| (if (o.LSHIFTLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.LSHIFTLOCKED) else 0)
| (if (o.RALTLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.RALTLOCKED) else 0)
| (if (o.RCTLLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.RCTLLOCKED) else 0)
| (if (o.RSHIFTLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.RSHIFTLOCKED) else 0)
| (if (o.LWINLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.LWINLOCKED) else 0)
| (if (o.RWINLOCKED == 1) @enumToInt(STICKYKEYS_FLAGS.RWINLOCKED) else 0)
);
}
};
pub const SKF_STICKYKEYSON = STICKYKEYS_FLAGS.STICKYKEYSON;
pub const SKF_AVAILABLE = STICKYKEYS_FLAGS.AVAILABLE;
pub const SKF_HOTKEYACTIVE = STICKYKEYS_FLAGS.HOTKEYACTIVE;
pub const SKF_CONFIRMHOTKEY = STICKYKEYS_FLAGS.CONFIRMHOTKEY;
pub const SKF_HOTKEYSOUND = STICKYKEYS_FLAGS.HOTKEYSOUND;
pub const SKF_INDICATOR = STICKYKEYS_FLAGS.INDICATOR;
pub const SKF_AUDIBLEFEEDBACK = STICKYKEYS_FLAGS.AUDIBLEFEEDBACK;
pub const SKF_TRISTATE = STICKYKEYS_FLAGS.TRISTATE;
pub const SKF_TWOKEYSOFF = STICKYKEYS_FLAGS.TWOKEYSOFF;
pub const SKF_LALTLATCHED = STICKYKEYS_FLAGS.LALTLATCHED;
pub const SKF_LCTLLATCHED = STICKYKEYS_FLAGS.LCTLLATCHED;
pub const SKF_LSHIFTLATCHED = STICKYKEYS_FLAGS.LSHIFTLATCHED;
pub const SKF_RALTLATCHED = STICKYKEYS_FLAGS.RALTLATCHED;
pub const SKF_RCTLLATCHED = STICKYKEYS_FLAGS.RCTLLATCHED;
pub const SKF_RSHIFTLATCHED = STICKYKEYS_FLAGS.RSHIFTLATCHED;
pub const SKF_LWINLATCHED = STICKYKEYS_FLAGS.LWINLATCHED;
pub const SKF_RWINLATCHED = STICKYKEYS_FLAGS.RWINLATCHED;
pub const SKF_LALTLOCKED = STICKYKEYS_FLAGS.LALTLOCKED;
pub const SKF_LCTLLOCKED = STICKYKEYS_FLAGS.LCTLLOCKED;
pub const SKF_LSHIFTLOCKED = STICKYKEYS_FLAGS.LSHIFTLOCKED;
pub const SKF_RALTLOCKED = STICKYKEYS_FLAGS.RALTLOCKED;
pub const SKF_RCTLLOCKED = STICKYKEYS_FLAGS.RCTLLOCKED;
pub const SKF_RSHIFTLOCKED = STICKYKEYS_FLAGS.RSHIFTLOCKED;
pub const SKF_LWINLOCKED = STICKYKEYS_FLAGS.LWINLOCKED;
pub const SKF_RWINLOCKED = STICKYKEYS_FLAGS.RWINLOCKED;
pub const SOUNDSENTRY_FLAGS = enum(u32) {
SOUNDSENTRYON = 1,
AVAILABLE = 2,
INDICATOR = 4,
_,
pub fn initFlags(o: struct {
SOUNDSENTRYON: u1 = 0,
AVAILABLE: u1 = 0,
INDICATOR: u1 = 0,
}) SOUNDSENTRY_FLAGS {
return @intToEnum(SOUNDSENTRY_FLAGS,
(if (o.SOUNDSENTRYON == 1) @enumToInt(SOUNDSENTRY_FLAGS.SOUNDSENTRYON) else 0)
| (if (o.AVAILABLE == 1) @enumToInt(SOUNDSENTRY_FLAGS.AVAILABLE) else 0)
| (if (o.INDICATOR == 1) @enumToInt(SOUNDSENTRY_FLAGS.INDICATOR) else 0)
);
}
};
pub const SSF_SOUNDSENTRYON = SOUNDSENTRY_FLAGS.SOUNDSENTRYON;
pub const SSF_AVAILABLE = SOUNDSENTRY_FLAGS.AVAILABLE;
pub const SSF_INDICATOR = SOUNDSENTRY_FLAGS.INDICATOR;
pub const ACC_UTILITY_STATE_FLAGS = enum(u32) {
ON_SCREEN_KEYBOARD_ACTIVE = 1,
TOUCH_MODIFICATION_ACTIVE = 2,
PRIORITY_AUDIO_ACTIVE = 4,
PRIORITY_AUDIO_ACTIVE_NODUCK = 8,
_,
pub fn initFlags(o: struct {
ON_SCREEN_KEYBOARD_ACTIVE: u1 = 0,
TOUCH_MODIFICATION_ACTIVE: u1 = 0,
PRIORITY_AUDIO_ACTIVE: u1 = 0,
PRIORITY_AUDIO_ACTIVE_NODUCK: u1 = 0,
}) ACC_UTILITY_STATE_FLAGS {
return @intToEnum(ACC_UTILITY_STATE_FLAGS,
(if (o.ON_SCREEN_KEYBOARD_ACTIVE == 1) @enumToInt(ACC_UTILITY_STATE_FLAGS.ON_SCREEN_KEYBOARD_ACTIVE) else 0)
| (if (o.TOUCH_MODIFICATION_ACTIVE == 1) @enumToInt(ACC_UTILITY_STATE_FLAGS.TOUCH_MODIFICATION_ACTIVE) else 0)
| (if (o.PRIORITY_AUDIO_ACTIVE == 1) @enumToInt(ACC_UTILITY_STATE_FLAGS.PRIORITY_AUDIO_ACTIVE) else 0)
| (if (o.PRIORITY_AUDIO_ACTIVE_NODUCK == 1) @enumToInt(ACC_UTILITY_STATE_FLAGS.PRIORITY_AUDIO_ACTIVE_NODUCK) else 0)
);
}
};
pub const ANRUS_ON_SCREEN_KEYBOARD_ACTIVE = ACC_UTILITY_STATE_FLAGS.ON_SCREEN_KEYBOARD_ACTIVE;
pub const ANRUS_TOUCH_MODIFICATION_ACTIVE = ACC_UTILITY_STATE_FLAGS.TOUCH_MODIFICATION_ACTIVE;
pub const ANRUS_PRIORITY_AUDIO_ACTIVE = ACC_UTILITY_STATE_FLAGS.PRIORITY_AUDIO_ACTIVE;
pub const ANRUS_PRIORITY_AUDIO_ACTIVE_NODUCK = ACC_UTILITY_STATE_FLAGS.PRIORITY_AUDIO_ACTIVE_NODUCK;
pub const SOUND_SENTRY_GRAPHICS_EFFECT = enum(u32) {
DISPLAY = 3,
NONE = 0,
};
pub const SSGF_DISPLAY = SOUND_SENTRY_GRAPHICS_EFFECT.DISPLAY;
pub const SSGF_NONE = SOUND_SENTRY_GRAPHICS_EFFECT.NONE;
pub const SERIALKEYS_FLAGS = enum(u32) {
AVAILABLE = 2,
INDICATOR = 4,
SERIALKEYSON = 1,
_,
pub fn initFlags(o: struct {
AVAILABLE: u1 = 0,
INDICATOR: u1 = 0,
SERIALKEYSON: u1 = 0,
}) SERIALKEYS_FLAGS {
return @intToEnum(SERIALKEYS_FLAGS,
(if (o.AVAILABLE == 1) @enumToInt(SERIALKEYS_FLAGS.AVAILABLE) else 0)
| (if (o.INDICATOR == 1) @enumToInt(SERIALKEYS_FLAGS.INDICATOR) else 0)
| (if (o.SERIALKEYSON == 1) @enumToInt(SERIALKEYS_FLAGS.SERIALKEYSON) else 0)
);
}
};
pub const SERKF_AVAILABLE = SERIALKEYS_FLAGS.AVAILABLE;
pub const SERKF_INDICATOR = SERIALKEYS_FLAGS.INDICATOR;
pub const SERKF_SERIALKEYSON = SERIALKEYS_FLAGS.SERIALKEYSON;
pub const HIGHCONTRASTW_FLAGS = enum(u32) {
HIGHCONTRASTON = 1,
AVAILABLE = 2,
HOTKEYACTIVE = 4,
CONFIRMHOTKEY = 8,
HOTKEYSOUND = 16,
INDICATOR = 32,
HOTKEYAVAILABLE = 64,
OPTION_NOTHEMECHANGE = 4096,
_,
pub fn initFlags(o: struct {
HIGHCONTRASTON: u1 = 0,
AVAILABLE: u1 = 0,
HOTKEYACTIVE: u1 = 0,
CONFIRMHOTKEY: u1 = 0,
HOTKEYSOUND: u1 = 0,
INDICATOR: u1 = 0,
HOTKEYAVAILABLE: u1 = 0,
OPTION_NOTHEMECHANGE: u1 = 0,
}) HIGHCONTRASTW_FLAGS {
return @intToEnum(HIGHCONTRASTW_FLAGS,
(if (o.HIGHCONTRASTON == 1) @enumToInt(HIGHCONTRASTW_FLAGS.HIGHCONTRASTON) else 0)
| (if (o.AVAILABLE == 1) @enumToInt(HIGHCONTRASTW_FLAGS.AVAILABLE) else 0)
| (if (o.HOTKEYACTIVE == 1) @enumToInt(HIGHCONTRASTW_FLAGS.HOTKEYACTIVE) else 0)
| (if (o.CONFIRMHOTKEY == 1) @enumToInt(HIGHCONTRASTW_FLAGS.CONFIRMHOTKEY) else 0)
| (if (o.HOTKEYSOUND == 1) @enumToInt(HIGHCONTRASTW_FLAGS.HOTKEYSOUND) else 0)
| (if (o.INDICATOR == 1) @enumToInt(HIGHCONTRASTW_FLAGS.INDICATOR) else 0)
| (if (o.HOTKEYAVAILABLE == 1) @enumToInt(HIGHCONTRASTW_FLAGS.HOTKEYAVAILABLE) else 0)
| (if (o.OPTION_NOTHEMECHANGE == 1) @enumToInt(HIGHCONTRASTW_FLAGS.OPTION_NOTHEMECHANGE) else 0)
);
}
};
pub const HCF_HIGHCONTRASTON = HIGHCONTRASTW_FLAGS.HIGHCONTRASTON;
pub const HCF_AVAILABLE = HIGHCONTRASTW_FLAGS.AVAILABLE;
pub const HCF_HOTKEYACTIVE = HIGHCONTRASTW_FLAGS.HOTKEYACTIVE;
pub const HCF_CONFIRMHOTKEY = HIGHCONTRASTW_FLAGS.CONFIRMHOTKEY;
pub const HCF_HOTKEYSOUND = HIGHCONTRASTW_FLAGS.HOTKEYSOUND;
pub const HCF_INDICATOR = HIGHCONTRASTW_FLAGS.INDICATOR;
pub const HCF_HOTKEYAVAILABLE = HIGHCONTRASTW_FLAGS.HOTKEYAVAILABLE;
pub const HCF_OPTION_NOTHEMECHANGE = HIGHCONTRASTW_FLAGS.OPTION_NOTHEMECHANGE;
pub const SOUNDSENTRY_TEXT_EFFECT = enum(u32) {
BORDER = 2,
CHARS = 1,
DISPLAY = 3,
NONE = 0,
};
pub const SSTF_BORDER = SOUNDSENTRY_TEXT_EFFECT.BORDER;
pub const SSTF_CHARS = SOUNDSENTRY_TEXT_EFFECT.CHARS;
pub const SSTF_DISPLAY = SOUNDSENTRY_TEXT_EFFECT.DISPLAY;
pub const SSTF_NONE = SOUNDSENTRY_TEXT_EFFECT.NONE;
pub const SOUNDSENTRY_WINDOWS_EFFECT = enum(u32) {
CUSTOM = 4,
DISPLAY = 3,
NONE = 0,
TITLE = 1,
WINDOW = 2,
};
pub const SSWF_CUSTOM = SOUNDSENTRY_WINDOWS_EFFECT.CUSTOM;
pub const SSWF_DISPLAY = SOUNDSENTRY_WINDOWS_EFFECT.DISPLAY;
pub const SSWF_NONE = SOUNDSENTRY_WINDOWS_EFFECT.NONE;
pub const SSWF_TITLE = SOUNDSENTRY_WINDOWS_EFFECT.TITLE;
pub const SSWF_WINDOW = SOUNDSENTRY_WINDOWS_EFFECT.WINDOW;
// TODO: this type has a FreeFunc 'UnhookWinEvent', what can Zig do with this information?
pub const HWINEVENTHOOK = *opaque{};
pub const HUIANODE = *opaque{};
pub const HUIAPATTERNOBJECT = *opaque{};
pub const HUIATEXTRANGE = *opaque{};
pub const HUIAEVENT = *opaque{};
pub const SERIALKEYSA = extern struct {
cbSize: u32,
dwFlags: SERIALKEYS_FLAGS,
lpszActivePort: ?PSTR,
lpszPort: ?PSTR,
iBaudRate: u32,
iPortState: u32,
iActive: u32,
};
pub const SERIALKEYSW = extern struct {
cbSize: u32,
dwFlags: SERIALKEYS_FLAGS,
lpszActivePort: ?PWSTR,
lpszPort: ?PWSTR,
iBaudRate: u32,
iPortState: u32,
iActive: u32,
};
pub const HIGHCONTRASTA = extern struct {
cbSize: u32,
dwFlags: HIGHCONTRASTW_FLAGS,
lpszDefaultScheme: ?PSTR,
};
pub const HIGHCONTRASTW = extern struct {
cbSize: u32,
dwFlags: HIGHCONTRASTW_FLAGS,
lpszDefaultScheme: ?PWSTR,
};
pub const FILTERKEYS = extern struct {
cbSize: u32,
dwFlags: u32,
iWaitMSec: u32,
iDelayMSec: u32,
iRepeatMSec: u32,
iBounceMSec: u32,
};
pub const STICKYKEYS = extern struct {
cbSize: u32,
dwFlags: STICKYKEYS_FLAGS,
};
pub const MOUSEKEYS = extern struct {
cbSize: u32,
dwFlags: u32,
iMaxSpeed: u32,
iTimeToMaxSpeed: u32,
iCtrlSpeed: u32,
dwReserved1: u32,
dwReserved2: u32,
};
pub const ACCESSTIMEOUT = extern struct {
cbSize: u32,
dwFlags: u32,
iTimeOutMSec: u32,
};
pub const SOUNDSENTRYA = extern struct {
cbSize: u32,
dwFlags: SOUNDSENTRY_FLAGS,
iFSTextEffect: SOUNDSENTRY_TEXT_EFFECT,
iFSTextEffectMSec: u32,
iFSTextEffectColorBits: u32,
iFSGrafEffect: SOUND_SENTRY_GRAPHICS_EFFECT,
iFSGrafEffectMSec: u32,
iFSGrafEffectColor: u32,
iWindowsEffect: SOUNDSENTRY_WINDOWS_EFFECT,
iWindowsEffectMSec: u32,
lpszWindowsEffectDLL: ?PSTR,
iWindowsEffectOrdinal: u32,
};
pub const SOUNDSENTRYW = extern struct {
cbSize: u32,
dwFlags: SOUNDSENTRY_FLAGS,
iFSTextEffect: SOUNDSENTRY_TEXT_EFFECT,
iFSTextEffectMSec: u32,
iFSTextEffectColorBits: u32,
iFSGrafEffect: SOUND_SENTRY_GRAPHICS_EFFECT,
iFSGrafEffectMSec: u32,
iFSGrafEffectColor: u32,
iWindowsEffect: SOUNDSENTRY_WINDOWS_EFFECT,
iWindowsEffectMSec: u32,
lpszWindowsEffectDLL: ?PWSTR,
iWindowsEffectOrdinal: u32,
};
pub const TOGGLEKEYS = extern struct {
cbSize: u32,
dwFlags: u32,
};
pub const WINEVENTPROC = fn(
hWinEventHook: ?HWINEVENTHOOK,
event: u32,
hwnd: ?HWND,
idObject: i32,
idChild: i32,
idEventThread: u32,
dwmsEventTime: u32,
) callconv(@import("std").os.windows.WINAPI) void;
const CLSID_CAccPropServices_Value = @import("../zig.zig").Guid.initString("b5f8350b-0548-48b1-a6ee-88bd00b4a5e7");
pub const CLSID_CAccPropServices = &CLSID_CAccPropServices_Value;
pub const LPFNLRESULTFROMOBJECT = fn(
riid: ?*const Guid,
wParam: WPARAM,
punk: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
pub const LPFNOBJECTFROMLRESULT = fn(
lResult: LRESULT,
riid: ?*const Guid,
wParam: WPARAM,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPFNACCESSIBLEOBJECTFROMWINDOW = fn(
hwnd: ?HWND,
dwId: u32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPFNACCESSIBLEOBJECTFROMPOINT = fn(
ptScreen: POINT,
ppacc: ?*?*IAccessible,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPFNCREATESTDACCESSIBLEOBJECT = fn(
hwnd: ?HWND,
idObject: i32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPFNACCESSIBLECHILDREN = fn(
paccContainer: ?*IAccessible,
iChildStart: i32,
cChildren: i32,
rgvarChildren: ?*VARIANT,
pcObtained: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const MSAAMENUINFO = extern struct {
dwMSAASignature: u32,
cchWText: u32,
pszWText: ?PWSTR,
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IAccessible_Value = @import("../zig.zig").Guid.initString("618736e0-3c3d-11cf-810c-00aa00389b71");
pub const IID_IAccessible = &IID_IAccessible_Value;
pub const IAccessible = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accParent: fn(
self: *const IAccessible,
ppdispParent: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accChildCount: fn(
self: *const IAccessible,
pcountChildren: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accChild: fn(
self: *const IAccessible,
varChild: VARIANT,
ppdispChild: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accName: fn(
self: *const IAccessible,
varChild: VARIANT,
pszName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accValue: fn(
self: *const IAccessible,
varChild: VARIANT,
pszValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accDescription: fn(
self: *const IAccessible,
varChild: VARIANT,
pszDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accRole: fn(
self: *const IAccessible,
varChild: VARIANT,
pvarRole: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accState: fn(
self: *const IAccessible,
varChild: VARIANT,
pvarState: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accHelp: fn(
self: *const IAccessible,
varChild: VARIANT,
pszHelp: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accHelpTopic: fn(
self: *const IAccessible,
pszHelpFile: ?*?BSTR,
varChild: VARIANT,
pidTopic: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accKeyboardShortcut: fn(
self: *const IAccessible,
varChild: VARIANT,
pszKeyboardShortcut: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accFocus: fn(
self: *const IAccessible,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accSelection: fn(
self: *const IAccessible,
pvarChildren: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_accDefaultAction: fn(
self: *const IAccessible,
varChild: VARIANT,
pszDefaultAction: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
accSelect: fn(
self: *const IAccessible,
flagsSelect: i32,
varChild: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
accLocation: fn(
self: *const IAccessible,
pxLeft: ?*i32,
pyTop: ?*i32,
pcxWidth: ?*i32,
pcyHeight: ?*i32,
varChild: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
accNavigate: fn(
self: *const IAccessible,
navDir: i32,
varStart: VARIANT,
pvarEndUpAt: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
accHitTest: fn(
self: *const IAccessible,
xLeft: i32,
yTop: i32,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
accDoDefaultAction: fn(
self: *const IAccessible,
varChild: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_accName: fn(
self: *const IAccessible,
varChild: VARIANT,
szName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_accValue: fn(
self: *const IAccessible,
varChild: VARIANT,
szValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accParent(self: *const T, ppdispParent: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accParent(@ptrCast(*const IAccessible, self), ppdispParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accChildCount(self: *const T, pcountChildren: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accChildCount(@ptrCast(*const IAccessible, self), pcountChildren);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accChild(self: *const T, varChild: VARIANT, ppdispChild: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accChild(@ptrCast(*const IAccessible, self), varChild, ppdispChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accName(self: *const T, varChild: VARIANT, pszName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accName(@ptrCast(*const IAccessible, self), varChild, pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accValue(self: *const T, varChild: VARIANT, pszValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accValue(@ptrCast(*const IAccessible, self), varChild, pszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accDescription(self: *const T, varChild: VARIANT, pszDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accDescription(@ptrCast(*const IAccessible, self), varChild, pszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accRole(self: *const T, varChild: VARIANT, pvarRole: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accRole(@ptrCast(*const IAccessible, self), varChild, pvarRole);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accState(self: *const T, varChild: VARIANT, pvarState: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accState(@ptrCast(*const IAccessible, self), varChild, pvarState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accHelp(self: *const T, varChild: VARIANT, pszHelp: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accHelp(@ptrCast(*const IAccessible, self), varChild, pszHelp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accHelpTopic(self: *const T, pszHelpFile: ?*?BSTR, varChild: VARIANT, pidTopic: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accHelpTopic(@ptrCast(*const IAccessible, self), pszHelpFile, varChild, pidTopic);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accKeyboardShortcut(self: *const T, varChild: VARIANT, pszKeyboardShortcut: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accKeyboardShortcut(@ptrCast(*const IAccessible, self), varChild, pszKeyboardShortcut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accFocus(self: *const T, pvarChild: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accFocus(@ptrCast(*const IAccessible, self), pvarChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accSelection(self: *const T, pvarChildren: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accSelection(@ptrCast(*const IAccessible, self), pvarChildren);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_get_accDefaultAction(self: *const T, varChild: VARIANT, pszDefaultAction: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).get_accDefaultAction(@ptrCast(*const IAccessible, self), varChild, pszDefaultAction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_accSelect(self: *const T, flagsSelect: i32, varChild: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).accSelect(@ptrCast(*const IAccessible, self), flagsSelect, varChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_accLocation(self: *const T, pxLeft: ?*i32, pyTop: ?*i32, pcxWidth: ?*i32, pcyHeight: ?*i32, varChild: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).accLocation(@ptrCast(*const IAccessible, self), pxLeft, pyTop, pcxWidth, pcyHeight, varChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_accNavigate(self: *const T, navDir: i32, varStart: VARIANT, pvarEndUpAt: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).accNavigate(@ptrCast(*const IAccessible, self), navDir, varStart, pvarEndUpAt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_accHitTest(self: *const T, xLeft: i32, yTop: i32, pvarChild: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).accHitTest(@ptrCast(*const IAccessible, self), xLeft, yTop, pvarChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_accDoDefaultAction(self: *const T, varChild: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).accDoDefaultAction(@ptrCast(*const IAccessible, self), varChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_put_accName(self: *const T, varChild: VARIANT, szName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).put_accName(@ptrCast(*const IAccessible, self), varChild, szName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessible_put_accValue(self: *const T, varChild: VARIANT, szValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessible.VTable, self.vtable).put_accValue(@ptrCast(*const IAccessible, self), varChild, szValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IAccessibleHandler_Value = @import("../zig.zig").Guid.initString("03022430-abc4-11d0-bde2-00aa001a1953");
pub const IID_IAccessibleHandler = &IID_IAccessibleHandler_Value;
pub const IAccessibleHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AccessibleObjectFromID: fn(
self: *const IAccessibleHandler,
hwnd: i32,
lObjectID: i32,
pIAccessible: ?*?*IAccessible,
) 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 IAccessibleHandler_AccessibleObjectFromID(self: *const T, hwnd: i32, lObjectID: i32, pIAccessible: ?*?*IAccessible) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleHandler.VTable, self.vtable).AccessibleObjectFromID(@ptrCast(*const IAccessibleHandler, self), hwnd, lObjectID, pIAccessible);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IAccessibleWindowlessSite_Value = @import("../zig.zig").Guid.initString("bf3abd9c-76da-4389-9eb6-1427d25abab7");
pub const IID_IAccessibleWindowlessSite = &IID_IAccessibleWindowlessSite_Value;
pub const IAccessibleWindowlessSite = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AcquireObjectIdRange: fn(
self: *const IAccessibleWindowlessSite,
rangeSize: i32,
pRangeOwner: ?*IAccessibleHandler,
pRangeBase: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseObjectIdRange: fn(
self: *const IAccessibleWindowlessSite,
rangeBase: i32,
pRangeOwner: ?*IAccessibleHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryObjectIdRanges: fn(
self: *const IAccessibleWindowlessSite,
pRangesOwner: ?*IAccessibleHandler,
psaRanges: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParentAccessible: fn(
self: *const IAccessibleWindowlessSite,
ppParent: ?*?*IAccessible,
) 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 IAccessibleWindowlessSite_AcquireObjectIdRange(self: *const T, rangeSize: i32, pRangeOwner: ?*IAccessibleHandler, pRangeBase: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleWindowlessSite.VTable, self.vtable).AcquireObjectIdRange(@ptrCast(*const IAccessibleWindowlessSite, self), rangeSize, pRangeOwner, pRangeBase);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleWindowlessSite_ReleaseObjectIdRange(self: *const T, rangeBase: i32, pRangeOwner: ?*IAccessibleHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleWindowlessSite.VTable, self.vtable).ReleaseObjectIdRange(@ptrCast(*const IAccessibleWindowlessSite, self), rangeBase, pRangeOwner);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleWindowlessSite_QueryObjectIdRanges(self: *const T, pRangesOwner: ?*IAccessibleHandler, psaRanges: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleWindowlessSite.VTable, self.vtable).QueryObjectIdRanges(@ptrCast(*const IAccessibleWindowlessSite, self), pRangesOwner, psaRanges);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleWindowlessSite_GetParentAccessible(self: *const T, ppParent: ?*?*IAccessible) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleWindowlessSite.VTable, self.vtable).GetParentAccessible(@ptrCast(*const IAccessibleWindowlessSite, self), ppParent);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const AnnoScope = enum(i32) {
THIS = 0,
CONTAINER = 1,
};
pub const ANNO_THIS = AnnoScope.THIS;
pub const ANNO_CONTAINER = AnnoScope.CONTAINER;
// TODO: this type is limited to platform 'windows5.0'
const IID_IAccIdentity_Value = @import("../zig.zig").Guid.initString("7852b78d-1cfd-41c1-a615-9c0c85960b5f");
pub const IID_IAccIdentity = &IID_IAccIdentity_Value;
pub const IAccIdentity = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetIdentityString: fn(
self: *const IAccIdentity,
dwIDChild: u32,
ppIDString: [*]?*u8,
pdwIDStringLen: ?*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 IAccIdentity_GetIdentityString(self: *const T, dwIDChild: u32, ppIDString: [*]?*u8, pdwIDStringLen: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccIdentity.VTable, self.vtable).GetIdentityString(@ptrCast(*const IAccIdentity, self), dwIDChild, ppIDString, pdwIDStringLen);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IAccPropServer_Value = @import("../zig.zig").Guid.initString("76c0dbbb-15e0-4e7b-b61b-20eeea2001e0");
pub const IID_IAccPropServer = &IID_IAccPropServer_Value;
pub const IAccPropServer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPropValue: fn(
self: *const IAccPropServer,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
idProp: Guid,
pvarValue: ?*VARIANT,
pfHasProp: ?*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 IAccPropServer_GetPropValue(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, idProp: Guid, pvarValue: ?*VARIANT, pfHasProp: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServer.VTable, self.vtable).GetPropValue(@ptrCast(*const IAccPropServer, self), pIDString, dwIDStringLen, idProp, pvarValue, pfHasProp);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IAccPropServices_Value = @import("../zig.zig").Guid.initString("6e26e776-04f0-495d-80e4-3330352e3169");
pub const IID_IAccPropServices = &IID_IAccPropServices_Value;
pub const IAccPropServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetPropValue: fn(
self: *const IAccPropServices,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
idProp: Guid,
@"var": VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPropServer: fn(
self: *const IAccPropServices,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
paProps: [*]const Guid,
cProps: i32,
pServer: ?*IAccPropServer,
annoScope: AnnoScope,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearProps: fn(
self: *const IAccPropServices,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
paProps: [*]const Guid,
cProps: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHwndProp: fn(
self: *const IAccPropServices,
hwnd: ?HWND,
idObject: u32,
idChild: u32,
idProp: Guid,
@"var": VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHwndPropStr: fn(
self: *const IAccPropServices,
hwnd: ?HWND,
idObject: u32,
idChild: u32,
idProp: Guid,
str: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHwndPropServer: fn(
self: *const IAccPropServices,
hwnd: ?HWND,
idObject: u32,
idChild: u32,
paProps: [*]const Guid,
cProps: i32,
pServer: ?*IAccPropServer,
annoScope: AnnoScope,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearHwndProps: fn(
self: *const IAccPropServices,
hwnd: ?HWND,
idObject: u32,
idChild: u32,
paProps: [*]const Guid,
cProps: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ComposeHwndIdentityString: fn(
self: *const IAccPropServices,
hwnd: ?HWND,
idObject: u32,
idChild: u32,
ppIDString: [*]?*u8,
pdwIDStringLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DecomposeHwndIdentityString: fn(
self: *const IAccPropServices,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
phwnd: ?*?HWND,
pidObject: ?*u32,
pidChild: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHmenuProp: fn(
self: *const IAccPropServices,
hmenu: ?HMENU,
idChild: u32,
idProp: Guid,
@"var": VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHmenuPropStr: fn(
self: *const IAccPropServices,
hmenu: ?HMENU,
idChild: u32,
idProp: Guid,
str: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHmenuPropServer: fn(
self: *const IAccPropServices,
hmenu: ?HMENU,
idChild: u32,
paProps: [*]const Guid,
cProps: i32,
pServer: ?*IAccPropServer,
annoScope: AnnoScope,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearHmenuProps: fn(
self: *const IAccPropServices,
hmenu: ?HMENU,
idChild: u32,
paProps: [*]const Guid,
cProps: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ComposeHmenuIdentityString: fn(
self: *const IAccPropServices,
hmenu: ?HMENU,
idChild: u32,
ppIDString: [*]?*u8,
pdwIDStringLen: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DecomposeHmenuIdentityString: fn(
self: *const IAccPropServices,
pIDString: [*:0]const u8,
dwIDStringLen: u32,
phmenu: ?*?HMENU,
pidChild: ?*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 IAccPropServices_SetPropValue(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, idProp: Guid, @"var": VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetPropValue(@ptrCast(*const IAccPropServices, self), pIDString, dwIDStringLen, idProp, @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetPropServer(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, paProps: [*]const Guid, cProps: i32, pServer: ?*IAccPropServer, annoScope: AnnoScope) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetPropServer(@ptrCast(*const IAccPropServices, self), pIDString, dwIDStringLen, paProps, cProps, pServer, annoScope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_ClearProps(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, paProps: [*]const Guid, cProps: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).ClearProps(@ptrCast(*const IAccPropServices, self), pIDString, dwIDStringLen, paProps, cProps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHwndProp(self: *const T, hwnd: ?HWND, idObject: u32, idChild: u32, idProp: Guid, @"var": VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHwndProp(@ptrCast(*const IAccPropServices, self), hwnd, idObject, idChild, idProp, @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHwndPropStr(self: *const T, hwnd: ?HWND, idObject: u32, idChild: u32, idProp: Guid, str: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHwndPropStr(@ptrCast(*const IAccPropServices, self), hwnd, idObject, idChild, idProp, str);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHwndPropServer(self: *const T, hwnd: ?HWND, idObject: u32, idChild: u32, paProps: [*]const Guid, cProps: i32, pServer: ?*IAccPropServer, annoScope: AnnoScope) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHwndPropServer(@ptrCast(*const IAccPropServices, self), hwnd, idObject, idChild, paProps, cProps, pServer, annoScope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_ClearHwndProps(self: *const T, hwnd: ?HWND, idObject: u32, idChild: u32, paProps: [*]const Guid, cProps: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).ClearHwndProps(@ptrCast(*const IAccPropServices, self), hwnd, idObject, idChild, paProps, cProps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_ComposeHwndIdentityString(self: *const T, hwnd: ?HWND, idObject: u32, idChild: u32, ppIDString: [*]?*u8, pdwIDStringLen: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).ComposeHwndIdentityString(@ptrCast(*const IAccPropServices, self), hwnd, idObject, idChild, ppIDString, pdwIDStringLen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_DecomposeHwndIdentityString(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, phwnd: ?*?HWND, pidObject: ?*u32, pidChild: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).DecomposeHwndIdentityString(@ptrCast(*const IAccPropServices, self), pIDString, dwIDStringLen, phwnd, pidObject, pidChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHmenuProp(self: *const T, hmenu: ?HMENU, idChild: u32, idProp: Guid, @"var": VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHmenuProp(@ptrCast(*const IAccPropServices, self), hmenu, idChild, idProp, @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHmenuPropStr(self: *const T, hmenu: ?HMENU, idChild: u32, idProp: Guid, str: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHmenuPropStr(@ptrCast(*const IAccPropServices, self), hmenu, idChild, idProp, str);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_SetHmenuPropServer(self: *const T, hmenu: ?HMENU, idChild: u32, paProps: [*]const Guid, cProps: i32, pServer: ?*IAccPropServer, annoScope: AnnoScope) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).SetHmenuPropServer(@ptrCast(*const IAccPropServices, self), hmenu, idChild, paProps, cProps, pServer, annoScope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_ClearHmenuProps(self: *const T, hmenu: ?HMENU, idChild: u32, paProps: [*]const Guid, cProps: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).ClearHmenuProps(@ptrCast(*const IAccPropServices, self), hmenu, idChild, paProps, cProps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_ComposeHmenuIdentityString(self: *const T, hmenu: ?HMENU, idChild: u32, ppIDString: [*]?*u8, pdwIDStringLen: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).ComposeHmenuIdentityString(@ptrCast(*const IAccPropServices, self), hmenu, idChild, ppIDString, pdwIDStringLen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccPropServices_DecomposeHmenuIdentityString(self: *const T, pIDString: [*:0]const u8, dwIDStringLen: u32, phmenu: ?*?HMENU, pidChild: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccPropServices.VTable, self.vtable).DecomposeHmenuIdentityString(@ptrCast(*const IAccPropServices, self), pIDString, dwIDStringLen, phmenu, pidChild);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_CUIAutomation_Value = @import("../zig.zig").Guid.initString("ff48dba4-60ef-4201-aa87-54103eef594e");
pub const CLSID_CUIAutomation = &CLSID_CUIAutomation_Value;
const CLSID_CUIAutomation8_Value = @import("../zig.zig").Guid.initString("e22ad333-b25f-460c-83d0-0581107395c9");
pub const CLSID_CUIAutomation8 = &CLSID_CUIAutomation8_Value;
const CLSID_CUIAutomationRegistrar_Value = @import("../zig.zig").Guid.initString("6e29fabf-9977-42d1-8d0e-ca7e61ad87e6");
pub const CLSID_CUIAutomationRegistrar = &CLSID_CUIAutomationRegistrar_Value;
pub const NavigateDirection = enum(i32) {
Parent = 0,
NextSibling = 1,
PreviousSibling = 2,
FirstChild = 3,
LastChild = 4,
};
pub const NavigateDirection_Parent = NavigateDirection.Parent;
pub const NavigateDirection_NextSibling = NavigateDirection.NextSibling;
pub const NavigateDirection_PreviousSibling = NavigateDirection.PreviousSibling;
pub const NavigateDirection_FirstChild = NavigateDirection.FirstChild;
pub const NavigateDirection_LastChild = NavigateDirection.LastChild;
pub const ProviderOptions = enum(i32) {
ClientSideProvider = 1,
ServerSideProvider = 2,
NonClientAreaProvider = 4,
OverrideProvider = 8,
ProviderOwnsSetFocus = 16,
UseComThreading = 32,
RefuseNonClientSupport = 64,
HasNativeIAccessible = 128,
UseClientCoordinates = 256,
};
pub const ProviderOptions_ClientSideProvider = ProviderOptions.ClientSideProvider;
pub const ProviderOptions_ServerSideProvider = ProviderOptions.ServerSideProvider;
pub const ProviderOptions_NonClientAreaProvider = ProviderOptions.NonClientAreaProvider;
pub const ProviderOptions_OverrideProvider = ProviderOptions.OverrideProvider;
pub const ProviderOptions_ProviderOwnsSetFocus = ProviderOptions.ProviderOwnsSetFocus;
pub const ProviderOptions_UseComThreading = ProviderOptions.UseComThreading;
pub const ProviderOptions_RefuseNonClientSupport = ProviderOptions.RefuseNonClientSupport;
pub const ProviderOptions_HasNativeIAccessible = ProviderOptions.HasNativeIAccessible;
pub const ProviderOptions_UseClientCoordinates = ProviderOptions.UseClientCoordinates;
pub const StructureChangeType = enum(i32) {
Added = 0,
Removed = 1,
renInvalidated = 2,
renBulkAdded = 3,
renBulkRemoved = 4,
renReordered = 5,
};
pub const StructureChangeType_ChildAdded = StructureChangeType.Added;
pub const StructureChangeType_ChildRemoved = StructureChangeType.Removed;
pub const StructureChangeType_ChildrenInvalidated = StructureChangeType.renInvalidated;
pub const StructureChangeType_ChildrenBulkAdded = StructureChangeType.renBulkAdded;
pub const StructureChangeType_ChildrenBulkRemoved = StructureChangeType.renBulkRemoved;
pub const StructureChangeType_ChildrenReordered = StructureChangeType.renReordered;
pub const TextEditChangeType = enum(i32) {
None = 0,
AutoCorrect = 1,
Composition = 2,
CompositionFinalized = 3,
AutoComplete = 4,
};
pub const TextEditChangeType_None = TextEditChangeType.None;
pub const TextEditChangeType_AutoCorrect = TextEditChangeType.AutoCorrect;
pub const TextEditChangeType_Composition = TextEditChangeType.Composition;
pub const TextEditChangeType_CompositionFinalized = TextEditChangeType.CompositionFinalized;
pub const TextEditChangeType_AutoComplete = TextEditChangeType.AutoComplete;
pub const OrientationType = enum(i32) {
None = 0,
Horizontal = 1,
Vertical = 2,
};
pub const OrientationType_None = OrientationType.None;
pub const OrientationType_Horizontal = OrientationType.Horizontal;
pub const OrientationType_Vertical = OrientationType.Vertical;
pub const DockPosition = enum(i32) {
Top = 0,
Left = 1,
Bottom = 2,
Right = 3,
Fill = 4,
None = 5,
};
pub const DockPosition_Top = DockPosition.Top;
pub const DockPosition_Left = DockPosition.Left;
pub const DockPosition_Bottom = DockPosition.Bottom;
pub const DockPosition_Right = DockPosition.Right;
pub const DockPosition_Fill = DockPosition.Fill;
pub const DockPosition_None = DockPosition.None;
pub const ExpandCollapseState = enum(i32) {
Collapsed = 0,
Expanded = 1,
PartiallyExpanded = 2,
LeafNode = 3,
};
pub const ExpandCollapseState_Collapsed = ExpandCollapseState.Collapsed;
pub const ExpandCollapseState_Expanded = ExpandCollapseState.Expanded;
pub const ExpandCollapseState_PartiallyExpanded = ExpandCollapseState.PartiallyExpanded;
pub const ExpandCollapseState_LeafNode = ExpandCollapseState.LeafNode;
pub const ScrollAmount = enum(i32) {
LargeDecrement = 0,
SmallDecrement = 1,
NoAmount = 2,
LargeIncrement = 3,
SmallIncrement = 4,
};
pub const ScrollAmount_LargeDecrement = ScrollAmount.LargeDecrement;
pub const ScrollAmount_SmallDecrement = ScrollAmount.SmallDecrement;
pub const ScrollAmount_NoAmount = ScrollAmount.NoAmount;
pub const ScrollAmount_LargeIncrement = ScrollAmount.LargeIncrement;
pub const ScrollAmount_SmallIncrement = ScrollAmount.SmallIncrement;
pub const RowOrColumnMajor = enum(i32) {
RowMajor = 0,
ColumnMajor = 1,
Indeterminate = 2,
};
pub const RowOrColumnMajor_RowMajor = RowOrColumnMajor.RowMajor;
pub const RowOrColumnMajor_ColumnMajor = RowOrColumnMajor.ColumnMajor;
pub const RowOrColumnMajor_Indeterminate = RowOrColumnMajor.Indeterminate;
pub const ToggleState = enum(i32) {
Off = 0,
On = 1,
Indeterminate = 2,
};
pub const ToggleState_Off = ToggleState.Off;
pub const ToggleState_On = ToggleState.On;
pub const ToggleState_Indeterminate = ToggleState.Indeterminate;
pub const WindowVisualState = enum(i32) {
Normal = 0,
Maximized = 1,
Minimized = 2,
};
pub const WindowVisualState_Normal = WindowVisualState.Normal;
pub const WindowVisualState_Maximized = WindowVisualState.Maximized;
pub const WindowVisualState_Minimized = WindowVisualState.Minimized;
pub const SynchronizedInputType = enum(i32) {
KeyUp = 1,
KeyDown = 2,
LeftMouseUp = 4,
LeftMouseDown = 8,
RightMouseUp = 16,
RightMouseDown = 32,
};
pub const SynchronizedInputType_KeyUp = SynchronizedInputType.KeyUp;
pub const SynchronizedInputType_KeyDown = SynchronizedInputType.KeyDown;
pub const SynchronizedInputType_LeftMouseUp = SynchronizedInputType.LeftMouseUp;
pub const SynchronizedInputType_LeftMouseDown = SynchronizedInputType.LeftMouseDown;
pub const SynchronizedInputType_RightMouseUp = SynchronizedInputType.RightMouseUp;
pub const SynchronizedInputType_RightMouseDown = SynchronizedInputType.RightMouseDown;
pub const WindowInteractionState = enum(i32) {
Running = 0,
Closing = 1,
ReadyForUserInteraction = 2,
BlockedByModalWindow = 3,
NotResponding = 4,
};
pub const WindowInteractionState_Running = WindowInteractionState.Running;
pub const WindowInteractionState_Closing = WindowInteractionState.Closing;
pub const WindowInteractionState_ReadyForUserInteraction = WindowInteractionState.ReadyForUserInteraction;
pub const WindowInteractionState_BlockedByModalWindow = WindowInteractionState.BlockedByModalWindow;
pub const WindowInteractionState_NotResponding = WindowInteractionState.NotResponding;
pub const SayAsInterpretAs = enum(i32) {
None = 0,
Spell = 1,
Cardinal = 2,
Ordinal = 3,
Number = 4,
Date = 5,
Time = 6,
Telephone = 7,
Currency = 8,
Net = 9,
Url = 10,
Address = 11,
Alphanumeric = 12,
Name = 13,
Media = 14,
Date_MonthDayYear = 15,
Date_DayMonthYear = 16,
Date_YearMonthDay = 17,
Date_YearMonth = 18,
Date_MonthYear = 19,
Date_DayMonth = 20,
Date_MonthDay = 21,
Date_Year = 22,
Time_HoursMinutesSeconds12 = 23,
Time_HoursMinutes12 = 24,
Time_HoursMinutesSeconds24 = 25,
Time_HoursMinutes24 = 26,
};
pub const SayAsInterpretAs_None = SayAsInterpretAs.None;
pub const SayAsInterpretAs_Spell = SayAsInterpretAs.Spell;
pub const SayAsInterpretAs_Cardinal = SayAsInterpretAs.Cardinal;
pub const SayAsInterpretAs_Ordinal = SayAsInterpretAs.Ordinal;
pub const SayAsInterpretAs_Number = SayAsInterpretAs.Number;
pub const SayAsInterpretAs_Date = SayAsInterpretAs.Date;
pub const SayAsInterpretAs_Time = SayAsInterpretAs.Time;
pub const SayAsInterpretAs_Telephone = SayAsInterpretAs.Telephone;
pub const SayAsInterpretAs_Currency = SayAsInterpretAs.Currency;
pub const SayAsInterpretAs_Net = SayAsInterpretAs.Net;
pub const SayAsInterpretAs_Url = SayAsInterpretAs.Url;
pub const SayAsInterpretAs_Address = SayAsInterpretAs.Address;
pub const SayAsInterpretAs_Alphanumeric = SayAsInterpretAs.Alphanumeric;
pub const SayAsInterpretAs_Name = SayAsInterpretAs.Name;
pub const SayAsInterpretAs_Media = SayAsInterpretAs.Media;
pub const SayAsInterpretAs_Date_MonthDayYear = SayAsInterpretAs.Date_MonthDayYear;
pub const SayAsInterpretAs_Date_DayMonthYear = SayAsInterpretAs.Date_DayMonthYear;
pub const SayAsInterpretAs_Date_YearMonthDay = SayAsInterpretAs.Date_YearMonthDay;
pub const SayAsInterpretAs_Date_YearMonth = SayAsInterpretAs.Date_YearMonth;
pub const SayAsInterpretAs_Date_MonthYear = SayAsInterpretAs.Date_MonthYear;
pub const SayAsInterpretAs_Date_DayMonth = SayAsInterpretAs.Date_DayMonth;
pub const SayAsInterpretAs_Date_MonthDay = SayAsInterpretAs.Date_MonthDay;
pub const SayAsInterpretAs_Date_Year = SayAsInterpretAs.Date_Year;
pub const SayAsInterpretAs_Time_HoursMinutesSeconds12 = SayAsInterpretAs.Time_HoursMinutesSeconds12;
pub const SayAsInterpretAs_Time_HoursMinutes12 = SayAsInterpretAs.Time_HoursMinutes12;
pub const SayAsInterpretAs_Time_HoursMinutesSeconds24 = SayAsInterpretAs.Time_HoursMinutesSeconds24;
pub const SayAsInterpretAs_Time_HoursMinutes24 = SayAsInterpretAs.Time_HoursMinutes24;
pub const TextUnit = enum(i32) {
Character = 0,
Format = 1,
Word = 2,
Line = 3,
Paragraph = 4,
Page = 5,
Document = 6,
};
pub const TextUnit_Character = TextUnit.Character;
pub const TextUnit_Format = TextUnit.Format;
pub const TextUnit_Word = TextUnit.Word;
pub const TextUnit_Line = TextUnit.Line;
pub const TextUnit_Paragraph = TextUnit.Paragraph;
pub const TextUnit_Page = TextUnit.Page;
pub const TextUnit_Document = TextUnit.Document;
pub const TextPatternRangeEndpoint = enum(i32) {
Start = 0,
End = 1,
};
pub const TextPatternRangeEndpoint_Start = TextPatternRangeEndpoint.Start;
pub const TextPatternRangeEndpoint_End = TextPatternRangeEndpoint.End;
pub const SupportedTextSelection = enum(i32) {
None = 0,
Single = 1,
Multiple = 2,
};
pub const SupportedTextSelection_None = SupportedTextSelection.None;
pub const SupportedTextSelection_Single = SupportedTextSelection.Single;
pub const SupportedTextSelection_Multiple = SupportedTextSelection.Multiple;
pub const LiveSetting = enum(i32) {
Off = 0,
Polite = 1,
Assertive = 2,
};
pub const Off = LiveSetting.Off;
pub const Polite = LiveSetting.Polite;
pub const Assertive = LiveSetting.Assertive;
pub const ActiveEnd = enum(i32) {
None = 0,
Start = 1,
End = 2,
};
pub const ActiveEnd_None = ActiveEnd.None;
pub const ActiveEnd_Start = ActiveEnd.Start;
pub const ActiveEnd_End = ActiveEnd.End;
pub const CaretPosition = enum(i32) {
Unknown = 0,
EndOfLine = 1,
BeginningOfLine = 2,
};
pub const CaretPosition_Unknown = CaretPosition.Unknown;
pub const CaretPosition_EndOfLine = CaretPosition.EndOfLine;
pub const CaretPosition_BeginningOfLine = CaretPosition.BeginningOfLine;
pub const CaretBidiMode = enum(i32) {
LTR = 0,
RTL = 1,
};
pub const CaretBidiMode_LTR = CaretBidiMode.LTR;
pub const CaretBidiMode_RTL = CaretBidiMode.RTL;
pub const ZoomUnit = enum(i32) {
NoAmount = 0,
LargeDecrement = 1,
SmallDecrement = 2,
LargeIncrement = 3,
SmallIncrement = 4,
};
pub const ZoomUnit_NoAmount = ZoomUnit.NoAmount;
pub const ZoomUnit_LargeDecrement = ZoomUnit.LargeDecrement;
pub const ZoomUnit_SmallDecrement = ZoomUnit.SmallDecrement;
pub const ZoomUnit_LargeIncrement = ZoomUnit.LargeIncrement;
pub const ZoomUnit_SmallIncrement = ZoomUnit.SmallIncrement;
pub const AnimationStyle = enum(i32) {
None = 0,
LasVegasLights = 1,
BlinkingBackground = 2,
SparkleText = 3,
MarchingBlackAnts = 4,
MarchingRedAnts = 5,
Shimmer = 6,
Other = -1,
};
pub const AnimationStyle_None = AnimationStyle.None;
pub const AnimationStyle_LasVegasLights = AnimationStyle.LasVegasLights;
pub const AnimationStyle_BlinkingBackground = AnimationStyle.BlinkingBackground;
pub const AnimationStyle_SparkleText = AnimationStyle.SparkleText;
pub const AnimationStyle_MarchingBlackAnts = AnimationStyle.MarchingBlackAnts;
pub const AnimationStyle_MarchingRedAnts = AnimationStyle.MarchingRedAnts;
pub const AnimationStyle_Shimmer = AnimationStyle.Shimmer;
pub const AnimationStyle_Other = AnimationStyle.Other;
pub const BulletStyle = enum(i32) {
None = 0,
HollowRoundBullet = 1,
FilledRoundBullet = 2,
HollowSquareBullet = 3,
FilledSquareBullet = 4,
DashBullet = 5,
Other = -1,
};
pub const BulletStyle_None = BulletStyle.None;
pub const BulletStyle_HollowRoundBullet = BulletStyle.HollowRoundBullet;
pub const BulletStyle_FilledRoundBullet = BulletStyle.FilledRoundBullet;
pub const BulletStyle_HollowSquareBullet = BulletStyle.HollowSquareBullet;
pub const BulletStyle_FilledSquareBullet = BulletStyle.FilledSquareBullet;
pub const BulletStyle_DashBullet = BulletStyle.DashBullet;
pub const BulletStyle_Other = BulletStyle.Other;
pub const CapStyle = enum(i32) {
None = 0,
SmallCap = 1,
AllCap = 2,
AllPetiteCaps = 3,
PetiteCaps = 4,
Unicase = 5,
Titling = 6,
Other = -1,
};
pub const CapStyle_None = CapStyle.None;
pub const CapStyle_SmallCap = CapStyle.SmallCap;
pub const CapStyle_AllCap = CapStyle.AllCap;
pub const CapStyle_AllPetiteCaps = CapStyle.AllPetiteCaps;
pub const CapStyle_PetiteCaps = CapStyle.PetiteCaps;
pub const CapStyle_Unicase = CapStyle.Unicase;
pub const CapStyle_Titling = CapStyle.Titling;
pub const CapStyle_Other = CapStyle.Other;
pub const FillType = enum(i32) {
None = 0,
Color = 1,
Gradient = 2,
Picture = 3,
Pattern = 4,
};
pub const FillType_None = FillType.None;
pub const FillType_Color = FillType.Color;
pub const FillType_Gradient = FillType.Gradient;
pub const FillType_Picture = FillType.Picture;
pub const FillType_Pattern = FillType.Pattern;
pub const FlowDirections = enum(i32) {
Default = 0,
RightToLeft = 1,
BottomToTop = 2,
Vertical = 4,
};
pub const FlowDirections_Default = FlowDirections.Default;
pub const FlowDirections_RightToLeft = FlowDirections.RightToLeft;
pub const FlowDirections_BottomToTop = FlowDirections.BottomToTop;
pub const FlowDirections_Vertical = FlowDirections.Vertical;
pub const HorizontalTextAlignment = enum(i32) {
Left = 0,
Centered = 1,
Right = 2,
Justified = 3,
};
pub const HorizontalTextAlignment_Left = HorizontalTextAlignment.Left;
pub const HorizontalTextAlignment_Centered = HorizontalTextAlignment.Centered;
pub const HorizontalTextAlignment_Right = HorizontalTextAlignment.Right;
pub const HorizontalTextAlignment_Justified = HorizontalTextAlignment.Justified;
pub const OutlineStyles = enum(i32) {
None = 0,
Outline = 1,
Shadow = 2,
Engraved = 4,
Embossed = 8,
};
pub const OutlineStyles_None = OutlineStyles.None;
pub const OutlineStyles_Outline = OutlineStyles.Outline;
pub const OutlineStyles_Shadow = OutlineStyles.Shadow;
pub const OutlineStyles_Engraved = OutlineStyles.Engraved;
pub const OutlineStyles_Embossed = OutlineStyles.Embossed;
pub const TextDecorationLineStyle = enum(i32) {
None = 0,
Single = 1,
WordsOnly = 2,
Double = 3,
Dot = 4,
Dash = 5,
DashDot = 6,
DashDotDot = 7,
Wavy = 8,
ThickSingle = 9,
DoubleWavy = 11,
ThickWavy = 12,
LongDash = 13,
ThickDash = 14,
ThickDashDot = 15,
ThickDashDotDot = 16,
ThickDot = 17,
ThickLongDash = 18,
Other = -1,
};
pub const TextDecorationLineStyle_None = TextDecorationLineStyle.None;
pub const TextDecorationLineStyle_Single = TextDecorationLineStyle.Single;
pub const TextDecorationLineStyle_WordsOnly = TextDecorationLineStyle.WordsOnly;
pub const TextDecorationLineStyle_Double = TextDecorationLineStyle.Double;
pub const TextDecorationLineStyle_Dot = TextDecorationLineStyle.Dot;
pub const TextDecorationLineStyle_Dash = TextDecorationLineStyle.Dash;
pub const TextDecorationLineStyle_DashDot = TextDecorationLineStyle.DashDot;
pub const TextDecorationLineStyle_DashDotDot = TextDecorationLineStyle.DashDotDot;
pub const TextDecorationLineStyle_Wavy = TextDecorationLineStyle.Wavy;
pub const TextDecorationLineStyle_ThickSingle = TextDecorationLineStyle.ThickSingle;
pub const TextDecorationLineStyle_DoubleWavy = TextDecorationLineStyle.DoubleWavy;
pub const TextDecorationLineStyle_ThickWavy = TextDecorationLineStyle.ThickWavy;
pub const TextDecorationLineStyle_LongDash = TextDecorationLineStyle.LongDash;
pub const TextDecorationLineStyle_ThickDash = TextDecorationLineStyle.ThickDash;
pub const TextDecorationLineStyle_ThickDashDot = TextDecorationLineStyle.ThickDashDot;
pub const TextDecorationLineStyle_ThickDashDotDot = TextDecorationLineStyle.ThickDashDotDot;
pub const TextDecorationLineStyle_ThickDot = TextDecorationLineStyle.ThickDot;
pub const TextDecorationLineStyle_ThickLongDash = TextDecorationLineStyle.ThickLongDash;
pub const TextDecorationLineStyle_Other = TextDecorationLineStyle.Other;
pub const VisualEffects = enum(i32) {
None = 0,
Shadow = 1,
Reflection = 2,
Glow = 4,
SoftEdges = 8,
Bevel = 16,
};
pub const VisualEffects_None = VisualEffects.None;
pub const VisualEffects_Shadow = VisualEffects.Shadow;
pub const VisualEffects_Reflection = VisualEffects.Reflection;
pub const VisualEffects_Glow = VisualEffects.Glow;
pub const VisualEffects_SoftEdges = VisualEffects.SoftEdges;
pub const VisualEffects_Bevel = VisualEffects.Bevel;
pub const NotificationProcessing = enum(i32) {
ImportantAll = 0,
ImportantMostRecent = 1,
All = 2,
MostRecent = 3,
CurrentThenMostRecent = 4,
};
pub const NotificationProcessing_ImportantAll = NotificationProcessing.ImportantAll;
pub const NotificationProcessing_ImportantMostRecent = NotificationProcessing.ImportantMostRecent;
pub const NotificationProcessing_All = NotificationProcessing.All;
pub const NotificationProcessing_MostRecent = NotificationProcessing.MostRecent;
pub const NotificationProcessing_CurrentThenMostRecent = NotificationProcessing.CurrentThenMostRecent;
pub const NotificationKind = enum(i32) {
ItemAdded = 0,
ItemRemoved = 1,
ActionCompleted = 2,
ActionAborted = 3,
Other = 4,
};
pub const NotificationKind_ItemAdded = NotificationKind.ItemAdded;
pub const NotificationKind_ItemRemoved = NotificationKind.ItemRemoved;
pub const NotificationKind_ActionCompleted = NotificationKind.ActionCompleted;
pub const NotificationKind_ActionAborted = NotificationKind.ActionAborted;
pub const NotificationKind_Other = NotificationKind.Other;
pub const UiaRect = extern struct {
left: f64,
top: f64,
width: f64,
height: f64,
};
pub const UiaPoint = extern struct {
x: f64,
y: f64,
};
pub const UiaChangeInfo = extern struct {
uiaId: i32,
payload: VARIANT,
extraInfo: VARIANT,
};
pub const UIAutomationType = enum(i32) {
Int = 1,
Bool = 2,
String = 3,
Double = 4,
Point = 5,
Rect = 6,
Element = 7,
Array = 65536,
Out = 131072,
IntArray = 65537,
BoolArray = 65538,
StringArray = 65539,
DoubleArray = 65540,
PointArray = 65541,
RectArray = 65542,
ElementArray = 65543,
OutInt = 131073,
OutBool = 131074,
OutString = 131075,
OutDouble = 131076,
OutPoint = 131077,
OutRect = 131078,
OutElement = 131079,
OutIntArray = 196609,
OutBoolArray = 196610,
OutStringArray = 196611,
OutDoubleArray = 196612,
OutPointArray = 196613,
OutRectArray = 196614,
OutElementArray = 196615,
};
pub const UIAutomationType_Int = UIAutomationType.Int;
pub const UIAutomationType_Bool = UIAutomationType.Bool;
pub const UIAutomationType_String = UIAutomationType.String;
pub const UIAutomationType_Double = UIAutomationType.Double;
pub const UIAutomationType_Point = UIAutomationType.Point;
pub const UIAutomationType_Rect = UIAutomationType.Rect;
pub const UIAutomationType_Element = UIAutomationType.Element;
pub const UIAutomationType_Array = UIAutomationType.Array;
pub const UIAutomationType_Out = UIAutomationType.Out;
pub const UIAutomationType_IntArray = UIAutomationType.IntArray;
pub const UIAutomationType_BoolArray = UIAutomationType.BoolArray;
pub const UIAutomationType_StringArray = UIAutomationType.StringArray;
pub const UIAutomationType_DoubleArray = UIAutomationType.DoubleArray;
pub const UIAutomationType_PointArray = UIAutomationType.PointArray;
pub const UIAutomationType_RectArray = UIAutomationType.RectArray;
pub const UIAutomationType_ElementArray = UIAutomationType.ElementArray;
pub const UIAutomationType_OutInt = UIAutomationType.OutInt;
pub const UIAutomationType_OutBool = UIAutomationType.OutBool;
pub const UIAutomationType_OutString = UIAutomationType.OutString;
pub const UIAutomationType_OutDouble = UIAutomationType.OutDouble;
pub const UIAutomationType_OutPoint = UIAutomationType.OutPoint;
pub const UIAutomationType_OutRect = UIAutomationType.OutRect;
pub const UIAutomationType_OutElement = UIAutomationType.OutElement;
pub const UIAutomationType_OutIntArray = UIAutomationType.OutIntArray;
pub const UIAutomationType_OutBoolArray = UIAutomationType.OutBoolArray;
pub const UIAutomationType_OutStringArray = UIAutomationType.OutStringArray;
pub const UIAutomationType_OutDoubleArray = UIAutomationType.OutDoubleArray;
pub const UIAutomationType_OutPointArray = UIAutomationType.OutPointArray;
pub const UIAutomationType_OutRectArray = UIAutomationType.OutRectArray;
pub const UIAutomationType_OutElementArray = UIAutomationType.OutElementArray;
pub const UIAutomationParameter = extern struct {
type: UIAutomationType,
pData: ?*c_void,
};
pub const UIAutomationPropertyInfo = extern struct {
guid: Guid,
pProgrammaticName: ?[*:0]const u16,
type: UIAutomationType,
};
pub const UIAutomationEventInfo = extern struct {
guid: Guid,
pProgrammaticName: ?[*:0]const u16,
};
pub const UIAutomationMethodInfo = extern struct {
pProgrammaticName: ?[*:0]const u16,
doSetFocus: BOOL,
cInParameters: u32,
cOutParameters: u32,
pParameterTypes: ?*UIAutomationType,
pParameterNames: ?*?PWSTR,
};
pub const UIAutomationPatternInfo = extern struct {
guid: Guid,
pProgrammaticName: ?[*:0]const u16,
providerInterfaceId: Guid,
clientInterfaceId: Guid,
cProperties: u32,
pProperties: ?*UIAutomationPropertyInfo,
cMethods: u32,
pMethods: ?*UIAutomationMethodInfo,
cEvents: u32,
pEvents: ?*UIAutomationEventInfo,
pPatternHandler: ?*IUIAutomationPatternHandler,
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRawElementProviderSimple_Value = @import("../zig.zig").Guid.initString("d6dd68d1-86fd-4332-8666-9abedea2d24c");
pub const IID_IRawElementProviderSimple = &IID_IRawElementProviderSimple_Value;
pub const IRawElementProviderSimple = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProviderOptions: fn(
self: *const IRawElementProviderSimple,
pRetVal: ?*ProviderOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPatternProvider: fn(
self: *const IRawElementProviderSimple,
patternId: i32,
pRetVal: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyValue: fn(
self: *const IRawElementProviderSimple,
propertyId: i32,
pRetVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_HostRawElementProvider: fn(
self: *const IRawElementProviderSimple,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 IRawElementProviderSimple_get_ProviderOptions(self: *const T, pRetVal: ?*ProviderOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple.VTable, self.vtable).get_ProviderOptions(@ptrCast(*const IRawElementProviderSimple, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderSimple_GetPatternProvider(self: *const T, patternId: i32, pRetVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple.VTable, self.vtable).GetPatternProvider(@ptrCast(*const IRawElementProviderSimple, self), patternId, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderSimple_GetPropertyValue(self: *const T, propertyId: i32, pRetVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple.VTable, self.vtable).GetPropertyValue(@ptrCast(*const IRawElementProviderSimple, self), propertyId, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderSimple_get_HostRawElementProvider(self: *const T, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple.VTable, self.vtable).get_HostRawElementProvider(@ptrCast(*const IRawElementProviderSimple, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IAccessibleEx_Value = @import("../zig.zig").Guid.initString("f8b80ada-2c44-48d0-89be-5ff23c9cd875");
pub const IID_IAccessibleEx = &IID_IAccessibleEx_Value;
pub const IAccessibleEx = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetObjectForChild: fn(
self: *const IAccessibleEx,
idChild: i32,
pRetVal: ?*?*IAccessibleEx,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIAccessiblePair: fn(
self: *const IAccessibleEx,
ppAcc: ?*?*IAccessible,
pidChild: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRuntimeId: fn(
self: *const IAccessibleEx,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConvertReturnedElement: fn(
self: *const IAccessibleEx,
pIn: ?*IRawElementProviderSimple,
ppRetValOut: ?*?*IAccessibleEx,
) 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 IAccessibleEx_GetObjectForChild(self: *const T, idChild: i32, pRetVal: ?*?*IAccessibleEx) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleEx.VTable, self.vtable).GetObjectForChild(@ptrCast(*const IAccessibleEx, self), idChild, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleEx_GetIAccessiblePair(self: *const T, ppAcc: ?*?*IAccessible, pidChild: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleEx.VTable, self.vtable).GetIAccessiblePair(@ptrCast(*const IAccessibleEx, self), ppAcc, pidChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleEx_GetRuntimeId(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleEx.VTable, self.vtable).GetRuntimeId(@ptrCast(*const IAccessibleEx, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleEx_ConvertReturnedElement(self: *const T, pIn: ?*IRawElementProviderSimple, ppRetValOut: ?*?*IAccessibleEx) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleEx.VTable, self.vtable).ConvertReturnedElement(@ptrCast(*const IAccessibleEx, self), pIn, ppRetValOut);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IRawElementProviderSimple2_Value = @import("../zig.zig").Guid.initString("a0a839a9-8da1-4a82-806a-8e0d44e79f56");
pub const IID_IRawElementProviderSimple2 = &IID_IRawElementProviderSimple2_Value;
pub const IRawElementProviderSimple2 = extern struct {
pub const VTable = extern struct {
base: IRawElementProviderSimple.VTable,
ShowContextMenu: fn(
self: *const IRawElementProviderSimple2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRawElementProviderSimple.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderSimple2_ShowContextMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple2.VTable, self.vtable).ShowContextMenu(@ptrCast(*const IRawElementProviderSimple2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IRawElementProviderSimple3_Value = @import("../zig.zig").Guid.initString("fcf5d820-d7ec-4613-bdf6-42a84ce7daaf");
pub const IID_IRawElementProviderSimple3 = &IID_IRawElementProviderSimple3_Value;
pub const IRawElementProviderSimple3 = extern struct {
pub const VTable = extern struct {
base: IRawElementProviderSimple2.VTable,
GetMetadataValue: fn(
self: *const IRawElementProviderSimple3,
targetId: i32,
metadataId: i32,
returnVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IRawElementProviderSimple2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderSimple3_GetMetadataValue(self: *const T, targetId: i32, metadataId: i32, returnVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderSimple3.VTable, self.vtable).GetMetadataValue(@ptrCast(*const IRawElementProviderSimple3, self), targetId, metadataId, returnVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRawElementProviderFragmentRoot_Value = @import("../zig.zig").Guid.initString("620ce2a5-ab8f-40a9-86cb-de3c75599b58");
pub const IID_IRawElementProviderFragmentRoot = &IID_IRawElementProviderFragmentRoot_Value;
pub const IRawElementProviderFragmentRoot = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ElementProviderFromPoint: fn(
self: *const IRawElementProviderFragmentRoot,
x: f64,
y: f64,
pRetVal: ?*?*IRawElementProviderFragment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFocus: fn(
self: *const IRawElementProviderFragmentRoot,
pRetVal: ?*?*IRawElementProviderFragment,
) 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 IRawElementProviderFragmentRoot_ElementProviderFromPoint(self: *const T, x: f64, y: f64, pRetVal: ?*?*IRawElementProviderFragment) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragmentRoot.VTable, self.vtable).ElementProviderFromPoint(@ptrCast(*const IRawElementProviderFragmentRoot, self), x, y, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragmentRoot_GetFocus(self: *const T, pRetVal: ?*?*IRawElementProviderFragment) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragmentRoot.VTable, self.vtable).GetFocus(@ptrCast(*const IRawElementProviderFragmentRoot, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRawElementProviderFragment_Value = @import("../zig.zig").Guid.initString("f7063da8-8359-439c-9297-bbc5299a7d87");
pub const IID_IRawElementProviderFragment = &IID_IRawElementProviderFragment_Value;
pub const IRawElementProviderFragment = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Navigate: fn(
self: *const IRawElementProviderFragment,
direction: NavigateDirection,
pRetVal: ?*?*IRawElementProviderFragment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRuntimeId: fn(
self: *const IRawElementProviderFragment,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BoundingRectangle: fn(
self: *const IRawElementProviderFragment,
pRetVal: ?*UiaRect,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEmbeddedFragmentRoots: fn(
self: *const IRawElementProviderFragment,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFocus: fn(
self: *const IRawElementProviderFragment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FragmentRoot: fn(
self: *const IRawElementProviderFragment,
pRetVal: ?*?*IRawElementProviderFragmentRoot,
) 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 IRawElementProviderFragment_Navigate(self: *const T, direction: NavigateDirection, pRetVal: ?*?*IRawElementProviderFragment) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).Navigate(@ptrCast(*const IRawElementProviderFragment, self), direction, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragment_GetRuntimeId(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).GetRuntimeId(@ptrCast(*const IRawElementProviderFragment, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragment_get_BoundingRectangle(self: *const T, pRetVal: ?*UiaRect) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).get_BoundingRectangle(@ptrCast(*const IRawElementProviderFragment, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragment_GetEmbeddedFragmentRoots(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).GetEmbeddedFragmentRoots(@ptrCast(*const IRawElementProviderFragment, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragment_SetFocus(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).SetFocus(@ptrCast(*const IRawElementProviderFragment, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderFragment_get_FragmentRoot(self: *const T, pRetVal: ?*?*IRawElementProviderFragmentRoot) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderFragment.VTable, self.vtable).get_FragmentRoot(@ptrCast(*const IRawElementProviderFragment, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRawElementProviderAdviseEvents_Value = @import("../zig.zig").Guid.initString("a407b27b-0f6d-4427-9292-473c7bf93258");
pub const IID_IRawElementProviderAdviseEvents = &IID_IRawElementProviderAdviseEvents_Value;
pub const IRawElementProviderAdviseEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AdviseEventAdded: fn(
self: *const IRawElementProviderAdviseEvents,
eventId: i32,
propertyIDs: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AdviseEventRemoved: fn(
self: *const IRawElementProviderAdviseEvents,
eventId: i32,
propertyIDs: ?*SAFEARRAY,
) 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 IRawElementProviderAdviseEvents_AdviseEventAdded(self: *const T, eventId: i32, propertyIDs: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderAdviseEvents.VTable, self.vtable).AdviseEventAdded(@ptrCast(*const IRawElementProviderAdviseEvents, self), eventId, propertyIDs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderAdviseEvents_AdviseEventRemoved(self: *const T, eventId: i32, propertyIDs: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderAdviseEvents.VTable, self.vtable).AdviseEventRemoved(@ptrCast(*const IRawElementProviderAdviseEvents, self), eventId, propertyIDs);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRawElementProviderHwndOverride_Value = @import("../zig.zig").Guid.initString("1d5df27c-8947-4425-b8d9-79787bb460b8");
pub const IID_IRawElementProviderHwndOverride = &IID_IRawElementProviderHwndOverride_Value;
pub const IRawElementProviderHwndOverride = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetOverrideProviderForHwnd: fn(
self: *const IRawElementProviderHwndOverride,
hwnd: ?HWND,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 IRawElementProviderHwndOverride_GetOverrideProviderForHwnd(self: *const T, hwnd: ?HWND, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderHwndOverride.VTable, self.vtable).GetOverrideProviderForHwnd(@ptrCast(*const IRawElementProviderHwndOverride, self), hwnd, pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IProxyProviderWinEventSink_Value = @import("../zig.zig").Guid.initString("4fd82b78-a43e-46ac-9803-0a6969c7c183");
pub const IID_IProxyProviderWinEventSink = &IID_IProxyProviderWinEventSink_Value;
pub const IProxyProviderWinEventSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddAutomationPropertyChangedEvent: fn(
self: *const IProxyProviderWinEventSink,
pProvider: ?*IRawElementProviderSimple,
id: i32,
newValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddAutomationEvent: fn(
self: *const IProxyProviderWinEventSink,
pProvider: ?*IRawElementProviderSimple,
id: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddStructureChangedEvent: fn(
self: *const IProxyProviderWinEventSink,
pProvider: ?*IRawElementProviderSimple,
structureChangeType: StructureChangeType,
runtimeId: ?*SAFEARRAY,
) 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 IProxyProviderWinEventSink_AddAutomationPropertyChangedEvent(self: *const T, pProvider: ?*IRawElementProviderSimple, id: i32, newValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IProxyProviderWinEventSink.VTable, self.vtable).AddAutomationPropertyChangedEvent(@ptrCast(*const IProxyProviderWinEventSink, self), pProvider, id, newValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IProxyProviderWinEventSink_AddAutomationEvent(self: *const T, pProvider: ?*IRawElementProviderSimple, id: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IProxyProviderWinEventSink.VTable, self.vtable).AddAutomationEvent(@ptrCast(*const IProxyProviderWinEventSink, self), pProvider, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IProxyProviderWinEventSink_AddStructureChangedEvent(self: *const T, pProvider: ?*IRawElementProviderSimple, structureChangeType: StructureChangeType, runtimeId: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IProxyProviderWinEventSink.VTable, self.vtable).AddStructureChangedEvent(@ptrCast(*const IProxyProviderWinEventSink, self), pProvider, structureChangeType, runtimeId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IProxyProviderWinEventHandler_Value = @import("../zig.zig").Guid.initString("89592ad4-f4e0-43d5-a3b6-bad7e111b435");
pub const IID_IProxyProviderWinEventHandler = &IID_IProxyProviderWinEventHandler_Value;
pub const IProxyProviderWinEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RespondToWinEvent: fn(
self: *const IProxyProviderWinEventHandler,
idWinEvent: u32,
hwnd: ?HWND,
idObject: i32,
idChild: i32,
pSink: ?*IProxyProviderWinEventSink,
) 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 IProxyProviderWinEventHandler_RespondToWinEvent(self: *const T, idWinEvent: u32, hwnd: ?HWND, idObject: i32, idChild: i32, pSink: ?*IProxyProviderWinEventSink) callconv(.Inline) HRESULT {
return @ptrCast(*const IProxyProviderWinEventHandler.VTable, self.vtable).RespondToWinEvent(@ptrCast(*const IProxyProviderWinEventHandler, self), idWinEvent, hwnd, idObject, idChild, pSink);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IRawElementProviderWindowlessSite_Value = @import("../zig.zig").Guid.initString("0a2a93cc-bfad-42ac-9b2e-0991fb0d3ea0");
pub const IID_IRawElementProviderWindowlessSite = &IID_IRawElementProviderWindowlessSite_Value;
pub const IRawElementProviderWindowlessSite = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAdjacentFragment: fn(
self: *const IRawElementProviderWindowlessSite,
direction: NavigateDirection,
ppParent: ?*?*IRawElementProviderFragment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRuntimeIdPrefix: fn(
self: *const IRawElementProviderWindowlessSite,
pRetVal: ?*?*SAFEARRAY,
) 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 IRawElementProviderWindowlessSite_GetAdjacentFragment(self: *const T, direction: NavigateDirection, ppParent: ?*?*IRawElementProviderFragment) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderWindowlessSite.VTable, self.vtable).GetAdjacentFragment(@ptrCast(*const IRawElementProviderWindowlessSite, self), direction, ppParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRawElementProviderWindowlessSite_GetRuntimeIdPrefix(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderWindowlessSite.VTable, self.vtable).GetRuntimeIdPrefix(@ptrCast(*const IRawElementProviderWindowlessSite, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IAccessibleHostingElementProviders_Value = @import("../zig.zig").Guid.initString("33ac331b-943e-4020-b295-db37784974a3");
pub const IID_IAccessibleHostingElementProviders = &IID_IAccessibleHostingElementProviders_Value;
pub const IAccessibleHostingElementProviders = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetEmbeddedFragmentRoots: fn(
self: *const IAccessibleHostingElementProviders,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetObjectIdForProvider: fn(
self: *const IAccessibleHostingElementProviders,
pProvider: ?*IRawElementProviderSimple,
pidObject: ?*i32,
) 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 IAccessibleHostingElementProviders_GetEmbeddedFragmentRoots(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleHostingElementProviders.VTable, self.vtable).GetEmbeddedFragmentRoots(@ptrCast(*const IAccessibleHostingElementProviders, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAccessibleHostingElementProviders_GetObjectIdForProvider(self: *const T, pProvider: ?*IRawElementProviderSimple, pidObject: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAccessibleHostingElementProviders.VTable, self.vtable).GetObjectIdForProvider(@ptrCast(*const IAccessibleHostingElementProviders, self), pProvider, pidObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IRawElementProviderHostingAccessibles_Value = @import("../zig.zig").Guid.initString("24be0b07-d37d-487a-98cf-a13ed465e9b3");
pub const IID_IRawElementProviderHostingAccessibles = &IID_IRawElementProviderHostingAccessibles_Value;
pub const IRawElementProviderHostingAccessibles = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetEmbeddedAccessibles: fn(
self: *const IRawElementProviderHostingAccessibles,
pRetVal: ?*?*SAFEARRAY,
) 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 IRawElementProviderHostingAccessibles_GetEmbeddedAccessibles(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IRawElementProviderHostingAccessibles.VTable, self.vtable).GetEmbeddedAccessibles(@ptrCast(*const IRawElementProviderHostingAccessibles, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IDockProvider_Value = @import("../zig.zig").Guid.initString("159bc72c-4ad3-485e-9637-d7052edf0146");
pub const IID_IDockProvider = &IID_IDockProvider_Value;
pub const IDockProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetDockPosition: fn(
self: *const IDockProvider,
dockPosition: DockPosition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DockPosition: fn(
self: *const IDockProvider,
pRetVal: ?*DockPosition,
) 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 IDockProvider_SetDockPosition(self: *const T, dockPosition: DockPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IDockProvider.VTable, self.vtable).SetDockPosition(@ptrCast(*const IDockProvider, self), dockPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDockProvider_get_DockPosition(self: *const T, pRetVal: ?*DockPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IDockProvider.VTable, self.vtable).get_DockPosition(@ptrCast(*const IDockProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IExpandCollapseProvider_Value = @import("../zig.zig").Guid.initString("d847d3a5-cab0-4a98-8c32-ecb45c59ad24");
pub const IID_IExpandCollapseProvider = &IID_IExpandCollapseProvider_Value;
pub const IExpandCollapseProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Expand: fn(
self: *const IExpandCollapseProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Collapse: fn(
self: *const IExpandCollapseProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ExpandCollapseState: fn(
self: *const IExpandCollapseProvider,
pRetVal: ?*ExpandCollapseState,
) 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 IExpandCollapseProvider_Expand(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IExpandCollapseProvider.VTable, self.vtable).Expand(@ptrCast(*const IExpandCollapseProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IExpandCollapseProvider_Collapse(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IExpandCollapseProvider.VTable, self.vtable).Collapse(@ptrCast(*const IExpandCollapseProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IExpandCollapseProvider_get_ExpandCollapseState(self: *const T, pRetVal: ?*ExpandCollapseState) callconv(.Inline) HRESULT {
return @ptrCast(*const IExpandCollapseProvider.VTable, self.vtable).get_ExpandCollapseState(@ptrCast(*const IExpandCollapseProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IGridProvider_Value = @import("../zig.zig").Guid.initString("b17d6187-0907-464b-a168-0ef17a1572b1");
pub const IID_IGridProvider = &IID_IGridProvider_Value;
pub const IGridProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItem: fn(
self: *const IGridProvider,
row: i32,
column: i32,
pRetVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RowCount: fn(
self: *const IGridProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ColumnCount: fn(
self: *const IGridProvider,
pRetVal: ?*i32,
) 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 IGridProvider_GetItem(self: *const T, row: i32, column: i32, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridProvider.VTable, self.vtable).GetItem(@ptrCast(*const IGridProvider, self), row, column, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridProvider_get_RowCount(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridProvider.VTable, self.vtable).get_RowCount(@ptrCast(*const IGridProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridProvider_get_ColumnCount(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridProvider.VTable, self.vtable).get_ColumnCount(@ptrCast(*const IGridProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IGridItemProvider_Value = @import("../zig.zig").Guid.initString("d02541f1-fb81-4d64-ae32-f520f8a6dbd1");
pub const IID_IGridItemProvider = &IID_IGridItemProvider_Value;
pub const IGridItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Row: fn(
self: *const IGridItemProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Column: fn(
self: *const IGridItemProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RowSpan: fn(
self: *const IGridItemProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ColumnSpan: fn(
self: *const IGridItemProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ContainingGrid: fn(
self: *const IGridItemProvider,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 IGridItemProvider_get_Row(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridItemProvider.VTable, self.vtable).get_Row(@ptrCast(*const IGridItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridItemProvider_get_Column(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridItemProvider.VTable, self.vtable).get_Column(@ptrCast(*const IGridItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridItemProvider_get_RowSpan(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridItemProvider.VTable, self.vtable).get_RowSpan(@ptrCast(*const IGridItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridItemProvider_get_ColumnSpan(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridItemProvider.VTable, self.vtable).get_ColumnSpan(@ptrCast(*const IGridItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGridItemProvider_get_ContainingGrid(self: *const T, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IGridItemProvider.VTable, self.vtable).get_ContainingGrid(@ptrCast(*const IGridItemProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IInvokeProvider_Value = @import("../zig.zig").Guid.initString("54fcb24b-e18e-47a2-b4d3-eccbe77599a2");
pub const IID_IInvokeProvider = &IID_IInvokeProvider_Value;
pub const IInvokeProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Invoke: fn(
self: *const IInvokeProvider,
) 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 IInvokeProvider_Invoke(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IInvokeProvider.VTable, self.vtable).Invoke(@ptrCast(*const IInvokeProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IMultipleViewProvider_Value = @import("../zig.zig").Guid.initString("6278cab1-b556-4a1a-b4e0-418acc523201");
pub const IID_IMultipleViewProvider = &IID_IMultipleViewProvider_Value;
pub const IMultipleViewProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetViewName: fn(
self: *const IMultipleViewProvider,
viewId: i32,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCurrentView: fn(
self: *const IMultipleViewProvider,
viewId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentView: fn(
self: *const IMultipleViewProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSupportedViews: fn(
self: *const IMultipleViewProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 IMultipleViewProvider_GetViewName(self: *const T, viewId: i32, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMultipleViewProvider.VTable, self.vtable).GetViewName(@ptrCast(*const IMultipleViewProvider, self), viewId, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMultipleViewProvider_SetCurrentView(self: *const T, viewId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMultipleViewProvider.VTable, self.vtable).SetCurrentView(@ptrCast(*const IMultipleViewProvider, self), viewId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMultipleViewProvider_get_CurrentView(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMultipleViewProvider.VTable, self.vtable).get_CurrentView(@ptrCast(*const IMultipleViewProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMultipleViewProvider_GetSupportedViews(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IMultipleViewProvider.VTable, self.vtable).GetSupportedViews(@ptrCast(*const IMultipleViewProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IRangeValueProvider_Value = @import("../zig.zig").Guid.initString("36dc7aef-33e6-4691-afe1-2be7274b3d33");
pub const IID_IRangeValueProvider = &IID_IRangeValueProvider_Value;
pub const IRangeValueProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetValue: fn(
self: *const IRangeValueProvider,
val: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IRangeValueProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsReadOnly: fn(
self: *const IRangeValueProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Maximum: fn(
self: *const IRangeValueProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Minimum: fn(
self: *const IRangeValueProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LargeChange: fn(
self: *const IRangeValueProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SmallChange: fn(
self: *const IRangeValueProvider,
pRetVal: ?*f64,
) 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 IRangeValueProvider_SetValue(self: *const T, val: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).SetValue(@ptrCast(*const IRangeValueProvider, self), val);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_Value(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_Value(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_IsReadOnly(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_IsReadOnly(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_Maximum(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_Maximum(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_Minimum(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_Minimum(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_LargeChange(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_LargeChange(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRangeValueProvider_get_SmallChange(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IRangeValueProvider.VTable, self.vtable).get_SmallChange(@ptrCast(*const IRangeValueProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IScrollItemProvider_Value = @import("../zig.zig").Guid.initString("2360c714-4bf1-4b26-ba65-9b21316127eb");
pub const IID_IScrollItemProvider = &IID_IScrollItemProvider_Value;
pub const IScrollItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ScrollIntoView: fn(
self: *const IScrollItemProvider,
) 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 IScrollItemProvider_ScrollIntoView(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollItemProvider.VTable, self.vtable).ScrollIntoView(@ptrCast(*const IScrollItemProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ISelectionProvider_Value = @import("../zig.zig").Guid.initString("fb8b03af-3bdf-48d4-bd36-1a65793be168");
pub const IID_ISelectionProvider = &IID_ISelectionProvider_Value;
pub const ISelectionProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSelection: fn(
self: *const ISelectionProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanSelectMultiple: fn(
self: *const ISelectionProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsSelectionRequired: fn(
self: *const ISelectionProvider,
pRetVal: ?*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 ISelectionProvider_GetSelection(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider.VTable, self.vtable).GetSelection(@ptrCast(*const ISelectionProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider_get_CanSelectMultiple(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider.VTable, self.vtable).get_CanSelectMultiple(@ptrCast(*const ISelectionProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider_get_IsSelectionRequired(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider.VTable, self.vtable).get_IsSelectionRequired(@ptrCast(*const ISelectionProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.16299'
const IID_ISelectionProvider2_Value = @import("../zig.zig").Guid.initString("14f68475-ee1c-44f6-a869-d239381f0fe7");
pub const IID_ISelectionProvider2 = &IID_ISelectionProvider2_Value;
pub const ISelectionProvider2 = extern struct {
pub const VTable = extern struct {
base: ISelectionProvider.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FirstSelectedItem: fn(
self: *const ISelectionProvider2,
retVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastSelectedItem: fn(
self: *const ISelectionProvider2,
retVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentSelectedItem: fn(
self: *const ISelectionProvider2,
retVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ItemCount: fn(
self: *const ISelectionProvider2,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISelectionProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider2_get_FirstSelectedItem(self: *const T, retVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider2.VTable, self.vtable).get_FirstSelectedItem(@ptrCast(*const ISelectionProvider2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider2_get_LastSelectedItem(self: *const T, retVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider2.VTable, self.vtable).get_LastSelectedItem(@ptrCast(*const ISelectionProvider2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider2_get_CurrentSelectedItem(self: *const T, retVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider2.VTable, self.vtable).get_CurrentSelectedItem(@ptrCast(*const ISelectionProvider2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionProvider2_get_ItemCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionProvider2.VTable, self.vtable).get_ItemCount(@ptrCast(*const ISelectionProvider2, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IScrollProvider_Value = @import("../zig.zig").Guid.initString("b38b8077-1fc3-42a5-8cae-d40c2215055a");
pub const IID_IScrollProvider = &IID_IScrollProvider_Value;
pub const IScrollProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Scroll: fn(
self: *const IScrollProvider,
horizontalAmount: ScrollAmount,
verticalAmount: ScrollAmount,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetScrollPercent: fn(
self: *const IScrollProvider,
horizontalPercent: f64,
verticalPercent: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_HorizontalScrollPercent: fn(
self: *const IScrollProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_VerticalScrollPercent: fn(
self: *const IScrollProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_HorizontalViewSize: fn(
self: *const IScrollProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_VerticalViewSize: fn(
self: *const IScrollProvider,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_HorizontallyScrollable: fn(
self: *const IScrollProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_VerticallyScrollable: fn(
self: *const IScrollProvider,
pRetVal: ?*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 IScrollProvider_Scroll(self: *const T, horizontalAmount: ScrollAmount, verticalAmount: ScrollAmount) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).Scroll(@ptrCast(*const IScrollProvider, self), horizontalAmount, verticalAmount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_SetScrollPercent(self: *const T, horizontalPercent: f64, verticalPercent: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).SetScrollPercent(@ptrCast(*const IScrollProvider, self), horizontalPercent, verticalPercent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_HorizontalScrollPercent(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_HorizontalScrollPercent(@ptrCast(*const IScrollProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_VerticalScrollPercent(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_VerticalScrollPercent(@ptrCast(*const IScrollProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_HorizontalViewSize(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_HorizontalViewSize(@ptrCast(*const IScrollProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_VerticalViewSize(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_VerticalViewSize(@ptrCast(*const IScrollProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_HorizontallyScrollable(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_HorizontallyScrollable(@ptrCast(*const IScrollProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScrollProvider_get_VerticallyScrollable(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IScrollProvider.VTable, self.vtable).get_VerticallyScrollable(@ptrCast(*const IScrollProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ISelectionItemProvider_Value = @import("../zig.zig").Guid.initString("2acad808-b2d4-452d-a407-91ff1ad167b2");
pub const IID_ISelectionItemProvider = &IID_ISelectionItemProvider_Value;
pub const ISelectionItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Select: fn(
self: *const ISelectionItemProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddToSelection: fn(
self: *const ISelectionItemProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFromSelection: fn(
self: *const ISelectionItemProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsSelected: fn(
self: *const ISelectionItemProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SelectionContainer: fn(
self: *const ISelectionItemProvider,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 ISelectionItemProvider_Select(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionItemProvider.VTable, self.vtable).Select(@ptrCast(*const ISelectionItemProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionItemProvider_AddToSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionItemProvider.VTable, self.vtable).AddToSelection(@ptrCast(*const ISelectionItemProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionItemProvider_RemoveFromSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionItemProvider.VTable, self.vtable).RemoveFromSelection(@ptrCast(*const ISelectionItemProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionItemProvider_get_IsSelected(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionItemProvider.VTable, self.vtable).get_IsSelected(@ptrCast(*const ISelectionItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISelectionItemProvider_get_SelectionContainer(self: *const T, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ISelectionItemProvider.VTable, self.vtable).get_SelectionContainer(@ptrCast(*const ISelectionItemProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISynchronizedInputProvider_Value = @import("../zig.zig").Guid.initString("29db1a06-02ce-4cf7-9b42-565d4fab20ee");
pub const IID_ISynchronizedInputProvider = &IID_ISynchronizedInputProvider_Value;
pub const ISynchronizedInputProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
StartListening: fn(
self: *const ISynchronizedInputProvider,
inputType: SynchronizedInputType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cancel: fn(
self: *const ISynchronizedInputProvider,
) 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 ISynchronizedInputProvider_StartListening(self: *const T, inputType: SynchronizedInputType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISynchronizedInputProvider.VTable, self.vtable).StartListening(@ptrCast(*const ISynchronizedInputProvider, self), inputType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISynchronizedInputProvider_Cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISynchronizedInputProvider.VTable, self.vtable).Cancel(@ptrCast(*const ISynchronizedInputProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ITableProvider_Value = @import("../zig.zig").Guid.initString("9c860395-97b3-490a-b52a-858cc22af166");
pub const IID_ITableProvider = &IID_ITableProvider_Value;
pub const ITableProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetRowHeaders: fn(
self: *const ITableProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetColumnHeaders: fn(
self: *const ITableProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RowOrColumnMajor: fn(
self: *const ITableProvider,
pRetVal: ?*RowOrColumnMajor,
) 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 ITableProvider_GetRowHeaders(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITableProvider.VTable, self.vtable).GetRowHeaders(@ptrCast(*const ITableProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITableProvider_GetColumnHeaders(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITableProvider.VTable, self.vtable).GetColumnHeaders(@ptrCast(*const ITableProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITableProvider_get_RowOrColumnMajor(self: *const T, pRetVal: ?*RowOrColumnMajor) callconv(.Inline) HRESULT {
return @ptrCast(*const ITableProvider.VTable, self.vtable).get_RowOrColumnMajor(@ptrCast(*const ITableProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ITableItemProvider_Value = @import("../zig.zig").Guid.initString("b9734fa6-771f-4d78-9c90-2517999349cd");
pub const IID_ITableItemProvider = &IID_ITableItemProvider_Value;
pub const ITableItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetRowHeaderItems: fn(
self: *const ITableItemProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetColumnHeaderItems: fn(
self: *const ITableItemProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 ITableItemProvider_GetRowHeaderItems(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITableItemProvider.VTable, self.vtable).GetRowHeaderItems(@ptrCast(*const ITableItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITableItemProvider_GetColumnHeaderItems(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITableItemProvider.VTable, self.vtable).GetColumnHeaderItems(@ptrCast(*const ITableItemProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IToggleProvider_Value = @import("../zig.zig").Guid.initString("56d00bd0-c4f4-433c-a836-1a52a57e0892");
pub const IID_IToggleProvider = &IID_IToggleProvider_Value;
pub const IToggleProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Toggle: fn(
self: *const IToggleProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ToggleState: fn(
self: *const IToggleProvider,
pRetVal: ?*ToggleState,
) 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 IToggleProvider_Toggle(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IToggleProvider.VTable, self.vtable).Toggle(@ptrCast(*const IToggleProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IToggleProvider_get_ToggleState(self: *const T, pRetVal: ?*ToggleState) callconv(.Inline) HRESULT {
return @ptrCast(*const IToggleProvider.VTable, self.vtable).get_ToggleState(@ptrCast(*const IToggleProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ITransformProvider_Value = @import("../zig.zig").Guid.initString("6829ddc4-4f91-4ffa-b86f-bd3e2987cb4c");
pub const IID_ITransformProvider = &IID_ITransformProvider_Value;
pub const ITransformProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Move: fn(
self: *const ITransformProvider,
x: f64,
y: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resize: fn(
self: *const ITransformProvider,
width: f64,
height: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rotate: fn(
self: *const ITransformProvider,
degrees: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanMove: fn(
self: *const ITransformProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanResize: fn(
self: *const ITransformProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanRotate: fn(
self: *const ITransformProvider,
pRetVal: ?*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 ITransformProvider_Move(self: *const T, x: f64, y: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).Move(@ptrCast(*const ITransformProvider, self), x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider_Resize(self: *const T, width: f64, height: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).Resize(@ptrCast(*const ITransformProvider, self), width, height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider_Rotate(self: *const T, degrees: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).Rotate(@ptrCast(*const ITransformProvider, self), degrees);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider_get_CanMove(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).get_CanMove(@ptrCast(*const ITransformProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider_get_CanResize(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).get_CanResize(@ptrCast(*const ITransformProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider_get_CanRotate(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider.VTable, self.vtable).get_CanRotate(@ptrCast(*const ITransformProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IValueProvider_Value = @import("../zig.zig").Guid.initString("c7935180-6fb3-4201-b174-7df73adbf64a");
pub const IID_IValueProvider = &IID_IValueProvider_Value;
pub const IValueProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetValue: fn(
self: *const IValueProvider,
val: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IValueProvider,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsReadOnly: fn(
self: *const IValueProvider,
pRetVal: ?*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 IValueProvider_SetValue(self: *const T, val: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueProvider.VTable, self.vtable).SetValue(@ptrCast(*const IValueProvider, self), val);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueProvider_get_Value(self: *const T, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueProvider.VTable, self.vtable).get_Value(@ptrCast(*const IValueProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueProvider_get_IsReadOnly(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueProvider.VTable, self.vtable).get_IsReadOnly(@ptrCast(*const IValueProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IWindowProvider_Value = @import("../zig.zig").Guid.initString("987df77b-db06-4d77-8f8a-86a9c3bb90b9");
pub const IID_IWindowProvider = &IID_IWindowProvider_Value;
pub const IWindowProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetVisualState: fn(
self: *const IWindowProvider,
state: WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Close: fn(
self: *const IWindowProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WaitForInputIdle: fn(
self: *const IWindowProvider,
milliseconds: i32,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanMaximize: fn(
self: *const IWindowProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanMinimize: fn(
self: *const IWindowProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsModal: fn(
self: *const IWindowProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_WindowVisualState: fn(
self: *const IWindowProvider,
pRetVal: ?*WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_WindowInteractionState: fn(
self: *const IWindowProvider,
pRetVal: ?*WindowInteractionState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsTopmost: fn(
self: *const IWindowProvider,
pRetVal: ?*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 IWindowProvider_SetVisualState(self: *const T, state: WindowVisualState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).SetVisualState(@ptrCast(*const IWindowProvider, self), state);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_Close(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).Close(@ptrCast(*const IWindowProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_WaitForInputIdle(self: *const T, milliseconds: i32, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).WaitForInputIdle(@ptrCast(*const IWindowProvider, self), milliseconds, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_CanMaximize(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_CanMaximize(@ptrCast(*const IWindowProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_CanMinimize(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_CanMinimize(@ptrCast(*const IWindowProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_IsModal(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_IsModal(@ptrCast(*const IWindowProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_WindowVisualState(self: *const T, pRetVal: ?*WindowVisualState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_WindowVisualState(@ptrCast(*const IWindowProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_WindowInteractionState(self: *const T, pRetVal: ?*WindowInteractionState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_WindowInteractionState(@ptrCast(*const IWindowProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowProvider_get_IsTopmost(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowProvider.VTable, self.vtable).get_IsTopmost(@ptrCast(*const IWindowProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ILegacyIAccessibleProvider_Value = @import("../zig.zig").Guid.initString("e44c3566-915d-4070-99c6-047bff5a08f5");
pub const IID_ILegacyIAccessibleProvider = &IID_ILegacyIAccessibleProvider_Value;
pub const ILegacyIAccessibleProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Select: fn(
self: *const ILegacyIAccessibleProvider,
flagsSelect: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DoDefaultAction: fn(
self: *const ILegacyIAccessibleProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetValue: fn(
self: *const ILegacyIAccessibleProvider,
szValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIAccessible: fn(
self: *const ILegacyIAccessibleProvider,
ppAccessible: ?*?*IAccessible,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ChildId: fn(
self: *const ILegacyIAccessibleProvider,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const ILegacyIAccessibleProvider,
pszName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const ILegacyIAccessibleProvider,
pszValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const ILegacyIAccessibleProvider,
pszDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Role: fn(
self: *const ILegacyIAccessibleProvider,
pdwRole: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_State: fn(
self: *const ILegacyIAccessibleProvider,
pdwState: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Help: fn(
self: *const ILegacyIAccessibleProvider,
pszHelp: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_KeyboardShortcut: fn(
self: *const ILegacyIAccessibleProvider,
pszKeyboardShortcut: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelection: fn(
self: *const ILegacyIAccessibleProvider,
pvarSelectedChildren: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DefaultAction: fn(
self: *const ILegacyIAccessibleProvider,
pszDefaultAction: ?*?BSTR,
) 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 ILegacyIAccessibleProvider_Select(self: *const T, flagsSelect: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).Select(@ptrCast(*const ILegacyIAccessibleProvider, self), flagsSelect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_DoDefaultAction(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).DoDefaultAction(@ptrCast(*const ILegacyIAccessibleProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_SetValue(self: *const T, szValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).SetValue(@ptrCast(*const ILegacyIAccessibleProvider, self), szValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_GetIAccessible(self: *const T, ppAccessible: ?*?*IAccessible) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).GetIAccessible(@ptrCast(*const ILegacyIAccessibleProvider, self), ppAccessible);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_ChildId(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_ChildId(@ptrCast(*const ILegacyIAccessibleProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_Name(self: *const T, pszName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_Name(@ptrCast(*const ILegacyIAccessibleProvider, self), pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_Value(self: *const T, pszValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_Value(@ptrCast(*const ILegacyIAccessibleProvider, self), pszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_Description(self: *const T, pszDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_Description(@ptrCast(*const ILegacyIAccessibleProvider, self), pszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_Role(self: *const T, pdwRole: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_Role(@ptrCast(*const ILegacyIAccessibleProvider, self), pdwRole);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_State(self: *const T, pdwState: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_State(@ptrCast(*const ILegacyIAccessibleProvider, self), pdwState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_Help(self: *const T, pszHelp: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_Help(@ptrCast(*const ILegacyIAccessibleProvider, self), pszHelp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_KeyboardShortcut(self: *const T, pszKeyboardShortcut: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_KeyboardShortcut(@ptrCast(*const ILegacyIAccessibleProvider, self), pszKeyboardShortcut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_GetSelection(self: *const T, pvarSelectedChildren: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).GetSelection(@ptrCast(*const ILegacyIAccessibleProvider, self), pvarSelectedChildren);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILegacyIAccessibleProvider_get_DefaultAction(self: *const T, pszDefaultAction: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ILegacyIAccessibleProvider.VTable, self.vtable).get_DefaultAction(@ptrCast(*const ILegacyIAccessibleProvider, self), pszDefaultAction);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IItemContainerProvider_Value = @import("../zig.zig").Guid.initString("e747770b-39ce-4382-ab30-d8fb3f336f24");
pub const IID_IItemContainerProvider = &IID_IItemContainerProvider_Value;
pub const IItemContainerProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
FindItemByProperty: fn(
self: *const IItemContainerProvider,
pStartAfter: ?*IRawElementProviderSimple,
propertyId: i32,
value: VARIANT,
pFound: ?*?*IRawElementProviderSimple,
) 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 IItemContainerProvider_FindItemByProperty(self: *const T, pStartAfter: ?*IRawElementProviderSimple, propertyId: i32, value: VARIANT, pFound: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IItemContainerProvider.VTable, self.vtable).FindItemByProperty(@ptrCast(*const IItemContainerProvider, self), pStartAfter, propertyId, value, pFound);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVirtualizedItemProvider_Value = @import("../zig.zig").Guid.initString("cb98b665-2d35-4fac-ad35-f3c60d0c0b8b");
pub const IID_IVirtualizedItemProvider = &IID_IVirtualizedItemProvider_Value;
pub const IVirtualizedItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Realize: fn(
self: *const IVirtualizedItemProvider,
) 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 IVirtualizedItemProvider_Realize(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVirtualizedItemProvider.VTable, self.vtable).Realize(@ptrCast(*const IVirtualizedItemProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IObjectModelProvider_Value = @import("../zig.zig").Guid.initString("3ad86ebd-f5ef-483d-bb18-b1042a475d64");
pub const IID_IObjectModelProvider = &IID_IObjectModelProvider_Value;
pub const IObjectModelProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetUnderlyingObjectModel: fn(
self: *const IObjectModelProvider,
ppUnknown: ?*?*IUnknown,
) 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 IObjectModelProvider_GetUnderlyingObjectModel(self: *const T, ppUnknown: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IObjectModelProvider.VTable, self.vtable).GetUnderlyingObjectModel(@ptrCast(*const IObjectModelProvider, self), ppUnknown);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IAnnotationProvider_Value = @import("../zig.zig").Guid.initString("f95c7e80-bd63-4601-9782-445ebff011fc");
pub const IID_IAnnotationProvider = &IID_IAnnotationProvider_Value;
pub const IAnnotationProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AnnotationTypeId: fn(
self: *const IAnnotationProvider,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AnnotationTypeName: fn(
self: *const IAnnotationProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Author: fn(
self: *const IAnnotationProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DateTime: fn(
self: *const IAnnotationProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Target: fn(
self: *const IAnnotationProvider,
retVal: ?*?*IRawElementProviderSimple,
) 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 IAnnotationProvider_get_AnnotationTypeId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAnnotationProvider.VTable, self.vtable).get_AnnotationTypeId(@ptrCast(*const IAnnotationProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAnnotationProvider_get_AnnotationTypeName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAnnotationProvider.VTable, self.vtable).get_AnnotationTypeName(@ptrCast(*const IAnnotationProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAnnotationProvider_get_Author(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAnnotationProvider.VTable, self.vtable).get_Author(@ptrCast(*const IAnnotationProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAnnotationProvider_get_DateTime(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAnnotationProvider.VTable, self.vtable).get_DateTime(@ptrCast(*const IAnnotationProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAnnotationProvider_get_Target(self: *const T, retVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IAnnotationProvider.VTable, self.vtable).get_Target(@ptrCast(*const IAnnotationProvider, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IStylesProvider_Value = @import("../zig.zig").Guid.initString("19b6b649-f5d7-4a6d-bdcb-129252be588a");
pub const IID_IStylesProvider = &IID_IStylesProvider_Value;
pub const IStylesProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StyleId: fn(
self: *const IStylesProvider,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StyleName: fn(
self: *const IStylesProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FillColor: fn(
self: *const IStylesProvider,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FillPatternStyle: fn(
self: *const IStylesProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Shape: fn(
self: *const IStylesProvider,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FillPatternColor: fn(
self: *const IStylesProvider,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ExtendedProperties: fn(
self: *const IStylesProvider,
retVal: ?*?BSTR,
) 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 IStylesProvider_get_StyleId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_StyleId(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_StyleName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_StyleName(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_FillColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_FillColor(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_FillPatternStyle(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_FillPatternStyle(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_Shape(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_Shape(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_FillPatternColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_FillPatternColor(@ptrCast(*const IStylesProvider, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IStylesProvider_get_ExtendedProperties(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IStylesProvider.VTable, self.vtable).get_ExtendedProperties(@ptrCast(*const IStylesProvider, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ISpreadsheetProvider_Value = @import("../zig.zig").Guid.initString("6f6b5d35-5525-4f80-b758-85473832ffc7");
pub const IID_ISpreadsheetProvider = &IID_ISpreadsheetProvider_Value;
pub const ISpreadsheetProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItemByName: fn(
self: *const ISpreadsheetProvider,
name: ?[*:0]const u16,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 ISpreadsheetProvider_GetItemByName(self: *const T, name: ?[*:0]const u16, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ISpreadsheetProvider.VTable, self.vtable).GetItemByName(@ptrCast(*const ISpreadsheetProvider, self), name, pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ISpreadsheetItemProvider_Value = @import("../zig.zig").Guid.initString("eaed4660-7b3d-4879-a2e6-365ce603f3d0");
pub const IID_ISpreadsheetItemProvider = &IID_ISpreadsheetItemProvider_Value;
pub const ISpreadsheetItemProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Formula: fn(
self: *const ISpreadsheetItemProvider,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAnnotationObjects: fn(
self: *const ISpreadsheetItemProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAnnotationTypes: fn(
self: *const ISpreadsheetItemProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 ISpreadsheetItemProvider_get_Formula(self: *const T, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISpreadsheetItemProvider.VTable, self.vtable).get_Formula(@ptrCast(*const ISpreadsheetItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISpreadsheetItemProvider_GetAnnotationObjects(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ISpreadsheetItemProvider.VTable, self.vtable).GetAnnotationObjects(@ptrCast(*const ISpreadsheetItemProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISpreadsheetItemProvider_GetAnnotationTypes(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ISpreadsheetItemProvider.VTable, self.vtable).GetAnnotationTypes(@ptrCast(*const ISpreadsheetItemProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITransformProvider2_Value = @import("../zig.zig").Guid.initString("4758742f-7ac2-460c-bc48-09fc09308a93");
pub const IID_ITransformProvider2 = &IID_ITransformProvider2_Value;
pub const ITransformProvider2 = extern struct {
pub const VTable = extern struct {
base: ITransformProvider.VTable,
Zoom: fn(
self: *const ITransformProvider2,
zoom: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanZoom: fn(
self: *const ITransformProvider2,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ZoomLevel: fn(
self: *const ITransformProvider2,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ZoomMinimum: fn(
self: *const ITransformProvider2,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ZoomMaximum: fn(
self: *const ITransformProvider2,
pRetVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ZoomByUnit: fn(
self: *const ITransformProvider2,
zoomUnit: ZoomUnit,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITransformProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_Zoom(self: *const T, zoom: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).Zoom(@ptrCast(*const ITransformProvider2, self), zoom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_get_CanZoom(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).get_CanZoom(@ptrCast(*const ITransformProvider2, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_get_ZoomLevel(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).get_ZoomLevel(@ptrCast(*const ITransformProvider2, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_get_ZoomMinimum(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).get_ZoomMinimum(@ptrCast(*const ITransformProvider2, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_get_ZoomMaximum(self: *const T, pRetVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).get_ZoomMaximum(@ptrCast(*const ITransformProvider2, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransformProvider2_ZoomByUnit(self: *const T, zoomUnit: ZoomUnit) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransformProvider2.VTable, self.vtable).ZoomByUnit(@ptrCast(*const ITransformProvider2, self), zoomUnit);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDragProvider_Value = @import("../zig.zig").Guid.initString("6aa7bbbb-7ff9-497d-904f-d20b897929d8");
pub const IID_IDragProvider = &IID_IDragProvider_Value;
pub const IDragProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsGrabbed: fn(
self: *const IDragProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DropEffect: fn(
self: *const IDragProvider,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DropEffects: fn(
self: *const IDragProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGrabbedItems: fn(
self: *const IDragProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 IDragProvider_get_IsGrabbed(self: *const T, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDragProvider.VTable, self.vtable).get_IsGrabbed(@ptrCast(*const IDragProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDragProvider_get_DropEffect(self: *const T, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDragProvider.VTable, self.vtable).get_DropEffect(@ptrCast(*const IDragProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDragProvider_get_DropEffects(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDragProvider.VTable, self.vtable).get_DropEffects(@ptrCast(*const IDragProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDragProvider_GetGrabbedItems(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDragProvider.VTable, self.vtable).GetGrabbedItems(@ptrCast(*const IDragProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IDropTargetProvider_Value = @import("../zig.zig").Guid.initString("bae82bfd-358a-481c-85a0-d8b4d90a5d61");
pub const IID_IDropTargetProvider = &IID_IDropTargetProvider_Value;
pub const IDropTargetProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DropTargetEffect: fn(
self: *const IDropTargetProvider,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DropTargetEffects: fn(
self: *const IDropTargetProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 IDropTargetProvider_get_DropTargetEffect(self: *const T, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDropTargetProvider.VTable, self.vtable).get_DropTargetEffect(@ptrCast(*const IDropTargetProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDropTargetProvider_get_DropTargetEffects(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDropTargetProvider.VTable, self.vtable).get_DropTargetEffects(@ptrCast(*const IDropTargetProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ITextRangeProvider_Value = @import("../zig.zig").Guid.initString("5347ad7b-c355-46f8-aff5-909033582f63");
pub const IID_ITextRangeProvider = &IID_ITextRangeProvider_Value;
pub const ITextRangeProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Clone: fn(
self: *const ITextRangeProvider,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Compare: fn(
self: *const ITextRangeProvider,
range: ?*ITextRangeProvider,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CompareEndpoints: fn(
self: *const ITextRangeProvider,
endpoint: TextPatternRangeEndpoint,
targetRange: ?*ITextRangeProvider,
targetEndpoint: TextPatternRangeEndpoint,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExpandToEnclosingUnit: fn(
self: *const ITextRangeProvider,
unit: TextUnit,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAttribute: fn(
self: *const ITextRangeProvider,
attributeId: i32,
val: VARIANT,
backward: BOOL,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindText: fn(
self: *const ITextRangeProvider,
text: ?BSTR,
backward: BOOL,
ignoreCase: BOOL,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributeValue: fn(
self: *const ITextRangeProvider,
attributeId: i32,
pRetVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBoundingRectangles: fn(
self: *const ITextRangeProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnclosingElement: fn(
self: *const ITextRangeProvider,
pRetVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetText: fn(
self: *const ITextRangeProvider,
maxLength: i32,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const ITextRangeProvider,
unit: TextUnit,
count: i32,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndpointByUnit: fn(
self: *const ITextRangeProvider,
endpoint: TextPatternRangeEndpoint,
unit: TextUnit,
count: i32,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndpointByRange: fn(
self: *const ITextRangeProvider,
endpoint: TextPatternRangeEndpoint,
targetRange: ?*ITextRangeProvider,
targetEndpoint: TextPatternRangeEndpoint,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Select: fn(
self: *const ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddToSelection: fn(
self: *const ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFromSelection: fn(
self: *const ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScrollIntoView: fn(
self: *const ITextRangeProvider,
alignToTop: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildren: fn(
self: *const ITextRangeProvider,
pRetVal: ?*?*SAFEARRAY,
) 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 ITextRangeProvider_Clone(self: *const T, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).Clone(@ptrCast(*const ITextRangeProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_Compare(self: *const T, range: ?*ITextRangeProvider, pRetVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).Compare(@ptrCast(*const ITextRangeProvider, self), range, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_CompareEndpoints(self: *const T, endpoint: TextPatternRangeEndpoint, targetRange: ?*ITextRangeProvider, targetEndpoint: TextPatternRangeEndpoint, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).CompareEndpoints(@ptrCast(*const ITextRangeProvider, self), endpoint, targetRange, targetEndpoint, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_ExpandToEnclosingUnit(self: *const T, unit: TextUnit) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).ExpandToEnclosingUnit(@ptrCast(*const ITextRangeProvider, self), unit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_FindAttribute(self: *const T, attributeId: i32, val: VARIANT, backward: BOOL, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).FindAttribute(@ptrCast(*const ITextRangeProvider, self), attributeId, val, backward, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_FindText(self: *const T, text: ?BSTR, backward: BOOL, ignoreCase: BOOL, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).FindText(@ptrCast(*const ITextRangeProvider, self), text, backward, ignoreCase, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_GetAttributeValue(self: *const T, attributeId: i32, pRetVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).GetAttributeValue(@ptrCast(*const ITextRangeProvider, self), attributeId, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_GetBoundingRectangles(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).GetBoundingRectangles(@ptrCast(*const ITextRangeProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_GetEnclosingElement(self: *const T, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).GetEnclosingElement(@ptrCast(*const ITextRangeProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_GetText(self: *const T, maxLength: i32, pRetVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).GetText(@ptrCast(*const ITextRangeProvider, self), maxLength, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_Move(self: *const T, unit: TextUnit, count: i32, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).Move(@ptrCast(*const ITextRangeProvider, self), unit, count, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_MoveEndpointByUnit(self: *const T, endpoint: TextPatternRangeEndpoint, unit: TextUnit, count: i32, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).MoveEndpointByUnit(@ptrCast(*const ITextRangeProvider, self), endpoint, unit, count, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_MoveEndpointByRange(self: *const T, endpoint: TextPatternRangeEndpoint, targetRange: ?*ITextRangeProvider, targetEndpoint: TextPatternRangeEndpoint) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).MoveEndpointByRange(@ptrCast(*const ITextRangeProvider, self), endpoint, targetRange, targetEndpoint);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_Select(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).Select(@ptrCast(*const ITextRangeProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_AddToSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).AddToSelection(@ptrCast(*const ITextRangeProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_RemoveFromSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).RemoveFromSelection(@ptrCast(*const ITextRangeProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_ScrollIntoView(self: *const T, alignToTop: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).ScrollIntoView(@ptrCast(*const ITextRangeProvider, self), alignToTop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider_GetChildren(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider.VTable, self.vtable).GetChildren(@ptrCast(*const ITextRangeProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ITextProvider_Value = @import("../zig.zig").Guid.initString("3589c92c-63f3-4367-99bb-ada653b77cf2");
pub const IID_ITextProvider = &IID_ITextProvider_Value;
pub const ITextProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSelection: fn(
self: *const ITextProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVisibleRanges: fn(
self: *const ITextProvider,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RangeFromChild: fn(
self: *const ITextProvider,
childElement: ?*IRawElementProviderSimple,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RangeFromPoint: fn(
self: *const ITextProvider,
point: UiaPoint,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DocumentRange: fn(
self: *const ITextProvider,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SupportedTextSelection: fn(
self: *const ITextProvider,
pRetVal: ?*SupportedTextSelection,
) 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 ITextProvider_GetSelection(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).GetSelection(@ptrCast(*const ITextProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider_GetVisibleRanges(self: *const T, pRetVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).GetVisibleRanges(@ptrCast(*const ITextProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider_RangeFromChild(self: *const T, childElement: ?*IRawElementProviderSimple, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).RangeFromChild(@ptrCast(*const ITextProvider, self), childElement, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider_RangeFromPoint(self: *const T, point: UiaPoint, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).RangeFromPoint(@ptrCast(*const ITextProvider, self), point, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider_get_DocumentRange(self: *const T, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).get_DocumentRange(@ptrCast(*const ITextProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider_get_SupportedTextSelection(self: *const T, pRetVal: ?*SupportedTextSelection) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider.VTable, self.vtable).get_SupportedTextSelection(@ptrCast(*const ITextProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextProvider2_Value = @import("../zig.zig").Guid.initString("0dc5e6ed-3e16-4bf1-8f9a-a979878bc195");
pub const IID_ITextProvider2 = &IID_ITextProvider2_Value;
pub const ITextProvider2 = extern struct {
pub const VTable = extern struct {
base: ITextProvider.VTable,
RangeFromAnnotation: fn(
self: *const ITextProvider2,
annotationElement: ?*IRawElementProviderSimple,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCaretRange: fn(
self: *const ITextProvider2,
isActive: ?*BOOL,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider2_RangeFromAnnotation(self: *const T, annotationElement: ?*IRawElementProviderSimple, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider2.VTable, self.vtable).RangeFromAnnotation(@ptrCast(*const ITextProvider2, self), annotationElement, pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextProvider2_GetCaretRange(self: *const T, isActive: ?*BOOL, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextProvider2.VTable, self.vtable).GetCaretRange(@ptrCast(*const ITextProvider2, self), isActive, pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_ITextEditProvider_Value = @import("../zig.zig").Guid.initString("ea3605b4-3a05-400e-b5f9-4e91b40f6176");
pub const IID_ITextEditProvider = &IID_ITextEditProvider_Value;
pub const ITextEditProvider = extern struct {
pub const VTable = extern struct {
base: ITextProvider.VTable,
GetActiveComposition: fn(
self: *const ITextEditProvider,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConversionTarget: fn(
self: *const ITextEditProvider,
pRetVal: ?*?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextEditProvider_GetActiveComposition(self: *const T, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextEditProvider.VTable, self.vtable).GetActiveComposition(@ptrCast(*const ITextEditProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextEditProvider_GetConversionTarget(self: *const T, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextEditProvider.VTable, self.vtable).GetConversionTarget(@ptrCast(*const ITextEditProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_ITextRangeProvider2_Value = @import("../zig.zig").Guid.initString("9bbce42c-1921-4f18-89ca-dba1910a0386");
pub const IID_ITextRangeProvider2 = &IID_ITextRangeProvider2_Value;
pub const ITextRangeProvider2 = extern struct {
pub const VTable = extern struct {
base: ITextRangeProvider.VTable,
ShowContextMenu: fn(
self: *const ITextRangeProvider2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextRangeProvider.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRangeProvider2_ShowContextMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRangeProvider2.VTable, self.vtable).ShowContextMenu(@ptrCast(*const ITextRangeProvider2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextChildProvider_Value = @import("../zig.zig").Guid.initString("4c2de2b9-c88f-4f88-a111-f1d336b7d1a9");
pub const IID_ITextChildProvider = &IID_ITextChildProvider_Value;
pub const ITextChildProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TextContainer: fn(
self: *const ITextChildProvider,
pRetVal: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TextRange: fn(
self: *const ITextChildProvider,
pRetVal: ?*?*ITextRangeProvider,
) 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 ITextChildProvider_get_TextContainer(self: *const T, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextChildProvider.VTable, self.vtable).get_TextContainer(@ptrCast(*const ITextChildProvider, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextChildProvider_get_TextRange(self: *const T, pRetVal: ?*?*ITextRangeProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextChildProvider.VTable, self.vtable).get_TextRange(@ptrCast(*const ITextChildProvider, self), pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ICustomNavigationProvider_Value = @import("../zig.zig").Guid.initString("2062a28a-8c07-4b94-8e12-7037c622aeb8");
pub const IID_ICustomNavigationProvider = &IID_ICustomNavigationProvider_Value;
pub const ICustomNavigationProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Navigate: fn(
self: *const ICustomNavigationProvider,
direction: NavigateDirection,
pRetVal: ?*?*IRawElementProviderSimple,
) 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 ICustomNavigationProvider_Navigate(self: *const T, direction: NavigateDirection, pRetVal: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const ICustomNavigationProvider.VTable, self.vtable).Navigate(@ptrCast(*const ICustomNavigationProvider, self), direction, pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationPatternInstance_Value = @import("../zig.zig").Guid.initString("c03a7fe4-9431-409f-bed8-ae7c2299bc8d");
pub const IID_IUIAutomationPatternInstance = &IID_IUIAutomationPatternInstance_Value;
pub const IUIAutomationPatternInstance = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperty: fn(
self: *const IUIAutomationPatternInstance,
index: u32,
cached: BOOL,
type: UIAutomationType,
pPtr: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CallMethod: fn(
self: *const IUIAutomationPatternInstance,
index: u32,
pParams: ?*const UIAutomationParameter,
cParams: 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 IUIAutomationPatternInstance_GetProperty(self: *const T, index: u32, cached: BOOL, type_: UIAutomationType, pPtr: ?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPatternInstance.VTable, self.vtable).GetProperty(@ptrCast(*const IUIAutomationPatternInstance, self), index, cached, type_, pPtr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationPatternInstance_CallMethod(self: *const T, index: u32, pParams: ?*const UIAutomationParameter, cParams: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPatternInstance.VTable, self.vtable).CallMethod(@ptrCast(*const IUIAutomationPatternInstance, self), index, pParams, cParams);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationPatternHandler_Value = @import("../zig.zig").Guid.initString("d97022f3-a947-465e-8b2a-ac4315fa54e8");
pub const IID_IUIAutomationPatternHandler = &IID_IUIAutomationPatternHandler_Value;
pub const IUIAutomationPatternHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateClientWrapper: fn(
self: *const IUIAutomationPatternHandler,
pPatternInstance: ?*IUIAutomationPatternInstance,
pClientWrapper: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Dispatch: fn(
self: *const IUIAutomationPatternHandler,
pTarget: ?*IUnknown,
index: u32,
pParams: ?*const UIAutomationParameter,
cParams: 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 IUIAutomationPatternHandler_CreateClientWrapper(self: *const T, pPatternInstance: ?*IUIAutomationPatternInstance, pClientWrapper: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPatternHandler.VTable, self.vtable).CreateClientWrapper(@ptrCast(*const IUIAutomationPatternHandler, self), pPatternInstance, pClientWrapper);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationPatternHandler_Dispatch(self: *const T, pTarget: ?*IUnknown, index: u32, pParams: ?*const UIAutomationParameter, cParams: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPatternHandler.VTable, self.vtable).Dispatch(@ptrCast(*const IUIAutomationPatternHandler, self), pTarget, index, pParams, cParams);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationRegistrar_Value = @import("../zig.zig").Guid.initString("8609c4ec-4a1a-4d88-a357-5a66e060e1cf");
pub const IID_IUIAutomationRegistrar = &IID_IUIAutomationRegistrar_Value;
pub const IUIAutomationRegistrar = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RegisterProperty: fn(
self: *const IUIAutomationRegistrar,
property: ?*const UIAutomationPropertyInfo,
propertyId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterEvent: fn(
self: *const IUIAutomationRegistrar,
event: ?*const UIAutomationEventInfo,
eventId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterPattern: fn(
self: *const IUIAutomationRegistrar,
pattern: ?*const UIAutomationPatternInfo,
pPatternId: ?*i32,
pPatternAvailablePropertyId: ?*i32,
propertyIdCount: u32,
pPropertyIds: [*]i32,
eventIdCount: u32,
pEventIds: [*]i32,
) 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 IUIAutomationRegistrar_RegisterProperty(self: *const T, property: ?*const UIAutomationPropertyInfo, propertyId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRegistrar.VTable, self.vtable).RegisterProperty(@ptrCast(*const IUIAutomationRegistrar, self), property, propertyId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRegistrar_RegisterEvent(self: *const T, event: ?*const UIAutomationEventInfo, eventId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRegistrar.VTable, self.vtable).RegisterEvent(@ptrCast(*const IUIAutomationRegistrar, self), event, eventId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRegistrar_RegisterPattern(self: *const T, pattern: ?*const UIAutomationPatternInfo, pPatternId: ?*i32, pPatternAvailablePropertyId: ?*i32, propertyIdCount: u32, pPropertyIds: [*]i32, eventIdCount: u32, pEventIds: [*]i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRegistrar.VTable, self.vtable).RegisterPattern(@ptrCast(*const IUIAutomationRegistrar, self), pattern, pPatternId, pPatternAvailablePropertyId, propertyIdCount, pPropertyIds, eventIdCount, pEventIds);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const TreeScope = enum(i32) {
None = 0,
Element = 1,
Children = 2,
Descendants = 4,
Parent = 8,
Ancestors = 16,
Subtree = 7,
};
pub const TreeScope_None = TreeScope.None;
pub const TreeScope_Element = TreeScope.Element;
pub const TreeScope_Children = TreeScope.Children;
pub const TreeScope_Descendants = TreeScope.Descendants;
pub const TreeScope_Parent = TreeScope.Parent;
pub const TreeScope_Ancestors = TreeScope.Ancestors;
pub const TreeScope_Subtree = TreeScope.Subtree;
pub const PropertyConditionFlags = enum(i32) {
None = 0,
IgnoreCase = 1,
MatchSubstring = 2,
};
pub const PropertyConditionFlags_None = PropertyConditionFlags.None;
pub const PropertyConditionFlags_IgnoreCase = PropertyConditionFlags.IgnoreCase;
pub const PropertyConditionFlags_MatchSubstring = PropertyConditionFlags.MatchSubstring;
pub const AutomationElementMode = enum(i32) {
None = 0,
Full = 1,
};
pub const AutomationElementMode_None = AutomationElementMode.None;
pub const AutomationElementMode_Full = AutomationElementMode.Full;
pub const TreeTraversalOptions = enum(i32) {
Default = 0,
PostOrder = 1,
LastToFirstOrder = 2,
};
pub const TreeTraversalOptions_Default = TreeTraversalOptions.Default;
pub const TreeTraversalOptions_PostOrder = TreeTraversalOptions.PostOrder;
pub const TreeTraversalOptions_LastToFirstOrder = TreeTraversalOptions.LastToFirstOrder;
pub const ConnectionRecoveryBehaviorOptions = enum(i32) {
Disabled = 0,
Enabled = 1,
};
pub const ConnectionRecoveryBehaviorOptions_Disabled = ConnectionRecoveryBehaviorOptions.Disabled;
pub const ConnectionRecoveryBehaviorOptions_Enabled = ConnectionRecoveryBehaviorOptions.Enabled;
pub const CoalesceEventsOptions = enum(i32) {
Disabled = 0,
Enabled = 1,
};
pub const CoalesceEventsOptions_Disabled = CoalesceEventsOptions.Disabled;
pub const CoalesceEventsOptions_Enabled = CoalesceEventsOptions.Enabled;
pub const ExtendedProperty = extern struct {
PropertyName: ?BSTR,
PropertyValue: ?BSTR,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationElement_Value = @import("../zig.zig").Guid.initString("d22108aa-8ac5-49a5-837b-37bbb3d7591e");
pub const IID_IUIAutomationElement = &IID_IUIAutomationElement_Value;
pub const IUIAutomationElement = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetFocus: fn(
self: *const IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRuntimeId: fn(
self: *const IUIAutomationElement,
runtimeId: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFirst: fn(
self: *const IUIAutomationElement,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
found: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAll: fn(
self: *const IUIAutomationElement,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
found: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFirstBuildCache: fn(
self: *const IUIAutomationElement,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
cacheRequest: ?*IUIAutomationCacheRequest,
found: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAllBuildCache: fn(
self: *const IUIAutomationElement,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
cacheRequest: ?*IUIAutomationCacheRequest,
found: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BuildUpdatedCache: fn(
self: *const IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
updatedElement: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPropertyValue: fn(
self: *const IUIAutomationElement,
propertyId: i32,
retVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPropertyValueEx: fn(
self: *const IUIAutomationElement,
propertyId: i32,
ignoreDefaultValue: BOOL,
retVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedPropertyValue: fn(
self: *const IUIAutomationElement,
propertyId: i32,
retVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedPropertyValueEx: fn(
self: *const IUIAutomationElement,
propertyId: i32,
ignoreDefaultValue: BOOL,
retVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPatternAs: fn(
self: *const IUIAutomationElement,
patternId: i32,
riid: ?*const Guid,
patternObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedPatternAs: fn(
self: *const IUIAutomationElement,
patternId: i32,
riid: ?*const Guid,
patternObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPattern: fn(
self: *const IUIAutomationElement,
patternId: i32,
patternObject: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedPattern: fn(
self: *const IUIAutomationElement,
patternId: i32,
patternObject: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedParent: fn(
self: *const IUIAutomationElement,
parent: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedChildren: fn(
self: *const IUIAutomationElement,
children: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentProcessId: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentControlType: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLocalizedControlType: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentName: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAcceleratorKey: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAccessKey: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHasKeyboardFocus: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsKeyboardFocusable: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsEnabled: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAutomationId: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentClassName: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHelpText: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCulture: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsControlElement: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsContentElement: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsPassword: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentNativeWindowHandle: fn(
self: *const IUIAutomationElement,
retVal: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentItemType: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsOffscreen: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentOrientation: fn(
self: *const IUIAutomationElement,
retVal: ?*OrientationType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFrameworkId: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsRequiredForForm: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentItemStatus: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentBoundingRectangle: fn(
self: *const IUIAutomationElement,
retVal: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLabeledBy: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAriaRole: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAriaProperties: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsDataValidForForm: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentControllerFor: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDescribedBy: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFlowsTo: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentProviderDescription: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedProcessId: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedControlType: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLocalizedControlType: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedName: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAcceleratorKey: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAccessKey: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHasKeyboardFocus: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsKeyboardFocusable: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsEnabled: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAutomationId: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedClassName: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHelpText: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCulture: fn(
self: *const IUIAutomationElement,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsControlElement: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsContentElement: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsPassword: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedNativeWindowHandle: fn(
self: *const IUIAutomationElement,
retVal: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedItemType: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsOffscreen: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedOrientation: fn(
self: *const IUIAutomationElement,
retVal: ?*OrientationType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFrameworkId: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsRequiredForForm: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedItemStatus: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedBoundingRectangle: fn(
self: *const IUIAutomationElement,
retVal: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLabeledBy: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAriaRole: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAriaProperties: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsDataValidForForm: fn(
self: *const IUIAutomationElement,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedControllerFor: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDescribedBy: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFlowsTo: fn(
self: *const IUIAutomationElement,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedProviderDescription: fn(
self: *const IUIAutomationElement,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClickablePoint: fn(
self: *const IUIAutomationElement,
clickable: ?*POINT,
gotClickable: ?*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 IUIAutomationElement_SetFocus(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).SetFocus(@ptrCast(*const IUIAutomationElement, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetRuntimeId(self: *const T, runtimeId: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetRuntimeId(@ptrCast(*const IUIAutomationElement, self), runtimeId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_FindFirst(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, found: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).FindFirst(@ptrCast(*const IUIAutomationElement, self), scope, condition, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_FindAll(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, found: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).FindAll(@ptrCast(*const IUIAutomationElement, self), scope, condition, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_FindFirstBuildCache(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, cacheRequest: ?*IUIAutomationCacheRequest, found: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).FindFirstBuildCache(@ptrCast(*const IUIAutomationElement, self), scope, condition, cacheRequest, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_FindAllBuildCache(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, cacheRequest: ?*IUIAutomationCacheRequest, found: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).FindAllBuildCache(@ptrCast(*const IUIAutomationElement, self), scope, condition, cacheRequest, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_BuildUpdatedCache(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, updatedElement: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).BuildUpdatedCache(@ptrCast(*const IUIAutomationElement, self), cacheRequest, updatedElement);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCurrentPropertyValue(self: *const T, propertyId: i32, retVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCurrentPropertyValue(@ptrCast(*const IUIAutomationElement, self), propertyId, retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCurrentPropertyValueEx(self: *const T, propertyId: i32, ignoreDefaultValue: BOOL, retVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCurrentPropertyValueEx(@ptrCast(*const IUIAutomationElement, self), propertyId, ignoreDefaultValue, retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedPropertyValue(self: *const T, propertyId: i32, retVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedPropertyValue(@ptrCast(*const IUIAutomationElement, self), propertyId, retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedPropertyValueEx(self: *const T, propertyId: i32, ignoreDefaultValue: BOOL, retVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedPropertyValueEx(@ptrCast(*const IUIAutomationElement, self), propertyId, ignoreDefaultValue, retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCurrentPatternAs(self: *const T, patternId: i32, riid: ?*const Guid, patternObject: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCurrentPatternAs(@ptrCast(*const IUIAutomationElement, self), patternId, riid, patternObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedPatternAs(self: *const T, patternId: i32, riid: ?*const Guid, patternObject: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedPatternAs(@ptrCast(*const IUIAutomationElement, self), patternId, riid, patternObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCurrentPattern(self: *const T, patternId: i32, patternObject: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCurrentPattern(@ptrCast(*const IUIAutomationElement, self), patternId, patternObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedPattern(self: *const T, patternId: i32, patternObject: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedPattern(@ptrCast(*const IUIAutomationElement, self), patternId, patternObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedParent(self: *const T, parent: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedParent(@ptrCast(*const IUIAutomationElement, self), parent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetCachedChildren(self: *const T, children: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetCachedChildren(@ptrCast(*const IUIAutomationElement, self), children);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentProcessId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentProcessId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentControlType(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentControlType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentLocalizedControlType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentLocalizedControlType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentName(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentAcceleratorKey(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentAcceleratorKey(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentAccessKey(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentAccessKey(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentHasKeyboardFocus(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentHasKeyboardFocus(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsKeyboardFocusable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsKeyboardFocusable(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsEnabled(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsEnabled(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentAutomationId(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentAutomationId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentClassName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentClassName(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentHelpText(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentHelpText(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentCulture(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentCulture(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsControlElement(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsControlElement(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsContentElement(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsContentElement(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsPassword(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsPassword(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentNativeWindowHandle(self: *const T, retVal: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentNativeWindowHandle(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentItemType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentItemType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsOffscreen(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsOffscreen(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentOrientation(self: *const T, retVal: ?*OrientationType) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentOrientation(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentFrameworkId(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentFrameworkId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsRequiredForForm(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsRequiredForForm(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentItemStatus(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentItemStatus(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentBoundingRectangle(self: *const T, retVal: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentBoundingRectangle(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentLabeledBy(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentLabeledBy(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentAriaRole(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentAriaRole(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentAriaProperties(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentAriaProperties(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentIsDataValidForForm(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentIsDataValidForForm(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentControllerFor(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentControllerFor(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentDescribedBy(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentDescribedBy(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentFlowsTo(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentFlowsTo(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CurrentProviderDescription(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CurrentProviderDescription(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedProcessId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedProcessId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedControlType(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedControlType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedLocalizedControlType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedLocalizedControlType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedName(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedAcceleratorKey(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedAcceleratorKey(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedAccessKey(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedAccessKey(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedHasKeyboardFocus(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedHasKeyboardFocus(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsKeyboardFocusable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsKeyboardFocusable(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsEnabled(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsEnabled(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedAutomationId(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedAutomationId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedClassName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedClassName(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedHelpText(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedHelpText(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedCulture(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedCulture(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsControlElement(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsControlElement(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsContentElement(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsContentElement(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsPassword(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsPassword(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedNativeWindowHandle(self: *const T, retVal: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedNativeWindowHandle(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedItemType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedItemType(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsOffscreen(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsOffscreen(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedOrientation(self: *const T, retVal: ?*OrientationType) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedOrientation(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedFrameworkId(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedFrameworkId(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsRequiredForForm(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsRequiredForForm(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedItemStatus(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedItemStatus(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedBoundingRectangle(self: *const T, retVal: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedBoundingRectangle(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedLabeledBy(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedLabeledBy(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedAriaRole(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedAriaRole(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedAriaProperties(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedAriaProperties(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedIsDataValidForForm(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedIsDataValidForForm(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedControllerFor(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedControllerFor(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedDescribedBy(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedDescribedBy(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedFlowsTo(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedFlowsTo(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_get_CachedProviderDescription(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).get_CachedProviderDescription(@ptrCast(*const IUIAutomationElement, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement_GetClickablePoint(self: *const T, clickable: ?*POINT, gotClickable: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement.VTable, self.vtable).GetClickablePoint(@ptrCast(*const IUIAutomationElement, self), clickable, gotClickable);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationElementArray_Value = @import("../zig.zig").Guid.initString("14314595-b4bc-4055-95f2-58f2e42c9855");
pub const IID_IUIAutomationElementArray = &IID_IUIAutomationElementArray_Value;
pub const IUIAutomationElementArray = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Length: fn(
self: *const IUIAutomationElementArray,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetElement: fn(
self: *const IUIAutomationElementArray,
index: i32,
element: ?*?*IUIAutomationElement,
) 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 IUIAutomationElementArray_get_Length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElementArray.VTable, self.vtable).get_Length(@ptrCast(*const IUIAutomationElementArray, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElementArray_GetElement(self: *const T, index: i32, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElementArray.VTable, self.vtable).GetElement(@ptrCast(*const IUIAutomationElementArray, self), index, element);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationCondition_Value = @import("../zig.zig").Guid.initString("352ffba8-0973-437c-a61f-f64cafd81df9");
pub const IID_IUIAutomationCondition = &IID_IUIAutomationCondition_Value;
pub const IUIAutomationCondition = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationBoolCondition_Value = @import("../zig.zig").Guid.initString("1b4e1f2e-75eb-4d0b-8952-5a69988e2307");
pub const IID_IUIAutomationBoolCondition = &IID_IUIAutomationBoolCondition_Value;
pub const IUIAutomationBoolCondition = extern struct {
pub const VTable = extern struct {
base: IUIAutomationCondition.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BooleanValue: fn(
self: *const IUIAutomationBoolCondition,
boolVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationCondition.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationBoolCondition_get_BooleanValue(self: *const T, boolVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationBoolCondition.VTable, self.vtable).get_BooleanValue(@ptrCast(*const IUIAutomationBoolCondition, self), boolVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationPropertyCondition_Value = @import("../zig.zig").Guid.initString("99ebf2cb-5578-4267-9ad4-afd6ea77e94b");
pub const IID_IUIAutomationPropertyCondition = &IID_IUIAutomationPropertyCondition_Value;
pub const IUIAutomationPropertyCondition = extern struct {
pub const VTable = extern struct {
base: IUIAutomationCondition.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PropertyId: fn(
self: *const IUIAutomationPropertyCondition,
propertyId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PropertyValue: fn(
self: *const IUIAutomationPropertyCondition,
propertyValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PropertyConditionFlags: fn(
self: *const IUIAutomationPropertyCondition,
flags: ?*PropertyConditionFlags,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationCondition.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationPropertyCondition_get_PropertyId(self: *const T, propertyId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPropertyCondition.VTable, self.vtable).get_PropertyId(@ptrCast(*const IUIAutomationPropertyCondition, self), propertyId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationPropertyCondition_get_PropertyValue(self: *const T, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPropertyCondition.VTable, self.vtable).get_PropertyValue(@ptrCast(*const IUIAutomationPropertyCondition, self), propertyValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationPropertyCondition_get_PropertyConditionFlags(self: *const T, flags: ?*PropertyConditionFlags) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPropertyCondition.VTable, self.vtable).get_PropertyConditionFlags(@ptrCast(*const IUIAutomationPropertyCondition, self), flags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationAndCondition_Value = @import("../zig.zig").Guid.initString("a7d0af36-b912-45fe-9855-091ddc174aec");
pub const IID_IUIAutomationAndCondition = &IID_IUIAutomationAndCondition_Value;
pub const IUIAutomationAndCondition = extern struct {
pub const VTable = extern struct {
base: IUIAutomationCondition.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ChildCount: fn(
self: *const IUIAutomationAndCondition,
childCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildrenAsNativeArray: fn(
self: *const IUIAutomationAndCondition,
childArray: [*]?*?*IUIAutomationCondition,
childArrayCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildren: fn(
self: *const IUIAutomationAndCondition,
childArray: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationCondition.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAndCondition_get_ChildCount(self: *const T, childCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAndCondition.VTable, self.vtable).get_ChildCount(@ptrCast(*const IUIAutomationAndCondition, self), childCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAndCondition_GetChildrenAsNativeArray(self: *const T, childArray: [*]?*?*IUIAutomationCondition, childArrayCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAndCondition.VTable, self.vtable).GetChildrenAsNativeArray(@ptrCast(*const IUIAutomationAndCondition, self), childArray, childArrayCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAndCondition_GetChildren(self: *const T, childArray: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAndCondition.VTable, self.vtable).GetChildren(@ptrCast(*const IUIAutomationAndCondition, self), childArray);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationOrCondition_Value = @import("../zig.zig").Guid.initString("8753f032-3db1-47b5-a1fc-6e34a266c712");
pub const IID_IUIAutomationOrCondition = &IID_IUIAutomationOrCondition_Value;
pub const IUIAutomationOrCondition = extern struct {
pub const VTable = extern struct {
base: IUIAutomationCondition.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ChildCount: fn(
self: *const IUIAutomationOrCondition,
childCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildrenAsNativeArray: fn(
self: *const IUIAutomationOrCondition,
childArray: [*]?*?*IUIAutomationCondition,
childArrayCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildren: fn(
self: *const IUIAutomationOrCondition,
childArray: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationCondition.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationOrCondition_get_ChildCount(self: *const T, childCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationOrCondition.VTable, self.vtable).get_ChildCount(@ptrCast(*const IUIAutomationOrCondition, self), childCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationOrCondition_GetChildrenAsNativeArray(self: *const T, childArray: [*]?*?*IUIAutomationCondition, childArrayCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationOrCondition.VTable, self.vtable).GetChildrenAsNativeArray(@ptrCast(*const IUIAutomationOrCondition, self), childArray, childArrayCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationOrCondition_GetChildren(self: *const T, childArray: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationOrCondition.VTable, self.vtable).GetChildren(@ptrCast(*const IUIAutomationOrCondition, self), childArray);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationNotCondition_Value = @import("../zig.zig").Guid.initString("f528b657-847b-498c-8896-d52b565407a1");
pub const IID_IUIAutomationNotCondition = &IID_IUIAutomationNotCondition_Value;
pub const IUIAutomationNotCondition = extern struct {
pub const VTable = extern struct {
base: IUIAutomationCondition.VTable,
GetChild: fn(
self: *const IUIAutomationNotCondition,
condition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationCondition.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationNotCondition_GetChild(self: *const T, condition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationNotCondition.VTable, self.vtable).GetChild(@ptrCast(*const IUIAutomationNotCondition, self), condition);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationCacheRequest_Value = @import("../zig.zig").Guid.initString("b32a92b5-bc25-4078-9c08-d7ee95c48e03");
pub const IID_IUIAutomationCacheRequest = &IID_IUIAutomationCacheRequest_Value;
pub const IUIAutomationCacheRequest = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddProperty: fn(
self: *const IUIAutomationCacheRequest,
propertyId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPattern: fn(
self: *const IUIAutomationCacheRequest,
patternId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IUIAutomationCacheRequest,
clonedRequest: ?*?*IUIAutomationCacheRequest,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TreeScope: fn(
self: *const IUIAutomationCacheRequest,
scope: ?*TreeScope,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TreeScope: fn(
self: *const IUIAutomationCacheRequest,
scope: TreeScope,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TreeFilter: fn(
self: *const IUIAutomationCacheRequest,
filter: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TreeFilter: fn(
self: *const IUIAutomationCacheRequest,
filter: ?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AutomationElementMode: fn(
self: *const IUIAutomationCacheRequest,
mode: ?*AutomationElementMode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AutomationElementMode: fn(
self: *const IUIAutomationCacheRequest,
mode: AutomationElementMode,
) 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 IUIAutomationCacheRequest_AddProperty(self: *const T, propertyId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).AddProperty(@ptrCast(*const IUIAutomationCacheRequest, self), propertyId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_AddPattern(self: *const T, patternId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).AddPattern(@ptrCast(*const IUIAutomationCacheRequest, self), patternId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_Clone(self: *const T, clonedRequest: ?*?*IUIAutomationCacheRequest) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).Clone(@ptrCast(*const IUIAutomationCacheRequest, self), clonedRequest);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_get_TreeScope(self: *const T, scope: ?*TreeScope) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).get_TreeScope(@ptrCast(*const IUIAutomationCacheRequest, self), scope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_put_TreeScope(self: *const T, scope: TreeScope) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).put_TreeScope(@ptrCast(*const IUIAutomationCacheRequest, self), scope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_get_TreeFilter(self: *const T, filter: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).get_TreeFilter(@ptrCast(*const IUIAutomationCacheRequest, self), filter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_put_TreeFilter(self: *const T, filter: ?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).put_TreeFilter(@ptrCast(*const IUIAutomationCacheRequest, self), filter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_get_AutomationElementMode(self: *const T, mode: ?*AutomationElementMode) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).get_AutomationElementMode(@ptrCast(*const IUIAutomationCacheRequest, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationCacheRequest_put_AutomationElementMode(self: *const T, mode: AutomationElementMode) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCacheRequest.VTable, self.vtable).put_AutomationElementMode(@ptrCast(*const IUIAutomationCacheRequest, self), mode);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTreeWalker_Value = @import("../zig.zig").Guid.initString("4042c624-389c-4afc-a630-9df854a541fc");
pub const IID_IUIAutomationTreeWalker = &IID_IUIAutomationTreeWalker_Value;
pub const IUIAutomationTreeWalker = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetParentElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
parent: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstChildElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
first: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastChildElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
last: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNextSiblingElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
next: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousSiblingElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
previous: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NormalizeElement: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
normalized: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetParentElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
parent: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstChildElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
first: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLastChildElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
last: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNextSiblingElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
next: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousSiblingElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
previous: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NormalizeElementBuildCache: fn(
self: *const IUIAutomationTreeWalker,
element: ?*IUIAutomationElement,
cacheRequest: ?*IUIAutomationCacheRequest,
normalized: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Condition: fn(
self: *const IUIAutomationTreeWalker,
condition: ?*?*IUIAutomationCondition,
) 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 IUIAutomationTreeWalker_GetParentElement(self: *const T, element: ?*IUIAutomationElement, parent: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetParentElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, parent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetFirstChildElement(self: *const T, element: ?*IUIAutomationElement, first: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetFirstChildElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, first);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetLastChildElement(self: *const T, element: ?*IUIAutomationElement, last: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetLastChildElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, last);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetNextSiblingElement(self: *const T, element: ?*IUIAutomationElement, next: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetNextSiblingElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, next);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetPreviousSiblingElement(self: *const T, element: ?*IUIAutomationElement, previous: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetPreviousSiblingElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, previous);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_NormalizeElement(self: *const T, element: ?*IUIAutomationElement, normalized: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).NormalizeElement(@ptrCast(*const IUIAutomationTreeWalker, self), element, normalized);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetParentElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, parent: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetParentElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, parent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetFirstChildElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, first: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetFirstChildElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, first);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetLastChildElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, last: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetLastChildElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, last);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetNextSiblingElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, next: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetNextSiblingElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, next);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_GetPreviousSiblingElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, previous: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).GetPreviousSiblingElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, previous);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_NormalizeElementBuildCache(self: *const T, element: ?*IUIAutomationElement, cacheRequest: ?*IUIAutomationCacheRequest, normalized: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).NormalizeElementBuildCache(@ptrCast(*const IUIAutomationTreeWalker, self), element, cacheRequest, normalized);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTreeWalker_get_Condition(self: *const T, condition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTreeWalker.VTable, self.vtable).get_Condition(@ptrCast(*const IUIAutomationTreeWalker, self), condition);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationEventHandler_Value = @import("../zig.zig").Guid.initString("146c3c17-f12e-4e22-8c27-f894b9b79c69");
pub const IID_IUIAutomationEventHandler = &IID_IUIAutomationEventHandler_Value;
pub const IUIAutomationEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleAutomationEvent: fn(
self: *const IUIAutomationEventHandler,
sender: ?*IUIAutomationElement,
eventId: i32,
) 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 IUIAutomationEventHandler_HandleAutomationEvent(self: *const T, sender: ?*IUIAutomationElement, eventId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandler.VTable, self.vtable).HandleAutomationEvent(@ptrCast(*const IUIAutomationEventHandler, self), sender, eventId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationPropertyChangedEventHandler_Value = @import("../zig.zig").Guid.initString("40cd37d4-c756-4b0c-8c6f-bddfeeb13b50");
pub const IID_IUIAutomationPropertyChangedEventHandler = &IID_IUIAutomationPropertyChangedEventHandler_Value;
pub const IUIAutomationPropertyChangedEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandlePropertyChangedEvent: fn(
self: *const IUIAutomationPropertyChangedEventHandler,
sender: ?*IUIAutomationElement,
propertyId: i32,
newValue: VARIANT,
) 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 IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self: *const T, sender: ?*IUIAutomationElement, propertyId: i32, newValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationPropertyChangedEventHandler.VTable, self.vtable).HandlePropertyChangedEvent(@ptrCast(*const IUIAutomationPropertyChangedEventHandler, self), sender, propertyId, newValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationStructureChangedEventHandler_Value = @import("../zig.zig").Guid.initString("e81d1b4e-11c5-42f8-9754-e7036c79f054");
pub const IID_IUIAutomationStructureChangedEventHandler = &IID_IUIAutomationStructureChangedEventHandler_Value;
pub const IUIAutomationStructureChangedEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleStructureChangedEvent: fn(
self: *const IUIAutomationStructureChangedEventHandler,
sender: ?*IUIAutomationElement,
changeType: StructureChangeType,
runtimeId: ?*SAFEARRAY,
) 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 IUIAutomationStructureChangedEventHandler_HandleStructureChangedEvent(self: *const T, sender: ?*IUIAutomationElement, changeType: StructureChangeType, runtimeId: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStructureChangedEventHandler.VTable, self.vtable).HandleStructureChangedEvent(@ptrCast(*const IUIAutomationStructureChangedEventHandler, self), sender, changeType, runtimeId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationFocusChangedEventHandler_Value = @import("../zig.zig").Guid.initString("c270f6b5-5c69-4290-9745-7a7f97169468");
pub const IID_IUIAutomationFocusChangedEventHandler = &IID_IUIAutomationFocusChangedEventHandler_Value;
pub const IUIAutomationFocusChangedEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleFocusChangedEvent: fn(
self: *const IUIAutomationFocusChangedEventHandler,
sender: ?*IUIAutomationElement,
) 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 IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self: *const T, sender: ?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationFocusChangedEventHandler.VTable, self.vtable).HandleFocusChangedEvent(@ptrCast(*const IUIAutomationFocusChangedEventHandler, self), sender);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IUIAutomationTextEditTextChangedEventHandler_Value = @import("../zig.zig").Guid.initString("92faa680-e704-4156-931a-e32d5bb38f3f");
pub const IID_IUIAutomationTextEditTextChangedEventHandler = &IID_IUIAutomationTextEditTextChangedEventHandler_Value;
pub const IUIAutomationTextEditTextChangedEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleTextEditTextChangedEvent: fn(
self: *const IUIAutomationTextEditTextChangedEventHandler,
sender: ?*IUIAutomationElement,
textEditChangeType: TextEditChangeType,
eventStrings: ?*SAFEARRAY,
) 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 IUIAutomationTextEditTextChangedEventHandler_HandleTextEditTextChangedEvent(self: *const T, sender: ?*IUIAutomationElement, textEditChangeType: TextEditChangeType, eventStrings: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextEditTextChangedEventHandler.VTable, self.vtable).HandleTextEditTextChangedEvent(@ptrCast(*const IUIAutomationTextEditTextChangedEventHandler, self), sender, textEditChangeType, eventStrings);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IUIAutomationChangesEventHandler_Value = @import("../zig.zig").Guid.initString("58edca55-2c3e-4980-b1b9-56c17f27a2a0");
pub const IID_IUIAutomationChangesEventHandler = &IID_IUIAutomationChangesEventHandler_Value;
pub const IUIAutomationChangesEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleChangesEvent: fn(
self: *const IUIAutomationChangesEventHandler,
sender: ?*IUIAutomationElement,
uiaChanges: [*]UiaChangeInfo,
changesCount: i32,
) 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 IUIAutomationChangesEventHandler_HandleChangesEvent(self: *const T, sender: ?*IUIAutomationElement, uiaChanges: [*]UiaChangeInfo, changesCount: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationChangesEventHandler.VTable, self.vtable).HandleChangesEvent(@ptrCast(*const IUIAutomationChangesEventHandler, self), sender, uiaChanges, changesCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.16299'
const IID_IUIAutomationNotificationEventHandler_Value = @import("../zig.zig").Guid.initString("c7cb2637-e6c2-4d0c-85de-4948c02175c7");
pub const IID_IUIAutomationNotificationEventHandler = &IID_IUIAutomationNotificationEventHandler_Value;
pub const IUIAutomationNotificationEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleNotificationEvent: fn(
self: *const IUIAutomationNotificationEventHandler,
sender: ?*IUIAutomationElement,
notificationKind: NotificationKind,
notificationProcessing: NotificationProcessing,
displayString: ?BSTR,
activityId: ?BSTR,
) 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 IUIAutomationNotificationEventHandler_HandleNotificationEvent(self: *const T, sender: ?*IUIAutomationElement, notificationKind: NotificationKind, notificationProcessing: NotificationProcessing, displayString: ?BSTR, activityId: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationNotificationEventHandler.VTable, self.vtable).HandleNotificationEvent(@ptrCast(*const IUIAutomationNotificationEventHandler, self), sender, notificationKind, notificationProcessing, displayString, activityId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationInvokePattern_Value = @import("../zig.zig").Guid.initString("fb377fbe-8ea6-46d5-9c73-6499642d3059");
pub const IID_IUIAutomationInvokePattern = &IID_IUIAutomationInvokePattern_Value;
pub const IUIAutomationInvokePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Invoke: fn(
self: *const IUIAutomationInvokePattern,
) 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 IUIAutomationInvokePattern_Invoke(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationInvokePattern.VTable, self.vtable).Invoke(@ptrCast(*const IUIAutomationInvokePattern, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationDockPattern_Value = @import("../zig.zig").Guid.initString("fde5ef97-1464-48f6-90bf-43d0948e86ec");
pub const IID_IUIAutomationDockPattern = &IID_IUIAutomationDockPattern_Value;
pub const IUIAutomationDockPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetDockPosition: fn(
self: *const IUIAutomationDockPattern,
dockPos: DockPosition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDockPosition: fn(
self: *const IUIAutomationDockPattern,
retVal: ?*DockPosition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDockPosition: fn(
self: *const IUIAutomationDockPattern,
retVal: ?*DockPosition,
) 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 IUIAutomationDockPattern_SetDockPosition(self: *const T, dockPos: DockPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDockPattern.VTable, self.vtable).SetDockPosition(@ptrCast(*const IUIAutomationDockPattern, self), dockPos);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDockPattern_get_CurrentDockPosition(self: *const T, retVal: ?*DockPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDockPattern.VTable, self.vtable).get_CurrentDockPosition(@ptrCast(*const IUIAutomationDockPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDockPattern_get_CachedDockPosition(self: *const T, retVal: ?*DockPosition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDockPattern.VTable, self.vtable).get_CachedDockPosition(@ptrCast(*const IUIAutomationDockPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationExpandCollapsePattern_Value = @import("../zig.zig").Guid.initString("619be086-1f4e-4ee4-bafa-210128738730");
pub const IID_IUIAutomationExpandCollapsePattern = &IID_IUIAutomationExpandCollapsePattern_Value;
pub const IUIAutomationExpandCollapsePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Expand: fn(
self: *const IUIAutomationExpandCollapsePattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Collapse: fn(
self: *const IUIAutomationExpandCollapsePattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentExpandCollapseState: fn(
self: *const IUIAutomationExpandCollapsePattern,
retVal: ?*ExpandCollapseState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedExpandCollapseState: fn(
self: *const IUIAutomationExpandCollapsePattern,
retVal: ?*ExpandCollapseState,
) 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 IUIAutomationExpandCollapsePattern_Expand(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationExpandCollapsePattern.VTable, self.vtable).Expand(@ptrCast(*const IUIAutomationExpandCollapsePattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationExpandCollapsePattern_Collapse(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationExpandCollapsePattern.VTable, self.vtable).Collapse(@ptrCast(*const IUIAutomationExpandCollapsePattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationExpandCollapsePattern_get_CurrentExpandCollapseState(self: *const T, retVal: ?*ExpandCollapseState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationExpandCollapsePattern.VTable, self.vtable).get_CurrentExpandCollapseState(@ptrCast(*const IUIAutomationExpandCollapsePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationExpandCollapsePattern_get_CachedExpandCollapseState(self: *const T, retVal: ?*ExpandCollapseState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationExpandCollapsePattern.VTable, self.vtable).get_CachedExpandCollapseState(@ptrCast(*const IUIAutomationExpandCollapsePattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationGridPattern_Value = @import("../zig.zig").Guid.initString("414c3cdc-856b-4f5b-8538-3131c6302550");
pub const IID_IUIAutomationGridPattern = &IID_IUIAutomationGridPattern_Value;
pub const IUIAutomationGridPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItem: fn(
self: *const IUIAutomationGridPattern,
row: i32,
column: i32,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentRowCount: fn(
self: *const IUIAutomationGridPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentColumnCount: fn(
self: *const IUIAutomationGridPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedRowCount: fn(
self: *const IUIAutomationGridPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedColumnCount: fn(
self: *const IUIAutomationGridPattern,
retVal: ?*i32,
) 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 IUIAutomationGridPattern_GetItem(self: *const T, row: i32, column: i32, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridPattern.VTable, self.vtable).GetItem(@ptrCast(*const IUIAutomationGridPattern, self), row, column, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridPattern_get_CurrentRowCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridPattern.VTable, self.vtable).get_CurrentRowCount(@ptrCast(*const IUIAutomationGridPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridPattern_get_CurrentColumnCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridPattern.VTable, self.vtable).get_CurrentColumnCount(@ptrCast(*const IUIAutomationGridPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridPattern_get_CachedRowCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridPattern.VTable, self.vtable).get_CachedRowCount(@ptrCast(*const IUIAutomationGridPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridPattern_get_CachedColumnCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridPattern.VTable, self.vtable).get_CachedColumnCount(@ptrCast(*const IUIAutomationGridPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationGridItemPattern_Value = @import("../zig.zig").Guid.initString("78f8ef57-66c3-4e09-bd7c-e79b2004894d");
pub const IID_IUIAutomationGridItemPattern = &IID_IUIAutomationGridItemPattern_Value;
pub const IUIAutomationGridItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentContainingGrid: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentRow: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentColumn: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentRowSpan: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentColumnSpan: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedContainingGrid: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedRow: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedColumn: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedRowSpan: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedColumnSpan: fn(
self: *const IUIAutomationGridItemPattern,
retVal: ?*i32,
) 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 IUIAutomationGridItemPattern_get_CurrentContainingGrid(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CurrentContainingGrid(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CurrentRow(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CurrentRow(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CurrentColumn(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CurrentColumn(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CurrentRowSpan(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CurrentRowSpan(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CurrentColumnSpan(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CurrentColumnSpan(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CachedContainingGrid(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CachedContainingGrid(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CachedRow(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CachedRow(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CachedColumn(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CachedColumn(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CachedRowSpan(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CachedRowSpan(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationGridItemPattern_get_CachedColumnSpan(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationGridItemPattern.VTable, self.vtable).get_CachedColumnSpan(@ptrCast(*const IUIAutomationGridItemPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationMultipleViewPattern_Value = @import("../zig.zig").Guid.initString("8d253c91-1dc5-4bb5-b18f-ade16fa495e8");
pub const IID_IUIAutomationMultipleViewPattern = &IID_IUIAutomationMultipleViewPattern_Value;
pub const IUIAutomationMultipleViewPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetViewName: fn(
self: *const IUIAutomationMultipleViewPattern,
view: i32,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCurrentView: fn(
self: *const IUIAutomationMultipleViewPattern,
view: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCurrentView: fn(
self: *const IUIAutomationMultipleViewPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentSupportedViews: fn(
self: *const IUIAutomationMultipleViewPattern,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCurrentView: fn(
self: *const IUIAutomationMultipleViewPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedSupportedViews: fn(
self: *const IUIAutomationMultipleViewPattern,
retVal: ?*?*SAFEARRAY,
) 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 IUIAutomationMultipleViewPattern_GetViewName(self: *const T, view: i32, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).GetViewName(@ptrCast(*const IUIAutomationMultipleViewPattern, self), view, name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationMultipleViewPattern_SetCurrentView(self: *const T, view: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).SetCurrentView(@ptrCast(*const IUIAutomationMultipleViewPattern, self), view);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationMultipleViewPattern_get_CurrentCurrentView(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).get_CurrentCurrentView(@ptrCast(*const IUIAutomationMultipleViewPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationMultipleViewPattern_GetCurrentSupportedViews(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).GetCurrentSupportedViews(@ptrCast(*const IUIAutomationMultipleViewPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationMultipleViewPattern_get_CachedCurrentView(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).get_CachedCurrentView(@ptrCast(*const IUIAutomationMultipleViewPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationMultipleViewPattern_GetCachedSupportedViews(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationMultipleViewPattern.VTable, self.vtable).GetCachedSupportedViews(@ptrCast(*const IUIAutomationMultipleViewPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationObjectModelPattern_Value = @import("../zig.zig").Guid.initString("71c284b3-c14d-4d14-981e-19751b0d756d");
pub const IID_IUIAutomationObjectModelPattern = &IID_IUIAutomationObjectModelPattern_Value;
pub const IUIAutomationObjectModelPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetUnderlyingObjectModel: fn(
self: *const IUIAutomationObjectModelPattern,
retVal: ?*?*IUnknown,
) 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 IUIAutomationObjectModelPattern_GetUnderlyingObjectModel(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationObjectModelPattern.VTable, self.vtable).GetUnderlyingObjectModel(@ptrCast(*const IUIAutomationObjectModelPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationRangeValuePattern_Value = @import("../zig.zig").Guid.initString("59213f4f-7346-49e5-b120-80555987a148");
pub const IID_IUIAutomationRangeValuePattern = &IID_IUIAutomationRangeValuePattern_Value;
pub const IUIAutomationRangeValuePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetValue: fn(
self: *const IUIAutomationRangeValuePattern,
val: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentValue: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsReadOnly: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentMaximum: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentMinimum: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLargeChange: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentSmallChange: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedValue: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsReadOnly: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedMaximum: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedMinimum: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLargeChange: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedSmallChange: fn(
self: *const IUIAutomationRangeValuePattern,
retVal: ?*f64,
) 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 IUIAutomationRangeValuePattern_SetValue(self: *const T, val: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).SetValue(@ptrCast(*const IUIAutomationRangeValuePattern, self), val);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentValue(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentValue(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentIsReadOnly(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentIsReadOnly(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentMaximum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentMaximum(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentMinimum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentMinimum(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentLargeChange(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentLargeChange(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CurrentSmallChange(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CurrentSmallChange(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedValue(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedValue(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedIsReadOnly(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedIsReadOnly(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedMaximum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedMaximum(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedMinimum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedMinimum(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedLargeChange(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedLargeChange(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationRangeValuePattern_get_CachedSmallChange(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationRangeValuePattern.VTable, self.vtable).get_CachedSmallChange(@ptrCast(*const IUIAutomationRangeValuePattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationScrollPattern_Value = @import("../zig.zig").Guid.initString("88f4d42a-e881-459d-a77c-73bbbb7e02dc");
pub const IID_IUIAutomationScrollPattern = &IID_IUIAutomationScrollPattern_Value;
pub const IUIAutomationScrollPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Scroll: fn(
self: *const IUIAutomationScrollPattern,
horizontalAmount: ScrollAmount,
verticalAmount: ScrollAmount,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetScrollPercent: fn(
self: *const IUIAutomationScrollPattern,
horizontalPercent: f64,
verticalPercent: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHorizontalScrollPercent: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentVerticalScrollPercent: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHorizontalViewSize: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentVerticalViewSize: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHorizontallyScrollable: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentVerticallyScrollable: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHorizontalScrollPercent: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedVerticalScrollPercent: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHorizontalViewSize: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedVerticalViewSize: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHorizontallyScrollable: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedVerticallyScrollable: fn(
self: *const IUIAutomationScrollPattern,
retVal: ?*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 IUIAutomationScrollPattern_Scroll(self: *const T, horizontalAmount: ScrollAmount, verticalAmount: ScrollAmount) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).Scroll(@ptrCast(*const IUIAutomationScrollPattern, self), horizontalAmount, verticalAmount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_SetScrollPercent(self: *const T, horizontalPercent: f64, verticalPercent: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).SetScrollPercent(@ptrCast(*const IUIAutomationScrollPattern, self), horizontalPercent, verticalPercent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentHorizontalScrollPercent(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentHorizontalScrollPercent(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentVerticalScrollPercent(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentVerticalScrollPercent(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentHorizontalViewSize(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentHorizontalViewSize(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentVerticalViewSize(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentVerticalViewSize(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentHorizontallyScrollable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentHorizontallyScrollable(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CurrentVerticallyScrollable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CurrentVerticallyScrollable(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedHorizontalScrollPercent(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedHorizontalScrollPercent(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedVerticalScrollPercent(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedVerticalScrollPercent(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedHorizontalViewSize(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedHorizontalViewSize(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedVerticalViewSize(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedVerticalViewSize(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedHorizontallyScrollable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedHorizontallyScrollable(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationScrollPattern_get_CachedVerticallyScrollable(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollPattern.VTable, self.vtable).get_CachedVerticallyScrollable(@ptrCast(*const IUIAutomationScrollPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationScrollItemPattern_Value = @import("../zig.zig").Guid.initString("b488300f-d015-4f19-9c29-bb595e3645ef");
pub const IID_IUIAutomationScrollItemPattern = &IID_IUIAutomationScrollItemPattern_Value;
pub const IUIAutomationScrollItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ScrollIntoView: fn(
self: *const IUIAutomationScrollItemPattern,
) 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 IUIAutomationScrollItemPattern_ScrollIntoView(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationScrollItemPattern.VTable, self.vtable).ScrollIntoView(@ptrCast(*const IUIAutomationScrollItemPattern, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationSelectionPattern_Value = @import("../zig.zig").Guid.initString("5ed5202e-b2ac-47a6-b638-4b0bf140d78e");
pub const IID_IUIAutomationSelectionPattern = &IID_IUIAutomationSelectionPattern_Value;
pub const IUIAutomationSelectionPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCurrentSelection: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanSelectMultiple: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsSelectionRequired: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedSelection: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanSelectMultiple: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsSelectionRequired: fn(
self: *const IUIAutomationSelectionPattern,
retVal: ?*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 IUIAutomationSelectionPattern_GetCurrentSelection(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).GetCurrentSelection(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern_get_CurrentCanSelectMultiple(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).get_CurrentCanSelectMultiple(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern_get_CurrentIsSelectionRequired(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).get_CurrentIsSelectionRequired(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern_GetCachedSelection(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).GetCachedSelection(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern_get_CachedCanSelectMultiple(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).get_CachedCanSelectMultiple(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern_get_CachedIsSelectionRequired(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern.VTable, self.vtable).get_CachedIsSelectionRequired(@ptrCast(*const IUIAutomationSelectionPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.16299'
const IID_IUIAutomationSelectionPattern2_Value = @import("../zig.zig").Guid.initString("0532bfae-c011-4e32-a343-6d642d798555");
pub const IID_IUIAutomationSelectionPattern2 = &IID_IUIAutomationSelectionPattern2_Value;
pub const IUIAutomationSelectionPattern2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationSelectionPattern.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFirstSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLastSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCurrentSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentItemCount: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFirstSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLastSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCurrentSelectedItem: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedItemCount: fn(
self: *const IUIAutomationSelectionPattern2,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationSelectionPattern.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CurrentFirstSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CurrentFirstSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CurrentLastSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CurrentLastSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CurrentCurrentSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CurrentCurrentSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CurrentItemCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CurrentItemCount(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CachedFirstSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CachedFirstSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CachedLastSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CachedLastSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CachedCurrentSelectedItem(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CachedCurrentSelectedItem(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionPattern2_get_CachedItemCount(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionPattern2.VTable, self.vtable).get_CachedItemCount(@ptrCast(*const IUIAutomationSelectionPattern2, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationSelectionItemPattern_Value = @import("../zig.zig").Guid.initString("a8efa66a-0fda-421a-9194-38021f3578ea");
pub const IID_IUIAutomationSelectionItemPattern = &IID_IUIAutomationSelectionItemPattern_Value;
pub const IUIAutomationSelectionItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Select: fn(
self: *const IUIAutomationSelectionItemPattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddToSelection: fn(
self: *const IUIAutomationSelectionItemPattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFromSelection: fn(
self: *const IUIAutomationSelectionItemPattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsSelected: fn(
self: *const IUIAutomationSelectionItemPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentSelectionContainer: fn(
self: *const IUIAutomationSelectionItemPattern,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsSelected: fn(
self: *const IUIAutomationSelectionItemPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedSelectionContainer: fn(
self: *const IUIAutomationSelectionItemPattern,
retVal: ?*?*IUIAutomationElement,
) 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 IUIAutomationSelectionItemPattern_Select(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).Select(@ptrCast(*const IUIAutomationSelectionItemPattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_AddToSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).AddToSelection(@ptrCast(*const IUIAutomationSelectionItemPattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_RemoveFromSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).RemoveFromSelection(@ptrCast(*const IUIAutomationSelectionItemPattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_get_CurrentIsSelected(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).get_CurrentIsSelected(@ptrCast(*const IUIAutomationSelectionItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_get_CurrentSelectionContainer(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).get_CurrentSelectionContainer(@ptrCast(*const IUIAutomationSelectionItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_get_CachedIsSelected(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).get_CachedIsSelected(@ptrCast(*const IUIAutomationSelectionItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSelectionItemPattern_get_CachedSelectionContainer(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSelectionItemPattern.VTable, self.vtable).get_CachedSelectionContainer(@ptrCast(*const IUIAutomationSelectionItemPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationSynchronizedInputPattern_Value = @import("../zig.zig").Guid.initString("2233be0b-afb7-448b-9fda-3b378aa5eae1");
pub const IID_IUIAutomationSynchronizedInputPattern = &IID_IUIAutomationSynchronizedInputPattern_Value;
pub const IUIAutomationSynchronizedInputPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
StartListening: fn(
self: *const IUIAutomationSynchronizedInputPattern,
inputType: SynchronizedInputType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cancel: fn(
self: *const IUIAutomationSynchronizedInputPattern,
) 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 IUIAutomationSynchronizedInputPattern_StartListening(self: *const T, inputType: SynchronizedInputType) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSynchronizedInputPattern.VTable, self.vtable).StartListening(@ptrCast(*const IUIAutomationSynchronizedInputPattern, self), inputType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSynchronizedInputPattern_Cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSynchronizedInputPattern.VTable, self.vtable).Cancel(@ptrCast(*const IUIAutomationSynchronizedInputPattern, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTablePattern_Value = @import("../zig.zig").Guid.initString("620e691c-ea96-4710-a850-754b24ce2417");
pub const IID_IUIAutomationTablePattern = &IID_IUIAutomationTablePattern_Value;
pub const IUIAutomationTablePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCurrentRowHeaders: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentColumnHeaders: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentRowOrColumnMajor: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*RowOrColumnMajor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedRowHeaders: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedColumnHeaders: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedRowOrColumnMajor: fn(
self: *const IUIAutomationTablePattern,
retVal: ?*RowOrColumnMajor,
) 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 IUIAutomationTablePattern_GetCurrentRowHeaders(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).GetCurrentRowHeaders(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTablePattern_GetCurrentColumnHeaders(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).GetCurrentColumnHeaders(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTablePattern_get_CurrentRowOrColumnMajor(self: *const T, retVal: ?*RowOrColumnMajor) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).get_CurrentRowOrColumnMajor(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTablePattern_GetCachedRowHeaders(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).GetCachedRowHeaders(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTablePattern_GetCachedColumnHeaders(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).GetCachedColumnHeaders(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTablePattern_get_CachedRowOrColumnMajor(self: *const T, retVal: ?*RowOrColumnMajor) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTablePattern.VTable, self.vtable).get_CachedRowOrColumnMajor(@ptrCast(*const IUIAutomationTablePattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTableItemPattern_Value = @import("../zig.zig").Guid.initString("0b964eb3-ef2e-4464-9c79-61d61737a27e");
pub const IID_IUIAutomationTableItemPattern = &IID_IUIAutomationTableItemPattern_Value;
pub const IUIAutomationTableItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCurrentRowHeaderItems: fn(
self: *const IUIAutomationTableItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentColumnHeaderItems: fn(
self: *const IUIAutomationTableItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedRowHeaderItems: fn(
self: *const IUIAutomationTableItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedColumnHeaderItems: fn(
self: *const IUIAutomationTableItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) 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 IUIAutomationTableItemPattern_GetCurrentRowHeaderItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTableItemPattern.VTable, self.vtable).GetCurrentRowHeaderItems(@ptrCast(*const IUIAutomationTableItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTableItemPattern_GetCurrentColumnHeaderItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTableItemPattern.VTable, self.vtable).GetCurrentColumnHeaderItems(@ptrCast(*const IUIAutomationTableItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTableItemPattern_GetCachedRowHeaderItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTableItemPattern.VTable, self.vtable).GetCachedRowHeaderItems(@ptrCast(*const IUIAutomationTableItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTableItemPattern_GetCachedColumnHeaderItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTableItemPattern.VTable, self.vtable).GetCachedColumnHeaderItems(@ptrCast(*const IUIAutomationTableItemPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTogglePattern_Value = @import("../zig.zig").Guid.initString("94cf8058-9b8d-4ab9-8bfd-4cd0a33c8c70");
pub const IID_IUIAutomationTogglePattern = &IID_IUIAutomationTogglePattern_Value;
pub const IUIAutomationTogglePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Toggle: fn(
self: *const IUIAutomationTogglePattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentToggleState: fn(
self: *const IUIAutomationTogglePattern,
retVal: ?*ToggleState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedToggleState: fn(
self: *const IUIAutomationTogglePattern,
retVal: ?*ToggleState,
) 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 IUIAutomationTogglePattern_Toggle(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTogglePattern.VTable, self.vtable).Toggle(@ptrCast(*const IUIAutomationTogglePattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTogglePattern_get_CurrentToggleState(self: *const T, retVal: ?*ToggleState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTogglePattern.VTable, self.vtable).get_CurrentToggleState(@ptrCast(*const IUIAutomationTogglePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTogglePattern_get_CachedToggleState(self: *const T, retVal: ?*ToggleState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTogglePattern.VTable, self.vtable).get_CachedToggleState(@ptrCast(*const IUIAutomationTogglePattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTransformPattern_Value = @import("../zig.zig").Guid.initString("a9b55844-a55d-4ef0-926d-569c16ff89bb");
pub const IID_IUIAutomationTransformPattern = &IID_IUIAutomationTransformPattern_Value;
pub const IUIAutomationTransformPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Move: fn(
self: *const IUIAutomationTransformPattern,
x: f64,
y: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resize: fn(
self: *const IUIAutomationTransformPattern,
width: f64,
height: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rotate: fn(
self: *const IUIAutomationTransformPattern,
degrees: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanMove: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanResize: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanRotate: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanMove: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanResize: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanRotate: fn(
self: *const IUIAutomationTransformPattern,
retVal: ?*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 IUIAutomationTransformPattern_Move(self: *const T, x: f64, y: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).Move(@ptrCast(*const IUIAutomationTransformPattern, self), x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_Resize(self: *const T, width: f64, height: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).Resize(@ptrCast(*const IUIAutomationTransformPattern, self), width, height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_Rotate(self: *const T, degrees: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).Rotate(@ptrCast(*const IUIAutomationTransformPattern, self), degrees);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CurrentCanMove(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CurrentCanMove(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CurrentCanResize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CurrentCanResize(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CurrentCanRotate(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CurrentCanRotate(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CachedCanMove(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CachedCanMove(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CachedCanResize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CachedCanResize(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern_get_CachedCanRotate(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern.VTable, self.vtable).get_CachedCanRotate(@ptrCast(*const IUIAutomationTransformPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationValuePattern_Value = @import("../zig.zig").Guid.initString("a94cd8b1-0844-4cd6-9d2d-640537ab39e9");
pub const IID_IUIAutomationValuePattern = &IID_IUIAutomationValuePattern_Value;
pub const IUIAutomationValuePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetValue: fn(
self: *const IUIAutomationValuePattern,
val: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentValue: fn(
self: *const IUIAutomationValuePattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsReadOnly: fn(
self: *const IUIAutomationValuePattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedValue: fn(
self: *const IUIAutomationValuePattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsReadOnly: fn(
self: *const IUIAutomationValuePattern,
retVal: ?*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 IUIAutomationValuePattern_SetValue(self: *const T, val: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationValuePattern.VTable, self.vtable).SetValue(@ptrCast(*const IUIAutomationValuePattern, self), val);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationValuePattern_get_CurrentValue(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationValuePattern.VTable, self.vtable).get_CurrentValue(@ptrCast(*const IUIAutomationValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationValuePattern_get_CurrentIsReadOnly(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationValuePattern.VTable, self.vtable).get_CurrentIsReadOnly(@ptrCast(*const IUIAutomationValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationValuePattern_get_CachedValue(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationValuePattern.VTable, self.vtable).get_CachedValue(@ptrCast(*const IUIAutomationValuePattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationValuePattern_get_CachedIsReadOnly(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationValuePattern.VTable, self.vtable).get_CachedIsReadOnly(@ptrCast(*const IUIAutomationValuePattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationWindowPattern_Value = @import("../zig.zig").Guid.initString("0faef453-9208-43ef-bbb2-3b485177864f");
pub const IID_IUIAutomationWindowPattern = &IID_IUIAutomationWindowPattern_Value;
pub const IUIAutomationWindowPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Close: fn(
self: *const IUIAutomationWindowPattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WaitForInputIdle: fn(
self: *const IUIAutomationWindowPattern,
milliseconds: i32,
success: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWindowVisualState: fn(
self: *const IUIAutomationWindowPattern,
state: WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanMaximize: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanMinimize: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsModal: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsTopmost: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentWindowVisualState: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentWindowInteractionState: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*WindowInteractionState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanMaximize: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanMinimize: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsModal: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsTopmost: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedWindowVisualState: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedWindowInteractionState: fn(
self: *const IUIAutomationWindowPattern,
retVal: ?*WindowInteractionState,
) 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 IUIAutomationWindowPattern_Close(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).Close(@ptrCast(*const IUIAutomationWindowPattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_WaitForInputIdle(self: *const T, milliseconds: i32, success: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).WaitForInputIdle(@ptrCast(*const IUIAutomationWindowPattern, self), milliseconds, success);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_SetWindowVisualState(self: *const T, state: WindowVisualState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).SetWindowVisualState(@ptrCast(*const IUIAutomationWindowPattern, self), state);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentCanMaximize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentCanMaximize(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentCanMinimize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentCanMinimize(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentIsModal(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentIsModal(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentIsTopmost(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentIsTopmost(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentWindowVisualState(self: *const T, retVal: ?*WindowVisualState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentWindowVisualState(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CurrentWindowInteractionState(self: *const T, retVal: ?*WindowInteractionState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CurrentWindowInteractionState(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedCanMaximize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedCanMaximize(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedCanMinimize(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedCanMinimize(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedIsModal(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedIsModal(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedIsTopmost(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedIsTopmost(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedWindowVisualState(self: *const T, retVal: ?*WindowVisualState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedWindowVisualState(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationWindowPattern_get_CachedWindowInteractionState(self: *const T, retVal: ?*WindowInteractionState) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationWindowPattern.VTable, self.vtable).get_CachedWindowInteractionState(@ptrCast(*const IUIAutomationWindowPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTextRange_Value = @import("../zig.zig").Guid.initString("a543cc6a-f4ae-494b-8239-c814481187a8");
pub const IID_IUIAutomationTextRange = &IID_IUIAutomationTextRange_Value;
pub const IUIAutomationTextRange = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Clone: fn(
self: *const IUIAutomationTextRange,
clonedRange: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Compare: fn(
self: *const IUIAutomationTextRange,
range: ?*IUIAutomationTextRange,
areSame: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CompareEndpoints: fn(
self: *const IUIAutomationTextRange,
srcEndPoint: TextPatternRangeEndpoint,
range: ?*IUIAutomationTextRange,
targetEndPoint: TextPatternRangeEndpoint,
compValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExpandToEnclosingUnit: fn(
self: *const IUIAutomationTextRange,
textUnit: TextUnit,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAttribute: fn(
self: *const IUIAutomationTextRange,
attr: i32,
val: VARIANT,
backward: BOOL,
found: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindText: fn(
self: *const IUIAutomationTextRange,
text: ?BSTR,
backward: BOOL,
ignoreCase: BOOL,
found: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributeValue: fn(
self: *const IUIAutomationTextRange,
attr: i32,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBoundingRectangles: fn(
self: *const IUIAutomationTextRange,
boundingRects: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnclosingElement: fn(
self: *const IUIAutomationTextRange,
enclosingElement: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetText: fn(
self: *const IUIAutomationTextRange,
maxLength: i32,
text: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const IUIAutomationTextRange,
unit: TextUnit,
count: i32,
moved: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndpointByUnit: fn(
self: *const IUIAutomationTextRange,
endpoint: TextPatternRangeEndpoint,
unit: TextUnit,
count: i32,
moved: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndpointByRange: fn(
self: *const IUIAutomationTextRange,
srcEndPoint: TextPatternRangeEndpoint,
range: ?*IUIAutomationTextRange,
targetEndPoint: TextPatternRangeEndpoint,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Select: fn(
self: *const IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddToSelection: fn(
self: *const IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFromSelection: fn(
self: *const IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScrollIntoView: fn(
self: *const IUIAutomationTextRange,
alignToTop: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildren: fn(
self: *const IUIAutomationTextRange,
children: ?*?*IUIAutomationElementArray,
) 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 IUIAutomationTextRange_Clone(self: *const T, clonedRange: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).Clone(@ptrCast(*const IUIAutomationTextRange, self), clonedRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_Compare(self: *const T, range: ?*IUIAutomationTextRange, areSame: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).Compare(@ptrCast(*const IUIAutomationTextRange, self), range, areSame);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_CompareEndpoints(self: *const T, srcEndPoint: TextPatternRangeEndpoint, range: ?*IUIAutomationTextRange, targetEndPoint: TextPatternRangeEndpoint, compValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).CompareEndpoints(@ptrCast(*const IUIAutomationTextRange, self), srcEndPoint, range, targetEndPoint, compValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_ExpandToEnclosingUnit(self: *const T, textUnit: TextUnit) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).ExpandToEnclosingUnit(@ptrCast(*const IUIAutomationTextRange, self), textUnit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_FindAttribute(self: *const T, attr: i32, val: VARIANT, backward: BOOL, found: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).FindAttribute(@ptrCast(*const IUIAutomationTextRange, self), attr, val, backward, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_FindText(self: *const T, text: ?BSTR, backward: BOOL, ignoreCase: BOOL, found: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).FindText(@ptrCast(*const IUIAutomationTextRange, self), text, backward, ignoreCase, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_GetAttributeValue(self: *const T, attr: i32, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).GetAttributeValue(@ptrCast(*const IUIAutomationTextRange, self), attr, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_GetBoundingRectangles(self: *const T, boundingRects: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).GetBoundingRectangles(@ptrCast(*const IUIAutomationTextRange, self), boundingRects);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_GetEnclosingElement(self: *const T, enclosingElement: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).GetEnclosingElement(@ptrCast(*const IUIAutomationTextRange, self), enclosingElement);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_GetText(self: *const T, maxLength: i32, text: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).GetText(@ptrCast(*const IUIAutomationTextRange, self), maxLength, text);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_Move(self: *const T, unit: TextUnit, count: i32, moved: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).Move(@ptrCast(*const IUIAutomationTextRange, self), unit, count, moved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_MoveEndpointByUnit(self: *const T, endpoint: TextPatternRangeEndpoint, unit: TextUnit, count: i32, moved: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).MoveEndpointByUnit(@ptrCast(*const IUIAutomationTextRange, self), endpoint, unit, count, moved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_MoveEndpointByRange(self: *const T, srcEndPoint: TextPatternRangeEndpoint, range: ?*IUIAutomationTextRange, targetEndPoint: TextPatternRangeEndpoint) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).MoveEndpointByRange(@ptrCast(*const IUIAutomationTextRange, self), srcEndPoint, range, targetEndPoint);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_Select(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).Select(@ptrCast(*const IUIAutomationTextRange, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_AddToSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).AddToSelection(@ptrCast(*const IUIAutomationTextRange, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_RemoveFromSelection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).RemoveFromSelection(@ptrCast(*const IUIAutomationTextRange, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_ScrollIntoView(self: *const T, alignToTop: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).ScrollIntoView(@ptrCast(*const IUIAutomationTextRange, self), alignToTop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange_GetChildren(self: *const T, children: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange.VTable, self.vtable).GetChildren(@ptrCast(*const IUIAutomationTextRange, self), children);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IUIAutomationTextRange2_Value = @import("../zig.zig").Guid.initString("bb9b40e0-5e04-46bd-9be0-4b601b9afad4");
pub const IID_IUIAutomationTextRange2 = &IID_IUIAutomationTextRange2_Value;
pub const IUIAutomationTextRange2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationTextRange.VTable,
ShowContextMenu: fn(
self: *const IUIAutomationTextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationTextRange.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange2_ShowContextMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange2.VTable, self.vtable).ShowContextMenu(@ptrCast(*const IUIAutomationTextRange2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IUIAutomationTextRange3_Value = @import("../zig.zig").Guid.initString("6a315d69-5512-4c2e-85f0-53fce6dd4bc2");
pub const IID_IUIAutomationTextRange3 = &IID_IUIAutomationTextRange3_Value;
pub const IUIAutomationTextRange3 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationTextRange2.VTable,
GetEnclosingElementBuildCache: fn(
self: *const IUIAutomationTextRange3,
cacheRequest: ?*IUIAutomationCacheRequest,
enclosingElement: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChildrenBuildCache: fn(
self: *const IUIAutomationTextRange3,
cacheRequest: ?*IUIAutomationCacheRequest,
children: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributeValues: fn(
self: *const IUIAutomationTextRange3,
attributeIds: [*]const i32,
attributeIdCount: i32,
attributeValues: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationTextRange2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange3_GetEnclosingElementBuildCache(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, enclosingElement: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange3.VTable, self.vtable).GetEnclosingElementBuildCache(@ptrCast(*const IUIAutomationTextRange3, self), cacheRequest, enclosingElement);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange3_GetChildrenBuildCache(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, children: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange3.VTable, self.vtable).GetChildrenBuildCache(@ptrCast(*const IUIAutomationTextRange3, self), cacheRequest, children);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRange3_GetAttributeValues(self: *const T, attributeIds: [*]const i32, attributeIdCount: i32, attributeValues: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRange3.VTable, self.vtable).GetAttributeValues(@ptrCast(*const IUIAutomationTextRange3, self), attributeIds, attributeIdCount, attributeValues);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTextRangeArray_Value = @import("../zig.zig").Guid.initString("ce4ae76a-e717-4c98-81ea-47371d028eb6");
pub const IID_IUIAutomationTextRangeArray = &IID_IUIAutomationTextRangeArray_Value;
pub const IUIAutomationTextRangeArray = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Length: fn(
self: *const IUIAutomationTextRangeArray,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetElement: fn(
self: *const IUIAutomationTextRangeArray,
index: i32,
element: ?*?*IUIAutomationTextRange,
) 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 IUIAutomationTextRangeArray_get_Length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRangeArray.VTable, self.vtable).get_Length(@ptrCast(*const IUIAutomationTextRangeArray, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextRangeArray_GetElement(self: *const T, index: i32, element: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextRangeArray.VTable, self.vtable).GetElement(@ptrCast(*const IUIAutomationTextRangeArray, self), index, element);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationTextPattern_Value = @import("../zig.zig").Guid.initString("32eba289-3583-42c9-9c59-3b6d9a1e9b6a");
pub const IID_IUIAutomationTextPattern = &IID_IUIAutomationTextPattern_Value;
pub const IUIAutomationTextPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RangeFromPoint: fn(
self: *const IUIAutomationTextPattern,
pt: POINT,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RangeFromChild: fn(
self: *const IUIAutomationTextPattern,
child: ?*IUIAutomationElement,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelection: fn(
self: *const IUIAutomationTextPattern,
ranges: ?*?*IUIAutomationTextRangeArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVisibleRanges: fn(
self: *const IUIAutomationTextPattern,
ranges: ?*?*IUIAutomationTextRangeArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DocumentRange: fn(
self: *const IUIAutomationTextPattern,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SupportedTextSelection: fn(
self: *const IUIAutomationTextPattern,
supportedTextSelection: ?*SupportedTextSelection,
) 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 IUIAutomationTextPattern_RangeFromPoint(self: *const T, pt: POINT, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).RangeFromPoint(@ptrCast(*const IUIAutomationTextPattern, self), pt, range);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern_RangeFromChild(self: *const T, child: ?*IUIAutomationElement, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).RangeFromChild(@ptrCast(*const IUIAutomationTextPattern, self), child, range);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern_GetSelection(self: *const T, ranges: ?*?*IUIAutomationTextRangeArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).GetSelection(@ptrCast(*const IUIAutomationTextPattern, self), ranges);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern_GetVisibleRanges(self: *const T, ranges: ?*?*IUIAutomationTextRangeArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).GetVisibleRanges(@ptrCast(*const IUIAutomationTextPattern, self), ranges);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern_get_DocumentRange(self: *const T, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).get_DocumentRange(@ptrCast(*const IUIAutomationTextPattern, self), range);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern_get_SupportedTextSelection(self: *const T, supportedTextSelection: ?*SupportedTextSelection) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern.VTable, self.vtable).get_SupportedTextSelection(@ptrCast(*const IUIAutomationTextPattern, self), supportedTextSelection);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationTextPattern2_Value = @import("../zig.zig").Guid.initString("506a921a-fcc9-409f-b23b-37eb74106872");
pub const IID_IUIAutomationTextPattern2 = &IID_IUIAutomationTextPattern2_Value;
pub const IUIAutomationTextPattern2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationTextPattern.VTable,
RangeFromAnnotation: fn(
self: *const IUIAutomationTextPattern2,
annotation: ?*IUIAutomationElement,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCaretRange: fn(
self: *const IUIAutomationTextPattern2,
isActive: ?*BOOL,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationTextPattern.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern2_RangeFromAnnotation(self: *const T, annotation: ?*IUIAutomationElement, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern2.VTable, self.vtable).RangeFromAnnotation(@ptrCast(*const IUIAutomationTextPattern2, self), annotation, range);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextPattern2_GetCaretRange(self: *const T, isActive: ?*BOOL, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextPattern2.VTable, self.vtable).GetCaretRange(@ptrCast(*const IUIAutomationTextPattern2, self), isActive, range);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IUIAutomationTextEditPattern_Value = @import("../zig.zig").Guid.initString("17e21576-996c-4870-99d9-bff323380c06");
pub const IID_IUIAutomationTextEditPattern = &IID_IUIAutomationTextEditPattern_Value;
pub const IUIAutomationTextEditPattern = extern struct {
pub const VTable = extern struct {
base: IUIAutomationTextPattern.VTable,
GetActiveComposition: fn(
self: *const IUIAutomationTextEditPattern,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConversionTarget: fn(
self: *const IUIAutomationTextEditPattern,
range: ?*?*IUIAutomationTextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationTextPattern.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextEditPattern_GetActiveComposition(self: *const T, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextEditPattern.VTable, self.vtable).GetActiveComposition(@ptrCast(*const IUIAutomationTextEditPattern, self), range);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextEditPattern_GetConversionTarget(self: *const T, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextEditPattern.VTable, self.vtable).GetConversionTarget(@ptrCast(*const IUIAutomationTextEditPattern, self), range);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IUIAutomationCustomNavigationPattern_Value = @import("../zig.zig").Guid.initString("01ea217a-1766-47ed-a6cc-acf492854b1f");
pub const IID_IUIAutomationCustomNavigationPattern = &IID_IUIAutomationCustomNavigationPattern_Value;
pub const IUIAutomationCustomNavigationPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Navigate: fn(
self: *const IUIAutomationCustomNavigationPattern,
direction: NavigateDirection,
pRetVal: ?*?*IUIAutomationElement,
) 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 IUIAutomationCustomNavigationPattern_Navigate(self: *const T, direction: NavigateDirection, pRetVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationCustomNavigationPattern.VTable, self.vtable).Navigate(@ptrCast(*const IUIAutomationCustomNavigationPattern, self), direction, pRetVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17763'
const IID_IUIAutomationActiveTextPositionChangedEventHandler_Value = @import("../zig.zig").Guid.initString("f97933b0-8dae-4496-8997-5ba015fe0d82");
pub const IID_IUIAutomationActiveTextPositionChangedEventHandler = &IID_IUIAutomationActiveTextPositionChangedEventHandler_Value;
pub const IUIAutomationActiveTextPositionChangedEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleActiveTextPositionChangedEvent: fn(
self: *const IUIAutomationActiveTextPositionChangedEventHandler,
sender: ?*IUIAutomationElement,
range: ?*IUIAutomationTextRange,
) 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 IUIAutomationActiveTextPositionChangedEventHandler_HandleActiveTextPositionChangedEvent(self: *const T, sender: ?*IUIAutomationElement, range: ?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationActiveTextPositionChangedEventHandler.VTable, self.vtable).HandleActiveTextPositionChangedEvent(@ptrCast(*const IUIAutomationActiveTextPositionChangedEventHandler, self), sender, range);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationLegacyIAccessiblePattern_Value = @import("../zig.zig").Guid.initString("828055ad-355b-4435-86d5-3b51c14a9b1b");
pub const IID_IUIAutomationLegacyIAccessiblePattern = &IID_IUIAutomationLegacyIAccessiblePattern_Value;
pub const IUIAutomationLegacyIAccessiblePattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Select: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
flagsSelect: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DoDefaultAction: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetValue: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
szValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentChildId: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentName: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentValue: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDescription: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentRole: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pdwRole: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentState: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pdwState: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHelp: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszHelp: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentKeyboardShortcut: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszKeyboardShortcut: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentSelection: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pvarSelectedChildren: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDefaultAction: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszDefaultAction: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedChildId: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedName: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedValue: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDescription: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedRole: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pdwRole: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedState: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pdwState: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHelp: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszHelp: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedKeyboardShortcut: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszKeyboardShortcut: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedSelection: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pvarSelectedChildren: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDefaultAction: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
pszDefaultAction: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIAccessible: fn(
self: *const IUIAutomationLegacyIAccessiblePattern,
ppAccessible: ?*?*IAccessible,
) 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 IUIAutomationLegacyIAccessiblePattern_Select(self: *const T, flagsSelect: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).Select(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), flagsSelect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_DoDefaultAction(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).DoDefaultAction(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_SetValue(self: *const T, szValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).SetValue(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), szValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentChildId(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentChildId(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentName(self: *const T, pszName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentName(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentValue(self: *const T, pszValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentValue(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentDescription(self: *const T, pszDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentDescription(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentRole(self: *const T, pdwRole: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentRole(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pdwRole);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentState(self: *const T, pdwState: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentState(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pdwState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentHelp(self: *const T, pszHelp: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentHelp(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszHelp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentKeyboardShortcut(self: *const T, pszKeyboardShortcut: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentKeyboardShortcut(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszKeyboardShortcut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_GetCurrentSelection(self: *const T, pvarSelectedChildren: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).GetCurrentSelection(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pvarSelectedChildren);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CurrentDefaultAction(self: *const T, pszDefaultAction: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CurrentDefaultAction(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszDefaultAction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedChildId(self: *const T, pRetVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedChildId(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pRetVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedName(self: *const T, pszName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedName(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedValue(self: *const T, pszValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedValue(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedDescription(self: *const T, pszDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedDescription(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedRole(self: *const T, pdwRole: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedRole(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pdwRole);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedState(self: *const T, pdwState: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedState(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pdwState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedHelp(self: *const T, pszHelp: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedHelp(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszHelp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedKeyboardShortcut(self: *const T, pszKeyboardShortcut: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedKeyboardShortcut(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszKeyboardShortcut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_GetCachedSelection(self: *const T, pvarSelectedChildren: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).GetCachedSelection(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pvarSelectedChildren);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_get_CachedDefaultAction(self: *const T, pszDefaultAction: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).get_CachedDefaultAction(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), pszDefaultAction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationLegacyIAccessiblePattern_GetIAccessible(self: *const T, ppAccessible: ?*?*IAccessible) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationLegacyIAccessiblePattern.VTable, self.vtable).GetIAccessible(@ptrCast(*const IUIAutomationLegacyIAccessiblePattern, self), ppAccessible);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationItemContainerPattern_Value = @import("../zig.zig").Guid.initString("c690fdb2-27a8-423c-812d-429773c9084e");
pub const IID_IUIAutomationItemContainerPattern = &IID_IUIAutomationItemContainerPattern_Value;
pub const IUIAutomationItemContainerPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
FindItemByProperty: fn(
self: *const IUIAutomationItemContainerPattern,
pStartAfter: ?*IUIAutomationElement,
propertyId: i32,
value: VARIANT,
pFound: ?*?*IUIAutomationElement,
) 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 IUIAutomationItemContainerPattern_FindItemByProperty(self: *const T, pStartAfter: ?*IUIAutomationElement, propertyId: i32, value: VARIANT, pFound: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationItemContainerPattern.VTable, self.vtable).FindItemByProperty(@ptrCast(*const IUIAutomationItemContainerPattern, self), pStartAfter, propertyId, value, pFound);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationVirtualizedItemPattern_Value = @import("../zig.zig").Guid.initString("6ba3d7a6-04cf-4f11-8793-a8d1cde9969f");
pub const IID_IUIAutomationVirtualizedItemPattern = &IID_IUIAutomationVirtualizedItemPattern_Value;
pub const IUIAutomationVirtualizedItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Realize: fn(
self: *const IUIAutomationVirtualizedItemPattern,
) 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 IUIAutomationVirtualizedItemPattern_Realize(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationVirtualizedItemPattern.VTable, self.vtable).Realize(@ptrCast(*const IUIAutomationVirtualizedItemPattern, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationAnnotationPattern_Value = @import("../zig.zig").Guid.initString("9a175b21-339e-41b1-8e8b-623f6b681098");
pub const IID_IUIAutomationAnnotationPattern = &IID_IUIAutomationAnnotationPattern_Value;
pub const IUIAutomationAnnotationPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAnnotationTypeId: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAnnotationTypeName: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAuthor: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDateTime: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentTarget: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAnnotationTypeId: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAnnotationTypeName: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAuthor: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDateTime: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedTarget: fn(
self: *const IUIAutomationAnnotationPattern,
retVal: ?*?*IUIAutomationElement,
) 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 IUIAutomationAnnotationPattern_get_CurrentAnnotationTypeId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CurrentAnnotationTypeId(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CurrentAnnotationTypeName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CurrentAnnotationTypeName(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CurrentAuthor(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CurrentAuthor(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CurrentDateTime(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CurrentDateTime(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CurrentTarget(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CurrentTarget(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CachedAnnotationTypeId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CachedAnnotationTypeId(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CachedAnnotationTypeName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CachedAnnotationTypeName(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CachedAuthor(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CachedAuthor(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CachedDateTime(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CachedDateTime(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationAnnotationPattern_get_CachedTarget(self: *const T, retVal: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationAnnotationPattern.VTable, self.vtable).get_CachedTarget(@ptrCast(*const IUIAutomationAnnotationPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationStylesPattern_Value = @import("../zig.zig").Guid.initString("85b5f0a2-bd79-484a-ad2b-388c9838d5fb");
pub const IID_IUIAutomationStylesPattern = &IID_IUIAutomationStylesPattern_Value;
pub const IUIAutomationStylesPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentStyleId: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentStyleName: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFillColor: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFillPatternStyle: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentShape: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFillPatternColor: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentExtendedProperties: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentExtendedPropertiesAsArray: fn(
self: *const IUIAutomationStylesPattern,
propertyArray: ?*?*ExtendedProperty,
propertyCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedStyleId: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedStyleName: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFillColor: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFillPatternStyle: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedShape: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFillPatternColor: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedExtendedProperties: fn(
self: *const IUIAutomationStylesPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedExtendedPropertiesAsArray: fn(
self: *const IUIAutomationStylesPattern,
propertyArray: ?*?*ExtendedProperty,
propertyCount: ?*i32,
) 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 IUIAutomationStylesPattern_get_CurrentStyleId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentStyleId(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentStyleName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentStyleName(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentFillColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentFillColor(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentFillPatternStyle(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentFillPatternStyle(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentShape(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentShape(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentFillPatternColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentFillPatternColor(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CurrentExtendedProperties(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CurrentExtendedProperties(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_GetCurrentExtendedPropertiesAsArray(self: *const T, propertyArray: ?*?*ExtendedProperty, propertyCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).GetCurrentExtendedPropertiesAsArray(@ptrCast(*const IUIAutomationStylesPattern, self), propertyArray, propertyCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedStyleId(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedStyleId(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedStyleName(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedStyleName(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedFillColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedFillColor(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedFillPatternStyle(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedFillPatternStyle(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedShape(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedShape(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedFillPatternColor(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedFillPatternColor(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_get_CachedExtendedProperties(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).get_CachedExtendedProperties(@ptrCast(*const IUIAutomationStylesPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationStylesPattern_GetCachedExtendedPropertiesAsArray(self: *const T, propertyArray: ?*?*ExtendedProperty, propertyCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationStylesPattern.VTable, self.vtable).GetCachedExtendedPropertiesAsArray(@ptrCast(*const IUIAutomationStylesPattern, self), propertyArray, propertyCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationSpreadsheetPattern_Value = @import("../zig.zig").Guid.initString("7517a7c8-faae-4de9-9f08-29b91e8595c1");
pub const IID_IUIAutomationSpreadsheetPattern = &IID_IUIAutomationSpreadsheetPattern_Value;
pub const IUIAutomationSpreadsheetPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetItemByName: fn(
self: *const IUIAutomationSpreadsheetPattern,
name: ?BSTR,
element: ?*?*IUIAutomationElement,
) 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 IUIAutomationSpreadsheetPattern_GetItemByName(self: *const T, name: ?BSTR, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetPattern.VTable, self.vtable).GetItemByName(@ptrCast(*const IUIAutomationSpreadsheetPattern, self), name, element);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationSpreadsheetItemPattern_Value = @import("../zig.zig").Guid.initString("7d4fb86c-8d34-40e1-8e83-62c15204e335");
pub const IID_IUIAutomationSpreadsheetItemPattern = &IID_IUIAutomationSpreadsheetItemPattern_Value;
pub const IUIAutomationSpreadsheetItemPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFormula: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentAnnotationObjects: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentAnnotationTypes: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFormula: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedAnnotationObjects: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedAnnotationTypes: fn(
self: *const IUIAutomationSpreadsheetItemPattern,
retVal: ?*?*SAFEARRAY,
) 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 IUIAutomationSpreadsheetItemPattern_get_CurrentFormula(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).get_CurrentFormula(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSpreadsheetItemPattern_GetCurrentAnnotationObjects(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).GetCurrentAnnotationObjects(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSpreadsheetItemPattern_GetCurrentAnnotationTypes(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).GetCurrentAnnotationTypes(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSpreadsheetItemPattern_get_CachedFormula(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).get_CachedFormula(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSpreadsheetItemPattern_GetCachedAnnotationObjects(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).GetCachedAnnotationObjects(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationSpreadsheetItemPattern_GetCachedAnnotationTypes(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationSpreadsheetItemPattern.VTable, self.vtable).GetCachedAnnotationTypes(@ptrCast(*const IUIAutomationSpreadsheetItemPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationTransformPattern2_Value = @import("../zig.zig").Guid.initString("6d74d017-6ecb-4381-b38b-3c17a48ff1c2");
pub const IID_IUIAutomationTransformPattern2 = &IID_IUIAutomationTransformPattern2_Value;
pub const IUIAutomationTransformPattern2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationTransformPattern.VTable,
Zoom: fn(
self: *const IUIAutomationTransformPattern2,
zoomValue: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ZoomByUnit: fn(
self: *const IUIAutomationTransformPattern2,
zoomUnit: ZoomUnit,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentCanZoom: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedCanZoom: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentZoomLevel: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedZoomLevel: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentZoomMinimum: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedZoomMinimum: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentZoomMaximum: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedZoomMaximum: fn(
self: *const IUIAutomationTransformPattern2,
retVal: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationTransformPattern.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_Zoom(self: *const T, zoomValue: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).Zoom(@ptrCast(*const IUIAutomationTransformPattern2, self), zoomValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_ZoomByUnit(self: *const T, zoomUnit: ZoomUnit) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).ZoomByUnit(@ptrCast(*const IUIAutomationTransformPattern2, self), zoomUnit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CurrentCanZoom(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CurrentCanZoom(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CachedCanZoom(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CachedCanZoom(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CurrentZoomLevel(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CurrentZoomLevel(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CachedZoomLevel(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CachedZoomLevel(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CurrentZoomMinimum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CurrentZoomMinimum(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CachedZoomMinimum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CachedZoomMinimum(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CurrentZoomMaximum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CurrentZoomMaximum(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTransformPattern2_get_CachedZoomMaximum(self: *const T, retVal: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTransformPattern2.VTable, self.vtable).get_CachedZoomMaximum(@ptrCast(*const IUIAutomationTransformPattern2, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationTextChildPattern_Value = @import("../zig.zig").Guid.initString("6552b038-ae05-40c8-abfd-aa08352aab86");
pub const IID_IUIAutomationTextChildPattern = &IID_IUIAutomationTextChildPattern_Value;
pub const IUIAutomationTextChildPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TextContainer: fn(
self: *const IUIAutomationTextChildPattern,
container: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TextRange: fn(
self: *const IUIAutomationTextChildPattern,
range: ?*?*IUIAutomationTextRange,
) 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 IUIAutomationTextChildPattern_get_TextContainer(self: *const T, container: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextChildPattern.VTable, self.vtable).get_TextContainer(@ptrCast(*const IUIAutomationTextChildPattern, self), container);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationTextChildPattern_get_TextRange(self: *const T, range: ?*?*IUIAutomationTextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationTextChildPattern.VTable, self.vtable).get_TextRange(@ptrCast(*const IUIAutomationTextChildPattern, self), range);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationDragPattern_Value = @import("../zig.zig").Guid.initString("1dc7b570-1f54-4bad-bcda-d36a722fb7bd");
pub const IID_IUIAutomationDragPattern = &IID_IUIAutomationDragPattern_Value;
pub const IUIAutomationDragPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsGrabbed: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsGrabbed: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDropEffect: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDropEffect: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDropEffects: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDropEffects: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentGrabbedItems: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCachedGrabbedItems: fn(
self: *const IUIAutomationDragPattern,
retVal: ?*?*IUIAutomationElementArray,
) 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 IUIAutomationDragPattern_get_CurrentIsGrabbed(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CurrentIsGrabbed(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_get_CachedIsGrabbed(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CachedIsGrabbed(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_get_CurrentDropEffect(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CurrentDropEffect(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_get_CachedDropEffect(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CachedDropEffect(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_get_CurrentDropEffects(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CurrentDropEffects(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_get_CachedDropEffects(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).get_CachedDropEffects(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_GetCurrentGrabbedItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).GetCurrentGrabbedItems(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDragPattern_GetCachedGrabbedItems(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDragPattern.VTable, self.vtable).GetCachedGrabbedItems(@ptrCast(*const IUIAutomationDragPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationDropTargetPattern_Value = @import("../zig.zig").Guid.initString("69a095f7-eee4-430e-a46b-fb73b1ae39a5");
pub const IID_IUIAutomationDropTargetPattern = &IID_IUIAutomationDropTargetPattern_Value;
pub const IUIAutomationDropTargetPattern = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDropTargetEffect: fn(
self: *const IUIAutomationDropTargetPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDropTargetEffect: fn(
self: *const IUIAutomationDropTargetPattern,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentDropTargetEffects: fn(
self: *const IUIAutomationDropTargetPattern,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedDropTargetEffects: fn(
self: *const IUIAutomationDropTargetPattern,
retVal: ?*?*SAFEARRAY,
) 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 IUIAutomationDropTargetPattern_get_CurrentDropTargetEffect(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDropTargetPattern.VTable, self.vtable).get_CurrentDropTargetEffect(@ptrCast(*const IUIAutomationDropTargetPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDropTargetPattern_get_CachedDropTargetEffect(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDropTargetPattern.VTable, self.vtable).get_CachedDropTargetEffect(@ptrCast(*const IUIAutomationDropTargetPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDropTargetPattern_get_CurrentDropTargetEffects(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDropTargetPattern.VTable, self.vtable).get_CurrentDropTargetEffects(@ptrCast(*const IUIAutomationDropTargetPattern, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationDropTargetPattern_get_CachedDropTargetEffects(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationDropTargetPattern.VTable, self.vtable).get_CachedDropTargetEffects(@ptrCast(*const IUIAutomationDropTargetPattern, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomationElement2_Value = @import("../zig.zig").Guid.initString("6749c683-f70d-4487-a698-5f79d55290d6");
pub const IID_IUIAutomationElement2 = &IID_IUIAutomationElement2_Value;
pub const IUIAutomationElement2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentOptimizeForVisualContent: fn(
self: *const IUIAutomationElement2,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedOptimizeForVisualContent: fn(
self: *const IUIAutomationElement2,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLiveSetting: fn(
self: *const IUIAutomationElement2,
retVal: ?*LiveSetting,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLiveSetting: fn(
self: *const IUIAutomationElement2,
retVal: ?*LiveSetting,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFlowsFrom: fn(
self: *const IUIAutomationElement2,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFlowsFrom: fn(
self: *const IUIAutomationElement2,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CurrentOptimizeForVisualContent(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CurrentOptimizeForVisualContent(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CachedOptimizeForVisualContent(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CachedOptimizeForVisualContent(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CurrentLiveSetting(self: *const T, retVal: ?*LiveSetting) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CurrentLiveSetting(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CachedLiveSetting(self: *const T, retVal: ?*LiveSetting) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CachedLiveSetting(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CurrentFlowsFrom(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CurrentFlowsFrom(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement2_get_CachedFlowsFrom(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement2.VTable, self.vtable).get_CachedFlowsFrom(@ptrCast(*const IUIAutomationElement2, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IUIAutomationElement3_Value = @import("../zig.zig").Guid.initString("8471df34-aee0-4a01-a7de-7db9af12c296");
pub const IID_IUIAutomationElement3 = &IID_IUIAutomationElement3_Value;
pub const IUIAutomationElement3 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement2.VTable,
ShowContextMenu: fn(
self: *const IUIAutomationElement3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsPeripheral: fn(
self: *const IUIAutomationElement3,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsPeripheral: fn(
self: *const IUIAutomationElement3,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement3_ShowContextMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement3.VTable, self.vtable).ShowContextMenu(@ptrCast(*const IUIAutomationElement3, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement3_get_CurrentIsPeripheral(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement3.VTable, self.vtable).get_CurrentIsPeripheral(@ptrCast(*const IUIAutomationElement3, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement3_get_CachedIsPeripheral(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement3.VTable, self.vtable).get_CachedIsPeripheral(@ptrCast(*const IUIAutomationElement3, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IUIAutomationElement4_Value = @import("../zig.zig").Guid.initString("3b6e233c-52fb-4063-a4c9-77c075c2a06b");
pub const IID_IUIAutomationElement4 = &IID_IUIAutomationElement4_Value;
pub const IUIAutomationElement4 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement3.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentPositionInSet: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentSizeOfSet: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLevel: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAnnotationTypes: fn(
self: *const IUIAutomationElement4,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentAnnotationObjects: fn(
self: *const IUIAutomationElement4,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedPositionInSet: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedSizeOfSet: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLevel: fn(
self: *const IUIAutomationElement4,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAnnotationTypes: fn(
self: *const IUIAutomationElement4,
retVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedAnnotationObjects: fn(
self: *const IUIAutomationElement4,
retVal: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CurrentPositionInSet(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CurrentPositionInSet(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CurrentSizeOfSet(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CurrentSizeOfSet(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CurrentLevel(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CurrentLevel(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CurrentAnnotationTypes(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CurrentAnnotationTypes(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CurrentAnnotationObjects(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CurrentAnnotationObjects(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CachedPositionInSet(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CachedPositionInSet(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CachedSizeOfSet(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CachedSizeOfSet(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CachedLevel(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CachedLevel(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CachedAnnotationTypes(self: *const T, retVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CachedAnnotationTypes(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement4_get_CachedAnnotationObjects(self: *const T, retVal: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement4.VTable, self.vtable).get_CachedAnnotationObjects(@ptrCast(*const IUIAutomationElement4, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IUIAutomationElement5_Value = @import("../zig.zig").Guid.initString("98141c1d-0d0e-4175-bbe2-6bff455842a7");
pub const IID_IUIAutomationElement5 = &IID_IUIAutomationElement5_Value;
pub const IUIAutomationElement5 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement4.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLandmarkType: fn(
self: *const IUIAutomationElement5,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentLocalizedLandmarkType: fn(
self: *const IUIAutomationElement5,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLandmarkType: fn(
self: *const IUIAutomationElement5,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedLocalizedLandmarkType: fn(
self: *const IUIAutomationElement5,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement5_get_CurrentLandmarkType(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement5.VTable, self.vtable).get_CurrentLandmarkType(@ptrCast(*const IUIAutomationElement5, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement5_get_CurrentLocalizedLandmarkType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement5.VTable, self.vtable).get_CurrentLocalizedLandmarkType(@ptrCast(*const IUIAutomationElement5, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement5_get_CachedLandmarkType(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement5.VTable, self.vtable).get_CachedLandmarkType(@ptrCast(*const IUIAutomationElement5, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement5_get_CachedLocalizedLandmarkType(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement5.VTable, self.vtable).get_CachedLocalizedLandmarkType(@ptrCast(*const IUIAutomationElement5, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IUIAutomationElement6_Value = @import("../zig.zig").Guid.initString("4780d450-8bca-4977-afa5-a4a517f555e3");
pub const IID_IUIAutomationElement6 = &IID_IUIAutomationElement6_Value;
pub const IUIAutomationElement6 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement5.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentFullDescription: fn(
self: *const IUIAutomationElement6,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedFullDescription: fn(
self: *const IUIAutomationElement6,
retVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement6_get_CurrentFullDescription(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement6.VTable, self.vtable).get_CurrentFullDescription(@ptrCast(*const IUIAutomationElement6, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement6_get_CachedFullDescription(self: *const T, retVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement6.VTable, self.vtable).get_CachedFullDescription(@ptrCast(*const IUIAutomationElement6, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.15063'
const IID_IUIAutomationElement7_Value = @import("../zig.zig").Guid.initString("204e8572-cfc3-4c11-b0c8-7da7420750b7");
pub const IID_IUIAutomationElement7 = &IID_IUIAutomationElement7_Value;
pub const IUIAutomationElement7 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement6.VTable,
FindFirstWithOptions: fn(
self: *const IUIAutomationElement7,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
traversalOptions: TreeTraversalOptions,
root: ?*IUIAutomationElement,
found: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAllWithOptions: fn(
self: *const IUIAutomationElement7,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
traversalOptions: TreeTraversalOptions,
root: ?*IUIAutomationElement,
found: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindFirstWithOptionsBuildCache: fn(
self: *const IUIAutomationElement7,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
cacheRequest: ?*IUIAutomationCacheRequest,
traversalOptions: TreeTraversalOptions,
root: ?*IUIAutomationElement,
found: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindAllWithOptionsBuildCache: fn(
self: *const IUIAutomationElement7,
scope: TreeScope,
condition: ?*IUIAutomationCondition,
cacheRequest: ?*IUIAutomationCacheRequest,
traversalOptions: TreeTraversalOptions,
root: ?*IUIAutomationElement,
found: ?*?*IUIAutomationElementArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentMetadataValue: fn(
self: *const IUIAutomationElement7,
targetId: i32,
metadataId: i32,
returnVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement6.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement7_FindFirstWithOptions(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, traversalOptions: TreeTraversalOptions, root: ?*IUIAutomationElement, found: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement7.VTable, self.vtable).FindFirstWithOptions(@ptrCast(*const IUIAutomationElement7, self), scope, condition, traversalOptions, root, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement7_FindAllWithOptions(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, traversalOptions: TreeTraversalOptions, root: ?*IUIAutomationElement, found: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement7.VTable, self.vtable).FindAllWithOptions(@ptrCast(*const IUIAutomationElement7, self), scope, condition, traversalOptions, root, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement7_FindFirstWithOptionsBuildCache(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, cacheRequest: ?*IUIAutomationCacheRequest, traversalOptions: TreeTraversalOptions, root: ?*IUIAutomationElement, found: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement7.VTable, self.vtable).FindFirstWithOptionsBuildCache(@ptrCast(*const IUIAutomationElement7, self), scope, condition, cacheRequest, traversalOptions, root, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement7_FindAllWithOptionsBuildCache(self: *const T, scope: TreeScope, condition: ?*IUIAutomationCondition, cacheRequest: ?*IUIAutomationCacheRequest, traversalOptions: TreeTraversalOptions, root: ?*IUIAutomationElement, found: ?*?*IUIAutomationElementArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement7.VTable, self.vtable).FindAllWithOptionsBuildCache(@ptrCast(*const IUIAutomationElement7, self), scope, condition, cacheRequest, traversalOptions, root, found);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement7_GetCurrentMetadataValue(self: *const T, targetId: i32, metadataId: i32, returnVal: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement7.VTable, self.vtable).GetCurrentMetadataValue(@ptrCast(*const IUIAutomationElement7, self), targetId, metadataId, returnVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17134'
const IID_IUIAutomationElement8_Value = @import("../zig.zig").Guid.initString("8c60217d-5411-4cde-bcc0-1ceda223830c");
pub const IID_IUIAutomationElement8 = &IID_IUIAutomationElement8_Value;
pub const IUIAutomationElement8 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement7.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentHeadingLevel: fn(
self: *const IUIAutomationElement8,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedHeadingLevel: fn(
self: *const IUIAutomationElement8,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement7.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement8_get_CurrentHeadingLevel(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement8.VTable, self.vtable).get_CurrentHeadingLevel(@ptrCast(*const IUIAutomationElement8, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement8_get_CachedHeadingLevel(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement8.VTable, self.vtable).get_CachedHeadingLevel(@ptrCast(*const IUIAutomationElement8, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17763'
const IID_IUIAutomationElement9_Value = @import("../zig.zig").Guid.initString("39325fac-039d-440e-a3a3-5eb81a5cecc3");
pub const IID_IUIAutomationElement9 = &IID_IUIAutomationElement9_Value;
pub const IUIAutomationElement9 = extern struct {
pub const VTable = extern struct {
base: IUIAutomationElement8.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CurrentIsDialog: fn(
self: *const IUIAutomationElement9,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CachedIsDialog: fn(
self: *const IUIAutomationElement9,
retVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomationElement8.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement9_get_CurrentIsDialog(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement9.VTable, self.vtable).get_CurrentIsDialog(@ptrCast(*const IUIAutomationElement9, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationElement9_get_CachedIsDialog(self: *const T, retVal: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationElement9.VTable, self.vtable).get_CachedIsDialog(@ptrCast(*const IUIAutomationElement9, self), retVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationProxyFactory_Value = @import("../zig.zig").Guid.initString("85b94ecd-849d-42b6-b94d-d6db23fdf5a4");
pub const IID_IUIAutomationProxyFactory = &IID_IUIAutomationProxyFactory_Value;
pub const IUIAutomationProxyFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateProvider: fn(
self: *const IUIAutomationProxyFactory,
hwnd: ?HWND,
idObject: i32,
idChild: i32,
provider: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProxyFactoryId: fn(
self: *const IUIAutomationProxyFactory,
factoryId: ?*?BSTR,
) 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 IUIAutomationProxyFactory_CreateProvider(self: *const T, hwnd: ?HWND, idObject: i32, idChild: i32, provider: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactory.VTable, self.vtable).CreateProvider(@ptrCast(*const IUIAutomationProxyFactory, self), hwnd, idObject, idChild, provider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactory_get_ProxyFactoryId(self: *const T, factoryId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactory.VTable, self.vtable).get_ProxyFactoryId(@ptrCast(*const IUIAutomationProxyFactory, self), factoryId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationProxyFactoryEntry_Value = @import("../zig.zig").Guid.initString("d50e472e-b64b-490c-bca1-d30696f9f289");
pub const IID_IUIAutomationProxyFactoryEntry = &IID_IUIAutomationProxyFactoryEntry_Value;
pub const IUIAutomationProxyFactoryEntry = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProxyFactory: fn(
self: *const IUIAutomationProxyFactoryEntry,
factory: ?*?*IUIAutomationProxyFactory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClassName: fn(
self: *const IUIAutomationProxyFactoryEntry,
className: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ImageName: fn(
self: *const IUIAutomationProxyFactoryEntry,
imageName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AllowSubstringMatch: fn(
self: *const IUIAutomationProxyFactoryEntry,
allowSubstringMatch: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CanCheckBaseClass: fn(
self: *const IUIAutomationProxyFactoryEntry,
canCheckBaseClass: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_NeedsAdviseEvents: fn(
self: *const IUIAutomationProxyFactoryEntry,
adviseEvents: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ClassName: fn(
self: *const IUIAutomationProxyFactoryEntry,
className: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ImageName: fn(
self: *const IUIAutomationProxyFactoryEntry,
imageName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AllowSubstringMatch: fn(
self: *const IUIAutomationProxyFactoryEntry,
allowSubstringMatch: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_CanCheckBaseClass: fn(
self: *const IUIAutomationProxyFactoryEntry,
canCheckBaseClass: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_NeedsAdviseEvents: fn(
self: *const IUIAutomationProxyFactoryEntry,
adviseEvents: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWinEventsForAutomationEvent: fn(
self: *const IUIAutomationProxyFactoryEntry,
eventId: i32,
propertyId: i32,
winEvents: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWinEventsForAutomationEvent: fn(
self: *const IUIAutomationProxyFactoryEntry,
eventId: i32,
propertyId: i32,
winEvents: ?*?*SAFEARRAY,
) 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 IUIAutomationProxyFactoryEntry_get_ProxyFactory(self: *const T, factory: ?*?*IUIAutomationProxyFactory) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_ProxyFactory(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), factory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_get_ClassName(self: *const T, className: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_ClassName(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), className);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_get_ImageName(self: *const T, imageName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_ImageName(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), imageName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_get_AllowSubstringMatch(self: *const T, allowSubstringMatch: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_AllowSubstringMatch(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), allowSubstringMatch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_get_CanCheckBaseClass(self: *const T, canCheckBaseClass: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_CanCheckBaseClass(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), canCheckBaseClass);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_get_NeedsAdviseEvents(self: *const T, adviseEvents: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).get_NeedsAdviseEvents(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), adviseEvents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_put_ClassName(self: *const T, className: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).put_ClassName(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), className);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_put_ImageName(self: *const T, imageName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).put_ImageName(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), imageName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_put_AllowSubstringMatch(self: *const T, allowSubstringMatch: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).put_AllowSubstringMatch(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), allowSubstringMatch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_put_CanCheckBaseClass(self: *const T, canCheckBaseClass: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).put_CanCheckBaseClass(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), canCheckBaseClass);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_put_NeedsAdviseEvents(self: *const T, adviseEvents: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).put_NeedsAdviseEvents(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), adviseEvents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_SetWinEventsForAutomationEvent(self: *const T, eventId: i32, propertyId: i32, winEvents: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).SetWinEventsForAutomationEvent(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), eventId, propertyId, winEvents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryEntry_GetWinEventsForAutomationEvent(self: *const T, eventId: i32, propertyId: i32, winEvents: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryEntry.VTable, self.vtable).GetWinEventsForAutomationEvent(@ptrCast(*const IUIAutomationProxyFactoryEntry, self), eventId, propertyId, winEvents);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomationProxyFactoryMapping_Value = @import("../zig.zig").Guid.initString("09e31e18-872d-4873-93d1-1e541ec133fd");
pub const IID_IUIAutomationProxyFactoryMapping = &IID_IUIAutomationProxyFactoryMapping_Value;
pub const IUIAutomationProxyFactoryMapping = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IUIAutomationProxyFactoryMapping,
count: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTable: fn(
self: *const IUIAutomationProxyFactoryMapping,
table: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEntry: fn(
self: *const IUIAutomationProxyFactoryMapping,
index: u32,
entry: ?*?*IUIAutomationProxyFactoryEntry,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTable: fn(
self: *const IUIAutomationProxyFactoryMapping,
factoryList: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertEntries: fn(
self: *const IUIAutomationProxyFactoryMapping,
before: u32,
factoryList: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertEntry: fn(
self: *const IUIAutomationProxyFactoryMapping,
before: u32,
factory: ?*IUIAutomationProxyFactoryEntry,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveEntry: fn(
self: *const IUIAutomationProxyFactoryMapping,
index: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearTable: fn(
self: *const IUIAutomationProxyFactoryMapping,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RestoreDefaultTable: fn(
self: *const IUIAutomationProxyFactoryMapping,
) 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 IUIAutomationProxyFactoryMapping_get_Count(self: *const T, count: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).get_Count(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_GetTable(self: *const T, table: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).GetTable(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), table);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_GetEntry(self: *const T, index: u32, entry: ?*?*IUIAutomationProxyFactoryEntry) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).GetEntry(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), index, entry);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_SetTable(self: *const T, factoryList: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).SetTable(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), factoryList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_InsertEntries(self: *const T, before: u32, factoryList: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).InsertEntries(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), before, factoryList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_InsertEntry(self: *const T, before: u32, factory: ?*IUIAutomationProxyFactoryEntry) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).InsertEntry(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), before, factory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_RemoveEntry(self: *const T, index: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).RemoveEntry(@ptrCast(*const IUIAutomationProxyFactoryMapping, self), index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_ClearTable(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).ClearTable(@ptrCast(*const IUIAutomationProxyFactoryMapping, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationProxyFactoryMapping_RestoreDefaultTable(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationProxyFactoryMapping.VTable, self.vtable).RestoreDefaultTable(@ptrCast(*const IUIAutomationProxyFactoryMapping, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17763'
const IID_IUIAutomationEventHandlerGroup_Value = @import("../zig.zig").Guid.initString("c9ee12f2-c13b-4408-997c-639914377f4e");
pub const IID_IUIAutomationEventHandlerGroup = &IID_IUIAutomationEventHandlerGroup_Value;
pub const IUIAutomationEventHandlerGroup = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddActiveTextPositionChangedEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationActiveTextPositionChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddAutomationEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
eventId: i32,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddChangesEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
changeTypes: [*]i32,
changesCount: i32,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationChangesEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddNotificationEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationNotificationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPropertyChangedEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationPropertyChangedEventHandler,
propertyArray: [*]i32,
propertyCount: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddStructureChangedEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationStructureChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTextEditTextChangedEventHandler: fn(
self: *const IUIAutomationEventHandlerGroup,
scope: TreeScope,
textEditChangeType: TextEditChangeType,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationTextEditTextChangedEventHandler,
) 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 IUIAutomationEventHandlerGroup_AddActiveTextPositionChangedEventHandler(self: *const T, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationActiveTextPositionChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddActiveTextPositionChangedEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddAutomationEventHandler(self: *const T, eventId: i32, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddAutomationEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), eventId, scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddChangesEventHandler(self: *const T, scope: TreeScope, changeTypes: [*]i32, changesCount: i32, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationChangesEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddChangesEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, changeTypes, changesCount, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddNotificationEventHandler(self: *const T, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationNotificationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddNotificationEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddPropertyChangedEventHandler(self: *const T, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationPropertyChangedEventHandler, propertyArray: [*]i32, propertyCount: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddPropertyChangedEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, cacheRequest, handler, propertyArray, propertyCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddStructureChangedEventHandler(self: *const T, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationStructureChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddStructureChangedEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomationEventHandlerGroup_AddTextEditTextChangedEventHandler(self: *const T, scope: TreeScope, textEditChangeType: TextEditChangeType, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationTextEditTextChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomationEventHandlerGroup.VTable, self.vtable).AddTextEditTextChangedEventHandler(@ptrCast(*const IUIAutomationEventHandlerGroup, self), scope, textEditChangeType, cacheRequest, handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAutomation_Value = @import("../zig.zig").Guid.initString("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee");
pub const IID_IUIAutomation = &IID_IUIAutomation_Value;
pub const IUIAutomation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CompareElements: fn(
self: *const IUIAutomation,
el1: ?*IUIAutomationElement,
el2: ?*IUIAutomationElement,
areSame: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CompareRuntimeIds: fn(
self: *const IUIAutomation,
runtimeId1: ?*SAFEARRAY,
runtimeId2: ?*SAFEARRAY,
areSame: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRootElement: fn(
self: *const IUIAutomation,
root: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromHandle: fn(
self: *const IUIAutomation,
hwnd: ?HWND,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromPoint: fn(
self: *const IUIAutomation,
pt: POINT,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFocusedElement: fn(
self: *const IUIAutomation,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRootElementBuildCache: fn(
self: *const IUIAutomation,
cacheRequest: ?*IUIAutomationCacheRequest,
root: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromHandleBuildCache: fn(
self: *const IUIAutomation,
hwnd: ?HWND,
cacheRequest: ?*IUIAutomationCacheRequest,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromPointBuildCache: fn(
self: *const IUIAutomation,
pt: POINT,
cacheRequest: ?*IUIAutomationCacheRequest,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFocusedElementBuildCache: fn(
self: *const IUIAutomation,
cacheRequest: ?*IUIAutomationCacheRequest,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTreeWalker: fn(
self: *const IUIAutomation,
pCondition: ?*IUIAutomationCondition,
walker: ?*?*IUIAutomationTreeWalker,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ControlViewWalker: fn(
self: *const IUIAutomation,
walker: ?*?*IUIAutomationTreeWalker,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ContentViewWalker: fn(
self: *const IUIAutomation,
walker: ?*?*IUIAutomationTreeWalker,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RawViewWalker: fn(
self: *const IUIAutomation,
walker: ?*?*IUIAutomationTreeWalker,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RawViewCondition: fn(
self: *const IUIAutomation,
condition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ControlViewCondition: fn(
self: *const IUIAutomation,
condition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ContentViewCondition: fn(
self: *const IUIAutomation,
condition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCacheRequest: fn(
self: *const IUIAutomation,
cacheRequest: ?*?*IUIAutomationCacheRequest,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTrueCondition: fn(
self: *const IUIAutomation,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFalseCondition: fn(
self: *const IUIAutomation,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreatePropertyCondition: fn(
self: *const IUIAutomation,
propertyId: i32,
value: VARIANT,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreatePropertyConditionEx: fn(
self: *const IUIAutomation,
propertyId: i32,
value: VARIANT,
flags: PropertyConditionFlags,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAndCondition: fn(
self: *const IUIAutomation,
condition1: ?*IUIAutomationCondition,
condition2: ?*IUIAutomationCondition,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAndConditionFromArray: fn(
self: *const IUIAutomation,
conditions: ?*SAFEARRAY,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAndConditionFromNativeArray: fn(
self: *const IUIAutomation,
conditions: [*]?*IUIAutomationCondition,
conditionCount: i32,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateOrCondition: fn(
self: *const IUIAutomation,
condition1: ?*IUIAutomationCondition,
condition2: ?*IUIAutomationCondition,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateOrConditionFromArray: fn(
self: *const IUIAutomation,
conditions: ?*SAFEARRAY,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateOrConditionFromNativeArray: fn(
self: *const IUIAutomation,
conditions: [*]?*IUIAutomationCondition,
conditionCount: i32,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateNotCondition: fn(
self: *const IUIAutomation,
condition: ?*IUIAutomationCondition,
newCondition: ?*?*IUIAutomationCondition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddAutomationEventHandler: fn(
self: *const IUIAutomation,
eventId: i32,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveAutomationEventHandler: fn(
self: *const IUIAutomation,
eventId: i32,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPropertyChangedEventHandlerNativeArray: fn(
self: *const IUIAutomation,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationPropertyChangedEventHandler,
propertyArray: [*]i32,
propertyCount: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPropertyChangedEventHandler: fn(
self: *const IUIAutomation,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationPropertyChangedEventHandler,
propertyArray: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemovePropertyChangedEventHandler: fn(
self: *const IUIAutomation,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationPropertyChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddStructureChangedEventHandler: fn(
self: *const IUIAutomation,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationStructureChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveStructureChangedEventHandler: fn(
self: *const IUIAutomation,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationStructureChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddFocusChangedEventHandler: fn(
self: *const IUIAutomation,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationFocusChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFocusChangedEventHandler: fn(
self: *const IUIAutomation,
handler: ?*IUIAutomationFocusChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveAllEventHandlers: fn(
self: *const IUIAutomation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IntNativeArrayToSafeArray: fn(
self: *const IUIAutomation,
array: [*]i32,
arrayCount: i32,
safeArray: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IntSafeArrayToNativeArray: fn(
self: *const IUIAutomation,
intArray: ?*SAFEARRAY,
array: [*]?*i32,
arrayCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RectToVariant: fn(
self: *const IUIAutomation,
rc: RECT,
@"var": ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
VariantToRect: fn(
self: *const IUIAutomation,
@"var": VARIANT,
rc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SafeArrayToRectNativeArray: fn(
self: *const IUIAutomation,
rects: ?*SAFEARRAY,
rectArray: [*]?*RECT,
rectArrayCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateProxyFactoryEntry: fn(
self: *const IUIAutomation,
factory: ?*IUIAutomationProxyFactory,
factoryEntry: ?*?*IUIAutomationProxyFactoryEntry,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProxyFactoryMapping: fn(
self: *const IUIAutomation,
factoryMapping: ?*?*IUIAutomationProxyFactoryMapping,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyProgrammaticName: fn(
self: *const IUIAutomation,
property: i32,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPatternProgrammaticName: fn(
self: *const IUIAutomation,
pattern: i32,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PollForPotentialSupportedPatterns: fn(
self: *const IUIAutomation,
pElement: ?*IUIAutomationElement,
patternIds: ?*?*SAFEARRAY,
patternNames: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PollForPotentialSupportedProperties: fn(
self: *const IUIAutomation,
pElement: ?*IUIAutomationElement,
propertyIds: ?*?*SAFEARRAY,
propertyNames: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckNotSupported: fn(
self: *const IUIAutomation,
value: VARIANT,
isNotSupported: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReservedNotSupportedValue: fn(
self: *const IUIAutomation,
notSupportedValue: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReservedMixedAttributeValue: fn(
self: *const IUIAutomation,
mixedAttributeValue: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromIAccessible: fn(
self: *const IUIAutomation,
accessible: ?*IAccessible,
childId: i32,
element: ?*?*IUIAutomationElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ElementFromIAccessibleBuildCache: fn(
self: *const IUIAutomation,
accessible: ?*IAccessible,
childId: i32,
cacheRequest: ?*IUIAutomationCacheRequest,
element: ?*?*IUIAutomationElement,
) 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 IUIAutomation_CompareElements(self: *const T, el1: ?*IUIAutomationElement, el2: ?*IUIAutomationElement, areSame: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CompareElements(@ptrCast(*const IUIAutomation, self), el1, el2, areSame);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CompareRuntimeIds(self: *const T, runtimeId1: ?*SAFEARRAY, runtimeId2: ?*SAFEARRAY, areSame: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CompareRuntimeIds(@ptrCast(*const IUIAutomation, self), runtimeId1, runtimeId2, areSame);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetRootElement(self: *const T, root: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetRootElement(@ptrCast(*const IUIAutomation, self), root);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromHandle(self: *const T, hwnd: ?HWND, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromHandle(@ptrCast(*const IUIAutomation, self), hwnd, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromPoint(self: *const T, pt: POINT, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromPoint(@ptrCast(*const IUIAutomation, self), pt, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetFocusedElement(self: *const T, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetFocusedElement(@ptrCast(*const IUIAutomation, self), element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetRootElementBuildCache(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, root: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetRootElementBuildCache(@ptrCast(*const IUIAutomation, self), cacheRequest, root);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromHandleBuildCache(self: *const T, hwnd: ?HWND, cacheRequest: ?*IUIAutomationCacheRequest, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromHandleBuildCache(@ptrCast(*const IUIAutomation, self), hwnd, cacheRequest, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromPointBuildCache(self: *const T, pt: POINT, cacheRequest: ?*IUIAutomationCacheRequest, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromPointBuildCache(@ptrCast(*const IUIAutomation, self), pt, cacheRequest, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetFocusedElementBuildCache(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetFocusedElementBuildCache(@ptrCast(*const IUIAutomation, self), cacheRequest, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateTreeWalker(self: *const T, pCondition: ?*IUIAutomationCondition, walker: ?*?*IUIAutomationTreeWalker) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateTreeWalker(@ptrCast(*const IUIAutomation, self), pCondition, walker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ControlViewWalker(self: *const T, walker: ?*?*IUIAutomationTreeWalker) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ControlViewWalker(@ptrCast(*const IUIAutomation, self), walker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ContentViewWalker(self: *const T, walker: ?*?*IUIAutomationTreeWalker) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ContentViewWalker(@ptrCast(*const IUIAutomation, self), walker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_RawViewWalker(self: *const T, walker: ?*?*IUIAutomationTreeWalker) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_RawViewWalker(@ptrCast(*const IUIAutomation, self), walker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_RawViewCondition(self: *const T, condition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_RawViewCondition(@ptrCast(*const IUIAutomation, self), condition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ControlViewCondition(self: *const T, condition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ControlViewCondition(@ptrCast(*const IUIAutomation, self), condition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ContentViewCondition(self: *const T, condition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ContentViewCondition(@ptrCast(*const IUIAutomation, self), condition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateCacheRequest(self: *const T, cacheRequest: ?*?*IUIAutomationCacheRequest) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateCacheRequest(@ptrCast(*const IUIAutomation, self), cacheRequest);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateTrueCondition(self: *const T, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateTrueCondition(@ptrCast(*const IUIAutomation, self), newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateFalseCondition(self: *const T, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateFalseCondition(@ptrCast(*const IUIAutomation, self), newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreatePropertyCondition(self: *const T, propertyId: i32, value: VARIANT, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreatePropertyCondition(@ptrCast(*const IUIAutomation, self), propertyId, value, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreatePropertyConditionEx(self: *const T, propertyId: i32, value: VARIANT, flags: PropertyConditionFlags, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreatePropertyConditionEx(@ptrCast(*const IUIAutomation, self), propertyId, value, flags, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateAndCondition(self: *const T, condition1: ?*IUIAutomationCondition, condition2: ?*IUIAutomationCondition, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateAndCondition(@ptrCast(*const IUIAutomation, self), condition1, condition2, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateAndConditionFromArray(self: *const T, conditions: ?*SAFEARRAY, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateAndConditionFromArray(@ptrCast(*const IUIAutomation, self), conditions, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateAndConditionFromNativeArray(self: *const T, conditions: [*]?*IUIAutomationCondition, conditionCount: i32, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateAndConditionFromNativeArray(@ptrCast(*const IUIAutomation, self), conditions, conditionCount, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateOrCondition(self: *const T, condition1: ?*IUIAutomationCondition, condition2: ?*IUIAutomationCondition, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateOrCondition(@ptrCast(*const IUIAutomation, self), condition1, condition2, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateOrConditionFromArray(self: *const T, conditions: ?*SAFEARRAY, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateOrConditionFromArray(@ptrCast(*const IUIAutomation, self), conditions, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateOrConditionFromNativeArray(self: *const T, conditions: [*]?*IUIAutomationCondition, conditionCount: i32, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateOrConditionFromNativeArray(@ptrCast(*const IUIAutomation, self), conditions, conditionCount, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateNotCondition(self: *const T, condition: ?*IUIAutomationCondition, newCondition: ?*?*IUIAutomationCondition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateNotCondition(@ptrCast(*const IUIAutomation, self), condition, newCondition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_AddAutomationEventHandler(self: *const T, eventId: i32, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).AddAutomationEventHandler(@ptrCast(*const IUIAutomation, self), eventId, element, scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RemoveAutomationEventHandler(self: *const T, eventId: i32, element: ?*IUIAutomationElement, handler: ?*IUIAutomationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RemoveAutomationEventHandler(@ptrCast(*const IUIAutomation, self), eventId, element, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_AddPropertyChangedEventHandlerNativeArray(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationPropertyChangedEventHandler, propertyArray: [*]i32, propertyCount: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).AddPropertyChangedEventHandlerNativeArray(@ptrCast(*const IUIAutomation, self), element, scope, cacheRequest, handler, propertyArray, propertyCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_AddPropertyChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationPropertyChangedEventHandler, propertyArray: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).AddPropertyChangedEventHandler(@ptrCast(*const IUIAutomation, self), element, scope, cacheRequest, handler, propertyArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RemovePropertyChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationPropertyChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RemovePropertyChangedEventHandler(@ptrCast(*const IUIAutomation, self), element, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_AddStructureChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationStructureChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).AddStructureChangedEventHandler(@ptrCast(*const IUIAutomation, self), element, scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RemoveStructureChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationStructureChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RemoveStructureChangedEventHandler(@ptrCast(*const IUIAutomation, self), element, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_AddFocusChangedEventHandler(self: *const T, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationFocusChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).AddFocusChangedEventHandler(@ptrCast(*const IUIAutomation, self), cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RemoveFocusChangedEventHandler(self: *const T, handler: ?*IUIAutomationFocusChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RemoveFocusChangedEventHandler(@ptrCast(*const IUIAutomation, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RemoveAllEventHandlers(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RemoveAllEventHandlers(@ptrCast(*const IUIAutomation, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_IntNativeArrayToSafeArray(self: *const T, array: [*]i32, arrayCount: i32, safeArray: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).IntNativeArrayToSafeArray(@ptrCast(*const IUIAutomation, self), array, arrayCount, safeArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_IntSafeArrayToNativeArray(self: *const T, intArray: ?*SAFEARRAY, array: [*]?*i32, arrayCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).IntSafeArrayToNativeArray(@ptrCast(*const IUIAutomation, self), intArray, array, arrayCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_RectToVariant(self: *const T, rc: RECT, @"var": ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).RectToVariant(@ptrCast(*const IUIAutomation, self), rc, @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_VariantToRect(self: *const T, @"var": VARIANT, rc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).VariantToRect(@ptrCast(*const IUIAutomation, self), @"var", rc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_SafeArrayToRectNativeArray(self: *const T, rects: ?*SAFEARRAY, rectArray: [*]?*RECT, rectArrayCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).SafeArrayToRectNativeArray(@ptrCast(*const IUIAutomation, self), rects, rectArray, rectArrayCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CreateProxyFactoryEntry(self: *const T, factory: ?*IUIAutomationProxyFactory, factoryEntry: ?*?*IUIAutomationProxyFactoryEntry) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CreateProxyFactoryEntry(@ptrCast(*const IUIAutomation, self), factory, factoryEntry);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ProxyFactoryMapping(self: *const T, factoryMapping: ?*?*IUIAutomationProxyFactoryMapping) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ProxyFactoryMapping(@ptrCast(*const IUIAutomation, self), factoryMapping);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetPropertyProgrammaticName(self: *const T, property: i32, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetPropertyProgrammaticName(@ptrCast(*const IUIAutomation, self), property, name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_GetPatternProgrammaticName(self: *const T, pattern: i32, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).GetPatternProgrammaticName(@ptrCast(*const IUIAutomation, self), pattern, name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_PollForPotentialSupportedPatterns(self: *const T, pElement: ?*IUIAutomationElement, patternIds: ?*?*SAFEARRAY, patternNames: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).PollForPotentialSupportedPatterns(@ptrCast(*const IUIAutomation, self), pElement, patternIds, patternNames);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_PollForPotentialSupportedProperties(self: *const T, pElement: ?*IUIAutomationElement, propertyIds: ?*?*SAFEARRAY, propertyNames: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).PollForPotentialSupportedProperties(@ptrCast(*const IUIAutomation, self), pElement, propertyIds, propertyNames);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_CheckNotSupported(self: *const T, value: VARIANT, isNotSupported: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).CheckNotSupported(@ptrCast(*const IUIAutomation, self), value, isNotSupported);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ReservedNotSupportedValue(self: *const T, notSupportedValue: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ReservedNotSupportedValue(@ptrCast(*const IUIAutomation, self), notSupportedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_get_ReservedMixedAttributeValue(self: *const T, mixedAttributeValue: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).get_ReservedMixedAttributeValue(@ptrCast(*const IUIAutomation, self), mixedAttributeValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromIAccessible(self: *const T, accessible: ?*IAccessible, childId: i32, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromIAccessible(@ptrCast(*const IUIAutomation, self), accessible, childId, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation_ElementFromIAccessibleBuildCache(self: *const T, accessible: ?*IAccessible, childId: i32, cacheRequest: ?*IUIAutomationCacheRequest, element: ?*?*IUIAutomationElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation.VTable, self.vtable).ElementFromIAccessibleBuildCache(@ptrCast(*const IUIAutomation, self), accessible, childId, cacheRequest, element);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAutomation2_Value = @import("../zig.zig").Guid.initString("34723aff-0c9d-49d0-9896-7ab52df8cd8a");
pub const IID_IUIAutomation2 = &IID_IUIAutomation2_Value;
pub const IUIAutomation2 = extern struct {
pub const VTable = extern struct {
base: IUIAutomation.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AutoSetFocus: fn(
self: *const IUIAutomation2,
autoSetFocus: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AutoSetFocus: fn(
self: *const IUIAutomation2,
autoSetFocus: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ConnectionTimeout: fn(
self: *const IUIAutomation2,
timeout: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ConnectionTimeout: fn(
self: *const IUIAutomation2,
timeout: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TransactionTimeout: fn(
self: *const IUIAutomation2,
timeout: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TransactionTimeout: fn(
self: *const IUIAutomation2,
timeout: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomation.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_get_AutoSetFocus(self: *const T, autoSetFocus: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).get_AutoSetFocus(@ptrCast(*const IUIAutomation2, self), autoSetFocus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_put_AutoSetFocus(self: *const T, autoSetFocus: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).put_AutoSetFocus(@ptrCast(*const IUIAutomation2, self), autoSetFocus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_get_ConnectionTimeout(self: *const T, timeout: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).get_ConnectionTimeout(@ptrCast(*const IUIAutomation2, self), timeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_put_ConnectionTimeout(self: *const T, timeout: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).put_ConnectionTimeout(@ptrCast(*const IUIAutomation2, self), timeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_get_TransactionTimeout(self: *const T, timeout: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).get_TransactionTimeout(@ptrCast(*const IUIAutomation2, self), timeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation2_put_TransactionTimeout(self: *const T, timeout: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation2.VTable, self.vtable).put_TransactionTimeout(@ptrCast(*const IUIAutomation2, self), timeout);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IUIAutomation3_Value = @import("../zig.zig").Guid.initString("73d768da-9b51-4b89-936e-c209290973e7");
pub const IID_IUIAutomation3 = &IID_IUIAutomation3_Value;
pub const IUIAutomation3 = extern struct {
pub const VTable = extern struct {
base: IUIAutomation2.VTable,
AddTextEditTextChangedEventHandler: fn(
self: *const IUIAutomation3,
element: ?*IUIAutomationElement,
scope: TreeScope,
textEditChangeType: TextEditChangeType,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationTextEditTextChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveTextEditTextChangedEventHandler: fn(
self: *const IUIAutomation3,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationTextEditTextChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomation2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation3_AddTextEditTextChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, textEditChangeType: TextEditChangeType, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationTextEditTextChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation3.VTable, self.vtable).AddTextEditTextChangedEventHandler(@ptrCast(*const IUIAutomation3, self), element, scope, textEditChangeType, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation3_RemoveTextEditTextChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationTextEditTextChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation3.VTable, self.vtable).RemoveTextEditTextChangedEventHandler(@ptrCast(*const IUIAutomation3, self), element, handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IUIAutomation4_Value = @import("../zig.zig").Guid.initString("1189c02a-05f8-4319-8e21-e817e3db2860");
pub const IID_IUIAutomation4 = &IID_IUIAutomation4_Value;
pub const IUIAutomation4 = extern struct {
pub const VTable = extern struct {
base: IUIAutomation3.VTable,
AddChangesEventHandler: fn(
self: *const IUIAutomation4,
element: ?*IUIAutomationElement,
scope: TreeScope,
changeTypes: [*]i32,
changesCount: i32,
pCacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationChangesEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveChangesEventHandler: fn(
self: *const IUIAutomation4,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationChangesEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomation3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation4_AddChangesEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, changeTypes: [*]i32, changesCount: i32, pCacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationChangesEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation4.VTable, self.vtable).AddChangesEventHandler(@ptrCast(*const IUIAutomation4, self), element, scope, changeTypes, changesCount, pCacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation4_RemoveChangesEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationChangesEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation4.VTable, self.vtable).RemoveChangesEventHandler(@ptrCast(*const IUIAutomation4, self), element, handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.14393'
const IID_IUIAutomation5_Value = @import("../zig.zig").Guid.initString("25f700c8-d816-4057-a9dc-3cbdee77e256");
pub const IID_IUIAutomation5 = &IID_IUIAutomation5_Value;
pub const IUIAutomation5 = extern struct {
pub const VTable = extern struct {
base: IUIAutomation4.VTable,
AddNotificationEventHandler: fn(
self: *const IUIAutomation5,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationNotificationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveNotificationEventHandler: fn(
self: *const IUIAutomation5,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationNotificationEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomation4.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation5_AddNotificationEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationNotificationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation5.VTable, self.vtable).AddNotificationEventHandler(@ptrCast(*const IUIAutomation5, self), element, scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation5_RemoveNotificationEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationNotificationEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation5.VTable, self.vtable).RemoveNotificationEventHandler(@ptrCast(*const IUIAutomation5, self), element, handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.17763'
const IID_IUIAutomation6_Value = @import("../zig.zig").Guid.initString("aae072da-29e3-413d-87a7-192dbf81ed10");
pub const IID_IUIAutomation6 = &IID_IUIAutomation6_Value;
pub const IUIAutomation6 = extern struct {
pub const VTable = extern struct {
base: IUIAutomation5.VTable,
CreateEventHandlerGroup: fn(
self: *const IUIAutomation6,
handlerGroup: ?*?*IUIAutomationEventHandlerGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddEventHandlerGroup: fn(
self: *const IUIAutomation6,
element: ?*IUIAutomationElement,
handlerGroup: ?*IUIAutomationEventHandlerGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveEventHandlerGroup: fn(
self: *const IUIAutomation6,
element: ?*IUIAutomationElement,
handlerGroup: ?*IUIAutomationEventHandlerGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ConnectionRecoveryBehavior: fn(
self: *const IUIAutomation6,
connectionRecoveryBehaviorOptions: ?*ConnectionRecoveryBehaviorOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ConnectionRecoveryBehavior: fn(
self: *const IUIAutomation6,
connectionRecoveryBehaviorOptions: ConnectionRecoveryBehaviorOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CoalesceEvents: fn(
self: *const IUIAutomation6,
coalesceEventsOptions: ?*CoalesceEventsOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_CoalesceEvents: fn(
self: *const IUIAutomation6,
coalesceEventsOptions: CoalesceEventsOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddActiveTextPositionChangedEventHandler: fn(
self: *const IUIAutomation6,
element: ?*IUIAutomationElement,
scope: TreeScope,
cacheRequest: ?*IUIAutomationCacheRequest,
handler: ?*IUIAutomationActiveTextPositionChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveActiveTextPositionChangedEventHandler: fn(
self: *const IUIAutomation6,
element: ?*IUIAutomationElement,
handler: ?*IUIAutomationActiveTextPositionChangedEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUIAutomation5.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_CreateEventHandlerGroup(self: *const T, handlerGroup: ?*?*IUIAutomationEventHandlerGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).CreateEventHandlerGroup(@ptrCast(*const IUIAutomation6, self), handlerGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_AddEventHandlerGroup(self: *const T, element: ?*IUIAutomationElement, handlerGroup: ?*IUIAutomationEventHandlerGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).AddEventHandlerGroup(@ptrCast(*const IUIAutomation6, self), element, handlerGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_RemoveEventHandlerGroup(self: *const T, element: ?*IUIAutomationElement, handlerGroup: ?*IUIAutomationEventHandlerGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).RemoveEventHandlerGroup(@ptrCast(*const IUIAutomation6, self), element, handlerGroup);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_get_ConnectionRecoveryBehavior(self: *const T, connectionRecoveryBehaviorOptions: ?*ConnectionRecoveryBehaviorOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).get_ConnectionRecoveryBehavior(@ptrCast(*const IUIAutomation6, self), connectionRecoveryBehaviorOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_put_ConnectionRecoveryBehavior(self: *const T, connectionRecoveryBehaviorOptions: ConnectionRecoveryBehaviorOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).put_ConnectionRecoveryBehavior(@ptrCast(*const IUIAutomation6, self), connectionRecoveryBehaviorOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_get_CoalesceEvents(self: *const T, coalesceEventsOptions: ?*CoalesceEventsOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).get_CoalesceEvents(@ptrCast(*const IUIAutomation6, self), coalesceEventsOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_put_CoalesceEvents(self: *const T, coalesceEventsOptions: CoalesceEventsOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).put_CoalesceEvents(@ptrCast(*const IUIAutomation6, self), coalesceEventsOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_AddActiveTextPositionChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, scope: TreeScope, cacheRequest: ?*IUIAutomationCacheRequest, handler: ?*IUIAutomationActiveTextPositionChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).AddActiveTextPositionChangedEventHandler(@ptrCast(*const IUIAutomation6, self), element, scope, cacheRequest, handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAutomation6_RemoveActiveTextPositionChangedEventHandler(self: *const T, element: ?*IUIAutomationElement, handler: ?*IUIAutomationActiveTextPositionChangedEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAutomation6.VTable, self.vtable).RemoveActiveTextPositionChangedEventHandler(@ptrCast(*const IUIAutomation6, self), element, handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const ConditionType = enum(i32) {
True = 0,
False = 1,
Property = 2,
And = 3,
Or = 4,
Not = 5,
};
pub const ConditionType_True = ConditionType.True;
pub const ConditionType_False = ConditionType.False;
pub const ConditionType_Property = ConditionType.Property;
pub const ConditionType_And = ConditionType.And;
pub const ConditionType_Or = ConditionType.Or;
pub const ConditionType_Not = ConditionType.Not;
pub const UiaCondition = extern struct {
ConditionType: ConditionType,
};
pub const UiaPropertyCondition = extern struct {
ConditionType: ConditionType,
PropertyId: i32,
Value: VARIANT,
Flags: PropertyConditionFlags,
};
pub const UiaAndOrCondition = extern struct {
ConditionType: ConditionType,
ppConditions: ?*?*UiaCondition,
cConditions: i32,
};
pub const UiaNotCondition = extern struct {
ConditionType: ConditionType,
pCondition: ?*UiaCondition,
};
pub const UiaCacheRequest = extern struct {
pViewCondition: ?*UiaCondition,
Scope: TreeScope,
pProperties: ?*i32,
cProperties: i32,
pPatterns: ?*i32,
cPatterns: i32,
automationElementMode: AutomationElementMode,
};
pub const NormalizeState = enum(i32) {
None = 0,
View = 1,
Custom = 2,
};
pub const NormalizeState_None = NormalizeState.None;
pub const NormalizeState_View = NormalizeState.View;
pub const NormalizeState_Custom = NormalizeState.Custom;
pub const UiaFindParams = extern struct {
MaxDepth: i32,
FindFirst: BOOL,
ExcludeRoot: BOOL,
pFindCondition: ?*UiaCondition,
};
pub const ProviderType = enum(i32) {
BaseHwnd = 0,
Proxy = 1,
NonClientArea = 2,
};
pub const ProviderType_BaseHwnd = ProviderType.BaseHwnd;
pub const ProviderType_Proxy = ProviderType.Proxy;
pub const ProviderType_NonClientArea = ProviderType.NonClientArea;
pub const UiaProviderCallback = fn(
hwnd: ?HWND,
providerType: ProviderType,
) callconv(@import("std").os.windows.WINAPI) ?*SAFEARRAY;
pub const AutomationIdentifierType = enum(i32) {
Property = 0,
Pattern = 1,
Event = 2,
ControlType = 3,
TextAttribute = 4,
LandmarkType = 5,
Annotation = 6,
Changes = 7,
Style = 8,
};
pub const AutomationIdentifierType_Property = AutomationIdentifierType.Property;
pub const AutomationIdentifierType_Pattern = AutomationIdentifierType.Pattern;
pub const AutomationIdentifierType_Event = AutomationIdentifierType.Event;
pub const AutomationIdentifierType_ControlType = AutomationIdentifierType.ControlType;
pub const AutomationIdentifierType_TextAttribute = AutomationIdentifierType.TextAttribute;
pub const AutomationIdentifierType_LandmarkType = AutomationIdentifierType.LandmarkType;
pub const AutomationIdentifierType_Annotation = AutomationIdentifierType.Annotation;
pub const AutomationIdentifierType_Changes = AutomationIdentifierType.Changes;
pub const AutomationIdentifierType_Style = AutomationIdentifierType.Style;
pub const EventArgsType = enum(i32) {
Simple = 0,
PropertyChanged = 1,
StructureChanged = 2,
AsyncContentLoaded = 3,
WindowClosed = 4,
TextEditTextChanged = 5,
Changes = 6,
Notification = 7,
ActiveTextPositionChanged = 8,
StructuredMarkup = 9,
};
pub const EventArgsType_Simple = EventArgsType.Simple;
pub const EventArgsType_PropertyChanged = EventArgsType.PropertyChanged;
pub const EventArgsType_StructureChanged = EventArgsType.StructureChanged;
pub const EventArgsType_AsyncContentLoaded = EventArgsType.AsyncContentLoaded;
pub const EventArgsType_WindowClosed = EventArgsType.WindowClosed;
pub const EventArgsType_TextEditTextChanged = EventArgsType.TextEditTextChanged;
pub const EventArgsType_Changes = EventArgsType.Changes;
pub const EventArgsType_Notification = EventArgsType.Notification;
pub const EventArgsType_ActiveTextPositionChanged = EventArgsType.ActiveTextPositionChanged;
pub const EventArgsType_StructuredMarkup = EventArgsType.StructuredMarkup;
pub const AsyncContentLoadedState = enum(i32) {
Beginning = 0,
Progress = 1,
Completed = 2,
};
pub const AsyncContentLoadedState_Beginning = AsyncContentLoadedState.Beginning;
pub const AsyncContentLoadedState_Progress = AsyncContentLoadedState.Progress;
pub const AsyncContentLoadedState_Completed = AsyncContentLoadedState.Completed;
pub const UiaEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
};
pub const UiaPropertyChangedEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
PropertyId: i32,
OldValue: VARIANT,
NewValue: VARIANT,
};
pub const UiaStructureChangedEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
StructureChangeType: StructureChangeType,
pRuntimeId: ?*i32,
cRuntimeIdLen: i32,
};
pub const UiaTextEditTextChangedEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
TextEditChangeType: TextEditChangeType,
pTextChange: ?*SAFEARRAY,
};
pub const UiaChangesEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
EventIdCount: i32,
pUiaChanges: ?*UiaChangeInfo,
};
pub const UiaAsyncContentLoadedEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
AsyncContentLoadedState: AsyncContentLoadedState,
PercentComplete: f64,
};
pub const UiaWindowClosedEventArgs = extern struct {
Type: EventArgsType,
EventId: i32,
pRuntimeId: ?*i32,
cRuntimeIdLen: i32,
};
pub const UiaEventCallback = fn(
pArgs: ?*UiaEventArgs,
pRequestedData: ?*SAFEARRAY,
pTreeStructure: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void;
//--------------------------------------------------------------------------------
// Section: Functions (123)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn RegisterPointerInputTarget(
hwnd: ?HWND,
pointerType: POINTER_INPUT_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn UnregisterPointerInputTarget(
hwnd: ?HWND,
pointerType: POINTER_INPUT_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "USER32" fn RegisterPointerInputTargetEx(
hwnd: ?HWND,
pointerType: POINTER_INPUT_TYPE,
fObserve: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "USER32" fn UnregisterPointerInputTargetEx(
hwnd: ?HWND,
pointerType: POINTER_INPUT_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn NotifyWinEvent(
event: u32,
hwnd: ?HWND,
idObject: i32,
idChild: i32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWinEventHook(
eventMin: u32,
eventMax: u32,
hmodWinEventProc: ?HINSTANCE,
pfnWinEventProc: ?WINEVENTPROC,
idProcess: u32,
idThread: u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) ?HWINEVENTHOOK;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn IsWinEventHookInstalled(
event: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn UnhookWinEvent(
hWinEventHook: ?HWINEVENTHOOK,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn LresultFromObject(
riid: ?*const Guid,
wParam: WPARAM,
punk: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "OLEACC" fn ObjectFromLresult(
lResult: LRESULT,
riid: ?*const Guid,
wParam: WPARAM,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn WindowFromAccessibleObject(
param0: ?*IAccessible,
phwnd: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn AccessibleObjectFromWindow(
hwnd: ?HWND,
dwId: u32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn AccessibleObjectFromEvent(
hwnd: ?HWND,
dwId: u32,
dwChildId: u32,
ppacc: ?*?*IAccessible,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn AccessibleObjectFromPoint(
ptScreen: POINT,
ppacc: ?*?*IAccessible,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn AccessibleChildren(
paccContainer: ?*IAccessible,
iChildStart: i32,
cChildren: i32,
rgvarChildren: [*]VARIANT,
pcObtained: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn GetRoleTextA(
lRole: u32,
lpszRole: ?[*:0]u8,
cchRoleMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn GetRoleTextW(
lRole: u32,
lpszRole: ?[*:0]u16,
cchRoleMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn GetStateTextA(
lStateBit: u32,
lpszState: ?[*:0]u8,
cchState: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn GetStateTextW(
lStateBit: u32,
lpszState: ?[*:0]u16,
cchState: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn GetOleaccVersionInfo(
pVer: ?*u32,
pBuild: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn CreateStdAccessibleObject(
hwnd: ?HWND,
idObject: i32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn CreateStdAccessibleProxyA(
hwnd: ?HWND,
pClassName: ?[*:0]const u8,
idObject: i32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "OLEACC" fn CreateStdAccessibleProxyW(
hwnd: ?HWND,
pClassName: ?[*:0]const u16,
idObject: i32,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "OLEACC" fn AccSetRunningUtilityState(
hwndApp: ?HWND,
dwUtilityStateMask: u32,
dwUtilityState: ACC_UTILITY_STATE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "OLEACC" fn AccNotifyTouchInteraction(
hwndApp: ?HWND,
hwndTarget: ?HWND,
ptTarget: POINT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetErrorDescription(
pDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaHUiaNodeFromVariant(
pvar: ?*VARIANT,
phnode: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaHPatternObjectFromVariant(
pvar: ?*VARIANT,
phobj: ?*?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaHTextRangeFromVariant(
pvar: ?*VARIANT,
phtextrange: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNodeRelease(
hnode: ?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetPropertyValue(
hnode: ?HUIANODE,
propertyId: i32,
pValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetPatternProvider(
hnode: ?HUIANODE,
patternId: i32,
phobj: ?*?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetRuntimeId(
hnode: ?HUIANODE,
pruntimeId: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaSetFocus(
hnode: ?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNavigate(
hnode: ?HUIANODE,
direction: NavigateDirection,
pCondition: ?*UiaCondition,
pRequest: ?*UiaCacheRequest,
ppRequestedData: ?*?*SAFEARRAY,
ppTreeStructure: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetUpdatedCache(
hnode: ?HUIANODE,
pRequest: ?*UiaCacheRequest,
normalizeState: NormalizeState,
pNormalizeCondition: ?*UiaCondition,
ppRequestedData: ?*?*SAFEARRAY,
ppTreeStructure: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaFind(
hnode: ?HUIANODE,
pParams: ?*UiaFindParams,
pRequest: ?*UiaCacheRequest,
ppRequestedData: ?*?*SAFEARRAY,
ppOffsets: ?*?*SAFEARRAY,
ppTreeStructures: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNodeFromPoint(
x: f64,
y: f64,
pRequest: ?*UiaCacheRequest,
ppRequestedData: ?*?*SAFEARRAY,
ppTreeStructure: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNodeFromFocus(
pRequest: ?*UiaCacheRequest,
ppRequestedData: ?*?*SAFEARRAY,
ppTreeStructure: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNodeFromHandle(
hwnd: ?HWND,
phnode: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaNodeFromProvider(
pProvider: ?*IRawElementProviderSimple,
phnode: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetRootNode(
phnode: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRegisterProviderCallback(
pCallback: ?*?UiaProviderCallback,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaLookupId(
type: AutomationIdentifierType,
pGuid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetReservedNotSupportedValue(
punkNotSupportedValue: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaGetReservedMixedAttributeValue(
punkMixedAttributeValue: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaClientsAreListening(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRaiseAutomationPropertyChangedEvent(
pProvider: ?*IRawElementProviderSimple,
id: i32,
oldValue: VARIANT,
newValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRaiseAutomationEvent(
pProvider: ?*IRawElementProviderSimple,
id: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRaiseStructureChangedEvent(
pProvider: ?*IRawElementProviderSimple,
structureChangeType: StructureChangeType,
pRuntimeId: ?*i32,
cRuntimeIdLen: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRaiseAsyncContentLoadedEvent(
pProvider: ?*IRawElementProviderSimple,
asyncContentLoadedState: AsyncContentLoadedState,
percentComplete: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.1'
pub extern "UIAutomationCore" fn UiaRaiseTextEditTextChangedEvent(
pProvider: ?*IRawElementProviderSimple,
textEditChangeType: TextEditChangeType,
pChangedData: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "UIAutomationCore" fn UiaRaiseChangesEvent(
pProvider: ?*IRawElementProviderSimple,
eventIdCount: i32,
pUiaChanges: ?*UiaChangeInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "UIAutomationCore" fn UiaRaiseNotificationEvent(
provider: ?*IRawElementProviderSimple,
notificationKind: NotificationKind,
notificationProcessing: NotificationProcessing,
displayString: ?BSTR,
activityId: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.1'
pub extern "UIAutomationCore" fn UiaRaiseActiveTextPositionChangedEvent(
provider: ?*IRawElementProviderSimple,
textRange: ?*ITextRangeProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaAddEvent(
hnode: ?HUIANODE,
eventId: i32,
pCallback: ?*?UiaEventCallback,
scope: TreeScope,
pProperties: ?*i32,
cProperties: i32,
pRequest: ?*UiaCacheRequest,
phEvent: ?*?HUIAEVENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaRemoveEvent(
hEvent: ?HUIAEVENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaEventAddWindow(
hEvent: ?HUIAEVENT,
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaEventRemoveWindow(
hEvent: ?HUIAEVENT,
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn DockPattern_SetDockPosition(
hobj: ?HUIAPATTERNOBJECT,
dockPosition: DockPosition,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ExpandCollapsePattern_Collapse(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ExpandCollapsePattern_Expand(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn GridPattern_GetItem(
hobj: ?HUIAPATTERNOBJECT,
row: i32,
column: i32,
pResult: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn InvokePattern_Invoke(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn MultipleViewPattern_GetViewName(
hobj: ?HUIAPATTERNOBJECT,
viewId: i32,
ppStr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn MultipleViewPattern_SetCurrentView(
hobj: ?HUIAPATTERNOBJECT,
viewId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn RangeValuePattern_SetValue(
hobj: ?HUIAPATTERNOBJECT,
val: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ScrollItemPattern_ScrollIntoView(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ScrollPattern_Scroll(
hobj: ?HUIAPATTERNOBJECT,
horizontalAmount: ScrollAmount,
verticalAmount: ScrollAmount,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ScrollPattern_SetScrollPercent(
hobj: ?HUIAPATTERNOBJECT,
horizontalPercent: f64,
verticalPercent: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn SelectionItemPattern_AddToSelection(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn SelectionItemPattern_RemoveFromSelection(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn SelectionItemPattern_Select(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TogglePattern_Toggle(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TransformPattern_Move(
hobj: ?HUIAPATTERNOBJECT,
x: f64,
y: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TransformPattern_Resize(
hobj: ?HUIAPATTERNOBJECT,
width: f64,
height: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TransformPattern_Rotate(
hobj: ?HUIAPATTERNOBJECT,
degrees: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn ValuePattern_SetValue(
hobj: ?HUIAPATTERNOBJECT,
pVal: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn WindowPattern_Close(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn WindowPattern_SetWindowVisualState(
hobj: ?HUIAPATTERNOBJECT,
state: WindowVisualState,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn WindowPattern_WaitForInputIdle(
hobj: ?HUIAPATTERNOBJECT,
milliseconds: i32,
pResult: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_GetSelection(
hobj: ?HUIAPATTERNOBJECT,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_GetVisibleRanges(
hobj: ?HUIAPATTERNOBJECT,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_RangeFromChild(
hobj: ?HUIAPATTERNOBJECT,
hnodeChild: ?HUIANODE,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_RangeFromPoint(
hobj: ?HUIAPATTERNOBJECT,
point: UiaPoint,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_get_DocumentRange(
hobj: ?HUIAPATTERNOBJECT,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextPattern_get_SupportedTextSelection(
hobj: ?HUIAPATTERNOBJECT,
pRetVal: ?*SupportedTextSelection,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_Clone(
hobj: ?HUIATEXTRANGE,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_Compare(
hobj: ?HUIATEXTRANGE,
range: ?HUIATEXTRANGE,
pRetVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_CompareEndpoints(
hobj: ?HUIATEXTRANGE,
endpoint: TextPatternRangeEndpoint,
targetRange: ?HUIATEXTRANGE,
targetEndpoint: TextPatternRangeEndpoint,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_ExpandToEnclosingUnit(
hobj: ?HUIATEXTRANGE,
unit: TextUnit,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_GetAttributeValue(
hobj: ?HUIATEXTRANGE,
attributeId: i32,
pRetVal: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_FindAttribute(
hobj: ?HUIATEXTRANGE,
attributeId: i32,
val: VARIANT,
backward: BOOL,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_FindText(
hobj: ?HUIATEXTRANGE,
text: ?BSTR,
backward: BOOL,
ignoreCase: BOOL,
pRetVal: ?*?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_GetBoundingRectangles(
hobj: ?HUIATEXTRANGE,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_GetEnclosingElement(
hobj: ?HUIATEXTRANGE,
pRetVal: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_GetText(
hobj: ?HUIATEXTRANGE,
maxLength: i32,
pRetVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_Move(
hobj: ?HUIATEXTRANGE,
unit: TextUnit,
count: i32,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_MoveEndpointByUnit(
hobj: ?HUIATEXTRANGE,
endpoint: TextPatternRangeEndpoint,
unit: TextUnit,
count: i32,
pRetVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_MoveEndpointByRange(
hobj: ?HUIATEXTRANGE,
endpoint: TextPatternRangeEndpoint,
targetRange: ?HUIATEXTRANGE,
targetEndpoint: TextPatternRangeEndpoint,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_Select(
hobj: ?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_AddToSelection(
hobj: ?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_RemoveFromSelection(
hobj: ?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_ScrollIntoView(
hobj: ?HUIATEXTRANGE,
alignToTop: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn TextRange_GetChildren(
hobj: ?HUIATEXTRANGE,
pRetVal: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn ItemContainerPattern_FindItemByProperty(
hobj: ?HUIAPATTERNOBJECT,
hnodeStartAfter: ?HUIANODE,
propertyId: i32,
value: VARIANT,
pFound: ?*?HUIANODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn LegacyIAccessiblePattern_Select(
hobj: ?HUIAPATTERNOBJECT,
flagsSelect: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn LegacyIAccessiblePattern_DoDefaultAction(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn LegacyIAccessiblePattern_SetValue(
hobj: ?HUIAPATTERNOBJECT,
szValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn LegacyIAccessiblePattern_GetIAccessible(
hobj: ?HUIAPATTERNOBJECT,
pAccessible: ?*?*IAccessible,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn SynchronizedInputPattern_StartListening(
hobj: ?HUIAPATTERNOBJECT,
inputType: SynchronizedInputType,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn SynchronizedInputPattern_Cancel(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "UIAutomationCore" fn VirtualizedItemPattern_Realize(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaPatternRelease(
hobj: ?HUIAPATTERNOBJECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaTextRangeRelease(
hobj: ?HUIATEXTRANGE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaReturnRawElementProvider(
hwnd: ?HWND,
wParam: WPARAM,
lParam: LPARAM,
el: ?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaHostProviderFromHwnd(
hwnd: ?HWND,
ppProvider: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UIAutomationCore" fn UiaProviderForNonClient(
hwnd: ?HWND,
idObject: i32,
idChild: i32,
ppProvider: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UIAutomationCore" fn UiaIAccessibleFromProvider(
pProvider: ?*IRawElementProviderSimple,
dwFlags: u32,
ppAccessible: ?*?*IAccessible,
pvarChild: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UIAutomationCore" fn UiaProviderFromIAccessible(
pAccessible: ?*IAccessible,
idChild: i32,
dwFlags: u32,
ppProvider: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UIAutomationCore" fn UiaDisconnectAllProviders(
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UIAutomationCore" fn UiaDisconnectProvider(
pProvider: ?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "UIAutomationCore" fn UiaHasServerSideProvider(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (6)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const SERIALKEYS = thismodule.SERIALKEYSA;
pub const HIGHCONTRAST = thismodule.HIGHCONTRASTA;
pub const SOUNDSENTRY = thismodule.SOUNDSENTRYA;
pub const GetRoleText = thismodule.GetRoleTextA;
pub const GetStateText = thismodule.GetStateTextA;
pub const CreateStdAccessibleProxy = thismodule.CreateStdAccessibleProxyA;
},
.wide => struct {
pub const SERIALKEYS = thismodule.SERIALKEYSW;
pub const HIGHCONTRAST = thismodule.HIGHCONTRASTW;
pub const SOUNDSENTRY = thismodule.SOUNDSENTRYW;
pub const GetRoleText = thismodule.GetRoleTextW;
pub const GetStateText = thismodule.GetStateTextW;
pub const CreateStdAccessibleProxy = thismodule.CreateStdAccessibleProxyW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const SERIALKEYS = *opaque{};
pub const HIGHCONTRAST = *opaque{};
pub const SOUNDSENTRY = *opaque{};
pub const GetRoleText = *opaque{};
pub const GetStateText = *opaque{};
pub const CreateStdAccessibleProxy = *opaque{};
} else struct {
pub const SERIALKEYS = @compileError("'SERIALKEYS' requires that UNICODE be set to true or false in the root module");
pub const HIGHCONTRAST = @compileError("'HIGHCONTRAST' requires that UNICODE be set to true or false in the root module");
pub const SOUNDSENTRY = @compileError("'SOUNDSENTRY' requires that UNICODE be set to true or false in the root module");
pub const GetRoleText = @compileError("'GetRoleText' requires that UNICODE be set to true or false in the root module");
pub const GetStateText = @compileError("'GetStateText' requires that UNICODE be set to true or false in the root module");
pub const CreateStdAccessibleProxy = @compileError("'CreateStdAccessibleProxy' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (19)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BSTR = @import("../foundation.zig").BSTR;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HMENU = @import("../ui/windows_and_messaging.zig").HMENU;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IDispatch = @import("../system/ole_automation.zig").IDispatch;
const IUnknown = @import("../system/com.zig").IUnknown;
const LPARAM = @import("../foundation.zig").LPARAM;
const LRESULT = @import("../foundation.zig").LRESULT;
const POINT = @import("../foundation.zig").POINT;
const POINTER_INPUT_TYPE = @import("../ui/windows_and_messaging.zig").POINTER_INPUT_TYPE;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const SAFEARRAY = @import("../system/ole_automation.zig").SAFEARRAY;
const VARIANT = @import("../system/ole_automation.zig").VARIANT;
const WPARAM = @import("../foundation.zig").WPARAM;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "WINEVENTPROC")) { _ = WINEVENTPROC; }
if (@hasDecl(@This(), "LPFNLRESULTFROMOBJECT")) { _ = LPFNLRESULTFROMOBJECT; }
if (@hasDecl(@This(), "LPFNOBJECTFROMLRESULT")) { _ = LPFNOBJECTFROMLRESULT; }
if (@hasDecl(@This(), "LPFNACCESSIBLEOBJECTFROMWINDOW")) { _ = LPFNACCESSIBLEOBJECTFROMWINDOW; }
if (@hasDecl(@This(), "LPFNACCESSIBLEOBJECTFROMPOINT")) { _ = LPFNACCESSIBLEOBJECTFROMPOINT; }
if (@hasDecl(@This(), "LPFNCREATESTDACCESSIBLEOBJECT")) { _ = LPFNCREATESTDACCESSIBLEOBJECT; }
if (@hasDecl(@This(), "LPFNACCESSIBLECHILDREN")) { _ = LPFNACCESSIBLECHILDREN; }
if (@hasDecl(@This(), "UiaProviderCallback")) { _ = UiaProviderCallback; }
if (@hasDecl(@This(), "UiaEventCallback")) { _ = UiaEventCallback; }
@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/ui/accessibility.zig
|
const std = @import("std");
const stdx = @import("stdx");
const t = stdx.testing;
// Based on w3c specs. New keys are added at the end.
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
pub const KeyCode = enum(u8) {
Unknown = 0,
Backspace = 8,
Tab = 9,
Enter = 13,
Shift = 16,
ControlLeft = 17,
AltLeft = 18,
Pause = 19,
CapsLock = 20,
Escape = 27,
Space = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
ArrowUp = 37,
ArrowLeft = 38,
ArrowRight = 39,
ArrowDown = 40,
PrintScreen = 44,
Insert = 45,
Delete = 46,
Digit0 = 48,
Digit1 = 49,
Digit2 = 50,
Digit3 = 51,
Digit4 = 52,
Digit5 = 53,
Digit6 = 54,
Digit7 = 55,
Digit8 = 56,
Digit9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
Meta = 91,
ContextMenu = 93,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
F13 = 124,
F14 = 125,
F15 = 126,
F16 = 127,
F17 = 128,
F18 = 129,
F19 = 130,
F20 = 131,
F21 = 132,
F22 = 133,
F23 = 134,
F24 = 135,
ScrollLock = 145,
Semicolon = 186,
Equal = 187,
Comma = 188,
Minus = 189,
Period = 190,
Slash = 191,
Backquote = 192,
BracketLeft = 219,
Backslash = 220,
BracketRight = 221,
Quote = 222,
// Start adding new ones here. Start at a higher index if needed.
ControlRight = 223,
AltRight = 224,
};
const ShiftMask = 8;
const ControlMask = 4;
const AltMask = 2;
const MetaMask = 1;
const MaxCodes = 225;
const PrintableCharMap = b: {
var map: [MaxCodes][2]u8 = undefined;
const S = struct {
map: *[MaxCodes][2]u8,
fn set(self: *@This(), code: KeyCode, shift: bool, char: u8) void {
self.map[@enumToInt(code)][@boolToInt(shift)] = char;
}
fn setBoth(self: *@This(), code: KeyCode, char: u8) void {
self.map[@enumToInt(code)][0] = char;
self.map[@enumToInt(code)][1] = char;
}
};
// Default to 0.
var s = S{ .map = &map };
for (std.enums.values(KeyCode)) |code| {
s.set(code, false, 0);
s.set(code, true, 0);
}
s.set(.Digit1, true, '!');
s.set(.Digit2, true, '@');
s.set(.Digit3, true, '#');
s.set(.Digit4, true, '$');
s.set(.Digit5, true, '%');
s.set(.Digit6, true, '^');
s.set(.Digit7, true, '&');
s.set(.Digit8, true, '*');
s.set(.Digit9, true, '(');
s.set(.Digit0, true, ')');
s.set(.Period, false, '.');
s.set(.Period, true, '>');
s.set(.Comma, false, ',');
s.set(.Comma, true, '<');
s.set(.Slash, false, '/');
s.set(.Slash, true, '?');
s.set(.Semicolon, false, ';');
s.set(.Semicolon, true, ':');
s.set(.Quote, false, '\'');
s.set(.Quote, true, '"');
s.set(.BracketLeft, false, '[');
s.set(.BracketLeft, true, '{');
s.set(.BracketRight, false, ']');
s.set(.BracketRight, true, '}');
s.set(.Backslash, false, '\\');
s.set(.Backslash, true, '|');
s.set(.Backquote, false, '`');
s.set(.Backquote, true, '~');
s.set(.Minus, false, '-');
s.set(.Minus, true, '_');
s.set(.Equal, false, '=');
s.set(.Equal, true, '+');
s.setBoth(.Space, ' ');
s.setBoth(.Enter, '\n');
var i: u16 = @enumToInt(KeyCode.A);
while (i <= @enumToInt(KeyCode.Z)) : (i += 1) {
map[i][0] = std.ascii.toLower(i);
map[i][1] = i;
}
i = @enumToInt(KeyCode.Digit0);
while (i <= @enumToInt(KeyCode.Digit9)) : (i += 1) {
map[i][0] = i;
}
break :b map;
};
pub const KeyDownEvent = struct {
const Self = @This();
code: KeyCode,
// Keyboard modifiers.
mods: u8,
// Whether it's a repeated key down, pressed and held. Frequency depends on target platform settings.
is_repeat: bool,
pub fn initWithMods(code: KeyCode, mods: u8, is_repeat: bool) @This() {
return .{
.code = code,
.mods = mods,
.is_repeat = is_repeat,
};
}
pub fn init(code: KeyCode, is_repeat: bool, shift_pressed: bool, control_pressed: bool, alt_pressed: bool, meta_pressed: bool) Self {
var mods: u8 = 0;
if (shift_pressed) {
mods |= ShiftMask;
}
if (control_pressed) {
mods |= ControlMask;
}
if (alt_pressed) {
mods |= AltMask;
}
if (meta_pressed) {
mods |= MetaMask;
}
return .{
.code = code,
.mods = mods,
.is_repeat = is_repeat,
};
}
/// Returns the printable ascii char. Returns null if it's not a visible char.
pub fn getPrintChar(self: Self) ?u8 {
const shift_idx = @boolToInt((self.mods & ShiftMask) == ShiftMask);
const res = PrintableCharMap[@enumToInt(self.code)][shift_idx];
if (res != 0) return res else return null;
}
pub fn isShiftPressed(self: Self) bool {
return self.mods & ShiftMask > 0;
}
pub fn isControlPressed(self: Self) bool {
return self.mods & ControlMask > 0;
}
pub fn isAltPressed(self: Self) bool {
return self.mods & AltMask > 0;
}
pub fn isMetaPressed(self: Self) bool {
return self.mods & MetaMask > 0;
}
};
pub const KeyUpEvent = struct {
const Self = @This();
code: KeyCode,
// Keyboard modifiers.
mods: u8,
pub fn initWithMods(code: KeyCode, mods: u8) @This() {
return .{
.code = code,
.mods = mods,
};
}
pub fn init(code: KeyCode, shift_pressed: bool, control_pressed: bool, alt_pressed: bool, meta_pressed: bool) Self {
var mods: u8 = 0;
if (shift_pressed) {
mods |= ShiftMask;
}
if (control_pressed) {
mods |= ControlMask;
}
if (alt_pressed) {
mods |= AltMask;
}
if (meta_pressed) {
mods |= MetaMask;
}
return .{
.code = code,
.mods = mods,
};
}
/// Returns the printable ascii char. Returns null if it's not a visible char.
pub fn getPrintChar(self: Self) ?u8 {
const shift_idx = @boolToInt((self.mods & ShiftMask) == ShiftMask);
const res = PrintableCharMap[@enumToInt(self.code)][shift_idx];
if (res != 0) return res else return null;
}
pub fn isShiftPressed(self: Self) bool {
return self.mods & ShiftMask > 0;
}
pub fn isControlPressed(self: Self) bool {
return self.mods & ControlMask > 0;
}
pub fn isAltPressed(self: Self) bool {
return self.mods & AltMask > 0;
}
pub fn isMetaPressed(self: Self) bool {
return self.mods & MetaMask > 0;
}
};
test "KeyUpEvent.getPrintChar" {
const S = struct {
fn case(code: KeyCode, shift: bool, expected: ?u8) !void {
const mods: u8 = if (shift) ShiftMask else 0;
if (expected == null) {
try t.eq(KeyUpEvent.initWithMods(code, mods).getPrintChar(), expected);
} else {
try t.eq(KeyUpEvent.initWithMods(code, mods).getPrintChar().?, expected.?);
}
}
};
const case = S.case;
try case(.A, false, 'a');
try case(.A, true, 'A');
try case(.Z, false, 'z');
try case(.Z, true, 'Z');
try case(.Digit1, false, '1');
try case(.Digit1, true, '!');
try case(.Digit2, false, '2');
try case(.Digit2, true, '@');
try case(.Digit3, false, '3');
try case(.Digit3, true, '#');
try case(.Digit4, false, '4');
try case(.Digit4, true, '$');
try case(.Digit5, false, '5');
try case(.Digit5, true, '%');
try case(.Digit6, false, '6');
try case(.Digit6, true, '^');
try case(.Digit7, false, '7');
try case(.Digit7, true, '&');
try case(.Digit8, false, '8');
try case(.Digit8, true, '*');
try case(.Digit9, false, '9');
try case(.Digit9, true, '(');
try case(.Digit0, false, '0');
try case(.Digit0, true, ')');
try case(.Period, false, '.');
try case(.Period, true, '>');
try case(.Comma, false, ',');
try case(.Comma, true, '<');
try case(.Slash, false, '/');
try case(.Slash, true, '?');
try case(.Semicolon, false, ';');
try case(.Semicolon, true, ':');
try case(.Quote, false, '\'');
try case(.Quote, true, '"');
try case(.BracketLeft, false, '[');
try case(.BracketLeft, true, '{');
try case(.BracketRight, false, ']');
try case(.BracketRight, true, '}');
try case(.Backslash, false, '\\');
try case(.Backslash, true, '|');
try case(.Backquote, false, '`');
try case(.Backquote, true, '~');
try case(.Minus, false, '-');
try case(.Minus, true, '_');
try case(.Equal, false, '=');
try case(.Equal, true, '+');
try case(.Space, false, ' ');
try case(.Space, true, ' ');
try case(.Backspace, false, null);
try case(.Enter, false, '\n');
}
|
platform/keyboard.zig
|
const std = @import("std");
const Backend = @import("build_options").GraphicsBackend;
const stdx = @import("stdx");
const ds = stdx.ds;
const gl = @import("gl");
const vk = @import("vk");
const lyon = @import("lyon");
const Vec2 = stdx.math.Vec2;
const Vec4 = stdx.math.Vec4;
const graphics = @import("../../graphics.zig");
const gpu = graphics.gpu;
const gvk = graphics.vk;
const ImageId = graphics.ImageId;
const ImageTex = graphics.gpu.ImageTex;
const GLTextureId = gl.GLuint;
const Color = graphics.Color;
const Transform = graphics.transform.Transform;
const mesh = @import("mesh.zig");
const VertexData = mesh.VertexData;
const TexShaderVertex = mesh.TexShaderVertex;
const Mesh = mesh.Mesh;
const log = stdx.log.scoped(.batcher);
const NullId = std.math.maxInt(u32);
const ShaderType = enum(u3) {
Tex = 0,
Tex3D = 1,
Gradient = 2,
Plane = 3,
Wireframe = 4,
Custom = 5,
};
const PreFlushTask = struct {
cb: fn (ctx: ?*anyopaque) void,
ctx: ?*anyopaque,
};
/// The batcher should be the primary way for consumer to push draw data/calls. It is responsible for:
/// 1. Pushing various vertex/index data formats into a mesh buffer.
/// 2. Automatically ending the current batch command when necessary. eg. Change to shader, texture, mvp, or reaching a buffer limit.
pub const Batcher = struct {
pre_flush_tasks: std.ArrayList(PreFlushTask),
mesh: Mesh,
cmds: std.ArrayList(DrawCmd),
cmd_vert_start_idx: u32,
cmd_index_start_idx: u32,
/// Model view projection is kept until flush time to reduce redundant uniform uploads.
mvp: Transform,
/// It's useful to store the current texture associated with the current buffer data,
/// so a resize op can know whether to trigger a force flush.
cur_image_tex: ImageTex,
/// Keep track of the current shader used.
cur_shader_type: ShaderType,
inner: switch (Backend) {
.OpenGL => struct {
vert_buf_id: gl.GLuint,
index_buf_id: gl.GLuint,
pipelines: graphics.gl.Pipelines,
cur_gl_tex_id: GLTextureId,
},
.Vulkan => struct {
ctx: gvk.VkContext,
cur_cmd_buf: vk.VkCommandBuffer,
pipelines: gvk.Pipelines,
vert_buf: vk.VkBuffer,
vert_buf_mem: vk.VkDeviceMemory,
index_buf: vk.VkBuffer,
index_buf_mem: vk.VkDeviceMemory,
cur_tex_desc_set: vk.VkDescriptorSet,
host_vert_buf: [*]TexShaderVertex,
host_index_buf: [*]u16,
},
else => @compileError("unsupported"),
},
image_store: *graphics.gpu.ImageStore,
/// Vars for gradient shader.
start_pos: Vec2,
start_color: Color,
end_pos: Vec2,
end_color: Color,
const Self = @This();
/// Batcher owns vert_buf_id afterwards.
pub fn initGL(alloc: std.mem.Allocator, vert_buf_id: gl.GLuint, pipelines: graphics.gl.Pipelines, image_store: *graphics.gpu.ImageStore) Self {
var new = Self{
.mesh = Mesh.init(alloc),
.cmds = std.ArrayList(DrawCmd).init(alloc),
.cmd_vert_start_idx = 0,
.cmd_index_start_idx = 0,
.inner = .{
.pipelines = pipelines,
.vert_buf_id = vert_buf_id,
.index_buf_id = undefined,
.cur_gl_tex_id = undefined,
},
.pre_flush_tasks = std.ArrayList(PreFlushTask).init(alloc),
.mvp = undefined,
.cur_image_tex = .{
.image_id = NullId,
.tex_id = NullId,
},
.cur_shader_type = undefined,
.start_pos = undefined,
.start_color = undefined,
.end_pos = undefined,
.end_color = undefined,
.image_store = image_store,
};
// Generate buffers.
var buf_ids: [1]gl.GLuint = undefined;
gl.genBuffers(1, &buf_ids);
new.inner.index_buf_id = buf_ids[0];
return new;
}
pub fn initVK(alloc: std.mem.Allocator,
vert_buf: vk.VkBuffer, vert_buf_mem: vk.VkDeviceMemory, index_buf: vk.VkBuffer, index_buf_mem: vk.VkDeviceMemory,
vk_ctx: gvk.VkContext,
pipelines: gvk.Pipelines,
image_store: *graphics.gpu.ImageStore
) Self {
var new = Self{
.mesh = Mesh.init(alloc),
.cmds = std.ArrayList(DrawCmd).init(alloc),
.cmd_vert_start_idx = 0,
.cmd_index_start_idx = 0,
.pre_flush_tasks = std.ArrayList(PreFlushTask).init(alloc),
.mvp = undefined,
.cur_image_tex = .{
.image_id = NullId,
.tex_id = NullId,
},
.cur_shader_type = undefined,
.start_pos = undefined,
.start_color = undefined,
.end_pos = undefined,
.end_color = undefined,
.inner = .{
.ctx = vk_ctx,
.cur_cmd_buf = undefined,
.pipelines = pipelines,
.vert_buf = vert_buf,
.vert_buf_mem = vert_buf_mem,
.index_buf = index_buf,
.index_buf_mem = index_buf_mem,
.cur_tex_desc_set = undefined,
.host_vert_buf = undefined,
.host_index_buf = undefined,
},
.image_store = image_store,
};
var res = vk.mapMemory(new.inner.ctx.device, new.inner.vert_buf_mem, 0, 40 * 10000, 0, @ptrCast([*c]?*anyopaque, &new.inner.host_vert_buf));
vk.assertSuccess(res);
res = vk.mapMemory(new.inner.ctx.device, new.inner.index_buf_mem, 0, 2 * 10000 * 3, 0, @ptrCast([*c]?*anyopaque, &new.inner.host_index_buf));
vk.assertSuccess(res);
return new;
}
pub fn deinit(self: Self) void {
self.pre_flush_tasks.deinit();
self.mesh.deinit();
self.cmds.deinit();
switch (Backend) {
.OpenGL => {
const bufs = [_]gl.GLuint{ self.inner.vert_buf_id, self.inner.index_buf_id };
gl.deleteBuffers(2, &bufs);
},
.Vulkan => {
const device = self.inner.ctx.device;
vk.destroyBuffer(device, self.inner.vert_buf, null);
vk.freeMemory(device, self.inner.vert_buf_mem, null);
vk.destroyBuffer(device, self.inner.index_buf, null);
vk.freeMemory(device, self.inner.index_buf_mem, null);
},
else => {},
}
}
/// Queue a task to run before the next flush.
pub fn addNextPreFlushTask(self: *Self, ctx: ?*anyopaque, cb: fn (?*anyopaque) void) void {
self.pre_flush_tasks.append(.{
.ctx = ctx,
.cb = cb,
}) catch @panic("error");
}
/// Begins the tex shader. Will flush previous batched command.
pub fn beginTex(self: *Self, image: ImageTex) void {
if (self.cur_shader_type != .Tex) {
self.endCmd();
self.cur_shader_type = .Tex;
self.setTexture(image);
return;
}
self.setTexture(image);
}
pub fn beginTex3D(self: *Self, image: ImageTex) void {
if (self.cur_shader_type != .Tex3D) {
self.endCmd();
self.cur_shader_type = .Tex3D;
self.setTexture(image);
return;
}
self.setTexture(image);
}
pub fn beginWireframe(self: *Self) void {
if (self.cur_shader_type != .Wireframe) {
self.endCmd();
self.cur_shader_type = .Wireframe;
}
}
/// Begins the gradient shader. Will flush previous batched command.
pub fn beginGradient(self: *Self, start_pos: Vec2, start_color: Color, end_pos: Vec2, end_color: Color) void {
// Always flush the previous.
self.endCmd();
self.start_pos = start_pos;
self.start_color = start_color;
self.end_pos = end_pos;
self.end_color = end_color;
self.cur_shader_type = .Gradient;
}
// TODO: we can use sample2d arrays and pass active tex ids in vertex data to further reduce number of flushes.
pub fn beginTexture(self: *Self, image: ImageTex) void {
self.setTexture(image);
}
inline fn setTexture(self: *Self, image: ImageTex) void {
if (self.cur_image_tex.tex_id != image.tex_id) {
self.endCmd();
self.cur_image_tex = image;
switch (Backend) {
.OpenGL => {
self.inner.cur_gl_tex_id = self.image_store.getTexture(image.tex_id).inner.tex_id;
},
.Vulkan => {
self.inner.cur_tex_desc_set = self.image_store.getTexture(image.tex_id).inner.desc_set;
},
else => {},
}
}
}
pub fn resetState(self: *Self, tex: ImageTex) void {
self.cur_image_tex = tex;
self.cur_shader_type = .Tex;
self.cmd_vert_start_idx = 0;
self.cmd_index_start_idx = 0;
self.inner.cur_gl_tex_id = self.image_store.getTexture(tex.tex_id).inner.tex_id;
self.mesh.reset();
}
pub fn resetStateVK(self: *Self, image_tex: ImageTex, image_idx: u32, frame_idx: u32, clear_color: Color) void {
_ = frame_idx;
self.inner.cur_cmd_buf = self.inner.ctx.cmd_bufs[image_idx];
self.inner.cur_tex_desc_set = self.image_store.getTexture(image_tex.tex_id).inner.desc_set;
self.cur_image_tex = image_tex;
self.cur_shader_type = .Tex;
self.cmd_vert_start_idx = 0;
self.cmd_index_start_idx = 0;
self.mesh.reset();
const cmd_buf = self.inner.cur_cmd_buf;
gvk.command.beginCommandBuffer(cmd_buf);
gvk.command.beginRenderPass(cmd_buf, self.inner.ctx.pass, self.inner.ctx.framebuffers[image_idx], self.inner.ctx.framebuffer_size, clear_color);
var offset: vk.VkDeviceSize = 0;
vk.cmdBindVertexBuffers(cmd_buf, 0, 1, &self.inner.vert_buf, &offset);
vk.cmdBindIndexBuffer(cmd_buf, self.inner.index_buf, 0, vk.VK_INDEX_TYPE_UINT16);
}
pub fn endFrameVK(self: *Self) void {
const cmd_buf = self.inner.cur_cmd_buf;
gvk.command.endRenderPass(cmd_buf);
gvk.command.endCommandBuffer(cmd_buf);
// Send all the mesh data at once.
// TODO: This should work with zero copy if mesh is aware of the buffer pointer.
// TODO: Buffer should be reallocated if it's not big enough.
// TODO: The buffers should be large enough to hold 2 frames worth of data and writing data should use an offset from the previous frame.
// Copy vertex buffer.
std.mem.copy(TexShaderVertex, self.inner.host_vert_buf[0..self.mesh.cur_vert_buf_size], self.mesh.vert_buf[0..self.mesh.cur_vert_buf_size]);
// Copy index buffer.
std.mem.copy(u16, self.inner.host_index_buf[0..self.mesh.cur_index_buf_size], self.mesh.index_buf[0..self.mesh.cur_index_buf_size]);
}
pub fn beginMvp(self: *Self, mvp: Transform) void {
// Always flush the previous.
self.endCmd();
self.mvp = mvp;
}
pub fn ensureUnusedBuffer(self: *Self, vert_inc: usize, index_inc: usize) bool {
return self.mesh.ensureUnusedBuffer(vert_inc, index_inc);
}
/// Push a batch of vertices and indexes where index 0 refers to the first vertex.
pub fn pushVertIdxBatch(self: *Self, verts: []const Vec2, idxes: []const u16, color: Color) void {
var gpu_vert: TexShaderVertex = undefined;
gpu_vert.setColor(color);
const vert_offset_id = self.mesh.getNextIndexId();
for (verts) |v| {
gpu_vert.setXY(v.x, v.y);
gpu_vert.setUV(0, 0);
_ = self.mesh.addVertex(&gpu_vert);
}
for (idxes) |i| {
self.mesh.addIndex(vert_offset_id + i);
}
}
// Caller must check if there is enough buffer space prior.
pub fn pushLyonVertexData(self: *Self, data: *lyon.VertexData, color: Color) void {
var vert: TexShaderVertex = undefined;
vert.setColor(color);
const vert_offset_id = self.mesh.getNextIndexId();
for (data.vertex_buf[0..data.vertex_len]) |pos| {
vert.setXY(pos.x, pos.y);
vert.setUV(0, 0);
_ = self.mesh.addVertex(&vert);
}
for (data.index_buf[0..data.index_len]) |id| {
self.mesh.addIndex(vert_offset_id + id);
}
}
// Caller must check if there is enough buffer space prior.
pub fn pushVertexData(self: *Self, comptime num_verts: usize, comptime num_indices: usize, data: *VertexData(num_verts, num_indices)) void {
self.mesh.addVertexData(num_verts, num_indices, data);
}
pub fn pushMeshData(self: *Self, verts: []const TexShaderVertex, indexes: []const u16) void {
if (!self.ensureUnusedBuffer(verts.len, indexes.len)) {
self.endCmd();
}
const vert_start = self.mesh.addVertices(verts);
self.mesh.addDeltaIndices(vert_start, indexes);
}
pub fn endCmdForce(self: *Self) void {
// Run pre flush callbacks.
if (self.pre_flush_tasks.items.len > 0) {
for (self.pre_flush_tasks.items) |it| {
it.cb(it.ctx);
}
self.pre_flush_tasks.clearRetainingCapacity();
}
self.pushDrawCall();
switch (Backend) {
.OpenGL => {
self.mesh.reset();
},
.Vulkan => {
self.cmd_vert_start_idx = self.mesh.cur_vert_buf_size;
self.cmd_index_start_idx = self.mesh.cur_index_buf_size;
},
else => {},
}
}
pub fn endCmd(self: *Self) void {
if (self.mesh.cur_index_buf_size > self.cmd_index_start_idx) {
self.endCmdForce();
}
}
/// OpenGL immediately flushes with drawElements.
/// Vulkan records the draw command, flushed by endFrameVK.
fn pushDrawCall(self: *Self) void {
switch (Backend) {
.OpenGL => {
switch (self.cur_shader_type) {
.Tex => {
self.inner.pipelines.tex.bind(self.mvp.mat, self.inner.cur_gl_tex_id);
// Recall how to pull data from the buffer for shader.
gl.bindVertexArray(self.inner.pipelines.tex.shader.vao_id);
},
.Gradient => {
self.inner.pipelines.gradient.bind(self.mvp.mat, self.start_pos, self.start_color, self.end_pos, self.end_color);
// Recall how to pull data from the buffer for shader.
gl.bindVertexArray(self.inner.pipelines.gradient.shader.vao_id);
},
.Custom => stdx.unsupported(),
}
const num_verts = self.mesh.cur_vert_buf_size;
const num_indexes = self.mesh.cur_index_buf_size;
// Update vertex buffer.
gl.bindBuffer(gl.GL_ARRAY_BUFFER, self.inner.vert_buf_id);
gl.bufferData(gl.GL_ARRAY_BUFFER, @intCast(c_long, num_verts * 10 * 4), self.mesh.vert_buf.ptr, gl.GL_DYNAMIC_DRAW);
// Update index buffer.
gl.bindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.inner.index_buf_id);
gl.bufferData(gl.GL_ELEMENT_ARRAY_BUFFER, @intCast(c_long, num_indexes * 2), self.mesh.index_buf.ptr, gl.GL_DYNAMIC_DRAW);
gl.drawElements(gl.GL_TRIANGLES, num_indexes, self.mesh.index_buffer_type, 0);
// Unbind vao.
gl.bindVertexArray(0);
},
.Vulkan => {
const cmd_buf = self.inner.cur_cmd_buf;
switch (self.cur_shader_type) {
.Tex3D => {
const pipeline = self.inner.pipelines.tex_pipeline;
vk.cmdBindPipeline(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline);
vk.cmdBindDescriptorSets(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.layout, 0, 1, &self.inner.cur_tex_desc_set, 0, null);
// It's expensive to update a uniform buffer all the time so use push constants.
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_VERTEX_BIT, 0, 16 * 4, &self.mvp.mat);
},
.Wireframe => {
const pipeline = self.inner.pipelines.wireframe_pipeline;
vk.cmdBindPipeline(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline);
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_VERTEX_BIT, 0, 16 * 4, &self.mvp.mat);
},
.Tex => {
const pipeline = self.inner.pipelines.tex_pipeline_2d;
vk.cmdBindPipeline(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline);
vk.cmdBindDescriptorSets(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.layout, 0, 1, &self.inner.cur_tex_desc_set, 0, null);
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_VERTEX_BIT, 0, 16 * 4, &self.mvp.mat);
},
.Gradient => {
const pipeline = self.inner.pipelines.gradient_pipeline_2d;
vk.cmdBindPipeline(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline);
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_VERTEX_BIT, 0, 16 * 4, &self.mvp.mat);
const data = GradientFragmentData{
.start_pos = self.start_pos,
.start_color = self.start_color.toFloatArray(),
.end_pos = self.end_pos,
.end_color = self.end_color.toFloatArray(),
};
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_FRAGMENT_BIT, 16 * 4, 4 * 12, &data);
},
.Plane => {
const pipeline = self.inner.pipelines.plane_pipeline;
vk.cmdBindPipeline(cmd_buf, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline);
vk.cmdPushConstants(cmd_buf, pipeline.layout, vk.VK_SHADER_STAGE_VERTEX_BIT, 0, 16 * 4, &self.mvp.mat);
},
else => stdx.unsupported(),
}
const num_indexes = self.mesh.cur_index_buf_size - self.cmd_index_start_idx;
vk.cmdDrawIndexed(cmd_buf, num_indexes, 1, self.cmd_index_start_idx, 0, 0);
},
else => stdx.unsupported(),
}
}
};
/// Currently not used.
const DrawCmd = struct {
vert_offset: u32,
idx_offset: u32,
};
/// Properties are ordered to have the same alignment in glsl.
const GradientFragmentData = struct {
start_color: [4]f32,
end_color: [4]f32,
start_pos: Vec2,
end_pos: Vec2,
};
|
graphics/src/backend/gpu/batcher.zig
|
pub const NEUTRAL = 0x00;
pub const DEFAULT = 0x01;
pub const SYS_DEFAULT = 0x02;
pub const CUSTOM_DEFAULT = 0x03;
pub const CUSTOM_UNSPECIFIED = 0x04;
pub const UI_CUSTOM_DEFAULT = 0x05;
pub const AFRIKAANS_SOUTH_AFRICA = 0x01;
pub const ALBANIAN_ALBANIA = 0x01;
pub const ALSATIAN_FRANCE = 0x01;
pub const AMHARIC_ETHIOPIA = 0x01;
pub const ARABIC_SAUDI_ARABIA = 0x01;
pub const ARABIC_IRAQ = 0x02;
pub const ARABIC_EGYPT = 0x03;
pub const ARABIC_LIBYA = 0x04;
pub const ARABIC_ALGERIA = 0x05;
pub const ARABIC_MOROCCO = 0x06;
pub const ARABIC_TUNISIA = 0x07;
pub const ARABIC_OMAN = 0x08;
pub const ARABIC_YEMEN = 0x09;
pub const ARABIC_SYRIA = 0x0a;
pub const ARABIC_JORDAN = 0x0b;
pub const ARABIC_LEBANON = 0x0c;
pub const ARABIC_KUWAIT = 0x0d;
pub const ARABIC_UAE = 0x0e;
pub const ARABIC_BAHRAIN = 0x0f;
pub const ARABIC_QATAR = 0x10;
pub const ARMENIAN_ARMENIA = 0x01;
pub const ASSAMESE_INDIA = 0x01;
pub const AZERI_LATIN = 0x01;
pub const AZERI_CYRILLIC = 0x02;
pub const AZERBAIJANI_AZERBAIJAN_LATIN = 0x01;
pub const AZERBAIJANI_AZERBAIJAN_CYRILLIC = 0x02;
pub const BANGLA_INDIA = 0x01;
pub const BANGLA_BANGLADESH = 0x02;
pub const BASHKIR_RUSSIA = 0x01;
pub const BASQUE_BASQUE = 0x01;
pub const BELARUSIAN_BELARUS = 0x01;
pub const BENGALI_INDIA = 0x01;
pub const BENGALI_BANGLADESH = 0x02;
pub const BOSNIAN_BOSNIA_HERZEGOVINA_LATIN = 0x05;
pub const BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC = 0x08;
pub const BRETON_FRANCE = 0x01;
pub const BULGARIAN_BULGARIA = 0x01;
pub const CATALAN_CATALAN = 0x01;
pub const CENTRAL_KURDISH_IRAQ = 0x01;
pub const CHEROKEE_CHEROKEE = 0x01;
pub const CHINESE_TRADITIONAL = 0x01;
pub const CHINESE_SIMPLIFIED = 0x02;
pub const CHINESE_HONGKONG = 0x03;
pub const CHINESE_SINGAPORE = 0x04;
pub const CHINESE_MACAU = 0x05;
pub const CORSICAN_FRANCE = 0x01;
pub const CZECH_CZECH_REPUBLIC = 0x01;
pub const CROATIAN_CROATIA = 0x01;
pub const CROATIAN_BOSNIA_HERZEGOVINA_LATIN = 0x04;
pub const DANISH_DENMARK = 0x01;
pub const DARI_AFGHANISTAN = 0x01;
pub const DIVEHI_MALDIVES = 0x01;
pub const DUTCH = 0x01;
pub const DUTCH_BELGIAN = 0x02;
pub const ENGLISH_US = 0x01;
pub const ENGLISH_UK = 0x02;
pub const ENGLISH_AUS = 0x03;
pub const ENGLISH_CAN = 0x04;
pub const ENGLISH_NZ = 0x05;
pub const ENGLISH_EIRE = 0x06;
pub const ENGLISH_SOUTH_AFRICA = 0x07;
pub const ENGLISH_JAMAICA = 0x08;
pub const ENGLISH_CARIBBEAN = 0x09;
pub const ENGLISH_BELIZE = 0x0a;
pub const ENGLISH_TRINIDAD = 0x0b;
pub const ENGLISH_ZIMBABWE = 0x0c;
pub const ENGLISH_PHILIPPINES = 0x0d;
pub const ENGLISH_INDIA = 0x10;
pub const ENGLISH_MALAYSIA = 0x11;
pub const ENGLISH_SINGAPORE = 0x12;
pub const ESTONIAN_ESTONIA = 0x01;
pub const FAEROESE_FAROE_ISLANDS = 0x01;
pub const FILIPINO_PHILIPPINES = 0x01;
pub const FINNISH_FINLAND = 0x01;
pub const FRENCH = 0x01;
pub const FRENCH_BELGIAN = 0x02;
pub const FRENCH_CANADIAN = 0x03;
pub const FRENCH_SWISS = 0x04;
pub const FRENCH_LUXEMBOURG = 0x05;
pub const FRENCH_MONACO = 0x06;
pub const FRISIAN_NETHERLANDS = 0x01;
pub const FULAH_SENEGAL = 0x02;
pub const GALICIAN_GALICIAN = 0x01;
pub const GEORGIAN_GEORGIA = 0x01;
pub const GERMAN = 0x01;
pub const GERMAN_SWISS = 0x02;
pub const GERMAN_AUSTRIAN = 0x03;
pub const GERMAN_LUXEMBOURG = 0x04;
pub const GERMAN_LIECHTENSTEIN = 0x05;
pub const GREEK_GREECE = 0x01;
pub const GREENLANDIC_GREENLAND = 0x01;
pub const GUJARATI_INDIA = 0x01;
pub const HAUSA_NIGERIA_LATIN = 0x01;
pub const HAWAIIAN_US = 0x01;
pub const HEBREW_ISRAEL = 0x01;
pub const HINDI_INDIA = 0x01;
pub const HUNGARIAN_HUNGARY = 0x01;
pub const ICELANDIC_ICELAND = 0x01;
pub const IGBO_NIGERIA = 0x01;
pub const INDONESIAN_INDONESIA = 0x01;
pub const INUKTITUT_CANADA = 0x01;
pub const INUKTITUT_CANADA_LATIN = 0x02;
pub const IRISH_IRELAND = 0x02;
pub const ITALIAN = 0x01;
pub const ITALIAN_SWISS = 0x02;
pub const JAPANESE_JAPAN = 0x01;
pub const KANNADA_INDIA = 0x01;
pub const KASHMIRI_SASIA = 0x02;
pub const KASHMIRI_INDIA = 0x02;
pub const KAZAK_KAZAKHSTAN = 0x01;
pub const KHMER_CAMBODIA = 0x01;
pub const KICHE_GUATEMALA = 0x01;
pub const KINYARWANDA_RWANDA = 0x01;
pub const KONKANI_INDIA = 0x01;
pub const KOREAN = 0x01;
pub const KYRGYZ_KYRGYZSTAN = 0x01;
pub const LAO_LAO = 0x01;
pub const LATVIAN_LATVIA = 0x01;
pub const LITHUANIAN = 0x01;
pub const LOWER_SORBIAN_GERMANY = 0x02;
pub const LUXEMBOURGISH_LUXEMBOURG = 0x01;
pub const MACEDONIAN_MACEDONIA = 0x01;
pub const MALAY_MALAYSIA = 0x01;
pub const MALAY_BRUNEI_DARUSSALAM = 0x02;
pub const MALAYALAM_INDIA = 0x01;
pub const MALTESE_MALTA = 0x01;
pub const MAORI_NEW_ZEALAND = 0x01;
pub const MAPUDUNGUN_CHILE = 0x01;
pub const MARATHI_INDIA = 0x01;
pub const MOHAWK_MOHAWK = 0x01;
pub const MONGOLIAN_CYRILLIC_MONGOLIA = 0x01;
pub const MONGOLIAN_PRC = 0x02;
pub const NEPALI_INDIA = 0x02;
pub const NEPALI_NEPAL = 0x01;
pub const NORWEGIAN_BOKMAL = 0x01;
pub const NORWEGIAN_NYNORSK = 0x02;
pub const OCCITAN_FRANCE = 0x01;
pub const ODIA_INDIA = 0x01;
pub const ORIYA_INDIA = 0x01;
pub const PASHTO_AFGHANISTAN = 0x01;
pub const PERSIAN_IRAN = 0x01;
pub const POLISH_POLAND = 0x01;
pub const PORTUGUESE = 0x02;
pub const PORTUGUESE_BRAZILIAN = 0x01;
pub const PULAR_SENEGAL = 0x02;
pub const PUNJABI_INDIA = 0x01;
pub const PUNJABI_PAKISTAN = 0x02;
pub const QUECHUA_BOLIVIA = 0x01;
pub const QUECHUA_ECUADOR = 0x02;
pub const QUECHUA_PERU = 0x03;
pub const ROMANIAN_ROMANIA = 0x01;
pub const ROMANSH_SWITZERLAND = 0x01;
pub const RUSSIAN_RUSSIA = 0x01;
pub const SAKHA_RUSSIA = 0x01;
pub const SAMI_NORTHERN_NORWAY = 0x01;
pub const SAMI_NORTHERN_SWEDEN = 0x02;
pub const SAMI_NORTHERN_FINLAND = 0x03;
pub const SAMI_LULE_NORWAY = 0x04;
pub const SAMI_LULE_SWEDEN = 0x05;
pub const SAMI_SOUTHERN_NORWAY = 0x06;
pub const SAMI_SOUTHERN_SWEDEN = 0x07;
pub const SAMI_SKOLT_FINLAND = 0x08;
pub const SAMI_INARI_FINLAND = 0x09;
pub const SANSKRIT_INDIA = 0x01;
pub const SCOTTISH_GAELIC = 0x01;
pub const SERBIAN_BOSNIA_HERZEGOVINA_LATIN = 0x06;
pub const SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC = 0x07;
pub const SERBIAN_MONTENEGRO_LATIN = 0x0b;
pub const SERBIAN_MONTENEGRO_CYRILLIC = 0x0c;
pub const SERBIAN_SERBIA_LATIN = 0x09;
pub const SERBIAN_SERBIA_CYRILLIC = 0x0a;
pub const SERBIAN_CROATIA = 0x01;
pub const SERBIAN_LATIN = 0x02;
pub const SERBIAN_CYRILLIC = 0x03;
pub const SINDHI_INDIA = 0x01;
pub const SINDHI_PAKISTAN = 0x02;
pub const SINDHI_AFGHANISTAN = 0x02;
pub const SINHALESE_SRI_LANKA = 0x01;
pub const SOTHO_NORTHERN_SOUTH_AFRICA = 0x01;
pub const SLOVAK_SLOVAKIA = 0x01;
pub const SLOVENIAN_SLOVENIA = 0x01;
pub const SPANISH = 0x01;
pub const SPANISH_MEXICAN = 0x02;
pub const SPANISH_MODERN = 0x03;
pub const SPANISH_GUATEMALA = 0x04;
pub const SPANISH_COSTA_RICA = 0x05;
pub const SPANISH_PANAMA = 0x06;
pub const SPANISH_DOMINICAN_REPUBLIC = 0x07;
pub const SPANISH_VENEZUELA = 0x08;
pub const SPANISH_COLOMBIA = 0x09;
pub const SPANISH_PERU = 0x0a;
pub const SPANISH_ARGENTINA = 0x0b;
pub const SPANISH_ECUADOR = 0x0c;
pub const SPANISH_CHILE = 0x0d;
pub const SPANISH_URUGUAY = 0x0e;
pub const SPANISH_PARAGUAY = 0x0f;
pub const SPANISH_BOLIVIA = 0x10;
pub const SPANISH_EL_SALVADOR = 0x11;
pub const SPANISH_HONDURAS = 0x12;
pub const SPANISH_NICARAGUA = 0x13;
pub const SPANISH_PUERTO_RICO = 0x14;
pub const SPANISH_US = 0x15;
pub const SWAHILI_KENYA = 0x01;
pub const SWEDISH = 0x01;
pub const SWEDISH_FINLAND = 0x02;
pub const SYRIAC_SYRIA = 0x01;
pub const TAJIK_TAJIKISTAN = 0x01;
pub const TAMAZIGHT_ALGERIA_LATIN = 0x02;
pub const TAMAZIGHT_MOROCCO_TIFINAGH = 0x04;
pub const TAMIL_INDIA = 0x01;
pub const TAMIL_SRI_LANKA = 0x02;
pub const TATAR_RUSSIA = 0x01;
pub const TELUGU_INDIA = 0x01;
pub const THAI_THAILAND = 0x01;
pub const TIBETAN_PRC = 0x01;
pub const TIGRIGNA_ERITREA = 0x02;
pub const TIGRINYA_ERITREA = 0x02;
pub const TIGRINYA_ETHIOPIA = 0x01;
pub const TSWANA_BOTSWANA = 0x02;
pub const TSWANA_SOUTH_AFRICA = 0x01;
pub const TURKISH_TURKEY = 0x01;
pub const TURKMEN_TURKMENISTAN = 0x01;
pub const UIGHUR_PRC = 0x01;
pub const UKRAINIAN_UKRAINE = 0x01;
pub const UPPER_SORBIAN_GERMANY = 0x01;
pub const URDU_PAKISTAN = 0x01;
pub const URDU_INDIA = 0x02;
pub const UZBEK_LATIN = 0x01;
pub const UZBEK_CYRILLIC = 0x02;
pub const VALENCIAN_VALENCIA = 0x02;
pub const VIETNAMESE_VIETNAM = 0x01;
pub const WELSH_UNITED_KINGDOM = 0x01;
pub const WOLOF_SENEGAL = 0x01;
pub const XHOSA_SOUTH_AFRICA = 0x01;
pub const YAKUT_RUSSIA = 0x01;
pub const YI_PRC = 0x01;
pub const YORUBA_NIGERIA = 0x01;
pub const ZULU_SOUTH_AFRICA = 0x01;
|
lib/std/os/windows/sublang.zig
|
const std = @import("std");
const testing = std.testing;
const ArrayList = std.ArrayList;
const global_allocator = std.debug.global_allocator;
fn concatT(comptime T: type) type {
return struct {
const Self = @This();
const Iterator = struct {
iter1: ArrayList(T).Iterator,
iter2: ArrayList(T).Iterator,
end1: bool,
end2: bool,
pub fn next(self: *Iterator) ?T {
var a: ?T = null;
if (!self.end1) {
a = self.iter1.next();
if (a == null) {
self.end1 = true;
a = self.iter2.next();
if (a == null) {
self.end2 = true;
}
}
} else if (!self.end2) {
a = self.iter2.next();
if (a == null) {
self.end2 = true;
}
}
return a;
}
};
pub fn init() Self {
return Self{};
}
pub fn iterator(self: *Self, iter1: ArrayList(T).Iterator, iter2: ArrayList(T).Iterator) Iterator {
return Iterator{
.iter1 = iter1,
.iter2 = iter2,
.end1 = false,
.end2 = false,
};
}
};
}
fn elemOf(comptime A: type) type { return std.meta.Child(A.Slice); }
fn concat(list1: var, list2: var) concatT(elemOf(@typeOf(list1))).Iterator {
return concatT(elemOf(@typeOf(list1))).init().iterator(list1.iterator(), list2.iterator());
}
test "concat.non_empty" {
var list1 = std.ArrayList(i32).init(global_allocator);
defer list1.deinit();
var list2 = std.ArrayList(i32).init(global_allocator);
defer list2.deinit();
try list1.appendSlice([_]i32{1,2,3});
try list2.appendSlice([_]i32{4,5});
var iter = concat(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next().? == 3);
testing.expect(iter.next().? == 4);
testing.expect(iter.next().? == 5);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "concat.first_empty" {
var list1 = std.ArrayList(i32).init(global_allocator);
defer list1.deinit();
var list2 = std.ArrayList(i32).init(global_allocator);
defer list2.deinit();
try list1.appendSlice([_]i32{});
try list2.appendSlice([_]i32{1,2});
var iter = concat(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "concat.second_empty" {
var list1 = std.ArrayList(i32).init(global_allocator);
defer list1.deinit();
var list2 = std.ArrayList(i32).init(global_allocator);
defer list2.deinit();
try list1.appendSlice([_]i32{1});
try list2.appendSlice([_]i32{});
var iter = concat(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
|
src/concat.zig
|
const fmath = @import("index.zig");
const expo2 = @import("_expo2.zig").expo2;
pub fn cosh(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(coshf, x),
f64 => @inlineCall(coshd, x),
else => @compileError("cosh not implemented for " ++ @typeName(T)),
}
}
// cosh(x) = (exp(x) + 1 / exp(x)) / 2
// = 1 + 0.5 * (exp(x) - 1) * (exp(x) - 1) / exp(x)
// = 1 + (x * x) / 2 + o(x^4)
fn coshf(x: f32) -> f32 {
const u = @bitCast(u32, x);
const ux = u & 0x7FFFFFFF;
const ax = @bitCast(f32, ux);
// |x| < log(2)
if (ux < 0x3F317217) {
if (ux < 0x3F800000 - (12 << 23)) {
fmath.raiseOverflow();
return 1.0;
}
const t = fmath.expm1(ax);
return 1 + t * t / (2 * (1 + t));
}
// |x| < log(FLT_MAX)
if (ux < 0x42B17217) {
const t = fmath.exp(ax);
return 0.5 * (t + 1 / t);
}
// |x| > log(FLT_MAX) or nan
expo2(ax)
}
fn coshd(x: f64) -> f64 {
const u = @bitCast(u64, x);
const w = u32(u >> 32);
const ax = @bitCast(f64, u & (@maxValue(u64) >> 1));
// |x| < log(2)
if (w < 0x3FE62E42) {
if (w < 0x3FF00000 - (26 << 20)) {
if (x != 0) {
fmath.raiseInexact();
}
return 1.0;
}
const t = fmath.expm1(ax);
return 1 + t * t / (2 * (1 + t));
}
// |x| < log(DBL_MAX)
if (w < 0x40862E42) {
const t = fmath.exp(ax);
// NOTE: If x > log(0x1p26) then 1/t is not required.
return 0.5 * (t + 1 / t);
}
// |x| > log(CBL_MAX) or nan
expo2(ax)
}
test "cosh" {
fmath.assert(cosh(f32(1.5)) == coshf(1.5));
fmath.assert(cosh(f64(1.5)) == coshd(1.5));
}
test "coshf" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, coshf(0.0), 1.0, epsilon));
fmath.assert(fmath.approxEq(f32, coshf(0.2), 1.020067, epsilon));
fmath.assert(fmath.approxEq(f32, coshf(0.8923), 1.425225, epsilon));
fmath.assert(fmath.approxEq(f32, coshf(1.5), 2.352410, epsilon));
}
test "coshd" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, coshd(0.0), 1.0, epsilon));
fmath.assert(fmath.approxEq(f64, coshd(0.2), 1.020067, epsilon));
fmath.assert(fmath.approxEq(f64, coshd(0.8923), 1.425225, epsilon));
fmath.assert(fmath.approxEq(f64, coshd(1.5), 2.352410, epsilon));
}
|
src/cosh.zig
|
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const os = std.os;
const target = std.Target.current;
const is_linux = target.os.tag == .linux;
const config = @import("config.zig");
const log = std.log.scoped(.message_bus);
const vsr = @import("vsr.zig");
const Header = vsr.Header;
const RingBuffer = @import("ring_buffer.zig").RingBuffer;
const IO = @import("io.zig").IO;
const MessagePool = @import("message_pool.zig").MessagePool;
const Message = MessagePool.Message;
const SendQueue = RingBuffer(*Message, config.connection_send_queue_max);
pub const MessageBusReplica = MessageBusImpl(.replica);
pub const MessageBusClient = MessageBusImpl(.client);
const ProcessType = enum { replica, client };
fn MessageBusImpl(comptime process_type: ProcessType) type {
return struct {
const Self = @This();
pool: MessagePool,
io: *IO,
cluster: u32,
configuration: []std.net.Address,
process: switch (process_type) {
.replica => struct {
replica: u8,
/// The file descriptor for the process on which to accept connections.
accept_fd: os.socket_t,
accept_completion: IO.Completion = undefined,
/// The connection reserved for the currently in progress accept operation.
/// This is non-null exactly when an accept operation is submitted.
accept_connection: ?*Connection = null,
/// Map from client id to the currently active connection for that client.
/// This is used to make lookup of client connections when sending messages
/// efficient and to ensure old client connections are dropped if a new one
/// is established.
clients: std.AutoHashMapUnmanaged(u128, *Connection) = .{},
},
.client => void,
},
/// The callback to be called when a message is received. Use set_on_message() to set
/// with type safety for the context pointer.
on_message_callback: ?fn (context: ?*c_void, message: *Message) void = null,
on_message_context: ?*c_void = null,
/// This slice is allocated with a fixed size in the init function and never reallocated.
connections: []Connection,
/// Number of connections currently in use (i.e. connection.peer != .none).
connections_used: usize = 0,
/// Map from replica index to the currently active connection for that replica, if any.
/// The connection for the process replica if any will always be null.
replicas: []?*Connection,
/// The number of outgoing `connect()` attempts for a given replica:
/// Reset to zero after a successful `on_connect()`.
replicas_connect_attempts: []u64,
/// Used to apply jitter when calculating exponential backoff:
/// Seeded with the process' replica index or client ID.
prng: std.rand.DefaultPrng,
/// Initialize the MessageBus for the given cluster, configuration and replica/client process.
pub fn init(
allocator: *mem.Allocator,
cluster: u32,
configuration: []std.net.Address,
process: switch (process_type) {
.replica => u8,
.client => u128,
},
io: *IO,
) !Self {
// There must be enough connections for all replicas and at least one client.
assert(config.connections_max > configuration.len);
const connections = try allocator.alloc(Connection, config.connections_max);
errdefer allocator.free(connections);
mem.set(Connection, connections, .{});
const replicas = try allocator.alloc(?*Connection, configuration.len);
errdefer allocator.free(replicas);
mem.set(?*Connection, replicas, null);
const replicas_connect_attempts = try allocator.alloc(u64, configuration.len);
errdefer allocator.free(replicas_connect_attempts);
mem.set(u64, replicas_connect_attempts, 0);
const prng_seed = switch (process_type) {
.replica => process,
.client => @truncate(u64, process),
};
var bus: Self = .{
.pool = try MessagePool.init(allocator),
.io = io,
.cluster = cluster,
.configuration = configuration,
.process = switch (process_type) {
.replica => .{
.replica = process,
.accept_fd = try init_tcp(configuration[process]),
},
.client => {},
},
.connections = connections,
.replicas = replicas,
.replicas_connect_attempts = replicas_connect_attempts,
.prng = std.rand.DefaultPrng.init(prng_seed),
};
// Pre-allocate enough memory to hold all possible connections in the client map.
if (process_type == .replica) {
try bus.process.clients.ensureCapacity(allocator, config.connections_max);
}
return bus;
}
pub fn set_on_message(
bus: *Self,
comptime Context: type,
context: Context,
comptime on_message: fn (context: Context, message: *Message) void,
) void {
assert(bus.on_message_callback == null);
assert(bus.on_message_context == null);
bus.on_message_callback = struct {
fn wrapper(_context: ?*c_void, message: *Message) void {
on_message(@intToPtr(Context, @ptrToInt(_context)), message);
}
}.wrapper;
bus.on_message_context = context;
}
/// TODO This is required by the Client.
pub fn deinit(bus: *Self) void {}
fn init_tcp(address: std.net.Address) !os.socket_t {
const fd = try IO.openSocket(
address.any.family,
os.SOCK_STREAM,
os.IPPROTO_TCP,
);
errdefer os.close(fd);
const set = struct {
fn set(_fd: os.socket_t, level: u32, option: u32, value: c_int) !void {
try os.setsockopt(_fd, level, option, &mem.toBytes(value));
}
}.set;
// Set tcp recv buffer size
if (config.tcp_rcvbuf > 0) rcvbuf: {
if (is_linux) {
// Requires CAP_NET_ADMIN privilege (settle for SO_RCVBUF in case of an EPERM):
if (set(fd, os.SOL_SOCKET, os.SO_RCVBUFFORCE, config.tcp_rcvbuf)) |_| {
break :rcvbuf;
} else |err| switch (err) {
error.PermissionDenied => {},
else => |e| return e,
}
}
try set(fd, os.SOL_SOCKET, os.SO_RCVBUF, config.tcp_rcvbuf);
}
// Set tcp send buffer size
if (config.tcp_sndbuf > 0) sndbuf: {
if (is_linux) {
// Requires CAP_NET_ADMIN privilege (settle for SO_SNDBUF in case of an EPERM):
if (set(fd, os.SOL_SOCKET, os.SO_SNDBUFFORCE, config.tcp_sndbuf)) |_| {
break :sndbuf;
} else |err| switch (err) {
error.PermissionDenied => {},
else => |e| return e,
}
}
try set(fd, os.SOL_SOCKET, os.SO_SNDBUF, config.tcp_sndbuf);
}
// Set tcp keep alive
if (config.tcp_keepalive) {
try set(fd, os.SOL_SOCKET, os.SO_KEEPALIVE, 1);
if (is_linux) {
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPIDLE, config.tcp_keepidle);
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPINTVL, config.tcp_keepintvl);
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPCNT, config.tcp_keepcnt);
}
}
// Set tcp user timeout
if (config.tcp_user_timeout > 0) {
if (is_linux) {
try set(fd, os.IPPROTO_TCP, os.TCP_USER_TIMEOUT, config.tcp_user_timeout);
}
}
// Set tcp no-delay
if (config.tcp_nodelay) {
// TODO: use the version in the zig standard library when upgrading to 0.9
// https://github.com/rust-lang/libc/search?q=TCP_NODELAY
// https://github.com/ziglang/zig/search?q=TCP_NODELAY
const TCP_NODELAY: u32 = 1;
try set(fd, os.IPPROTO_TCP, TCP_NODELAY, 1);
}
try set(fd, os.SOL_SOCKET, os.SO_REUSEADDR, 1);
try os.bind(fd, &address.any, address.getOsSockLen());
try os.listen(fd, config.tcp_backlog);
return fd;
}
pub fn tick(bus: *Self) void {
switch (process_type) {
.replica => {
// Each replica is responsible for connecting to replicas that come
// after it in the configuration. This ensures that replicas never try
// to connect to each other at the same time.
var replica: u8 = bus.process.replica + 1;
while (replica < bus.replicas.len) : (replica += 1) {
bus.maybe_connect_to_replica(replica);
}
// Only replicas accept connections from other replicas and clients:
bus.maybe_accept();
},
.client => {
// The client connects to all replicas.
var replica: u8 = 0;
while (replica < bus.replicas.len) : (replica += 1) {
bus.maybe_connect_to_replica(replica);
}
},
}
}
fn maybe_connect_to_replica(bus: *Self, replica: u8) void {
// We already have a connection to the given replica.
if (bus.replicas[replica] != null) {
assert(bus.connections_used > 0);
return;
}
// Obtain a connection struct for our new replica connection.
// If there is a free connection, use that. Otherwise drop
// a client or unknown connection to make space. Prefer dropping
// a client connection to an unknown one as the unknown peer may
// be a replica. Since shutting a connection down does not happen
// instantly, simply return after starting the shutdown and try again
// on the next tick().
for (bus.connections) |*connection| {
if (connection.state == .free) {
assert(connection.peer == .none);
// This will immediately add the connection to bus.replicas,
// or else will return early if a socket file descriptor cannot be obtained:
// TODO See if we can clean this up to remove/expose the early return branch.
connection.connect_to_replica(bus, replica);
return;
}
}
// If there is already a connection being shut down, no need to kill another.
for (bus.connections) |*connection| {
if (connection.state == .terminating) return;
}
log.notice("all connections in use but not all replicas are connected, " ++
"attempting to disconnect a client", .{});
for (bus.connections) |*connection| {
if (connection.peer == .client) {
connection.terminate(bus, .shutdown);
return;
}
}
log.notice("failed to disconnect a client as no peer was a known client, " ++
"attempting to disconnect an unknown peer.", .{});
for (bus.connections) |*connection| {
if (connection.peer == .unknown) {
connection.terminate(bus, .shutdown);
return;
}
}
// We assert that the max number of connections is greater
// than the number of replicas in init().
unreachable;
}
fn maybe_accept(bus: *Self) void {
comptime assert(process_type == .replica);
if (bus.process.accept_connection != null) return;
// All connections are currently in use, do nothing.
if (bus.connections_used == bus.connections.len) return;
assert(bus.connections_used < bus.connections.len);
bus.process.accept_connection = for (bus.connections) |*connection| {
if (connection.state == .free) {
assert(connection.peer == .none);
connection.state = .accepting;
break connection;
}
} else unreachable;
bus.io.accept(
*Self,
bus,
on_accept,
&bus.process.accept_completion,
bus.process.accept_fd,
);
}
fn on_accept(
bus: *Self,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
comptime assert(process_type == .replica);
assert(bus.process.accept_connection != null);
defer bus.process.accept_connection = null;
const fd = result catch |err| {
bus.process.accept_connection.?.state = .free;
// TODO: some errors should probably be fatal
log.err("accept failed: {}", .{err});
return;
};
bus.process.accept_connection.?.on_accept(bus, fd);
}
pub fn get_message(bus: *Self) ?*Message {
return bus.pool.get_message();
}
pub fn unref(bus: *Self, message: *Message) void {
bus.pool.unref(message);
}
pub fn send_message_to_replica(bus: *Self, replica: u8, message: *Message) void {
// Messages sent by a replica to itself should never be passed to the message bus.
if (process_type == .replica) assert(replica != bus.process.replica);
if (bus.replicas[replica]) |connection| {
connection.send_message(bus, message);
} else {
log.debug("no active connection to replica {}, " ++
"dropping message with header {}", .{ replica, message.header });
}
}
/// Try to send the message to the client with the given id.
/// If the client is not currently connected, the message is silently dropped.
pub fn send_message_to_client(bus: *Self, client_id: u128, message: *Message) void {
comptime assert(process_type == .replica);
if (bus.process.clients.get(client_id)) |connection| {
connection.send_message(bus, message);
} else {
log.debug("no connection to client {x}", .{client_id});
}
}
/// Used to send/receive messages to/from a client or fellow replica.
const Connection = struct {
/// The peer is determined by inspecting the first message header
/// received.
peer: union(enum) {
/// No peer is currently connected.
none: void,
/// A connection is established but an unambiguous header has not yet been received.
unknown: void,
/// The peer is a client with the given id.
client: u128,
/// The peer is a replica with the given id.
replica: u8,
} = .none,
state: enum {
/// The connection is not in use, with peer set to `.none`.
free,
/// The connection has been reserved for an in progress accept operation,
/// with peer set to `.none`.
accepting,
/// The peer is a replica and a connect operation has been started
/// but not yet competed.
connecting,
/// The peer is fully connected and may be a client, replica, or unknown.
connected,
/// The connection is being terminated but cleanup has not yet finished.
terminating,
} = .free,
/// This is guaranteed to be valid only while state is connected.
/// It will be reset to -1 during the shutdown process and is always -1 if the
/// connection is unused (i.e. peer == .none). We use -1 instead of undefined here
/// for safety to ensure an error if the invalid value is ever used, instead of
/// potentially performing an action on an active fd.
fd: os.socket_t = -1,
/// This completion is used for all recv operations.
/// It is also used for the initial connect when establishing a replica connection.
recv_completion: IO.Completion = undefined,
/// True exactly when the recv_completion has been submitted to the IO abstraction
/// but the callback has not yet been run.
recv_submitted: bool = false,
/// The Message with the buffer passed to the kernel for recv operations.
recv_message: ?*Message = null,
/// The number of bytes in `recv_message` that have been received and need parsing.
recv_progress: usize = 0,
/// The number of bytes in `recv_message` that have been parsed.
recv_parsed: usize = 0,
/// True if we have already checked the header checksum of the message we
/// are currently receiving/parsing.
recv_checked_header: bool = false,
/// This completion is used for all send operations.
send_completion: IO.Completion = undefined,
/// True exactly when the send_completion has been submitted to the IO abstraction
/// but the callback has not yet been run.
send_submitted: bool = false,
/// Number of bytes of the current message that have already been sent.
send_progress: usize = 0,
/// The queue of messages to send to the client or replica peer.
send_queue: SendQueue = .{},
/// Attempt to connect to a replica.
/// The slot in the Message.replicas slices is immediately reserved.
/// Failure is silent and returns the connection to an unused state.
pub fn connect_to_replica(connection: *Connection, bus: *Self, replica: u8) void {
if (process_type == .replica) assert(replica != bus.process.replica);
assert(connection.peer == .none);
assert(connection.state == .free);
assert(connection.fd == -1);
// The first replica's network address family determines the
// family for all other replicas:
const family = bus.configuration[0].any.family;
connection.fd = IO.openSocket(family, os.SOCK_STREAM, os.IPPROTO_TCP) catch return;
connection.peer = .{ .replica = replica };
connection.state = .connecting;
bus.connections_used += 1;
assert(bus.replicas[replica] == null);
bus.replicas[replica] = connection;
var attempts = &bus.replicas_connect_attempts[replica];
const ms = vsr.exponential_backoff_with_jitter(
&bus.prng,
config.connection_delay_min_ms,
config.connection_delay_max_ms,
attempts.*,
);
attempts.* += 1;
log.debug("connecting to replica {} in {}ms...", .{ connection.peer.replica, ms });
assert(!connection.recv_submitted);
connection.recv_submitted = true;
bus.io.timeout(
*Self,
bus,
on_connect_with_exponential_backoff,
// We use `recv_completion` for the connection `timeout()` and `connect()` calls
&connection.recv_completion,
@intCast(u63, ms * std.time.ns_per_ms),
);
}
fn on_connect_with_exponential_backoff(
bus: *Self,
completion: *IO.Completion,
result: IO.TimeoutError!void,
) void {
const connection = @fieldParentPtr(Connection, "recv_completion", completion);
assert(connection.recv_submitted);
connection.recv_submitted = false;
if (connection.state == .terminating) {
connection.maybe_close(bus);
return;
}
assert(connection.state == .connecting);
result catch unreachable;
log.debug("connecting to replica {}...", .{connection.peer.replica});
assert(!connection.recv_submitted);
connection.recv_submitted = true;
bus.io.connect(
*Self,
bus,
on_connect,
// We use `recv_completion` for the connection `timeout()` and `connect()` calls
&connection.recv_completion,
connection.fd,
bus.configuration[connection.peer.replica],
);
}
fn on_connect(
bus: *Self,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
const connection = @fieldParentPtr(Connection, "recv_completion", completion);
assert(connection.recv_submitted);
connection.recv_submitted = false;
if (connection.state == .terminating) {
connection.maybe_close(bus);
return;
}
assert(connection.state == .connecting);
connection.state = .connected;
result catch |err| {
log.err("error connecting to replica {}: {}", .{ connection.peer.replica, err });
connection.terminate(bus, .close);
return;
};
log.info("connected to replica {}", .{connection.peer.replica});
bus.replicas_connect_attempts[connection.peer.replica] = 0;
connection.assert_recv_send_initial_state(bus);
// This will terminate the connection if there are no messages available:
connection.get_recv_message_and_recv(bus);
// A message may have been queued for sending while we were connecting:
// TODO Should we relax recv() and send() to return if `connection.state != .connected`?
if (connection.state == .connected) connection.send(bus);
}
/// Given a newly accepted fd, start receiving messages on it.
/// Callbacks will be continuously re-registered until terminate() is called.
pub fn on_accept(connection: *Connection, bus: *Self, fd: os.socket_t) void {
assert(connection.peer == .none);
assert(connection.state == .accepting);
assert(connection.fd == -1);
connection.peer = .unknown;
connection.state = .connected;
connection.fd = fd;
bus.connections_used += 1;
connection.assert_recv_send_initial_state(bus);
connection.get_recv_message_and_recv(bus);
assert(connection.send_queue.empty());
}
fn assert_recv_send_initial_state(connection: *Connection, bus: *Self) void {
assert(bus.connections_used > 0);
assert(connection.peer == .unknown or connection.peer == .replica);
assert(connection.state == .connected);
assert(connection.fd != -1);
assert(connection.recv_submitted == false);
assert(connection.recv_message == null);
assert(connection.recv_progress == 0);
assert(connection.recv_parsed == 0);
assert(connection.send_submitted == false);
assert(connection.send_progress == 0);
}
/// Add a message to the connection's send queue, starting a send operation
/// if the queue was previously empty.
pub fn send_message(connection: *Connection, bus: *Self, message: *Message) void {
assert(connection.peer == .client or connection.peer == .replica);
switch (connection.state) {
.connected, .connecting => {},
.terminating => return,
.free, .accepting => unreachable,
}
connection.send_queue.push(message.ref()) catch |err| switch (err) {
error.NoSpaceLeft => {
bus.unref(message);
log.notice("message queue for peer {} full, dropping message", .{
connection.peer,
});
return;
},
};
// If the connection has not yet been established we can't send yet.
// Instead on_connect() will call send().
if (connection.state == .connecting) {
assert(connection.peer == .replica);
return;
}
// If there is no send operation currently in progress, start one.
if (!connection.send_submitted) connection.send(bus);
}
/// Clean up an active connection and reset it to its initial, unused, state.
/// This reset does not happen instantly as currently in progress operations
/// must first be stopped. The `how` arg allows the caller to specify if a
/// shutdown syscall should be made or not before proceeding to wait for
/// currently in progress operations to complete and close the socket.
/// I'll be back! (when the Connection is reused after being fully closed)
pub fn terminate(connection: *Connection, bus: *Self, how: enum { shutdown, close }) void {
assert(connection.peer != .none);
assert(connection.state != .free);
assert(connection.fd != -1);
switch (how) {
.shutdown => {
// The shutdown syscall will cause currently in progress send/recv
// operations to be gracefully closed while keeping the fd open.
//
// TODO: Investigate differences between shutdown() on Linux vs Darwin.
// Especially how this interacts with our assumptions around pending I/O.
const rc = os.system.shutdown(connection.fd, os.SHUT_RDWR);
switch (os.errno(rc)) {
0 => {},
os.EBADF => unreachable,
os.EINVAL => unreachable,
os.ENOTCONN => {
// This should only happen if we for some reason decide to terminate
// a connection while a connect operation is in progress.
// This is fine though, we simply continue with the logic below and
// wait for the connect operation to finish.
// TODO: This currently happens in other cases if the
// connection was closed due to an error. We need to intelligently
// decide whether to shutdown or close directly based on the error
// before these assertions may be re-enabled.
//assert(connection.state == .connecting);
//assert(connection.recv_submitted);
//assert(!connection.send_submitted);
},
os.ENOTSOCK => unreachable,
else => |err| os.unexpectedErrno(err) catch {},
}
},
.close => {},
}
assert(connection.state != .terminating);
connection.state = .terminating;
connection.maybe_close(bus);
}
fn parse_messages(connection: *Connection, bus: *Self) void {
assert(connection.peer != .none);
assert(connection.state == .connected);
assert(connection.fd != -1);
while (connection.parse_message(bus)) |message| {
defer bus.unref(message);
connection.on_message(bus, message);
}
}
fn parse_message(connection: *Connection, bus: *Self) ?*Message {
const data = connection.recv_message.?.buffer[connection.recv_parsed..connection.recv_progress];
if (data.len < @sizeOf(Header)) {
connection.get_recv_message_and_recv(bus);
return null;
}
const header = mem.bytesAsValue(Header, data[0..@sizeOf(Header)]);
if (!connection.recv_checked_header) {
if (!header.valid_checksum()) {
log.err("invalid header checksum received from {}", .{connection.peer});
connection.terminate(bus, .shutdown);
return null;
}
if (header.size < @sizeOf(Header) or header.size > config.message_size_max) {
log.err("header with invalid size {d} received from peer {}", .{
header.size,
connection.peer,
});
connection.terminate(bus, .shutdown);
return null;
}
if (header.cluster != bus.cluster) {
log.err("message addressed to the wrong cluster: {}", .{header.cluster});
connection.terminate(bus, .shutdown);
return null;
}
switch (process_type) {
// Replicas may forward messages from clients or from other replicas so we
// may receive messages from a peer before we know who they are:
// This has the same effect as an asymmetric network where, for a short time
// bounded by the time it takes to ping, we can hear from a peer before we
// can send back to them.
.replica => connection.maybe_set_peer(bus, header),
// The client connects only to replicas and should set peer when connecting:
.client => assert(connection.peer == .replica),
}
connection.recv_checked_header = true;
}
if (data.len < header.size) {
connection.get_recv_message_and_recv(bus);
return null;
}
// At this point we know that we have the full message in our buffer.
// We will now either deliver this message or terminate the connection
// due to an error, so reset recv_checked_header for the next message.
assert(connection.recv_checked_header);
connection.recv_checked_header = false;
const body = data[@sizeOf(Header)..header.size];
if (!header.valid_checksum_body(body)) {
log.err("invalid body checksum received from {}", .{connection.peer});
connection.terminate(bus, .shutdown);
return null;
}
connection.recv_parsed += header.size;
// Return the parsed message using zero-copy if we can, or copy if the client is
// pipelining:
// If this is the first message but there are messages in the pipeline then we
// copy the message so that its sector padding (if any) will not overwrite the
// front of the pipeline. If this is not the first message then we must copy
// the message to a new message as each message needs to have its own unique
// `references` and `header` metadata.
if (connection.recv_progress == header.size) return connection.recv_message.?.ref();
const message = bus.get_message() orelse {
// TODO Decrease the probability of this happening by:
// 1. using a header-only message if possible.
// 2. determining a true upper limit for static allocation.
log.err("no free buffer available to deliver message from {}", .{connection.peer});
connection.terminate(bus, .shutdown);
return null;
};
mem.copy(u8, message.buffer, data[0..header.size]);
return message;
}
/// Forward a received message to `Process.on_message()`.
/// Zero any `.prepare` sector padding up to the nearest sector multiple after the body.
fn on_message(connection: *Connection, bus: *Self, message: *Message) void {
if (message == connection.recv_message.?) {
assert(connection.recv_parsed == message.header.size);
assert(connection.recv_parsed == connection.recv_progress);
} else if (connection.recv_parsed == message.header.size) {
assert(connection.recv_parsed < connection.recv_progress);
} else {
assert(connection.recv_parsed > message.header.size);
assert(connection.recv_parsed <= connection.recv_progress);
}
if (message.header.command == .request or message.header.command == .prepare) {
const sector_ceil = vsr.sector_ceil(message.header.size);
if (message.header.size != sector_ceil) {
assert(message.header.size < sector_ceil);
assert(message.buffer.len == config.message_size_max + config.sector_size);
mem.set(u8, message.buffer[message.header.size..sector_ceil], 0);
}
}
bus.on_message_callback.?(bus.on_message_context, message);
}
fn maybe_set_peer(connection: *Connection, bus: *Self, header: *const Header) void {
comptime assert(process_type == .replica);
assert(bus.cluster == header.cluster);
assert(bus.connections_used > 0);
assert(connection.peer != .none);
assert(connection.state == .connected);
assert(connection.fd != -1);
if (connection.peer != .unknown) return;
switch (header.peer_type()) {
.unknown => return,
.replica => {
connection.peer = .{ .replica = header.replica };
// If there is a connection to this replica, terminate and replace it:
if (bus.replicas[connection.peer.replica]) |old| {
assert(old.peer == .replica);
assert(old.peer.replica == connection.peer.replica);
assert(old.state != .free);
if (old.state != .terminating) old.terminate(bus, .shutdown);
}
bus.replicas[connection.peer.replica] = connection;
log.info("connection from replica {}", .{connection.peer.replica});
},
.client => {
connection.peer = .{ .client = header.client };
const result = bus.process.clients.getOrPutAssumeCapacity(header.client);
// If there is a connection to this client, terminate and replace it:
if (result.found_existing) {
const old = result.value_ptr.*;
assert(old.peer == .client);
assert(old.peer.client == connection.peer.client);
assert(old.state == .connected or old.state == .terminating);
if (old.state != .terminating) old.terminate(bus, .shutdown);
}
result.value_ptr.* = connection;
log.info("connection from client {}", .{connection.peer.client});
},
}
}
/// Acquires a free message if necessary and then calls `recv()`.
/// Terminates the connection if a free message cannot be obtained.
/// If the connection has a `recv_message` and the message being parsed is
/// at pole position then calls `recv()` immediately, otherwise copies any
/// partially received message into a new Message and sets `recv_message`,
/// releasing the old one.
fn get_recv_message_and_recv(connection: *Connection, bus: *Self) void {
if (connection.recv_message != null and connection.recv_parsed == 0) {
connection.recv(bus);
return;
}
const new_message = bus.get_message() orelse {
// TODO Decrease the probability of this happening by:
// 1. using a header-only message if possible.
// 2. determining a true upper limit for static allocation.
log.err("no free buffer available to recv message from {}", .{connection.peer});
connection.terminate(bus, .shutdown);
return;
};
defer bus.unref(new_message);
if (connection.recv_message) |recv_message| {
defer bus.unref(recv_message);
assert(connection.recv_progress > 0);
assert(connection.recv_parsed > 0);
const data = recv_message.buffer[connection.recv_parsed..connection.recv_progress];
mem.copy(u8, new_message.buffer, data);
connection.recv_progress = data.len;
connection.recv_parsed = 0;
} else {
assert(connection.recv_progress == 0);
assert(connection.recv_parsed == 0);
}
connection.recv_message = new_message.ref();
connection.recv(bus);
}
fn recv(connection: *Connection, bus: *Self) void {
assert(connection.peer != .none);
assert(connection.state == .connected);
assert(connection.fd != -1);
assert(!connection.recv_submitted);
connection.recv_submitted = true;
assert(connection.recv_progress < config.message_size_max);
bus.io.recv(
*Self,
bus,
on_recv,
&connection.recv_completion,
connection.fd,
connection.recv_message.?.buffer[connection.recv_progress..config.message_size_max],
);
}
fn on_recv(bus: *Self, completion: *IO.Completion, result: IO.RecvError!usize) void {
const connection = @fieldParentPtr(Connection, "recv_completion", completion);
assert(connection.recv_submitted);
connection.recv_submitted = false;
if (connection.state == .terminating) {
connection.maybe_close(bus);
return;
}
assert(connection.state == .connected);
const bytes_received = result catch |err| {
// TODO: maybe don't need to close on *every* error
log.err("error receiving from {}: {}", .{ connection.peer, err });
connection.terminate(bus, .shutdown);
return;
};
// No bytes received means that the peer closed its side of the connection.
if (bytes_received == 0) {
log.info("peer performed an orderly shutdown: {}", .{connection.peer});
connection.terminate(bus, .close);
return;
}
connection.recv_progress += bytes_received;
connection.parse_messages(bus);
}
fn send(connection: *Connection, bus: *Self) void {
assert(connection.peer == .client or connection.peer == .replica);
assert(connection.state == .connected);
assert(connection.fd != -1);
const message = connection.send_queue.head() orelse return;
assert(!connection.send_submitted);
connection.send_submitted = true;
bus.io.send(
*Self,
bus,
on_send,
&connection.send_completion,
connection.fd,
message.buffer[connection.send_progress..message.header.size],
);
}
fn on_send(bus: *Self, completion: *IO.Completion, result: IO.SendError!usize) void {
const connection = @fieldParentPtr(Connection, "send_completion", completion);
assert(connection.send_submitted);
connection.send_submitted = false;
assert(connection.peer == .client or connection.peer == .replica);
if (connection.state == .terminating) {
connection.maybe_close(bus);
return;
}
assert(connection.state == .connected);
connection.send_progress += result catch |err| {
// TODO: maybe don't need to close on *every* error
log.err("error sending message to replica at {}: {}", .{ connection.peer, err });
connection.terminate(bus, .shutdown);
return;
};
assert(connection.send_progress <= connection.send_queue.head().?.header.size);
// If the message has been fully sent, move on to the next one.
if (connection.send_progress == connection.send_queue.head().?.header.size) {
connection.send_progress = 0;
const message = connection.send_queue.pop().?;
bus.unref(message);
}
connection.send(bus);
}
fn maybe_close(connection: *Connection, bus: *Self) void {
assert(connection.peer != .none);
assert(connection.state == .terminating);
// If a recv or send operation is currently submitted to the kernel,
// submitting a close would cause a race. Therefore we must wait for
// any currently submitted operation to complete.
if (connection.recv_submitted or connection.send_submitted) return;
connection.send_submitted = true;
connection.recv_submitted = true;
// We can free resources now that there is no longer any I/O in progress.
while (connection.send_queue.pop()) |message| {
bus.unref(message);
}
if (connection.recv_message) |message| {
bus.unref(message);
connection.recv_message = null;
}
assert(connection.fd != -1);
defer connection.fd = -1;
// It's OK to use the send completion here as we know that no send
// operation is currently in progress.
bus.io.close(*Self, bus, on_close, &connection.send_completion, connection.fd);
}
fn on_close(bus: *Self, completion: *IO.Completion, result: IO.CloseError!void) void {
const connection = @fieldParentPtr(Connection, "send_completion", completion);
assert(connection.send_submitted);
assert(connection.recv_submitted);
assert(connection.peer != .none);
assert(connection.state == .terminating);
// Reset the connection to its initial state.
defer {
assert(connection.recv_message == null);
assert(connection.send_queue.empty());
switch (connection.peer) {
.none => unreachable,
.unknown => {},
.client => switch (process_type) {
.replica => assert(bus.process.clients.remove(connection.peer.client)),
.client => unreachable,
},
.replica => {
// A newer replica connection may have replaced this one:
if (bus.replicas[connection.peer.replica] == connection) {
bus.replicas[connection.peer.replica] = null;
} else {
// A newer replica connection may even leapfrog this connection and
// then be terminated and set to null before we can get here:
assert(bus.replicas[connection.peer.replica] != null or
bus.replicas[connection.peer.replica] == null);
}
},
}
bus.connections_used -= 1;
connection.* = .{};
}
result catch |err| {
log.err("error closing connection to {}: {}", .{ connection.peer, err });
return;
};
}
};
};
}
|
src/message_bus.zig
|