code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day10.txt");
const Input = struct {
lines: std.ArrayList([]const u8),
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{
.lines = std.ArrayList([]const u8).initCapacity(allocator, 110) catch unreachable,
};
errdefer input.deinit();
var lines = std.mem.tokenize(u8, input_text, "\r\n");
while (lines.next()) |line| {
input.lines.append(line) catch unreachable;
}
return input;
}
pub fn deinit(self: @This()) void {
self.lines.deinit();
}
};
fn part1(input: Input) i64 {
var openers = std.ArrayList(u8).initCapacity(std.testing.allocator, input.lines.items[0].len) catch unreachable;
defer openers.deinit();
var score: i64 = 0;
for (input.lines.items) |line, i| {
openers.shrinkRetainingCapacity(0);
for (line) |c| {
if (c == '[' or c == '(' or c == '{' or c == '<') {
openers.append(c) catch unreachable;
} else if (c == ']' or c == ')' or c == '}' or c == '>') {
assert(openers.items.len > 0);
const o = openers.pop();
if ((o == '[' and c != ']') or
(o == '(' and c != ')') or
(o == '{' and c != '}') or
(o == '<' and c != '>'))
{
_ = i;
//print("Line {d} is corrupt: Opened with {c} but closed with {c} instead\n", .{i, o, c});
if (c == ']') {
score += 57;
} else if (c == ')') {
score += 3;
} else if (c == '}') {
score += 1197;
} else if (c == '>') {
score += 25137;
} else {
unreachable;
}
continue;
}
}
}
}
return score;
}
fn part2(input: Input) i64 {
var openers = std.ArrayList(u8).initCapacity(std.testing.allocator, input.lines.items[0].len) catch unreachable;
defer openers.deinit();
var scores = std.ArrayList(i64).initCapacity(std.testing.allocator, input.lines.items.len) catch unreachable;
defer scores.deinit();
outer: for (input.lines.items) |line, i| {
var score: i64 = 0;
openers.shrinkRetainingCapacity(0);
for (line) |c| {
if (c == '(' or c == '[' or c == '{' or c == '<') {
openers.append(c) catch unreachable;
} else if (c == ')' or c == ']' or c == '}' or c == '>') {
assert(openers.items.len > 0);
const o = openers.pop();
if ((o == '(' and c != ')') or
(o == '[' and c != ']') or
(o == '{' and c != '}') or
(o == '<' and c != '>'))
{
//print("Line {d} is corrupt: Opened with {c} but closed with {c} instead\n", .{i, o, c});
continue :outer;
}
}
}
if (openers.items.len > 0) {
_ = i;
//print("Line {d} is incomplete: closing sequence is ", .{i});
while (openers.items.len > 0) {
const o = openers.pop();
if (o == '(') {
//print(")", .{});
score = (score * 5) + 1;
} else if (o == '[') {
//print("]", .{});
score = (score * 5) + 2;
} else if (o == '{') {
//print("}}", .{});
score = (score * 5) + 3;
} else if (o == '<') {
//print(">", .{});
score = (score * 5) + 4;
} else {
unreachable;
}
}
}
//print(" for a score of {d}\n", .{score});
scores.append(score) catch unreachable;
}
std.sort.sort(i64, scores.items, {}, comptime std.sort.asc(i64));
return scores.items[@divFloor(scores.items.len, 2)];
}
const test_data =
\\[({(<(())[]>[[{[]{<()<>>
\\[(()[<>])]({[<{<<[]>>(
\\{([(<{}[<>[]}>{[]{[(<()>
\\(((({<>}<{<{<>}{[]{[]{}
\\[[<[([]))<([[{}[[()]]]
\\[{[{({}]{}}([{[{{{}}([]
\\{<[[]]>}<{[{[{[]{()[[[]
\\[<(<(<(<{}))><([]([]()
\\<{([([[(<>()){}]>(<<{{
\\<{([{{}}[<[[[<>{}]]]>[]]
;
const part1_test_solution: ?i64 = 26397;
const part1_solution: ?i64 = 392367;
const part2_test_solution: ?i64 = 288957;
const part2_solution: ?i64 = 2192104158;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var input = try Input.init(data, std.testing.allocator);
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/day10.zig
|
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day14.txt");
const Input = struct {
template: []const u8 = undefined,
rules: std.StringHashMap(u8) = undefined,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{
.rules = std.StringHashMap(u8).init(allocator),
};
errdefer input.deinit();
try input.rules.ensureTotalCapacity(100);
var lines = std.mem.tokenize(u8, input_text, "\r\n");
input.template = lines.next().?;
while (lines.next()) |rule| {
input.rules.putAssumeCapacity(rule[0..2], rule[6]);
}
return input;
}
pub fn deinit(self: *@This()) void {
self.rules.deinit();
}
};
inline fn hashPair(pair: []const u8) u16 {
return @as(u16, pair[0]) * 256 + @as(u16, pair[1]);
}
inline fn unhashPair(hash: u16) [2]u8 {
return [2]u8{ @truncate(u8, hash >> 8), @truncate(u8, hash & 0xFF) };
}
fn buildPolymer(input: Input, step_count: usize) i64 {
var step: usize = 0;
var polymer = std.AutoHashMap(u16, i64).init(std.testing.allocator);
polymer.ensureTotalCapacity(26 * 26) catch unreachable;
{
var i: usize = 0;
while (i < input.template.len - 1) : (i += 1) {
const pair = input.template[i .. i + 2];
var result = polymer.getOrPut(hashPair(pair)) catch unreachable;
if (!result.found_existing) {
result.value_ptr.* = 0;
}
result.value_ptr.* += 1;
}
}
while (step < step_count) : (step += 1) {
var src = polymer;
defer src.deinit();
polymer = std.AutoHashMap(u16, i64).init(std.testing.allocator);
polymer.ensureTotalCapacity(26 * 26) catch unreachable;
var src_itor = src.iterator();
while (src_itor.next()) |kv| {
const pair_hash = kv.key_ptr.*;
const pair = unhashPair(pair_hash);
const count = kv.value_ptr.*;
if (input.rules.get(pair[0..])) |middle| {
// insert count copies of pair1
const pair1 = [2]u8{ pair[0], middle };
var result1 = polymer.getOrPut(hashPair(pair1[0..])) catch unreachable;
if (!result1.found_existing) {
result1.value_ptr.* = 0;
}
result1.value_ptr.* += count;
// insert count copies of pair2
const pair2 = [2]u8{ middle, pair[1] };
var result2 = polymer.getOrPut(hashPair(pair2[0..])) catch unreachable;
if (!result2.found_existing) {
result2.value_ptr.* = 0;
}
result2.value_ptr.* += count;
} else {
// insert count copies of pair
var result = polymer.getOrPut(pair_hash) catch unreachable;
if (!result.found_existing) {
result.value_ptr.* = 0;
}
result.value_ptr.* += count;
}
}
}
var counts: [26]i64 = .{0} ** 26;
{
var itor = polymer.iterator();
while (itor.next()) |kv| {
const pair_hash = kv.key_ptr.*;
const pair = unhashPair(pair_hash);
const count = kv.value_ptr.*;
counts[pair[1] - 'A'] += count;
}
// The first element never changes
counts[input.template[0] - 'A'] += 1;
}
polymer.deinit();
var min_count: i64 = std.math.maxInt(i64);
var max_count: i64 = 0;
for (counts) |count| {
if (count == 0) {
continue;
}
min_count = std.math.min(min_count, count);
max_count = std.math.max(max_count, count);
}
return max_count - min_count;
}
fn part1(input: Input) i64 {
return buildPolymer(input, 10);
}
fn part2(input: Input) i64 {
return buildPolymer(input, 40);
}
const test_data =
\\NNCB
\\
\\CH -> B
\\HH -> N
\\CB -> H
\\NH -> C
\\HB -> C
\\HC -> B
\\HN -> C
\\NN -> C
\\BH -> H
\\NC -> B
\\NB -> B
\\BN -> B
\\BB -> N
\\BC -> B
\\CC -> N
\\CN -> C
;
const part1_test_solution: ?i64 = 1588;
const part1_solution: ?i64 = 3306;
const part2_test_solution: ?i64 = 2188189693529;
const part2_solution: ?i64 = 3760312702877;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
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/day14.zig
|
const std = @import("std");
const buildns = std.build;
const fs = std.fs;
const Builder = buildns.Builder;
const Version = buildns.Version;
fn deleteOldDll(dllNameExt: []const u8) !void {
// delete existing dll if it's there
const workingDir = fs.cwd();
var binDir = try workingDir.openDir("zig-cache", .{});
binDir = try binDir.openDir("bin", .{});
try binDir.deleteFile(dllNameExt);
}
fn openDllSrcDir(comptime dllDir: []const []const u8) !fs.Dir {
var srcPath = fs.cwd();
for (dllDir) |dir| {
srcPath = try srcPath.openDir(dir, .{});
}
return srcPath;
}
fn openDllDstDir() !fs.Dir {
const workingDir = fs.cwd();
var dstPath = try workingDir.openDir("zig-cache", .{});
dstPath = try dstPath.openDir("bin", .{});
return dstPath;
}
// Copy files to zig-cache/bin
fn copyDllToBin(comptime dllDir: []const []const u8, comptime dllName: []const u8) !void {
const dllNameExt = dllName ++ ".dll";
deleteOldDll(dllNameExt) catch |e| { // this is allowed to fail
// make dir if it doesn't exist
const workingDir = fs.cwd();
workingDir.makeDir("zig-cache") catch |e2| {}; // may already exist
var cacheDir = try workingDir.openDir("zig-cache", .{});
cacheDir.makeDir("bin") catch |e2| {}; // may already exist
};
const srcPath = openDllSrcDir(dllDir) catch |e| {
std.debug.warn("Unable to resolve src path\n", .{});
return e;
};
const dstPath = openDllDstDir() catch |e| {
std.debug.warn("Unable to resolve dst path\n", .{});
return e;
};
srcPath.copyFile(dllNameExt, dstPath, dllNameExt, .{}) catch |e| {
std.debug.warn("Unable to copy file from {} to {}\n", .{ srcPath, dstPath });
return e;
};
}
pub fn build(b: *Builder) void {
const isDebug = false;
const mode = if (isDebug) std.builtin.Mode.Debug else b.standardReleaseOptions();
const exe = b.addExecutable("sdl-zig-demo", "src/main.zig");
exe.setBuildMode(mode);
// for build debugging
//exe.setVerboseLink(true);
//exe.setVerboseCC(true);
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("opengl32");
exe.addIncludeDir("src");
exe.addIncludeDir("dependency/glew-2.1.0/include");
exe.addLibPath("dependency/glew-2.1.0/lib/Release/x64");
exe.linkSystemLibrary("glew32s"); //only include 1 of the 2 glew libs
exe.addIncludeDir("dependency/cimgui");
exe.addIncludeDir("dependency/cimgui/imgui");
exe.addIncludeDir("dependency/cimgui/imgui/examples");
const imgui_flags = &[_][]const u8{
"-std=c++17",
"-Wno-return-type-c-linkage",
"-DIMGUI_IMPL_OPENGL_LOADER_GLEW=1",
"-fno-exceptions",
"-fno-rtti",
"-Wno-pragma-pack",
};
exe.addCSourceFile("dependency/cimgui/cimgui.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/imgui.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/imgui_demo.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/imgui_draw.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/imgui_widgets.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/examples/imgui_impl_sdl.cpp", imgui_flags);
exe.addCSourceFile("dependency/cimgui/imgui/examples/imgui_impl_opengl3.cpp", imgui_flags);
exe.addIncludeDir("dependency/SDL2/include");
exe.addLibPath("dependency/SDL2/lib/x64");
exe.linkSystemLibrary("SDL2");
const sdl2DllPath = &[_][]const u8{ "dependency", "SDL2", "lib", "x64" };
copyDllToBin(sdl2DllPath, "SDL2") catch |e| {
std.debug.warn("Could not copy SDL2.dll, {}\n", .{e});
@panic("Build failure.");
};
exe.addIncludeDir("dependency/assimp/include");
exe.linkSystemLibrary("assimp-vc142-mt");
if (isDebug) {
exe.addLibPath("dependency/assimp/lib/RelWithDebInfo");
} else {
exe.addLibPath("dependency/assimp/lib/Release");
}
const assimpDllPath = if (isDebug) &[_][]const u8{ "dependency", "assimp", "bin", "RelWithDebInfo" } else &[_][]const u8{ "dependency", "assimp", "bin", "Release" };
copyDllToBin(assimpDllPath, "assimp-vc142-mt") catch |e| {
std.debug.warn("Could not copy assimp-vc142-mt.dll, {}\n", .{e});
@panic("Build failure.");
};
exe.addIncludeDir("dependency/stb");
const stb_flags = &[_][]const u8{
"-std=c17",
};
exe.addCSourceFile("dependency/stb/stb_image_impl.c", stb_flags);
exe.linkSystemLibrary("user32");
exe.linkSystemLibrary("gdi32");
exe.install();
const run_exe_cmd = exe.run();
run_exe_cmd.step.dependOn(b.getInstallStep());
const run_exe_step = b.step("run", "Run the demo");
run_exe_step.dependOn(&run_exe_cmd.step);
}
|
build.zig
|
pub const Block = struct {
from: u21,
to: u21,
name: []const u8,
};
pub const data = [_]Block{
.{ .from = 0x0000, .to = 0x007F, .name = "Basic Latin" },
.{ .from = 0x0080, .to = 0x00FF, .name = "Latin-1 Supplement" },
.{ .from = 0x0100, .to = 0x017F, .name = "Latin Extended-A" },
.{ .from = 0x0180, .to = 0x024F, .name = "Latin Extended-B" },
.{ .from = 0x0250, .to = 0x02AF, .name = "IPA Extensions" },
.{ .from = 0x02B0, .to = 0x02FF, .name = "Spacing Modifier Letters" },
.{ .from = 0x0300, .to = 0x036F, .name = "Combining Diacritical Marks" },
.{ .from = 0x0370, .to = 0x03FF, .name = "Greek and Coptic" },
.{ .from = 0x0400, .to = 0x04FF, .name = "Cyrillic" },
.{ .from = 0x0500, .to = 0x052F, .name = "Cyrillic Supplement" },
.{ .from = 0x0530, .to = 0x058F, .name = "Armenian" },
.{ .from = 0x0590, .to = 0x05FF, .name = "Hebrew" },
.{ .from = 0x0600, .to = 0x06FF, .name = "Arabic" },
.{ .from = 0x0700, .to = 0x074F, .name = "Syriac" },
.{ .from = 0x0750, .to = 0x077F, .name = "Arabic Supplement" },
.{ .from = 0x0780, .to = 0x07BF, .name = "Thaana" },
.{ .from = 0x07C0, .to = 0x07FF, .name = "NKo" },
.{ .from = 0x0800, .to = 0x083F, .name = "Samaritan" },
.{ .from = 0x0840, .to = 0x085F, .name = "Mandaic" },
.{ .from = 0x0860, .to = 0x086F, .name = "Syriac Supplement" },
.{ .from = 0x08A0, .to = 0x08FF, .name = "Arabic Extended-A" },
.{ .from = 0x0900, .to = 0x097F, .name = "Devanagari" },
.{ .from = 0x0980, .to = 0x09FF, .name = "Bengali" },
.{ .from = 0x0A00, .to = 0x0A7F, .name = "Gurmukhi" },
.{ .from = 0x0A80, .to = 0x0AFF, .name = "Gujarati" },
.{ .from = 0x0B00, .to = 0x0B7F, .name = "Oriya" },
.{ .from = 0x0B80, .to = 0x0BFF, .name = "Tamil" },
.{ .from = 0x0C00, .to = 0x0C7F, .name = "Telugu" },
.{ .from = 0x0C80, .to = 0x0CFF, .name = "Kannada" },
.{ .from = 0x0D00, .to = 0x0D7F, .name = "Malayalam" },
.{ .from = 0x0D80, .to = 0x0DFF, .name = "Sinhala" },
.{ .from = 0x0E00, .to = 0x0E7F, .name = "Thai" },
.{ .from = 0x0E80, .to = 0x0EFF, .name = "Lao" },
.{ .from = 0x0F00, .to = 0x0FFF, .name = "Tibetan" },
.{ .from = 0x1000, .to = 0x109F, .name = "Myanmar" },
.{ .from = 0x10A0, .to = 0x10FF, .name = "Georgian" },
.{ .from = 0x1100, .to = 0x11FF, .name = "<NAME>" },
.{ .from = 0x1200, .to = 0x137F, .name = "Ethiopic" },
.{ .from = 0x1380, .to = 0x139F, .name = "Ethiopic Supplement" },
.{ .from = 0x13A0, .to = 0x13FF, .name = "Cherokee" },
.{ .from = 0x1400, .to = 0x167F, .name = "Unified Canadian Aboriginal Syllabics" },
.{ .from = 0x1680, .to = 0x169F, .name = "Ogham" },
.{ .from = 0x16A0, .to = 0x16FF, .name = "Runic" },
.{ .from = 0x1700, .to = 0x171F, .name = "Tagalog" },
.{ .from = 0x1720, .to = 0x173F, .name = "Hanunoo" },
.{ .from = 0x1740, .to = 0x175F, .name = "Buhid" },
.{ .from = 0x1760, .to = 0x177F, .name = "Tagbanwa" },
.{ .from = 0x1780, .to = 0x17FF, .name = "Khmer" },
.{ .from = 0x1800, .to = 0x18AF, .name = "Mongolian" },
.{ .from = 0x18B0, .to = 0x18FF, .name = "Unified Canadian Aboriginal Syllabics Extended" },
.{ .from = 0x1900, .to = 0x194F, .name = "Limbu" },
.{ .from = 0x1950, .to = 0x197F, .name = "<NAME>" },
.{ .from = 0x1980, .to = 0x19DF, .name = "New Tai Lue" },
.{ .from = 0x19E0, .to = 0x19FF, .name = "Khmer Symbols" },
.{ .from = 0x1A00, .to = 0x1A1F, .name = "Buginese" },
.{ .from = 0x1A20, .to = 0x1AAF, .name = "<NAME>" },
.{ .from = 0x1AB0, .to = 0x1AFF, .name = "Combining Diacritical Marks Extended" },
.{ .from = 0x1B00, .to = 0x1B7F, .name = "Balinese" },
.{ .from = 0x1B80, .to = 0x1BBF, .name = "Sundanese" },
.{ .from = 0x1BC0, .to = 0x1BFF, .name = "Batak" },
.{ .from = 0x1C00, .to = 0x1C4F, .name = "Lepcha" },
.{ .from = 0x1C50, .to = 0x1C7F, .name = "Ol Chiki" },
.{ .from = 0x1C80, .to = 0x1C8F, .name = "Cyrillic Extended-C" },
.{ .from = 0x1C90, .to = 0x1CBF, .name = "Georgian Extended" },
.{ .from = 0x1CC0, .to = 0x1CCF, .name = "Sundanese Supplement" },
.{ .from = 0x1CD0, .to = 0x1CFF, .name = "Vedic Extensions" },
.{ .from = 0x1D00, .to = 0x1D7F, .name = "Phonetic Extensions" },
.{ .from = 0x1D80, .to = 0x1DBF, .name = "Phonetic Extensions Supplement" },
.{ .from = 0x1DC0, .to = 0x1DFF, .name = "Combining Diacritical Marks Supplement" },
.{ .from = 0x1E00, .to = 0x1EFF, .name = "Latin Extended Additional" },
.{ .from = 0x1F00, .to = 0x1FFF, .name = "Greek Extended" },
.{ .from = 0x2000, .to = 0x206F, .name = "General Punctuation" },
.{ .from = 0x2070, .to = 0x209F, .name = "Superscripts and Subscripts" },
.{ .from = 0x20A0, .to = 0x20CF, .name = "Currency Symbols" },
.{ .from = 0x20D0, .to = 0x20FF, .name = "Combining Diacritical Marks for Symbols" },
.{ .from = 0x2100, .to = 0x214F, .name = "Letterlike Symbols" },
.{ .from = 0x2150, .to = 0x218F, .name = "Number Forms" },
.{ .from = 0x2190, .to = 0x21FF, .name = "Arrows" },
.{ .from = 0x2200, .to = 0x22FF, .name = "Mathematical Operators" },
.{ .from = 0x2300, .to = 0x23FF, .name = "Miscellaneous Technical" },
.{ .from = 0x2400, .to = 0x243F, .name = "Control Pictures" },
.{ .from = 0x2440, .to = 0x245F, .name = "Optical Character Recognition" },
.{ .from = 0x2460, .to = 0x24FF, .name = "Enclosed Alphanumerics" },
.{ .from = 0x2500, .to = 0x257F, .name = "Box Drawing" },
.{ .from = 0x2580, .to = 0x259F, .name = "Block Elements" },
.{ .from = 0x25A0, .to = 0x25FF, .name = "Geometric Shapes" },
.{ .from = 0x2600, .to = 0x26FF, .name = "Miscellaneous Symbols" },
.{ .from = 0x2700, .to = 0x27BF, .name = "Dingbats" },
.{ .from = 0x27C0, .to = 0x27EF, .name = "Miscellaneous Mathematical Symbols-A" },
.{ .from = 0x27F0, .to = 0x27FF, .name = "Supplemental Arrows-A" },
.{ .from = 0x2800, .to = 0x28FF, .name = "Braille Patterns" },
.{ .from = 0x2900, .to = 0x297F, .name = "Supplemental Arrows-B" },
.{ .from = 0x2980, .to = 0x29FF, .name = "Miscellaneous Mathematical Symbols-B" },
.{ .from = 0x2A00, .to = 0x2AFF, .name = "Supplemental Mathematical Operators" },
.{ .from = 0x2B00, .to = 0x2BFF, .name = "Miscellaneous Symbols and Arrows" },
.{ .from = 0x2C00, .to = 0x2C5F, .name = "Glagolitic" },
.{ .from = 0x2C60, .to = 0x2C7F, .name = "Latin Extended-C" },
.{ .from = 0x2C80, .to = 0x2CFF, .name = "Coptic" },
.{ .from = 0x2D00, .to = 0x2D2F, .name = "Georgian Supplement" },
.{ .from = 0x2D30, .to = 0x2D7F, .name = "Tifinagh" },
.{ .from = 0x2D80, .to = 0x2DDF, .name = "Ethiopic Extended" },
.{ .from = 0x2DE0, .to = 0x2DFF, .name = "Cyrillic Extended-A" },
.{ .from = 0x2E00, .to = 0x2E7F, .name = "Supplemental Punctuation" },
.{ .from = 0x2E80, .to = 0x2EFF, .name = "CJK Radicals Supplement" },
.{ .from = 0x2F00, .to = 0x2FDF, .name = "Kangxi Radicals" },
.{ .from = 0x2FF0, .to = 0x2FFF, .name = "Ideographic Description Characters" },
.{ .from = 0x3000, .to = 0x303F, .name = "CJK Symbols and Punctuation" },
.{ .from = 0x3040, .to = 0x309F, .name = "Hiragana" },
.{ .from = 0x30A0, .to = 0x30FF, .name = "Katakana" },
.{ .from = 0x3100, .to = 0x312F, .name = "Bopomofo" },
.{ .from = 0x3130, .to = 0x318F, .name = "Hangul Compatibility Jamo" },
.{ .from = 0x3190, .to = 0x319F, .name = "Kanbun" },
.{ .from = 0x31A0, .to = 0x31BF, .name = "Bopomofo Extended" },
.{ .from = 0x31C0, .to = 0x31EF, .name = "CJK Strokes" },
.{ .from = 0x31F0, .to = 0x31FF, .name = "Katakana Phonetic Extensions" },
.{ .from = 0x3200, .to = 0x32FF, .name = "Enclosed CJK Letters and Months" },
.{ .from = 0x3300, .to = 0x33FF, .name = "CJK Compatibility" },
.{ .from = 0x3400, .to = 0x4DBF, .name = "CJK Unified Ideographs Extension A" },
.{ .from = 0x4DC0, .to = 0x4DFF, .name = "Yijing Hexagram Symbols" },
.{ .from = 0x4E00, .to = 0x9FFF, .name = "CJK Unified Ideographs" },
.{ .from = 0xA000, .to = 0xA48F, .name = "Yi Syllables" },
.{ .from = 0xA490, .to = 0xA4CF, .name = "Yi Radicals" },
.{ .from = 0xA4D0, .to = 0xA4FF, .name = "Lisu" },
.{ .from = 0xA500, .to = 0xA63F, .name = "Vai" },
.{ .from = 0xA640, .to = 0xA69F, .name = "Cyrillic Extended-B" },
.{ .from = 0xA6A0, .to = 0xA6FF, .name = "Bamum" },
.{ .from = 0xA700, .to = 0xA71F, .name = "Modifier Tone Letters" },
.{ .from = 0xA720, .to = 0xA7FF, .name = "Latin Extended-D" },
.{ .from = 0xA800, .to = 0xA82F, .name = "<NAME>" },
.{ .from = 0xA830, .to = 0xA83F, .name = "Common Indic Number Forms" },
.{ .from = 0xA840, .to = 0xA87F, .name = "Phags-pa" },
.{ .from = 0xA880, .to = 0xA8DF, .name = "Saurashtra" },
.{ .from = 0xA8E0, .to = 0xA8FF, .name = "Devanagari Extended" },
.{ .from = 0xA900, .to = 0xA92F, .name = "<NAME>" },
.{ .from = 0xA930, .to = 0xA95F, .name = "Rejang" },
.{ .from = 0xA960, .to = 0xA97F, .name = "Hangul Jamo Extended-A" },
.{ .from = 0xA980, .to = 0xA9DF, .name = "Javanese" },
.{ .from = 0xA9E0, .to = 0xA9FF, .name = "Myanmar Extended-B" },
.{ .from = 0xAA00, .to = 0xAA5F, .name = "Cham" },
.{ .from = 0xAA60, .to = 0xAA7F, .name = "Myanmar Extended-A" },
.{ .from = 0xAA80, .to = 0xAADF, .name = "Tai Viet" },
.{ .from = 0xAAE0, .to = 0xAAFF, .name = "Meetei Mayek Extensions" },
.{ .from = 0xAB00, .to = 0xAB2F, .name = "Ethiopic Extended-A" },
.{ .from = 0xAB30, .to = 0xAB6F, .name = "Latin Extended-E" },
.{ .from = 0xAB70, .to = 0xABBF, .name = "Cherokee Supplement" },
.{ .from = 0xABC0, .to = 0xABFF, .name = "Meetei Mayek" },
.{ .from = 0xAC00, .to = 0xD7AF, .name = "Hangul Syllables" },
.{ .from = 0xD7B0, .to = 0xD7FF, .name = "Hangul Jamo Extended-B" },
.{ .from = 0xD800, .to = 0xDB7F, .name = "High Surrogates" },
.{ .from = 0xDB80, .to = 0xDBFF, .name = "High Private Use Surrogates" },
.{ .from = 0xDC00, .to = 0xDFFF, .name = "Low Surrogates" },
.{ .from = 0xE000, .to = 0xF8FF, .name = "Private Use Area" },
.{ .from = 0xF900, .to = 0xFAFF, .name = "CJK Compatibility Ideographs" },
.{ .from = 0xFB00, .to = 0xFB4F, .name = "Alphabetic Presentation Forms" },
.{ .from = 0xFB50, .to = 0xFDFF, .name = "Arabic Presentation Forms-A" },
.{ .from = 0xFE00, .to = 0xFE0F, .name = "Variation Selectors" },
.{ .from = 0xFE10, .to = 0xFE1F, .name = "Vertical Forms" },
.{ .from = 0xFE20, .to = 0xFE2F, .name = "Combining Half Marks" },
.{ .from = 0xFE30, .to = 0xFE4F, .name = "CJK Compatibility Forms" },
.{ .from = 0xFE50, .to = 0xFE6F, .name = "Small Form Variants" },
.{ .from = 0xFE70, .to = 0xFEFF, .name = "Arabic Presentation Forms-B" },
.{ .from = 0xFF00, .to = 0xFFEF, .name = "Halfwidth and Fullwidth Forms" },
.{ .from = 0xFFF0, .to = 0xFFFF, .name = "Specials" },
.{ .from = 0x10000, .to = 0x1007F, .name = "Linear B Syllabary" },
.{ .from = 0x10080, .to = 0x100FF, .name = "Linear B Ideograms" },
.{ .from = 0x10100, .to = 0x1013F, .name = "Aegean Numbers" },
.{ .from = 0x10140, .to = 0x1018F, .name = "Ancient Greek Numbers" },
.{ .from = 0x10190, .to = 0x101CF, .name = "Ancient Symbols" },
.{ .from = 0x101D0, .to = 0x101FF, .name = "Phaistos Disc" },
.{ .from = 0x10280, .to = 0x1029F, .name = "Lycian" },
.{ .from = 0x102A0, .to = 0x102DF, .name = "Carian" },
.{ .from = 0x102E0, .to = 0x102FF, .name = "Coptic Epact Numbers" },
.{ .from = 0x10300, .to = 0x1032F, .name = "Old Italic" },
.{ .from = 0x10330, .to = 0x1034F, .name = "Gothic" },
.{ .from = 0x10350, .to = 0x1037F, .name = "Old Permic" },
.{ .from = 0x10380, .to = 0x1039F, .name = "Ugaritic" },
.{ .from = 0x103A0, .to = 0x103DF, .name = "Old Persian" },
.{ .from = 0x10400, .to = 0x1044F, .name = "Deseret" },
.{ .from = 0x10450, .to = 0x1047F, .name = "Shavian" },
.{ .from = 0x10480, .to = 0x104AF, .name = "Osmanya" },
.{ .from = 0x104B0, .to = 0x104FF, .name = "Osage" },
.{ .from = 0x10500, .to = 0x1052F, .name = "Elbasan" },
.{ .from = 0x10530, .to = 0x1056F, .name = "<NAME>" },
.{ .from = 0x10600, .to = 0x1077F, .name = "<NAME>" },
.{ .from = 0x10800, .to = 0x1083F, .name = "<NAME>" },
.{ .from = 0x10840, .to = 0x1085F, .name = "Imperial Aramaic" },
.{ .from = 0x10860, .to = 0x1087F, .name = "Palmyrene" },
.{ .from = 0x10880, .to = 0x108AF, .name = "Nabataean" },
.{ .from = 0x108E0, .to = 0x108FF, .name = "Hatran" },
.{ .from = 0x10900, .to = 0x1091F, .name = "Phoenician" },
.{ .from = 0x10920, .to = 0x1093F, .name = "Lydian" },
.{ .from = 0x10980, .to = 0x1099F, .name = "Meroitic Hieroglyphs" },
.{ .from = 0x109A0, .to = 0x109FF, .name = "Mero<NAME>" },
.{ .from = 0x10A00, .to = 0x10A5F, .name = "Kharoshthi" },
.{ .from = 0x10A60, .to = 0x10A7F, .name = "Old South Arabian" },
.{ .from = 0x10A80, .to = 0x10A9F, .name = "Old North Arabian" },
.{ .from = 0x10AC0, .to = 0x10AFF, .name = "Manichaean" },
.{ .from = 0x10B00, .to = 0x10B3F, .name = "Avestan" },
.{ .from = 0x10B40, .to = 0x10B5F, .name = "Inscriptional Parthian" },
.{ .from = 0x10B60, .to = 0x10B7F, .name = "Inscriptional Pahlavi" },
.{ .from = 0x10B80, .to = 0x10BAF, .name = "<NAME>" },
.{ .from = 0x10C00, .to = 0x10C4F, .name = "Old Turkic" },
.{ .from = 0x10C80, .to = 0x10CFF, .name = "Old Hungarian" },
.{ .from = 0x10D00, .to = 0x10D3F, .name = "<NAME>ohingya" },
.{ .from = 0x10E60, .to = 0x10E7F, .name = "Rumi Numeral Symbols" },
.{ .from = 0x10E80, .to = 0x10EBF, .name = "Yezidi" },
.{ .from = 0x10F00, .to = 0x10F2F, .name = "<NAME>" },
.{ .from = 0x10F30, .to = 0x10F6F, .name = "Sogdian" },
.{ .from = 0x10FB0, .to = 0x10FDF, .name = "Chorasmian" },
.{ .from = 0x10FE0, .to = 0x10FFF, .name = "Elymaic" },
.{ .from = 0x11000, .to = 0x1107F, .name = "Brahmi" },
.{ .from = 0x11080, .to = 0x110CF, .name = "Kaithi" },
.{ .from = 0x110D0, .to = 0x110FF, .name = "<NAME>" },
.{ .from = 0x11100, .to = 0x1114F, .name = "Chakma" },
.{ .from = 0x11150, .to = 0x1117F, .name = "Mahajani" },
.{ .from = 0x11180, .to = 0x111DF, .name = "Sharada" },
.{ .from = 0x111E0, .to = 0x111FF, .name = "Sinhala Archaic Numbers" },
.{ .from = 0x11200, .to = 0x1124F, .name = "Khojki" },
.{ .from = 0x11280, .to = 0x112AF, .name = "Multani" },
.{ .from = 0x112B0, .to = 0x112FF, .name = "Khudawadi" },
.{ .from = 0x11300, .to = 0x1137F, .name = "Grantha" },
.{ .from = 0x11400, .to = 0x1147F, .name = "Newa" },
.{ .from = 0x11480, .to = 0x114DF, .name = "Tirhuta" },
.{ .from = 0x11580, .to = 0x115FF, .name = "Siddham" },
.{ .from = 0x11600, .to = 0x1165F, .name = "Modi" },
.{ .from = 0x11660, .to = 0x1167F, .name = "<NAME>" },
.{ .from = 0x11680, .to = 0x116CF, .name = "Takri" },
.{ .from = 0x11700, .to = 0x1173F, .name = "Ahom" },
.{ .from = 0x11800, .to = 0x1184F, .name = "Dogra" },
.{ .from = 0x118A0, .to = 0x118FF, .name = "<NAME>" },
.{ .from = 0x11900, .to = 0x1195F, .name = "<NAME>" },
.{ .from = 0x119A0, .to = 0x119FF, .name = "Nandinagari" },
.{ .from = 0x11A00, .to = 0x11A4F, .name = "<NAME>" },
.{ .from = 0x11A50, .to = 0x11AAF, .name = "Soyombo" },
.{ .from = 0x11AC0, .to = 0x11AFF, .name = "<NAME>" },
.{ .from = 0x11C00, .to = 0x11C6F, .name = "Bhaiksuki" },
.{ .from = 0x11C70, .to = 0x11CBF, .name = "Marchen" },
.{ .from = 0x11D00, .to = 0x11D5F, .name = "<NAME>" },
.{ .from = 0x11D60, .to = 0x11DAF, .name = "<NAME>" },
.{ .from = 0x11EE0, .to = 0x11EFF, .name = "Makasar" },
.{ .from = 0x11FB0, .to = 0x11FBF, .name = "Lisu Supplement" },
.{ .from = 0x11FC0, .to = 0x11FFF, .name = "Tamil Supplement" },
.{ .from = 0x12000, .to = 0x123FF, .name = "Cuneiform" },
.{ .from = 0x12400, .to = 0x1247F, .name = "Cuneiform Numbers and Punctuation" },
.{ .from = 0x12480, .to = 0x1254F, .name = "Early Dynastic Cuneiform" },
.{ .from = 0x13000, .to = 0x1342F, .name = "Egyptian Hieroglyphs" },
.{ .from = 0x13430, .to = 0x1343F, .name = "Egyptian Hieroglyph Format Controls" },
.{ .from = 0x14400, .to = 0x1467F, .name = "Anatolian Hieroglyphs" },
.{ .from = 0x16800, .to = 0x16A3F, .name = "Bamum Supplement" },
.{ .from = 0x16A40, .to = 0x16A6F, .name = "Mro" },
.{ .from = 0x16AD0, .to = 0x16AFF, .name = "Bassa Vah" },
.{ .from = 0x16B00, .to = 0x16B8F, .name = "Pahawh Hmong" },
.{ .from = 0x16E40, .to = 0x16E9F, .name = "Medefaidrin" },
.{ .from = 0x16F00, .to = 0x16F9F, .name = "Miao" },
.{ .from = 0x16FE0, .to = 0x16FFF, .name = "Ideographic Symbols and Punctuation" },
.{ .from = 0x17000, .to = 0x187FF, .name = "Tangut" },
.{ .from = 0x18800, .to = 0x18AFF, .name = "Tangut Components" },
.{ .from = 0x18B00, .to = 0x18CFF, .name = "Khitan Small Script" },
.{ .from = 0x18D00, .to = 0x18D8F, .name = "Tangut Supplement" },
.{ .from = 0x1B000, .to = 0x1B0FF, .name = "Kana Supplement" },
.{ .from = 0x1B100, .to = 0x1B12F, .name = "Kana Extended-A" },
.{ .from = 0x1B130, .to = 0x1B16F, .name = "Small Kana Extension" },
.{ .from = 0x1B170, .to = 0x1B2FF, .name = "Nushu" },
.{ .from = 0x1BC00, .to = 0x1BC9F, .name = "Duployan" },
.{ .from = 0x1BCA0, .to = 0x1BCAF, .name = "Shorthand Format Controls" },
.{ .from = 0x1D000, .to = 0x1D0FF, .name = "Byzantine Musical Symbols" },
.{ .from = 0x1D100, .to = 0x1D1FF, .name = "Musical Symbols" },
.{ .from = 0x1D200, .to = 0x1D24F, .name = "Ancient Greek Musical Notation" },
.{ .from = 0x1D2E0, .to = 0x1D2FF, .name = "Mayan Numerals" },
.{ .from = 0x1D300, .to = 0x1D35F, .name = "Tai Xuan Jing Symbols" },
.{ .from = 0x1D360, .to = 0x1D37F, .name = "Counting Rod Numerals" },
.{ .from = 0x1D400, .to = 0x1D7FF, .name = "Mathematical Alphanumeric Symbols" },
.{ .from = 0x1D800, .to = 0x1DAAF, .name = "Sutton SignWriting" },
.{ .from = 0x1E000, .to = 0x1E02F, .name = "Glagolitic Supplement" },
.{ .from = 0x1E100, .to = 0x1E14F, .name = "<NAME>" },
.{ .from = 0x1E2C0, .to = 0x1E2FF, .name = "Wancho" },
.{ .from = 0x1E800, .to = 0x1E8DF, .name = "<NAME>" },
.{ .from = 0x1E900, .to = 0x1E95F, .name = "Adlam" },
.{ .from = 0x1EC70, .to = 0x1ECBF, .name = "Indic Siyaq Numbers" },
.{ .from = 0x1ED00, .to = 0x1ED4F, .name = "Ottoman Siyaq Numbers" },
.{ .from = 0x1EE00, .to = 0x1EEFF, .name = "Arabic Mathematical Alphabetic Symbols" },
.{ .from = 0x1F000, .to = 0x1F02F, .name = "<NAME>" },
.{ .from = 0x1F030, .to = 0x1F09F, .name = "<NAME>" },
.{ .from = 0x1F0A0, .to = 0x1F0FF, .name = "Playing Cards" },
.{ .from = 0x1F100, .to = 0x1F1FF, .name = "Enclosed Alphanumeric Supplement" },
.{ .from = 0x1F200, .to = 0x1F2FF, .name = "Enclosed Ideographic Supplement" },
.{ .from = 0x1F300, .to = 0x1F5FF, .name = "Miscellaneous Symbols and Pictographs" },
.{ .from = 0x1F600, .to = 0x1F64F, .name = "Emoticons" },
.{ .from = 0x1F650, .to = 0x1F67F, .name = "Ornamental Dingbats" },
.{ .from = 0x1F680, .to = 0x1F6FF, .name = "Transport and Map Symbols" },
.{ .from = 0x1F700, .to = 0x1F77F, .name = "Alchemical Symbols" },
.{ .from = 0x1F780, .to = 0x1F7FF, .name = "Geometric Shapes Extended" },
.{ .from = 0x1F800, .to = 0x1F8FF, .name = "Supplemental Arrows-C" },
.{ .from = 0x1F900, .to = 0x1F9FF, .name = "Supplemental Symbols and Pictographs" },
.{ .from = 0x1FA00, .to = 0x1FA6F, .name = "Chess Symbols" },
.{ .from = 0x1FA70, .to = 0x1FAFF, .name = "Symbols and Pictographs Extended-A" },
.{ .from = 0x1FB00, .to = 0x1FBFF, .name = "Symbols for Legacy Computing" },
.{ .from = 0x20000, .to = 0x2A6DF, .name = "CJK Unified Ideographs Extension B" },
.{ .from = 0x2A700, .to = 0x2B73F, .name = "CJK Unified Ideographs Extension C" },
.{ .from = 0x2B740, .to = 0x2B81F, .name = "CJK Unified Ideographs Extension D" },
.{ .from = 0x2B820, .to = 0x2CEAF, .name = "CJK Unified Ideographs Extension E" },
.{ .from = 0x2CEB0, .to = 0x2EBEF, .name = "CJK Unified Ideographs Extension F" },
.{ .from = 0x2F800, .to = 0x2FA1F, .name = "CJK Compatibility Ideographs Supplement" },
.{ .from = 0x30000, .to = 0x3134F, .name = "CJK Unified Ideographs Extension G" },
.{ .from = 0xE0000, .to = 0xE007F, .name = "Tags" },
.{ .from = 0xE0100, .to = 0xE01EF, .name = "Variation Selectors Supplement" },
.{ .from = 0xF0000, .to = 0xFFFFF, .name = "Supplementary Private Use Area-A" },
.{ .from = 0x100000, .to = 0x10FFFF, .name = "Supplementary Private Use Area-B" },
};
|
src/blocks.zig
|
const std = @import("std");
const hyperia = @import("hyperia.zig");
const mem = std.mem;
const meta = std.meta;
const builtin = std.builtin;
const oneshot = hyperia.oneshot;
pub fn ResultUnionOf(comptime Cases: type) type {
var union_fields: [@typeInfo(Cases).Struct.fields.len]builtin.TypeInfo.UnionField = undefined;
var union_tag = meta.FieldEnum(Cases);
inline for (@typeInfo(Cases).Struct.fields) |field, i| {
const run = meta.fieldInfo(field.field_type, .run).field_type;
const return_type = @typeInfo(@typeInfo(run).Struct.decls[0].data.Var).Fn.return_type.?;
const field_alignment = if (@sizeOf(return_type) > 0) @alignOf(return_type) else 0;
union_fields[i] = .{
.name = field.name,
.field_type = return_type,
.alignment = field_alignment,
};
}
return @Type(builtin.TypeInfo{
.Union = .{
.layout = .Auto,
.tag_type = union_tag,
.fields = &union_fields,
.decls = &.{},
},
});
}
pub fn select(cases: anytype) ResultUnionOf(@TypeOf(cases)) {
const ResultUnion = ResultUnionOf(@TypeOf(cases));
const Channel = oneshot.Channel(ResultUnion);
const Memoized = struct {
pub fn Closure(
comptime C: type,
comptime case_name: []const u8,
) type {
return struct {
fn call(channel: *Channel, case: C) callconv(.Async) void {
const result = @call(.{}, C.function, case.args);
const result_union = @unionInit(ResultUnion, case_name, result);
if (channel.set()) channel.commit(result_union);
}
};
}
};
comptime var types: []const type = &[_]type{};
inline for (@typeInfo(@TypeOf(cases)).Struct.fields) |field| {
const C = Memoized.Closure(@TypeOf(@field(@field(cases, field.name), "run")), field.name);
types = types ++ [_]type{@Frame(C.call)};
}
var frames: meta.Tuple(types) = undefined;
var channel: Channel = .{};
inline for (@typeInfo(@TypeOf(cases)).Struct.fields) |field, i| {
const C = Memoized.Closure(@TypeOf(@field(@field(cases, field.name), "run")), field.name);
frames[i] = async C.call(&channel, @field(@field(cases, field.name), "run"));
}
const result = channel.wait();
const result_idx = @enumToInt(result);
inline for (@typeInfo(@TypeOf(cases)).Struct.fields) |field, i| {
if (i != result_idx) {
if (comptime @hasField(@TypeOf(@field(cases, field.name)), "cancel")) {
const cancel = @field(@field(cases, field.name), "cancel");
@call(comptime .{}, @TypeOf(cancel).function, cancel.args);
}
}
await frames[i];
}
return result;
}
pub fn Case(comptime Function: anytype) type {
return struct {
pub const function = Function;
args: meta.ArgsTuple(@TypeOf(Function)),
};
}
pub fn call(comptime Function: anytype, arguments: anytype) Case(Function) {
var args: meta.ArgsTuple(@TypeOf(Function)) = undefined;
mem.copy(u8, mem.asBytes(&args), mem.asBytes(&arguments));
return .{ .args = args };
}
|
select.zig
|
const std = @import("std");
const zua = @import("zua.zig");
const Token = zua.lex.Token;
// From lopcodes.h:
//
// We assume that instructions are unsigned numbers.
// All instructions have an opcode in the first 6 bits.
// Instructions can have the following fields:
// 'A': 8 bits
// 'B': 9 bits
// 'C': 9 bits
// 'Bx': 18 bits ('B' and 'C' together)
// 'sBx': signed Bx
//
// A signed argument is represented in excess K; that is, the number
// value is the unsigned value minus K. K is exactly the maximum value
// for that argument (so that -max is represented by 0, and +max is
// represented by 2*max), which is half the maximum for the corresponding
// unsigned argument.
pub const OpCode = enum(u6) {
// TODO: rest of the opcodes
move = 0,
loadk = 1,
loadbool = 2,
loadnil = 3,
getglobal = 5,
gettable = 6,
setglobal = 7,
settable = 9,
newtable = 10,
self = 11,
add = 12,
sub = 13,
mul = 14,
div = 15,
mod = 16,
pow = 17,
unm = 18,
len = 20,
concat = 21,
call = 28,
tailcall = 29,
@"return" = 30,
setlist = 34,
vararg = 37,
pub fn InstructionType(op: OpCode) type {
return switch (op) {
.move => Instruction.Move,
.loadk => Instruction.LoadK,
.loadbool => Instruction.LoadBool,
.loadnil => Instruction.LoadNil,
.getglobal => Instruction.GetGlobal,
.gettable => Instruction.GetTable,
.setglobal => Instruction.SetGlobal,
.settable => Instruction.SetTable,
.newtable => Instruction.NewTable,
.self => Instruction.Self,
.add, .sub, .mul, .div, .mod, .pow => Instruction.BinaryMath,
.unm => Instruction.UnaryMinus,
.len => Instruction.Length,
.concat => Instruction.Concat,
.call, .tailcall => Instruction.Call,
.@"return" => Instruction.Return,
.setlist => Instruction.SetList,
.vararg => Instruction.VarArg,
};
}
pub const OpMode = enum {
iABC,
iABx,
iAsBx,
};
// A mapping of OpCode -> OpMode
const op_modes = blk: {
const max_fields = std.math.maxInt(@typeInfo(OpCode).Enum.tag_type);
var array: [max_fields]OpMode = undefined;
for (@typeInfo(OpCode).Enum.fields) |field| {
const Type = @field(OpCode, field.name).InstructionType();
const mode: OpMode = switch (@typeInfo(Type).Struct.fields[0].field_type) {
Instruction.ABC => .iABC,
Instruction.ABx => .iABx,
Instruction.AsBx => .iAsBx,
else => unreachable,
};
array[field.value] = mode;
}
break :blk array;
};
pub fn getOpMode(self: OpCode) OpMode {
return op_modes[@enumToInt(self)];
}
pub const OpArgMask = enum {
NotUsed, // N
Used, // U
RegisterOrJumpOffset, // R
ConstantOrRegisterConstant, // K
};
pub const OpMeta = struct {
b_mode: OpArgMask,
c_mode: OpArgMask,
test_a_mode: bool,
test_t_mode: bool,
};
const op_meta = blk: {
const max_fields = std.math.maxInt(@typeInfo(OpCode).Enum.tag_type);
var array: [max_fields]*const OpMeta = undefined;
for (@typeInfo(OpCode).Enum.fields) |field| {
const Type = @field(OpCode, field.name).InstructionType();
const meta = &@field(Type, "meta");
array[field.value] = meta;
}
break :blk array;
};
pub fn getBMode(self: OpCode) OpArgMask {
return op_meta[@enumToInt(self)].b_mode;
}
pub fn getCMode(self: OpCode) OpArgMask {
return op_meta[@enumToInt(self)].c_mode;
}
// TODO rename
/// instruction set register A
pub fn testAMode(self: OpCode) bool {
return op_meta[@enumToInt(self)].test_a_mode;
}
// TODO rename
/// operator is a test
pub fn testTMode(self: OpCode) bool {
return op_meta[@enumToInt(self)].test_t_mode;
}
};
// R(x) - register
// Kst(x) - constant (in constant table)
// RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
/// SIZE_B define equivalent (lopcodes.h)
const bit_size_b = 9;
/// BITRK define equivalent (lopcodes.h)
const bit_mask_constant: u9 = 1 << (bit_size_b - 1);
/// MAXINDEXRK define equivalent (lopcodes.h)
pub const max_constant_index: u9 = bit_mask_constant - 1;
/// ISK macro equivalent (lopcodes.h)
pub fn isConstant(val: u9) bool {
return val & bit_mask_constant != 0;
}
/// INDEXK macro equivalent (lopcodes.h)
pub fn getConstantIndex(val: u9) u9 {
return val & ~bit_mask_constant;
}
/// RKASK macro equivalent (lopcodes.h)
pub fn constantIndexToRK(val: u9) u9 {
return val | bit_mask_constant;
}
/// To be bit-casted depending on the op field
pub const Instruction = packed struct {
op: OpCode,
a: u8,
fields: u18,
pub const ABC = packed struct {
op: OpCode,
a: u8,
c: u9,
b: u9,
pub fn init(op: OpCode, a: u8, b: u9, c: u9) Instruction.ABC {
return .{
.op = op,
.a = a,
.b = b,
.c = c,
};
}
pub const max_a = std.math.maxInt(u8);
pub const max_b = std.math.maxInt(u9);
pub const max_c = std.math.maxInt(u9);
};
pub const ABx = packed struct {
op: OpCode,
a: u8,
bx: u18,
pub fn init(op: OpCode, a: u8, bx: u18) Instruction.ABx {
return .{
.op = op,
.a = a,
.bx = bx,
};
}
pub const max_bx = std.math.maxInt(u18);
};
pub const AsBx = packed struct {
op: OpCode,
a: u8,
/// Underscore in the name to make it hard to accidentally use this field directly.
/// Stored as unsigned for binary compatibility
_bx: u18,
pub fn init(op: OpCode, a: u8, sbx: i18) Instruction.AsBx {
return .{
.op = op,
.a = a,
._bx = signedBxToUnsigned(sbx),
};
}
pub fn getSignedBx(self: *const Instruction.AsBx) i18 {
return unsignedBxToSigned(self._bx);
}
pub fn setSignedBx(self: *Instruction.AsBx, val: i18) void {
self._bx = signedBxToUnsigned(val);
}
pub const max_sbx = std.math.maxInt(i18);
// Not std.math.minInt because of the subtraction stuff
pub const min_sbx = -max_sbx;
pub fn unsignedBxToSigned(Bx: u18) i18 {
const fitting_int = std.math.IntFittingRange(min_sbx, ABx.max_bx);
return @intCast(i18, @intCast(fitting_int, Bx) - max_sbx);
}
pub fn signedBxToUnsigned(sBx: i18) u18 {
const fitting_int = std.math.IntFittingRange(min_sbx, ABx.max_bx);
return @intCast(u18, @intCast(fitting_int, sBx) + max_sbx);
}
};
pub const Move = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const LoadK = packed struct {
instruction: Instruction.ABx,
pub const meta: OpCode.OpMeta = .{
.b_mode = .ConstantOrRegisterConstant,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const LoadBool = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .Used,
.test_a_mode = true,
.test_t_mode = false,
};
pub fn init(reg: u8, val: bool, does_jump: bool) LoadBool {
return .{
.instruction = Instruction.ABC.init(
.loadbool,
reg,
@boolToInt(val),
@boolToInt(does_jump),
),
};
}
pub fn doesJump(self: *const LoadBool) bool {
return self.instruction.c == 1;
}
};
pub const LoadNil = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const GetGlobal = packed struct {
instruction: Instruction.ABx,
pub const meta: OpCode.OpMeta = .{
.b_mode = .ConstantOrRegisterConstant,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const GetTable = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .ConstantOrRegisterConstant,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const SetGlobal = packed struct {
instruction: Instruction.ABx,
pub const meta: OpCode.OpMeta = .{
.b_mode = .ConstantOrRegisterConstant,
.c_mode = .NotUsed,
.test_a_mode = false,
.test_t_mode = false,
};
};
pub const SetTable = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .ConstantOrRegisterConstant,
.c_mode = .ConstantOrRegisterConstant,
.test_a_mode = false,
.test_t_mode = false,
};
pub fn init(table_reg: u8, key_rk: u9, val_rk: u9) SetTable {
return .{
.instruction = Instruction.ABC.init(
.settable,
table_reg,
key_rk,
val_rk,
),
};
}
};
pub const NewTable = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .Used,
.test_a_mode = true,
.test_t_mode = false,
};
pub fn setArraySize(self: *NewTable, num: zua.object.FloatingPointByteIntType) void {
self.instruction.b = @intCast(u9, zua.object.intToFloatingPointByte(num));
}
pub fn setTableSize(self: *NewTable, num: zua.object.FloatingPointByteIntType) void {
self.instruction.c = @intCast(u9, zua.object.intToFloatingPointByte(num));
}
};
pub const Self = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .ConstantOrRegisterConstant,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const BinaryMath = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .ConstantOrRegisterConstant,
.c_mode = .ConstantOrRegisterConstant,
.test_a_mode = true,
.test_t_mode = false,
};
// TODO what is `a`?
pub fn init(op: OpCode, a: u8, left_rk: u9, right_rk: u9) BinaryMath {
return .{
.instruction = Instruction.ABC.init(
op,
a,
left_rk,
right_rk,
),
};
}
pub fn tokenToOpCode(token: Token) OpCode {
return switch (token.char.?) {
'+' => .add,
'-' => .sub,
'*' => .mul,
'/' => .div,
'%' => .mod,
'^' => .pow,
else => unreachable,
};
}
};
pub const UnaryMinus = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const Length = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
};
pub const Concat = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .RegisterOrJumpOffset,
.c_mode = .RegisterOrJumpOffset,
.test_a_mode = true,
.test_t_mode = false,
};
};
/// Used for both call and tailcall opcodes
pub const Call = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .Used,
.test_a_mode = true,
.test_t_mode = false,
};
pub fn init(base: u8, num_params: u9, num_return_values: ?u9) Call {
const c_val = if (num_return_values != null) num_return_values.? + 1 else 0;
return .{
.instruction = Instruction.ABC.init(
.call,
base,
num_params + 1,
c_val,
),
};
}
pub fn setNumReturnValues(self: *Call, num_return_values: ?u9) void {
if (num_return_values) |v| {
self.instruction.c = v + 1;
} else {
self.instruction.c = 0;
}
}
pub fn getNumReturnValues(self: *const Call) ?u9 {
if (self.isMultipleReturns()) return null;
return self.instruction.c - 1;
}
pub fn isMultipleReturns(self: *const Call) bool {
return self.instruction.c == 0;
}
};
pub const Return = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .NotUsed,
.test_a_mode = false,
.test_t_mode = false,
};
pub fn init(first_return_value_register: u8, num_return_values: ?u9) Return {
const b_val = if (num_return_values != null) num_return_values.? + 1 else 0;
return .{
.instruction = Instruction.ABC.init(
.@"return",
first_return_value_register,
b_val,
0,
),
};
}
pub fn getFirstReturnValueRegister(self: *const Return) u8 {
return self.instruction.a;
}
pub fn setFirstReturnValueRegister(self: *Return, first_return_value_register: u8) void {
self.instruction.a = first_return_value_register;
}
pub fn setNumReturnValues(self: *Return, num_return_values: ?u9) void {
if (num_return_values) |v| {
self.instruction.b = v + 1;
} else {
self.instruction.b = 0;
}
}
pub fn getNumReturnValues(self: *const Return) ?u9 {
if (self.isMultipleReturns()) return null;
return self.instruction.b - 1;
}
pub fn isMultipleReturns(self: *const Return) bool {
return self.instruction.b == 0;
}
};
pub const SetList = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .Used,
.test_a_mode = false,
.test_t_mode = false,
};
// TODO init fn + get/setters as needed, should probably move the logic of setlist
// in compiler to here
pub fn isBatchNumberStoredInNextInstruction(self: *const SetList) bool {
return self.instruction.c == 0;
}
/// equivalent to LFIELDS_PER_FLUSH from lopcodes.h
pub const fields_per_flush = 50;
};
pub const VarArg = packed struct {
instruction: Instruction.ABC,
pub const meta: OpCode.OpMeta = .{
.b_mode = .Used,
.c_mode = .NotUsed,
.test_a_mode = true,
.test_t_mode = false,
};
pub fn init(first_return_value_register: u8, num_return_values: ?u9) VarArg {
const b_val = if (num_return_values != null) num_return_values.? + 1 else 0;
return .{
.instruction = Instruction.ABC.init(
.vararg,
first_return_value_register,
b_val,
0,
),
};
}
pub fn getFirstReturnValueRegister(self: *const VarArg) u8 {
return self.instruction.a;
}
pub fn setFirstReturnValueRegister(self: *VarArg, first_return_value_register: u8) void {
self.instruction.a = first_return_value_register;
}
pub fn setNumReturnValues(self: *VarArg, num_return_values: ?u9) void {
if (num_return_values) |v| {
self.instruction.b = v + 1;
} else {
self.instruction.b = 0;
}
}
pub fn getNumReturnValues(self: *const VarArg) ?u9 {
if (self.isMultipleReturns()) return null;
return self.instruction.b - 1;
}
pub fn isMultipleReturns(self: *const VarArg) bool {
return self.instruction.b == 0;
}
};
};
test "sBx" {
try std.testing.expectEqual(
@as(i18, Instruction.AsBx.min_sbx),
Instruction.AsBx.unsignedBxToSigned(0),
);
const max_sbx_as_bx = Instruction.AsBx.signedBxToUnsigned(Instruction.AsBx.max_sbx);
try std.testing.expectEqual(
@as(i18, Instruction.AsBx.max_sbx),
Instruction.AsBx.unsignedBxToSigned(max_sbx_as_bx),
);
}
|
src/opcodes.zig
|
const std = @import("std");
const net = std.net;
const meta = std.meta;
const Allocator = std.mem.Allocator;
const deflate = std.compress.deflate;
const io = std.io;
const zlib = @import("zlib");
const c = @cImport({
@cInclude("zlib.h");
@cInclude("stddef.h");
});
const mcp = @import("mcproto.zig");
pub const ZlibCompressor = struct {
allocator: Allocator,
stream: *c.z_stream,
const Self = @This();
pub fn init(allocator: Allocator) !Self {
var ret = Self{
.allocator = allocator,
.stream = undefined,
};
ret.stream = try allocator.create(c.z_stream);
errdefer allocator.destroy(ret.stream);
// if the user provides an allocator zlib uses an opaque pointer for
// custom malloc an free callbacks, this requires pinning, so we use
// the allocator to allocate the Allocator struct on the heap
const pinned = try allocator.create(Allocator);
errdefer allocator.destroy(pinned);
pinned.* = allocator;
ret.stream.@"opaque" = pinned;
ret.stream.zalloc = zlib.zalloc;
ret.stream.zfree = zlib.zfree;
const rc = c.deflateInit(ret.stream, c.Z_DEFAULT_COMPRESSION);
return if (rc == c.Z_OK) ret else zlib.errorFromInt(rc);
}
pub fn deinit(self: *Self) void {
const pinned = @ptrCast(*Allocator, @alignCast(@alignOf(*Allocator), self.stream.@"opaque".?));
_ = c.deflateEnd(self.stream);
self.allocator.destroy(pinned);
self.allocator.destroy(self.stream);
}
pub fn reset(self: *Self) void {
_ = c.deflateReset(self.stream);
}
pub fn flush(self: *Self, w: anytype) !void {
var tmp: [4096]u8 = undefined;
while (true) {
self.stream.next_out = &tmp;
self.stream.avail_out = tmp.len;
var rc = c.deflate(self.stream, c.Z_FINISH);
if (rc != c.Z_STREAM_END)
return zlib.errorFromInt(rc);
if (self.stream.avail_out != 0) {
const n = tmp.len - self.stream.avail_out;
try w.writeAll(tmp[0..n]);
break;
} else try w.writeAll(&tmp);
}
}
pub fn WithWriter(comptime WriterType: type) type {
return struct {
const WriterError = zlib.Error || WriterType.Error;
const Writer = io.Writer(InnerSelf, WriterError, write);
inner: WriterType,
parent: *ZlibCompressor,
const InnerSelf = @This();
pub fn write(self: InnerSelf, buf: []const u8) WriterError!usize {
var tmp: [4096]u8 = undefined;
self.parent.stream.next_in = @intToPtr([*]u8, @ptrToInt(buf.ptr));
self.parent.stream.avail_in = @intCast(c_uint, buf.len);
while (true) {
self.parent.stream.next_out = &tmp;
self.parent.stream.avail_out = tmp.len;
var rc = c.deflate(self.parent.stream, c.Z_PARTIAL_FLUSH);
if (rc != c.Z_OK)
return zlib.errorFromInt(rc);
if (self.parent.stream.avail_out != 0) {
const n = tmp.len - self.parent.stream.avail_out;
try self.inner.writeAll(tmp[0..n]);
break;
} else try self.inner.writeAll(&tmp);
}
return buf.len - self.stream.avail_in;
}
};
}
pub fn writer(self: *Self, w: anytype) WithWriter(@TypeOf(w)).Writer {
return .{ .context = WithWriter(@TypeOf(w)){
.inner = w,
.parent = self,
} };
}
};
// modified from stdlib to have an error message separate from EndOfStream
pub fn LimitedReader(comptime ReaderType: type) type {
return struct {
inner_reader: ReaderType,
bytes_left: u64,
pub const Error = ReaderType.Error || error{ReadTooFar};
pub const Reader = io.Reader(*Self, Error, read);
const Self = @This();
pub fn read(self: *Self, dest: []u8) Error!usize {
if (self.bytes_left == 0) return error.ReadTooFar;
const max_read = std.math.min(self.bytes_left, dest.len);
const n = try self.inner_reader.read(dest[0..max_read]);
self.bytes_left -= n;
return n;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn limitedReader(inner_reader: anytype, bytes_left: u64) LimitedReader(@TypeOf(inner_reader)) {
return .{ .inner_reader = inner_reader, .bytes_left = bytes_left };
}
pub fn PacketClient(comptime ReaderType: type, comptime WriterType: type, comptime compression_threshold: ?i32) type {
return struct {
pub const Threshold = compression_threshold;
connection: net.StreamServer.Connection,
reader: io.BufferedReader(1024, ReaderType),
writer: io.BufferedWriter(1024, WriterType),
const Self = @This();
pub fn readHandshakePacket(self: *Self, comptime PacketType: type, alloc: Allocator) !PacketType.UserType {
var len = try mcp.VarInt.deserialize(alloc, self.reader.reader());
if (len == 0xFE) {
return PacketType.UserType.legacy;
}
return try self.readPacketLen(PacketType, alloc, @intCast(usize, len));
}
pub fn readPacket(self: *Self, comptime PacketType: type, alloc: Allocator) !PacketType.UserType {
var len = try mcp.VarInt.deserialize(alloc, self.reader.reader());
return try self.readPacketLen(PacketType, alloc, @intCast(usize, len));
}
usingnamespace if (compression_threshold) |threshold| struct {
pub fn readPacketLen(self: *Self, comptime PacketType: type, alloc: Allocator, len: usize) !PacketType.UserType {
var reader = io.limitedReader(self.reader.reader(), len);
const data_len = try mcp.VarInt.deserialize(alloc, reader.reader());
if (data_len == 0) {
return try PacketType.deserialize(alloc, reader.reader());
} else {
var decompressor = std.compress.zlib.zlibStream(alloc, reader.reader());
defer decompressor.deinit();
return try PacketType.deserialize(alloc, decompressor.reader()); // TODO can these readers not be pointers?
}
}
pub fn writePacket(self: *Self, comptime PacketType: type, packet: PacketType.UserType, compressor: *ZlibCompressor) !void {
const actual_len = @intCast(i32, PacketType.size(packet));
var buf_writer = self.writer.writer();
if (actual_len < compression_threshold) {
try mcp.VarInt.write(actual_len, buf_writer);
try buf_writer.writeByte(0x00); // varint of 0
try PacketType.write(packet, buf_writer);
} else {
// not sure if compression works and im not sure ill try for a while
// update: it does not work. (because it doesnt compile at the moment)
// we need the length of the compressed data :(
var compressed_data = try std.ArrayList(u8).initCapacity(compressor.allocator, threshold);
// yeah i guess ill just use the compressors allocator. we'll see how that goes
defer compressed_data.deinit();
defer compressor.reset();
var compressed_data_writer = compressed_data.writer();
try PacketType.write(packet, compressor.writer(compressed_data_writer));
try mcp.VarInt.write(@intCast(i32, compressed_data.items.len + mcp.VarInt.size(actual_len)), self.writer);
try mcp.VarInt.write(actual_len, buf_writer);
try compressor.flush(compressed_data_writer);
try buf_writer.writeAll(compressed_data.items);
}
try self.writer.flush();
}
pub fn intoUncompressed(self: *Self) PacketClient(ReaderType, WriterType, null) {
return .{
.reader = self.reader,
.writer = self.writer,
};
}
} else struct {
pub fn readPacketLen(self: *Self, comptime PacketType: type, alloc: Allocator, len: usize) !PacketType.UserType {
var lim_reader = limitedReader(self.reader.reader(), len);
var reader = io.countingReader(lim_reader.reader());
const result = PacketType.deserialize(alloc, reader.reader()) catch |err| {
if (err == error.EndOfStream or err == error.ReadTooFar) {
return err;
} else {
// we need to make sure we read the rest, or else the next packet that reads will intersect with this
var r = reader.reader();
while (reader.bytes_read < len) {
_ = try r.readByte();
}
// TODO multiple different types of errors could come out of this. handle properly
// actually it might be fine since the only error that comes out of readByte might be EndOfStream?
return err;
}
};
if (reader.bytes_read < len) {
std.log.info("read {}/{} bytes in packet, is this a group packet?", .{ reader.bytes_read, len });
var r = reader.reader();
std.log.info("next byte in potential group packet is 0x{X}", .{try r.readByte()});
while (reader.bytes_read < len) {
_ = try r.readByte();
}
}
return result;
}
pub fn writePacket(self: *Self, comptime PacketType: type, packet: anytype) !void {
var buf_writer = self.writer.writer();
try mcp.VarInt.write(@intCast(i32, PacketType.size(packet)), buf_writer);
// TODO: fill up rest of packet space with garbage on error?
try PacketType.write(packet, buf_writer);
try self.writer.flush();
}
pub fn intoCompressed(self: *Self, comptime threshold: i32) PacketClient(ReaderType, WriterType, threshold) {
return .{
.reader = self.reader,
.writer = self.writer,
};
}
};
pub fn close(self: *Self) void {
self.connection.stream.close();
}
};
}
pub fn packetClient(conn: net.StreamServer.Connection, reader: anytype, writer: anytype, comptime threshold: ?i32) PacketClient(@TypeOf(reader), @TypeOf(writer), threshold) {
return .{
.connection = conn,
.reader = .{ .unbuffered_reader = reader },
.writer = .{ .unbuffered_writer = writer },
};
}
|
src/mcnet.zig
|
const Coff = @This();
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const coff = std.coff;
const fs = std.fs;
const log = std.log.scoped(.coff);
const mem = std.mem;
const Allocator = mem.Allocator;
const Object = @import("Coff/Object.zig");
const Zld = @import("Zld.zig");
pub const base_tag = Zld.Tag.coff;
base: Zld,
objects: std.ArrayListUnmanaged(Object) = .{},
pub fn openPath(allocator: *Allocator, options: Zld.Options) !*Coff {
const file = try options.emit.directory.createFile(options.emit.sub_path, .{
.truncate = true,
.read = true,
.mode = if (builtin.os.tag == .windows) 0 else 0o777,
});
errdefer file.close();
const self = try createEmpty(allocator, options);
errdefer allocator.destroy(self);
self.base.file = file;
return self;
}
fn createEmpty(gpa: *Allocator, options: Zld.Options) !*Coff {
const self = try gpa.create(Coff);
self.* = .{
.base = .{
.tag = .coff,
.options = options,
.allocator = gpa,
.file = undefined,
},
};
return self;
}
pub fn deinit(self: *Coff) void {
self.closeFiles();
for (self.objects.items) |*object| {
object.deinit(self.base.allocator);
}
self.objects.deinit(self.base.allocator);
}
pub fn closeFiles(self: Coff) void {
for (self.objects.items) |object| {
object.file.close();
}
}
pub fn flush(self: *Coff) !void {
try self.parsePositionals(self.base.options.positionals);
}
fn parsePositionals(self: *Coff, files: []const []const u8) !void {
for (files) |file_name| {
const full_path = full_path: {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
const path = try std.fs.realpath(file_name, &buffer);
break :full_path try self.base.allocator.dupe(u8, path);
};
defer self.base.allocator.free(full_path);
log.debug("parsing input file path '{s}'", .{full_path});
if (try self.parseObject(full_path)) continue;
log.warn("unknown filetype for positional input file: '{s}'", .{file_name});
}
}
fn parseObject(self: *Coff, path: []const u8) !bool {
const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
error.FileNotFound => return false,
else => |e| return e,
};
errdefer file.close();
const name = try self.base.allocator.dupe(u8, path);
errdefer self.base.allocator.free(name);
var object = Object{
.name = name,
.file = file,
};
object.parse(self.base.allocator, self.base.options.target) catch |err| switch (err) {
error.EndOfStream => {
object.deinit(self.base.allocator);
return false;
},
else => |e| return e,
};
try self.objects.append(self.base.allocator, object);
return true;
}
|
src/Coff.zig
|
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const assert = std.debug.assert;
const text = @import("ir/text.zig");
const BigInt = std.math.big.Int;
const Target = std.Target;
/// These are in-memory, analyzed instructions. See `text.Inst` for the representation
/// of instructions that correspond to the ZIR text format.
/// This struct owns the `Value` and `Type` memory. When the struct is deallocated,
/// so are the `Value` and `Type`. The value of a constant must be copied into
/// a memory location for the value to survive after a const instruction.
pub const Inst = struct {
tag: Tag,
ty: Type,
/// Byte offset into the source.
src: usize,
pub const Tag = enum {
unreach,
constant,
assembly,
ptrtoint,
bitcast,
};
pub fn cast(base: *Inst, comptime T: type) ?*T {
if (base.tag != T.base_tag)
return null;
return @fieldParentPtr(T, "base", base);
}
pub fn Args(comptime T: type) type {
return std.meta.fieldInfo(T, "args").field_type;
}
/// Returns `null` if runtime-known.
pub fn value(base: *Inst) ?Value {
return switch (base.tag) {
.unreach => Value.initTag(.noreturn_value),
.constant => base.cast(Constant).?.val,
.assembly,
.ptrtoint,
.bitcast,
=> null,
};
}
pub const Unreach = struct {
pub const base_tag = Tag.unreach;
base: Inst,
args: void,
};
pub const Constant = struct {
pub const base_tag = Tag.constant;
base: Inst,
val: Value,
};
pub const Assembly = struct {
pub const base_tag = Tag.assembly;
base: Inst,
args: struct {
asm_source: []const u8,
is_volatile: bool,
output: ?[]const u8,
inputs: []const []const u8,
clobbers: []const []const u8,
args: []const *Inst,
},
};
pub const PtrToInt = struct {
pub const base_tag = Tag.ptrtoint;
base: Inst,
args: struct {
ptr: *Inst,
},
};
pub const BitCast = struct {
pub const base_tag = Tag.bitcast;
base: Inst,
args: struct {
operand: *Inst,
},
};
};
pub const TypedValue = struct {
ty: Type,
val: Value,
};
pub const Module = struct {
exports: []Export,
errors: []ErrorMsg,
arena: std.heap.ArenaAllocator,
fns: []Fn,
target: Target,
pub const Export = struct {
name: []const u8,
typed_value: TypedValue,
src: usize,
};
pub const Fn = struct {
analysis_status: enum { in_progress, failure, success },
body: []*Inst,
fn_type: Type,
};
pub fn deinit(self: *Module, allocator: *Allocator) void {
allocator.free(self.exports);
allocator.free(self.errors);
self.arena.deinit();
self.* = undefined;
}
};
pub const ErrorMsg = struct {
byte_offset: usize,
msg: []const u8,
};
pub fn analyze(allocator: *Allocator, old_module: text.Module, target: Target) !Module {
var ctx = Analyze{
.allocator = allocator,
.arena = std.heap.ArenaAllocator.init(allocator),
.old_module = &old_module,
.errors = std.ArrayList(ErrorMsg).init(allocator),
.decl_table = std.AutoHashMap(*text.Inst, Analyze.NewDecl).init(allocator),
.exports = std.ArrayList(Module.Export).init(allocator),
.fns = std.ArrayList(Module.Fn).init(allocator),
.target = target,
};
defer ctx.errors.deinit();
defer ctx.decl_table.deinit();
defer ctx.exports.deinit();
defer ctx.fns.deinit();
errdefer ctx.arena.deinit();
ctx.analyzeRoot() catch |err| switch (err) {
error.AnalysisFail => {
assert(ctx.errors.items.len != 0);
},
else => |e| return e,
};
return Module{
.exports = ctx.exports.toOwnedSlice(),
.errors = ctx.errors.toOwnedSlice(),
.fns = ctx.fns.toOwnedSlice(),
.arena = ctx.arena,
.target = target,
};
}
const Analyze = struct {
allocator: *Allocator,
arena: std.heap.ArenaAllocator,
old_module: *const text.Module,
errors: std.ArrayList(ErrorMsg),
decl_table: std.AutoHashMap(*text.Inst, NewDecl),
exports: std.ArrayList(Module.Export),
fns: std.ArrayList(Module.Fn),
target: Target,
const NewDecl = struct {
/// null means a semantic analysis error happened
ptr: ?*Inst,
};
const NewInst = struct {
/// null means a semantic analysis error happened
ptr: ?*Inst,
};
const Fn = struct {
body: std.ArrayList(*Inst),
inst_table: std.AutoHashMap(*text.Inst, NewInst),
/// Index into Module fns array
fn_index: usize,
};
const InnerError = error{ OutOfMemory, AnalysisFail };
fn analyzeRoot(self: *Analyze) !void {
for (self.old_module.decls) |decl| {
if (decl.cast(text.Inst.Export)) |export_inst| {
try analyzeExport(self, null, export_inst);
}
}
}
fn resolveInst(self: *Analyze, opt_func: ?*Fn, old_inst: *text.Inst) InnerError!*Inst {
if (opt_func) |func| {
if (func.inst_table.get(old_inst)) |kv| {
return kv.value.ptr orelse return error.AnalysisFail;
}
}
if (self.decl_table.get(old_inst)) |kv| {
return kv.value.ptr orelse return error.AnalysisFail;
} else {
const new_inst = self.analyzeInst(null, old_inst) catch |err| switch (err) {
error.AnalysisFail => {
try self.decl_table.putNoClobber(old_inst, .{ .ptr = null });
return error.AnalysisFail;
},
else => |e| return e,
};
try self.decl_table.putNoClobber(old_inst, .{ .ptr = new_inst });
return new_inst;
}
}
fn requireFunctionBody(self: *Analyze, func: ?*Fn, src: usize) !*Fn {
return func orelse return self.fail(src, "instruction illegal outside function body", .{});
}
fn resolveInstConst(self: *Analyze, func: ?*Fn, old_inst: *text.Inst) InnerError!TypedValue {
const new_inst = try self.resolveInst(func, old_inst);
const val = try self.resolveConstValue(new_inst);
return TypedValue{
.ty = new_inst.ty,
.val = val,
};
}
fn resolveConstValue(self: *Analyze, base: *Inst) !Value {
return base.value() orelse return self.fail(base.src, "unable to resolve comptime value", .{});
}
fn resolveConstString(self: *Analyze, func: ?*Fn, old_inst: *text.Inst) ![]u8 {
const new_inst = try self.resolveInst(func, old_inst);
const wanted_type = Type.initTag(.const_slice_u8);
const coerced_inst = try self.coerce(func, wanted_type, new_inst);
const val = try self.resolveConstValue(coerced_inst);
return val.toAllocatedBytes(&self.arena.allocator);
}
fn resolveType(self: *Analyze, func: ?*Fn, old_inst: *text.Inst) !Type {
const new_inst = try self.resolveInst(func, old_inst);
const wanted_type = Type.initTag(.@"type");
const coerced_inst = try self.coerce(func, wanted_type, new_inst);
const val = try self.resolveConstValue(coerced_inst);
return val.toType();
}
fn analyzeExport(self: *Analyze, func: ?*Fn, export_inst: *text.Inst.Export) !void {
const symbol_name = try self.resolveConstString(func, export_inst.positionals.symbol_name);
const typed_value = try self.resolveInstConst(func, export_inst.positionals.value);
switch (typed_value.ty.zigTypeTag()) {
.Fn => {},
else => return self.fail(
export_inst.positionals.value.src,
"unable to export type '{}'",
.{typed_value.ty},
),
}
try self.exports.append(.{
.name = symbol_name,
.typed_value = typed_value,
.src = export_inst.base.src,
});
}
/// TODO should not need the cast on the last parameter at the callsites
fn addNewInstArgs(
self: *Analyze,
func: *Fn,
src: usize,
ty: Type,
comptime T: type,
args: Inst.Args(T),
) !*Inst {
const inst = try self.addNewInst(func, src, ty, T);
inst.args = args;
return &inst.base;
}
fn addNewInst(self: *Analyze, func: *Fn, src: usize, ty: Type, comptime T: type) !*T {
const inst = try self.arena.allocator.create(T);
inst.* = .{
.base = .{
.tag = T.base_tag,
.ty = ty,
.src = src,
},
.args = undefined,
};
try func.body.append(&inst.base);
return inst;
}
fn constInst(self: *Analyze, src: usize, typed_value: TypedValue) !*Inst {
const const_inst = try self.arena.allocator.create(Inst.Constant);
const_inst.* = .{
.base = .{
.tag = Inst.Constant.base_tag,
.ty = typed_value.ty,
.src = src,
},
.val = typed_value.val,
};
return &const_inst.base;
}
fn constStr(self: *Analyze, src: usize, str: []const u8) !*Inst {
const array_payload = try self.arena.allocator.create(Type.Payload.Array_u8_Sentinel0);
array_payload.* = .{ .len = str.len };
const ty_payload = try self.arena.allocator.create(Type.Payload.SingleConstPointer);
ty_payload.* = .{ .pointee_type = Type.initPayload(&array_payload.base) };
const bytes_payload = try self.arena.allocator.create(Value.Payload.Bytes);
bytes_payload.* = .{ .data = str };
return self.constInst(src, .{
.ty = Type.initPayload(&ty_payload.base),
.val = Value.initPayload(&bytes_payload.base),
});
}
fn constType(self: *Analyze, src: usize, ty: Type) !*Inst {
return self.constInst(src, .{
.ty = Type.initTag(.type),
.val = try ty.toValue(&self.arena.allocator),
});
}
fn constVoid(self: *Analyze, src: usize) !*Inst {
return self.constInst(src, .{
.ty = Type.initTag(.void),
.val = Value.initTag(.void_value),
});
}
fn constIntUnsigned(self: *Analyze, src: usize, ty: Type, int: u64) !*Inst {
const int_payload = try self.arena.allocator.create(Value.Payload.Int_u64);
int_payload.* = .{ .int = int };
return self.constInst(src, .{
.ty = ty,
.val = Value.initPayload(&int_payload.base),
});
}
fn constIntSigned(self: *Analyze, src: usize, ty: Type, int: i64) !*Inst {
const int_payload = try self.arena.allocator.create(Value.Payload.Int_i64);
int_payload.* = .{ .int = int };
return self.constInst(src, .{
.ty = ty,
.val = Value.initPayload(&int_payload.base),
});
}
fn constIntBig(self: *Analyze, src: usize, ty: Type, big_int: BigInt) !*Inst {
if (big_int.isPositive()) {
if (big_int.to(u64)) |x| {
return self.constIntUnsigned(src, ty, x);
} else |err| switch (err) {
error.NegativeIntoUnsigned => unreachable,
error.TargetTooSmall => {}, // handled below
}
} else {
if (big_int.to(i64)) |x| {
return self.constIntSigned(src, ty, x);
} else |err| switch (err) {
error.NegativeIntoUnsigned => unreachable,
error.TargetTooSmall => {}, // handled below
}
}
const big_int_payload = try self.arena.allocator.create(Value.Payload.IntBig);
big_int_payload.* = .{ .big_int = big_int };
return self.constInst(src, .{
.ty = ty,
.val = Value.initPayload(&big_int_payload.base),
});
}
fn analyzeInst(self: *Analyze, func: ?*Fn, old_inst: *text.Inst) InnerError!*Inst {
switch (old_inst.tag) {
.str => {
// We can use this reference because Inst.Const's Value is arena-allocated.
// The value would get copied to a MemoryCell before the `text.Inst.Str` lifetime ends.
const bytes = old_inst.cast(text.Inst.Str).?.positionals.bytes;
return self.constStr(old_inst.src, bytes);
},
.int => {
const big_int = old_inst.cast(text.Inst.Int).?.positionals.int;
return self.constIntBig(old_inst.src, Type.initTag(.comptime_int), big_int);
},
.ptrtoint => return self.analyzeInstPtrToInt(func, old_inst.cast(text.Inst.PtrToInt).?),
.fieldptr => return self.analyzeInstFieldPtr(func, old_inst.cast(text.Inst.FieldPtr).?),
.deref => return self.analyzeInstDeref(func, old_inst.cast(text.Inst.Deref).?),
.as => return self.analyzeInstAs(func, old_inst.cast(text.Inst.As).?),
.@"asm" => return self.analyzeInstAsm(func, old_inst.cast(text.Inst.Asm).?),
.@"unreachable" => return self.analyzeInstUnreachable(func, old_inst.cast(text.Inst.Unreachable).?),
.@"fn" => return self.analyzeInstFn(func, old_inst.cast(text.Inst.Fn).?),
.@"export" => {
try self.analyzeExport(func, old_inst.cast(text.Inst.Export).?);
return self.constVoid(old_inst.src);
},
.primitive => return self.analyzeInstPrimitive(func, old_inst.cast(text.Inst.Primitive).?),
.fntype => return self.analyzeInstFnType(func, old_inst.cast(text.Inst.FnType).?),
.intcast => return self.analyzeInstIntCast(func, old_inst.cast(text.Inst.IntCast).?),
.bitcast => return self.analyzeInstBitCast(func, old_inst.cast(text.Inst.BitCast).?),
}
}
fn analyzeInstFn(self: *Analyze, opt_func: ?*Fn, fn_inst: *text.Inst.Fn) InnerError!*Inst {
const fn_type = try self.resolveType(opt_func, fn_inst.positionals.fn_type);
var new_func: Fn = .{
.body = std.ArrayList(*Inst).init(self.allocator),
.inst_table = std.AutoHashMap(*text.Inst, NewInst).init(self.allocator),
.fn_index = self.fns.items.len,
};
defer new_func.body.deinit();
defer new_func.inst_table.deinit();
// Don't hang on to a reference to this when analyzing body instructions, since the memory
// could become invalid.
(try self.fns.addOne()).* = .{
.analysis_status = .in_progress,
.fn_type = fn_type,
.body = undefined,
};
for (fn_inst.positionals.body.instructions) |src_inst| {
const new_inst = self.analyzeInst(&new_func, src_inst) catch |err| {
self.fns.items[new_func.fn_index].analysis_status = .failure;
try new_func.inst_table.putNoClobber(src_inst, .{ .ptr = null });
return err;
};
try new_func.inst_table.putNoClobber(src_inst, .{ .ptr = new_inst });
}
const f = &self.fns.items[new_func.fn_index];
f.analysis_status = .success;
f.body = new_func.body.toOwnedSlice();
const fn_payload = try self.arena.allocator.create(Value.Payload.Function);
fn_payload.* = .{ .index = new_func.fn_index };
return self.constInst(fn_inst.base.src, .{
.ty = fn_type,
.val = Value.initPayload(&fn_payload.base),
});
}
fn analyzeInstFnType(self: *Analyze, func: ?*Fn, fntype: *text.Inst.FnType) InnerError!*Inst {
const return_type = try self.resolveType(func, fntype.positionals.return_type);
if (return_type.zigTypeTag() == .NoReturn and
fntype.positionals.param_types.len == 0 and
fntype.kw_args.cc == .Naked)
{
return self.constType(fntype.base.src, Type.initTag(.fn_naked_noreturn_no_args));
}
return self.fail(fntype.base.src, "TODO implement fntype instruction more", .{});
}
fn analyzeInstPrimitive(self: *Analyze, func: ?*Fn, primitive: *text.Inst.Primitive) InnerError!*Inst {
return self.constType(primitive.base.src, primitive.positionals.tag.toType());
}
fn analyzeInstAs(self: *Analyze, func: ?*Fn, as: *text.Inst.As) InnerError!*Inst {
const dest_type = try self.resolveType(func, as.positionals.dest_type);
const new_inst = try self.resolveInst(func, as.positionals.value);
return self.coerce(func, dest_type, new_inst);
}
fn analyzeInstPtrToInt(self: *Analyze, func: ?*Fn, ptrtoint: *text.Inst.PtrToInt) InnerError!*Inst {
const ptr = try self.resolveInst(func, ptrtoint.positionals.ptr);
if (ptr.ty.zigTypeTag() != .Pointer) {
return self.fail(ptrtoint.positionals.ptr.src, "expected pointer, found '{}'", .{ptr.ty});
}
// TODO handle known-pointer-address
const f = try self.requireFunctionBody(func, ptrtoint.base.src);
const ty = Type.initTag(.usize);
return self.addNewInstArgs(f, ptrtoint.base.src, ty, Inst.PtrToInt, Inst.Args(Inst.PtrToInt){ .ptr = ptr });
}
fn analyzeInstFieldPtr(self: *Analyze, func: ?*Fn, fieldptr: *text.Inst.FieldPtr) InnerError!*Inst {
const object_ptr = try self.resolveInst(func, fieldptr.positionals.object_ptr);
const field_name = try self.resolveConstString(func, fieldptr.positionals.field_name);
const elem_ty = switch (object_ptr.ty.zigTypeTag()) {
.Pointer => object_ptr.ty.elemType(),
else => return self.fail(fieldptr.positionals.object_ptr.src, "expected pointer, found '{}'", .{object_ptr.ty}),
};
switch (elem_ty.zigTypeTag()) {
.Array => {
if (mem.eql(u8, field_name, "len")) {
const len_payload = try self.arena.allocator.create(Value.Payload.Int_u64);
len_payload.* = .{ .int = elem_ty.arrayLen() };
const ref_payload = try self.arena.allocator.create(Value.Payload.RefVal);
ref_payload.* = .{ .val = Value.initPayload(&len_payload.base) };
return self.constInst(fieldptr.base.src, .{
.ty = Type.initTag(.single_const_pointer_to_comptime_int),
.val = Value.initPayload(&ref_payload.base),
});
} else {
return self.fail(
fieldptr.positionals.field_name.src,
"no member named '{}' in '{}'",
.{ field_name, elem_ty },
);
}
},
else => return self.fail(fieldptr.base.src, "type '{}' does not support field access", .{elem_ty}),
}
}
fn analyzeInstIntCast(self: *Analyze, func: ?*Fn, intcast: *text.Inst.IntCast) InnerError!*Inst {
const dest_type = try self.resolveType(func, intcast.positionals.dest_type);
const new_inst = try self.resolveInst(func, intcast.positionals.value);
const dest_is_comptime_int = switch (dest_type.zigTypeTag()) {
.ComptimeInt => true,
.Int => false,
else => return self.fail(
intcast.positionals.dest_type.src,
"expected integer type, found '{}'",
.{
dest_type,
},
),
};
switch (new_inst.ty.zigTypeTag()) {
.ComptimeInt, .Int => {},
else => return self.fail(
intcast.positionals.value.src,
"expected integer type, found '{}'",
.{new_inst.ty},
),
}
if (dest_is_comptime_int or new_inst.value() != null) {
return self.coerce(func, dest_type, new_inst);
}
return self.fail(intcast.base.src, "TODO implement analyze widen or shorten int", .{});
}
fn analyzeInstBitCast(self: *Analyze, func: ?*Fn, inst: *text.Inst.BitCast) InnerError!*Inst {
const dest_type = try self.resolveType(func, inst.positionals.dest_type);
const operand = try self.resolveInst(func, inst.positionals.operand);
return self.bitcast(func, dest_type, operand);
}
fn analyzeInstDeref(self: *Analyze, func: ?*Fn, deref: *text.Inst.Deref) InnerError!*Inst {
const ptr = try self.resolveInst(func, deref.positionals.ptr);
const elem_ty = switch (ptr.ty.zigTypeTag()) {
.Pointer => ptr.ty.elemType(),
else => return self.fail(deref.positionals.ptr.src, "expected pointer, found '{}'", .{ptr.ty}),
};
if (ptr.value()) |val| {
return self.constInst(deref.base.src, .{
.ty = elem_ty,
.val = val.pointerDeref(),
});
}
return self.fail(deref.base.src, "TODO implement runtime deref", .{});
}
fn analyzeInstAsm(self: *Analyze, func: ?*Fn, assembly: *text.Inst.Asm) InnerError!*Inst {
const return_type = try self.resolveType(func, assembly.positionals.return_type);
const asm_source = try self.resolveConstString(func, assembly.positionals.asm_source);
const output = if (assembly.kw_args.output) |o| try self.resolveConstString(func, o) else null;
const inputs = try self.arena.allocator.alloc([]const u8, assembly.kw_args.inputs.len);
const clobbers = try self.arena.allocator.alloc([]const u8, assembly.kw_args.clobbers.len);
const args = try self.arena.allocator.alloc(*Inst, assembly.kw_args.args.len);
for (inputs) |*elem, i| {
elem.* = try self.resolveConstString(func, assembly.kw_args.inputs[i]);
}
for (clobbers) |*elem, i| {
elem.* = try self.resolveConstString(func, assembly.kw_args.clobbers[i]);
}
for (args) |*elem, i| {
const arg = try self.resolveInst(func, assembly.kw_args.args[i]);
elem.* = try self.coerce(func, Type.initTag(.usize), arg);
}
const f = try self.requireFunctionBody(func, assembly.base.src);
return self.addNewInstArgs(f, assembly.base.src, return_type, Inst.Assembly, Inst.Args(Inst.Assembly){
.asm_source = asm_source,
.is_volatile = assembly.kw_args.@"volatile",
.output = output,
.inputs = inputs,
.clobbers = clobbers,
.args = args,
});
}
fn analyzeInstUnreachable(self: *Analyze, func: ?*Fn, unreach: *text.Inst.Unreachable) InnerError!*Inst {
const f = try self.requireFunctionBody(func, unreach.base.src);
return self.addNewInstArgs(f, unreach.base.src, Type.initTag(.noreturn), Inst.Unreach, {});
}
fn coerce(self: *Analyze, func: ?*Fn, dest_type: Type, inst: *Inst) !*Inst {
// If the types are the same, we can return the operand.
if (dest_type.eql(inst.ty))
return inst;
const in_memory_result = coerceInMemoryAllowed(dest_type, inst.ty);
if (in_memory_result == .ok) {
return self.bitcast(func, dest_type, inst);
}
// *[N]T to []T
if (inst.ty.isSinglePointer() and dest_type.isSlice() and
(!inst.ty.pointerIsConst() or dest_type.pointerIsConst()))
{
const array_type = inst.ty.elemType();
const dst_elem_type = dest_type.elemType();
if (array_type.zigTypeTag() == .Array and
coerceInMemoryAllowed(dst_elem_type, array_type.elemType()) == .ok)
{
return self.coerceArrayPtrToSlice(dest_type, inst);
}
}
// comptime_int to fixed-width integer
if (inst.ty.zigTypeTag() == .ComptimeInt and dest_type.zigTypeTag() == .Int) {
// The representation is already correct; we only need to make sure it fits in the destination type.
const val = inst.value().?; // comptime_int always has comptime known value
if (!val.intFitsInType(dest_type, self.target)) {
return self.fail(inst.src, "type {} cannot represent integer value {}", .{ inst.ty, val });
}
return self.constInst(inst.src, .{ .ty = dest_type, .val = val });
}
return self.fail(inst.src, "TODO implement type coercion", .{});
}
fn bitcast(self: *Analyze, func: ?*Fn, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
// Keep the comptime Value representation; take the new type.
return self.constInst(inst.src, .{ .ty = dest_type, .val = val });
}
// TODO validate the type size and other compile errors
const f = try self.requireFunctionBody(func, inst.src);
return self.addNewInstArgs(f, inst.src, dest_type, Inst.BitCast, Inst.Args(Inst.BitCast){ .operand = inst });
}
fn coerceArrayPtrToSlice(self: *Analyze, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
// The comptime Value representation is compatible with both types.
return self.constInst(inst.src, .{ .ty = dest_type, .val = val });
}
return self.fail(inst.src, "TODO implement coerceArrayPtrToSlice runtime instruction", .{});
}
fn fail(self: *Analyze, src: usize, comptime format: []const u8, args: var) InnerError {
@setCold(true);
const msg = try std.fmt.allocPrint(&self.arena.allocator, format, args);
(try self.errors.addOne()).* = .{
.byte_offset = src,
.msg = msg,
};
return error.AnalysisFail;
}
const InMemoryCoercionResult = enum {
ok,
no_match,
};
fn coerceInMemoryAllowed(dest_type: Type, src_type: Type) InMemoryCoercionResult {
if (dest_type.eql(src_type))
return .ok;
// TODO: implement more of this function
return .no_match;
}
};
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = if (std.builtin.link_libc) std.heap.c_allocator else &arena.allocator;
const args = try std.process.argsAlloc(allocator);
const src_path = args[1];
const debug_error_trace = true;
const source = try std.fs.cwd().readFileAllocOptions(allocator, src_path, std.math.maxInt(u32), 1, 0);
var zir_module = try text.parse(allocator, source);
defer zir_module.deinit(allocator);
if (zir_module.errors.len != 0) {
for (zir_module.errors) |err_msg| {
const loc = findLineColumn(source, err_msg.byte_offset);
std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg });
}
if (debug_error_trace) return error.ParseFailure;
std.process.exit(1);
}
const native_info = try std.zig.system.NativeTargetInfo.detect(allocator, .{});
var analyzed_module = try analyze(allocator, zir_module, native_info.target);
defer analyzed_module.deinit(allocator);
if (analyzed_module.errors.len != 0) {
for (analyzed_module.errors) |err_msg| {
const loc = findLineColumn(source, err_msg.byte_offset);
std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg });
}
if (debug_error_trace) return error.ParseFailure;
std.process.exit(1);
}
const output_zir = true;
if (output_zir) {
var new_zir_module = try text.emit_zir(allocator, analyzed_module);
defer new_zir_module.deinit(allocator);
var bos = std.io.bufferedOutStream(std.io.getStdOut().outStream());
try new_zir_module.writeToStream(allocator, bos.outStream());
try bos.flush();
}
const link = @import("link.zig");
var result = try link.updateExecutableFilePath(allocator, analyzed_module, std.fs.cwd(), "a.out");
defer result.deinit(allocator);
if (result.errors.len != 0) {
for (result.errors) |err_msg| {
const loc = findLineColumn(source, err_msg.byte_offset);
std.debug.warn("{}:{}:{}: error: {}\n", .{ src_path, loc.line + 1, loc.column + 1, err_msg.msg });
}
if (debug_error_trace) return error.ParseFailure;
std.process.exit(1);
}
}
fn findLineColumn(source: []const u8, byte_offset: usize) struct { line: usize, column: usize } {
var line: usize = 0;
var column: usize = 0;
for (source[0..byte_offset]) |byte| {
switch (byte) {
'\n' => {
line += 1;
column = 0;
},
else => {
column += 1;
},
}
}
return .{ .line = line, .column = column };
}
// Performance optimization ideas:
// * when analyzing use a field in the Inst instead of HashMap to track corresponding instructions
|
src-self-hosted/ir.zig
|
const std = @import("std");
const Builder = std.build.Builder;
const Pkg = std.build.Pkg;
const Step = std.build.Step;
const debug = std.debug;
const Allocator = std.mem.Allocator;
const CrossTarget = std.zig.CrossTarget;
const ClumsyArch = enum { x86, x64 };
const ClumsyConf = enum { Debug, Release, Ship };
const ClumsyWinDivertSign = enum { A, B, C };
pub fn build(b: *std.build.Builder) void {
const arch = b.option(ClumsyArch, "arch", "x86, x64") orelse .x64;
const conf = b.option(ClumsyConf, "conf", "Debug, Release") orelse .Debug;
const windivert_sign = b.option(ClumsyWinDivertSign, "sign", "A, B, C") orelse .A;
const windows_kit_bin_root = b.option([]const u8, "windows_kit_bin_root", "Windows SDK Bin root") orelse "C:/Program Files (x86)/Windows Kits/10/bin/10.0.19041.0";
const arch_tag = @tagName(arch);
const conf_tag = @tagName(conf);
const sign_tag = @tagName(windivert_sign);
const windivert_dir = b.fmt("WinDivert-2.2.0-{s}", .{sign_tag});
debug.print("- arch: {s}, conf: {s}, sign: {s}\n", .{@tagName(arch), @tagName(conf), @tagName(windivert_sign)});
debug.print("- windows_kit_bin_root: {s}\n", .{windows_kit_bin_root});
_ = std.fs.realpathAlloc(b.allocator, windows_kit_bin_root) catch @panic("windows_kit_bin_root not found");
const prefix = b.fmt("{s}_{s}_{s}", .{arch_tag, conf_tag, sign_tag});
b.exe_dir = b.fmt("{s}/{s}", .{b.install_path, prefix});
debug.print("- out: {s}\n", .{b.exe_dir});
const tmp_path = b.fmt("tmp/{s}", .{prefix});
b.makePath(tmp_path) catch @panic("unable to create tmp directory");
b.installFile(b.fmt("external/{s}/{s}/WinDivert.dll", .{windivert_dir, arch_tag}), b.fmt("{s}/WinDivert.dll", .{prefix}));
switch (arch) {
.x64 => b.installFile(b.fmt("external/{s}/{s}/WinDivert64.sys", .{windivert_dir, arch_tag}), b.fmt("{s}/WinDivert64.sys", .{prefix})),
.x86 => b.installFile(b.fmt("external/{s}/{s}/WinDivert32.sys", .{windivert_dir, arch_tag}), b.fmt("{s}/WinDivert32.sys", .{prefix})),
}
b.installFile("etc/config.txt", b.fmt("{s}/config.txt", .{prefix}));
if (conf == .Ship)
b.installFile("LICENSE", b.fmt("{s}/License.txt", .{prefix}));
const res_obj_path = b.fmt("{s}/clumsy_res.obj", .{tmp_path});
const rc_exe = b.findProgram(&.{
"rc",
}, &.{
b.pathJoin(&.{windows_kit_bin_root, @tagName(arch)}),
}) catch @panic("unable to find `rc.exe`, check your windows_kit_bin_root");
const archFlag = switch (arch) {
.x86 => "X86",
.x64 => "X64",
};
const cmd = b.addSystemCommand(&.{
rc_exe,
"/nologo",
"/d",
"NDEBUG",
"/d",
archFlag,
"/r",
"/fo",
res_obj_path,
"etc/clumsy.rc",
});
const exe = b.addExecutable("clumsy", null);
switch (conf) {
.Debug => {
exe.setBuildMode(.Debug);
exe.subsystem = .Console;
},
.Release => {
exe.setBuildMode(.ReleaseSafe);
exe.subsystem = .Windows;
},
.Ship => {
exe.setBuildMode(.ReleaseFast);
exe.subsystem = .Windows;
},
}
const triple = switch (arch) {
.x64 => "x86_64-windows-gnu",
.x86 => "i386-windows-gnu",
};
const target = CrossTarget.parse(.{
.arch_os_abi = triple,
}) catch unreachable;
exe.setTarget(target);
exe.step.dependOn(&cmd.step);
exe.addObjectFile(res_obj_path);
exe.addCSourceFile("src/bandwidth.c", &.{""});
exe.addCSourceFile("src/divert.c", &.{""});
exe.addCSourceFile("src/drop.c", &.{""});
exe.addCSourceFile("src/duplicate.c", &.{""});
exe.addCSourceFile("src/elevate.c", &.{""});
exe.addCSourceFile("src/lag.c", &.{""});
exe.addCSourceFile("src/main.c", &.{""});
exe.addCSourceFile("src/ood.c", &.{""});
exe.addCSourceFile("src/packet.c", &.{""});
exe.addCSourceFile("src/reset.c", &.{""});
exe.addCSourceFile("src/tamper.c", &.{""});
exe.addCSourceFile("src/throttle.c", &.{""});
exe.addCSourceFile("src/utils.c", &.{""});
exe.addCSourceFile("src/utils.c", &.{""});
if (arch == .x86)
exe.addCSourceFile("etc/chkstk.s", &.{""});
exe.addIncludeDir(b.fmt("external/{s}/include", .{windivert_dir}));
const iupLib = switch (arch) {
.x64 => "external/iup-3.30_Win64_mingw6_lib",
.x86 => "external/iup-3.30_Win32_mingw6_lib",
};
exe.addIncludeDir(b.pathJoin(&.{iupLib, "include"}));
exe.addCSourceFile(b.pathJoin(&.{iupLib, "libiup.a"}), &.{""});
exe.linkLibC();
exe.addLibPath(b.fmt("external/{s}/{s}", .{windivert_dir, arch_tag}));
exe.linkSystemLibrary("WinDivert");
exe.linkSystemLibrary("comctl32");
exe.linkSystemLibrary("Winmm");
exe.linkSystemLibrary("ws2_32");
exe.linkSystemLibrary("kernel32");
exe.linkSystemLibrary("gdi32");
exe.linkSystemLibrary("comdlg32");
exe.linkSystemLibrary("uuid");
exe.linkSystemLibrary("ole32");
const exe_install_step = b.addInstallArtifact(exe);
if (conf == .Ship)
{
const remove_pdb_step = RemoveOutFile.create(b, "clumsy.pdb");
remove_pdb_step.step.dependOn(&exe_install_step.step);
b.getInstallStep().dependOn(&remove_pdb_step.step);
}
else
{
b.getInstallStep().dependOn(&exe_install_step.step);
}
const clean_all = b.step("clean", "purge zig-cache and zig-out");
clean_all.dependOn(&b.addRemoveDirTree(b.install_path).step);
// TODO can't clean cache atm since build.exe is in it
// clean_all.dependOn(&b.addRemoveDirTree("zig-cache").step);
}
pub const RemoveOutFile = struct {
step: Step,
builder: *Builder,
rel_path: []const u8,
pub fn create(builder: *Builder, rel_path: []const u8) *@This() {
const self = builder.allocator.create(@This()) catch unreachable;
self.* = . {
.step = Step.init(.custom, builder.fmt("RemoveOutFile {s}", .{rel_path}), builder.allocator, make),
.builder = builder,
.rel_path = rel_path,
};
return self;
}
fn make(step: *Step) anyerror!void {
const self = @fieldParentPtr(RemoveOutFile, "step", step);
const out_dir = try std.fs.openDirAbsolute(self.builder.exe_dir, .{});
try out_dir.deleteFile(self.rel_path);
}
};
|
build.zig
|
const std = @import("std");
const Ip4Packet = @This();
pub const Flags = enum(u3) {
dont_fragment = 0b010,
more_fragments = 0b001,
_,
};
pub const Protocol = enum(u8) {
ipv6_hop_by_hop = 0,
icmpv4 = 1,
igmp = 2,
ipv4 = 4,
tcp = 6,
udp = 17,
rudp = 27,
ipv6 = 41,
ipv6_routing = 43,
ipv6_fragment = 44,
gre = 47,
esp = 50,
ah = 51,
icmpv6 = 58,
no_next_header = 59,
ipv6_destination = 60,
ospf = 89,
ipip = 94,
etherip = 97,
vrrp = 112,
sctp = 132,
udp_lite = 136,
mpls_in_ip = 137,
_,
};
pub const OptionKind = enum(u8) {
/// End of Option List
eool = 0,
/// No Operation
nop = 1,
/// Security (defunct)
sec_defunct = 2,
/// Record Route
rr = 7,
/// Experimental Measurement
zsu = 10,
/// MTU Probe
mtup = 11,
/// MTU Reply
mtur = 12,
/// ENCODE
encode = 15,
/// Quick-Start
qs = 25,
/// RFC3692-style Experiment
exp1 = 30,
/// Time Stamp
ts = 68,
/// Traceroute
tr = 82,
/// RFC3692-style Experiment
exp2 = 94,
/// Security (RIPSO)
sec = 130,
/// Loose Source Route
lsr = 131,
/// Extended Security (RIPSO)
e_sec = 133,
/// Commercial IP Security Option
cipso = 134,
/// Stream ID
sid = 136,
/// Strict Source Route
ssr = 137,
/// Experimental Access Control
visa = 142,
/// IMI Traffic Descriptor
imitd = 144,
/// Extended Internet Protocol
eip = 145,
/// Address Extension
addext = 147,
/// Router Alert
rtralt = 148,
/// Selective Directed Broadcast
sdb = 149,
/// Dynamic Packet State
dps = 151,
/// Upstream Multicast Pkt.
ump = 152,
/// RFC3692-style Experiment
exp3 = 158,
/// Experimental Flow Control
finn = 205,
/// RFC3692-style Experiment
exp4 = 222,
pub fn isExperiment(self: OptionKind) bool {
return self == .exp1 or self == .exp2 or self == .exp3 or self == .exp4;
}
};
pub const Option = struct {
kind: OptionKind,
data: []u8,
};
version: u4,
/// Multiply by 32 to get the header length in bits, by 4 to get it in bytes!
header_length: u4,
/// Differentiated Services Code Point, used by real-time data
dscp: u6,
/// Explicit Congestion Notification
ecn: u2,
total_length: u16,
id: u16,
flags: Flags,
fragment_offset: u13,
ttl: u8,
protocol: Protocol,
checksum: u16,
source_ip: [4]u8,
destination_ip: [4]u8,
options: std.ArrayListUnmanaged(Option),
payload: []u8,
pub fn decode(allocator: *std.mem.Allocator, data: []const u8) !Ip4Packet {
var reader = std.io.fixedBufferStream(data).reader();
if (data.len < 20)
return error.TooShort;
var packet: Ip4Packet = undefined;
var byte = try reader.readByte();
packet.version = @truncate(u4, byte >> 4);
if (packet.version != 4)
return error.InvalidVersion;
packet.header_length = @truncate(u4, byte & 0b1111);
byte = try reader.readByte();
packet.dscp = @truncate(u6, byte >> 2);
packet.ecn = @truncate(u2, byte & 0b11);
packet.total_length = try reader.readIntBig(u16);
packet.id = try reader.readIntBig(u16);
var two_bytes = try reader.readIntBig(u16);
packet.flags = @intToEnum(Flags, @truncate(u3, two_bytes >> 13));
packet.fragment_offset = @truncate(u13, two_bytes & 0b1111111111111);
packet.ttl = try reader.readIntBig(u8);
packet.protocol = @intToEnum(Protocol, try reader.readIntBig(u8));
packet.checksum = try reader.readIntBig(u16);
_ = try reader.readAll(&packet.source_ip);
_ = try reader.readAll(&packet.destination_ip);
if (packet.total_length < 20 or packet.header_length < 5) {
return error.TooShort;
} else if (@as(u8, packet.header_length) * 4 > packet.total_length) {
return error.InvalidLength;
}
packet.options = std.ArrayListUnmanaged(Option){};
packet.payload = try allocator.dupe(u8, data[@as(u8, packet.header_length) * 4 ..]);
var options_counter = packet.header_length;
while (options_counter > 5) : (options_counter -= 1) {
if (packet.options.capacity == 0)
try packet.options.ensureTotalCapacity(allocator, 4);
var kind = @intToEnum(OptionKind, try reader.readByte());
switch (kind) {
.eool, .nop => {},
else => {
var option = try packet.options.addOne(allocator);
option.kind = kind;
var length = try reader.readByte();
if (length <= 2)
return error.OptionTooSmall;
option.data = try allocator.alloc(u8, length);
_ = try reader.readAll(option.data);
},
}
}
return packet;
}
pub fn deinit(self: *Ip4Packet, allocator: *std.mem.Allocator) void {
self.options.deinit(allocator);
allocator.free(self.payload);
}
test "Basic TCP packet parsing (example.com)" {
const raw_packet = @embedFile("test-data/ip4/example.com.bin");
var packet = try decode(std.testing.allocator, raw_packet);
defer packet.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(u4, 4), packet.version);
try std.testing.expectEqual(@as(u4, 5), packet.header_length);
try std.testing.expectEqual(@as(u6, 0), packet.dscp);
try std.testing.expectEqual(@as(u2, 0), packet.ecn);
try std.testing.expectEqual(@as(u16, 478), packet.total_length);
try std.testing.expectEqual(@as(u16, 33239), packet.id);
try std.testing.expectEqual(Flags.dont_fragment, packet.flags);
try std.testing.expectEqual(@as(u13, 0), packet.fragment_offset);
try std.testing.expectEqual(@as(u8, 128), packet.ttl);
try std.testing.expectEqual(Protocol.tcp, packet.protocol);
try std.testing.expectEqual(@as(u16, 0), packet.checksum);
try std.testing.expectEqual([4]u8{ 192, 168, 0, 112 }, packet.source_ip);
try std.testing.expectEqual([4]u8{ 93, 184, 216, 34 }, packet.destination_ip);
}
|
src/Ip4Packet.zig
|
// Copyright (c) 2015 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
const std = @import("std");
const c = @cImport({ @cInclude("stb_image.h"); });
pub const Png = struct {
width: u32,
height: u32,
pitch: u32,
raw: []u8,
pub fn destroy(pi: *PngImage) void {
stbi_image_free(pi.raw.ptr);
}
pub fn create(compressed_bytes: []const u8) !Png {
var pi: Png = undefined;
var width: c_int = undefined;
var height: c_int = undefined;
if (c.stbi_info_from_memory(compressed_bytes.ptr, @intCast(c_int, compressed_bytes.len), &width, &height, null) == 0) {
return error.NotPngFile;
}
if (width <= 0 or height <= 0) return error.NoPixels;
pi.width = @intCast(u32, width);
pi.height = @intCast(u32, height);
if (c.stbi_is_16_bit_from_memory(compressed_bytes.ptr, @intCast(c_int, compressed_bytes.len)) != 0) {
return error.InvalidFormat;
}
const bits_per_channel = 8;
const channel_count = 4;
const image_data = c.stbi_load_from_memory(compressed_bytes.ptr, @intCast(c_int, compressed_bytes.len), &width, &height, null, channel_count);
if (image_data == null) return error.NoMem;
pi.pitch = pi.width * bits_per_channel * channel_count / 8;
pi.raw = image_data[0 .. pi.height * pi.pitch];
return pi;
}
pub fn fromFile(filename: []const u8) !Png {
const file = try std.fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
var buffer: [9012]u8 = undefined; // Yes, i know this is "hacky", but it seems to work :)
try file.seekTo(0);
const bytes_read = try file.readAll(&buffer);
return Png.create(buffer[0..bytes_read]);
}
};
|
src/fileformats/glue.zig
|
const std = @import("std");
const openssl = @cImport({
@cInclude("openssl/crypto.h");
@cInclude("openssl/obj_mac.h");
@cInclude("openssl/ec.h");
@cInclude("openssl/err.h");
@cInclude("openssl/evp.h");
});
const crypto = std.crypto;
const builtin = std.builtin;
const aes = crypto.core.aes;
const hmac = crypto.auth.hmac;
const Key = struct {
key: ?*openssl.EC_KEY,
skey: ?*const openssl.BIGNUM,
// Generate a new key
pub fn generate() !Key {
var this = Key{ .key = null, .skey = null };
std.log.info("NID: {}", .{openssl.NID_secp256k1});
this.key = openssl.EC_KEY_new_by_curve_name(openssl.NID_secp256k1);
if (this.key == null) {
std.log.info("could not create key: {}", .{openssl.ERR_get_error()});
return error.CouldNotCreateKey;
}
errdefer openssl.EC_KEY_free(this.key.?);
if (openssl.EC_KEY_generate_key(this.key.?) != 1) {
std.log.info("could not generate random key: {}", .{openssl.ERR_get_error()});
return error.CouldNotGenerateKey;
}
if (openssl.EC_KEY_check_key(this.key.?) != 1) {
return error.GeneratedKeyIsNotValid;
}
this.skey = openssl.EC_KEY_get0_private_key(this.key);
if (this.skey == null) {
std.log.info("could not get private key: {}", .{openssl.ERR_get_error()});
return error.CouldNotGetPrivateKey;
}
std.log.info("secret key: {}", .{@ptrCast([*:0]u8, openssl.BN_bn2hex(this.skey.?))});
return this;
}
// a helper function to serialize the other party's key in these tests.
pub fn from_coordinates(x_str: [*c]const u8, y_str: [*c]const u8) !Key {
var newkey = openssl.EC_KEY_new_by_curve_name(openssl.NID_secp256k1);
if (newkey == null) {
std.log.info("could not create the public key: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotCreateBobsPublicKey;
}
errdefer openssl.EC_KEY_free(newkey);
var x_bob = openssl.BN_new();
if (openssl.BN_hex2bn(&x_bob, x_str) == 1) {
return error.InvalidXCoordinate;
}
defer openssl.BN_clear_free(x_bob);
var y_bob = openssl.BN_new();
if (openssl.BN_hex2bn(&y_bob, y_str) == 1) {
return error.InvalidYCoordinate;
}
defer openssl.BN_clear_free(y_bob);
if (openssl.EC_KEY_set_public_key_affine_coordinates(newkey, x_bob, y_bob) == 0) {
std.log.info("could not set public key: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotSetBobsPublicKey;
}
if (openssl.EC_KEY_check_key(newkey) != 1) {
return error.BobsKeyIsNotValid;
}
return Key{
.key = newkey,
.skey = null,
};
}
pub fn generate_shared(self: Key, other: Key) !*openssl.EC_POINT {
const grp = self.group();
// S = Kb*r
var spoint = openssl.EC_POINT_new(grp);
if (spoint == null) {
std.log.info("could not create r: {}", .{openssl.ERR_get_error()});
return error.CouldNotCreateS;
}
var one = openssl.BN_new();
if (openssl.BN_one(one) != 1) {
return error.CouldNotSetOne;
}
var zero = openssl.BN_new();
if (openssl.BN_zero(zero) != 1) {
return error.CouldNotSetZero;
}
// S = 0*G + r*Kb
const rp = try other.pubkey();
if (openssl.EC_POINT_mul(grp, spoint, one, rp.get_point(), self.skey.?, null) != 1) {
std.log.info("could not compute S: {}", .{openssl.ERR_get_error()});
return error.CouldNotComputeS;
}
// check S != 0
if (openssl.EC_POINT_is_at_infinity(grp, spoint) == 1) {
return error.SAtInfinity;
}
return spoint.?;
}
pub fn pubkey(self: Key) !PubKey {
var pkey = openssl.EC_KEY_get0_public_key(self.key.?);
if (pkey == null) {
std.log.info("could not get public key: {}", .{openssl.ERR_get_error()});
return error.CouldNotGetPublicKey;
}
return PubKey.from_EC_POINT(pkey.?);
}
pub fn group(self: Key) *const openssl.EC_GROUP {
return openssl.EC_KEY_get0_group(self.key.?).?;
}
pub fn serialize(self: Key, out: []u8) !void {
return (try self.pubkey()).serialize(self.group(), out[0..]);
}
pub fn free(self: Key) void {
openssl.EC_KEY_free(self.key.?);
}
};
const PubKey = struct {
point: *const openssl.EC_POINT,
pub fn get_point(self: PubKey) *const openssl.EC_POINT {
return self.point;
}
pub fn from_EC_POINT(point: *const openssl.EC_POINT) PubKey {
return PubKey{ .point = point };
}
pub fn x(self: PubKey, grp: *const openssl.EC_GROUP, out: *[32]u8) !void {
var coord = openssl.BN_new();
defer openssl.BN_clear_free(coord);
if (openssl.EC_POINT_get_affine_coordinates_GFp(grp, self.point, coord, null, null) != 1) {
std.log.info("could not compute S: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetXCoordinate;
}
if (openssl.BN_bn2bin(coord, out) != 32) {
std.log.info("could not get bytes: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetBytes;
}
}
pub fn y(self: PubKey, grp: *const openssl.EC_GROUP, out: *[32]u8) !void {
var coord = openssl.BN_new();
defer openssl.BN_clear_free(coord);
if (openssl.EC_POINT_get_affine_coordinates_GFp(grp, self.point, null, coord, null) != 1) {
std.log.info("could not compute S: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetXCoordinate;
}
if (openssl.BN_bn2bin(coord, out) != 32) {
std.log.info("could not get bytes: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetBytes;
}
}
pub fn serialize(self: PubKey, grp: *const openssl.EC_GROUP, out: []u8) !void {
if (out.len < 65) {
return error.NotEnoughMemoryToSerialize;
}
out[0] = 4;
try self.x(grp, out[1..33]);
try self.y(grp, out[33..65]);
}
};
fn get_x_coordinate(point: *const openssl.EC_POINT, group: *const openssl.EC_GROUP, out: *[32]u8) !void {
var x = openssl.BN_new();
defer openssl.BN_clear_free(x);
if (openssl.EC_POINT_get_affine_coordinates_GFp(group, point, x, null, null) != 1) {
std.log.info("could not compute S: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetXCoordinate;
}
if (openssl.BN_bn2bin(x, out) != 32) {
std.log.info("could not get bytes: {}", .{@ptrCast([*:0]const u8, openssl.ERR_reason_error_string(openssl.ERR_get_error()))});
return error.CouldNotGetBytes;
}
}
fn kdf(key: *std.ArrayList(u8), len: usize, z: []const u8, s1: ?[]const u8) !void {
const digest_length = crypto.hash.sha3.Sha3_256.digest_length;
var counter: u32 = 1;
var counter_bytes = [4]u8{ 0, 0, 0, 0 };
const aligned_len = len + (digest_length - len % digest_length) % digest_length;
while (key.items.len < aligned_len) : (counter += 1) {
var hasher = crypto.hash.sha3.Sha3_256.init(crypto.hash.sha3.Sha3_256.Options{});
std.mem.writeIntBig(u32, counter_bytes[0..], counter);
hasher.update(counter_bytes[0..]);
hasher.update(z);
if (s1 != null)
hasher.update(s1.?);
var k: [32]u8 = undefined;
hasher.final(&k);
_ = try key.writer().write(k[0..]);
}
}
pub fn main() anyerror!void {
var err = openssl.OPENSSL_init_crypto(openssl.OPENSSL_INIT_LOAD_CONFIG, null);
if (err == 0) {
std.log.info("error initializing openssl: {}", .{openssl.ERR_get_error()});
}
defer openssl.OPENSSL_cleanup();
std.log.info("initialized", .{});
const r = try Key.generate();
defer r.free();
// Prepare Kb
var keybob = try Key.from_coordinates("<KEY>", "<KEY>");
defer keybob.free();
// Shared secret
var spoint = try r.generate_shared(keybob);
defer openssl.EC_POINT_clear_free(spoint);
var s: [32]u8 = undefined;
try get_x_coordinate(spoint, keybob.group(), &s);
std.log.info("s={x}", .{s});
// KDF
var buffer = std.ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();
try kdf(&buffer, 32, s[0..], null);
const ke = buffer.items[0..16];
const km = buffer.items[16..];
std.log.info("ke={x} km={x} {} {}", .{ ke, km, ke.len, km.len });
var in = "I love croissants very, very much";
const serlen = 65; // Length of a serialized point
var out: [serlen + in.len + hmac.sha2.HmacSha256.mac_length]u8 = undefined;
try r.serialize(out[0..serlen]);
// AES encryption
const iv = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
var ctx = aes.Aes128.initEnc(ke.*);
crypto.core.modes.ctr(aes.AesEncryptCtx(aes.Aes128), ctx, out[serlen .. serlen + in.len], in[0..], iv, builtin.Endian.Big);
std.log.info("encrypted payload: {x} len={}", .{ out, out.len });
// Compute the MAC
var d: [hmac.sha2.HmacSha256.mac_length]u8 = undefined;
var hmac256 = hmac.sha2.HmacSha256.init(km);
hmac.sha2.HmacSha256.update(&hmac256, out[serlen .. serlen + in.len]);
//crypto.auth.hmac.Hmac.update(hmac, s2);
hmac.sha2.HmacSha256.final(&hmac256, out[serlen + in.len ..]);
std.log.info("d={x}", .{out[serlen + in.len ..]});
std.log.info("final={x}", .{out[0..]});
}
|
src/main.zig
|
// SPDX-License-Identifier: MIT
// This file is part of the `termcon` project under the MIT license.
//! Ziro is a super-simple terminal text editor written in Zig.
//! Ziro is inspired by [kilo](https://github.com/antirez/kilo),
//! and is intended to provide an example of using the `termcon`
//! library.
const std = @import("std");
const termcon = @import("termcon");
const Rune = termcon.view.Rune;
const Position = termcon.view.Position;
const Cell = termcon.view.Cell;
const Style = termcon.view.Style;
const Color = termcon.view.Color;
const ColorBit8 = termcon.view.ColorBit8;
const TextDecorations = termcon.view.TextDecorations;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const options = termcon.Options{
.raw_mode = true,
.alternate_screen = true,
.use_handler = true,
};
var tcon = try termcon.TermCon.init(&gpa.allocator, options);
defer _ = tcon.deinit();
// var cpos = try tcon.screen.cursor.getPosition();
// std.debug.warn("cpos: x:{} y:{}", .{cpos.col, cpos.row});
try tcon.screen.setCell(
Position{ .row = 0, .col = 0 },
Cell{
.rune = 'X',
.style = Style{
.fg_color = Color{ .Bit8 = ColorBit8{ .code = 148 } },
.bg_color = Color{ .Bit8 = ColorBit8{ .code = 197 } },
.text_decorations = TextDecorations{
.italic = false,
.bold = true,
.underline = false,
},
},
},
);
try tcon.screen.setCell(
Position{ .row = 0, .col = 1 },
Cell{
.rune = 'X',
.style = tcon.screen.getDefaultStyle(),
},
);
try tcon.screen.fillRunes(Position{ .row = 1, .col = 0 }, 'A', 8);
try tcon.screen.fillStyles(Position{ .row = 1, .col = 0 }, Style{
.fg_color = Color{ .Bit8 = ColorBit8{ .code = 183 } },
.bg_color = Color{ .Bit8 = ColorBit8{ .code = 238 } },
.text_decorations = TextDecorations{
.italic = true,
.underline = true,
.bold = false,
},
}, 4);
try tcon.screen.draw();
}
|
examples/ziro.zig
|
const std = @import("std");
const builtin = @import("builtin");
extern fn git_mbedtls__set_cert_location(path: ?[*:0]const u8, file: ?[*:0]const u8) c_int;
extern fn git_mbedtls__set_cert_buf(buf: [*]const u8, len: usize) c_int;
/// based off of golang's system cert finding code: https://golang.org/src/crypto/x509/
pub fn loadSystemCerts(allocator: *std.mem.Allocator) !void {
switch (builtin.target.os.tag) {
.windows => {
//const c = @cImport({
// @cInclude("wincrypt.h");
//});
//const store = c.CertOpenSystemStoreA(null, "ROOT");
//if (store == null) {
// std.log.err("failed to open system cert store", .{});
// return error.Explained;
//}
//defer _ = c.CertCloseStore(store, 0);
//var cert: ?*c.PCCERT_CONTEXT = null;
//while (true) {
// cert = c.CertEnumCertificatesInStore(store, cert);
// if (cert_context == null) {
// // TODO: handle errors and end of certs
// }
// // TODO: check for X509_ASN_ENCODING
// mbedtls_x509_crt_parse(ca_chain, cert.pbCertEncoded, cert.cbCertEncoded);
//}
//mbedtls_ssl_conf_ca_chain();
},
.ios => @compileError("TODO: ios certs"),
.macos => {},
.linux,
.aix,
.dragonfly,
.netbsd,
.freebsd,
.openbsd,
.plan9,
.solaris,
=> try loadUnixCerts(allocator),
else => std.log.warn("don't know how to load system certs for this os", .{}),
}
}
fn loadUnixCerts(allocator: *std.mem.Allocator) !void {
// TODO: env var overload
const has_env_var = try std.process.hasEnvVar(allocator, "SSL_CERT_FILE");
const files: []const [:0]const u8 = if (has_env_var) blk: {
const file_path = try std.process.getEnvVarOwned(allocator, "SSL_CERT_FILE");
defer allocator.free(file_path);
break :blk &.{try allocator.dupeZ(u8, file_path)};
} else switch (builtin.target.os.tag) {
.linux => &.{
// Debian/Ubuntu/Gentoo etc.
"/etc/ssl/certs/ca-certificates.crt",
// Fedora/RHEL 6
"/etc/pki/tls/certs/ca-bundle.crt",
// OpenSUSE
"/etc/ssl/ca-bundle.pem",
// OpenELEC
"/etc/pki/tls/cacert.pem",
// CentOS/RHEL 7
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
// Alpine Linux
"/etc/ssl/cert.pem",
},
.aix => &.{"/var/ssl/certs/ca-bundle.crt"},
.dragonfly => &.{"/usr/local/share/certs/ca-root-nss.crt"},
.netbsd => &.{"/etc/openssl/certs/ca-certificates.crt"},
.freebsd => &.{"/usr/local/etc/ssl/cert.pem"},
.openbsd => &.{"/etc/ssl/cert.pem"},
.plan9 => &.{"/sys/lib/tls/ca.pem"},
.solaris => &.{
// Solaris 11.2+
"/etc/certs/ca-certificates.crt",
// Joyent SmartOS
"/etc/ssl/certs/ca-certificates.crt",
// OmniOS
"/etc/ssl/cacert.pem",
},
else => @compileError("Don't know how to load system certs for this unix os"),
};
defer if (has_env_var) allocator.free(files[0]);
for (files) |path| {
const rc = git_mbedtls__set_cert_location(path, null);
if (rc == 0) {
return;
}
}
}
|
src/certs.zig
|
const std = @import("../std.zig");
/// This allocator is used in front of another allocator and counts the numbers of allocs and frees.
/// The test runner asserts every alloc has a corresponding free at the end of each test.
///
/// The detection algorithm is incredibly primitive and only accounts for number of calls.
/// This should be replaced by the general purpose debug allocator.
pub const LeakCountAllocator = struct {
count: usize,
allocator: std.mem.Allocator,
internal_allocator: *std.mem.Allocator,
pub fn init(allocator: *std.mem.Allocator) LeakCountAllocator {
return .{
.count = 0,
.allocator = .{
.reallocFn = realloc,
.shrinkFn = shrink,
},
.internal_allocator = allocator,
};
}
fn realloc(allocator: *std.mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
const self = @fieldParentPtr(LeakCountAllocator, "allocator", allocator);
var data = try self.internal_allocator.reallocFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
if (old_mem.len == 0) {
self.count += 1;
}
return data;
}
fn shrink(allocator: *std.mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
const self = @fieldParentPtr(LeakCountAllocator, "allocator", allocator);
if (new_size == 0) {
if (self.count == 0) {
std.debug.panic("error - too many calls to free, most likely double free", .{});
}
self.count -= 1;
}
return self.internal_allocator.shrinkFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
}
pub fn validate(self: LeakCountAllocator) !void {
if (self.count > 0) {
std.debug.warn("error - detected leaked allocations without matching free: {}\n", .{self.count});
return error.Leak;
}
}
};
|
lib/std/testing/leak_count_allocator.zig
|
const std = @import("std");
test "example" {
const data = @embedFile("4_example.txt");
const result = try run(data);
try std.testing.expectEqual(@as(u32, 4512), result);
}
pub fn main() !void {
const data = @embedFile("4.txt");
const result = try run(data);
std.debug.print("{}\n", .{result});
}
const Bingo = struct {
numbers: [25]u8 = undefined,
rowMarked: u25 = 0, // row-major bitset
colMarked: u25 = 0, // col-major bitset, makes hasWon easier
fn mark(self: *Bingo, number: u8) bool {
for (self.numbers) |n, i| {
if (n == number) {
self.rowMarked |= @as(u25, 1) << @intCast(u5, i);
self.colMarked |= @as(u25, 1) << @intCast(u5, 5 * (i % 5) + (i / 5)); // Column transpose
return true;
}
} else return false;
}
inline fn isRowMarked(self: Bingo, n: usize) bool {
const mask = @as(u25, 1) << @intCast(u5, n);
return self.rowMarked & mask != 0;
}
fn hasWon(self: Bingo) bool {
var mask = @as(u25, 0b11111);
var i: usize = 0;
while (i < 5) : (i += 1) {
if (self.rowMarked & mask == mask) return true;
if (self.colMarked & mask == mask) return true;
mask <<= 5;
} else return false;
}
fn countUnmarked(self: Bingo) u16 {
var total: u16 = 0;
for (self.numbers) |n, i| {
if (!self.isRowMarked(i)) total += n;
}
return total;
}
fn debug(self: Bingo) void {
std.debug.print("== {} {}\n", .{ self.hasWon(), self.countUnmarked() });
for (self.numbers) |n, i| {
if (i % 5 == 0) std.debug.print("\n", .{});
if (self.isRowMarked(i)) {
std.debug.print("\t\x1B[4m{}\x1B[0m", .{n}); // ANSI underline
} else std.debug.print("\t{}", .{n});
}
std.debug.print("==\n", .{});
}
};
fn run(input: []const u8) !u32 {
var numbers: [100]u8 = undefined;
var count: usize = 0;
const newline = std.mem.indexOfScalar(u8, input, '\n') orelse return error.NumbersReadError;
var ns = std.mem.split(u8, input[0..newline], ",");
while (ns.next()) |n| {
numbers[count] = try std.fmt.parseInt(u8, n, 10);
count += 1;
}
var bingos: [100]Bingo = .{Bingo{}} ** 100;
var bingo_count: usize = 0;
var tokens = std.mem.tokenize(u8, input[newline..], "\n ");
var number_count: usize = 0;
while (tokens.next()) |n| {
bingos[bingo_count].numbers[number_count] = try std.fmt.parseInt(u8, n, 10);
number_count += 1;
if (number_count == 25) {
bingo_count += 1;
number_count = 0;
}
} else if (number_count != 0) return error.IncompleteBoardError;
for (numbers[0..count]) |n| {
for (bingos[0..bingo_count]) |*b| {
if (b.mark(n) and b.hasWon()) return b.countUnmarked() * n;
}
} else return error.NoWinnerError;
}
|
shritesh+zig/4a.zig
|
// These are the addresses where some GPIO control registers are mapped to. They
// are marked as `volatile` to let the compiler know that accessing these
// addresses has side effects (and therefore these accesses will not be
// reordered or optimized away -- a property I'll explicitly make use of below).
const GPFSEL1 = @intToPtr(*volatile u32, 0x3F20_0004);
const GPSET0 = @intToPtr(*volatile u32, 0x3F20_001C);
const GPCLR0 = @intToPtr(*volatile u32, 0x3F20_0028);
// This is the real entry point for our program, and the only part of it in
// assembly. That's just one instruction! It simply jumps (or branches, using
// the `b` instruction) to our main function, `simplestMain`, written in Zig
// below.
//
// One important thing here is that I place this code in the `.text.boot`
// section of the resulting object. The linker script, `simplest.ld`, makes sure
// this section is placed right at the beginning of the resulting binary. That's
// what I want, because the Raspberry Pi 3 will start running from the beginning
// of the binary.
//
// Maybe important: the linker will look (by default) for the `_start` symbol as
// the program entry point. As far as I understand, though, this isn't relevant
// for this program, because the Pi 3 will start running from the first byte of
// the image. I am really defining the entry point by using the `.text.boot`,
// and `_start` is effectivelly ignored. However, the linker will complain if it
// can find `_start`, so I define it here to make our tools happy. There's
// probably a more elegant way to do this.
comptime {
asm (
\\.section .text.boot
\\.global _start
\\_start:
\\b simplestMain
);
}
// This is the "Zig entry point" of our program. The "real entry point" is
// written above in assembly; but it doesn't to anything interesting, it just
// jumps to here.
export fn simplestMain() noreturn {
// Configures the GPIO pin 16 as a digital output.
GPFSEL1.* = 0x0004_0000;
var ledON = true;
while (true) {
if (ledON) {
// Set GPIO pin 16 to high.
GPSET0.* = 0x0001_0000;
} else {
// Set GPIO pin 16 to low.
GPCLR0.* = 0x0001_0000;
}
// I am sure there are prettier ways to make the program sleep for a
// while. Anyway, looping idly for a while is easy to understand and
// works well-enough, especially considering I am targeting a specific
// hardware.
var i: u32 = 2_500_000;
while (i > 0) {
// This assignment is effectively a no-op, as I already configured
// the GPFSEL1 register above. However, it has a reason for being
// here: since `GPFSEL1` is marked as `volatile`, the compiler will
// assume this assignment has side effects. Without this, this whole
// loop would be removed by the compiler optimizer.
GPFSEL1.* = 0x0004_0000;
i -= 1;
}
ledON = !ledON;
}
}
|
src/main.zig
|
const std = @import("std");
const utils = @import("utils.zig");
const vector = @import("vector.zig");
const Vec4 = vector.Vec4;
const initPoint = vector.initPoint;
const initVector = vector.initVector;
const Mat4 = @import("matrix.zig").Mat4;
const Color = @import("color.zig").Color;
const Shape = @import("shape.zig").Shape;
const Stripe = struct {
const Self = @This();
a: Color,
b: Color,
pub fn patternAt(self: Self, point: Vec4) Color {
const c = @floor(point.x);
return if (@mod(c, 2) == 0) self.a else self.b;
}
};
const Gradient = struct {
const Self = @This();
a: Color,
b: Color,
pub fn patternAt(self: Self, point: Vec4) Color {
const distance = self.b.sub(self.a);
const fraction = point.x - @floor(point.x);
return self.a.add(distance.scale(fraction));
}
};
const Ring = struct {
const Self = @This();
a: Color,
b: Color,
pub fn patternAt(self: Self, point: Vec4) Color {
const c = @floor(std.math.sqrt(point.x * point.x + point.z * point.z));
return if (@mod(c, 2) == 0) self.a else self.b;
}
};
const Checkers = struct {
const Self = @This();
a: Color,
b: Color,
pub fn patternAt(self: Self, point: Vec4) Color {
const c = @floor(point.x) + @floor(point.y) + @floor(point.z);
return if (@mod(c, 2) == 0) self.a else self.b;
}
};
pub const Pattern = struct {
const Self = @This();
pattern: union(enum) {
point: void,
stripe: Stripe,
gradient: Gradient,
ring: Ring,
checkers: Checkers,
} = .{ .point = {} },
transform: Mat4 = Mat4.identity(),
pub fn patternAt(self: Self, object: Shape, world_point: Vec4) Color {
const object_space = object.transform.inverse();
const pattern_space = self.transform.inverse();
const object_point = object_space.multVec(world_point);
const pattern_point = pattern_space.multVec(object_point);
return switch (self.pattern) {
.point => Color.init(pattern_point.x, pattern_point.y, pattern_point.z),
.stripe => |p| p.patternAt(pattern_point),
.gradient => |p| p.patternAt(pattern_point),
.ring => |p| p.patternAt(pattern_point),
.checkers => |p| p.patternAt(pattern_point),
};
}
};
test "The default pattern transformation" {
const p = Pattern{};
try std.testing.expect(p.transform.eql(Mat4.identity()));
}
test "Changing a shape's transformation" {
const p = Pattern{ .transform = Mat4.identity().translate(1, 2, 3) };
try std.testing.expect(p.transform.eql(Mat4.identity().translate(1, 2, 3)));
}
test "A pattern with an object and pattern transformation" {
const p = Pattern{ .transform = Mat4.identity().translate(0.5, 1, 1.5) };
const s = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity().scale(2, 2, 2),
};
try utils.expectColorApproxEq(Color.init(0.75, 0.5, 0.25), p.patternAt(s, initPoint(2.5, 3, 3.5)));
}
test "Stripe pattern is constant in y" {
const p = Stripe{ .a = Color.White, .b = Color.Black };
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 1, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 2, 0)));
}
test "Stripe pattern is constant in z" {
const p = Stripe{ .a = Color.White, .b = Color.Black };
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 0, 1)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 0, 2)));
}
test "Stripe pattern alternates in x" {
const p = Stripe{ .a = Color.White, .b = Color.Black };
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(0.9, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(initPoint(1, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(initPoint(-0.1, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(initPoint(-1, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(initPoint(-1.1, 0, 0)));
}
test "Stripes with both an object and a pattern transformation" {
const p = Pattern{
.pattern = .{ .stripe = .{ .a = Color.White, .b = Color.Black } },
.transform = Mat4.identity().translate(0.5, 0, 0),
};
const s = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity().scale(2, 2, 2),
};
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(2.5, 0, 0)));
}
test "A gradient lienarly interpolates between colors" {
const p = Pattern{ .pattern = .{ .gradient = .{ .a = Color.White, .b = Color.Black } } };
const s = Shape{};
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.init(0.75, 0.75, 0.75), p.patternAt(s, initPoint(0.25, 0, 0)));
try utils.expectColorApproxEq(Color.init(0.5, 0.5, 0.5), p.patternAt(s, initPoint(0.5, 0, 0)));
try utils.expectColorApproxEq(Color.init(0.25, 0.25, 0.25), p.patternAt(s, initPoint(0.75, 0, 0)));
}
test "A ring should extend in both x and z" {
const p = Pattern{ .pattern = .{ .ring = .{ .a = Color.White, .b = Color.Black } } };
const s = Shape{};
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(1, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(0, 0, 1)));
// just slightly more than sqrt(2)/2
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(0.708, 0, 0.708)));
}
test "A checkers pattern should extend in x, y and z" {
const p = Pattern{ .pattern = .{ .checkers = .{ .a = Color.White, .b = Color.Black } } };
const s = Shape{};
// x
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0.99, 0, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(1.01, 0, 0)));
// y
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0.99, 0)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(0, 1.01, 0)));
// z
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0)));
try utils.expectColorApproxEq(Color.White, p.patternAt(s, initPoint(0, 0, 0.99)));
try utils.expectColorApproxEq(Color.Black, p.patternAt(s, initPoint(0, 0, 1.01)));
}
|
pattern.zig
|
const std = @import("std");
const builtin = @import("builtin");
const log = std.log.scoped(.@"brucelib.platform.win32");
const common = @import("common.zig");
const InitFn = common.InitFn;
const DeinitFn = common.DeinitFn;
const FrameFn = common.FrameFn;
const AudioPlaybackFn = common.AudioPlaybackFn;
const FrameInput = common.FrameInput;
const AudioPlaybackStream = common.AudioPlaybackStream;
const KeyEvent = common.KeyEvent;
const MouseButton = common.MouseButton;
const MouseButtonEvent = common.MouseButtonEvent;
const Key = common.Key;
const WasapiInterface = @import("win32/WasapiInterface.zig");
const AudioPlaybackInterface = WasapiInterface;
const zwin32 = @import("zwin32");
const BYTE = zwin32.base.BYTE;
const UINT = zwin32.base.UINT;
const DWORD = zwin32.base.DWORD;
const BOOL = zwin32.base.BOOL;
const TRUE = zwin32.base.TRUE;
const FALSE = zwin32.base.FALSE;
const LPCWSTR = zwin32.base.LPCWSTR;
const WPARAM = zwin32.base.WPARAM;
const LPARAM = zwin32.base.LPARAM;
const LRESULT = zwin32.base.LRESULT;
const HRESULT = zwin32.base.HRESULT;
const HINSTANCE = zwin32.base.HINSTANCE;
const HWND = zwin32.base.HWND;
const RECT = zwin32.base.RECT;
const kernel32 = zwin32.base.kernel32;
const user32 = zwin32.base.user32;
const dxgi = zwin32.dxgi;
const d3d = zwin32.d3d;
const d3d11 = zwin32.d3d11;
const d3dcompiler = zwin32.d3dcompiler;
const hrErrorOnFail = zwin32.hrErrorOnFail;
const L = std.unicode.utf8ToUtf16LeStringLiteral;
pub const Error = error{
FailedToGetModuleHandle,
};
const GraphicsAPI = enum {
d3d11,
};
pub var target_framerate: u16 = undefined;
var target_frame_dt: u64 = undefined;
var window_width: u16 = undefined;
var window_height: u16 = undefined;
var mouse_x: i32 = undefined;
var mouse_y: i32 = undefined;
var key_events: std.ArrayList(KeyEvent) = undefined;
var mouse_button_events: std.ArrayList(MouseButtonEvent) = undefined;
pub var audio_playback = struct {
user_cb: ?fn (AudioPlaybackStream) anyerror!u32 = null,
interface: AudioPlaybackInterface = undefined,
thread: std.Thread = undefined,
}{};
var timer: std.time.Timer = undefined;
var window_closed = false;
var quit = false;
pub fn getD3D11Device() *d3d11.IDevice {
return d3d11_device.?;
}
pub fn getD3D11DeviceContext() *d3d11.IDeviceContext {
return d3d11_device_context.?;
}
pub fn getD3D11RenderTargetView() *d3d11.IRenderTargetView {
return d3d11_render_target_view.?;
}
pub fn getSampleRate() u32 {
return audio_playback.interface.sample_rate;
}
pub fn timestamp() u64 {
return timer.read();
}
pub fn run(args: struct {
graphics_api: GraphicsAPI = .d3d11,
requested_framerate: u16 = 0,
title: []const u8 = "",
window_size: struct {
width: u16,
height: u16,
} = .{
.width = 854,
.height = 480,
},
init_fn: InitFn,
deinit_fn: DeinitFn,
frame_fn: FrameFn,
audio_playback: ?struct {
request_sample_rate: u32 = 48000,
callback: AudioPlaybackFn = null,
},
}) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var allocator = gpa.allocator();
// TODO(hazeycode): get monitor refresh and shoot for that, downgrade if we miss alot
target_framerate = if (args.requested_framerate == 0) 60 else args.requested_framerate;
window_width = args.window_size.width;
window_height = args.window_size.height;
timer = try std.time.Timer.start();
const hinstance = @ptrCast(HINSTANCE, kernel32.GetModuleHandleW(null) orelse {
log.err("GetModuleHandleW failed with error: {}", .{kernel32.GetLastError()});
return Error.FailedToGetModuleHandle;
});
var utf16_title = [_]u16{0} ** 64;
_ = try std.unicode.utf8ToUtf16Le(utf16_title[0..], args.title);
const utf16_title_ptr = @ptrCast([*:0]const u16, &utf16_title);
try registerClass(hinstance, utf16_title_ptr);
const hwnd = try createWindow(
hinstance,
utf16_title_ptr,
utf16_title_ptr,
);
try createDeviceAndSwapchain(hwnd);
try createRenderTargetView();
const audio_enabled = (args.audio_playback != null);
if (audio_enabled) {
audio_playback.user_cb = args.audio_playback.?.callback;
audio_playback.interface = try AudioPlaybackInterface.init(
args.audio_playback.?.request_sample_rate,
);
log.info(
\\Initilised audio playback (WASAPI):
\\ {} channels
\\ {} Hz
\\ {} bits per sample
,
.{
audio_playback.interface.num_channels,
audio_playback.interface.sample_rate,
audio_playback.interface.bits_per_sample,
},
);
}
defer {
if (audio_enabled) {
audio_playback.interface.deinit();
}
}
try args.init_fn(allocator);
defer args.deinit_fn(allocator);
if (audio_enabled) {
audio_playback.thread = try std.Thread.spawn(.{}, audioThread, .{});
audio_playback.thread.detach();
}
var frame_timer = try std.time.Timer.start();
var prev_cpu_frame_elapsed: u64 = 0;
while (quit == false) main_loop: {
const prev_frame_elapsed = frame_timer.lap();
const start_cpu_time = timestamp();
var frame_mem_arena = std.heap.ArenaAllocator.init(allocator);
defer frame_mem_arena.deinit();
var frame_arena_allocator = frame_mem_arena.allocator();
key_events = std.ArrayList(KeyEvent).init(frame_arena_allocator);
mouse_button_events = std.ArrayList(MouseButtonEvent).init(frame_arena_allocator);
var msg: user32.MSG = undefined;
while (try user32.peekMessageW(&msg, null, 0, 0, user32.PM_REMOVE)) {
_ = user32.translateMessage(&msg);
_ = user32.dispatchMessageW(&msg);
if (msg.message == user32.WM_QUIT) {
quit = true;
break :main_loop;
}
}
target_frame_dt = @floatToInt(u64, (1 / @intToFloat(f64, target_framerate) * 1e9));
quit = !(try args.frame_fn(.{
.frame_arena_allocator = frame_arena_allocator,
.quit_requested = window_closed,
.target_frame_dt = target_frame_dt,
.prev_frame_elapsed = prev_frame_elapsed,
.user_input = .{
.key_events = key_events.items,
.mouse_button_events = mouse_button_events.items,
.mouse_position = .{
.x = mouse_x,
.y = mouse_y,
},
},
.window_size = .{
.width = window_width,
.height = window_height,
},
.debug_stats = .{
.prev_cpu_frame_elapsed = prev_cpu_frame_elapsed,
},
}));
prev_cpu_frame_elapsed = timestamp() - start_cpu_time;
try hrErrorOnFail(dxgi_swap_chain.?.Present(1, 0));
}
}
fn audioThread() !void {
{ // write some silence before starting the stream
var buffer_frames: UINT = 0;
hrErrorOnFail(audio_playback.interface.client.GetBufferSize(&buffer_frames)) catch {
std.debug.panic("audioThread: failed to prefill silence", .{});
};
log.debug("audio stream buffer size = {} frames", .{buffer_frames});
var ptr: [*]f32 = undefined;
hrErrorOnFail(audio_playback.interface.render_client.GetBuffer(
buffer_frames,
@ptrCast(*?[*]BYTE, &ptr),
)) catch {
std.debug.panic("audioThread: failed to prefill silence", .{});
};
hrErrorOnFail(audio_playback.interface.render_client.ReleaseBuffer(
@intCast(UINT, buffer_frames),
zwin32.wasapi.AUDCLNT_BUFFERFLAGS_SILENT,
)) catch {
std.debug.panic("audioThread: failed to prefill silence", .{});
};
}
hrErrorOnFail(audio_playback.interface.client.Start()) catch {};
defer _ = audio_playback.interface.client.Stop();
while (quit == false) {
zwin32.base.WaitForSingleObject(audio_playback.interface.buffer_ready_event, zwin32.base.INFINITE) catch {
continue;
};
var buffer_frames: UINT = 0;
_ = audio_playback.interface.client.GetBufferSize(&buffer_frames);
var padding: UINT = 0;
_ = audio_playback.interface.client.GetCurrentPadding(&padding);
const num_frames = buffer_frames - padding;
const num_channels = audio_playback.interface.num_channels;
const num_samples = num_frames * num_channels;
var byte_buf: [*]BYTE = undefined;
hrErrorOnFail(audio_playback.interface.render_client.GetBuffer(num_frames, @ptrCast(*?[*]BYTE, &byte_buf))) catch |err| {
log.warn("Audio GetBuffer failed with error: {}", .{err});
continue;
};
const sample_buf = @ptrCast([*]f32, @alignCast(@alignOf(f32), byte_buf))[0..num_samples];
const frames_written = try audio_playback.user_cb.?(.{
.sample_rate = audio_playback.interface.sample_rate,
.channels = num_channels,
.sample_buf = sample_buf,
.max_frames = num_frames,
});
if (frames_written < num_frames) {
log.warn("Audio playback underflow", .{});
}
_ = audio_playback.interface.render_client.ReleaseBuffer(
@intCast(UINT, num_frames),
0,
);
}
}
fn wndProc(hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) callconv(.C) LRESULT {
switch (msg) {
user32.WM_CLOSE => {
window_closed = true;
return 0;
},
user32.WM_DESTROY => user32.postQuitMessage(0),
user32.WM_MOUSEMOVE => {
// TODO(hazeycode): Scale mouse using dpi
const scale: f32 = 1;
mouse_x = @floatToInt(i32, @intToFloat(f32, zwin32.base.GET_X_LPARAM(lparam)) * scale);
mouse_y = @floatToInt(i32, @intToFloat(f32, zwin32.base.GET_Y_LPARAM(lparam)) * scale);
// TODO(hazeycode): Also track mouse position even when it's outside the window
},
user32.WM_KEYDOWN, user32.WM_SYSKEYDOWN, user32.WM_KEYUP, user32.WM_SYSKEYUP => {
const key = translateKey(wparam);
key_events.append(.{
.action = switch (msg) {
user32.WM_KEYDOWN, user32.WM_SYSKEYDOWN => .press,
user32.WM_KEYUP, user32.WM_SYSKEYUP => .release,
else => unreachable,
// TODO(hazeycode): key repeat events
},
.key = key,
}) catch |err| {
log.warn("Failed to translate key {} with error: {}", .{ wparam, err });
};
},
else => {},
}
return user32.defWindowProcW(hwnd, msg, wparam, lparam);
}
fn registerClass(hinstance: HINSTANCE, name: LPCWSTR) !void {
var wndclass = user32.WNDCLASSEXW{
.cbSize = @sizeOf(user32.WNDCLASSEXW),
.style = 0,
.lpfnWndProc = wndProc,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = hinstance,
.hIcon = null,
.hCursor = null,
.hbrBackground = null,
.lpszMenuName = null,
.lpszClassName = name,
.hIconSm = null,
};
_ = try user32.registerClassExW(&wndclass);
}
fn createWindow(
hinstance: HINSTANCE,
class_name: LPCWSTR,
window_name: LPCWSTR,
) !HWND {
const offset_x = 60;
const offset_y = 60;
var rect = RECT{
.left = offset_x,
.top = offset_y,
.right = offset_x + window_width,
.bottom = offset_y + window_height,
};
const style: DWORD = user32.WS_OVERLAPPEDWINDOW;
try user32.adjustWindowRectEx(&rect, style, false, 0);
const hwnd = try user32.createWindowExW(
0,
class_name,
window_name,
style,
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
null,
null,
hinstance,
null,
);
_ = user32.showWindow(hwnd, user32.SW_SHOWNORMAL);
try user32.updateWindow(hwnd);
return hwnd;
}
var dxgi_swap_chain: ?*dxgi.ISwapChain = null;
var d3d11_device: ?*d3d11.IDevice = null;
var d3d11_device_context: ?*d3d11.IDeviceContext = null;
var d3d11_render_target_view: ?*d3d11.IRenderTargetView = null;
fn createDeviceAndSwapchain(hwnd: HWND) zwin32.HResultError!void {
const STANDARD_MULTISAMPLE_QUALITY_LEVELS = enum(UINT) {
STANDARD_MULTISAMPLE_PATTERN = 0xffffffff,
CENTER_MULTISAMPLE_PATTERN = 0xfffffffe,
};
// TODO(chris): check that hardware supports the multisampling values we want
// and downgrade if nessesary
var swapchain_desc: dxgi.SWAP_CHAIN_DESC = .{
.BufferDesc = .{
.Width = 0,
.Height = 0,
.RefreshRate = .{
.Numerator = 0,
.Denominator = 1,
},
.Format = dxgi.FORMAT.B8G8R8A8_UNORM,
.ScanlineOrdering = dxgi.MODE_SCANLINE_ORDER.UNSPECIFIED,
.Scaling = dxgi.MODE_SCALING.UNSPECIFIED,
},
.SampleDesc = .{
.Count = 4,
.Quality = @enumToInt(STANDARD_MULTISAMPLE_QUALITY_LEVELS.STANDARD_MULTISAMPLE_PATTERN),
},
.BufferUsage = dxgi.USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = 1,
.OutputWindow = hwnd,
.Windowed = TRUE,
.SwapEffect = dxgi.SWAP_EFFECT.DISCARD,
.Flags = 0,
};
var flags: UINT = d3d11.CREATE_DEVICE_SINGLETHREADED;
if (builtin.mode == .Debug) {
flags |= d3d11.CREATE_DEVICE_DEBUG;
}
var feature_level: d3d.FEATURE_LEVEL = .FL_11_1;
try hrErrorOnFail(d3d11.D3D11CreateDeviceAndSwapChain(
null,
d3d.DRIVER_TYPE.HARDWARE,
null,
flags,
null,
0,
d3d11.SDK_VERSION,
&swapchain_desc,
&dxgi_swap_chain,
&d3d11_device,
&feature_level,
&d3d11_device_context,
));
}
fn createRenderTargetView() zwin32.HResultError!void {
var framebuffer: *d3d11.IResource = undefined;
try hrErrorOnFail(dxgi_swap_chain.?.GetBuffer(
0,
&d3d11.IID_IResource,
@ptrCast(*?*anyopaque, &framebuffer),
));
try hrErrorOnFail(d3d11_device.?.CreateRenderTargetView(
framebuffer,
null,
&d3d11_render_target_view,
));
_ = framebuffer.Release();
}
fn translateKey(wparam: WPARAM) Key {
return switch (wparam) {
zwin32.base.VK_ESCAPE => .escape,
zwin32.base.VK_TAB => .tab,
zwin32.base.VK_LSHIFT => .shift_left,
zwin32.base.VK_RSHIFT => .shift_right,
zwin32.base.VK_LCONTROL => .ctrl_left,
zwin32.base.VK_RCONTROL => .ctrl_right,
zwin32.base.VK_LMENU => .alt_left,
zwin32.base.VK_RMENU => .alt_right,
zwin32.base.VK_LWIN => .super_left,
zwin32.base.VK_RWIN => .super_right,
zwin32.base.VK_APPS => .menu,
zwin32.base.VK_NUMLOCK => .numlock,
zwin32.base.VK_CAPITAL => .capslock,
zwin32.base.VK_SNAPSHOT => .printscreen,
zwin32.base.VK_SCROLL => .scrolllock,
zwin32.base.VK_PAUSE => .pause,
zwin32.base.VK_DELETE => .delete,
zwin32.base.VK_BACK => .backspace,
zwin32.base.VK_RETURN => .enter,
zwin32.base.VK_HOME => .home,
zwin32.base.VK_END => .end,
zwin32.base.VK_PRIOR => .pageup,
zwin32.base.VK_NEXT => .pagedown,
zwin32.base.VK_INSERT => .insert,
zwin32.base.VK_LEFT => .left,
zwin32.base.VK_RIGHT => .right,
zwin32.base.VK_DOWN => .down,
zwin32.base.VK_UP => .up,
zwin32.base.VK_F1 => .f1,
zwin32.base.VK_F2 => .f2,
zwin32.base.VK_F3 => .f3,
zwin32.base.VK_F4 => .f4,
zwin32.base.VK_F5 => .f5,
zwin32.base.VK_F6 => .f6,
zwin32.base.VK_F7 => .f7,
zwin32.base.VK_F8 => .f8,
zwin32.base.VK_F9 => .f9,
zwin32.base.VK_F10 => .f10,
zwin32.base.VK_F11 => .f11,
zwin32.base.VK_F12 => .f12,
zwin32.base.VK_DIVIDE => .keypad_divide,
zwin32.base.VK_MULTIPLY => .keypad_multiply,
zwin32.base.VK_SUBTRACT => .keypad_subtract,
zwin32.base.VK_ADD => .keypad_add,
zwin32.base.VK_NUMPAD0 => .keypad_0,
zwin32.base.VK_NUMPAD1 => .keypad_1,
zwin32.base.VK_NUMPAD2 => .keypad_2,
zwin32.base.VK_NUMPAD3 => .keypad_3,
zwin32.base.VK_NUMPAD4 => .keypad_4,
zwin32.base.VK_NUMPAD5 => .keypad_5,
zwin32.base.VK_NUMPAD6 => .keypad_6,
zwin32.base.VK_NUMPAD7 => .keypad_7,
zwin32.base.VK_NUMPAD8 => .keypad_8,
zwin32.base.VK_NUMPAD9 => .keypad_9,
zwin32.base.VK_DECIMAL => .keypad_decimal,
'A' => .a,
'B' => .b,
'C' => .c,
'D' => .d,
'E' => .e,
'F' => .f,
'G' => .g,
'H' => .h,
'I' => .i,
'J' => .j,
'K' => .k,
'L' => .l,
'M' => .m,
'N' => .n,
'O' => .o,
'P' => .p,
'Q' => .q,
'R' => .r,
'S' => .s,
'T' => .t,
'U' => .u,
'V' => .v,
'W' => .w,
'X' => .x,
'Y' => .y,
'Z' => .z,
'1' => .one,
'2' => .two,
'3' => .three,
'4' => .four,
'5' => .five,
'6' => .six,
'7' => .seven,
'8' => .eight,
'9' => .nine,
'0' => .zero,
zwin32.base.VK_SPACE => .space,
zwin32.base.VK_OEM_MINUS => .minus,
zwin32.base.VK_OEM_PLUS => .equal,
zwin32.base.VK_OEM_4 => .bracket_left,
zwin32.base.VK_OEM_6 => .bracket_right,
zwin32.base.VK_OEM_5 => .backslash,
zwin32.base.VK_OEM_1 => .semicolon,
zwin32.base.VK_OEM_7 => .apostrophe,
zwin32.base.VK_OEM_3 => .grave_accent,
zwin32.base.VK_OEM_COMMA => .comma,
zwin32.base.VK_OEM_PERIOD => .period,
zwin32.base.VK_OEM_2 => .slash,
else => .unknown,
};
}
|
modules/platform/src/win32.zig
|
const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const AesBlock = std.crypto.core.aes.Block;
const State128L = struct {
blocks: [8]AesBlock,
fn init(key: [16]u8, nonce: [16]u8) State128L {
const c1 = AesBlock.fromBytes(&[16]u8{ 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd });
const c2 = AesBlock.fromBytes(&[16]u8{ 0x0, 0x1, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 });
const key_block = AesBlock.fromBytes(&key);
const nonce_block = AesBlock.fromBytes(&nonce);
const blocks = [8]AesBlock{
key_block.xorBlocks(nonce_block),
c1,
c2,
c1,
key_block.xorBlocks(nonce_block),
key_block.xorBlocks(c2),
key_block.xorBlocks(c1),
key_block.xorBlocks(c2),
};
var state = State128L{ .blocks = blocks };
var i: usize = 0;
while (i < 10) : (i += 1) {
state.update(nonce_block, key_block);
}
return state;
}
inline fn update(state: *State128L, d1: AesBlock, d2: AesBlock) void {
const blocks = &state.blocks;
const tmp = blocks[7];
comptime var i: usize = 7;
inline while (i > 0) : (i -= 1) {
blocks[i] = blocks[i - 1].encrypt(blocks[i]);
}
blocks[0] = tmp.encrypt(blocks[0]);
blocks[0] = blocks[0].xorBlocks(d1);
blocks[4] = blocks[4].xorBlocks(d2);
}
fn enc(state: *State128L, dst: *[32]u8, src: *const [32]u8) void {
const blocks = &state.blocks;
const msg0 = AesBlock.fromBytes(src[0..16]);
const msg1 = AesBlock.fromBytes(src[16..32]);
var tmp0 = msg0.xorBlocks(blocks[6]).xorBlocks(blocks[1]);
var tmp1 = msg1.xorBlocks(blocks[2]).xorBlocks(blocks[5]);
tmp0 = tmp0.xorBlocks(blocks[2].andBlocks(blocks[3]));
tmp1 = tmp1.xorBlocks(blocks[6].andBlocks(blocks[7]));
dst[0..16].* = tmp0.toBytes();
dst[16..32].* = tmp1.toBytes();
state.update(msg0, msg1);
}
fn dec(state: *State128L, dst: *[32]u8, src: *const [32]u8) void {
const blocks = &state.blocks;
var msg0 = AesBlock.fromBytes(src[0..16]).xorBlocks(blocks[6]).xorBlocks(blocks[1]);
var msg1 = AesBlock.fromBytes(src[16..32]).xorBlocks(blocks[2]).xorBlocks(blocks[5]);
msg0 = msg0.xorBlocks(blocks[2].andBlocks(blocks[3]));
msg1 = msg1.xorBlocks(blocks[6].andBlocks(blocks[7]));
dst[0..16].* = msg0.toBytes();
dst[16..32].* = msg1.toBytes();
state.update(msg0, msg1);
}
fn mac(state: *State128L, adlen: usize, mlen: usize) [16]u8 {
const blocks = &state.blocks;
var sizes: [16]u8 = undefined;
mem.writeIntLittle(u64, sizes[0..8], adlen * 8);
mem.writeIntLittle(u64, sizes[8..16], mlen * 8);
const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[2]);
var i: usize = 0;
while (i < 7) : (i += 1) {
state.update(tmp, tmp);
}
return blocks[0].xorBlocks(blocks[1]).xorBlocks(blocks[2]).xorBlocks(blocks[3]).xorBlocks(blocks[4]).
xorBlocks(blocks[5]).xorBlocks(blocks[6]).toBytes();
}
};
/// AEGIS is a very fast authenticated encryption system built on top of the core AES function.
///
/// The 128L variant of AEGIS has a 128 bit key, a 128 bit nonce, and processes 256 bit message blocks.
/// It was designed to fully exploit the parallelism and built-in AES support of recent Intel and ARM CPUs.
///
/// https://competitions.cr.yp.to/round3/aegisv11.pdf
pub const Aegis128L = struct {
pub const tag_length = 16;
pub const nonce_length = 16;
pub const key_length = 16;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
assert(c.len == m.len);
var state = State128L.init(key, npub);
var src: [32]u8 align(16) = undefined;
var dst: [32]u8 align(16) = undefined;
var i: usize = 0;
while (i + 32 <= ad.len) : (i += 32) {
state.enc(&dst, ad[i..][0..32]);
}
if (ad.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]);
state.enc(&dst, &src);
}
i = 0;
while (i + 32 <= m.len) : (i += 32) {
state.enc(c[i..][0..32], m[i..][0..32]);
}
if (m.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 32], m[i .. i + m.len % 32]);
state.enc(&dst, &src);
mem.copy(u8, c[i .. i + m.len % 32], dst[0 .. m.len % 32]);
}
tag.* = state.mac(ad.len, m.len);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) !void {
assert(c.len == m.len);
var state = State128L.init(key, npub);
var src: [32]u8 align(16) = undefined;
var dst: [32]u8 align(16) = undefined;
var i: usize = 0;
while (i + 32 <= ad.len) : (i += 32) {
state.enc(&dst, ad[i..][0..32]);
}
if (ad.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]);
state.enc(&dst, &src);
}
i = 0;
while (i + 32 <= m.len) : (i += 32) {
state.dec(m[i..][0..32], c[i..][0..32]);
}
if (m.len % 32 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 32], c[i .. i + m.len % 32]);
state.dec(&dst, &src);
mem.copy(u8, m[i .. i + m.len % 32], dst[0 .. m.len % 32]);
mem.set(u8, dst[0 .. m.len % 32], 0);
const blocks = &state.blocks;
blocks[0] = blocks[0].xorBlocks(AesBlock.fromBytes(dst[0..16]));
blocks[4] = blocks[4].xorBlocks(AesBlock.fromBytes(dst[16..32]));
}
const computed_tag = state.mac(ad.len, m.len);
var acc: u8 = 0;
for (computed_tag) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
if (acc != 0) {
mem.set(u8, m, 0xaa);
return error.AuthenticationFailed;
}
}
};
const State256 = struct {
blocks: [6]AesBlock,
fn init(key: [32]u8, nonce: [32]u8) State256 {
const c1 = AesBlock.fromBytes(&[16]u8{ 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd });
const c2 = AesBlock.fromBytes(&[16]u8{ 0x0, 0x1, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 });
const key_block1 = AesBlock.fromBytes(key[0..16]);
const key_block2 = AesBlock.fromBytes(key[16..32]);
const nonce_block1 = AesBlock.fromBytes(nonce[0..16]);
const nonce_block2 = AesBlock.fromBytes(nonce[16..32]);
const kxn1 = key_block1.xorBlocks(nonce_block1);
const kxn2 = key_block2.xorBlocks(nonce_block2);
const blocks = [6]AesBlock{
kxn1,
kxn2,
c1,
c2,
key_block1.xorBlocks(c2),
key_block2.xorBlocks(c1),
};
var state = State256{ .blocks = blocks };
var i: usize = 0;
while (i < 4) : (i += 1) {
state.update(key_block1);
state.update(key_block2);
state.update(kxn1);
state.update(kxn2);
}
return state;
}
inline fn update(state: *State256, d: AesBlock) void {
const blocks = &state.blocks;
const tmp = blocks[5].encrypt(blocks[0]);
comptime var i: usize = 5;
inline while (i > 0) : (i -= 1) {
blocks[i] = blocks[i - 1].encrypt(blocks[i]);
}
blocks[0] = tmp.xorBlocks(d);
}
fn enc(state: *State256, dst: *[16]u8, src: *const [16]u8) void {
const blocks = &state.blocks;
const msg = AesBlock.fromBytes(src);
var tmp = msg.xorBlocks(blocks[5]).xorBlocks(blocks[4]).xorBlocks(blocks[1]);
tmp = tmp.xorBlocks(blocks[2].andBlocks(blocks[3]));
dst.* = tmp.toBytes();
state.update(msg);
}
fn dec(state: *State256, dst: *[16]u8, src: *const [16]u8) void {
const blocks = &state.blocks;
var msg = AesBlock.fromBytes(src).xorBlocks(blocks[5]).xorBlocks(blocks[4]).xorBlocks(blocks[1]);
msg = msg.xorBlocks(blocks[2].andBlocks(blocks[3]));
dst.* = msg.toBytes();
state.update(msg);
}
fn mac(state: *State256, adlen: usize, mlen: usize) [16]u8 {
const blocks = &state.blocks;
var sizes: [16]u8 = undefined;
mem.writeIntLittle(u64, sizes[0..8], adlen * 8);
mem.writeIntLittle(u64, sizes[8..16], mlen * 8);
const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[3]);
var i: usize = 0;
while (i < 7) : (i += 1) {
state.update(tmp);
}
return blocks[0].xorBlocks(blocks[1]).xorBlocks(blocks[2]).xorBlocks(blocks[3]).xorBlocks(blocks[4]).
xorBlocks(blocks[5]).toBytes();
}
};
/// AEGIS is a very fast authenticated encryption system built on top of the core AES function.
///
/// The 256 bit variant of AEGIS has a 256 bit key, a 256 bit nonce, and processes 128 bit message blocks.
///
/// https://competitions.cr.yp.to/round3/aegisv11.pdf
pub const Aegis256 = struct {
pub const tag_length = 16;
pub const nonce_length = 32;
pub const key_length = 32;
/// c: ciphertext: output buffer should be of size m.len
/// tag: authentication tag: output MAC
/// m: message
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
assert(c.len == m.len);
var state = State256.init(key, npub);
var src: [16]u8 align(16) = undefined;
var dst: [16]u8 align(16) = undefined;
var i: usize = 0;
while (i + 16 <= ad.len) : (i += 16) {
state.enc(&dst, ad[i..][0..16]);
}
if (ad.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 16], ad[i .. i + ad.len % 16]);
state.enc(&dst, &src);
}
i = 0;
while (i + 16 <= m.len) : (i += 16) {
state.enc(c[i..][0..16], m[i..][0..16]);
}
if (m.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 16], m[i .. i + m.len % 16]);
state.enc(&dst, &src);
mem.copy(u8, c[i .. i + m.len % 16], dst[0 .. m.len % 16]);
}
tag.* = state.mac(ad.len, m.len);
}
/// m: message: output buffer should be of size c.len
/// c: ciphertext
/// tag: authentication tag
/// ad: Associated Data
/// npub: public nonce
/// k: private key
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) !void {
assert(c.len == m.len);
var state = State256.init(key, npub);
var src: [16]u8 align(16) = undefined;
var dst: [16]u8 align(16) = undefined;
var i: usize = 0;
while (i + 16 <= ad.len) : (i += 16) {
state.enc(&dst, ad[i..][0..16]);
}
if (ad.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. ad.len % 16], ad[i .. i + ad.len % 16]);
state.enc(&dst, &src);
}
i = 0;
while (i + 16 <= m.len) : (i += 16) {
state.dec(m[i..][0..16], c[i..][0..16]);
}
if (m.len % 16 != 0) {
mem.set(u8, src[0..], 0);
mem.copy(u8, src[0 .. m.len % 16], c[i .. i + m.len % 16]);
state.dec(&dst, &src);
mem.copy(u8, m[i .. i + m.len % 16], dst[0 .. m.len % 16]);
mem.set(u8, dst[0 .. m.len % 16], 0);
const blocks = &state.blocks;
blocks[0] = blocks[0].xorBlocks(AesBlock.fromBytes(&dst));
}
const computed_tag = state.mac(ad.len, m.len);
var acc: u8 = 0;
for (computed_tag) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
if (acc != 0) {
mem.set(u8, m, 0xaa);
return error.AuthenticationFailed;
}
}
};
const htest = @import("test.zig");
const testing = std.testing;
test "Aegis128L test vector 1" {
const key: [Aegis128L.key_length]u8 = [_]u8{ 0x10, 0x01 } ++ [_]u8{0x00} ** 14;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{ 0x10, 0x00, 0x02 } ++ [_]u8{0x00} ** 13;
const ad = [8]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
const m = [32]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("79d94593d8c2119d7e8fd9b8fc77845c5c077a05b2528b6ac54b563aed8efe84", &c);
htest.assertEqual("cc6f3372f6aa1bb82388d695c3962d9a", &tag);
c[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis128L test vector 2" {
const key: [Aegis128L.key_length]u8 = [_]u8{0x00} ** 16;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{0x00} ** 16;
const ad = [_]u8{};
const m = [_]u8{0x00} ** 16;
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("41de9000a7b5e40e2d68bb64d99ebb19", &c);
htest.assertEqual("f4d997cc9b94227ada4fe4165422b1c8", &tag);
}
test "Aegis128L test vector 3" {
const key: [Aegis128L.key_length]u8 = [_]u8{0x00} ** 16;
const nonce: [Aegis128L.nonce_length]u8 = [_]u8{0x00} ** 16;
const ad = [_]u8{};
const m = [_]u8{};
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis128L.tag_length]u8 = undefined;
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("83cc600dc4e3e7e62d4055826174f149", &tag);
}
test "Aegis256 test vector 1" {
const key: [Aegis256.key_length]u8 = [_]u8{ 0x10, 0x01 } ++ [_]u8{0x00} ** 30;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{ 0x10, 0x00, 0x02 } ++ [_]u8{0x00} ** 29;
const ad = [8]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
const m = [32]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("f373079ed84b2709faee373584585d60accd191db310ef5d8b11833df9dec711", &c);
htest.assertEqual("8d86f91ee606e9ff26a01b64ccbdd91d", &tag);
c[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis256 test vector 2" {
const key: [Aegis256.key_length]u8 = [_]u8{0x00} ** 32;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{0x00} ** 32;
const ad = [_]u8{};
const m = [_]u8{0x00} ** 16;
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("b98f03a947807713d75a4fff9fc277a6", &c);
htest.assertEqual("478f3b50dc478ef7d5cf2d0f7cc13180", &tag);
}
test "Aegis256 test vector 3" {
const key: [Aegis256.key_length]u8 = [_]u8{0x00} ** 32;
const nonce: [Aegis256.nonce_length]u8 = [_]u8{0x00} ** 32;
const ad = [_]u8{};
const m = [_]u8{};
var c: [m.len]u8 = undefined;
var m2: [m.len]u8 = undefined;
var tag: [Aegis256.tag_length]u8 = undefined;
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("f7a0878f68bd083e8065354071fc27c3", &tag);
}
|
lib/std/crypto/aegis.zig
|
const Allocator = std.mem.Allocator;
const File = std.fs.File;
const FormatInterface = @import("../format_interface.zig").FormatInterface;
const ImageFormat = image.ImageFormat;
const ImageReader = image.ImageReader;
const ImageInfo = image.ImageInfo;
const ImageSeekStream = image.ImageSeekStream;
const PixelFormat = @import("../pixel_format.zig").PixelFormat;
const color = @import("../color.zig");
const errors = @import("../errors.zig");
const fs = std.fs;
const image = @import("../image.zig");
const io = std.io;
const mem = std.mem;
const path = std.fs.path;
const std = @import("std");
usingnamespace @import("../utils.zig");
pub const TGAImageType = packed struct {
indexed: bool = false,
truecolor: bool = false,
pad0: bool = false,
run_length: bool = false,
pad1: u4 = 0,
};
pub const TGAColorMapSpec = packed struct {
first_entry_index: u16 = 0,
color_map_length: u16 = 0,
color_map_bit_depth: u8 = 0,
};
pub const TGAImageSpec = packed struct {
origin_x: u16 = 0,
origin_y: u16 = 0,
width: u16 = 0,
height: u16 = 0,
bit_per_pixel: u8 = 0,
descriptor: u8 = 0,
};
pub const TGAHeader = packed struct {
id_length: u8 = 0,
has_color_map: u8 = 0,
image_type: TGAImageType = .{},
// BEGIN: TGAColorMapSpec
first_entry_index: u16 = 0,
color_map_length: u16 = 0,
color_map_bit_depth: u8 = 0,
// END TGAColorMapSpec
// TODO: Use TGAColorMapSpec once all packed struct bugs are fixed
// color_map_spec: TGAColorMapSpec,
// BEGIN TGAImageSpec
origin_x: u16 = 0,
origin_y: u16 = 0,
width: u16 = 0,
height: u16 = 0,
bit_per_pixel: u8 = 0,
descriptor: u8 = 0,
// END TGAImageSpec
//TODO: Use TGAImageSpec once all packed struct bugs are fixed
//image_spec: TGAImageSpec,
};
pub const TGAAttributeType = packed enum(u8) {
NoAlpha = 0,
UndefinedAlphaIgnore = 1,
UndefinedAlphaRetained = 2,
UsefulAlphaChannel = 3,
PremultipledAlpha = 4,
};
pub const TGAExtension = packed struct {
extension_size: u16 = 0,
author_name: [41]u8 = undefined,
author_comment: [324]u8 = undefined,
timestamp: [12]u8 = undefined,
job_id: [41]u8 = undefined,
job_time: [6]u8 = undefined,
software_id: [41]u8 = undefined,
software_version: [3]u8 = undefined,
key_color: [4]u8 = undefined,
pixel_aspect: [4]u8 = undefined,
gamma_value: [4]u8 = undefined,
color_correction_offset: u32 = 0,
postage_stamp_offset: u32 = 0,
scanline_offset: u32 = 0,
attributes: TGAAttributeType = .NoAlpha,
};
pub const TGAFooter = packed struct {
extension_offset: u32,
dev_area_offset: u32,
signature: [16]u8,
dot: u8,
null_value: u8,
};
pub const TGASignature = "TRUEVISION-XFILE";
comptime {
std.debug.assert(@sizeOf(TGAExtension) == 495);
}
const TargaRLEDecoder = struct {
source_stream: ImageReader,
allocator: *Allocator,
bytes_per_pixel: usize,
state: State = .ReadHeader,
repeat_count: usize = 0,
repeat_data: []u8 = undefined,
data_stream: std.io.FixedBufferStream([]u8) = undefined,
const Self = @This();
pub const ReadError = std.fs.File.ReadError;
const State = enum {
ReadHeader,
Repeated,
Raw,
};
const PacketType = packed enum(u1) {
Raw = 0,
Repeated = 1,
};
const PacketHeader = packed struct {
pixel_count: u7,
packet_type: PacketType,
};
pub fn init(allocator: *Allocator, source_stream: ImageReader, bytes_per_pixels: usize) !Self {
var result = Self{
.allocator = allocator,
.source_stream = source_stream,
.bytes_per_pixel = bytes_per_pixels,
};
result.repeat_data = try allocator.alloc(u8, bytes_per_pixels);
result.data_stream = std.io.fixedBufferStream(result.repeat_data);
return result;
}
pub fn deinit(self: Self) void {
self.allocator.free(self.repeat_data);
}
pub fn read(self: *Self, dest: []u8) ReadError!usize {
var read_count: usize = 0;
if (self.state == .ReadHeader) {
const packet_header = readStructLittle(self.source_stream, PacketHeader) catch |err| {
return ReadError.InputOutput;
};
if (packet_header.packet_type == .Repeated) {
self.state = .Repeated;
self.repeat_count = @intCast(usize, packet_header.pixel_count) + 1;
_ = try self.source_stream.read(self.repeat_data);
self.data_stream.reset();
} else if (packet_header.packet_type == .Raw) {
self.state = .Raw;
self.repeat_count = (@intCast(usize, packet_header.pixel_count) + 1) * self.bytes_per_pixel;
}
}
switch (self.state) {
.Repeated => {
const read_bytes = try self.data_stream.read(dest);
const end_pos = try self.data_stream.getEndPos();
if (self.data_stream.pos >= end_pos) {
self.data_stream.reset();
self.repeat_count -= 1;
}
read_count = dest.len;
},
.Raw => {
const read_bytes = try self.source_stream.read(dest);
self.repeat_count -= read_bytes;
read_count = read_bytes;
},
else => {
return ReadError.BrokenPipe;
},
}
if (self.repeat_count == 0) {
self.state = .ReadHeader;
}
return read_count;
}
pub fn reader(self: *Self) Reader {
return .{ .context = @ptrCast(*std.io.StreamSource, self) };
}
};
pub const TargaStream = union(enum) {
image: ImageReader,
rle: TargaRLEDecoder,
pub const ReadError = std.fs.File.ReadError;
pub const Reader = std.io.Reader(*TargaStream, ReadError, read);
pub fn read(self: *TargaStream, dest: []u8) ReadError!usize {
switch (self.*) {
.image => |*x| return x.read(dest),
.rle => |*x| return x.read(dest),
}
}
pub fn reader(self: *TargaStream) Reader {
return .{ .context = self };
}
};
pub const TGA = struct {
header: TGAHeader = .{},
extension: ?TGAExtension = null,
const Self = @This();
pub fn formatInterface() FormatInterface {
return FormatInterface{
.format = @ptrCast(FormatInterface.FormatFn, format),
.formatDetect = @ptrCast(FormatInterface.FormatDetectFn, formatDetect),
.readForImage = @ptrCast(FormatInterface.ReadForImageFn, readForImage),
.writeForImage = @ptrCast(FormatInterface.WriteForImageFn, writeForImage),
};
}
pub fn format() ImageFormat {
return ImageFormat.Tga;
}
pub fn formatDetect(reader: ImageReader, seekStream: ImageSeekStream) !bool {
const endPos = try seekStream.getEndPos();
if (@sizeOf(TGAFooter) < endPos) {
const footer_position = endPos - @sizeOf(TGAFooter);
try seekStream.seekTo(footer_position);
const footer: TGAFooter = try readStructLittle(reader, TGAFooter);
if (footer.dot != '.') {
return false;
}
if (footer.null_value != 0) {
return false;
}
if (std.mem.eql(u8, footer.signature[0..], TGASignature[0..])) {
return true;
}
}
return false;
}
pub fn readForImage(allocator: *Allocator, reader: ImageReader, seekStream: ImageSeekStream, pixels: *?color.ColorStorage) !ImageInfo {
var tga = Self{};
try tga.read(allocator, reader, seekStream, pixels);
var imageInfo = ImageInfo{};
imageInfo.width = tga.width();
imageInfo.height = tga.height();
imageInfo.pixel_format = try tga.pixelFormat();
return imageInfo;
}
pub fn writeForImage(allocator: *Allocator, write_stream: image.ImageWriterStream, seek_stream: ImageSeekStream, pixels: color.ColorStorage, save_info: image.ImageSaveInfo) !void {}
pub fn width(self: Self) usize {
return self.header.width;
}
pub fn height(self: Self) usize {
return self.header.height;
}
pub fn pixelFormat(self: Self) !PixelFormat {
if (self.header.image_type.indexed) {
if (self.header.image_type.truecolor) {
return PixelFormat.Grayscale8;
}
return PixelFormat.Bpp8;
} else if (self.header.image_type.truecolor) {
switch (self.header.bit_per_pixel) {
16 => return PixelFormat.Rgb555,
24 => return PixelFormat.Rgb24,
32 => return PixelFormat.Rgba32,
else => {},
}
}
return errors.ImageError.UnsupportedPixelFormat;
}
pub fn read(self: *Self, allocator: *Allocator, reader: ImageReader, seekStream: ImageSeekStream, pixelsOpt: *?color.ColorStorage) !void {
// Read footage
const endPos = try seekStream.getEndPos();
if (@sizeOf(TGAFooter) > endPos) {
return errors.ImageFormatInvalid;
}
const footer_position = endPos - @sizeOf(TGAFooter);
try seekStream.seekTo(endPos - @sizeOf(TGAFooter));
const footer: TGAFooter = try readStructLittle(reader, TGAFooter);
if (!std.mem.eql(u8, footer.signature[0..], TGASignature[0..])) {
return errors.ImageError.InvalidMagicHeader;
}
// Read extension
if (footer.extension_offset > 0) {
const extension_pos = @intCast(u64, footer.extension_offset);
try seekStream.seekTo(extension_pos);
self.extension = try readStructLittle(reader, TGAExtension);
}
// Read header
try seekStream.seekTo(0);
self.header = try readStructLittle(reader, TGAHeader);
// Read ID
if (self.header.id_length > 0) {
var id_buffer: [256]u8 = undefined;
std.mem.set(u8, id_buffer[0..], 0);
const read_id_size = try reader.read(id_buffer[0..self.header.id_length]);
if (read_id_size != self.header.id_length) {
return errors.ImageError.InvalidMagicHeader;
}
}
const pixel_format = try self.pixelFormat();
pixelsOpt.* = try color.ColorStorage.init(allocator, pixel_format, self.width() * self.height());
if (pixelsOpt.*) |pixels| {
const is_compressed = self.header.image_type.run_length;
var targa_stream: TargaStream = TargaStream{ .image = reader };
var rle_decoder: ?TargaRLEDecoder = null;
defer {
if (rle_decoder) |rle| {
rle.deinit();
}
}
if (is_compressed) {
const bytes_per_pixel = (self.header.bit_per_pixel + 7) / 8;
rle_decoder = try TargaRLEDecoder.init(allocator, reader, bytes_per_pixel);
if (rle_decoder) |rle| {
targa_stream = TargaStream{ .rle = rle };
}
}
switch (pixel_format) {
.Grayscale8 => {
try self.readGrayscale8(pixels.Grayscale8, targa_stream.reader());
},
.Bpp8 => {
// Read color map
switch (self.header.color_map_bit_depth) {
15, 16 => {
try self.readColorMap16(pixels.Bpp8, (TargaStream{ .image = reader }).reader());
},
else => {
return errors.ImageError.UnsupportedPixelFormat;
},
}
// Read indices
try self.readIndexed8(pixels.Bpp8, targa_stream.reader());
},
.Rgb555 => {
try self.readTruecolor16(pixels.Rgb555, targa_stream.reader());
},
.Rgb24 => {
try self.readTruecolor24(pixels.Rgb24, targa_stream.reader());
},
.Rgba32 => {
try self.readTruecolor32(pixels.Rgba32, targa_stream.reader());
},
else => {
return errors.ImageError.UnsupportedPixelFormat;
},
}
} else {
return errors.ImageError.AllocationFailed;
}
}
fn readGrayscale8(self: *Self, data: []color.Grayscale8, stream: TargaStream.Reader) !void {
var dataIndex: usize = 0;
const dataEnd: usize = self.width() * self.height();
while (dataIndex < dataEnd) : (dataIndex += 1) {
data[dataIndex] = color.Grayscale8{ .value = try stream.readByte() };
}
}
fn readIndexed8(self: *Self, data: color.IndexedStorage8, stream: TargaStream.Reader) !void {
var dataIndex: usize = 0;
const dataEnd: usize = self.width() * self.height();
while (dataIndex < dataEnd) : (dataIndex += 1) {
data.indices[dataIndex] = try stream.readByte();
}
}
fn readColorMap16(self: *Self, data: color.IndexedStorage8, stream: TargaStream.Reader) !void {
var dataIndex: usize = self.header.first_entry_index;
const dataEnd: usize = self.header.first_entry_index + self.header.color_map_length;
while (dataIndex < dataEnd) : (dataIndex += 1) {
const raw_color = try stream.readIntLittle(u16);
data.palette[dataIndex].R = color.toColorFloat(@intCast(u5, (raw_color >> (5 * 2)) & 0x1F));
data.palette[dataIndex].G = color.toColorFloat(@intCast(u5, (raw_color >> 5) & 0x1F));
data.palette[dataIndex].B = color.toColorFloat(@intCast(u5, raw_color & 0x1F));
data.palette[dataIndex].A = 1.0;
}
}
fn readTruecolor16(self: *Self, data: []color.Rgb555, stream: TargaStream.Reader) !void {
var dataIndex: usize = 0;
const dataEnd: usize = self.width() * self.height();
while (dataIndex < dataEnd) : (dataIndex += 1) {
const raw_color = try stream.readIntLittle(u16);
data[dataIndex].R = @intCast(u5, (raw_color >> (5 * 2)) & 0x1F);
data[dataIndex].G = @intCast(u5, (raw_color >> 5) & 0x1F);
data[dataIndex].B = @intCast(u5, raw_color & 0x1F);
}
}
fn readTruecolor24(self: *Self, data: []color.Rgb24, stream: TargaStream.Reader) !void {
var dataIndex: usize = 0;
const dataEnd: usize = self.width() * self.height();
while (dataIndex < dataEnd) : (dataIndex += 1) {
data[dataIndex].B = try stream.readByte();
data[dataIndex].G = try stream.readByte();
data[dataIndex].R = try stream.readByte();
}
}
fn readTruecolor32(self: *Self, data: []color.Rgba32, stream: TargaStream.Reader) !void {
var dataIndex: usize = 0;
const dataEnd: usize = self.width() * self.height();
while (dataIndex < dataEnd) : (dataIndex += 1) {
data[dataIndex].B = try stream.readByte();
data[dataIndex].G = try stream.readByte();
data[dataIndex].R = try stream.readByte();
data[dataIndex].A = try stream.readByte();
if (self.extension) |extended_info| {
if (extended_info.attributes != TGAAttributeType.UsefulAlphaChannel) {
data[dataIndex].A = 0xFF;
}
}
}
}
};
|
src/formats/tga.zig
|
const std = @import("std");
const utils = @import("utils");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const print = utils.print;
const Cell = struct { number: i32, marked: bool };
const Bingo = struct {
drawn_numbers: []i32,
board_count: usize,
board_lines: [][]Cell,
};
pub fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror!Bingo {
var allocator = &arena.allocator;
const drawn_line = lines_it.next() orelse unreachable;
var drawn_it = std.mem.tokenize(u8, drawn_line, ",");
var drawn_numbers = try std.ArrayList(i32).initCapacity(allocator, 1024);
while (drawn_it.next()) |drawn| {
try drawn_numbers.append(try std.fmt.parseInt(i32, drawn, 10));
}
var cells = try std.ArrayList(Cell).initCapacity(allocator, 4096);
var board_lines = try std.ArrayList([]Cell).initCapacity(allocator, 1024);
var board_count: usize = 0;
while (lines_it.next()) |line| {
if (line.len == 0) {
board_count += 1;
continue;
}
const line_start = cells.items.len;
var line_it = std.mem.tokenize(u8, line, " ");
while (line_it.next()) |num| {
if (num.len == 0) {
continue;
}
try cells.append(Cell{
.number = try std.fmt.parseInt(i32, num, 10),
.marked = false,
});
}
try board_lines.append(cells.items[line_start..]);
}
print("File ok :) Number of boards: {d}", .{board_count});
return Bingo{
.drawn_numbers = drawn_numbers.items,
.board_count = board_count,
.board_lines = board_lines.items,
};
}
fn checkRow(board: [][]const Cell, row: usize) bool {
for (board[row]) |*cell| {
if (!cell.marked) {
return false;
}
}
return true;
}
fn checkCol(board: [][]const Cell, col: usize) bool {
for (board) |line| {
if (!line[col].marked) {
return false;
}
}
return true;
}
fn getBoardScore(board: [][]const Cell, drawn_number: i32) i32 {
var sum: i32 = 0;
for (board) |line| {
for (line) |*cell| {
if (!cell.marked) {
sum += cell.number;
}
}
}
return sum * drawn_number;
}
fn playBoard(bingo: Bingo, board_index: usize, drawn_number: i32) ?i32 {
const board_size = bingo.board_lines.len / bingo.board_count;
const start = board_size * board_index;
const end = start + board_size;
const board = bingo.board_lines[start..end];
// Mark numbers
for (board) |line, row| {
for (line) |*cell, col| {
if (cell.number == drawn_number) {
cell.marked = true;
if (checkCol(board, col) or checkRow(board, row)) {
return getBoardScore(board, drawn_number);
}
}
}
}
return null;
}
pub fn part1(bingo: Bingo) i32 {
for (bingo.drawn_numbers) |drawn_number| {
var board_index: usize = 0;
while (board_index < bingo.board_count) : (board_index += 1) {
if (playBoard(bingo, board_index, drawn_number)) |score| {
return score;
}
}
}
// No winner
return -1;
}
pub fn part2(bingo: Bingo) i32 {
var winning_board_count: i32 = 0;
var winning_boards = std.mem.zeroes([1024]bool);
for (bingo.drawn_numbers) |drawn_number| {
var board_index: usize = 0;
while (board_index < bingo.board_count) : (board_index += 1) {
if (playBoard(bingo, board_index, drawn_number)) |score| {
if (!winning_boards[board_index]) {
winning_boards[board_index] = true;
winning_board_count += 1;
}
if (winning_board_count == bingo.board_count) {
return score;
}
}
}
}
// No winner
return -1;
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt");
defer lines_it.deinit();
const input = try readInput(&arena, &lines_it);
const part1_result = part1(input);
print("Part 1: {d}", .{part1_result});
const part2_result = part2(input);
print("Part 2: {d}", .{part2_result});
}
|
day4/src/main.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const Token = @import("lex.zig").Token;
pub const Tree = struct {
node: *Node,
/// not owned by the tree
source: []const u8,
arena: std.heap.ArenaAllocator.State,
allocator: Allocator,
pub fn deinit(self: *Tree) void {
self.arena.promote(self.allocator).deinit();
}
pub fn chunk(self: *Tree) *Node.Chunk {
return @fieldParentPtr(Node.Chunk, "base", self.node);
}
pub fn dump(self: *Tree, writer: anytype) @TypeOf(writer).Error!void {
try self.node.dump(writer, 0);
}
};
pub const Node = struct {
id: Id,
pub const Id = enum {
chunk,
call,
literal,
identifier,
assignment_statement,
field_access,
index_access,
if_statement,
if_clause,
return_statement,
while_statement,
do_statement,
repeat_statement,
break_statement,
for_statement_numeric,
for_statement_generic,
function_declaration,
table_constructor,
table_field,
unary_expression,
binary_expression,
grouped_expression,
pub fn Type(id: Id) type {
return switch (id) {
.chunk => Chunk,
.call => Call,
.literal => Literal,
.identifier => Identifier,
.assignment_statement => AssignmentStatement,
.field_access => FieldAccess,
.index_access => IndexAccess,
.if_statement => IfStatement,
.if_clause => IfClause,
.return_statement => ReturnStatement,
.while_statement => WhileStatement,
.do_statement => DoStatement,
.repeat_statement => RepeatStatement,
.break_statement => BreakStatement,
.for_statement_numeric => ForStatementNumeric,
.for_statement_generic => ForStatementGeneric,
.function_declaration => FunctionDeclaration,
.table_constructor => TableConstructor,
.table_field => TableField,
.unary_expression => UnaryExpression,
.binary_expression => BinaryExpression,
.grouped_expression => GroupedExpression,
};
}
};
pub fn cast(base: *Node, comptime id: Id) ?*id.Type() {
if (base.id == id) {
return @fieldParentPtr(id.Type(), "base", base);
}
return null;
}
pub const Chunk = struct {
base: Node = .{ .id = .chunk },
body: []*Node,
};
pub const Call = struct {
base: Node = .{ .id = .call },
expression: *Node,
arguments: []*Node,
open_args_token: ?Token,
close_args_token: ?Token,
is_statement: bool = false,
};
pub const Literal = struct {
base: Node = .{ .id = .literal },
/// Can be one of .keyword_nil, .keyword_true, .keyword_false, .number, .string, or .name
/// (.name is a special case that is only used for table constructor field keys)
token: Token,
};
pub const Identifier = struct {
base: Node = .{ .id = .identifier },
token: Token,
};
pub const AssignmentStatement = struct {
base: Node = .{ .id = .assignment_statement },
variables: []*Node,
values: []*Node,
is_local: bool,
};
pub const FieldAccess = struct {
base: Node = .{ .id = .field_access },
prefix: *Node,
field: Token,
separator: Token,
};
pub const IndexAccess = struct {
base: Node = .{ .id = .index_access },
prefix: *Node,
index: *Node,
open_token: Token,
close_token: Token,
};
pub const IfStatement = struct {
base: Node = .{ .id = .if_statement },
clauses: []*Node,
};
/// if, elseif, or else
pub const IfClause = struct {
base: Node = .{ .id = .if_clause },
if_token: Token,
condition: ?*Node,
body: []*Node,
};
pub const ReturnStatement = struct {
base: Node = .{ .id = .return_statement },
values: []*Node,
};
pub const WhileStatement = struct {
base: Node = .{ .id = .while_statement },
condition: *Node,
body: []*Node,
};
pub const DoStatement = struct {
base: Node = .{ .id = .do_statement },
body: []*Node,
};
pub const RepeatStatement = struct {
base: Node = .{ .id = .repeat_statement },
body: []*Node,
condition: *Node,
};
pub const BreakStatement = struct {
base: Node = .{ .id = .break_statement },
token: Token,
};
pub const ForStatementNumeric = struct {
base: Node = .{ .id = .for_statement_numeric },
name: Token,
start: *Node,
end: *Node,
increment: ?*Node,
body: []*Node,
};
pub const ForStatementGeneric = struct {
base: Node = .{ .id = .for_statement_generic },
names: []Token,
expressions: []*Node,
body: []*Node,
};
pub const FunctionDeclaration = struct {
base: Node = .{ .id = .function_declaration },
name: ?*Node, // null for anonymous functions
parameters: []Token,
body: []*Node,
is_local: bool,
};
pub const TableConstructor = struct {
base: Node = .{ .id = .table_constructor },
fields: []*Node,
open_token: Token,
close_token: Token,
};
pub const TableField = struct {
base: Node = .{ .id = .table_field },
key: ?*Node,
value: *Node,
};
pub const UnaryExpression = struct {
base: Node = .{ .id = .unary_expression },
operator: Token,
argument: *Node,
};
pub const BinaryExpression = struct {
base: Node = .{ .id = .binary_expression },
operator: Token,
left: *Node,
right: *Node,
};
pub const GroupedExpression = struct {
base: Node = .{ .id = .grouped_expression },
open_token: Token,
expression: *Node,
close_token: Token,
};
/// Gets the last token of an expression
/// Needed for detecting ambiguous function calls
pub fn getLastToken(node: *const Node) Token {
switch (node.id) {
.identifier => {
const casted = @fieldParentPtr(Node.Identifier, "base", node);
return casted.token;
},
.grouped_expression => {
const casted = @fieldParentPtr(Node.GroupedExpression, "base", node);
return casted.close_token;
},
.field_access => {
const casted = @fieldParentPtr(Node.FieldAccess, "base", node);
return casted.field;
},
.index_access => {
const casted = @fieldParentPtr(Node.IndexAccess, "base", node);
return casted.close_token;
},
.call => {
const casted = @fieldParentPtr(Node.Call, "base", node);
if (casted.close_args_token) |close_token| {
return close_token;
} else {
return casted.arguments[casted.arguments.len - 1].getLastToken();
}
},
.literal => {
const casted = @fieldParentPtr(Node.Literal, "base", node);
return casted.token;
},
.table_constructor => {
const casted = @fieldParentPtr(Node.TableConstructor, "base", node);
return casted.close_token;
},
else => {
std.debug.print("{}\n", .{node});
@panic("TODO");
},
}
}
pub fn dump(
node: *const Node,
writer: anytype,
indent: usize,
) @TypeOf(writer).Error!void {
try writer.writeByteNTimes(' ', indent);
try writer.writeAll(@tagName(node.id));
switch (node.id) {
.chunk => {
try writer.writeAll("\n");
const chunk = @fieldParentPtr(Node.Chunk, "base", node);
for (chunk.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.call => {
try writer.writeAll("\n");
const call = @fieldParentPtr(Node.Call, "base", node);
try call.expression.dump(writer, indent + 1);
try writer.writeByteNTimes(' ', indent + 1);
try writer.writeAll("(");
if (call.arguments.len > 0) {
try writer.writeAll("\n");
for (call.arguments) |arg_node| {
try arg_node.dump(writer, indent + 2);
}
try writer.writeByteNTimes(' ', indent + 1);
}
try writer.writeAll(")\n");
},
.identifier => {
try writer.writeAll("\n");
},
.literal => {
const literal = @fieldParentPtr(Node.Literal, "base", node);
try writer.writeAll(" ");
try writer.writeAll(literal.token.nameForDisplay());
try writer.writeAll("\n");
},
.assignment_statement => {
const assignment = @fieldParentPtr(Node.AssignmentStatement, "base", node);
if (assignment.is_local) {
try writer.writeAll(" local");
}
try writer.writeAll("\n");
for (assignment.variables) |var_node| {
try var_node.dump(writer, indent + 1);
}
if (assignment.values.len > 0) {
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("=\n");
for (assignment.values) |value_node| {
try value_node.dump(writer, indent + 1);
}
}
},
.field_access => {
const field_access = @fieldParentPtr(Node.FieldAccess, "base", node);
try writer.writeAll(" ");
try writer.writeAll(field_access.separator.nameForDisplay());
try writer.writeAll(field_access.field.nameForDisplay());
try writer.writeAll("\n");
try field_access.prefix.dump(writer, indent + 1);
},
.index_access => {
const index_access = @fieldParentPtr(Node.IndexAccess, "base", node);
try writer.writeAll("\n");
try index_access.prefix.dump(writer, indent + 1);
try index_access.index.dump(writer, indent + 1);
},
.if_statement => {
const if_statement = @fieldParentPtr(Node.IfStatement, "base", node);
try writer.writeAll("\n");
for (if_statement.clauses) |clause| {
try clause.dump(writer, indent + 1);
}
},
.if_clause => {
const if_clause = @fieldParentPtr(Node.IfClause, "base", node);
try writer.writeAll(" ");
try writer.writeAll(if_clause.if_token.nameForDisplay());
try writer.writeAll("\n");
if (if_clause.condition) |condition| {
try condition.dump(writer, indent + 1);
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("then\n");
}
for (if_clause.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.return_statement => {
const return_statement = @fieldParentPtr(Node.ReturnStatement, "base", node);
try writer.writeAll("\n");
for (return_statement.values) |value_node| {
try value_node.dump(writer, indent + 1);
}
},
.while_statement => {
const while_statement = @fieldParentPtr(Node.WhileStatement, "base", node);
try writer.writeAll("\n");
try while_statement.condition.dump(writer, indent + 1);
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("do\n");
for (while_statement.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.do_statement => {
const do_statement = @fieldParentPtr(Node.DoStatement, "base", node);
try writer.writeAll("\n");
for (do_statement.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.repeat_statement => {
const repeat_statement = @fieldParentPtr(Node.RepeatStatement, "base", node);
try writer.writeAll("\n");
for (repeat_statement.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("until\n");
try repeat_statement.condition.dump(writer, indent + 1);
},
.break_statement => {
try writer.writeAll("\n");
},
.for_statement_numeric => {
const for_statement = @fieldParentPtr(Node.ForStatementNumeric, "base", node);
try writer.writeAll("\n");
try for_statement.start.dump(writer, indent + 1);
try for_statement.end.dump(writer, indent + 1);
if (for_statement.increment) |increment| {
try increment.dump(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("do\n");
for (for_statement.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.for_statement_generic => {
const for_statement = @fieldParentPtr(Node.ForStatementGeneric, "base", node);
for (for_statement.names) |name_token| {
try writer.writeAll(" ");
try writer.writeAll(name_token.nameForDisplay());
}
try writer.writeAll("\n");
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("in\n");
for (for_statement.expressions) |exp_node| {
try exp_node.dump(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("do\n");
for (for_statement.body) |body_node| {
try body_node.dump(writer, indent + 1);
}
},
.function_declaration => {
const func = @fieldParentPtr(Node.FunctionDeclaration, "base", node);
if (func.is_local) {
try writer.writeAll(" local");
}
try writer.writeAll("\n");
if (func.name) |name| {
try name.dump(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent + 1);
try writer.writeAll("(");
for (func.parameters) |param, i| {
if (i != 0) try writer.writeAll(" ");
try writer.writeAll(param.nameForDisplay());
}
try writer.writeAll(")\n");
for (func.body) |body_node| {
try body_node.dump(writer, indent + 2);
}
},
.table_constructor => {
const constructor = @fieldParentPtr(Node.TableConstructor, "base", node);
try writer.writeAll("\n");
for (constructor.fields) |field| {
try field.dump(writer, indent + 1);
}
},
.table_field => {
const field = @fieldParentPtr(Node.TableField, "base", node);
try writer.writeAll("\n");
if (field.key) |key| {
try key.dump(writer, indent + 1);
try writer.writeByteNTimes(' ', indent);
try writer.writeAll("=\n");
}
try field.value.dump(writer, indent + 1);
},
.unary_expression => {
const unary = @fieldParentPtr(Node.UnaryExpression, "base", node);
try writer.writeAll(" ");
try writer.writeAll(unary.operator.nameForDisplay());
try writer.writeAll("\n");
try unary.argument.dump(writer, indent + 1);
},
.binary_expression => {
const binary = @fieldParentPtr(Node.BinaryExpression, "base", node);
try writer.writeAll(" ");
try writer.writeAll(binary.operator.nameForDisplay());
try writer.writeAll("\n");
try binary.left.dump(writer, indent + 1);
try binary.right.dump(writer, indent + 1);
},
.grouped_expression => {
const grouped = @fieldParentPtr(Node.GroupedExpression, "base", node);
try writer.writeAll("\n");
try writer.writeByteNTimes(' ', indent);
try writer.writeAll(grouped.open_token.nameForDisplay());
try writer.writeAll("\n");
try grouped.expression.dump(writer, indent + 1);
try writer.writeByteNTimes(' ', indent);
try writer.writeAll(grouped.close_token.nameForDisplay());
try writer.writeAll("\n");
},
}
}
};
|
src/ast.zig
|
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const assert = std.debug.assert;
const Compilation = @import("Compilation.zig");
const Source = @import("Source.zig");
const Tokenizer = @import("Tokenizer.zig");
const Preprocessor = @import("Preprocessor.zig");
const Tree = @import("Tree.zig");
const Token = Tree.Token;
const TokenIndex = Tree.TokenIndex;
const NodeIndex = Tree.NodeIndex;
const Type = @import("Type.zig");
const Diagnostics = @import("Diagnostics.zig");
const NodeList = std.ArrayList(NodeIndex);
const Parser = @This();
const Scope = union(enum) {
typedef: Symbol,
@"struct": Symbol,
@"union": Symbol,
@"enum": Symbol,
decl: Symbol,
def: Symbol,
param: Symbol,
enumeration: Enumeration,
loop,
@"switch": *Switch,
block,
const Symbol = struct {
name: []const u8,
ty: Type,
name_tok: TokenIndex,
};
const Enumeration = struct {
name: []const u8,
value: Result,
name_tok: TokenIndex,
};
const Switch = struct {
cases: CaseMap,
default: ?Case = null,
const ResultContext = struct {
pub fn eql(_: ResultContext, a: Result, b: Result) bool {
return a.eql(b);
}
pub fn hash(_: ResultContext, a: Result) u64 {
return a.hash();
}
};
const CaseMap = std.HashMap(Result, Case, ResultContext, std.hash_map.default_max_load_percentage);
const Case = struct {
node: NodeIndex,
tok: TokenIndex,
};
};
};
const Label = union(enum) {
unresolved_goto: TokenIndex,
label: TokenIndex,
};
pub const Error = Compilation.Error || error{ParsingFailed};
// values from preprocessor
pp: *Preprocessor,
tok_ids: []const Token.Id,
tok_i: TokenIndex = 0,
// values of the incomplete Tree
arena: *Allocator,
nodes: Tree.Node.List = .{},
data: NodeList,
strings: std.ArrayList(u8),
value_map: Tree.ValueMap,
// buffers used during compilation
scopes: std.ArrayList(Scope),
labels: std.ArrayList(Label),
list_buf: NodeList,
decl_buf: NodeList,
param_buf: std.ArrayList(Type.Func.Param),
enum_buf: std.ArrayList(Type.Enum.Field),
record_buf: std.ArrayList(Type.Record.Field),
// configuration and miscellaneous info
no_eval: bool = false,
in_macro: bool = false,
return_type: ?Type = null,
func_name: TokenIndex = 0,
label_count: u32 = 0,
fn eatToken(p: *Parser, id: Token.Id) ?TokenIndex {
if (p.tok_ids[p.tok_i] == id) {
defer p.tok_i += 1;
return p.tok_i;
} else return null;
}
fn expectToken(p: *Parser, expected: Token.Id) Error!TokenIndex {
const actual = p.tok_ids[p.tok_i];
if (actual != expected) {
try p.errExtra(
switch (actual) {
.invalid => .expected_invalid,
else => .expected_token,
},
p.tok_i,
.{ .tok_id = .{
.expected = expected,
.actual = actual,
} },
);
return error.ParsingFailed;
}
defer p.tok_i += 1;
return p.tok_i;
}
fn tokSlice(p: *Parser, tok: TokenIndex) []const u8 {
if (p.tok_ids[tok].lexeme()) |some| return some;
const loc = p.pp.tokens.items(.loc)[tok];
var tmp_tokenizer = Tokenizer{
.buf = if (loc.id == .generated)
p.pp.generated.items
else
p.pp.comp.getSource(loc.id).buf,
.comp = p.pp.comp,
.index = loc.byte_offset,
.source = .generated,
};
const res = tmp_tokenizer.next();
return tmp_tokenizer.buf[res.start..res.end];
}
fn expectClosing(p: *Parser, opening: TokenIndex, id: Token.Id) Error!void {
_ = p.expectToken(id) catch |e| {
if (e == error.ParsingFailed) {
try p.pp.comp.addDiagnostic(.{
.tag = switch (id) {
.r_paren => .to_match_paren,
.r_brace => .to_match_brace,
.r_bracket => .to_match_brace,
else => unreachable,
},
.loc = p.pp.tokens.items(.loc)[opening],
});
}
return e;
};
}
pub fn errStr(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex, str: []const u8) Compilation.Error!void {
@setCold(true);
return p.errExtra(tag, tok_i, .{ .str = str });
}
pub fn errExtra(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex, extra: Diagnostics.Message.Extra) Compilation.Error!void {
@setCold(true);
try p.pp.comp.addDiagnostic(.{
.tag = tag,
.loc = p.pp.tokens.items(.loc)[tok_i],
.extra = extra,
});
}
pub fn errTok(p: *Parser, tag: Diagnostics.Tag, tok_i: TokenIndex) Compilation.Error!void {
@setCold(true);
try p.pp.comp.addDiagnostic(.{
.tag = tag,
.loc = p.pp.tokens.items(.loc)[tok_i],
});
}
pub fn err(p: *Parser, tag: Diagnostics.Tag) Compilation.Error!void {
@setCold(true);
return p.errTok(tag, p.tok_i);
}
pub fn todo(p: *Parser, msg: []const u8) Error {
try p.errStr(.todo, p.tok_i, msg);
return error.ParsingFailed;
}
pub fn typeStr(p: *Parser, ty: Type) ![]const u8 {
if (Type.Builder.fromType(ty).str()) |str| return str;
const strings_top = p.strings.items.len;
defer p.strings.items.len = strings_top;
try ty.print(p.strings.writer());
return try p.arena.dupe(u8, p.strings.items[strings_top..]);
}
pub fn typePairStr(p: *Parser, a: Type, b: Type) ![]const u8 {
return p.typePairStrExtra(a, " and ", b);
}
pub fn typePairStrExtra(p: *Parser, a: Type, msg: []const u8, b: Type) ![]const u8 {
const strings_top = p.strings.items.len;
defer p.strings.items.len = strings_top;
try p.strings.append('\'');
try a.print(p.strings.writer());
try p.strings.append('\'');
try p.strings.appendSlice(msg);
try p.strings.append('\'');
try b.print(p.strings.writer());
try p.strings.append('\'');
return try p.arena.dupe(u8, p.strings.items[strings_top..]);
}
fn addNode(p: *Parser, node: Tree.Node) Allocator.Error!NodeIndex {
if (p.in_macro) return .none;
const res = p.nodes.len;
try p.nodes.append(p.pp.comp.gpa, node);
return @intToEnum(NodeIndex, res);
}
fn addList(p: *Parser, nodes: []const NodeIndex) Allocator.Error!Tree.Node.Range {
const start = @intCast(u32, p.data.items.len);
try p.data.appendSlice(nodes);
const end = @intCast(u32, p.data.items.len);
return Tree.Node.Range{ .start = start, .end = end };
}
fn findTypedef(p: *Parser, name_tok: TokenIndex) !?Scope.Symbol {
const name = p.tokSlice(name_tok);
var i = p.scopes.items.len;
while (i > 0) {
i -= 1;
switch (p.scopes.items[i]) {
.typedef => |t| if (mem.eql(u8, t.name, name)) return t,
.@"struct" => |s| if (mem.eql(u8, s.name, name)) {
try p.errStr(.must_use_struct, name_tok, name);
return s;
},
.@"union" => |u| if (mem.eql(u8, u.name, name)) {
try p.errStr(.must_use_union, name_tok, name);
return u;
},
.@"enum" => |e| if (mem.eql(u8, e.name, name)) {
try p.errStr(.must_use_enum, name_tok, name);
return e;
},
else => {},
}
}
return null;
}
fn findSymbol(p: *Parser, name_tok: TokenIndex, ref_kind: enum { reference, definition }) ?Scope {
const name = p.tokSlice(name_tok);
var i = p.scopes.items.len;
while (i > 0) {
i -= 1;
const sym = p.scopes.items[i];
switch (sym) {
.def, .decl, .param => |s| if (mem.eql(u8, s.name, name)) return sym,
.enumeration => |e| if (mem.eql(u8, e.name, name)) return sym,
.block => if (ref_kind == .definition) return null,
else => {},
}
}
return null;
}
fn findTag(p: *Parser, kind: Token.Id, name_tok: TokenIndex, ref_kind: enum { reference, definition }) !?Scope.Symbol {
const name = p.tokSlice(name_tok);
var i = p.scopes.items.len;
var saw_block = false;
while (i > 0) {
i -= 1;
const sym = p.scopes.items[i];
switch (sym) {
.@"enum" => |e| if (mem.eql(u8, e.name, name)) {
if (kind == .keyword_enum) return e;
if (saw_block) return null;
try p.errStr(.wrong_tag, name_tok, name);
try p.errTok(.previous_definition, e.name_tok);
return null;
},
.@"struct" => |s| if (mem.eql(u8, s.name, name)) {
if (kind == .keyword_struct) return s;
if (saw_block) return null;
try p.errStr(.wrong_tag, name_tok, name);
try p.errTok(.previous_definition, s.name_tok);
return null;
},
.@"union" => |u| if (mem.eql(u8, u.name, name)) {
if (kind == .keyword_union) return u;
if (saw_block) return null;
try p.errStr(.wrong_tag, name_tok, name);
try p.errTok(.previous_definition, u.name_tok);
return null;
},
.block => if (ref_kind == .reference) {
saw_block = true;
} else return null,
else => {},
}
}
return null;
}
fn inLoop(p: *Parser) bool {
var i = p.scopes.items.len;
while (i > 0) {
i -= 1;
switch (p.scopes.items[i]) {
.loop => return true,
else => {},
}
}
return false;
}
fn inLoopOrSwitch(p: *Parser) bool {
var i = p.scopes.items.len;
while (i > 0) {
i -= 1;
switch (p.scopes.items[i]) {
.loop, .@"switch" => return true,
else => {},
}
}
return false;
}
fn findLabel(p: *Parser, name: []const u8) ?TokenIndex {
for (p.labels.items) |item| {
switch (item) {
.label => |l| if (mem.eql(u8, p.tokSlice(l), name)) return l,
.unresolved_goto => {},
}
}
return null;
}
fn findSwitch(p: *Parser) ?*Scope.Switch {
var i = p.scopes.items.len;
while (i > 0) {
i -= 1;
switch (p.scopes.items[i]) {
.@"switch" => |s| return s,
else => {},
}
}
return null;
}
fn nodeIs(p: *Parser, node: NodeIndex, tag: Tree.Tag) bool {
var cur = node;
const tags = p.nodes.items(.tag);
const data = p.nodes.items(.data);
while (true) {
const cur_tag = tags[@enumToInt(cur)];
if (cur_tag == .paren_expr) {
cur = data[@enumToInt(cur)].un;
} else if (cur_tag == tag) {
return true;
} else {
return false;
}
}
}
/// root : (decl | staticAssert)*
pub fn parse(pp: *Preprocessor) Compilation.Error!Tree {
var arena = std.heap.ArenaAllocator.init(pp.comp.gpa);
errdefer arena.deinit();
var p = Parser{
.pp = pp,
.arena = &arena.allocator,
.tok_ids = pp.tokens.items(.id),
.strings = std.ArrayList(u8).init(pp.comp.gpa),
.value_map = Tree.ValueMap.init(pp.comp.gpa),
.data = NodeList.init(pp.comp.gpa),
.labels = std.ArrayList(Label).init(pp.comp.gpa),
.scopes = std.ArrayList(Scope).init(pp.comp.gpa),
.list_buf = NodeList.init(pp.comp.gpa),
.decl_buf = NodeList.init(pp.comp.gpa),
.param_buf = std.ArrayList(Type.Func.Param).init(pp.comp.gpa),
.enum_buf = std.ArrayList(Type.Enum.Field).init(pp.comp.gpa),
.record_buf = std.ArrayList(Type.Record.Field).init(pp.comp.gpa),
};
errdefer {
p.nodes.deinit(pp.comp.gpa);
p.strings.deinit();
p.value_map.deinit();
}
defer {
p.data.deinit();
p.labels.deinit();
p.scopes.deinit();
p.list_buf.deinit();
p.decl_buf.deinit();
p.param_buf.deinit();
p.enum_buf.deinit();
p.record_buf.deinit();
}
// NodeIndex 0 must be invalid
_ = try p.addNode(.{ .tag = .invalid, .ty = undefined, .data = undefined });
while (p.eatToken(.eof) == null) {
if (p.staticAssert() catch |er| switch (er) {
error.ParsingFailed => {
p.nextExternDecl();
continue;
},
else => |e| return e,
}) continue;
if (p.decl() catch |er| switch (er) {
error.ParsingFailed => {
p.nextExternDecl();
continue;
},
else => |e| return e,
}) continue;
try p.err(.expected_external_decl);
p.tok_i += 1;
}
return Tree{
.comp = pp.comp,
.tokens = pp.tokens.slice(),
.arena = arena,
.generated = pp.generated.items,
.nodes = p.nodes.toOwnedSlice(),
.data = p.data.toOwnedSlice(),
.root_decls = p.decl_buf.toOwnedSlice(),
.strings = p.strings.toOwnedSlice(),
.value_map = p.value_map,
};
}
fn nextExternDecl(p: *Parser) void {
var parens: u32 = 0;
while (p.tok_i < p.tok_ids.len) : (p.tok_i += 1) {
switch (p.tok_ids[p.tok_i]) {
.l_paren, .l_brace, .l_bracket => parens += 1,
.r_paren, .r_brace, .r_bracket => if (parens != 0) {
parens -= 1;
},
.keyword_typedef,
.keyword_extern,
.keyword_static,
.keyword_auto,
.keyword_register,
.keyword_thread_local,
.keyword_inline,
.keyword_noreturn,
.keyword_void,
.keyword_bool,
.keyword_char,
.keyword_short,
.keyword_int,
.keyword_long,
.keyword_signed,
.keyword_unsigned,
.keyword_float,
.keyword_double,
.keyword_complex,
.keyword_atomic,
.keyword_enum,
.keyword_struct,
.keyword_union,
.keyword_alignas,
.identifier,
.keyword_typeof,
.keyword_typeof1,
.keyword_typeof2,
=> if (parens == 0) return,
else => {},
}
}
p.tok_i -= 1; // so that we can consume the eof token elsewhere
}
// ====== declarations ======
/// decl
/// : declSpec (initDeclarator ( ',' initDeclarator)*)? ';'
/// | declSpec declarator decl* compoundStmt
fn decl(p: *Parser) Error!bool {
const first_tok = p.tok_i;
var decl_spec = if (try p.declSpec(false)) |some| some else blk: {
if (p.return_type != null) return false;
switch (p.tok_ids[first_tok]) {
.asterisk, .l_paren, .identifier => {},
else => return false,
}
var spec: Type.Builder = .{};
break :blk DeclSpec{ .ty = try spec.finish(p) };
};
var init_d = (try p.initDeclarator(&decl_spec)) orelse {
_ = try p.expectToken(.semicolon);
if (decl_spec.ty.specifier == .@"enum") return true;
if (decl_spec.ty.isRecord() and decl_spec.ty.data.record.name[0] != '(') return true;
try p.errTok(.missing_declaration, first_tok);
return true;
};
// Check for function definition.
if (init_d.d.func_declarator != null and init_d.initializer == .none and init_d.d.ty.isFunc()) fn_def: {
switch (p.tok_ids[p.tok_i]) {
.comma, .semicolon => break :fn_def,
.l_brace => {},
else => if (init_d.d.old_style_func == null) {
try p.err(.expected_fn_body);
break :fn_def;
},
}
if (p.return_type != null) try p.err(.func_not_in_root);
// TODO check redefinition
try p.scopes.append(.{ .def = .{
.name = p.tokSlice(init_d.d.name),
.ty = init_d.d.ty,
.name_tok = init_d.d.name,
} });
const return_type = p.return_type;
const func_name = p.func_name;
p.return_type = init_d.d.ty.data.func.return_type;
p.func_name = init_d.d.name;
defer {
p.return_type = return_type;
p.func_name = func_name;
}
const scopes_top = p.scopes.items.len;
defer p.scopes.items.len = scopes_top;
// findSymbol stops the search at .block
try p.scopes.append(.block);
// Collect old style parameter declarations.
if (init_d.d.old_style_func != null) {
init_d.d.ty.specifier = .func;
const param_buf_top = p.param_buf.items.len;
defer p.param_buf.items.len = param_buf_top;
param_loop: while (true) {
const param_decl_spec = (try p.declSpec(true)) orelse break;
if (p.eatToken(.semicolon)) |semi| {
try p.errTok(.missing_declaration, semi);
continue :param_loop;
}
while (true) {
var d = (try p.declarator(param_decl_spec.ty, .normal)) orelse {
try p.errTok(.missing_declaration, first_tok);
_ = try p.expectToken(.semicolon);
continue :param_loop;
};
if (d.ty.isFunc()) {
// Params declared as functions are converted to function pointers.
const elem_ty = try p.arena.create(Type);
elem_ty.* = d.ty;
d.ty = Type{
.specifier = .pointer,
.data = .{ .sub_type = elem_ty },
};
} else if (d.ty.isArray()) {
// params declared as arrays are converted to pointers
d.ty.decayArray();
} else if (d.ty.specifier == .void) {
try p.errTok(.invalid_void_param, d.name);
}
// find and correct parameter types
// TODO check for missing declarations and redefinitions
const name_str = p.tokSlice(d.name);
for (init_d.d.ty.data.func.params) |*param| {
if (mem.eql(u8, param.name, name_str)) {
param.ty = d.ty;
break;
}
} else {
try p.errStr(.parameter_missing, d.name, name_str);
}
try p.scopes.append(.{ .param = .{
.name = name_str,
.name_tok = d.name,
.ty = d.ty,
} });
if (p.eatToken(.comma) == null) break;
}
_ = try p.expectToken(.semicolon);
}
} else {
for (init_d.d.ty.data.func.params) |param| {
if (param.ty.hasUnboundVLA()) try p.errTok(.unbound_vla, param.name_tok);
try p.scopes.append(.{
.param = .{
.name = param.name,
.ty = param.ty,
.name_tok = param.name_tok,
},
});
}
}
const body = try p.compoundStmt(true);
const node = try p.addNode(.{
.ty = init_d.d.ty,
.tag = try decl_spec.validateFnDef(p),
.data = .{ .decl = .{ .name = init_d.d.name, .node = body.? } },
});
try p.decl_buf.append(node);
// check gotos
if (return_type == null) {
for (p.labels.items) |item| {
if (item == .unresolved_goto)
try p.errStr(.undeclared_label, item.unresolved_goto, p.tokSlice(item.unresolved_goto));
}
p.labels.items.len = 0;
p.label_count = 0;
}
return true;
}
// Declare all variable/typedef declarators.
while (true) {
if (init_d.d.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i);
const tag = try decl_spec.validate(p, &init_d.d.ty, init_d.initializer != .none);
const node = try p.addNode(.{ .ty = init_d.d.ty, .tag = tag, .data = .{
.decl = .{ .name = init_d.d.name, .node = init_d.initializer },
} });
try p.decl_buf.append(node);
const sym = Scope.Symbol{
.name = p.tokSlice(init_d.d.name),
.ty = init_d.d.ty,
.name_tok = init_d.d.name,
};
if (decl_spec.storage_class == .typedef) {
try p.scopes.append(.{ .typedef = sym });
} else if (init_d.initializer != .none) {
try p.scopes.append(.{ .def = sym });
} else {
try p.scopes.append(.{ .decl = sym });
}
if (p.eatToken(.comma) == null) break;
init_d = (try p.initDeclarator(&decl_spec)) orelse {
try p.err(.expected_ident_or_l_paren);
continue;
};
}
_ = try p.expectToken(.semicolon);
return true;
}
/// staticAssert : keyword_static_assert '(' constExpr ',' STRING_LITERAL ')' ';'
fn staticAssert(p: *Parser) Error!bool {
const static_assert = p.eatToken(.keyword_static_assert) orelse return false;
const l_paren = try p.expectToken(.l_paren);
const res_token = p.tok_i;
const res = try p.constExpr();
const str = if (p.eatToken(.comma) != null)
switch (p.tok_ids[p.tok_i]) {
.string_literal,
.string_literal_utf_16,
.string_literal_utf_8,
.string_literal_utf_32,
.string_literal_wide,
=> try p.stringLiteral(),
else => {
try p.err(.expected_str_literal);
return error.ParsingFailed;
},
}
else
Result{};
try p.expectClosing(l_paren, .r_paren);
_ = try p.expectToken(.semicolon);
if (str.node == .none) try p.errTok(.static_assert_missing_message, static_assert);
if (res.val == .unavailable) {
// an unavailable sizeof expression is already a compile error, so we don't emit
// another error for an invalid _Static_assert condition. This matches the behavior
// of gcc/clang
if (!p.nodeIs(res.node, .sizeof_expr)) try p.errTok(.static_assert_not_constant, res_token);
} else if (!res.getBool()) {
if (str.node != .none) {
const strings_top = p.strings.items.len;
defer p.strings.items.len = strings_top;
const data = p.nodes.items(.data)[@enumToInt(str.node)].str;
try Tree.dumpStr(
p.strings.items[data.index..][0..data.len],
p.nodes.items(.tag)[@enumToInt(str.node)],
p.strings.writer(),
);
try p.errStr(
.static_assert_failure_message,
static_assert,
try p.arena.dupe(u8, p.strings.items[strings_top..]),
);
} else try p.errTok(.static_assert_failure, static_assert);
}
const node = try p.addNode(.{
.tag = .static_assert,
.data = .{ .bin = .{
.lhs = res.node,
.rhs = str.node,
} },
});
try p.decl_buf.append(node);
return true;
}
pub const DeclSpec = struct {
storage_class: union(enum) {
auto: TokenIndex,
@"extern": TokenIndex,
register: TokenIndex,
static: TokenIndex,
typedef: TokenIndex,
none,
} = .none,
thread_local: ?TokenIndex = null,
@"inline": ?TokenIndex = null,
@"noreturn": ?TokenIndex = null,
ty: Type = .{ .specifier = undefined },
fn validateParam(d: DeclSpec, p: *Parser, ty: *Type) Error!void {
switch (d.storage_class) {
.none => {},
.register => ty.qual.register = true,
.auto, .@"extern", .static, .typedef => |tok_i| try p.errTok(.invalid_storage_on_param, tok_i),
}
if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i);
if (d.@"inline") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "inline");
if (d.@"noreturn") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "_Noreturn");
}
fn validateFnDef(d: DeclSpec, p: *Parser) Error!Tree.Tag {
switch (d.storage_class) {
.none, .@"extern", .static => {},
.auto, .register, .typedef => |tok_i| try p.errTok(.illegal_storage_on_func, tok_i),
}
if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i);
const is_static = d.storage_class == .static;
const is_inline = d.@"inline" != null;
const is_noreturn = d.@"noreturn" != null;
if (is_static) {
if (is_inline and is_noreturn) return .noreturn_inline_static_fn_def;
if (is_inline) return .inline_static_fn_def;
if (is_noreturn) return .noreturn_static_fn_def;
return .static_fn_def;
} else {
if (is_inline and is_noreturn) return .noreturn_inline_fn_def;
if (is_inline) return .inline_fn_def;
if (is_noreturn) return .noreturn_fn_def;
return .fn_def;
}
}
fn validate(d: DeclSpec, p: *Parser, ty: *Type, has_init: bool) Error!Tree.Tag {
const is_static = d.storage_class == .static;
if (ty.isFunc() and d.storage_class != .typedef) {
switch (d.storage_class) {
.none, .@"extern" => {},
.static => |tok_i| if (p.return_type != null) try p.errTok(.static_func_not_global, tok_i),
.typedef => unreachable,
.auto, .register => |tok_i| try p.errTok(.illegal_storage_on_func, tok_i),
}
if (d.thread_local) |tok_i| try p.errTok(.threadlocal_non_var, tok_i);
const is_inline = d.@"inline" != null;
const is_noreturn = d.@"noreturn" != null;
if (is_static) {
if (is_inline and is_noreturn) return .noreturn_inline_static_fn_proto;
if (is_inline) return .inline_static_fn_proto;
if (is_noreturn) return .noreturn_static_fn_proto;
return .static_fn_proto;
} else {
if (is_inline and is_noreturn) return .noreturn_inline_fn_proto;
if (is_inline) return .inline_fn_proto;
if (is_noreturn) return .noreturn_fn_proto;
return .fn_proto;
}
} else {
if (d.@"inline") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "inline");
if (d.@"noreturn") |tok_i| try p.errStr(.func_spec_non_func, tok_i, "_Noreturn");
switch (d.storage_class) {
.auto, .register => if (p.return_type == null) try p.err(.illegal_storage_on_global),
.typedef => return .typedef,
else => {},
}
ty.qual.register = d.storage_class == .register;
const is_extern = d.storage_class == .@"extern" and !has_init;
if (d.thread_local != null) {
if (is_static) return .threadlocal_static_var;
if (is_extern) return .threadlocal_extern_var;
return .threadlocal_var;
} else {
if (is_static) return .static_var;
if (is_extern) return .extern_var;
return .@"var";
}
}
}
};
fn typeof(p: *Parser) Error!?Type {
switch (p.tok_ids[p.tok_i]) {
.keyword_typeof, .keyword_typeof1, .keyword_typeof2 => p.tok_i += 1,
else => return null,
}
const l_paren = try p.expectToken(.l_paren);
const start = p.tok_i;
if (try p.typeName()) |ty| {
try p.expectClosing(l_paren, .r_paren);
return ty;
}
p.tok_i = start;
if (p.eatToken(.r_paren)) |r_paren| {
try p.errTok(.expected_expr, r_paren);
return error.ParsingFailed;
}
const typeof_expr = try p.parseNoEval(assignExpr);
try p.expectClosing(l_paren, .r_paren);
return typeof_expr.ty;
}
/// declSpec: (storageClassSpec | typeSpec | typeQual | funcSpec | alignSpec)+
/// storageClassSpec:
/// : keyword_typedef
/// | keyword_extern
/// | keyword_static
/// | keyword_threadlocal
/// | keyword_auto
/// | keyword_register
/// funcSpec : keyword_inline | keyword_noreturn
fn declSpec(p: *Parser, is_param: bool) Error!?DeclSpec {
var d: DeclSpec = .{};
var spec: Type.Builder = .{};
const start = p.tok_i;
while (true) {
if (try p.typeSpec(&spec)) continue;
const id = p.tok_ids[p.tok_i];
switch (id) {
.keyword_typedef,
.keyword_extern,
.keyword_static,
.keyword_auto,
.keyword_register,
=> {
if (d.storage_class != .none) {
try p.errStr(.multiple_storage_class, p.tok_i, @tagName(d.storage_class));
return error.ParsingFailed;
}
if (d.thread_local != null) {
switch (id) {
.keyword_typedef,
.keyword_auto,
.keyword_register,
=> try p.errStr(.cannot_combine_spec, p.tok_i, id.lexeme().?),
else => {},
}
}
switch (id) {
.keyword_typedef => d.storage_class = .{ .typedef = p.tok_i },
.keyword_extern => d.storage_class = .{ .@"extern" = p.tok_i },
.keyword_static => d.storage_class = .{ .static = p.tok_i },
.keyword_auto => d.storage_class = .{ .auto = p.tok_i },
.keyword_register => d.storage_class = .{ .register = p.tok_i },
else => unreachable,
}
},
.keyword_thread_local => {
if (d.thread_local != null) {
try p.errStr(.duplicate_decl_spec, p.tok_i, "_Thread_local");
}
switch (d.storage_class) {
.@"extern", .none, .static => {},
else => try p.errStr(.cannot_combine_spec, p.tok_i, @tagName(d.storage_class)),
}
d.thread_local = p.tok_i;
},
.keyword_inline => {
if (d.@"inline" != null) {
try p.errStr(.duplicate_decl_spec, p.tok_i, "inline");
}
d.@"inline" = p.tok_i;
},
.keyword_noreturn => {
if (d.@"noreturn" != p.tok_i) {
try p.errStr(.duplicate_decl_spec, p.tok_i, "_Noreturn");
}
d.@"noreturn" = null;
},
else => break,
}
p.tok_i += 1;
}
if (p.tok_i == start) return null;
if (is_param and spec.align_tok != null) {
try p.errTok(.alignas_on_param, spec.align_tok.?);
spec.align_tok = null;
}
d.ty = try spec.finish(p);
return d;
}
const InitDeclarator = struct { d: Declarator, initializer: NodeIndex = .none };
/// initDeclarator : declarator ('=' initializer)?
fn initDeclarator(p: *Parser, decl_spec: *DeclSpec) Error!?InitDeclarator {
var init_d = InitDeclarator{
.d = (try p.declarator(decl_spec.ty, .normal)) orelse return null,
};
if (p.eatToken(.equal)) |eq| {
if (decl_spec.storage_class == .typedef or init_d.d.func_declarator != null) {
try p.errTok(.illegal_initializer, eq);
} else if (init_d.d.ty.specifier == .variable_len_array) {
try p.errTok(.vla_init, eq);
} else if (decl_spec.storage_class == .@"extern") {
try p.err(.extern_initializer);
decl_spec.storage_class = .none;
}
var init_list_expr = try p.initializer(init_d.d.ty);
try init_list_expr.expect(p);
init_d.initializer = init_list_expr.node;
init_d.d.ty = init_list_expr.ty;
}
const name = init_d.d.name;
if (init_d.d.ty.hasIncompleteSize()) {
try p.errStr(.variable_incomplete_ty, name, try p.typeStr(init_d.d.ty));
return init_d;
}
if (p.findSymbol(name, .definition)) |scope| switch (scope) {
.enumeration => {
try p.errStr(.redefinition_different_sym, name, p.tokSlice(name));
try p.errTok(.previous_definition, scope.enumeration.name_tok);
},
.decl => |s| if (!s.ty.eql(init_d.d.ty, true)) {
try p.errStr(.redefinition_incompatible, name, p.tokSlice(name));
try p.errTok(.previous_definition, s.name_tok);
},
.def => |s| if (!s.ty.eql(init_d.d.ty, true)) {
try p.errStr(.redefinition_incompatible, name, p.tokSlice(name));
try p.errTok(.previous_definition, s.name_tok);
} else if (init_d.initializer != .none) {
try p.errStr(.redefinition, name, p.tokSlice(name));
try p.errTok(.previous_definition, s.name_tok);
},
.param => |s| {
try p.errStr(.redefinition, name, p.tokSlice(name));
try p.errTok(.previous_definition, s.name_tok);
},
else => unreachable,
};
return init_d;
}
/// typeSpec
/// : keyword_void
/// | keyword_char
/// | keyword_short
/// | keyword_int
/// | keyword_long
/// | keyword_float
/// | keyword_double
/// | keyword_signed
/// | keyword_unsigned
/// | keyword_bool
/// | keyword_complex
/// | atomicTypeSpec
/// | recordSpec
/// | enumSpec
/// | typedef // IDENTIFIER
/// atomicTypeSpec : keyword_atomic '(' typeName ')'
/// alignSpec
/// : keyword_alignas '(' typeName ')'
/// | keyword_alignas '(' constExpr ')'
fn typeSpec(p: *Parser, ty: *Type.Builder) Error!bool {
const start = p.tok_i;
while (true) {
if (try p.typeof()) |inner_ty| {
try ty.combineFromTypeof(p, inner_ty, start);
continue;
}
if (try p.typeQual(&ty.qual)) continue;
switch (p.tok_ids[p.tok_i]) {
.keyword_void => try ty.combine(p, .void, p.tok_i),
.keyword_bool => try ty.combine(p, .bool, p.tok_i),
.keyword_char => try ty.combine(p, .char, p.tok_i),
.keyword_short => try ty.combine(p, .short, p.tok_i),
.keyword_int => try ty.combine(p, .int, p.tok_i),
.keyword_long => try ty.combine(p, .long, p.tok_i),
.keyword_signed => try ty.combine(p, .signed, p.tok_i),
.keyword_unsigned => try ty.combine(p, .unsigned, p.tok_i),
.keyword_float => try ty.combine(p, .float, p.tok_i),
.keyword_double => try ty.combine(p, .double, p.tok_i),
.keyword_complex => try ty.combine(p, .complex, p.tok_i),
.keyword_atomic => {
const atomic_tok = p.tok_i;
p.tok_i += 1;
const l_paren = p.eatToken(.l_paren) orelse {
// _Atomic qualifier not _Atomic(typeName)
p.tok_i = atomic_tok;
break;
};
const inner_ty = (try p.typeName()) orelse {
try p.err(.expected_type);
return error.ParsingFailed;
};
try p.expectClosing(l_paren, .r_paren);
const new_spec = Type.Builder.fromType(inner_ty);
try ty.combine(p, new_spec, atomic_tok);
if (ty.qual.atomic != null)
try p.errStr(.duplicate_decl_spec, atomic_tok, "atomic")
else
ty.qual.atomic = atomic_tok;
continue;
},
.keyword_struct => {
const tag_tok = p.tok_i;
try ty.combine(p, .{ .@"struct" = try p.recordSpec() }, tag_tok);
continue;
},
.keyword_union => {
const tag_tok = p.tok_i;
try ty.combine(p, .{ .@"union" = try p.recordSpec() }, tag_tok);
continue;
},
.keyword_enum => {
const tag_tok = p.tok_i;
try ty.combine(p, .{ .@"enum" = try p.enumSpec() }, tag_tok);
continue;
},
.identifier => {
const typedef = (try p.findTypedef(p.tok_i)) orelse break;
const new_spec = Type.Builder.fromType(typedef.ty);
const err_start = p.pp.comp.diag.list.items.len;
ty.combine(p, new_spec, p.tok_i) catch {
// Remove new error messages
// TODO improve/make threadsafe?
p.pp.comp.diag.list.items.len = err_start;
break;
};
ty.typedef = .{
.tok = typedef.name_tok,
.ty = typedef.ty,
};
},
.keyword_alignas => {
if (ty.align_tok != null) try p.errStr(.duplicate_decl_spec, p.tok_i, "alignment");
ty.align_tok = p.tok_i;
p.tok_i += 1;
const l_paren = try p.expectToken(.l_paren);
if (try p.typeName()) |inner_ty| {
ty.alignment = inner_ty.alignment;
} else blk: {
const res = try p.constExpr();
if (res.val == .signed and res.val.signed < 0) {
try p.errExtra(.negative_alignment, ty.align_tok.?, .{ .signed = res.val.signed });
break :blk;
}
var requested = std.math.cast(u29, res.as_u64()) catch {
try p.errExtra(.maximum_alignment, ty.align_tok.?, .{ .unsigned = res.as_u64() });
break :blk;
};
if (requested == 0) {
try p.errTok(.zero_align_ignored, ty.align_tok.?);
} else if (!std.mem.isValidAlign(requested)) {
requested = 0;
try p.errTok(.non_pow2_align, ty.align_tok.?);
}
ty.alignment = requested;
}
try p.expectClosing(l_paren, .r_paren);
continue;
},
else => break,
}
p.tok_i += 1;
}
return p.tok_i != start;
}
fn getAnonymousName(p: *Parser, kind_tok: TokenIndex) ![]const u8 {
const loc = p.pp.tokens.items(.loc)[kind_tok];
const source = p.pp.comp.getSource(loc.id);
const lcs = source.lineColString(loc.byte_offset);
const kind_str = switch (p.tok_ids[kind_tok]) {
.keyword_struct, .keyword_union, .keyword_enum => p.tokSlice(kind_tok),
else => "record field",
};
return std.fmt.allocPrint(
p.arena,
"(anonymous {s} at {s}:{d}:{d})",
.{ kind_str, source.path, lcs.line, lcs.col },
);
}
/// recordSpec
/// : (keyword_struct | keyword_union) IDENTIFIER? { recordDecl* }
/// | (keyword_struct | keyword_union) IDENTIFIER
fn recordSpec(p: *Parser) Error!*Type.Record {
const kind_tok = p.tok_i;
const is_struct = p.tok_ids[kind_tok] == .keyword_struct;
p.tok_i += 1;
const maybe_ident = p.eatToken(.identifier);
const l_brace = p.eatToken(.l_brace) orelse {
const ident = maybe_ident orelse {
try p.err(.ident_or_l_brace);
return error.ParsingFailed;
};
// check if this is a reference to a previous type
if (try p.findTag(p.tok_ids[kind_tok], ident, .reference)) |prev| {
return prev.ty.data.record;
} else {
// this is a forward declaration, create a new record Type.
const record_ty = try Type.Record.create(p.arena, p.tokSlice(ident));
const ty = Type{
.specifier = if (is_struct) .@"struct" else .@"union",
.data = .{ .record = record_ty },
};
const sym = Scope.Symbol{ .name = record_ty.name, .ty = ty, .name_tok = ident };
try p.scopes.append(if (is_struct) .{ .@"struct" = sym } else .{ .@"union" = sym });
return record_ty;
}
};
// Get forward declared type or create a new one
const record_ty: *Type.Record = if (maybe_ident) |ident| record_ty: {
if (try p.findTag(p.tok_ids[kind_tok], ident, .definition)) |prev| {
if (!prev.ty.data.record.isIncomplete()) {
// if the record isn't incomplete, this is a redefinition
try p.errStr(.redefinition, ident, p.tokSlice(ident));
try p.errTok(.previous_definition, prev.name_tok);
} else {
break :record_ty prev.ty.data.record;
}
}
break :record_ty try Type.Record.create(p.arena, p.tokSlice(ident));
} else try Type.Record.create(p.arena, try p.getAnonymousName(kind_tok));
const ty = Type{
.specifier = if (is_struct) .@"struct" else .@"union",
.data = .{ .record = record_ty },
};
// declare a symbol for the type
if (maybe_ident) |ident| {
const sym = Scope.Symbol{ .name = record_ty.name, .ty = ty, .name_tok = ident };
try p.scopes.append(if (is_struct) .{ .@"struct" = sym } else .{ .@"union" = sym });
}
// reserve space for this record
try p.decl_buf.append(.none);
const decl_buf_top = p.decl_buf.items.len;
const record_buf_top = p.record_buf.items.len;
defer {
p.decl_buf.items.len = decl_buf_top;
p.record_buf.items.len = record_buf_top;
}
try p.recordDecls();
record_ty.fields = try p.arena.dupe(Type.Record.Field, p.record_buf.items[record_buf_top..]);
if (p.record_buf.items.len == record_buf_top) try p.errStr(.empty_record, kind_tok, p.tokSlice(kind_tok));
try p.expectClosing(l_brace, .r_brace);
// finish by creating a node
var node: Tree.Node = .{
.tag = if (is_struct) .struct_decl_two else .union_decl_two,
.ty = ty,
.data = .{ .bin = .{ .lhs = .none, .rhs = .none } },
};
const record_decls = p.decl_buf.items[decl_buf_top..];
switch (record_decls.len) {
0 => {},
1 => node.data = .{ .bin = .{ .lhs = record_decls[0], .rhs = .none } },
2 => node.data = .{ .bin = .{ .lhs = record_decls[0], .rhs = record_decls[1] } },
else => {
node.tag = if (is_struct) .struct_decl else .union_decl;
node.data = .{ .range = try p.addList(record_decls) };
},
}
p.decl_buf.items[decl_buf_top - 1] = try p.addNode(node);
return record_ty;
}
/// recordDecl
/// : specQual (recordDeclarator (',' recordDeclarator)*)? ;
/// | staticAssert
/// recordDeclarator : declarator (':' constExpr)?
fn recordDecls(p: *Parser) Error!void {
while (true) {
if (try p.staticAssert()) continue;
const base_ty = (try p.specQual()) orelse return;
while (true) {
// 0 means unnamed
var name_tok: TokenIndex = 0;
var ty = base_ty;
var bits_node: NodeIndex = .none;
var bits: u32 = 0;
const first_tok = p.tok_i;
if (try p.declarator(ty, .record)) |d| {
name_tok = d.name;
ty = d.ty;
}
if (p.eatToken(.colon)) |_| {
const res = try p.constExpr();
// TODO check using math.cast
switch (res.val) {
.unsigned => |v| bits = @intCast(u32, v),
.signed => |v| bits = @intCast(u32, v),
.unavailable => unreachable,
}
bits_node = res.node;
}
if (name_tok == 0 and bits_node == .none) unnamed: {
if (ty.specifier == .@"enum") break :unnamed;
if (ty.isRecord() and ty.data.record.name[0] == '(') {
// An anonymous record appears as indirect fields on the parent
try p.record_buf.append(.{
.name = try p.getAnonymousName(first_tok),
.ty = ty,
.bit_width = 0,
});
const node = try p.addNode(.{
.tag = .indirect_record_field_decl,
.ty = ty,
.data = undefined,
});
try p.decl_buf.append(node);
break; // must be followed by a semicolon
}
try p.err(.missing_declaration);
} else {
try p.record_buf.append(.{
.name = if (name_tok != 0) p.tokSlice(name_tok) else try p.getAnonymousName(first_tok),
.ty = ty,
.bit_width = bits,
});
const node = try p.addNode(.{
.tag = .record_field_decl,
.ty = ty,
.data = .{ .decl = .{ .name = name_tok, .node = bits_node } },
});
try p.decl_buf.append(node);
}
if (p.eatToken(.comma) == null) break;
}
_ = try p.expectToken(.semicolon);
}
}
/// specQual : (typeSpec | typeQual | alignSpec)+
fn specQual(p: *Parser) Error!?Type {
if (try p.typeof()) |ty| return ty;
var spec: Type.Builder = .{};
if (try p.typeSpec(&spec)) {
if (spec.alignment != 0) try p.errTok(.align_ignored, spec.align_tok.?);
spec.align_tok = null;
return try spec.finish(p);
}
return null;
}
/// enumSpec
/// : keyword_enum IDENTIFIER? { enumerator (',' enumerator)? ',') }
/// | keyword_enum IDENTIFIER
fn enumSpec(p: *Parser) Error!*Type.Enum {
const enum_tok = p.tok_i;
p.tok_i += 1;
const maybe_ident = p.eatToken(.identifier);
const l_brace = p.eatToken(.l_brace) orelse {
const ident = maybe_ident orelse {
try p.err(.ident_or_l_brace);
return error.ParsingFailed;
};
// check if this is a reference to a previous type
if (try p.findTag(.keyword_enum, ident, .reference)) |prev| {
return prev.ty.data.@"enum";
} else {
// this is a forward declaration, create a new enum Type.
const enum_ty = try Type.Enum.create(p.arena, p.tokSlice(ident));
const ty = Type{ .specifier = .@"enum", .data = .{ .@"enum" = enum_ty } };
const sym = Scope.Symbol{ .name = enum_ty.name, .ty = ty, .name_tok = ident };
try p.scopes.append(.{ .@"enum" = sym });
return enum_ty;
}
};
// Get forward declared type or create a new one
const enum_ty: *Type.Enum = if (maybe_ident) |ident| enum_ty: {
if (try p.findTag(.keyword_enum, ident, .definition)) |prev| {
if (!prev.ty.data.@"enum".isIncomplete()) {
// if the enum isn't incomplete, this is a redefinition
try p.errStr(.redefinition, ident, p.tokSlice(ident));
try p.errTok(.previous_definition, prev.name_tok);
} else {
break :enum_ty prev.ty.data.@"enum";
}
}
break :enum_ty try Type.Enum.create(p.arena, p.tokSlice(ident));
} else try Type.Enum.create(p.arena, try p.getAnonymousName(enum_tok));
const ty = Type{
.specifier = .@"enum",
.data = .{ .@"enum" = enum_ty },
};
// declare a symbol for the type
if (maybe_ident) |ident| {
try p.scopes.append(.{ .@"enum" = .{
.name = enum_ty.name,
.ty = ty,
.name_tok = ident,
} });
}
// reserve space for this enum
try p.decl_buf.append(.none);
const decl_buf_top = p.decl_buf.items.len;
const list_buf_top = p.list_buf.items.len;
const enum_buf_top = p.enum_buf.items.len;
defer {
p.decl_buf.items.len = decl_buf_top;
p.list_buf.items.len = list_buf_top;
p.enum_buf.items.len = enum_buf_top;
}
while (try p.enumerator()) |field_and_node| {
try p.enum_buf.append(field_and_node.field);
try p.list_buf.append(field_and_node.node);
if (p.eatToken(.comma) == null) break;
}
enum_ty.fields = try p.arena.dupe(Type.Enum.Field, p.enum_buf.items[enum_buf_top..]);
if (p.enum_buf.items.len == enum_buf_top) try p.err(.empty_enum);
try p.expectClosing(l_brace, .r_brace);
// finish by creating a node
var node: Tree.Node = .{ .tag = .enum_decl_two, .ty = ty, .data = .{
.bin = .{ .lhs = .none, .rhs = .none },
} };
const field_nodes = p.list_buf.items[list_buf_top..];
switch (field_nodes.len) {
0 => {},
1 => node.data = .{ .bin = .{ .lhs = field_nodes[0], .rhs = .none } },
2 => node.data = .{ .bin = .{ .lhs = field_nodes[0], .rhs = field_nodes[1] } },
else => {
node.tag = .enum_decl;
node.data = .{ .range = try p.addList(field_nodes) };
},
}
p.decl_buf.items[decl_buf_top - 1] = try p.addNode(node);
return enum_ty;
}
const EnumFieldAndNode = struct { field: Type.Enum.Field, node: NodeIndex };
/// enumerator : IDENTIFIER ('=' constExpr)
fn enumerator(p: *Parser) Error!?EnumFieldAndNode {
const name_tok = p.eatToken(.identifier) orelse {
if (p.tok_ids[p.tok_i] == .r_brace) return null;
try p.err(.expected_identifier);
// TODO skip to }
return error.ParsingFailed;
};
const name = p.tokSlice(name_tok);
// TODO get from enumSpec
var res: Result = .{
.ty = .{ .specifier = .int },
.val = .{
.unsigned = 0,
},
};
if (p.eatToken(.equal)) |_| {
res = try p.constExpr();
}
if (p.findSymbol(name_tok, .definition)) |scope| switch (scope) {
.enumeration => |e| {
try p.errStr(.redefinition, name_tok, name);
try p.errTok(.previous_definition, e.name_tok);
},
.decl, .def, .param => |s| {
try p.errStr(.redefinition_different_sym, name_tok, name);
try p.errTok(.previous_definition, s.name_tok);
},
else => unreachable,
};
try p.scopes.append(.{ .enumeration = .{
.name = name,
.value = res,
.name_tok = name_tok,
} });
return EnumFieldAndNode{ .field = .{
.name = name,
.ty = res.ty,
.value = res.as_u64(),
}, .node = try p.addNode(.{
.tag = .enum_field_decl,
.ty = res.ty,
.data = .{ .decl = .{
.name = name_tok,
.node = res.node,
} },
}) };
}
/// typeQual : keyword_const | keyword_restrict | keyword_volatile | keyword_atomic
fn typeQual(p: *Parser, b: *Type.Qualifiers.Builder) Error!bool {
var any = false;
while (true) {
switch (p.tok_ids[p.tok_i]) {
.keyword_restrict, .keyword_restrict1, .keyword_restrict2 => {
if (b.restrict != null)
try p.errStr(.duplicate_decl_spec, p.tok_i, "restrict")
else
b.restrict = p.tok_i;
},
.keyword_const, .keyword_const1, .keyword_const2 => {
if (b.@"const" != null)
try p.errStr(.duplicate_decl_spec, p.tok_i, "const")
else
b.@"const" = p.tok_i;
},
.keyword_volatile, .keyword_volatile1, .keyword_volatile2 => {
if (b.@"volatile" != null)
try p.errStr(.duplicate_decl_spec, p.tok_i, "volatile")
else
b.@"volatile" = p.tok_i;
},
.keyword_atomic => {
// _Atomic(typeName) instead of just _Atomic
if (p.tok_ids[p.tok_i + 1] == .l_paren) break;
if (b.atomic != null)
try p.errStr(.duplicate_decl_spec, p.tok_i, "atomic")
else
b.atomic = p.tok_i;
},
else => break,
}
p.tok_i += 1;
any = true;
}
return any;
}
const Declarator = struct {
name: TokenIndex,
ty: Type,
func_declarator: ?TokenIndex = null,
old_style_func: ?TokenIndex = null,
};
const DeclaratorKind = enum { normal, abstract, param, record };
/// declarator : pointer? (IDENTIFIER | '(' declarator ')') directDeclarator*
/// abstractDeclarator
/// : pointer? ('(' abstractDeclarator ')')? directAbstractDeclarator*
fn declarator(
p: *Parser,
base_type: Type,
kind: DeclaratorKind,
) Error!?Declarator {
const start = p.tok_i;
var d = Declarator{ .name = 0, .ty = try p.pointer(base_type) };
if (kind != .abstract and p.tok_ids[p.tok_i] == .identifier) {
d.name = p.tok_i;
p.tok_i += 1;
d.ty = try p.directDeclarator(d.ty, &d, kind);
return d;
} else if (p.eatToken(.l_paren)) |l_paren| blk: {
var res = (try p.declarator(.{ .specifier = .void }, kind)) orelse {
p.tok_i = l_paren;
break :blk;
};
try p.expectClosing(l_paren, .r_paren);
const suffix_start = p.tok_i;
const outer = try p.directDeclarator(d.ty, &d, kind);
try res.ty.combine(outer, p, res.func_declarator orelse suffix_start);
res.old_style_func = d.old_style_func;
return res;
}
if (kind == .normal and !base_type.isEnumOrRecord()) {
try p.err(.expected_ident_or_l_paren);
}
d.ty = try p.directDeclarator(d.ty, &d, kind);
if (start == p.tok_i) return null;
return d;
}
/// directDeclarator
/// : '[' typeQual* assignExpr? ']' directDeclarator?
/// | '[' keyword_static typeQual* assignExpr ']' directDeclarator?
/// | '[' typeQual+ keyword_static assignExpr ']' directDeclarator?
/// | '[' typeQual* '*' ']' directDeclarator?
/// | '(' paramDecls ')' directDeclarator?
/// | '(' (IDENTIFIER (',' IDENTIFIER))? ')' directDeclarator?
/// directAbstractDeclarator
/// : '[' typeQual* assignExpr? ']'
/// | '[' keyword_static typeQual* assignExpr ']'
/// | '[' typeQual+ keyword_static assignExpr ']'
/// | '[' '*' ']'
/// | '(' paramDecls? ')'
fn directDeclarator(p: *Parser, base_type: Type, d: *Declarator, kind: DeclaratorKind) Error!Type {
if (p.eatToken(.l_bracket)) |l_bracket| {
var res_ty = Type{
// so that we can get any restrict type that might be present
.specifier = .pointer,
};
var quals = Type.Qualifiers.Builder{};
var got_quals = try p.typeQual(&quals);
var static = p.eatToken(.keyword_static);
if (static != null and !got_quals) got_quals = try p.typeQual(&quals);
var star = p.eatToken(.asterisk);
const size = if (star) |_| Result{} else try p.assignExpr();
try p.expectClosing(l_bracket, .r_bracket);
if (star != null and static != null) {
try p.errTok(.invalid_static_star, static.?);
static = null;
}
if (kind != .param) {
if (static != null)
try p.errTok(.static_non_param, l_bracket)
else if (got_quals)
try p.errTok(.array_qualifiers, l_bracket);
if (star) |some| try p.errTok(.star_non_param, some);
static = null;
quals = .{};
star = null;
} else {
try quals.finish(p, &res_ty);
}
if (static) |_| try size.expect(p);
const outer = try p.directDeclarator(base_type, d, kind);
var max_bits = p.pp.comp.target.cpu.arch.ptrBitWidth();
if (max_bits > 61) max_bits = 61;
const max_bytes = (@as(u64, 1) << @truncate(u6, max_bits)) - 1;
const max_elems = max_bytes / (outer.sizeof(p.pp.comp) orelse 1);
switch (size.val) {
.unavailable => if (size.node != .none) {
if (p.return_type == null and kind != .param) try p.errTok(.variable_len_array_file_scope, l_bracket);
const vla_ty = try p.arena.create(Type.VLA);
vla_ty.expr = size.node;
res_ty.data = .{ .vla = vla_ty };
res_ty.specifier = .variable_len_array;
if (static) |some| try p.errTok(.useless_static, some);
} else if (star) |_| {
const elem_ty = try p.arena.create(Type);
res_ty.data = .{ .sub_type = elem_ty };
res_ty.specifier = .unspecified_variable_len_array;
} else {
const arr_ty = try p.arena.create(Type.Array);
arr_ty.len = 0;
res_ty.data = .{ .array = arr_ty };
res_ty.specifier = .incomplete_array;
},
.unsigned => |v| {
const arr_ty = try p.arena.create(Type.Array);
arr_ty.len = v;
if (arr_ty.len > max_elems) {
try p.errTok(.array_too_large, l_bracket);
arr_ty.len = max_elems;
}
res_ty.data = .{ .array = arr_ty };
res_ty.specifier = .array;
},
.signed => |v| {
if (v < 0) try p.errTok(.negative_array_size, l_bracket);
const arr_ty = try p.arena.create(Type.Array);
arr_ty.len = @bitCast(u64, v);
if (arr_ty.len > max_elems) {
try p.errTok(.array_too_large, l_bracket);
arr_ty.len = max_elems;
}
res_ty.data = .{ .array = arr_ty };
res_ty.specifier = .array;
},
}
try res_ty.combine(outer, p, l_bracket);
return res_ty;
} else if (p.eatToken(.l_paren)) |l_paren| {
d.func_declarator = l_paren;
if (p.tok_ids[p.tok_i] == .ellipsis) {
try p.err(.param_before_var_args);
p.tok_i += 1;
}
const func_ty = try p.arena.create(Type.Func);
func_ty.params = &.{};
var specifier: Type.Specifier = .func;
if (try p.paramDecls()) |params| {
func_ty.params = params;
if (p.eatToken(.ellipsis)) |_| specifier = .var_args_func;
} else if (p.tok_ids[p.tok_i] == .r_paren) {
specifier = .old_style_func;
} else if (p.tok_ids[p.tok_i] == .identifier) {
d.old_style_func = p.tok_i;
const param_buf_top = p.param_buf.items.len;
const scopes_top = p.scopes.items.len;
defer {
p.param_buf.items.len = param_buf_top;
p.scopes.items.len = scopes_top;
}
// findSymbol stops the search at .block
try p.scopes.append(.block);
specifier = .old_style_func;
while (true) {
const name_tok = try p.expectToken(.identifier);
if (p.findSymbol(name_tok, .definition)) |scope| {
try p.errStr(.redefinition_of_parameter, name_tok, p.tokSlice(name_tok));
try p.errTok(.previous_definition, scope.param.name_tok);
}
try p.scopes.append(.{ .param = .{
.name = p.tokSlice(name_tok),
.ty = undefined,
.name_tok = name_tok,
} });
try p.param_buf.append(.{
.name = p.tokSlice(name_tok),
.name_tok = name_tok,
.ty = .{ .specifier = .int },
});
if (p.eatToken(.comma) == null) break;
}
func_ty.params = try p.arena.dupe(Type.Func.Param, p.param_buf.items[param_buf_top..]);
} else {
try p.err(.expected_param_decl);
}
try p.expectClosing(l_paren, .r_paren);
var res_ty = Type{
.specifier = specifier,
.data = .{ .func = func_ty },
};
const outer = try p.directDeclarator(base_type, d, kind);
try res_ty.combine(outer, p, l_paren);
return res_ty;
} else return base_type;
}
/// pointer : '*' typeQual* pointer?
fn pointer(p: *Parser, base_ty: Type) Error!Type {
var ty = base_ty;
while (p.eatToken(.asterisk)) |_| {
const elem_ty = try p.arena.create(Type);
elem_ty.* = ty;
ty = Type{
.specifier = .pointer,
.data = .{ .sub_type = elem_ty },
};
var quals = Type.Qualifiers.Builder{};
_ = try p.typeQual(&quals);
try quals.finish(p, &ty);
}
return ty;
}
/// paramDecls : paramDecl (',' paramDecl)* (',' '...')
/// paramDecl : declSpec (declarator | abstractDeclarator)
fn paramDecls(p: *Parser) Error!?[]Type.Func.Param {
// TODO warn about visibility of types declared here
const param_buf_top = p.param_buf.items.len;
const scopes_top = p.scopes.items.len;
defer {
p.param_buf.items.len = param_buf_top;
p.scopes.items.len = scopes_top;
}
// findSymbol stops the search at .block
try p.scopes.append(.block);
while (true) {
const param_decl_spec = if (try p.declSpec(true)) |some|
some
else if (p.param_buf.items.len == param_buf_top)
return null
else blk: {
var spec: Type.Builder = .{};
break :blk DeclSpec{ .ty = try spec.finish(p) };
};
var name_tok: TokenIndex = 0;
const first_tok = p.tok_i;
var param_ty = param_decl_spec.ty;
if (try p.declarator(param_decl_spec.ty, .param)) |some| {
if (some.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i);
name_tok = some.name;
param_ty = some.ty;
if (some.name != 0) {
if (p.findSymbol(name_tok, .definition)) |scope| {
if (scope == .enumeration) {
try p.errStr(.redefinition_of_parameter, name_tok, p.tokSlice(name_tok));
try p.errTok(.previous_definition, scope.enumeration.name_tok);
} else {
try p.errStr(.redefinition_of_parameter, name_tok, p.tokSlice(name_tok));
try p.errTok(.previous_definition, scope.param.name_tok);
}
}
try p.scopes.append(.{ .param = .{
.name = p.tokSlice(name_tok),
.ty = some.ty,
.name_tok = name_tok,
} });
}
}
if (param_ty.isFunc()) {
// params declared as functions are converted to function pointers
const elem_ty = try p.arena.create(Type);
elem_ty.* = param_ty;
param_ty = Type{
.specifier = .pointer,
.data = .{ .sub_type = elem_ty },
};
} else if (param_ty.isArray()) {
// params declared as arrays are converted to pointers
param_ty.decayArray();
} else if (param_ty.specifier == .void) {
// validate void parameters
if (p.param_buf.items.len == param_buf_top) {
if (p.tok_ids[p.tok_i] != .r_paren) {
try p.err(.void_only_param);
if (param_ty.qual.any()) try p.err(.void_param_qualified);
return error.ParsingFailed;
}
return &[0]Type.Func.Param{};
}
try p.err(.void_must_be_first_param);
return error.ParsingFailed;
}
try param_decl_spec.validateParam(p, ¶m_ty);
try p.param_buf.append(.{
.name = if (name_tok == 0) "" else p.tokSlice(name_tok),
.name_tok = if (name_tok == 0) first_tok else name_tok,
.ty = param_ty,
});
if (p.eatToken(.comma) == null) break;
if (p.tok_ids[p.tok_i] == .ellipsis) break;
}
return try p.arena.dupe(Type.Func.Param, p.param_buf.items[param_buf_top..]);
}
/// typeName : specQual abstractDeclarator
fn typeName(p: *Parser) Error!?Type {
var ty = (try p.specQual()) orelse return null;
if (try p.declarator(ty, .abstract)) |some| {
if (some.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i);
return some.ty;
} else return ty;
}
/// initializer
/// : assignExpr
/// | '{' initializerItems '}'
/// initializerItems : designation? initializer (',' designation? initializer)* ','?
/// designation : designator+ '='
/// designator
/// : '[' constExpr ']'
/// | '.' identifier
fn initializer(p: *Parser, init_ty: Type) Error!Result {
const l_brace = p.eatToken(.l_brace) orelse {
const tok = p.tok_i;
var res = try p.assignExpr();
if (res.empty(p)) return res;
try p.coerceInit(&res, tok, init_ty);
return res;
};
var node: Tree.Node = .{
.tag = .init_list_expr_two,
.ty = init_ty,
.data = .{ .bin = .{ .lhs = .none, .rhs = .none } },
};
const is_scalar = init_ty.isInt() or init_ty.isFloat() or init_ty.isPtr();
if (p.eatToken(.r_brace)) |_| {
if (is_scalar) try p.errTok(.empty_scalar_init, l_brace);
return Result{ .node = try p.addNode(node), .ty = init_ty };
}
const list_buf_top = p.list_buf.items.len;
defer p.list_buf.items.len = list_buf_top;
var elem_ty = init_ty;
if (elem_ty.isArray()) {
elem_ty = elem_ty.elemType();
}
var first: Result = undefined;
var is_str_init = false;
while (true) {
const first_tok = p.tok_i;
var cur_ty = elem_ty;
var designator = false;
while (true) {
if (p.eatToken(.l_bracket)) |l_bracket| {
const res = try p.constExpr();
_ = res;
try p.expectClosing(l_bracket, .r_bracket);
designator = true;
} else if (p.eatToken(.period)) |_| {
const identifier = try p.expectToken(.identifier);
_ = identifier;
designator = true;
} else break;
}
const count = p.list_buf.items.len - list_buf_top;
var init_res: Result = undefined;
if (designator) {
_ = try p.expectToken(.equal);
init_res = try p.initializer(cur_ty);
try init_res.expect(p);
} else if (p.isStringInit()) {
if (count == 0) is_str_init = true;
init_res = try p.initializer(init_ty);
} else {
init_res = try p.initializer(cur_ty);
if (init_res.node == .none) break;
}
if (count == 0) {
first = init_res;
} else if (count == 1) {
if (is_scalar) try p.errTok(.excess_scalar_init, first_tok);
if (is_str_init) try p.errTok(.excess_str_init, first_tok);
}
try p.list_buf.append(init_res.node);
if (p.eatToken(.comma) == null) break;
}
try p.expectClosing(l_brace, .r_brace);
const initializers = p.list_buf.items[list_buf_top..];
if (is_scalar or is_str_init) return first;
if (init_ty.specifier == .incomplete_array) {
node.ty.data.array.len = initializers.len;
node.ty.specifier = .array;
}
switch (initializers.len) {
0 => unreachable,
1 => node.data = .{ .bin = .{ .lhs = initializers[0], .rhs = .none } },
2 => node.data = .{ .bin = .{ .lhs = initializers[0], .rhs = initializers[1] } },
else => {
node.tag = .init_list_expr;
node.data = .{ .range = try p.addList(initializers) };
},
}
return Result{ .node = try p.addNode(node), .ty = node.ty };
}
fn coerceInit(p: *Parser, item: *Result, tok: TokenIndex, target: Type) !void {
// item does not need to be qualified
var unqual_ty = target;
unqual_ty.qual = .{};
const e_msg = " from incompatible type ";
if (unqual_ty.isArray()) {
if (!item.ty.isArray()) {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
} else if (unqual_ty.specifier == .array) {
assert(item.ty.specifier == .array);
var len = item.ty.data.array.len;
if (p.nodeIs(item.node, .string_literal_expr)) {
if (len - 1 > unqual_ty.data.array.len)
try p.errTok(.str_init_too_long, tok);
} else if (len > unqual_ty.data.array.len) {
try p.errStr(
.arr_init_too_long,
tok,
try p.typePairStrExtra(target, " with array of type ", item.ty),
);
}
}
return;
}
try item.lvalConversion(p);
if (target.specifier == .bool) {
// this is ridiculous but it's what clang does
if (item.ty.isInt() or item.ty.isFloat() or item.ty.isPtr()) {
try item.boolCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
}
} else if (unqual_ty.isInt()) {
if (item.ty.isInt() or item.ty.isFloat()) {
try item.intCast(p, unqual_ty);
} else if (item.ty.isPtr()) {
try p.errStr(.implicit_ptr_to_int, tok, try p.typePairStrExtra(item.ty, " to ", target));
try item.intCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
}
} else if (unqual_ty.isFloat()) {
if (item.ty.isInt() or item.ty.isFloat()) {
try item.floatCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
}
} else if (unqual_ty.isPtr()) {
if (item.isZero()) {
try item.nullCast(p, target);
} else if (item.ty.isInt()) {
try p.errStr(.implicit_int_to_ptr, tok, try p.typePairStrExtra(item.ty, " to ", target));
try item.ptrCast(p, unqual_ty);
} else if (item.ty.isPtr()) {
if (!unqual_ty.eql(item.ty, false)) {
try p.errStr(.incompatible_ptr_assign, tok, try p.typePairStrExtra(target, e_msg, item.ty));
try item.ptrCast(p, unqual_ty);
}
} else {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
}
} else if (unqual_ty.isRecord()) {
if (!unqual_ty.eql(item.ty, false))
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
} else if (unqual_ty.isFunc()) {
// we have already issued an error for this
} else {
try p.errStr(.incompatible_init, tok, try p.typePairStrExtra(target, e_msg, item.ty));
}
}
fn isStringInit(p: *Parser) bool {
var i = p.tok_i;
while (true) : (i += 1) {
switch (p.tok_ids[i]) {
.l_paren => {},
.string_literal,
.string_literal_utf_16,
.string_literal_utf_8,
.string_literal_utf_32,
.string_literal_wide,
=> return true,
else => return false,
}
}
}
// ====== statements ======
/// stmt
/// : labeledStmt
/// | compoundStmt
/// | keyword_if '(' expr ')' stmt (keyword_else stmt)?
/// | keyword_switch '(' expr ')' stmt
/// | keyword_while '(' expr ')' stmt
/// | keyword_do stmt while '(' expr ')' ';'
/// | keyword_for '(' (decl | expr? ';') expr? ';' expr? ')' stmt
/// | keyword_goto IDENTIFIER ';'
/// | keyword_continue ';'
/// | keyword_break ';'
/// | keyword_return expr? ';'
/// | expr? ';'
fn stmt(p: *Parser) Error!NodeIndex {
if (try p.labeledStmt()) |some| return some;
if (try p.compoundStmt(false)) |some| return some;
if (p.eatToken(.keyword_if)) |_| {
const start_scopes_len = p.scopes.items.len;
defer p.scopes.items.len = start_scopes_len;
const l_paren = try p.expectToken(.l_paren);
var cond = try p.expr();
try cond.expect(p);
try cond.lvalConversion(p);
if (cond.ty.isInt())
try cond.intCast(p, cond.ty.integerPromotion(p.pp.comp))
else if (!cond.ty.isFloat() and !cond.ty.isPtr())
try p.errStr(.statement_scalar, l_paren + 1, try p.typeStr(cond.ty));
try cond.saveValue(p);
try p.expectClosing(l_paren, .r_paren);
const then = try p.stmt();
const @"else" = if (p.eatToken(.keyword_else)) |_| try p.stmt() else .none;
if (then != .none and @"else" != .none)
return try p.addNode(.{
.tag = .if_then_else_stmt,
.data = .{ .if3 = .{ .cond = cond.node, .body = (try p.addList(&.{ then, @"else" })).start } },
})
else if (then == .none and @"else" != .none)
return try p.addNode(.{
.tag = .if_else_stmt,
.data = .{ .bin = .{ .lhs = cond.node, .rhs = @"else" } },
})
else
return try p.addNode(.{
.tag = .if_then_stmt,
.data = .{ .bin = .{ .lhs = cond.node, .rhs = then } },
});
}
if (p.eatToken(.keyword_switch)) |_| {
const start_scopes_len = p.scopes.items.len;
defer p.scopes.items.len = start_scopes_len;
const l_paren = try p.expectToken(.l_paren);
var cond = try p.expr();
try cond.expect(p);
try cond.lvalConversion(p);
if (cond.ty.isInt())
try cond.intCast(p, cond.ty.integerPromotion(p.pp.comp))
else
try p.errStr(.statement_int, l_paren + 1, try p.typeStr(cond.ty));
try cond.saveValue(p);
try p.expectClosing(l_paren, .r_paren);
var switch_scope = Scope.Switch{
.cases = Scope.Switch.CaseMap.init(p.pp.comp.gpa),
};
defer switch_scope.cases.deinit();
try p.scopes.append(.{ .@"switch" = &switch_scope });
const body = try p.stmt();
return try p.addNode(.{
.tag = .switch_stmt,
.data = .{ .bin = .{ .rhs = cond.node, .lhs = body } },
});
}
if (p.eatToken(.keyword_while)) |_| {
const start_scopes_len = p.scopes.items.len;
defer p.scopes.items.len = start_scopes_len;
const l_paren = try p.expectToken(.l_paren);
var cond = try p.expr();
try cond.expect(p);
try cond.lvalConversion(p);
if (cond.ty.isInt())
try cond.intCast(p, cond.ty.integerPromotion(p.pp.comp))
else if (!cond.ty.isFloat() and !cond.ty.isPtr())
try p.errStr(.statement_scalar, l_paren + 1, try p.typeStr(cond.ty));
try cond.saveValue(p);
try p.expectClosing(l_paren, .r_paren);
try p.scopes.append(.loop);
const body = try p.stmt();
return try p.addNode(.{
.tag = .while_stmt,
.data = .{ .bin = .{ .rhs = cond.node, .lhs = body } },
});
}
if (p.eatToken(.keyword_do)) |_| {
const start_scopes_len = p.scopes.items.len;
defer p.scopes.items.len = start_scopes_len;
try p.scopes.append(.loop);
const body = try p.stmt();
p.scopes.items.len = start_scopes_len;
_ = try p.expectToken(.keyword_while);
const l_paren = try p.expectToken(.l_paren);
var cond = try p.expr();
try cond.expect(p);
try cond.lvalConversion(p);
if (cond.ty.isInt())
try cond.intCast(p, cond.ty.integerPromotion(p.pp.comp))
else if (!cond.ty.isFloat() and !cond.ty.isPtr())
try p.errStr(.statement_scalar, l_paren + 1, try p.typeStr(cond.ty));
try cond.saveValue(p);
try p.expectClosing(l_paren, .r_paren);
_ = try p.expectToken(.semicolon);
return try p.addNode(.{
.tag = .do_while_stmt,
.data = .{ .bin = .{ .rhs = cond.node, .lhs = body } },
});
}
if (p.eatToken(.keyword_for)) |_| {
const start_scopes_len = p.scopes.items.len;
defer p.scopes.items.len = start_scopes_len;
const decl_buf_top = p.decl_buf.items.len;
defer p.decl_buf.items.len = decl_buf_top;
const l_paren = try p.expectToken(.l_paren);
const got_decl = try p.decl();
// for (init
const init_start = p.tok_i;
var err_start = p.pp.comp.diag.list.items.len;
var init = if (!got_decl) try p.expr() else Result{};
try init.saveValue(p);
try init.maybeWarnUnused(p, init_start, err_start);
if (!got_decl) _ = try p.expectToken(.semicolon);
// for (init; cond
var cond = try p.expr();
if (cond.node != .none) {
try cond.lvalConversion(p);
if (cond.ty.isInt())
try cond.intCast(p, cond.ty.integerPromotion(p.pp.comp))
else if (!cond.ty.isFloat() and !cond.ty.isPtr())
try p.errStr(.statement_scalar, l_paren + 1, try p.typeStr(cond.ty));
}
try cond.saveValue(p);
_ = try p.expectToken(.semicolon);
// for (init; cond; incr
const incr_start = p.tok_i;
err_start = p.pp.comp.diag.list.items.len;
var incr = try p.expr();
try incr.maybeWarnUnused(p, incr_start, err_start);
try incr.saveValue(p);
try p.expectClosing(l_paren, .r_paren);
try p.scopes.append(.loop);
const body = try p.stmt();
if (got_decl) {
const start = (try p.addList(p.decl_buf.items[decl_buf_top..])).start;
const end = (try p.addList(&.{ cond.node, incr.node, body })).end;
return try p.addNode(.{
.tag = .for_decl_stmt,
.data = .{ .range = .{ .start = start, .end = end } },
});
} else if (init.node == .none and cond.node == .none and incr.node == .none) {
return try p.addNode(.{
.tag = .forever_stmt,
.data = .{ .un = body },
});
} else return try p.addNode(.{ .tag = .for_stmt, .data = .{ .if3 = .{
.cond = body,
.body = (try p.addList(&.{ init.node, cond.node, incr.node })).start,
} } });
}
if (p.eatToken(.keyword_goto)) |_| {
const name_tok = try p.expectToken(.identifier);
const str = p.tokSlice(name_tok);
if (p.findLabel(str) == null) {
try p.labels.append(.{ .unresolved_goto = name_tok });
}
_ = try p.expectToken(.semicolon);
return try p.addNode(.{
.tag = .goto_stmt,
.data = .{ .decl_ref = name_tok },
});
}
if (p.eatToken(.keyword_continue)) |cont| {
if (!p.inLoop()) try p.errTok(.continue_not_in_loop, cont);
_ = try p.expectToken(.semicolon);
return try p.addNode(.{ .tag = .continue_stmt, .data = undefined });
}
if (p.eatToken(.keyword_break)) |br| {
if (!p.inLoopOrSwitch()) try p.errTok(.break_not_in_loop_or_switch, br);
_ = try p.expectToken(.semicolon);
return try p.addNode(.{ .tag = .break_stmt, .data = undefined });
}
if (try p.returnStmt()) |some| return some;
const expr_start = p.tok_i;
const err_start = p.pp.comp.diag.list.items.len;
const e = try p.expr();
if (e.node != .none) {
_ = try p.expectToken(.semicolon);
try e.maybeWarnUnused(p, expr_start, err_start);
return e.node;
}
if (p.eatToken(.semicolon)) |_| return .none;
try p.err(.expected_stmt);
return error.ParsingFailed;
}
/// labeledStmt
/// : IDENTIFIER ':' stmt
/// | keyword_case constExpr ':' stmt
/// | keyword_default ':' stmt
fn labeledStmt(p: *Parser) Error!?NodeIndex {
if (p.tok_ids[p.tok_i] == .identifier and p.tok_ids[p.tok_i + 1] == .colon) {
const name_tok = p.tok_i;
const str = p.tokSlice(name_tok);
if (p.findLabel(str)) |some| {
try p.errStr(.duplicate_label, name_tok, str);
try p.errStr(.previous_label, some, str);
} else {
p.label_count += 1;
try p.labels.append(.{ .label = name_tok });
var i: usize = 0;
while (i < p.labels.items.len) : (i += 1) {
if (p.labels.items[i] == .unresolved_goto and
mem.eql(u8, p.tokSlice(p.labels.items[i].unresolved_goto), str))
{
_ = p.labels.swapRemove(i);
}
}
}
p.tok_i += 2;
return try p.addNode(.{
.tag = .labeled_stmt,
.data = .{ .decl = .{ .name = name_tok, .node = try p.stmt() } },
});
} else if (p.eatToken(.keyword_case)) |case| {
const val = try p.constExpr();
_ = try p.expectToken(.colon);
const s = try p.stmt();
const node = try p.addNode(.{
.tag = .case_stmt,
.data = .{ .bin = .{ .lhs = val.node, .rhs = s } },
});
if (p.findSwitch()) |some| {
const gop = try some.cases.getOrPut(val);
if (gop.found_existing) {
switch (val.val) {
.unsigned => |v| try p.errExtra(.duplicate_switch_case_unsigned, case, .{ .unsigned = v }),
.signed => |v| try p.errExtra(.duplicate_switch_case_signed, case, .{ .signed = v }),
else => unreachable,
}
try p.errTok(.previous_case, gop.value_ptr.tok);
} else {
gop.value_ptr.* = .{
.tok = case,
.node = node,
};
}
} else {
try p.errStr(.case_not_in_switch, case, "case");
}
return node;
} else if (p.eatToken(.keyword_default)) |default| {
_ = try p.expectToken(.colon);
const s = try p.stmt();
const node = try p.addNode(.{
.tag = .default_stmt,
.data = .{ .un = s },
});
if (p.findSwitch()) |some| {
if (some.default) |previous| {
try p.errTok(.multiple_default, default);
try p.errTok(.previous_case, previous.tok);
} else {
some.default = .{
.tok = default,
.node = node,
};
}
} else {
try p.errStr(.case_not_in_switch, default, "default");
}
return node;
} else return null;
}
/// compoundStmt : '{' ( decl| staticAssert | stmt)* '}'
fn compoundStmt(p: *Parser, is_fn_body: bool) Error!?NodeIndex {
const l_brace = p.eatToken(.l_brace) orelse return null;
const decl_buf_top = p.decl_buf.items.len;
defer p.decl_buf.items.len = decl_buf_top;
const scopes_top = p.scopes.items.len;
defer p.scopes.items.len = scopes_top;
// the parameters of a function are in the same scope as the body
if (!is_fn_body) try p.scopes.append(.block);
var noreturn_index: ?TokenIndex = null;
var noreturn_label_count: u32 = 0;
while (p.eatToken(.r_brace) == null) {
if (p.staticAssert() catch |er| switch (er) {
error.ParsingFailed => {
try p.nextStmt(l_brace);
continue;
},
else => |e| return e,
}) continue;
if (p.decl() catch |er| switch (er) {
error.ParsingFailed => {
try p.nextStmt(l_brace);
continue;
},
else => |e| return e,
}) continue;
const s = p.stmt() catch |er| switch (er) {
error.ParsingFailed => {
try p.nextStmt(l_brace);
continue;
},
else => |e| return e,
};
if (s == .none) continue;
try p.decl_buf.append(s);
if (noreturn_index == null and p.nodeIsNoreturn(s)) {
noreturn_index = p.tok_i;
noreturn_label_count = p.label_count;
}
}
if (noreturn_index) |some| {
// if new labels were defined we cannot be certain that the code is unreachable
if (some != p.tok_i - 1 and noreturn_label_count == p.label_count) try p.errTok(.unreachable_code, some);
}
if (is_fn_body and (p.decl_buf.items.len == decl_buf_top or
p.nodes.items(.tag)[@enumToInt(p.decl_buf.items[p.decl_buf.items.len - 1])] != .return_stmt))
{
if (p.return_type.?.specifier != .void) try p.errStr(.func_does_not_return, p.tok_i - 1, p.tokSlice(p.func_name));
try p.decl_buf.append(try p.addNode(.{ .tag = .implicit_return, .ty = p.return_type.?, .data = undefined }));
}
var node: Tree.Node = .{
.tag = .compound_stmt_two,
.data = .{ .bin = .{ .lhs = .none, .rhs = .none } },
};
const statements = p.decl_buf.items[decl_buf_top..];
switch (statements.len) {
0 => {},
1 => node.data = .{ .bin = .{ .lhs = statements[0], .rhs = .none } },
2 => node.data = .{ .bin = .{ .lhs = statements[0], .rhs = statements[1] } },
else => {
node.tag = .compound_stmt;
node.data = .{ .range = try p.addList(statements) };
},
}
return try p.addNode(node);
}
fn nodeIsNoreturn(p: *Parser, node: NodeIndex) bool {
switch (p.nodes.items(.tag)[@enumToInt(node)]) {
.break_stmt, .continue_stmt, .return_stmt => return true,
.if_then_else_stmt => {
const data = p.data.items[p.nodes.items(.data)[@enumToInt(node)].if3.body..];
return p.nodeIsNoreturn(data[0]) and p.nodeIsNoreturn(data[1]);
},
else => return false,
}
}
fn nextStmt(p: *Parser, l_brace: TokenIndex) !void {
var parens: u32 = 0;
while (p.tok_i < p.tok_ids.len) : (p.tok_i += 1) {
switch (p.tok_ids[p.tok_i]) {
.l_paren, .l_brace, .l_bracket => parens += 1,
.r_paren, .r_bracket => if (parens != 0) {
parens -= 1;
},
.r_brace => if (parens == 0)
return
else {
parens -= 1;
},
.semicolon,
.keyword_for,
.keyword_while,
.keyword_do,
.keyword_if,
.keyword_goto,
.keyword_switch,
.keyword_case,
.keyword_default,
.keyword_continue,
.keyword_break,
.keyword_return,
.keyword_typedef,
.keyword_extern,
.keyword_static,
.keyword_auto,
.keyword_register,
.keyword_thread_local,
.keyword_inline,
.keyword_noreturn,
.keyword_void,
.keyword_bool,
.keyword_char,
.keyword_short,
.keyword_int,
.keyword_long,
.keyword_signed,
.keyword_unsigned,
.keyword_float,
.keyword_double,
.keyword_complex,
.keyword_atomic,
.keyword_enum,
.keyword_struct,
.keyword_union,
.keyword_alignas,
.keyword_typeof,
.keyword_typeof1,
.keyword_typeof2,
=> if (parens == 0) return,
else => {},
}
}
p.tok_i -= 1; // So we can consume EOF
try p.expectClosing(l_brace, .r_brace);
unreachable;
}
fn returnStmt(p: *Parser) Error!?NodeIndex {
const ret_tok = p.eatToken(.keyword_return) orelse return null;
const e_tok = p.tok_i;
var e = try p.expr();
_ = try p.expectToken(.semicolon);
const ret_ty = p.return_type.?;
if (e.node == .none) {
if (ret_ty.specifier != .void) try p.errStr(.func_should_return, ret_tok, p.tokSlice(p.func_name));
return try p.addNode(.{ .tag = .return_stmt, .data = .{ .un = e.node } });
}
try e.lvalConversion(p);
// Return type conversion is done as if it was assignment
if (ret_ty.specifier == .bool) {
// this is ridiculous but it's what clang does
if (e.ty.isInt() or e.ty.isFloat() or e.ty.isPtr()) {
try e.boolCast(p, ret_ty);
} else {
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
} else if (ret_ty.isInt()) {
if (e.ty.isInt() or e.ty.isFloat()) {
try e.intCast(p, ret_ty);
} else if (e.ty.isPtr()) {
try p.errStr(.implicit_ptr_to_int, e_tok, try p.typePairStrExtra(e.ty, " to ", ret_ty));
try e.intCast(p, ret_ty);
} else {
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
} else if (ret_ty.isFloat()) {
if (e.ty.isInt() or e.ty.isFloat()) {
try e.floatCast(p, ret_ty);
} else {
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
} else if (ret_ty.isPtr()) {
if (e.ty.isInt()) {
try p.errStr(.implicit_int_to_ptr, e_tok, try p.typePairStrExtra(e.ty, " to ", ret_ty));
try e.intCast(p, ret_ty);
} else if (!ret_ty.eql(e.ty, false)) {
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
} else if (ret_ty.isRecord()) {
if (!ret_ty.eql(e.ty, false)) {
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
} else {
// should be unreachable
try p.errStr(.incompatible_return, e_tok, try p.typeStr(e.ty));
}
try e.saveValue(p);
return try p.addNode(.{ .tag = .return_stmt, .data = .{ .un = e.node } });
}
// ====== expressions ======
pub fn macroExpr(p: *Parser) Compilation.Error!bool {
const res = p.condExpr() catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.FatalError => return error.FatalError,
error.ParsingFailed => return false,
};
if (res.val == .unavailable) {
try p.errTok(.expected_expr, p.tok_i);
return false;
}
return res.getBool();
}
const Result = struct {
node: NodeIndex = .none,
ty: Type = .{ .specifier = .int },
val: union(enum) {
unsigned: u64,
signed: i64,
unavailable,
} = .unavailable,
pub fn getBool(res: Result) bool {
return switch (res.val) {
.signed => |v| v != 0,
.unsigned => |v| v != 0,
.unavailable => unreachable,
};
}
fn as_u64(res: Result) u64 {
return switch (res.val) {
.signed => |v| @bitCast(u64, v),
.unsigned => |v| v,
.unavailable => unreachable,
};
}
fn isZero(res: Result) bool {
return switch (res.val) {
.signed => |v| v == 0,
.unsigned => |v| v == 0,
.unavailable => false,
};
}
fn expect(res: Result, p: *Parser) Error!void {
if (p.in_macro) {
if (res.val == .unavailable) {
try p.errTok(.expected_expr, p.tok_i);
return error.ParsingFailed;
}
return;
}
if (res.node == .none) {
try p.errTok(.expected_expr, p.tok_i);
return error.ParsingFailed;
}
}
fn empty(res: Result, p: *Parser) bool {
if (p.in_macro) return res.val == .unavailable;
return res.node == .none;
}
fn maybeWarnUnused(res: Result, p: *Parser, expr_start: TokenIndex, err_start: usize) Error!void {
if (res.ty.specifier == .void or res.node == .none) return;
// don't warn about unused result if the expression contained errors
if (p.pp.comp.diag.list.items.len > err_start) return;
switch (p.nodes.items(.tag)[@enumToInt(res.node)]) {
.invalid, // So that we don't need to check for node == 0
.assign_expr,
.mul_assign_expr,
.div_assign_expr,
.mod_assign_expr,
.add_assign_expr,
.sub_assign_expr,
.shl_assign_expr,
.shr_assign_expr,
.bit_and_assign_expr,
.bit_xor_assign_expr,
.bit_or_assign_expr,
.call_expr,
.call_expr_one,
.pre_inc_expr,
.pre_dec_expr,
.post_inc_expr,
.post_dec_expr,
=> return,
else => {},
}
try p.errTok(.unused_value, expr_start);
}
fn bin(lhs: *Result, p: *Parser, tag: Tree.Tag, rhs: Result) !void {
lhs.node = try p.addNode(.{
.tag = tag,
.ty = lhs.ty,
.data = .{ .bin = .{ .lhs = lhs.node, .rhs = rhs.node } },
});
}
fn un(operand: *Result, p: *Parser, tag: Tree.Tag) Error!void {
operand.node = try p.addNode(.{
.tag = tag,
.ty = operand.ty,
.data = .{ .un = operand.node },
});
}
fn qualCast(res: *Result, p: *Parser, elem_ty: *Type) Error!void {
res.ty = .{
.data = .{ .sub_type = elem_ty },
.specifier = .pointer,
};
try res.un(p, .qual_cast);
}
fn adjustCondExprPtrs(a: *Result, tok: TokenIndex, b: *Result, p: *Parser) !bool {
assert(a.ty.isPtr() and b.ty.isPtr());
const a_elem = a.ty.elemType();
const b_elem = b.ty.elemType();
if (a_elem.eql(b_elem, true)) return true;
var adjusted_elem_ty = try p.arena.create(Type);
adjusted_elem_ty.* = a_elem;
const has_void_star_branch = a.ty.isVoidStar() or b.ty.isVoidStar();
const only_quals_differ = a_elem.eql(b_elem, false);
const pointers_compatible = only_quals_differ or has_void_star_branch;
if (!pointers_compatible or has_void_star_branch) {
if (!pointers_compatible) {
try p.errStr(.pointer_mismatch, tok, try p.typePairStrExtra(a.ty, " and ", b.ty));
}
adjusted_elem_ty.* = .{ .specifier = .void };
}
if (pointers_compatible) {
adjusted_elem_ty.qual = a_elem.qual.mergeCV(b_elem.qual);
}
if (!adjusted_elem_ty.eql(a_elem, true)) try a.qualCast(p, adjusted_elem_ty);
if (!adjusted_elem_ty.eql(b_elem, true)) try b.qualCast(p, adjusted_elem_ty);
return true;
}
/// Adjust types for binary operation, returns true if the result can and should be evaluated.
fn adjustTypes(a: *Result, tok: TokenIndex, b: *Result, p: *Parser, kind: enum {
integer,
arithmetic,
boolean_logic,
relational,
equality,
conditional,
add,
sub,
}) !bool {
try a.lvalConversion(p);
try b.lvalConversion(p);
const a_int = a.ty.isInt();
const b_int = b.ty.isInt();
if (a_int and b_int) {
try a.usualArithmeticConversion(b, p);
return a.shouldEval(b, p);
}
if (kind == .integer) return a.invalidBinTy(tok, b, p);
const a_float = a.ty.isFloat();
const b_float = b.ty.isFloat();
const a_arithmetic = a_int or a_float;
const b_arithmetic = b_int or b_float;
if (a_arithmetic and b_arithmetic) {
// <, <=, >, >= only work on real types
if (kind == .relational and (!a.ty.isReal() or !b.ty.isReal()))
return a.invalidBinTy(tok, b, p);
try a.usualArithmeticConversion(b, p);
return a.shouldEval(b, p);
}
if (kind == .arithmetic) return a.invalidBinTy(tok, b, p);
const a_ptr = a.ty.isPtr();
const b_ptr = b.ty.isPtr();
const a_scalar = a_arithmetic or a_ptr;
const b_scalar = b_arithmetic or b_ptr;
switch (kind) {
.boolean_logic => {
if (!a_scalar or !b_scalar) return a.invalidBinTy(tok, b, p);
// Do integer promotions but nothing else
if (a_int) try a.intCast(p, a.ty.integerPromotion(p.pp.comp));
if (b_int) try b.intCast(p, b.ty.integerPromotion(p.pp.comp));
return a.shouldEval(b, p);
},
.relational, .equality => {
// comparisons between floats and pointes not allowed
if (!a_scalar or !b_scalar or (a_float and b_ptr) or (b_float and a_ptr))
return a.invalidBinTy(tok, b, p);
if (a_int or b_int) try p.errStr(.comparison_ptr_int, tok, try p.typePairStr(a.ty, b.ty));
if (a_ptr and b_ptr) {
if (!a.ty.eql(b.ty, false)) try p.errStr(.comparison_distinct_ptr, tok, try p.typePairStr(a.ty, b.ty));
} else if (a_ptr) {
try b.ptrCast(p, a.ty);
} else {
assert(b_ptr);
try a.ptrCast(p, b.ty);
}
return a.shouldEval(b, p);
},
.conditional => {
// doesn't matter what we return here, as the result is ignored
if (a.ty.specifier == .void or b.ty.specifier == .void) {
try a.toVoid(p);
try b.toVoid(p);
return true;
}
if ((a_ptr and b_int) or (a_int and b_ptr)) {
if (a.isZero() or b.isZero()) {
try a.nullCast(p, b.ty);
try b.nullCast(p, a.ty);
return true;
}
const int_ty = if (a_int) a else b;
const ptr_ty = if (a_ptr) a else b;
try p.errStr(.implicit_int_to_ptr, tok, try p.typePairStrExtra(int_ty.ty, " to ", ptr_ty.ty));
try int_ty.ptrCast(p, ptr_ty.ty);
return true;
}
if (a_ptr and b_ptr) return a.adjustCondExprPtrs(tok, b, p);
// TODO struct/record
return a.invalidBinTy(tok, b, p);
},
.add => {
// if both aren't arithmetic one should be pointer and the other an integer
if (a_ptr == b_ptr or a_int == b_int) return a.invalidBinTy(tok, b, p);
// Do integer promotions but nothing else
if (a_int) try a.intCast(p, a.ty.integerPromotion(p.pp.comp));
if (b_int) try b.intCast(p, b.ty.integerPromotion(p.pp.comp));
return a.shouldEval(b, p);
},
.sub => {
// if both aren't arithmetic then either both should be pointers or just a
if (!a_ptr or !(b_ptr or b_int)) return a.invalidBinTy(tok, b, p);
if (a_ptr and b_ptr) {
if (!a.ty.eql(b.ty, false)) try p.errStr(.incompatible_pointers, tok, try p.typePairStr(a.ty, b.ty));
a.ty = Type.ptrDiffT(p.pp.comp);
}
// Do integer promotion on b if needed
if (b_int) try b.intCast(p, b.ty.integerPromotion(p.pp.comp));
return a.shouldEval(b, p);
},
else => return a.invalidBinTy(tok, b, p),
}
}
fn lvalConversion(res: *Result, p: *Parser) Error!void {
if (res.ty.isFunc()) {
var elem_ty = try p.arena.create(Type);
elem_ty.* = res.ty;
res.ty.specifier = .pointer;
res.ty.data = .{ .sub_type = elem_ty };
res.ty.alignment = 0;
try res.un(p, .function_to_pointer);
} else if (res.ty.isArray()) {
res.ty.decayArray();
res.ty.alignment = 0;
try res.un(p, .array_to_pointer);
} else if (!p.in_macro and Tree.isLval(p.nodes.slice(), res.node)) {
res.ty.qual = .{};
res.ty.alignment = 0;
try res.un(p, .lval_to_rval);
}
}
fn boolCast(res: *Result, p: *Parser, bool_ty: Type) Error!void {
if (res.ty.isPtr()) {
res.ty = bool_ty;
try res.un(p, .pointer_to_bool);
} else if (res.ty.isInt() and res.ty.specifier != .bool) {
res.ty = bool_ty;
try res.un(p, .int_to_bool);
} else if (res.ty.isFloat()) {
res.ty = bool_ty;
try res.un(p, .float_to_bool);
}
}
fn intCast(res: *Result, p: *Parser, int_ty: Type) Error!void {
if (res.ty.specifier == .bool) {
res.ty = int_ty;
try res.un(p, .bool_to_int);
} else if (res.ty.isPtr()) {
res.ty = int_ty;
try res.un(p, .pointer_to_int);
} else if (res.ty.isFloat()) {
res.ty = int_ty;
try res.un(p, .float_to_int);
} else if (!res.ty.eql(int_ty, true)) {
res.ty = int_ty;
try res.un(p, .int_cast);
const is_unsigned = int_ty.isUnsignedInt(p.pp.comp);
if (is_unsigned and res.val == .signed) {
const copy = res.val.signed;
res.val = .{ .unsigned = @bitCast(u64, copy) };
} else if (!is_unsigned and res.val == .unsigned) {
const copy = res.val.unsigned;
res.val = .{ .signed = @bitCast(i64, copy) };
}
}
}
fn floatCast(res: *Result, p: *Parser, float_ty: Type) Error!void {
if (res.ty.specifier == .bool) {
res.ty = float_ty;
try res.un(p, .bool_to_float);
} else if (res.ty.isInt()) {
res.ty = float_ty;
try res.un(p, .int_to_float);
} else if (!res.ty.eql(float_ty, true)) {
res.ty = float_ty;
try res.un(p, .float_cast);
}
}
fn ptrCast(res: *Result, p: *Parser, ptr_ty: Type) Error!void {
if (res.ty.specifier == .bool) {
res.ty = ptr_ty;
try res.un(p, .bool_to_pointer);
} else if (res.ty.isInt()) {
res.ty = ptr_ty;
try res.un(p, .int_to_pointer);
}
}
fn toVoid(res: *Result, p: *Parser) Error!void {
if (res.ty.specifier != .void) {
res.ty = .{ .specifier = .void };
res.node = try p.addNode(.{
.tag = .to_void,
.ty = res.ty,
.data = .{ .un = res.node },
});
}
}
fn nullCast(res: *Result, p: *Parser, ptr_ty: Type) Error!void {
if (!res.isZero()) return;
res.ty = ptr_ty;
try res.un(p, .null_to_pointer);
}
fn usualArithmeticConversion(a: *Result, b: *Result, p: *Parser) Error!void {
// if either is a float cast to that type
if (Type.eitherLongDouble(a.ty, b.ty)) |ty| {
try a.floatCast(p, ty);
try b.floatCast(p, ty);
return;
}
if (Type.eitherDouble(a.ty, b.ty)) |ty| {
try a.floatCast(p, ty);
try b.floatCast(p, ty);
return;
}
if (Type.eitherFloat(a.ty, b.ty)) |ty| {
try a.floatCast(p, ty);
try b.floatCast(p, ty);
return;
}
// Do integer promotion on both operands
const a_promoted = a.ty.integerPromotion(p.pp.comp);
const b_promoted = b.ty.integerPromotion(p.pp.comp);
if (a_promoted.eql(b_promoted, true)) {
// cast to promoted type
try a.intCast(p, a_promoted);
try b.intCast(p, a_promoted);
return;
}
const a_unsigned = a_promoted.isUnsignedInt(p.pp.comp);
const b_unsigned = b_promoted.isUnsignedInt(p.pp.comp);
if (a_unsigned == b_unsigned) {
// cast to greater signed or unsigned type
const res_spec = std.math.max(@enumToInt(a_promoted.specifier), @enumToInt(b_promoted.specifier));
const res_ty = Type{ .specifier = @intToEnum(Type.Specifier, res_spec) };
try a.intCast(p, res_ty);
try b.intCast(p, res_ty);
return;
}
// cast to the unsigned type with greater rank
if (a_unsigned and (@enumToInt(a_promoted.specifier) >= @enumToInt(b_promoted.specifier))) {
try a.intCast(p, a_promoted);
try b.intCast(p, a_promoted);
return;
} else {
assert(b_unsigned and (@enumToInt(b_promoted.specifier) >= @enumToInt(a_promoted.specifier)));
try a.intCast(p, b_promoted);
try b.intCast(p, b_promoted);
}
}
fn invalidBinTy(a: *Result, tok: TokenIndex, b: *Result, p: *Parser) Error!bool {
try p.errStr(.invalid_bin_types, tok, try p.typePairStr(a.ty, b.ty));
return false;
}
fn shouldEval(a: *Result, b: *Result, p: *Parser) Error!bool {
if (p.no_eval) return false;
if (a.val != .unavailable and b.val != .unavailable)
return true;
try a.saveValue(p);
try b.saveValue(p);
return p.no_eval;
}
fn saveValue(res: *Result, p: *Parser) !void {
assert(!p.in_macro);
switch (res.val) {
.unsigned => |v| try p.value_map.put(res.node, v),
.signed => |v| try p.value_map.put(res.node, @bitCast(u64, v)),
.unavailable => return,
}
res.val = .unavailable;
}
fn hash(res: Result) u64 {
switch (res.val) {
.unsigned => |v| return std.hash.Wyhash.hash(0, mem.asBytes(&v)),
.signed => |v| return std.hash.Wyhash.hash(0, mem.asBytes(&v)),
.unavailable => unreachable,
}
}
fn eql(a: Result, b: Result) bool {
return a.compare(.eq, b);
}
fn compare(a: Result, op: std.math.CompareOperator, b: Result) bool {
switch (a.val) {
.unsigned => |val| return std.math.compare(val, op, b.val.unsigned),
.signed => |val| return std.math.compare(val, op, b.val.signed),
.unavailable => unreachable,
}
}
fn mul(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void {
const size = a.ty.sizeof(p.pp.comp).?;
var overflow = false;
switch (a.val) {
.unsigned => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: u32 = undefined;
overflow = @mulWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.val.unsigned), &res);
v.* = res;
},
8 => overflow = @mulWithOverflow(u64, v.*, b.val.unsigned, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* });
},
.signed => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: i32 = undefined;
overflow = @mulWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.val.signed), &res);
v.* = res;
},
8 => overflow = @mulWithOverflow(i64, v.*, b.val.signed, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* });
},
.unavailable => unreachable,
}
}
fn add(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void {
const size = a.ty.sizeof(p.pp.comp).?;
var overflow = false;
switch (a.val) {
.unsigned => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: u32 = undefined;
overflow = @addWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.val.unsigned), &res);
v.* = res;
},
8 => overflow = @addWithOverflow(u64, v.*, b.val.unsigned, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* });
},
.signed => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: i32 = undefined;
overflow = @addWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.val.signed), &res);
v.* = res;
},
8 => overflow = @addWithOverflow(i64, v.*, b.val.signed, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* });
},
.unavailable => unreachable,
}
}
fn sub(a: *Result, tok: TokenIndex, b: Result, p: *Parser) !void {
const size = a.ty.sizeof(p.pp.comp).?;
var overflow = false;
switch (a.val) {
.unsigned => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: u32 = undefined;
overflow = @subWithOverflow(u32, @truncate(u32, v.*), @truncate(u32, b.val.unsigned), &res);
v.* = res;
},
8 => overflow = @subWithOverflow(u64, v.*, b.val.unsigned, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_unsigned, tok, .{ .unsigned = v.* });
},
.signed => |*v| {
switch (size) {
1 => unreachable, // promoted to int
2 => unreachable, // promoted to int
4 => {
var res: i32 = undefined;
overflow = @subWithOverflow(i32, @truncate(i32, v.*), @truncate(i32, b.val.signed), &res);
v.* = res;
},
8 => overflow = @subWithOverflow(i64, v.*, b.val.signed, v),
else => unreachable,
}
if (overflow) try p.errExtra(.overflow_signed, tok, .{ .signed = v.* });
},
.unavailable => unreachable,
}
}
};
/// expr : assignExpr (',' assignExpr)*
fn expr(p: *Parser) Error!Result {
var expr_start = p.tok_i;
var err_start = p.pp.comp.diag.list.items.len;
var lhs = try p.assignExpr();
while (p.eatToken(.comma)) |_| {
try lhs.maybeWarnUnused(p, expr_start, err_start);
expr_start = p.tok_i;
err_start = p.pp.comp.diag.list.items.len;
const rhs = try p.assignExpr();
lhs.val = rhs.val;
lhs.ty = rhs.ty;
try lhs.bin(p, .comma_expr, rhs);
}
return lhs;
}
fn tokToTag(p: *Parser, tok: TokenIndex) Tree.Tag {
return switch (p.tok_ids[tok]) {
.equal => .assign_expr,
.asterisk_equal => .mul_assign_expr,
.slash_equal => .div_assign_expr,
.percent_equal => .mod_assign_expr,
.plus_equal => .add_assign_expr,
.minus_equal => .sub_assign_expr,
.angle_bracket_angle_bracket_left_equal => .shl_assign_expr,
.angle_bracket_angle_bracket_right_equal => .shr_assign_expr,
.ampersand_equal => .bit_and_assign_expr,
.caret_equal => .bit_xor_assign_expr,
.pipe_equal => .bit_or_assign_expr,
.equal_equal => .equal_expr,
.bang_equal => .not_equal_expr,
.angle_bracket_left => .less_than_expr,
.angle_bracket_left_equal => .less_than_equal_expr,
.angle_bracket_right => .greater_than_expr,
.angle_bracket_right_equal => .greater_than_equal_expr,
.angle_bracket_angle_bracket_left => .shl_expr,
.angle_bracket_angle_bracket_right => .shr_expr,
.plus => .add_expr,
.minus => .sub_expr,
.asterisk => .mul_expr,
.slash => .div_expr,
.percent => .mod_expr,
else => unreachable,
};
}
/// assignExpr
/// : condExpr
/// | unExpr ('=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=') assignExpr
fn assignExpr(p: *Parser) Error!Result {
var lhs = try p.condExpr();
if (lhs.empty(p)) return lhs;
const tok = p.tok_i;
const eq = p.eatToken(.equal);
const mul = eq orelse p.eatToken(.asterisk_equal);
const div = mul orelse p.eatToken(.slash_equal);
const mod = div orelse p.eatToken(.percent_equal);
const add = mod orelse p.eatToken(.plus_equal);
const sub = add orelse p.eatToken(.minus_equal);
const shl = sub orelse p.eatToken(.angle_bracket_angle_bracket_left_equal);
const shr = shl orelse p.eatToken(.angle_bracket_angle_bracket_right_equal);
const bit_and = shr orelse p.eatToken(.ampersand_equal);
const bit_xor = bit_and orelse p.eatToken(.caret_equal);
const bit_or = bit_xor orelse p.eatToken(.pipe_equal);
const tag = p.tokToTag(bit_or orelse return lhs);
var rhs = try p.assignExpr();
try rhs.expect(p);
try rhs.lvalConversion(p);
if (!Tree.isLval(p.nodes.slice(), lhs.node) or lhs.ty.qual.@"const") {
try p.errTok(.not_assignable, tok);
return error.ParsingFailed;
}
// adjustTypes will do do lvalue conversion but we do not want that
var lhs_copy = lhs;
switch (tag) {
.assign_expr => {}, // handle plain assignment separately
.mul_assign_expr,
.div_assign_expr,
.mod_assign_expr,
=> {
if (rhs.isZero()) {
switch (tag) {
.div_assign_expr => try p.errStr(.division_by_zero, div.?, "division"),
.mod_assign_expr => try p.errStr(.division_by_zero, mod.?, "remainder"),
else => {},
}
}
_ = try lhs_copy.adjustTypes(tok, &rhs, p, .arithmetic);
try lhs.bin(p, tag, rhs);
return lhs;
},
.sub_assign_expr,
.add_assign_expr,
=> {
if (lhs.ty.isPtr() and rhs.ty.isInt()) {
try rhs.ptrCast(p, lhs.ty);
} else {
_ = try lhs_copy.adjustTypes(tok, &rhs, p, .arithmetic);
}
try lhs.bin(p, tag, rhs);
return lhs;
},
.shl_assign_expr,
.shr_assign_expr,
.bit_and_assign_expr,
.bit_xor_assign_expr,
.bit_or_assign_expr,
=> {
_ = try lhs_copy.adjustTypes(tok, &rhs, p, .integer);
try lhs.bin(p, tag, rhs);
return lhs;
},
else => unreachable,
}
// rhs does not need to be qualified
var unqual_ty = lhs.ty;
unqual_ty.qual = .{};
const e_msg = " from incompatible type ";
if (lhs.ty.specifier == .bool) {
// this is ridiculous but it's what clang does
if (rhs.ty.isInt() or rhs.ty.isFloat() or rhs.ty.isPtr()) {
try rhs.boolCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
}
} else if (unqual_ty.isInt()) {
if (rhs.ty.isInt() or rhs.ty.isFloat()) {
try rhs.intCast(p, unqual_ty);
} else if (rhs.ty.isPtr()) {
try p.errStr(.implicit_ptr_to_int, tok, try p.typePairStrExtra(rhs.ty, " to ", lhs.ty));
try rhs.intCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
}
} else if (unqual_ty.isFloat()) {
if (rhs.ty.isInt() or rhs.ty.isFloat()) {
try rhs.floatCast(p, unqual_ty);
} else {
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
}
} else if (unqual_ty.isPtr()) {
if (rhs.isZero()) {
try rhs.nullCast(p, lhs.ty);
} else if (rhs.ty.isInt()) {
try p.errStr(.implicit_int_to_ptr, tok, try p.typePairStrExtra(rhs.ty, " to ", lhs.ty));
try rhs.ptrCast(p, unqual_ty);
} else if (rhs.ty.isPtr()) {
if (!unqual_ty.eql(rhs.ty, false)) {
try p.errStr(.incompatible_ptr_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
try rhs.ptrCast(p, unqual_ty);
}
} else {
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
}
} else if (unqual_ty.isRecord()) {
if (!unqual_ty.eql(rhs.ty, false))
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
} else if (unqual_ty.isArray() or unqual_ty.isFunc()) {
try p.errTok(.not_assignable, tok);
} else {
try p.errStr(.incompatible_assign, tok, try p.typePairStrExtra(lhs.ty, e_msg, rhs.ty));
}
try lhs.bin(p, tag, rhs);
return lhs;
}
/// constExpr : condExpr
fn constExpr(p: *Parser) Error!Result {
const start = p.tok_i;
const res = try p.condExpr();
try res.expect(p);
if (!res.ty.isInt()) {
try p.errTok(.expected_integer_constant_expr, start);
return error.ParsingFailed;
}
// saveValue sets val to unavailable
var copy = res;
try copy.saveValue(p);
return res;
}
/// condExpr : lorExpr ('?' expression? ':' condExpr)?
fn condExpr(p: *Parser) Error!Result {
var cond = try p.lorExpr();
if (cond.empty(p) or p.eatToken(.question_mark) == null) return cond;
const saved_eval = p.no_eval;
// Depending on the value of the condition, avoid evaluating unreachable branches.
var then_expr = blk: {
defer p.no_eval = saved_eval;
if (cond.val != .unavailable and !cond.getBool()) p.no_eval = true;
break :blk try p.expr();
};
try then_expr.expect(p); // TODO binary cond expr
const colon = try p.expectToken(.colon);
var else_expr = blk: {
defer p.no_eval = saved_eval;
if (cond.val != .unavailable and cond.getBool()) p.no_eval = true;
break :blk try p.condExpr();
};
try else_expr.expect(p);
_ = try then_expr.adjustTypes(colon, &else_expr, p, .conditional);
if (cond.val != .unavailable) {
cond.val = if (cond.getBool()) then_expr.val else else_expr.val;
} else {
try then_expr.saveValue(p);
try else_expr.saveValue(p);
}
cond.ty = then_expr.ty;
cond.node = try p.addNode(.{
.tag = .cond_expr,
.ty = cond.ty,
.data = .{ .if3 = .{ .cond = cond.node, .body = (try p.addList(&.{ then_expr.node, else_expr.node })).start } },
});
return cond;
}
/// lorExpr : landExpr ('||' landExpr)*
fn lorExpr(p: *Parser) Error!Result {
var lhs = try p.landExpr();
if (lhs.empty(p)) return lhs;
const saved_eval = p.no_eval;
defer p.no_eval = saved_eval;
while (p.eatToken(.pipe_pipe)) |tok| {
if (lhs.val != .unavailable and lhs.getBool()) p.no_eval = true;
var rhs = try p.landExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(tok, &rhs, p, .boolean_logic)) {
const res = @boolToInt(lhs.getBool() or rhs.getBool());
lhs.val = .{ .signed = res };
}
lhs.ty = .{ .specifier = .int };
try lhs.bin(p, .bool_or_expr, rhs);
}
return lhs;
}
/// landExpr : orExpr ('&&' orExpr)*
fn landExpr(p: *Parser) Error!Result {
var lhs = try p.orExpr();
if (lhs.empty(p)) return lhs;
const saved_eval = p.no_eval;
defer p.no_eval = saved_eval;
while (p.eatToken(.ampersand_ampersand)) |tok| {
if (lhs.val != .unavailable and lhs.getBool()) p.no_eval = true;
var rhs = try p.orExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(tok, &rhs, p, .boolean_logic)) {
const res = @boolToInt(lhs.getBool() and rhs.getBool());
lhs.val = .{ .signed = res };
}
lhs.ty = .{ .specifier = .int };
try lhs.bin(p, .bool_and_expr, rhs);
}
return lhs;
}
/// orExpr : xorExpr ('|' xorExpr)*
fn orExpr(p: *Parser) Error!Result {
var lhs = try p.xorExpr();
if (lhs.empty(p)) return lhs;
while (p.eatToken(.pipe)) |tok| {
var rhs = try p.xorExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(tok, &rhs, p, .integer)) {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v | rhs.val.unsigned },
.signed => |v| .{ .signed = v | rhs.val.signed },
else => unreachable,
};
}
try lhs.bin(p, .bit_or_expr, rhs);
}
return lhs;
}
/// xorExpr : andExpr ('^' andExpr)*
fn xorExpr(p: *Parser) Error!Result {
var lhs = try p.andExpr();
if (lhs.empty(p)) return lhs;
while (p.eatToken(.caret)) |tok| {
var rhs = try p.andExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(tok, &rhs, p, .integer)) {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v ^ rhs.val.unsigned },
.signed => |v| .{ .signed = v ^ rhs.val.signed },
else => unreachable,
};
}
try lhs.bin(p, .bit_xor_expr, rhs);
}
return lhs;
}
/// andExpr : eqExpr ('&' eqExpr)*
fn andExpr(p: *Parser) Error!Result {
var lhs = try p.eqExpr();
if (lhs.empty(p)) return lhs;
while (p.eatToken(.ampersand)) |tok| {
var rhs = try p.eqExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(tok, &rhs, p, .integer)) {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v & rhs.val.unsigned },
.signed => |v| .{ .signed = v & rhs.val.signed },
else => unreachable,
};
}
try lhs.bin(p, .bit_and_expr, rhs);
}
return lhs;
}
/// eqExpr : compExpr (('==' | '!=') compExpr)*
fn eqExpr(p: *Parser) Error!Result {
var lhs = try p.compExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const eq = p.eatToken(.equal_equal);
const ne = eq orelse p.eatToken(.bang_equal);
const tag = p.tokToTag(ne orelse break);
var rhs = try p.compExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(ne.?, &rhs, p, .equality)) {
const res = if (tag == .equal_expr)
lhs.compare(.eq, rhs)
else
lhs.compare(.neq, rhs);
lhs.val = .{ .signed = @boolToInt(res) };
}
lhs.ty = .{ .specifier = .int };
try lhs.bin(p, tag, rhs);
}
return lhs;
}
/// compExpr : shiftExpr (('<' | '<=' | '>' | '>=') shiftExpr)*
fn compExpr(p: *Parser) Error!Result {
var lhs = try p.shiftExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const lt = p.eatToken(.angle_bracket_left);
const le = lt orelse p.eatToken(.angle_bracket_left_equal);
const gt = le orelse p.eatToken(.angle_bracket_right);
const ge = gt orelse p.eatToken(.angle_bracket_right_equal);
const tag = p.tokToTag(ge orelse break);
var rhs = try p.shiftExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(ge.?, &rhs, p, .relational)) {
const res = @boolToInt(switch (tag) {
.less_than_expr => lhs.compare(.lt, rhs),
.less_than_equal_expr => lhs.compare(.lte, rhs),
.greater_than_expr => lhs.compare(.gt, rhs),
.greater_than_equal_expr => lhs.compare(.gte, rhs),
else => unreachable,
});
lhs.val = .{ .signed = res };
}
lhs.ty = .{ .specifier = .int };
try lhs.bin(p, tag, rhs);
}
return lhs;
}
/// shiftExpr : addExpr (('<<' | '>>') addExpr)*
fn shiftExpr(p: *Parser) Error!Result {
var lhs = try p.addExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const shl = p.eatToken(.angle_bracket_angle_bracket_left);
const shr = shl orelse p.eatToken(.angle_bracket_angle_bracket_right);
const tag = p.tokToTag(shr orelse break);
var rhs = try p.addExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(shr.?, &rhs, p, .integer)) {
// TODO overflow
if (shl != null) {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v << @intCast(u6, rhs.val.unsigned) },
.signed => |v| .{ .signed = v << @intCast(u6, rhs.val.signed) },
else => unreachable,
};
} else {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v >> @intCast(u6, rhs.val.unsigned) },
.signed => |v| .{ .signed = v >> @intCast(u6, rhs.val.signed) },
else => unreachable,
};
}
}
try lhs.bin(p, tag, rhs);
}
return lhs;
}
/// addExpr : mulExpr (('+' | '-') mulExpr)*
fn addExpr(p: *Parser) Error!Result {
var lhs = try p.mulExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const plus = p.eatToken(.plus);
const minus = plus orelse p.eatToken(.minus);
const tag = p.tokToTag(minus orelse break);
var rhs = try p.mulExpr();
try rhs.expect(p);
if (try lhs.adjustTypes(minus.?, &rhs, p, if (plus != null) .add else .sub)) {
if (plus != null) {
try lhs.add(plus.?, rhs, p);
} else {
try lhs.sub(minus.?, rhs, p);
}
}
try lhs.bin(p, tag, rhs);
}
return lhs;
}
/// mulExpr : castExpr (('*' | '/' | '%') castExpr)*´
fn mulExpr(p: *Parser) Error!Result {
var lhs = try p.castExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const mul = p.eatToken(.asterisk);
const div = mul orelse p.eatToken(.slash);
const percent = div orelse p.eatToken(.percent);
const tag = p.tokToTag(percent orelse break);
var rhs = try p.castExpr();
try rhs.expect(p);
if (rhs.isZero() and mul == null and !p.no_eval) {
lhs.val = .unavailable;
if (div != null) {
try p.errStr(.division_by_zero, div.?, "division");
} else {
try p.errStr(.division_by_zero, percent.?, "remainder");
}
}
if (try lhs.adjustTypes(percent.?, &rhs, p, if (tag == .mod_expr) .integer else .arithmetic)) {
if (mul != null) {
try lhs.mul(mul.?, rhs, p);
} else if (div != null) {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v / rhs.val.unsigned },
.signed => |v| .{ .signed = @divFloor(v, rhs.val.signed) },
else => unreachable,
};
} else {
lhs.val = switch (lhs.val) {
.unsigned => |v| .{ .unsigned = v % rhs.val.unsigned },
.signed => |v| .{ .signed = @rem(v, rhs.val.signed) },
else => unreachable,
};
}
}
try lhs.bin(p, tag, rhs);
}
return lhs;
}
/// castExpr
/// : '(' typeName ')' castExpr
/// | '(' typeName ')' '{' initializerItems '}'
/// | unExpr
fn castExpr(p: *Parser) Error!Result {
if (p.eatToken(.l_paren)) |l_paren| {
if (try p.typeName()) |ty| {
try p.expectClosing(l_paren, .r_paren);
if (p.tok_ids[p.tok_i] == .l_brace) {
// compound literal
if (ty.isFunc()) {
try p.err(.func_init);
} else if (ty.specifier == .variable_len_array) {
try p.err(.vla_init);
}
var init_list_expr = try p.initializer(ty);
try init_list_expr.un(p, .compound_literal_expr);
return init_list_expr;
}
var operand = try p.castExpr();
try operand.expect(p);
if (ty.specifier == .void) {
// everything can cast to void
} else if (ty.isInt() or ty.isFloat() or ty.isPtr()) {
if (ty.isFloat() and operand.ty.isPtr())
try p.errStr(.invalid_cast_to_float, l_paren, try p.typeStr(operand.ty));
if (operand.ty.isFloat() and ty.isPtr())
try p.errStr(.invalid_cast_to_pointer, l_paren, try p.typeStr(operand.ty));
} else {
try p.errStr(.invalid_cast_type, l_paren, try p.typeStr(operand.ty));
}
if (ty.qual.any()) try p.errStr(.qual_cast, l_paren, try p.typeStr(ty));
operand.ty = ty;
operand.ty.qual = .{};
try operand.un(p, .cast_expr);
return operand;
}
p.tok_i -= 1;
}
return p.unExpr();
}
/// unExpr
/// : primaryExpr suffixExpr*
/// | ('&' | '*' | '+' | '-' | '~' | '!' | '++' | '--') castExpr
/// | keyword_sizeof unExpr
/// | keyword_sizeof '(' typeName ')'
/// | keyword_alignof '(' typeName ')'
fn unExpr(p: *Parser) Error!Result {
const tok = p.tok_i;
switch (p.tok_ids[tok]) {
.ampersand => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
const slice = p.nodes.slice();
if (!Tree.isLval(slice, operand.node)) {
try p.errTok(.addr_of_rvalue, tok);
}
if (operand.ty.qual.register) try p.errTok(.addr_of_register, tok);
const elem_ty = try p.arena.create(Type);
elem_ty.* = operand.ty;
operand.ty = Type{
.specifier = .pointer,
.data = .{ .sub_type = elem_ty },
};
try operand.un(p, .addr_of_expr);
return operand;
},
.asterisk => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
if (operand.ty.isArray() or operand.ty.isPtr()) {
operand.ty = operand.ty.elemType();
} else if (!operand.ty.isFunc()) {
try p.errTok(.indirection_ptr, tok);
}
try operand.un(p, .deref_expr);
return operand;
},
.plus => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
try operand.lvalConversion(p);
if (!operand.ty.isInt() and !operand.ty.isFloat())
try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
return operand;
},
.minus => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
try operand.lvalConversion(p);
if (!operand.ty.isInt() and !operand.ty.isFloat())
try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
const size = operand.ty.sizeof(p.pp.comp).?;
switch (operand.val) {
.unsigned => |*v| switch (size) {
1, 2, 4 => v.* = @truncate(u32, 0 -% v.*),
8 => v.* = 0 -% v.*,
else => unreachable,
},
.signed => |*v| switch (size) {
1, 2, 4 => v.* = @truncate(i32, 0 -% v.*),
8 => v.* = 0 -% v.*,
else => unreachable,
},
.unavailable => {},
}
try operand.un(p, .negate_expr);
return operand;
},
.plus_plus => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
if (!operand.ty.isInt() and !operand.ty.isFloat() and !operand.ty.isReal() and !operand.ty.isPtr())
try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (!Tree.isLval(p.nodes.slice(), operand.node) or operand.ty.qual.@"const") {
try p.errTok(.not_assignable, tok);
return error.ParsingFailed;
}
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
// TODO overflow
switch (operand.val) {
.unsigned => |*v| v.* += 1,
.signed => |*v| v.* += 1,
.unavailable => {},
}
try operand.un(p, .pre_inc_expr);
return operand;
},
.minus_minus => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
if (!operand.ty.isInt() and !operand.ty.isFloat() and !operand.ty.isReal() and !operand.ty.isPtr())
try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (!Tree.isLval(p.nodes.slice(), operand.node) or operand.ty.qual.@"const") {
try p.errTok(.not_assignable, tok);
return error.ParsingFailed;
}
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
// TODO overflow
switch (operand.val) {
.unsigned => |*v| v.* -= 1,
.signed => |*v| v.* -= 1,
.unavailable => {},
}
try operand.un(p, .pre_dec_expr);
return operand;
},
.tilde => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
try operand.lvalConversion(p);
if (!operand.ty.isInt()) try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
switch (operand.val) {
.unsigned => |*v| v.* = ~v.*,
.signed => |*v| v.* = ~v.*,
.unavailable => {},
}
try operand.un(p, .bool_not_expr);
return operand;
},
.bang => {
p.tok_i += 1;
var operand = try p.castExpr();
try operand.expect(p);
try operand.lvalConversion(p);
if (!operand.ty.isInt() and !operand.ty.isFloat() and !operand.ty.isPtr())
try p.errStr(.invalid_argument_un, tok, try p.typeStr(operand.ty));
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
if (operand.val != .unavailable) {
const res = @boolToInt(!operand.getBool());
operand.val = .{ .signed = res };
}
operand.ty = .{ .specifier = .int };
try operand.un(p, .bool_not_expr);
return operand;
},
.keyword_sizeof => {
p.tok_i += 1;
const expected_paren = p.tok_i;
var res = Result{};
if (try p.typeName()) |ty| {
res.ty = ty;
try p.errTok(.expected_parens_around_typename, expected_paren);
} else if (p.eatToken(.l_paren)) |l_paren| {
if (try p.typeName()) |ty| {
res.ty = ty;
try p.expectClosing(l_paren, .r_paren);
} else {
p.tok_i = expected_paren;
res = try p.parseNoEval(assignExpr);
}
} else {
res = try p.parseNoEval(unExpr);
}
if (res.ty.sizeof(p.pp.comp)) |size| {
res.val = .{ .unsigned = size };
} else {
res.val = .unavailable;
try p.errStr(.invalid_sizeof, expected_paren - 1, try p.typeStr(res.ty));
}
res.ty = Type.sizeT(p.pp.comp);
try res.un(p, .sizeof_expr);
return res;
},
.keyword_alignof, .keyword_alignof1, .keyword_alignof2 => {
p.tok_i += 1;
const expected_paren = p.tok_i;
var res = Result{};
if (try p.typeName()) |ty| {
res.ty = ty;
try p.errTok(.expected_parens_around_typename, expected_paren);
} else if (p.eatToken(.l_paren)) |l_paren| {
if (try p.typeName()) |ty| {
res.ty = ty;
try p.expectClosing(l_paren, .r_paren);
} else {
p.tok_i = expected_paren;
res = try p.parseNoEval(assignExpr);
try p.errTok(.alignof_expr, expected_paren);
}
} else {
res = try p.parseNoEval(unExpr);
try p.errTok(.alignof_expr, expected_paren);
}
res.ty = Type.sizeT(p.pp.comp);
res.val = .{ .unsigned = res.ty.alignof(p.pp.comp) };
try res.un(p, .alignof_expr);
return res;
},
else => {
var lhs = try p.primaryExpr();
if (lhs.empty(p)) return lhs;
while (true) {
const suffix = try p.suffixExpr(lhs);
if (suffix.empty(p)) break;
lhs = suffix;
}
return lhs;
},
}
}
/// suffixExpr
/// : '[' expr ']'
/// | '(' argumentExprList? ')'
/// | '.' IDENTIFIER
/// | '->' IDENTIFIER
/// | '++'
/// | '--'
/// argumentExprList : assignExpr (',' assignExpr)*
fn suffixExpr(p: *Parser, lhs: Result) Error!Result {
assert(!lhs.empty(p));
switch (p.tok_ids[p.tok_i]) {
.l_paren => return p.callExpr(lhs),
.plus_plus => {
defer p.tok_i += 1;
var operand = lhs;
if (!operand.ty.isInt() and !operand.ty.isFloat() and !operand.ty.isReal() and !operand.ty.isPtr())
try p.errStr(.invalid_argument_un, p.tok_i, try p.typeStr(operand.ty));
if (!Tree.isLval(p.nodes.slice(), operand.node) or operand.ty.qual.@"const") {
try p.err(.not_assignable);
return error.ParsingFailed;
}
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
try operand.un(p, .post_dec_expr);
return operand;
},
.minus_minus => {
defer p.tok_i += 1;
var operand = lhs;
if (!operand.ty.isInt() and !operand.ty.isFloat() and !operand.ty.isReal() and !operand.ty.isPtr())
try p.errStr(.invalid_argument_un, p.tok_i, try p.typeStr(operand.ty));
if (!Tree.isLval(p.nodes.slice(), operand.node) or operand.ty.qual.@"const") {
try p.err(.not_assignable);
return error.ParsingFailed;
}
if (operand.ty.isInt()) try operand.intCast(p, operand.ty.integerPromotion(p.pp.comp));
try operand.un(p, .post_dec_expr);
return operand;
},
.l_bracket => {
const l_bracket = p.tok_i;
p.tok_i += 1;
var index = try p.expr();
try index.expect(p);
try p.expectClosing(l_bracket, .r_bracket);
const l_ty = lhs.ty;
const r_ty = index.ty;
var ptr = lhs;
try ptr.lvalConversion(p);
try index.lvalConversion(p);
if (ptr.ty.isPtr()) {
ptr.ty = ptr.ty.elemType();
if (!index.ty.isInt()) try p.errTok(.invalid_index, l_bracket);
try p.checkArrayBounds(index, l_ty, l_bracket);
} else if (index.ty.isPtr()) {
index.ty = index.ty.elemType();
if (!ptr.ty.isInt()) try p.errTok(.invalid_index, l_bracket);
try p.checkArrayBounds(ptr, r_ty, l_bracket);
std.mem.swap(Result, &ptr, &index);
} else {
try p.errTok(.invalid_subscript, l_bracket);
}
try ptr.saveValue(p);
try index.saveValue(p);
try ptr.bin(p, .array_access_expr, index);
return ptr;
},
.period => {
p.tok_i += 1;
const name = try p.expectToken(.identifier);
// TODO validate type
return Result{
.ty = lhs.ty,
.node = try p.addNode(.{
.tag = .member_access_expr,
.ty = lhs.ty,
.data = .{ .member = .{ .lhs = lhs.node, .name = name } },
}),
};
},
.arrow => {
p.tok_i += 1;
const name = try p.expectToken(.identifier);
// TODO validate type / deref
return Result{
.ty = lhs.ty,
.node = try p.addNode(.{
.tag = .member_access_ptr_expr,
.ty = lhs.ty,
.data = .{ .member = .{ .lhs = lhs.node, .name = name } },
}),
};
},
else => return Result{},
}
}
fn callExpr(p: *Parser, lhs: Result) Error!Result {
const l_paren = p.tok_i;
p.tok_i += 1;
const ty = lhs.ty.isCallable() orelse {
try p.errStr(.not_callable, l_paren, try p.typeStr(lhs.ty));
return error.ParsingFailed;
};
const params = ty.data.func.params;
var func = lhs;
try func.lvalConversion(p);
const list_buf_top = p.list_buf.items.len;
defer p.list_buf.items.len = list_buf_top;
try p.list_buf.append(func.node);
var arg_count: u32 = 0;
var first_after = l_paren;
if (p.eatToken(.r_paren) == null) {
while (true) {
const param_tok = p.tok_i;
if (arg_count == params.len) first_after = p.tok_i;
var arg = try p.assignExpr();
try arg.expect(p);
try arg.lvalConversion(p);
if (arg_count < params.len) {
const p_ty = params[arg_count].ty;
if (p_ty.specifier == .bool) {
// this is ridiculous but it's what clang does
if (arg.ty.isInt() or arg.ty.isFloat() or arg.ty.isPtr()) {
try arg.boolCast(p, p_ty);
} else {
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else if (p_ty.isInt()) {
if (arg.ty.isInt() or arg.ty.isFloat()) {
try arg.intCast(p, p_ty);
} else if (arg.ty.isPtr()) {
try p.errStr(
.implicit_ptr_to_int,
param_tok,
try p.typePairStrExtra(arg.ty, " to ", p_ty),
);
try p.errTok(.parameter_here, params[arg_count].name_tok);
try arg.intCast(p, p_ty);
} else {
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else if (p_ty.isFloat()) {
if (arg.ty.isInt() or arg.ty.isFloat()) {
try arg.floatCast(p, p_ty);
} else {
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else if (p_ty.isPtr()) {
if (arg.ty.isInt()) {
try p.errStr(
.implicit_int_to_ptr,
param_tok,
try p.typePairStrExtra(arg.ty, " to ", p_ty),
);
try p.errTok(.parameter_here, params[arg_count].name_tok);
try arg.intCast(p, p_ty);
} else if (!p_ty.eql(arg.ty, false)) {
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else if (p_ty.isRecord()) {
if (!p_ty.eql(arg.ty, false)) {
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else {
// should be unreachable
try p.errStr(.incompatible_param, param_tok, try p.typeStr(arg.ty));
try p.errTok(.parameter_here, params[arg_count].name_tok);
}
} else {
if (arg.ty.isInt()) try arg.intCast(p, arg.ty.integerPromotion(p.pp.comp));
if (arg.ty.specifier == .float) try arg.floatCast(p, .{ .specifier = .double });
}
try arg.saveValue(p);
try p.list_buf.append(arg.node);
arg_count += 1;
_ = p.eatToken(.comma) orelse break;
}
try p.expectClosing(l_paren, .r_paren);
}
const extra = Diagnostics.Message.Extra{ .arguments = .{
.expected = @intCast(u32, params.len),
.actual = @intCast(u32, arg_count),
} };
if (ty.specifier == .func and params.len != arg_count) {
try p.errExtra(.expected_arguments, first_after, extra);
}
if (ty.specifier == .old_style_func and params.len != arg_count) {
try p.errExtra(.expected_arguments_old, first_after, extra);
}
if (ty.specifier == .var_args_func and arg_count < params.len) {
try p.errExtra(.expected_at_least_arguments, first_after, extra);
}
var call_node: Tree.Node = .{
.tag = .call_expr_one,
.ty = ty.data.func.return_type,
.data = .{ .bin = .{ .lhs = func.node, .rhs = .none } },
};
const args = p.list_buf.items[list_buf_top..];
switch (arg_count) {
0 => {},
1 => call_node.data.bin.rhs = args[1], // args[0] == func.node
else => {
call_node.tag = .call_expr;
call_node.data = .{ .range = try p.addList(args) };
},
}
return Result{ .node = try p.addNode(call_node), .ty = call_node.ty };
}
fn checkArrayBounds(p: *Parser, index: Result, arr_ty: Type, tok: TokenIndex) !void {
const len = switch (arr_ty.specifier) {
.array, .static_array, .decayed_array, .decayed_static_array => arr_ty.data.array.len,
else => return,
};
switch (index.val) {
.unsigned => |val| if (std.math.compare(val, .gte, len))
try p.errExtra(.array_after, tok, .{ .unsigned = val }),
.signed => |val| if (val < 0)
try p.errExtra(.array_before, tok, .{ .signed = val })
else if (std.math.compare(val, .gte, len))
try p.errExtra(.array_after, tok, .{ .unsigned = @intCast(u64, val) }),
.unavailable => return,
}
}
/// primaryExpr
/// : IDENTIFIER
/// | INTEGER_LITERAL
/// | FLOAT_LITERAL
/// | CHAR_LITERAL
/// | STRING_LITERAL
/// | '(' expr ')'
/// | genericSelection
fn primaryExpr(p: *Parser) Error!Result {
if (p.eatToken(.l_paren)) |l_paren| {
var e = try p.expr();
try e.expect(p);
try p.expectClosing(l_paren, .r_paren);
try e.un(p, .paren_expr);
return e;
}
switch (p.tok_ids[p.tok_i]) {
.identifier => {
const name_tok = p.tok_i;
p.tok_i += 1;
const sym = p.findSymbol(name_tok, .reference) orelse {
if (p.tok_ids[p.tok_i] == .l_paren) {
// implicitly declare simple functions as like `puts("foo")`;
const name = p.tokSlice(name_tok);
try p.errStr(.implicit_func_decl, name_tok, name);
const func_ty = try p.arena.create(Type.Func);
func_ty.* = .{ .return_type = .{ .specifier = .int }, .params = &.{} };
const ty: Type = .{ .specifier = .old_style_func, .data = .{ .func = func_ty } };
const node = try p.addNode(.{
.ty = ty,
.tag = .fn_proto,
.data = .{ .decl = .{ .name = name_tok } },
});
try p.decl_buf.append(node);
try p.scopes.append(.{ .decl = .{
.name = name,
.ty = ty,
.name_tok = name_tok,
} });
return Result{
.ty = ty,
.node = try p.addNode(.{
.tag = .decl_ref_expr,
.ty = ty,
.data = .{ .decl_ref = name_tok },
}),
};
}
try p.errStr(.undeclared_identifier, name_tok, p.tokSlice(name_tok));
return error.ParsingFailed;
};
switch (sym) {
.enumeration => |e| {
var res = e.value;
res.node = try p.addNode(.{
.tag = .enumeration_ref,
.ty = res.ty,
.data = .{ .decl_ref = name_tok },
});
return res;
},
.def, .decl, .param => |s| return Result{
.ty = s.ty,
.node = try p.addNode(.{
.tag = .decl_ref_expr,
.ty = s.ty,
.data = .{ .decl_ref = name_tok },
}),
},
else => unreachable,
}
},
.string_literal,
.string_literal_utf_16,
.string_literal_utf_8,
.string_literal_utf_32,
.string_literal_wide,
=> return p.stringLiteral(),
.char_literal,
.char_literal_utf_16,
.char_literal_utf_32,
.char_literal_wide,
=> return p.charLiteral(),
.float_literal => {
defer p.tok_i += 1;
const ty = Type{ .specifier = .double };
return Result{ .ty = ty, .node = try p.addNode(
.{ .tag = .double_literal, .ty = ty, .data = .{ .double = try p.parseFloat(p.tok_i, f64) } },
) };
},
.float_literal_f => {
defer p.tok_i += 1;
const ty = Type{ .specifier = .float };
return Result{ .ty = ty, .node = try p.addNode(
.{ .tag = .float_literal, .ty = ty, .data = .{ .float = try p.parseFloat(p.tok_i, f32) } },
) };
},
.float_literal_l => return p.todo("long double literals"),
.zero => {
p.tok_i += 1;
var res: Result = .{ .val = .{ .signed = 0 } };
res.node = try p.addNode(.{ .tag = .int_literal, .ty = res.ty, .data = .{ .int = 0 } });
return res;
},
.one => {
p.tok_i += 1;
var res: Result = .{ .val = .{ .signed = 1 } };
res.node = try p.addNode(.{ .tag = .int_literal, .ty = res.ty, .data = .{ .int = 1 } });
return res;
},
.integer_literal,
.integer_literal_u,
.integer_literal_l,
.integer_literal_lu,
.integer_literal_ll,
.integer_literal_llu,
=> return p.integerLiteral(),
.keyword_generic => return p.genericSelection(),
else => return Result{},
}
}
fn stringLiteral(p: *Parser) Error!Result {
var start = p.tok_i;
// use 1 for wchar_t
var width: ?u8 = null;
while (true) {
switch (p.tok_ids[p.tok_i]) {
.string_literal => {},
.string_literal_utf_16 => if (width) |some| {
if (some != 16) try p.err(.unsupported_str_cat);
} else {
width = 16;
},
.string_literal_utf_8 => if (width) |some| {
if (some != 8) try p.err(.unsupported_str_cat);
} else {
width = 8;
},
.string_literal_utf_32 => if (width) |some| {
if (some != 32) try p.err(.unsupported_str_cat);
} else {
width = 32;
},
.string_literal_wide => if (width) |some| {
if (some != 1) try p.err(.unsupported_str_cat);
} else {
width = 1;
},
else => break,
}
p.tok_i += 1;
}
if (width == null) width = 8;
if (width.? != 8) return p.todo("unicode string literals");
const index = p.strings.items.len;
while (start < p.tok_i) : (start += 1) {
var slice = p.tokSlice(start);
slice = slice[0 .. slice.len - 1];
var i = mem.indexOf(u8, slice, "\"").? + 1;
try p.strings.ensureUnusedCapacity(slice.len);
while (i < slice.len) : (i += 1) {
switch (slice[i]) {
'\\' => {
i += 1;
switch (slice[i]) {
'\n' => i += 1,
'\r' => i += 2,
'\'', '\"', '\\', '?' => |c| p.strings.appendAssumeCapacity(c),
'n' => p.strings.appendAssumeCapacity('\n'),
'r' => p.strings.appendAssumeCapacity('\r'),
't' => p.strings.appendAssumeCapacity('\t'),
'a' => p.strings.appendAssumeCapacity(0x07),
'b' => p.strings.appendAssumeCapacity(0x08),
'e' => p.strings.appendAssumeCapacity(0x1B),
'f' => p.strings.appendAssumeCapacity(0x0C),
'v' => p.strings.appendAssumeCapacity(0x0B),
'x' => p.strings.appendAssumeCapacity(try p.parseNumberEscape(start, 16, slice, &i)),
'0'...'7' => p.strings.appendAssumeCapacity(try p.parseNumberEscape(start, 8, slice, &i)),
'u' => try p.parseUnicodeEscape(start, 4, slice, &i),
'U' => try p.parseUnicodeEscape(start, 8, slice, &i),
else => unreachable,
}
},
else => |c| p.strings.appendAssumeCapacity(c),
}
}
}
try p.strings.append(0);
const len = p.strings.items.len - index;
const arr_ty = try p.arena.create(Type.Array);
arr_ty.* = .{ .elem = .{ .specifier = .char }, .len = len };
var res: Result = .{
.ty = .{
.specifier = .array,
.data = .{ .array = arr_ty },
},
};
res.node = try p.addNode(.{
.tag = .string_literal_expr,
.ty = res.ty,
.data = .{ .str = .{ .index = @intCast(u32, index), .len = @intCast(u32, len) } },
});
return res;
}
fn parseNumberEscape(p: *Parser, tok: TokenIndex, base: u8, slice: []const u8, i: *usize) !u8 {
if (base == 16) i.* += 1; // skip x
var char: u8 = 0;
var reported = false;
while (i.* < slice.len) : (i.* += 1) {
const val = std.fmt.charToDigit(slice[i.*], base) catch break; // validated by Tokenizer
if (@mulWithOverflow(u8, char, base, &char) and !reported) {
try p.errExtra(.escape_sequence_overflow, tok, .{ .unsigned = i.* });
reported = true;
}
char += val;
}
i.* -= 1;
return char;
}
fn parseUnicodeEscape(p: *Parser, tok: TokenIndex, count: u8, slice: []const u8, i: *usize) !void {
const c = std.fmt.parseInt(u21, slice[i.* + 1 ..][0..count], 16) catch unreachable; // Validated by tokenizer
i.* += count + 1;
if (c >= 0x110000 or (c < 0xa0 and c != '$' and c != '@' and c != '¸')) {
try p.errExtra(.invalid_universal_character, tok, .{ .unsigned = i.* - count - 2 });
return;
}
var buf: [4]u8 = undefined;
const to_write = std.unicode.utf8Encode(c, &buf) catch unreachable; // validated above
p.strings.appendSliceAssumeCapacity(buf[0..to_write]);
}
fn charLiteral(p: *Parser) Error!Result {
const lit_tok = p.tok_i;
const ty: Type = switch (p.tok_ids[p.tok_i]) {
.char_literal => .{ .specifier = .int },
else => return p.todo("unicode char literals"),
};
p.tok_i += 1;
var val: u32 = 0;
var overflow_reported = false;
var multichar: u8 = 0;
var slice = p.tokSlice(lit_tok);
slice = slice[0 .. slice.len - 1];
var i = mem.indexOf(u8, slice, "\'").? + 1;
while (i < slice.len) : (i += 1) {
var c = slice[i];
switch (c) {
'\\' => {
i += 1;
switch (slice[i]) {
'\n' => i += 1,
'\r' => i += 2,
'\'', '\"', '\\', '?' => c = slice[i],
'n' => c = '\n',
'r' => c = '\r',
't' => c = '\t',
'a' => c = 0x07,
'b' => c = 0x08,
'e' => c = 0x1B,
'f' => c = 0x0C,
'v' => c = 0x0B,
'x' => c = try p.parseNumberEscape(lit_tok, 16, slice, &i),
'0'...'7' => c = try p.parseNumberEscape(lit_tok, 8, slice, &i),
'u', 'U' => return p.todo("unicode escapes in char literals"),
else => unreachable,
}
},
else => {},
}
if (@mulWithOverflow(u32, val, 0xff, &val) and !overflow_reported) {
try p.errExtra(.char_lit_too_wide, lit_tok, .{ .unsigned = i });
overflow_reported = true;
}
val += c;
switch (multichar) {
0 => multichar = 1,
1 => {
multichar = 2;
try p.errTok(.multichar_literal, lit_tok);
},
else => {},
}
}
return Result{
.ty = ty,
.val = .{ .unsigned = val },
.node = try p.addNode(.{
.tag = .int_literal,
.ty = ty,
.data = .{ .int = val },
}),
};
}
fn parseFloat(p: *Parser, tok: TokenIndex, comptime T: type) Error!T {
var bytes = p.tokSlice(tok);
if (p.tok_ids[tok] != .float_literal) bytes = bytes[0 .. bytes.len - 1];
if (bytes.len > 2 and (bytes[1] == 'x' or bytes[1] == 'X')) {
assert(bytes[0] == '0'); // validated by Tokenizer
return std.fmt.parseHexFloat(T, bytes) catch |e| switch (e) {
error.InvalidCharacter => unreachable, // validated by Tokenizer
error.Overflow => p.todo("what to do with hex floats too big"),
};
} else {
return std.fmt.parseFloat(T, bytes) catch |e| switch (e) {
error.InvalidCharacter => unreachable, // validated by Tokenizer
};
}
}
fn integerLiteral(p: *Parser) Error!Result {
const id = p.tok_ids[p.tok_i];
var slice = p.tokSlice(p.tok_i);
defer p.tok_i += 1;
var base: u8 = 10;
if (mem.startsWith(u8, slice, "0x") or mem.startsWith(u8, slice, "0X")) {
slice = slice[2..];
base = 10;
} else if (mem.startsWith(u8, slice, "0b") or mem.startsWith(u8, slice, "0B")) {
slice = slice[2..];
base = 2;
} else if (slice[0] == '0') {
base = 8;
}
switch (id) {
.integer_literal_u, .integer_literal_l => slice = slice[0 .. slice.len - 1],
.integer_literal_lu, .integer_literal_ll => slice = slice[0 .. slice.len - 2],
.integer_literal_llu => slice = slice[0 .. slice.len - 3],
else => {},
}
var val: u64 = 0;
var overflow = false;
for (slice) |c| {
const digit: u64 = switch (c) {
'0'...'9' => c - '0',
'A'...'Z' => c - 'A' + 10,
'a'...'z' => c - 'a' + 10,
else => unreachable,
};
if (val != 0 and @mulWithOverflow(u64, val, base, &val)) overflow = true;
if (@addWithOverflow(u64, val, digit, &val)) overflow = true;
}
if (overflow) {
try p.err(.int_literal_too_big);
var res: Result = .{ .ty = .{ .specifier = .ulong_long }, .val = .{ .unsigned = val } };
res.node = try p.addNode(.{ .tag = .int_literal, .ty = res.ty, .data = .{ .int = val } });
return res;
}
if (base == 10) {
switch (id) {
.integer_literal => return p.castInt(val, &.{ .int, .long, .long_long }),
.integer_literal_u => return p.castInt(val, &.{ .uint, .ulong, .ulong_long }),
.integer_literal_l => return p.castInt(val, &.{ .long, .long_long }),
.integer_literal_lu => return p.castInt(val, &.{ .ulong, .ulong_long }),
.integer_literal_ll => return p.castInt(val, &.{.long_long}),
.integer_literal_llu => return p.castInt(val, &.{.ulong_long}),
else => unreachable,
}
} else {
switch (id) {
.integer_literal => return p.castInt(val, &.{ .int, .uint, .long, .ulong, .long_long, .ulong_long }),
.integer_literal_u => return p.castInt(val, &.{ .uint, .ulong, .ulong_long }),
.integer_literal_l => return p.castInt(val, &.{ .long, .ulong, .long_long, .ulong_long }),
.integer_literal_lu => return p.castInt(val, &.{ .ulong, .ulong_long }),
.integer_literal_ll => return p.castInt(val, &.{ .long_long, .ulong_long }),
.integer_literal_llu => return p.castInt(val, &.{.ulong_long}),
else => unreachable,
}
}
}
fn castInt(p: *Parser, val: u64, specs: []const Type.Specifier) Error!Result {
var res: Result = .{};
for (specs) |spec| {
const ty = Type{ .specifier = spec };
const unsigned = ty.isUnsignedInt(p.pp.comp);
const size = ty.sizeof(p.pp.comp).?;
res.ty = ty;
if (unsigned) {
res.val = .{ .unsigned = val };
switch (size) {
2 => if (val <= std.math.maxInt(u16)) break,
4 => if (val <= std.math.maxInt(u32)) break,
8 => if (val <= std.math.maxInt(u64)) break,
else => unreachable,
}
} else {
res.val = .{ .signed = @bitCast(i64, val) };
switch (size) {
2 => if (val <= std.math.maxInt(i16)) break,
4 => if (val <= std.math.maxInt(i32)) break,
8 => if (val <= std.math.maxInt(i64)) break,
else => unreachable,
}
}
} else {
res.ty = .{ .specifier = .ulong_long };
}
res.node = try p.addNode(.{ .tag = .int_literal, .ty = res.ty, .data = .{ .int = val } });
return res;
}
/// Run a parser function but do not evaluate the result
fn parseNoEval(p: *Parser, func: fn(*Parser) Error!Result) Error!Result {
const no_eval = p.no_eval;
defer p.no_eval = no_eval;
p.no_eval = true;
const parsed = try func(p);
try parsed.expect(p);
return parsed;
}
/// genericSelection : keyword_generic '(' assignExpr ',' genericAssoc (',' genericAssoc)* ')'
/// genericAssoc
/// : typeName ':' assignExpr
/// | keyword_default ':' assignExpr
fn genericSelection(p: *Parser) Error!Result {
p.tok_i += 1;
const l_paren = try p.expectToken(.l_paren);
const controlling = try p.parseNoEval(assignExpr);
_ = try p.expectToken(.comma);
const list_buf_top = p.list_buf.items.len;
defer p.list_buf.items.len = list_buf_top;
try p.list_buf.append(controlling.node);
var default_tok: ?TokenIndex = null;
// TODO actually choose
var chosen: Result = .{};
while (true) {
const start = p.tok_i;
if (try p.typeName()) |ty| {
if (ty.qual.any()) {
try p.errTok(.generic_qual_type, start);
}
_ = try p.expectToken(.colon);
chosen = try p.assignExpr();
try chosen.expect(p);
try chosen.saveValue(p);
try p.list_buf.append(try p.addNode(.{
.tag = .generic_association_expr,
.ty = ty,
.data = .{ .un = chosen.node },
}));
} else if (p.eatToken(.keyword_default)) |tok| {
if (default_tok) |prev| {
try p.errTok(.generic_duplicate_default, tok);
try p.errTok(.previous_case, prev);
}
default_tok = tok;
_ = try p.expectToken(.colon);
chosen = try p.assignExpr();
try chosen.expect(p);
try chosen.saveValue(p);
try p.list_buf.append(try p.addNode(.{
.tag = .generic_default_expr,
.data = .{ .un = chosen.node },
}));
} else {
if (p.list_buf.items.len == list_buf_top + 1) {
try p.err(.expected_type);
return error.ParsingFailed;
}
break;
}
if (p.eatToken(.comma) == null) break;
}
try p.expectClosing(l_paren, .r_paren);
var generic_node: Tree.Node = .{
.tag = .generic_expr_one,
.ty = chosen.ty,
.data = .{ .bin = .{ .lhs = controlling.node, .rhs = chosen.node } },
};
const associations = p.list_buf.items[list_buf_top..];
if (associations.len > 2) { // associations[0] == controlling.node
generic_node.tag = .generic_expr;
generic_node.data = .{ .range = try p.addList(associations) };
}
chosen.node = try p.addNode(generic_node);
return chosen;
}
|
src/Parser.zig
|
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
test "enum type" {
const foo1 = Foo{ .One = 13};
const foo2 = Foo{. Two = Point { .x = 1234, .y = 5678, }};
const bar = Bar.B;
assert(bar == Bar.B);
assert(@memberCount(Foo) == 3);
assert(@memberCount(Bar) == 4);
assert(@sizeOf(Foo) == @sizeOf(FooNoVoid));
assert(@sizeOf(Bar) == 1);
}
test "enum as return value" {
switch (returnAnInt(13)) {
Foo.One => |value| assert(value == 13),
else => unreachable,
}
}
const Point = struct {
x: u64,
y: u64,
};
const Foo = union(enum) {
One: i32,
Two: Point,
Three: void,
};
const FooNoVoid = union(enum) {
One: i32,
Two: Point,
};
const Bar = enum {
A,
B,
C,
D,
};
fn returnAnInt(x: i32) Foo {
return Foo { .One = x };
}
test "constant enum with payload" {
var empty = AnEnumWithPayload {.Empty = {}};
var full = AnEnumWithPayload {.Full = 13};
shouldBeEmpty(empty);
shouldBeNotEmpty(full);
}
fn shouldBeEmpty(x: &const AnEnumWithPayload) void {
switch (*x) {
AnEnumWithPayload.Empty => {},
else => unreachable,
}
}
fn shouldBeNotEmpty(x: &const AnEnumWithPayload) void {
switch (*x) {
AnEnumWithPayload.Empty => unreachable,
else => {},
}
}
const AnEnumWithPayload = union(enum) {
Empty: void,
Full: i32,
};
const Number = enum {
Zero,
One,
Two,
Three,
Four,
};
test "enum to int" {
shouldEqual(Number.Zero, 0);
shouldEqual(Number.One, 1);
shouldEqual(Number.Two, 2);
shouldEqual(Number.Three, 3);
shouldEqual(Number.Four, 4);
}
fn shouldEqual(n: Number, expected: u3) void {
assert(u3(n) == expected);
}
test "int to enum" {
testIntToEnumEval(3);
}
fn testIntToEnumEval(x: i32) void {
assert(IntToEnumNumber(u3(x)) == IntToEnumNumber.Three);
}
const IntToEnumNumber = enum {
Zero,
One,
Two,
Three,
Four,
};
test "@tagName" {
assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
comptime assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
}
fn testEnumTagNameBare(n: BareNumber) []const u8 {
return @tagName(n);
}
const BareNumber = enum {
One,
Two,
Three,
};
test "enum alignment" {
comptime {
assert(@alignOf(AlignTestEnum) >= @alignOf([9]u8));
assert(@alignOf(AlignTestEnum) >= @alignOf(u64));
}
}
const AlignTestEnum = union(enum) {
A: [9]u8,
B: u64,
};
const ValueCount1 = enum { I0 };
const ValueCount2 = enum { I0, I1 };
const ValueCount256 = enum {
I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, I13, I14, I15,
I16, I17, I18, I19, I20, I21, I22, I23, I24, I25, I26, I27, I28, I29, I30, I31,
I32, I33, I34, I35, I36, I37, I38, I39, I40, I41, I42, I43, I44, I45, I46, I47,
I48, I49, I50, I51, I52, I53, I54, I55, I56, I57, I58, I59, I60, I61, I62, I63,
I64, I65, I66, I67, I68, I69, I70, I71, I72, I73, I74, I75, I76, I77, I78, I79,
I80, I81, I82, I83, I84, I85, I86, I87, I88, I89, I90, I91, I92, I93, I94, I95,
I96, I97, I98, I99, I100, I101, I102, I103, I104, I105, I106, I107, I108, I109,
I110, I111, I112, I113, I114, I115, I116, I117, I118, I119, I120, I121, I122, I123,
I124, I125, I126, I127, I128, I129, I130, I131, I132, I133, I134, I135, I136, I137,
I138, I139, I140, I141, I142, I143, I144, I145, I146, I147, I148, I149, I150, I151,
I152, I153, I154, I155, I156, I157, I158, I159, I160, I161, I162, I163, I164, I165,
I166, I167, I168, I169, I170, I171, I172, I173, I174, I175, I176, I177, I178, I179,
I180, I181, I182, I183, I184, I185, I186, I187, I188, I189, I190, I191, I192, I193,
I194, I195, I196, I197, I198, I199, I200, I201, I202, I203, I204, I205, I206, I207,
I208, I209, I210, I211, I212, I213, I214, I215, I216, I217, I218, I219, I220, I221,
I222, I223, I224, I225, I226, I227, I228, I229, I230, I231, I232, I233, I234, I235,
I236, I237, I238, I239, I240, I241, I242, I243, I244, I245, I246, I247, I248, I249,
I250, I251, I252, I253, I254, I255
};
const ValueCount257 = enum {
I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, I13, I14, I15,
I16, I17, I18, I19, I20, I21, I22, I23, I24, I25, I26, I27, I28, I29, I30, I31,
I32, I33, I34, I35, I36, I37, I38, I39, I40, I41, I42, I43, I44, I45, I46, I47,
I48, I49, I50, I51, I52, I53, I54, I55, I56, I57, I58, I59, I60, I61, I62, I63,
I64, I65, I66, I67, I68, I69, I70, I71, I72, I73, I74, I75, I76, I77, I78, I79,
I80, I81, I82, I83, I84, I85, I86, I87, I88, I89, I90, I91, I92, I93, I94, I95,
I96, I97, I98, I99, I100, I101, I102, I103, I104, I105, I106, I107, I108, I109,
I110, I111, I112, I113, I114, I115, I116, I117, I118, I119, I120, I121, I122, I123,
I124, I125, I126, I127, I128, I129, I130, I131, I132, I133, I134, I135, I136, I137,
I138, I139, I140, I141, I142, I143, I144, I145, I146, I147, I148, I149, I150, I151,
I152, I153, I154, I155, I156, I157, I158, I159, I160, I161, I162, I163, I164, I165,
I166, I167, I168, I169, I170, I171, I172, I173, I174, I175, I176, I177, I178, I179,
I180, I181, I182, I183, I184, I185, I186, I187, I188, I189, I190, I191, I192, I193,
I194, I195, I196, I197, I198, I199, I200, I201, I202, I203, I204, I205, I206, I207,
I208, I209, I210, I211, I212, I213, I214, I215, I216, I217, I218, I219, I220, I221,
I222, I223, I224, I225, I226, I227, I228, I229, I230, I231, I232, I233, I234, I235,
I236, I237, I238, I239, I240, I241, I242, I243, I244, I245, I246, I247, I248, I249,
I250, I251, I252, I253, I254, I255, I256
};
test "enum sizes" {
comptime {
assert(@sizeOf(ValueCount1) == 0);
assert(@sizeOf(ValueCount2) == 1);
assert(@sizeOf(ValueCount256) == 1);
assert(@sizeOf(ValueCount257) == 2);
}
}
const Small2 = enum (u2) {
One,
Two,
};
const Small = enum (u2) {
One,
Two,
Three,
Four,
};
test "set enum tag type" {
{
var x = Small.One;
x = Small.Two;
comptime assert(@TagType(Small) == u2);
}
{
var x = Small2.One;
x = Small2.Two;
comptime assert(@TagType(Small2) == u2);
}
}
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;
assert(getA(&data) == A.Two);
assert(getB(&data) == B.Three3);
assert(getC(&data) == C.Four4);
comptime assert(@sizeOf(BitFieldOfEnums) == 1);
data.b = B.Four3;
assert(data.b == B.Four3);
data.a = A.Three;
assert(data.a == A.Three);
assert(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 "casting enum to its tag type" {
testCastEnumToTagType(Small2.Two);
comptime testCastEnumToTagType(Small2.Two);
}
fn testCastEnumToTagType(value: Small2) void {
assert(u2(value) == 1);
}
const MultipleChoice = enum(u32) {
A = 20,
B = 40,
C = 60,
D = 1000,
};
test "enum with specified tag values" {
testEnumWithSpecifiedTagValues(MultipleChoice.C);
comptime testEnumWithSpecifiedTagValues(MultipleChoice.C);
}
fn testEnumWithSpecifiedTagValues(x: MultipleChoice) void {
assert(u32(x) == 60);
assert(1234 == switch (x) {
MultipleChoice.A => 1,
MultipleChoice.B => 2,
MultipleChoice.C => u32(1234),
MultipleChoice.D => 4,
});
}
const MultipleChoice2 = enum(u32) {
Unspecified1,
A = 20,
Unspecified2,
B = 40,
Unspecified3,
C = 60,
Unspecified4,
D = 1000,
Unspecified5,
};
test "enum with specified and unspecified tag values" {
testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2.D);
comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2.D);
}
fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: MultipleChoice2) void {
assert(u32(x) == 1000);
assert(1234 == switch (x) {
MultipleChoice2.A => 1,
MultipleChoice2.B => 2,
MultipleChoice2.C => 3,
MultipleChoice2.D => u32(1234),
MultipleChoice2.Unspecified1 => 5,
MultipleChoice2.Unspecified2 => 6,
MultipleChoice2.Unspecified3 => 7,
MultipleChoice2.Unspecified4 => 8,
MultipleChoice2.Unspecified5 => 9,
});
}
test "cast integer literal to enum" {
assert(MultipleChoice2(0) == MultipleChoice2.Unspecified1);
assert(MultipleChoice2(40) == MultipleChoice2.B);
}
const EnumWithOneMember = enum {
Eof,
};
fn doALoopThing(id: EnumWithOneMember) void {
while (true) {
if (id == EnumWithOneMember.Eof) {
break;
}
@compileError("above if condition should be comptime");
}
}
test "comparison operator on enum with one member is comptime known" {
doALoopThing(EnumWithOneMember.Eof);
}
const State = enum {
Start,
};
test "switch on enum with one member is comptime known" {
var state = State.Start;
switch (state) {
State.Start => return,
}
@compileError("analysis should not reach here");
}
const EnumWithTagValues = enum(u4) {
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
};
test "enum with tag values don't require parens" {
assert(u4(EnumWithTagValues.C) == 0b0100);
}
test "enum with 1 field but explicit tag type should still have the tag type" {
const Enum = enum(u8) { B = 2 };
comptime @import("std").debug.assert(@sizeOf(Enum) == @sizeOf(u8));
}
|
test/cases/enum.zig
|
const std = @import("std");
const mem = std.mem;
usingnamespace @import("headers.zig");
usingnamespace @import("request.zig");
usingnamespace @import("common.zig");
usingnamespace @import("zuri");
const Context = @import("../server.zig").Server.Context;
const t = std.testing;
pub fn parse(req: *Request, ctx: *Context) !void {
var cur = ctx.index;
// method
if (!seek(ctx, ' ')) {
return error.NoMethod;
}
req.method = ctx.buf[cur .. ctx.index - 1];
cur = ctx.index;
// path
if (!seek(ctx, ' ')) {
return error.NoPath;
}
if (req.path.len > 1) {
const uri = try Uri.parse(ctx.buf[cur .. ctx.index - 1], true);
req.path = try Uri.resolvePath(req.headers.list.allocator, uri.path);
req.query = uri.query;
} else {
req.path = try req.headers.list.allocator.dupe(u8, ctx.buf[cur .. ctx.index - 1]);
}
cur = ctx.index;
// version
if (!seek(ctx, '\r')) {
return error.NoVersion;
}
req.version = try Version.fromString(ctx.buf[cur .. ctx.index - 1]);
if (req.version == .Http30) {
return error.UnsupportedVersion;
}
try expect(ctx, '\n');
// HTTP/0.9 allows request with no headers to end after "METHOD PATH HTTP/0.9\r\n"
if (req.version == .Http09 and ctx.index == ctx.count) {
return;
}
try parseHeaders(&req.headers, ctx);
try expect(ctx, '\r');
try expect(ctx, '\n');
req.body = ctx.buf[ctx.index..ctx.count];
}
fn parseHeaders(h: *Headers, ctx: *Context) !void {
var name: []u8 = "";
var cur = ctx.index;
while (ctx.buf[cur] != '\r') {
if (!seek(ctx, ':')) {
return error.NoName;
}
name = ctx.buf[cur .. ctx.index - 1];
cur = ctx.index;
if (!seek(ctx, '\r')) {
return error.NoValue;
}
try expect(ctx, '\n');
switch (ctx.buf[ctx.index]) {
'\t', ' ' => { // obs-fold
if (!seek(ctx, '\r')) {
return error.InvalidObsFold;
}
try expect(ctx, '\n');
},
else => {},
}
try h.put(name, ctx.buf[cur .. ctx.index - 2]);
cur = ctx.index;
}
}
// index is after first `c`
fn seek(ctx: *Context, c: u8) bool {
while (true) {
if (ctx.index >= ctx.count) {
return false;
} else if (ctx.buf[ctx.index] == c) {
ctx.index += 1;
return true;
} else {
ctx.index += 1;
}
}
}
// index is after `c`
fn expect(ctx: *Context, c: u8) !void {
if (ctx.count < ctx.index + 1) {
return error.UnexpectedEof;
}
if (ctx.buf[ctx.index] == c) {
ctx.index += 1;
} else {
return error.InvalidChar;
}
}
const alloc = std.heap.page_allocator;
test "parse headers" {
var b = try alloc.dupe(u8, "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0\r\n" ++
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" ++
"Accept-Language: en-US,en;q=0.5\r\n" ++
"Accept-Encoding: gzip, deflate\r\n" ++
"DNT: 1\r\n" ++
"Connection: keep-alive\r\n" ++
"Upgrade-Insecure-Requests: 1\r\n\r\n");
defer alloc.free(b);
var h = Headers.init(alloc);
defer h.list.deinit();
var ctx = Context{
.buf = b,
.count = b.len,
.stack = undefined,
.writer = undefined,
.server = undefined,
.file = undefined,
.frame = undefined,
.node = undefined,
};
try parseHeaders(&h, &ctx);
var slice = h.list.items;
t.expect(mem.eql(u8, slice[0].name, "user-agent"));
t.expect(mem.eql(u8, slice[0].value, "Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0"));
t.expect(mem.eql(u8, slice[1].name, "accept"));
t.expect(mem.eql(u8, slice[1].value, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
t.expect(mem.eql(u8, slice[2].name, "accept-language"));
t.expect(mem.eql(u8, slice[2].value, "en-US,en;q=0.5"));
t.expect(mem.eql(u8, slice[3].name, "accept-encoding"));
t.expect(mem.eql(u8, slice[3].value, "gzip, deflate"));
t.expect(mem.eql(u8, slice[4].name, "dnt"));
t.expect(mem.eql(u8, slice[4].value, "1"));
t.expect(mem.eql(u8, slice[5].name, "connection"));
t.expect(mem.eql(u8, slice[5].value, "keep-alive"));
t.expect(mem.eql(u8, slice[6].name, "upgrade-insecure-requests"));
t.expect(mem.eql(u8, slice[6].value, "1"));
}
test "HTTP/0.9" {
var b = try alloc.dupe(u8, "GET / HTTP/0.9\r\n");
defer alloc.free(b);
var req: Request = undefined;
req.headers = Headers.init(alloc);
defer req.headers.deinit();
var ctx = Context{
.buf = b,
.count = b.len,
.stack = undefined,
.writer = undefined,
.server = undefined,
.file = undefined,
.frame = undefined,
.node = undefined,
};
try parse(&req, &ctx);
t.expect(mem.eql(u8, req.method, Method.Get));
t.expect(mem.eql(u8, req.path, "/"));
t.expect(req.version == .Http09);
}
test "HTTP/1.1" {
var b = try alloc.dupe(u8, "POST /about HTTP/1.1\r\n" ++
"expires: Mon, 08 Jul 2019 11:49:03 GMT\r\n" ++
"last-modified: Fri, 09 Nov 2018 06:15:00 GMT\r\n" ++
"X-Test: test\r\n" ++
" obs-fold\r\n" ++
"\r\na body\n");
defer alloc.free(b);
var req: Request = undefined;
req.headers = Headers.init(alloc);
defer req.headers.deinit();
var ctx = Context{
.buf = b,
.count = b.len,
.stack = undefined,
.writer = undefined,
.server = undefined,
.file = undefined,
.frame = undefined,
.node = undefined,
};
try parse(&req, &ctx);
t.expect(mem.eql(u8, req.method, Method.Post));
t.expect(mem.eql(u8, req.path, "/about"));
t.expect(req.version == .Http11);
t.expect(mem.eql(u8, req.body, "a body\n"));
t.expect(mem.eql(u8, (try req.headers.get(alloc, "expires")).?[0].value, "Mon, 08 Jul 2019 11:49:03 GMT"));
t.expect(mem.eql(u8, (try req.headers.get(alloc, "last-modified")).?[0].value, "Fri, 09 Nov 2018 06:15:00 GMT"));
const val = try req.headers.get(alloc, "x-test");
t.expect(mem.eql(u8, (try req.headers.get(alloc, "x-test")).?[0].value, "test obs-fold"));
}
test "HTTP/3.0" {
var b = try alloc.dupe(u8, "POST /about HTTP/3.0\r\n\r\n");
defer alloc.free(b);
var req: Request = undefined;
req.headers = Headers.init(alloc);
defer req.headers.deinit();
var ctx = Context{
.buf = b,
.count = b.len,
.stack = undefined,
.writer = undefined,
.server = undefined,
.file = undefined,
.frame = undefined,
.node = undefined,
};
t.expectError(error.UnsupportedVersion, parse(&req, &ctx));
}
|
src/routez/http/parser.zig
|
const std = @import("std");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Carac = struct {
name: []const u8,
speed: u32,
duration: u32,
rest: u32,
};
fn parse_line(line: []const u8) Carac {
//Rudolph can fly 22 km/s for 8 seconds, but then must rest for 165 seconds.
var slice = line;
var sep = std.mem.indexOf(u8, slice, " can fly ");
const name = slice[0..sep.?];
slice = slice[sep.? + 9 ..];
sep = std.mem.indexOf(u8, slice, " km/s for ");
const speed = slice[0..sep.?];
slice = slice[sep.? + 10 ..];
sep = std.mem.indexOf(u8, slice, " seconds, but then must rest for ");
const duration = slice[0..sep.?];
slice = slice[sep.? + 33 ..];
sep = std.mem.indexOf(u8, slice, " seconds.");
const rest = slice[0..sep.?];
return Carac{
.name = name,
.speed = std.fmt.parseInt(u32, speed, 10) catch unreachable,
.duration = std.fmt.parseInt(u32, duration, 10) catch unreachable,
.rest = std.fmt.parseInt(u32, rest, 10) catch unreachable,
};
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day14.txt", limit);
const maxpeople = 10;
var reindeers: [maxpeople]Carac = undefined;
var popu: u32 = 0;
var it = std.mem.tokenize(u8, text, "\n");
while (it.next()) |line| {
reindeers[popu] = parse_line(line);
trace("{}\n", reindeers[popu]);
popu += 1;
}
var dist: [maxpeople]u32 = [1]u32{0} ** maxpeople;
var points: [maxpeople]u32 = [1]u32{0} ** maxpeople;
var tick: u32 = 0;
while (tick < 2503) : (tick += 1) {
var i: u32 = 0;
var bestdist: u32 = 0;
while (i < popu) : (i += 1) {
const c = reindeers[i];
const sleeping = (tick % (c.duration + c.rest)) >= c.duration;
if (!sleeping)
dist[i] += c.speed;
if (dist[i] > bestdist)
bestdist = dist[i];
}
i = 0;
while (i < popu) : (i += 1) {
if (dist[i] == bestdist)
points[i] += 1;
}
}
var i: u32 = 0;
while (i < popu) : (i += 1) {
trace("{} : {} km, {} points\n", reindeers[i].name, dist[i], points[i]);
}
const out = std.io.getStdOut().writer();
try out.print("pass = {}\n", popu);
// return error.SolutionNotFound;
}
|
2015/day14.zig
|
const std = @import("std");
const common = @import("common.zig");
const rom = @import("rom.zig");
pub const offsets = @import("gen5/offsets.zig");
pub const script = @import("gen5/script.zig");
const debug = std.debug;
const fmt = std.fmt;
const io = std.io;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const unicode = std.unicode;
const nds = rom.nds;
const lu128 = rom.int.lu128;
const lu16 = rom.int.lu16;
const lu32 = rom.int.lu32;
pub const BasePokemon = extern struct {
stats: common.Stats,
types: [2]u8,
catch_rate: u8,
stage: u8,
ev_yield: common.EvYield,
items: [3]lu16,
gender_ratio: u8,
egg_cycles: u8,
base_friendship: u8,
growth_rate: common.GrowthRate,
egg_groups: [2]common.EggGroup,
abilities: [3]u8,
flag: u8,
form_id: lu16,
forme: lu16,
form_count: u8,
color: common.Color,
base_exp_yield: lu16,
height: lu16,
weight: lu16,
// Memory layout
// TMS 01-92, HMS 01-06, TMS 93-95
machine_learnset: lu128,
// TODO: Tutor data only exists in BW2
//special_tutors: lu32,
//driftveil_tutor: lu32,
//lentimas_tutor: lu32,
//humilau_tutor: lu32,
//nacrene_tutor: lu32,
comptime {
debug.assert(@sizeOf(@This()) == 56);
}
};
pub const PartyMemberBase = extern struct {
iv: u8 = 0,
gender_ability: GenderAbilityPair = GenderAbilityPair{},
level: u8 = 0,
padding: u8 = 0,
species: lu16 = lu16.init(0),
form: lu16 = lu16.init(0),
comptime {
debug.assert(@sizeOf(@This()) == 8);
}
const GenderAbilityPair = packed struct {
gender: u4 = 0,
ability: u4 = 0,
};
pub fn toParent(base: *PartyMemberBase, comptime Parent: type) *Parent {
return @fieldParentPtr(Parent, "base", base);
}
};
pub const PartyMemberNone = extern struct {
base: PartyMemberBase = PartyMemberBase{},
comptime {
debug.assert(@sizeOf(@This()) == 8);
}
};
pub const PartyMemberItem = extern struct {
base: PartyMemberBase = PartyMemberBase{},
item: lu16 = lu16.init(0),
comptime {
debug.assert(@sizeOf(@This()) == 10);
}
};
pub const PartyMemberMoves = extern struct {
base: PartyMemberBase = PartyMemberBase{},
moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4,
comptime {
debug.assert(@sizeOf(@This()) == 16);
}
};
pub const PartyMemberBoth = extern struct {
base: PartyMemberBase = PartyMemberBase{},
item: lu16 = lu16.init(0),
moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4,
comptime {
debug.assert(@sizeOf(@This()) == 18);
}
};
pub const Trainer = extern struct {
party_type: common.PartyType,
class: u8,
battle_type: u8, // TODO: This should probably be an enum
party_size: u8,
items: [4]lu16,
ai: lu32,
healer: bool,
cash: u8,
post_battle_item: lu16,
comptime {
debug.assert(@sizeOf(@This()) == 20);
}
pub fn partyMember(trainer: Trainer, party: []u8, i: usize) ?*PartyMemberBase {
const member_size: usize = switch (trainer.party_type) {
.none => @sizeOf(PartyMemberNone),
.item => @sizeOf(PartyMemberItem),
.moves => @sizeOf(PartyMemberMoves),
.both => @sizeOf(PartyMemberBoth),
};
const start = i * member_size;
const end = start + member_size;
if (party.len < end)
return null;
return mem.bytesAsValue(PartyMemberBase, party[start..end][0..@sizeOf(PartyMemberBase)]);
}
};
pub const Move = packed struct {
type: u8,
effect_category: u8,
category: Category,
power: u8,
accuracy: u8,
pp: u8,
priority: u8,
min_hits: u4,
max_hits: u4,
result_effect: lu16,
effect_chance: u8,
status: u8,
min_turns: u8,
max_turns: u8,
crit: u8,
flinch: u8,
effect: lu16,
target_hp: u8,
user_hp: u8,
target: u8,
// TODO: Arrays of uneven elements doesn't quite work in
// packed structs.
stats_affected1: u8,
stats_affected2: u8,
stats_affected3: u8,
stats_affected_magnetude1: u8,
stats_affected_magnetude2: u8,
stats_affected_magnetude3: u8,
stats_affected_chance1: u8,
stats_affected_chance2: u8,
stats_affected_chance3: u8,
// TODO: Figure out if this is actually how the last fields are layed out.
padding1: [2]u8,
flags: lu16,
padding2: [2]u8,
pub const Category = enum(u8) {
status = 0x00,
physical = 0x01,
special = 0x02,
};
comptime {
debug.assert(@sizeOf(@This()) == 36);
}
};
pub const LevelUpMove = extern struct {
id: lu16,
level: lu16,
pub const term = LevelUpMove{
.id = lu16.init(math.maxInt(u16)),
.level = lu16.init(math.maxInt(u16)),
};
comptime {
debug.assert(@sizeOf(@This()) == 4);
}
};
// TODO: Verify layout
pub const Evolution = extern struct {
method: Method,
padding: u8,
param: lu16,
target: lu16,
comptime {
debug.assert(@sizeOf(@This()) == 6);
}
pub const Method = enum(u8) {
unused = 0x00,
friend_ship = 0x01,
unknown_0x02 = 0x02,
unknown_0x03 = 0x03,
level_up = 0x04,
trade = 0x05,
trade_holding_item = 0x06,
trade_with_pokemon = 0x07,
use_item = 0x08,
attack_gth_defense = 0x09,
attack_eql_defense = 0x0A,
attack_lth_defense = 0x0B,
personality_value1 = 0x0C,
personality_value2 = 0x0D,
level_up_may_spawn_pokemon = 0x0E,
level_up_spawn_if_cond = 0x0F,
beauty = 0x10,
use_item_on_male = 0x11,
use_item_on_female = 0x12,
level_up_holding_item_during_daytime = 0x13,
level_up_holding_item_during_the_night = 0x14,
level_up_knowning_move = 0x15,
level_up_with_other_pokemon_in_party = 0x16,
level_up_male = 0x17,
level_up_female = 0x18,
level_up_in_special_magnetic_field = 0x19,
level_up_near_moss_rock = 0x1A,
level_up_near_ice_rock = 0x1B,
_,
};
};
pub const EvolutionTable = extern struct {
items: [7]Evolution,
terminator: lu16,
comptime {
debug.assert(@sizeOf(@This()) == 44);
}
};
pub const Species = extern struct {
value: lu16,
comptime {
debug.assert(@sizeOf(@This()) == 2);
}
pub fn species(s: Species) u10 {
return @truncate(u10, s.value.value());
}
pub fn setSpecies(s: *Species, spe: u10) void {
s.value = lu16.init((@as(u16, s.form()) << @as(u4, 10)) | spe);
}
pub fn form(s: Species) u6 {
return @truncate(u6, s.value.value() >> 10);
}
pub fn setForm(s: *Species, f: u10) void {
s.value = lu16.init((@as(u16, f) << @as(u4, 10)) | s.species());
}
};
pub const WildPokemon = extern struct {
species: Species,
min_level: u8,
max_level: u8,
comptime {
debug.assert(@sizeOf(@This()) == 4);
}
};
pub const WildPokemons = extern struct {
rates: [7]u8,
pad: u8,
grass: [12]WildPokemon,
dark_grass: [12]WildPokemon,
rustling_grass: [12]WildPokemon,
surf: [5]WildPokemon,
ripple_surf: [5]WildPokemon,
fishing: [5]WildPokemon,
ripple_fishing: [5]WildPokemon,
comptime {
debug.assert(@sizeOf(@This()) == 232);
}
};
pub const Pocket = enum(u4) {
items = 0,
tms_hms = 1,
key_items = 2,
poke_balls = 8,
_,
};
// https://github.com/projectpokemon/PPRE/blob/master/pokemon/itemtool/itemdata.py
pub const Item = extern struct {
price: lu16,
battle_effect: u8,
gain: u8,
berry: u8,
fling_effect: u8,
fling_power: u8,
natural_gift_power: u8,
flag: u8,
pocket: packed struct {
pocket: Pocket,
pad: u4,
},
type: u8,
category: u8,
category2: lu16,
category3: u8,
index: u8,
anti_index: u8,
statboosts: Boost,
ev_yield: common.EvYield,
hp_restore: u8,
pp_restore: u8,
happy1: u8,
happy2: u8,
happy3: u8,
padding1: u8,
padding2: u8,
padding3: u8,
padding4: u8,
padding5: u8,
padding6: u8,
pub const Boost = packed struct {
hp: u2,
level: u1,
evolution: u1,
attack: u4,
defense: u4,
sp_attack: u4,
sp_defense: u4,
speed: u4,
accuracy: u4,
crit: u2,
pp: u2,
target: u8,
target2: u8,
};
comptime {
debug.assert(@sizeOf(@This()) == 36);
}
};
// All comments on fields are based on research done on Route 19 in b2
pub const MapHeader = extern struct {
// Something related to the map itself. Setting this to 5
// made it so the player stood in a blue void.
unknown00: u8,
// Setting to 0,5,255 had seemingly no effect
unknown01: u8,
// Setting to 5 removed the snow on the route, even though it was
// winter. Seemed like the fall map
unknown02: u8,
// Setting to 5 removed the snow on the route, even though it was
// winter. Seemed like the summer map
unknown03: u8,
// Something related to the map itself. Setting this to 5
// made it so the player stood in a blue void.
unknown04: u8,
// Setting to 0,5,255: "An error has occurred. Please turn off the power."
unknown05: u8,
// Setting to 5: No effect it seems
// Setting to 255: Freeze when talking to sign,npcs
// Seems to be an index to the script of the map
unknown06: lu16,
// Setting to 0,5,255: No effect it seems
unknown08: u8,
// Setting to 0,5,255: No effect it seems
unknown09: u8,
// Setting to 0: No text on sign, npc says "it seems you can't use it yet."
// Setting to 255: "An error has occurred. Please turn off the power."
// Seems related to text or something
unknown0a: lu16,
// Setting to 0,5,255: No effect it seems
unknown0c: u8,
// Setting to 0,5,255: No effect it seems
unknown0d: u8,
// Setting to 0,5,255: No effect it seems
unknown0e: u8,
// Setting to 0,5,255: No effect it seems
unknown0f: u8,
// Setting to 0,5,255: No effect it seems
unknown10: u8,
// Setting to 0,5,255: No effect it seems
unknown11: u8,
music: lu16,
wild_pokemons: lu16,
// Seems to be related to signs somehow
unknown16: lu16,
// Setting to 0,5,255: No effect it seems
unknown18: u8,
// Setting to 0,5,255: No effect it seems
unknown19: u8,
name_index: u8,
// Setting to 0,5,255: No effect it seems
unknown1b: u8,
// Setting to 0,5,255: No effect it seems
unknown1c: u8,
camera_angle: u8,
// Setting to 0,5,255: No effect it seems
unknown1e: u8,
battle_scene: u8,
// Setting to 0: No effect it seems
// Something related to the map itself. Setting this to 255
// gave a blue void.
unknown20: u8,
// Setting to 0: No effect it seems
// Setting to 5,255: "An error has occurred. Please turn off the power."
unknown21: u8,
// Setting to 0: No effect it seems
// Setting to 5: No effect it seems
// Setting to 255: After loading, "An error has occurred. Please turn off the power."
unknown22: u8,
// Setting to 0: No effect it seems
// Setting to 5,255: After moving "An error has occurred. Please turn off the power."
unknown23: u8,
// Setting to 0,5,255: No effect it seems
unknown24: u8,
// Setting to 0,5,255: No effect it seems
unknown25: u8,
// Setting to 0,5,255: No effect it seems
unknown26: u8,
// Setting to 0,5,255: No effect it seems
unknown27: u8,
// Setting to 0,5,255: No effect it seems
unknown28: u8,
// Setting to 0,5,255: No effect it seems
unknown29: u8,
// Setting to 0,5,255: No effect it seems
unknown2a: u8,
// Setting to 0,5,255: No effect it seems
unknown2b: u8,
// Setting to 0,5,255: No effect it seems
unknown2c: u8,
// Setting to 0,5,255: No effect it seems
unknown2d: u8,
// Setting to 0,5,255: No effect it seems
unknown2e: u8,
// Setting to 0,5,255: No effect it seems
unknown2f: u8,
comptime {
debug.assert(@sizeOf(@This()) == 48);
}
};
const HiddenHollow = extern struct {
pokemons: [8]HollowPokemons,
items: [6]lu16,
comptime {
debug.assert(@sizeOf(@This()) == 220);
}
};
const HollowPokemons = extern struct {
species: [4]lu16,
unknown: [4]lu16,
genders: [4]u8,
forms: [4]u8,
pad: [2]u8,
comptime {
debug.assert(@sizeOf(@This()) == 26);
}
};
const StaticPokemon = struct {
species: *lu16,
level: *lu16,
};
const PokeballItem = struct {
item: *lu16,
amount: *lu16,
};
const EncryptedStringTable = struct {
data: []u8,
fn sectionCount(table: EncryptedStringTable) u16 {
return table.header().sections.value();
}
fn entryCount(table: EncryptedStringTable) u16 {
return table.header().entries.value();
}
fn getEncryptedString(table: EncryptedStringTable, section_i: usize, entry_i: usize) []lu16 {
const section_offset = table.sectionOffsets()[section_i].value();
const entry = table.entries(section_offset)[entry_i];
const offset = section_offset + entry.offset.value();
const res = table.data[offset..][0 .. entry.count.value() * @sizeOf(lu16)];
return mem.bytesAsSlice(lu16, res);
}
const Header = packed struct {
sections: lu16,
entries: lu16,
file_size: lu32,
unknown2: lu32,
};
const Entry = packed struct {
offset: lu32,
count: lu16,
unknown: lu16,
};
fn header(table: EncryptedStringTable) *Header {
return @ptrCast(*Header, table.data[0..@sizeOf(Header)]);
}
fn sectionOffsets(table: EncryptedStringTable) []lu32 {
const h = table.header();
const rest = table.data[@sizeOf(Header)..];
return mem.bytesAsSlice(lu32, rest[0 .. @sizeOf(lu32) * h.sections.value()]);
}
fn entries(table: EncryptedStringTable, section_offset: u32) []Entry {
const h = table.header();
_ = mem.bytesAsValue(lu32, table.data[section_offset..][0..@sizeOf(lu32)]);
const rest = table.data[section_offset + @sizeOf(lu32) ..];
return mem.bytesAsSlice(Entry, rest[0 .. @sizeOf(Entry) * h.entries.value()]);
}
fn size(sections: u32, strings: u32, chars: u32) u32 {
return @sizeOf(Header) + // Header
@sizeOf(lu32) * sections + // Section offsets
@sizeOf(lu32) * sections + // Entry counts
@sizeOf(Entry) * strings + // Entries
strings * @sizeOf(lu16) + // String terminators
chars * @sizeOf(lu16); // String chars
}
};
fn decrypt(data: []const lu16, out: anytype) !u16 {
const H = struct {
fn output(out2: anytype, char: u16) !bool {
const Pair = struct {
len: usize,
codepoint: u21,
};
const pair: Pair = switch (char) {
0xffff => return true,
0x0, 0xf000, 0xfff0...0xfffd => {
try out2.print("\\x{x:0>4}", .{char});
return false;
},
0xfffe => .{ .len = 1, .codepoint = '\n' },
else => .{
.len = unicode.utf8CodepointSequenceLength(char) catch unreachable,
.codepoint = char,
},
};
var buf: [4]u8 = undefined;
_ = try unicode.utf8Encode(pair.codepoint, buf[0..pair.len]);
try out2.writeAll(buf[0..pair.len]);
return false;
}
};
const key = getKey(data);
const table = KeyTable.init(key);
const res = table.get(data.len, 0);
const first = data[0].value() ^ res;
const compressed = first == 0xF100;
const start = @boolToInt(compressed);
var bits: u5 = 0;
var container: u32 = 0;
for (data[start..]) |c, i| {
const decoded = c.value() ^ table.get(data.len, i + start);
if (compressed) {
container |= @as(u32, decoded) << bits;
bits += 16;
while (bits >= 9) : (bits -= 9) {
const char = @intCast(u16, container & 0x1FF);
if (char == 0x1Ff)
return res;
if (try H.output(out, char))
return res;
container >>= 9;
}
} else {
if (try H.output(out, decoded))
return res;
}
}
return res;
}
fn getKey(data: []const lu16) u16 {
const last = data[data.len - 1].value();
debug.assert(last ^ (last ^ 0xFFFF) == 0xFFFF);
return last ^ 0xFFFF;
}
fn encode(data: []const u8, out: anytype) !void {
var n: usize = 0;
while (n < data.len) {
if (mem.startsWith(u8, data[n..], "\n")) {
try out.writeIntLittle(u16, 0xfffe);
n += 1;
continue;
}
if (mem.startsWith(u8, data[n..], "\\x")) {
const hex = data[n + 2 ..][0..4];
const parsed = try fmt.parseUnsigned(u16, hex, 16);
try out.writeIntLittle(u16, parsed);
n += 6;
continue;
}
const ulen = unicode.utf8ByteSequenceLength(data[n]) catch unreachable;
if (data.len < n + ulen)
break;
const codepoint = unicode.utf8Decode(data[n..][0..ulen]) catch unreachable;
try out.writeIntLittle(u16, @intCast(u16, codepoint));
n += ulen;
}
try out.writeIntLittle(u16, 0xffff);
}
fn encrypt(data: []lu16, _key: u16) void {
var key = _key;
for (data) |*c| {
c.* = lu16.init(c.value() ^ key);
key = (key << 3) | (key >> 13);
}
}
const KeyTable = struct {
const table_size = 16;
table: [table_size]u16,
len: usize,
pub fn init(_key: u16) KeyTable {
var table: [table_size]u16 = undefined;
var key = _key;
for (table) |*entry, i| {
entry.* = key;
key = (key >> 3) | (key << 13);
if (key == _key)
return .{ .table = table, .len = i + 1 };
}
unreachable;
}
fn get(table: KeyTable, len: usize, i: usize) u16 {
return table.table[(len - (i + 1)) % table.len];
}
};
// This is the old correct version. We use this for testing the KeyTable
fn keyForI(key: u16, len: usize, i: usize) u16 {
const it = len - (i + 1);
var res: u16 = key;
for (@as([*]void, undefined)[0..it]) |_|
res = (res >> 3) | (res << 13);
return res;
}
test "KeyTable" {
var j: usize = 0;
while (j <= math.maxInt(u16)) : (j += 1)
_ = KeyTable.init(@intCast(u16, j));
for ([_]u16{ 0xf0f0, 0x0f0f, 0xdead, 0xbeef }) |key| {
const table = KeyTable.init(key);
var len: usize = 0;
while (len < 40) : (len += 1) {
var i: usize = 0;
while (i < len) : (i += 1)
try testing.expectEqual(keyForI(key, len, i), table.get(len, i));
}
}
}
pub const StringTable = struct {
file_this_was_extracted_from: u16,
buf: []u8 = &[_]u8{},
keys: []u16 = &[_]u16{},
pub fn create(
allocator: mem.Allocator,
file_this_was_extracted_from: u16,
number_of_strings: usize,
max_string_len: usize,
) !StringTable {
const buf = try allocator.alloc(u8, number_of_strings * max_string_len);
errdefer allocator.free(buf);
const keys = try allocator.alloc(u16, number_of_strings);
errdefer allocator.free(keys);
return StringTable{
.file_this_was_extracted_from = file_this_was_extracted_from,
.buf = buf,
.keys = keys,
};
}
pub fn destroy(table: StringTable, allocator: mem.Allocator) void {
allocator.free(table.buf);
allocator.free(table.keys);
}
pub fn maxStringLen(table: StringTable) usize {
return table.buf.len / table.keys.len;
}
pub fn get(table: StringTable, i: usize) []u8 {
const len = table.maxStringLen();
return table.buf[len * i ..][0..len];
}
pub fn getSpan(table: StringTable, i: usize) []u8 {
const res = table.get(i);
const end = mem.indexOfScalar(u8, res, 0) orelse res.len;
return res[0..end];
}
pub fn encryptedSize(table: StringTable) u32 {
return EncryptedStringTable.size(
1,
@intCast(u32, table.keys.len),
@intCast(u32, table.maxStringLen() * table.keys.len),
);
}
};
pub const Game = struct {
info: offsets.Info,
allocator: mem.Allocator,
rom: *nds.Rom,
owned: Owned,
ptrs: Pointers,
// These fields are owned by the game and will be applied to
// the rom oppon calling `apply`.
pub const Owned = struct {
old_arm_len: usize,
arm9: []u8,
trainer_parties: [][6]PartyMemberBoth,
text: Text,
story: Story,
pub fn deinit(owned: Owned, allocator: mem.Allocator) void {
allocator.free(owned.arm9);
allocator.free(owned.trainer_parties);
owned.text.deinit(allocator);
owned.story.deinit(allocator);
}
};
pub const Text = struct {
type_names: StringTable,
pokemon_names: StringTable,
trainer_names: StringTable,
move_names: StringTable,
ability_names: StringTable,
item_names: StringTable,
map_names: StringTable,
pokedex_category_names: StringTable,
item_names_on_the_ground: StringTable,
item_descriptions: StringTable,
move_descriptions: StringTable,
pub const Array = [std.meta.fields(Text).len]StringTable;
pub fn deinit(text: Text, allocator: mem.Allocator) void {
for (text.asArray()) |table|
table.destroy(allocator);
}
pub fn asArray(text: Text) Array {
var res: Array = undefined;
inline for (std.meta.fields(Text)) |field, i|
res[i] = @field(text, field.name);
return res;
}
};
pub const Story = struct {
starter_choice: StringTable,
pub const Array = [std.meta.fields(Story).len]StringTable;
pub fn deinit(story: Story, allocator: mem.Allocator) void {
for (story.asArray()) |table|
table.destroy(allocator);
}
pub fn asArray(story: Story) Array {
var res: Array = undefined;
inline for (std.meta.fields(Story)) |field, i|
res[i] = @field(story, field.name);
return res;
}
};
// The fields below are pointers into the nds rom and will
// be invalidated oppon calling `apply`.
pub const Pointers = struct {
starters: [3][]*lu16,
moves: []Move,
trainers: []Trainer,
items: []Item,
tms1: []lu16,
hms: []lu16,
tms2: []lu16,
evolutions: []EvolutionTable,
map_headers: []MapHeader,
hidden_hollows: ?[]HiddenHollow,
wild_pokemons: nds.fs.Fs,
pokemons: nds.fs.Fs,
level_up_moves: nds.fs.Fs,
scripts: nds.fs.Fs,
static_pokemons: []StaticPokemon,
given_pokemons: []StaticPokemon,
pokeball_items: []PokeballItem,
pub fn deinit(ptrs: Pointers, allocator: mem.Allocator) void {
for (ptrs.starters) |starter_ptrs|
allocator.free(starter_ptrs);
allocator.free(ptrs.static_pokemons);
allocator.free(ptrs.given_pokemons);
allocator.free(ptrs.pokeball_items);
}
};
pub fn identify(reader: anytype) !offsets.Info {
const header = try reader.readStruct(nds.Header);
for (offsets.infos) |info| {
//if (!mem.eql(u8, info.game_title, game_title))
// continue;
if (!mem.eql(u8, &info.gamecode, &header.gamecode))
continue;
return info;
}
return error.UnknownGame;
}
pub fn fromRom(allocator: mem.Allocator, nds_rom: *nds.Rom) !Game {
const file_system = nds_rom.fileSystem();
const info = try identify(io.fixedBufferStream(nds_rom.data.items).reader());
const arm9 = try nds.blz.decode(allocator, nds_rom.arm9());
errdefer allocator.free(arm9);
const text = try file_system.openNarc(nds.fs.root, info.text);
const story = try file_system.openNarc(nds.fs.root, info.story);
const trainers = try (try file_system.openNarc(nds.fs.root, info.trainers)).toSlice(1, Trainer);
const trainer_parties_narc = try file_system.openNarc(nds.fs.root, info.parties);
const trainer_parties = try allocator.alloc([6]PartyMemberBoth, trainer_parties_narc.fat.len);
errdefer allocator.free(trainer_parties);
for (trainer_parties) |*party, i| {
const party_data = trainer_parties_narc.fileData(.{ .i = @intCast(u32, i) });
const party_size = if (i != 0 and i - 1 < trainers.len) trainers[i - 1].party_size else 0;
var j: usize = 0;
while (j < party_size) : (j += 1) {
const base = trainers[i - 1].partyMember(party_data, j) orelse break;
party[j].base = base.*;
switch (trainers[i - 1].party_type) {
.none => {
party[j].item = lu16.init(0);
party[j].moves = [_]lu16{lu16.init(0)} ** 4;
},
.item => {
party[j].item = base.toParent(PartyMemberItem).item;
party[j].moves = [_]lu16{lu16.init(0)} ** 4;
},
.moves => {
party[j].item = lu16.init(0);
party[j].moves = base.toParent(PartyMemberMoves).moves;
},
.both => {
const member = base.toParent(PartyMemberBoth);
party[j].item = member.item;
party[j].moves = member.moves;
},
}
}
mem.set(PartyMemberBoth, party[party_size..], PartyMemberBoth{});
}
const type_names = try decryptStringTable(allocator, 8, text, info.type_names);
errdefer type_names.destroy(allocator);
const pokemon_names = try decryptStringTable(allocator, 16, text, info.pokemon_names);
errdefer pokemon_names.destroy(allocator);
const item_names = try decryptStringTable(allocator, 16, text, info.item_names);
errdefer item_names.destroy(allocator);
const ability_names = try decryptStringTable(allocator, 16, text, info.ability_names);
errdefer ability_names.destroy(allocator);
const move_names = try decryptStringTable(allocator, 16, text, info.move_names);
errdefer move_names.destroy(allocator);
const trainer_names = try decryptStringTable(allocator, 16, text, info.trainer_names);
errdefer trainer_names.destroy(allocator);
const map_names = try decryptStringTable(allocator, 32, text, info.map_names);
errdefer map_names.destroy(allocator);
const pokedex_category_names = try decryptStringTable(allocator, 32, text, info.pokedex_category_names);
errdefer pokedex_category_names.destroy(allocator);
const item_names_on_the_ground = try decryptStringTable(allocator, 64, text, info.item_names_on_the_ground);
errdefer item_names_on_the_ground.destroy(allocator);
const item_descriptions = try decryptStringTable(allocator, 128, text, info.item_descriptions);
errdefer item_descriptions.destroy(allocator);
const move_descriptions = try decryptStringTable(allocator, 256, text, info.move_descriptions);
errdefer move_descriptions.destroy(allocator);
const starter_choice = try decryptStringTable(allocator, 256 * 2, story, info.starter_choice);
errdefer starter_choice.destroy(allocator);
return fromRomEx(allocator, nds_rom, info, .{
.old_arm_len = nds_rom.arm9().len,
.arm9 = arm9,
.trainer_parties = trainer_parties,
.text = .{
.map_names = map_names,
.type_names = type_names,
.item_descriptions = item_descriptions,
.item_names_on_the_ground = item_names_on_the_ground,
.item_names = item_names,
.ability_names = ability_names,
.move_descriptions = move_descriptions,
.move_names = move_names,
.trainer_names = trainer_names,
.pokedex_category_names = pokedex_category_names,
.pokemon_names = pokemon_names,
},
.story = .{
.starter_choice = starter_choice,
},
});
}
pub fn fromRomEx(
allocator: mem.Allocator,
nds_rom: *nds.Rom,
info: offsets.Info,
owned: Owned,
) !Game {
const arm9 = owned.arm9;
const file_system = nds_rom.fileSystem();
const hm_tm_prefix_index = mem.indexOf(u8, arm9, offsets.hm_tm_prefix) orelse return error.CouldNotFindTmsOrHms;
const hm_tm_index = hm_tm_prefix_index + offsets.hm_tm_prefix.len;
const hm_tm_len = (offsets.tm_count + offsets.hm_count) * @sizeOf(u16);
const hm_tms = mem.bytesAsSlice(lu16, arm9[hm_tm_index..][0..hm_tm_len]);
const map_file = try file_system.openNarc(nds.fs.root, info.map_file);
const scripts = try file_system.openNarc(nds.fs.root, info.scripts);
const commands = try findScriptCommands(scripts, allocator);
errdefer {
allocator.free(commands.static_pokemons);
allocator.free(commands.given_pokemons);
allocator.free(commands.pokeball_items);
}
const map_header_bytes = map_file.fileData(.{ .i = info.map_headers });
return Game{
.info = info,
.allocator = allocator,
.rom = nds_rom,
.owned = owned,
.ptrs = .{
.starters = blk: {
var res: [3][]*lu16 = undefined;
var filled: usize = 0;
errdefer for (res[0..filled]) |item|
allocator.free(item);
for (info.starters) |offs, i| {
res[i] = try allocator.alloc(*lu16, offs.len);
filled += 1;
for (offs) |offset, j| {
const fat = scripts.fat[offset.file];
const file_data = scripts.data[fat.start.value()..fat.end.value()];
res[i][j] = mem.bytesAsValue(lu16, file_data[offset.offset..][0..2]);
}
}
break :blk res;
},
.moves = try (try file_system.openNarc(nds.fs.root, info.moves)).toSlice(0, Move),
.trainers = try (try file_system.openNarc(nds.fs.root, info.trainers)).toSlice(1, Trainer),
.items = try (try file_system.openNarc(nds.fs.root, info.itemdata)).toSlice(0, Item),
.evolutions = try (try file_system.openNarc(nds.fs.root, info.evolutions)).toSlice(0, EvolutionTable),
.map_headers = mem.bytesAsSlice(MapHeader, map_header_bytes[0..]),
.tms1 = hm_tms[0..92],
.hms = hm_tms[92..98],
.tms2 = hm_tms[98..],
.static_pokemons = commands.static_pokemons,
.given_pokemons = commands.given_pokemons,
.pokeball_items = commands.pokeball_items,
.wild_pokemons = try file_system.openNarc(nds.fs.root, info.wild_pokemons),
.pokemons = try file_system.openNarc(nds.fs.root, info.pokemons),
.level_up_moves = try file_system.openNarc(nds.fs.root, info.level_up_moves),
.hidden_hollows = if (info.hidden_hollows) |h| try (try file_system.openNarc(nds.fs.root, h)).toSlice(0, HiddenHollow) else null,
.scripts = scripts,
},
};
}
pub fn apply(game: *Game) !void {
game.updateStarterDialog();
try game.applyArm9();
try game.applyTrainerParties();
try game.applyStrings(&game.owned.story.asArray(), game.info.story);
try game.applyStrings(&game.owned.text.asArray(), game.info.text);
game.ptrs.deinit(game.allocator);
game.* = try fromRomEx(
game.allocator,
game.rom,
game.info,
game.owned,
);
}
fn updateStarterDialog(game: Game) void {
for (game.ptrs.starters) |starter_ptrs, i| {
const starter = starter_ptrs[0].value();
const index = game.info.starter_choice_indexs[i];
const text = game.owned.story.starter_choice.get(index);
mem.set(u8, text, 0);
const starter_name = game.owned.text.pokemon_names.getSpan(starter);
mem.copy(u8, text, starter_name);
}
}
fn applyArm9(game: Game) !void {
const arm9 = try nds.blz.encode(game.allocator, game.owned.arm9, 0x4000);
defer game.allocator.free(arm9);
// In the secure area, there is an offset that points to the end of the compressed arm9.
// We have to find that offset and replace it with the new size.
const secure_area = arm9[0..0x4000];
var len_bytes: [3]u8 = undefined;
mem.writeIntLittle(u24, &len_bytes, @intCast(u24, game.owned.old_arm_len + 0x4000));
if (mem.indexOf(u8, secure_area, &len_bytes)) |off| {
mem.writeIntLittle(
u24,
secure_area[off..][0..3],
@intCast(u24, arm9.len + 0x4000),
);
}
mem.copy(
u8,
try game.rom.resizeSection(game.rom.arm9(), arm9.len),
arm9,
);
}
/// Applies the `trainer_parties` owned field to the rom.
fn applyTrainerParties(game: Game) !void {
const FullParty = [6]PartyMemberBoth;
const full_party_size = @sizeOf(FullParty);
const PNone = PartyMemberNone;
const PItem = PartyMemberItem;
const PMoves = PartyMemberMoves;
const file_system = game.rom.fileSystem();
const trainer_parties_narc = try file_system.openFileData(nds.fs.root, game.info.parties);
const trainer_parties = game.owned.trainer_parties;
const content_size = @sizeOf(FullParty) *
trainer_parties.len;
const size = nds.fs.narcSize(trainer_parties.len, content_size);
const buf = try game.rom.resizeSection(trainer_parties_narc, size);
const trainers = try (try file_system.openNarc(nds.fs.root, game.info.trainers)).toSlice(1, Trainer);
var builder = nds.fs.SimpleNarcBuilder.init(buf, trainer_parties.len);
// We make sure that the new narc we create always has room for a full
// party for all trainers. By doing this, all future applies can always
// be done inline, and allocations can be avoided. This also makes patches
// generated simpler.
for (builder.fat()) |*f, i|
f.* = nds.Range.init(full_party_size * i, full_party_size * (i + 1));
for (trainer_parties) |party, i| {
const party_type = if (i != 0 and i - 1 < trainers.len) trainers[i - 1].party_type else .none;
const rest = buf[builder.stream.pos + i * full_party_size ..];
switch (party_type) {
.none => {
for (mem.bytesAsSlice(PNone, rest[0..@sizeOf([6]PNone)])) |*m, j| {
m.* = PartyMemberNone{ .base = party[j].base };
}
mem.set(u8, rest[@sizeOf([6]PNone)..full_party_size], 0);
},
.item => {
for (mem.bytesAsSlice(PItem, rest[0..@sizeOf([6]PItem)])) |*m, j| {
m.* = PartyMemberItem{
.base = party[j].base,
.item = party[j].item,
};
}
mem.set(u8, rest[@sizeOf([6]PItem)..full_party_size], 0);
},
.moves => {
for (mem.bytesAsSlice(PMoves, rest[0..@sizeOf([6]PMoves)])) |*m, j| {
m.* = PartyMemberMoves{
.base = party[j].base,
.moves = party[j].moves,
};
}
mem.set(u8, rest[@sizeOf([6]PMoves)..full_party_size], 0);
},
.both => mem.bytesAsValue(FullParty, rest[0..full_party_size]).* = party,
}
}
_ = builder.finish();
}
/// Applies all decrypted strings to the game.
fn applyStrings(game: Game, strings: []const StringTable, string_file: []const u8) !void {
const buf = blk: {
const file_system = game.rom.fileSystem();
const text_bytes = try file_system.openFileData(nds.fs.root, string_file);
const text = try nds.fs.Fs.fromNarc(text_bytes);
// We then calculate the size of the content for our new narc
var extra_bytes: usize = 0;
for (strings) |table| {
extra_bytes += math.sub(
u32,
table.encryptedSize(),
text.fat[table.file_this_was_extracted_from].len(),
) catch 0;
}
break :blk try game.rom.resizeSection(
text_bytes,
text_bytes.len + extra_bytes,
);
};
const text = try nds.fs.Fs.fromNarc(buf);
for (strings) |table| {
const new_file_size = table.encryptedSize();
const file = &text.fat[table.file_this_was_extracted_from];
const file_needs_a_resize = file.len() < new_file_size;
if (file_needs_a_resize) {
const extra = new_file_size - file.len();
mem.copyBackwards(
u8,
text.data[file.end.value() + extra ..],
text.data[file.end.value() .. text.data.len - extra],
);
const old_file_end = file.end.value();
file.* = nds.Range.init(file.start.value(), file.end.value() + extra);
for (text.fat) |*f| {
const start = f.start.value();
const end = f.end.value();
const file_is_before_the_file_we_moved = start < old_file_end;
if (file_is_before_the_file_we_moved)
continue;
f.* = nds.Range.init(start + extra, end + extra);
}
}
const Header = EncryptedStringTable.Header;
const Entry = EncryptedStringTable.Entry;
const bytes = text.data[file.start.value()..file.end.value()];
debug.assert(bytes.len == new_file_size);
// Non of the writes here can fail as long as we calculated the size
// of the file correctly above
const writer = io.fixedBufferStream(bytes).writer();
const number_of_entries = @intCast(u16, table.keys.len);
writer.writeAll(&mem.toBytes(Header{
.sections = lu16.init(1),
.entries = lu16.init(number_of_entries),
.file_size = lu32.init(new_file_size),
.unknown2 = lu32.init(0),
})) catch unreachable;
const chars_per_entry = table.maxStringLen() + 1; // Always make room for a terminator
const bytes_per_entry = chars_per_entry * 2;
const start_of_section = @sizeOf(Header) + @sizeOf(lu32);
writer.writeIntLittle(u32, start_of_section) catch unreachable;
writer.writeIntLittle(u32, @intCast(u32, number_of_entries *
(@sizeOf(Entry) + bytes_per_entry))) catch unreachable;
const start_of_entry_table = writer.context.pos;
for (@as([*]void, undefined)[0..number_of_entries]) |_| {
writer.writeAll(&mem.toBytes(Entry{
.offset = lu32.init(0),
.count = lu16.init(0),
.unknown = lu16.init(0),
})) catch unreachable;
}
const entries = mem.bytesAsSlice(Entry, bytes[start_of_entry_table..writer.context.pos]);
for (entries) |*entry, j| {
const start_of_str = writer.context.pos;
const str = table.getSpan(j);
try encode(str, writer);
const end_of_str = writer.context.pos;
const encoded_str = mem.bytesAsSlice(lu16, bytes[start_of_str..end_of_str]);
encrypt(encoded_str, table.keys[j]);
const length_of_str = @intCast(u16, (end_of_str - start_of_str) / 2);
entry.offset = lu32.init(@intCast(u32, start_of_str - start_of_section));
entry.count = lu16.init(length_of_str);
// Pad the string, so that each entry is always entry_size
// apart. This ensure that patches generated from tm35-apply
// are small.
writer.writeByteNTimes(0, (chars_per_entry - length_of_str) * 2) catch unreachable;
debug.assert(writer.context.pos - start_of_str == bytes_per_entry);
}
// Assert that we got the file size right.
debug.assert(writer.context.pos == bytes.len);
}
}
pub fn deinit(game: Game) void {
game.owned.deinit(game.allocator);
game.ptrs.deinit(game.allocator);
}
const ScriptCommands = struct {
static_pokemons: []StaticPokemon,
given_pokemons: []StaticPokemon,
pokeball_items: []PokeballItem,
};
fn findScriptCommands(scripts: nds.fs.Fs, allocator: mem.Allocator) !ScriptCommands {
var static_pokemons = std.ArrayList(StaticPokemon).init(allocator);
errdefer static_pokemons.deinit();
var given_pokemons = std.ArrayList(StaticPokemon).init(allocator);
errdefer given_pokemons.deinit();
var pokeball_items = std.ArrayList(PokeballItem).init(allocator);
errdefer pokeball_items.deinit();
var script_offsets = std.ArrayList(usize).init(allocator);
defer script_offsets.deinit();
var set_var_offsets = std.ArrayList(usize).init(allocator);
defer set_var_offsets.deinit();
var given_pokemons_to_resolve = std.AutoArrayHashMap(usize, *lu16).init(allocator);
defer given_pokemons_to_resolve.deinit();
for (scripts.fat) |fat| {
const script_data = scripts.data[fat.start.value()..fat.end.value()];
defer script_offsets.shrinkRetainingCapacity(0);
defer set_var_offsets.shrinkRetainingCapacity(0);
defer given_pokemons_to_resolve.shrinkRetainingCapacity(0);
for (script.getScriptOffsets(script_data)) |relative, i| {
const position = @intCast(isize, i + 1) * @sizeOf(lu32);
const offset = math.cast(usize, relative.value() + position) orelse continue;
if (script_data.len < offset)
continue;
try script_offsets.append(offset);
}
var offset_i: usize = 0;
while (offset_i < script_offsets.items.len) : (offset_i += 1) {
const offset = script_offsets.items[offset_i];
var command_offset = offset;
var decoder = script.CommandDecoder{
.bytes = script_data,
.i = offset,
};
while (decoder.next() catch continue) |command| : (command_offset = decoder.i) {
switch (command.toZigUnion()) {
.wild_battle => |battle| try static_pokemons.append(.{
.species = &battle.species,
.level = &battle.level,
}),
.wild_battle_store_result => |battle| try static_pokemons.append(.{
.species = &battle.species,
.level = &battle.level,
}),
.give_pokemon_1 => |given| if (given.species.value() & 0x8000 == 0) {
try given_pokemons.append(.{
.species = &given.species,
.level = &given.level,
});
} else {
try given_pokemons_to_resolve.put(
given.species.value(),
&given.level,
);
},
.give_pokemon_2 => |given| if (given.species.value() & 0x8000 == 0) {
try given_pokemons.append(.{
.species = &given.species,
.level = &given.level,
});
} else {
try given_pokemons_to_resolve.put(
given.species.value(),
&given.level,
);
},
.give_pokemon_4 => |given| if (given.species.value() & 0x8000 == 0) {
try given_pokemons.append(.{
.species = &given.species,
.level = &given.level,
});
} else {
try given_pokemons_to_resolve.put(
given.species.value(),
&given.level,
);
},
.set_var_eq_val,
.set_var_2a,
=> try set_var_offsets.append(command_offset),
.jump, .@"if", .call_routine => {
const off = switch (command.toZigUnion()) {
.jump => |jump| jump.offset.value(),
.@"if" => |if_| if_.offset.value(),
.call_routine => |call| call.offset.value(),
else => unreachable,
};
if (math.cast(usize, off + @intCast(isize, decoder.i))) |loc| {
if (loc < script_data.len and
mem.indexOfScalar(usize, script_offsets.items, loc) == null)
try script_offsets.append(loc);
}
},
else => {},
}
}
}
for (set_var_offsets.items) |offset| {
var decoder = script.CommandDecoder{
.bytes = script_data,
.i = @intCast(usize, offset),
};
const first = (decoder.next() catch unreachable).?;
switch (first.toZigUnion()) {
.set_var_eq_val => |set| if (given_pokemons_to_resolve.get(set.container.value())) |level| {
try given_pokemons.append(.{
.species = &set.value,
.level = level,
});
} else {
const item = set;
const amount = script.expectNext(&decoder, .set_var_eq_val) orelse continue;
_ = script.expectNext(&decoder, .call_routine) orelse continue;
_ = script.expectNext(&decoder, .wait_moment) orelse continue;
_ = script.expectNext(&decoder, .unlock_all) orelse continue;
_ = script.expectNext(&decoder, .end) orelse continue;
if (item.container.value() != 32780 or
amount.data().set_var_eq_val.container.value() != 32781)
continue;
try pokeball_items.append(.{
.item = &item.value,
.amount = &amount.data().set_var_eq_val.value,
});
},
.set_var_2a => |item| {
const amount = script.expectNext(&decoder, .set_var_2a) orelse continue;
const unknown = script.expectNext(&decoder, .set_var_2a) orelse continue;
_ = script.expectNext(&decoder, .call_std) orelse continue;
_ = script.expectNext(&decoder, .wait_moment) orelse continue;
_ = script.expectNext(&decoder, .unlock_all) orelse continue;
_ = script.expectNext(&decoder, .end) orelse continue;
if (item.container.value() != 32768 or
amount.data().set_var_2a.container.value() != 32769 or
unknown.data().set_var_2a.container.value() != 32770)
continue;
try pokeball_items.append(.{
.item = &item.value,
.amount = &amount.data().set_var_2a.value,
});
},
else => {},
}
}
}
return ScriptCommands{
.static_pokemons = static_pokemons.toOwnedSlice(),
.given_pokemons = given_pokemons.toOwnedSlice(),
.pokeball_items = pokeball_items.toOwnedSlice(),
};
}
fn decryptStringTable(allocator: mem.Allocator, max_string_len: usize, text: nds.fs.Fs, file: u16) !StringTable {
const table = EncryptedStringTable{ .data = text.fileData(.{ .i = file }) };
debug.assert(table.sectionCount() == 1);
const count = table.entryCount();
const res = try StringTable.create(
allocator,
file,
count,
max_string_len,
);
errdefer res.destroy(allocator);
mem.set(u8, res.buf, 0);
for (res.keys) |*key, i| {
const buf = res.get(i);
const writer = io.fixedBufferStream(buf).writer();
const encrypted_string = table.getEncryptedString(0, i);
key.* = try decrypt(encrypted_string, writer);
}
return res;
}
};
|
src/core/gen5.zig
|
const std = @import("std");
const fmt = std.fmt;
const math = std.math;
// The test input uses 12-bit numbers.
const Number = u12;
// The test input has 1000 lines. We can count up to that in `u16`.
const Count = u16;
pub fn run(input: anytype, output: anytype) !void {
// Build a binary max heap where a left branch indicates a 0 bit, a right
// branch indicates a 1 bit, and node values count numbers with that prefix.
var heap = [_]Count{0} ** (2 << @bitSizeOf(Number));
var i: usize = 0;
while (true) {
const byte = input.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => |e| return e,
};
heap[i] += 1;
switch (byte) {
'0' => i = i * 2 + 1,
'1' => i = i * 2 + 2,
'\n' => i = 0,
else => return error.InvalidInput,
}
}
// Calculate gamma by taking the sum of the left (zero) children along each
// row and checking if it's less than half the total count. If so, then it's
// less than the sum of the right children, and the mode is 1. Otherwise, 0.
const half_total_count = heap[0] / 2;
var gamma: Number = 0;
i = 1;
while (i < heap.len - 1) {
var zero_count: Count = 0;
const end = i * 2;
while (i < end) : (i += 2) {
zero_count += heap[i];
}
const mode = @boolToInt(zero_count <= half_total_count);
gamma = gamma << 1 | mode;
}
// Epsilon is just the bitwise NOT of gamma. To calculate the product of
// gamma and epsilon, we need more bits to avoid overflow.
const epsilon = ~gamma;
const power_consumption = @as(u64, gamma) * @as(u64, epsilon);
// Part 1:
try fmt.format(output, "{}\n", .{power_consumption});
// Calculate the oxygen generator rating and CO2 scrubber rating by
// descending down the heap, taking the most/least common branch each time.
var oxygen: u64 = 0;
i = 0;
while (i < heap.len / 2) {
const left = i * 2 + 1;
const right = i * 2 + 2;
const bit = bitCriteria(heap[left], heap[right], .gt, 1);
oxygen = oxygen << 1 | bit;
i = left + bit;
}
var co2: u64 = 0;
i = 0;
while (i < heap.len / 2) {
const left = i * 2 + 1;
const right = i * 2 + 2;
const bit = bitCriteria(heap[left], heap[right], .lt, 0);
co2 = co2 << 1 | bit;
i = left + bit;
}
const life_support_rating = oxygen * co2;
// Part 2:
try fmt.format(output, "{}\n", .{life_support_rating});
}
// Given the counts `c0`/`c1` of numbers with a 0/1 bit, return the one that
// compares `op` to the other, or `default` if they are the same. If `c0` or
// `c1` is zero, considers it an unset node and returns the other branch.
fn bitCriteria(c0: Count, c1: Count, op: math.CompareOperator, default: u1) u1 {
if (c0 == 0 and c1 == 0) unreachable;
if (c0 == 0) return 1;
if (c1 == 0) return 0;
if (c0 == c1) return default;
if (math.compare(c0, op, c1)) return 0;
return 1;
}
|
src/zig/2021_03.zig
|
const std = @import("std");
const daemon = @import("daemon.zig");
const util = @import("util.zig");
const DaemonState = daemon.DaemonState;
const ServiceDecl = daemon.ServiceDecl;
const Service = daemon.Service;
const ServiceStateType = daemon.ServiceStateType;
const ServiceLogger = @import("service_logger.zig").ServiceLogger;
pub const SupervisorContext = struct {
state: *DaemonState,
service: *Service,
};
const RECONN_RETRY_CAP = 1000;
const RECONN_RETRY_BASE = 700;
pub fn superviseProcess(ctx: SupervisorContext) !void {
var state = ctx.state;
var allocator = state.allocator;
var service = ctx.service;
state.logger.info("supervisor start\n", .{});
var argv = std.ArrayList([]const u8).init(allocator);
defer argv.deinit();
var path_it = std.mem.split(ctx.service.cmdline, " ");
while (path_it.next()) |component| {
try argv.append(component);
}
state.logger.info("sup:{}: arg0 = {}\n", .{ ctx.service.name, argv.items[0] });
var retries: u32 = 0;
while (!service.stop_flag) {
state.logger.info("trying to start service '{}'", .{ctx.service.name});
var proc = try std.ChildProcess.init(argv.items, allocator);
proc.stdout_behavior = .Pipe;
proc.stderr_behavior = .Pipe;
state.logger.info("service '{}' spawn", .{ctx.service.name});
try proc.spawn();
// spawn thread for logging of stderr and stdout
var logger_pipe = try std.os.pipe();
defer std.os.close(logger_pipe[0]);
defer std.os.close(logger_pipe[1]);
var file = std.fs.File{ .handle = logger_pipe[1] };
var stream = file.outStream();
var serializer = daemon.MsgSerializer.init(stream);
_ = std.Thread.spawn(ServiceLogger.Context{
.state = ctx.state,
.service = ctx.service,
.stdout = proc.stdout.?.handle,
.stderr = proc.stderr.?.handle,
.message_fd = logger_pipe[0],
}, ServiceLogger.handler) catch |err| {
state.logger.info("Failed to start logging thread: {}", .{err});
};
state.pushMessage(.{
.ServiceStarted = .{
.name = ctx.service.name,
.pid = proc.pid,
.stdout = proc.stdout.?,
.stderr = proc.stderr.?,
.logger_thread = logger_pipe[1],
},
}) catch |err| {
state.logger.info("Failed to send started message to daemon: {}", .{err});
};
state.logger.info("service '{}' wait", .{ctx.service.name});
const term_result = try proc.wait();
state.logger.info("service '{}' waited result {}", .{ ctx.service.name, term_result });
// we don't care about the status of the process if we're here,
// since it exited already, we must destroy the threads
// we made for stdout/err
ServiceLogger.stopLogger(logger_pipe[1]) catch |err| {
state.logger.info("Failed to signal logger thread to stop: {}", .{err});
};
var exit_code: u32 = undefined;
switch (term_result) {
.Exited, .Signal, .Stopped, .Unknown => |term_code| {
exit_code = term_code;
// reset retry count when the program exited cleanly
if (exit_code == 0) retries = 0;
state.pushMessage(.{
.ServiceExited = .{ .name = ctx.service.name, .exit_code = exit_code },
}) catch |err| {
state.logger.info("Failed to send exited message to daemon.", .{});
};
},
else => unreachable,
}
// if the service is set to stop, we shouldn't try to wait and then
// stop our loop. stop as soon as possible.
// this prevents the supervisor thread from living more than it should
state.logger.info("service '{}' stop? {}", .{ ctx.service.name, service.stop_flag });
if (service.stop_flag) break;
// calculations are done in the millisecond range
const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp()));
var r = std.rand.DefaultPrng.init(seed);
const sleep_ms = r.random.uintLessThan(
u32,
std.math.min(
@as(u32, RECONN_RETRY_CAP),
@as(u32, RECONN_RETRY_BASE * std.math.pow(u32, @as(u32, 2), retries)),
),
);
const sleep_ns = sleep_ms * std.time.ns_per_ms;
const clock_ts = util.monotonicRead();
state.pushMessage(.{
.ServiceRestarting = .{
.name = ctx.service.name,
.exit_code = exit_code,
.clock_ts_ns = clock_ts,
.sleep_ns = sleep_ns,
},
}) catch |err| {
state.logger.info("Failed to send restarting message to daemon: {}", .{err});
};
std.debug.warn("sleeping '{}' for {}ms\n", .{ ctx.service.name, sleep_ms });
std.time.sleep(sleep_ns);
std.debug.warn("slept '{}' for {}ms. stop_flag={}\n", .{ ctx.service.name, sleep_ms, service.stop_flag });
retries += 1;
}
}
|
src/supervisor.zig
|
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
pub const DisplayInfo = struct {
unix: bool,
host: []const u8,
display: u6,
screen: u8,
pub fn init(allocator: *Allocator, host_override: ?[]const u8, display_override: ?u6, screen_override: ?u8) !DisplayInfo {
// If everything is fixed, just return it verbatim without bothering with reading DISPLAY
if (host_override != null and display_override != null and screen_override != null) {
return DisplayInfo{
.unix = if (@hasDecl(std.os, "sockaddr_un") and (std.mem.eql(u8, "localhost", host_override.?) or host_override.?.len == 0)) true else false,
.host = host_override.?,
.display = display_override.?,
.screen = screen_override.?,
};
}
// Get the DISPLAY env variable
const DISPLAY = blk: {
if (builtin.os.tag == .windows) {
const display_w = std.os.getenvW(std.unicode.utf8ToUtf16LeStringLiteral("DISPLAY")) orelse break :blk ":0";
break :blk std.unicode.utf16leToUtf8Alloc(allocator, display_w[0..]) catch break :blk ":0";
} else {
if (std.os.getenv("DISPLAY")) |d|
break :blk d;
}
break :blk ":0";
};
// Parse the host, display, and screen
const colon = std.mem.indexOfScalar(u8, DISPLAY, ':') orelse return error.MalformedDisplay;
const host = if (host_override != null) host_override.? else DISPLAY[0..colon];
const unix = if (builtin.os.tag != .windows and @hasDecl(std.os, "sockaddr_un") and (std.mem.eql(u8, "localhost", host) or host.len == 0)) true else false;
const dot = std.mem.indexOfScalar(u8, DISPLAY[colon..], '.');
if (dot != null and dot.? == 1) return error.MalformedDisplay;
const display = if (display_override != null) display_override.? else if (dot != null) try std.fmt.parseUnsigned(u6, DISPLAY[colon + 1 .. colon + dot.?], 10) else try std.fmt.parseUnsigned(u6, DISPLAY[colon + 1 ..], 10);
const screen = if (screen_override != null) screen_override.? else if (dot != null) try std.fmt.parseUnsigned(u8, DISPLAY[colon + dot.? + 1 ..], 10) else 0;
var self = DisplayInfo{
.unix = unix,
.host = host,
.display = display,
.screen = screen,
};
return self;
}
};
|
didot-zwl/zwl/src/x11/display_info.zig
|
const std = @import("std");
const warn = std.debug.print;
const Allocator = std.mem.Allocator;
const util = @import("./util.zig");
const filter_lib = @import("./filter.zig");
const toot_lib = @import("./toot.zig");
const toot_list = @import("./toot_list.zig");
var allocator: *Allocator = undefined;
const c = @cImport({
@cInclude("time.h");
});
pub const Time = c.time_t;
// contains runtime-only values
pub const Settings = struct {
win_x: i64,
win_y: i64,
columns: std.ArrayList(*ColumnInfo),
config_path: []const u8,
};
// on-disk config
pub const ConfigFile = struct {
win_x: i64,
win_y: i64,
columns: []*ColumnConfig,
};
pub const ColumnInfo = struct {
config: *ColumnConfig,
filter: *filter_lib.ptree,
toots: toot_list.TootList,
refreshing: bool,
last_check: Time,
inError: bool,
account: ?std.StringHashMap(std.json.Value),
oauthClientId: ?[]const u8,
oauthClientSecret: ?[]const u8,
const Self = @This();
pub fn reset(self: *const Self) void { _ = self; }
pub fn parseFilter(self: *const Self, filter: []const u8) void {
self.filter = filter_lib.parse(filter);
}
pub fn makeTitle(column: *ColumnInfo) []const u8 {
var out: []const u8 = column.filter.host();
if (column.config.token) |tkn| {
_ = tkn ;
var addon: []const u8 = undefined;
if (column.account) |account| {
addon = account.get("acct").?.String;
} else {
addon = "_";
}
out = std.fmt.allocPrint(allocator, "{}@{}", .{ addon, column.filter.host() }) catch unreachable;
}
return out;
}
};
pub const ColumnConfig = struct {
title: []const u8,
filter: []const u8,
token: ?[]const u8,
img_only: bool,
const Self = @This();
};
pub const LoginInfo = struct {
username: []const u8,
password: []const u8,
};
pub const HttpInfo = struct {
url: []const u8,
verb: enum {
get,
post,
},
token: ?[]const u8,
post_body: []const u8,
body: []const u8,
content_type: []const u8,
response_code: c_long,
tree: std.json.ValueTree,
column: *ColumnInfo,
toot: *toot_lib.Type,
};
pub const ColumnAuth = struct {
code: []const u8,
column: *ColumnInfo,
};
const ConfigError = error{MissingParams};
pub fn init(alloc: *Allocator) !void {
allocator = alloc;
}
pub fn readfile(filename: []const u8) !Settings {
if (std.fs.cwd().createFile(filename, .{ .exclusive = true })) |*file| {
try file.writeAll("{}\n");
warn("Warning: creating new {}\n", .{filename});
file.close();
} else {} // existing file is OK
var json = try std.fs.cwd().readFileAlloc(allocator, filename, 65535); //max_size?
return read(json);
}
pub fn read(json: []const u8) !Settings {
var json_parser = std.json.Parser.init(allocator, false);
var value_tree = try json_parser.parse(json);
var settings = allocator.create(Settings) catch unreachable;
var root = value_tree.root.Object;
settings.columns = std.ArrayList(*ColumnInfo).init(allocator);
if (root.get("win_x")) |w| {
warn("config: win_x\n", .{});
settings.win_x = w.Integer;
} else {
settings.win_x = 800;
}
if (root.get("win_y")) |h| {
warn("config: win_y\n", .{});
settings.win_y = h.Integer;
} else {
settings.win_y = 600;
}
if (root.get("columns")) |columns| {
warn("config: columns {}\n", .{columns.Array.items.len});
for (columns.Array.items) |value| {
var colInfo = allocator.create(ColumnInfo) catch unreachable;
colInfo.reset();
colInfo.toots = toot_list.TootList.init();
var colconfig = allocator.create(ColumnConfig) catch unreachable;
colInfo.config = colconfig;
var title = value.Object.get("title").?.String;
colInfo.config.title = title;
var filter = value.Object.get("filter").?.String;
colInfo.config.filter = filter;
colInfo.filter = filter_lib.parse(allocator, filter);
var tokenTag = value.Object.get("token");
if (tokenTag) |tokenKV| {
if (@TypeOf(tokenKV) == []const u8) {
colInfo.config.token = tokenKV.value.String;
} else {
colInfo.config.token = null;
}
} else {
colInfo.config.token = null;
}
var img_only = value.Object.get("img_only").?.Bool;
colInfo.config.img_only = img_only;
settings.columns.append(colInfo) catch unreachable;
}
} else {
warn("missing columns\n", .{});
}
return settings.*;
}
pub fn writefile(settings: Settings, filename: []const u8) void {
var configFile = allocator.create(ConfigFile) catch unreachable;
configFile.win_x = settings.win_x;
configFile.win_y = settings.win_y;
var column_infos = std.ArrayList(*ColumnConfig).init(allocator);
for (settings.columns.items) |column| {
column_infos.append(column.config) catch unreachable;
}
configFile.columns = column_infos.items;
if (std.fs.cwd().createFile(filename, .{ .truncate = true })) |*file| {
warn("config.write toJson\n", .{});
std.json.stringify(configFile, std.json.StringifyOptions{}, file.writer()) catch unreachable;
warn("config saved. {} {} bytes\n", .{ filename, file.getPos() });
file.close();
} else |err| {
warn("config save fail. {}\n", .{err});
} // existing file is OK
}
pub fn now() Time {
var t: Time = undefined;
_ = c.time(&t);
return t;
}
const assert = @import("std").debug.assert;
test "read" {
var ret = read("{\"url\":\"abc\"}");
if (ret) {
assert(true);
} else |err| {
warn("warn: {}\n", .{err});
assert(false);
}
}
|
src/config.zig
|
const std = @import("std");
const builtin = @import("builtin");
const zee_alloc = @import("zee_alloc");
const Fundude = @import("main.zig");
const util = @import("util.zig");
const CYCLES_PER_MS = Fundude.MHz / 1000;
pub const is_profiling = false;
const allocator = if (builtin.link_libc)
std.heap.c_allocator
else if (builtin.arch.isWasm())
blk: {
(zee_alloc.ExportC{
.allocator = zee_alloc.ZeeAllocDefaults.wasm_allocator,
.malloc = true,
.free = true,
}).run();
break :blk zee_alloc.ZeeAllocDefaults.wasm_allocator;
} else {
@compileError("No allocator found. Did you remember to link libc?");
};
/// Convert a slice into known memory representation -- enables C ABI
pub const U8Chunk = packed struct {
// TODO: switch floats to ints
// JS can't handle i64 yet so we're using f64 for now
// const Int = std.meta.IntType(true, 2 * @bitSizeOf(usize));
const Float = @Type(builtin.TypeInfo{ .Float = .{ .bits = 2 * @bitSizeOf(usize) } });
const Abi = if (builtin.arch.isWasm()) Float else U8Chunk;
ptr: [*]u8,
len: usize,
pub fn toSlice(raw: Abi) []u8 {
const self = @bitCast(U8Chunk, raw);
return self.ptr[0..self.len];
}
pub fn fromSlice(slice: []u8) Abi {
const self = U8Chunk{ .ptr = slice.ptr, .len = slice.len };
return @bitCast(Abi, self);
}
pub fn empty() Abi {
return U8Chunk.fromSlice(&[0]u8{});
}
};
pub fn MatrixChunk(comptime T: type) type {
return packed struct {
const UsizeHalf = std.meta.Int(.signed, @bitSizeOf(usize) / 2);
const Abi = if (builtin.arch.isWasm()) U8Chunk.Abi else MatrixChunk(T);
ptr: [*]T,
width: UsizeHalf,
height: UsizeHalf,
pub fn fromMatrix(matrix: anytype) Abi {
const M = std.meta.Child(@TypeOf(matrix.ptr));
if (@sizeOf(M) != @sizeOf(T)) @compileError("Unsupported Matrix type: " ++ @typeName(M));
const self = MatrixChunk(T){
.ptr = @ptrCast([*]T, matrix.ptr),
.width = @intCast(UsizeHalf, matrix.width),
.height = @intCast(UsizeHalf, matrix.height),
};
return @bitCast(Abi, self);
}
pub fn toMatrix(raw: Abi) MatrixSlice(T) {
const self = @bitCast(MatrixChunk(T), raw);
return .{
.data = self.ptr[0 .. self.width * self.height],
.width = self.width,
.height = self.height,
};
}
};
}
export fn fd_create() ?*Fundude {
const fd = allocator.create(Fundude) catch return null;
fd.* = .{};
return fd;
}
export fn fd_destroy(fd: *Fundude) void {
fd.deinit(allocator);
allocator.destroy(fd);
}
export fn fd_load(fd: *Fundude, cart: U8Chunk.Abi) i8 {
fd.init(allocator, .{ .cart = U8Chunk.toSlice(cart) }) catch |err| return switch (err) {
error.CartTypeError => 1,
error.RomSizeError => 2,
error.RamSizeError => 3,
error.OutOfMemory => 127,
};
return 0;
}
export fn fd_reset(fd: *Fundude) void {
fd.init(allocator, .{}) catch unreachable;
}
export fn fd_step(fd: *Fundude) i8 {
fd.tick(false);
var duration: i8 = 4;
while (fd.cpu.remaining > 0) {
fd.tick(false);
duration += 4;
}
return duration;
}
export fn fd_step_ms(fd: *Fundude, ms: f64) i32 {
const cycles = @as(f64, ms) * CYCLES_PER_MS;
std.debug.assert(cycles < std.math.maxInt(i32));
return fd_step_cycles(fd, @floatToInt(i32, cycles));
}
export fn fd_step_cycles(fd: *Fundude, cycles: i32) i32 {
const target_cycles: i32 = cycles;
var track = target_cycles;
while (track >= 0) {
const catchup = track > 140_000 and !is_profiling;
fd.tick(catchup);
track -= 4;
if (fd.breakpoint == fd.cpu.reg._16.get(.PC)) {
return target_cycles - track;
}
}
return target_cycles - track;
}
export fn fd_rewind(fd: *Fundude) void {
fd.temportal.rewind(fd);
}
export fn fd_dump(fd: *Fundude) U8Chunk.Abi {
const mem = allocator.alloc(u8, Fundude.savestate_size) catch return U8Chunk.empty();
var stream = std.io.fixedBufferStream(mem);
fd.dump(stream.writer()) catch {
allocator.free(mem);
return U8Chunk.empty();
};
return U8Chunk.fromSlice(mem);
}
export fn fd_restore(fd: *Fundude, bytes: U8Chunk.Abi) u8 {
var stream = std.io.fixedBufferStream(U8Chunk.toSlice(bytes));
fd.validateSavestate(stream.reader()) catch return 1;
stream.reset();
fd.restore(stream.reader()) catch unreachable;
return 0;
}
export fn fd_input_press(fd: *Fundude, input: u8) u8 {
const changed = fd.inputs.press(&fd.mmu, .{ .raw = input });
if (changed) {
fd.cpu.mode = .norm;
fd.mmu.dyn.io.IF.joypad = true;
}
return fd.inputs.raw;
}
export fn fd_input_release(fd: *Fundude, input: u8) u8 {
_ = fd.inputs.release(&fd.mmu, .{ .raw = input });
return fd.inputs.raw;
}
export fn fd_disassemble(buffer: *[16]u8, arg0: u8, arg1: u8, arg2: u8) U8Chunk.Abi {
const op = Fundude.Cpu.Op.decode(.{ arg0, arg1, arg2 });
return U8Chunk.fromSlice(op.disassemble(buffer) catch unreachable);
}
export fn fd_instr_len(arg0: u8) usize {
const op = Fundude.Cpu.Op.decode(.{ arg0, 0, 0 });
return op.length;
}
// Video
export fn fd_screen(fd: *Fundude) MatrixChunk(u16).Abi {
return MatrixChunk(u16).fromMatrix(fd.video.screen().toSlice());
}
export fn fd_background(fd: *Fundude) MatrixChunk(u16).Abi {
return MatrixChunk(u16).fromMatrix(fd.video.cache.background.data.toSlice());
}
export fn fd_window(fd: *Fundude) MatrixChunk(u16).Abi {
return MatrixChunk(u16).fromMatrix(fd.video.cache.window.data.toSlice());
}
export fn fd_sprites(fd: *Fundude) MatrixChunk(u16).Abi {
return MatrixChunk(u16).fromMatrix(fd.video.cache.sprites.data.toSlice());
}
export fn fd_patterns(fd: *Fundude) MatrixChunk(u8).Abi {
return MatrixChunk(u8).fromMatrix(fd.video.cache.patterns.toMatrixSlice());
}
export fn fd_cpu_reg(fd: *Fundude) U8Chunk.Abi {
return U8Chunk.fromSlice(std.mem.asBytes(&fd.cpu.reg));
}
/// Only expose the dynamic memory -- e.g. 0x8000 - 0xFFFF
export fn fd_mmu(fd: *Fundude) U8Chunk.Abi {
return U8Chunk.fromSlice(std.mem.asBytes(&fd.mmu.dyn)[0x8000..]);
}
export fn fd_set_breakpoint(fd: *Fundude, breakpoint: u16) void {
fd.breakpoint = breakpoint;
}
|
src/exports.zig
|
pub const OBJ_HANDLE_TAGBITS = @as(i32, 3);
pub const RTL_BALANCED_NODE_RESERVED_PARENT_MASK = @as(u32, 3);
pub const OBJ_INHERIT = @as(i32, 2);
pub const OBJ_PERMANENT = @as(i32, 16);
pub const OBJ_EXCLUSIVE = @as(i32, 32);
pub const OBJ_CASE_INSENSITIVE = @as(i32, 64);
pub const OBJ_OPENIF = @as(i32, 128);
pub const OBJ_OPENLINK = @as(i32, 256);
pub const OBJ_KERNEL_HANDLE = @as(i32, 512);
pub const OBJ_FORCE_ACCESS_CHECK = @as(i32, 1024);
pub const OBJ_IGNORE_IMPERSONATED_DEVICEMAP = @as(i32, 2048);
pub const OBJ_DONT_REPARSE = @as(i32, 4096);
pub const OBJ_VALID_ATTRIBUTES = @as(i32, 8178);
pub const NULL64 = @as(u32, 0);
pub const MAXUCHAR = @as(u32, 255);
pub const MAXUSHORT = @as(u32, 65535);
pub const MAXULONG = @as(u32, 4294967295);
//--------------------------------------------------------------------------------
// Section: Types (31)
//--------------------------------------------------------------------------------
pub const EXCEPTION_DISPOSITION = enum(i32) {
ContinueExecution = 0,
ContinueSearch = 1,
NestedException = 2,
CollidedUnwind = 3,
};
pub const ExceptionContinueExecution = EXCEPTION_DISPOSITION.ContinueExecution;
pub const ExceptionContinueSearch = EXCEPTION_DISPOSITION.ContinueSearch;
pub const ExceptionNestedException = EXCEPTION_DISPOSITION.NestedException;
pub const ExceptionCollidedUnwind = EXCEPTION_DISPOSITION.CollidedUnwind;
pub const COMPARTMENT_ID = enum(i32) {
UNSPECIFIED_COMPARTMENT_ID = 0,
DEFAULT_COMPARTMENT_ID = 1,
};
pub const UNSPECIFIED_COMPARTMENT_ID = COMPARTMENT_ID.UNSPECIFIED_COMPARTMENT_ID;
pub const DEFAULT_COMPARTMENT_ID = COMPARTMENT_ID.DEFAULT_COMPARTMENT_ID;
pub const SLIST_ENTRY = extern struct {
Next: ?*SLIST_ENTRY,
};
pub const QUAD = extern struct {
Anonymous: extern union {
UseThisFieldToCopy: i64,
DoNotUseThisField: f64,
},
};
pub const PROCESSOR_NUMBER = extern struct {
Group: u16,
Number: u8,
Reserved: u8,
};
pub const GROUP_AFFINITY = extern struct {
Mask: usize,
Group: u16,
Reserved: [3]u16,
};
pub const EVENT_TYPE = enum(i32) {
NotificationEvent = 0,
SynchronizationEvent = 1,
};
pub const NotificationEvent = EVENT_TYPE.NotificationEvent;
pub const SynchronizationEvent = EVENT_TYPE.SynchronizationEvent;
pub const TIMER_TYPE = enum(i32) {
NotificationTimer = 0,
SynchronizationTimer = 1,
};
pub const NotificationTimer = TIMER_TYPE.NotificationTimer;
pub const SynchronizationTimer = TIMER_TYPE.SynchronizationTimer;
pub const WAIT_TYPE = enum(i32) {
All = 0,
Any = 1,
Notification = 2,
Dequeue = 3,
};
pub const WaitAll = WAIT_TYPE.All;
pub const WaitAny = WAIT_TYPE.Any;
pub const WaitNotification = WAIT_TYPE.Notification;
pub const WaitDequeue = WAIT_TYPE.Dequeue;
pub const STRING = extern struct {
Length: u16,
MaximumLength: u16,
Buffer: ?[*]u8,
};
pub const CSTRING = extern struct {
Length: u16,
MaximumLength: u16,
Buffer: ?[*:0]const u8,
};
pub const UNICODE_STRING = extern struct {
Length: u16,
MaximumLength: u16,
Buffer: ?[*]u16,
};
pub const LIST_ENTRY = extern struct {
Flink: ?*LIST_ENTRY,
Blink: ?*LIST_ENTRY,
};
pub const RTL_BALANCED_NODE = extern struct {
Anonymous1: extern union {
Children: [2]?*RTL_BALANCED_NODE,
Anonymous: extern struct {
Left: ?*RTL_BALANCED_NODE,
Right: ?*RTL_BALANCED_NODE,
},
},
Anonymous2: extern union {
_bitfield: u8,
ParentValue: usize,
},
};
pub const LIST_ENTRY32 = extern struct {
Flink: u32,
Blink: u32,
};
pub const LIST_ENTRY64 = extern struct {
Flink: u64,
Blink: u64,
};
pub const SINGLE_LIST_ENTRY32 = extern struct {
Next: u32,
};
pub const WNF_STATE_NAME = extern struct {
Data: [2]u32,
};
pub const STRING32 = extern struct {
Length: u16,
MaximumLength: u16,
Buffer: u32,
};
pub const STRING64 = extern struct {
Length: u16,
MaximumLength: u16,
Buffer: u64,
};
pub const OBJECT_ATTRIBUTES64 = extern struct {
Length: u32,
RootDirectory: u64,
ObjectName: u64,
Attributes: u32,
SecurityDescriptor: u64,
SecurityQualityOfService: u64,
};
pub const OBJECT_ATTRIBUTES32 = extern struct {
Length: u32,
RootDirectory: u32,
ObjectName: u32,
Attributes: u32,
SecurityDescriptor: u32,
SecurityQualityOfService: u32,
};
pub const OBJECTID = extern struct {
Lineage: Guid,
Uniquifier: u32,
};
pub const EXCEPTION_ROUTINE = fn(
ExceptionRecord: ?*EXCEPTION_RECORD,
EstablisherFrame: ?*c_void,
ContextRecord: ?*CONTEXT,
DispatcherContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) EXCEPTION_DISPOSITION;
pub const NT_PRODUCT_TYPE = enum(i32) {
WinNt = 1,
LanManNt = 2,
Server = 3,
};
pub const NtProductWinNt = NT_PRODUCT_TYPE.WinNt;
pub const NtProductLanManNt = NT_PRODUCT_TYPE.LanManNt;
pub const NtProductServer = NT_PRODUCT_TYPE.Server;
pub const SUITE_TYPE = enum(i32) {
SmallBusiness = 0,
Enterprise = 1,
BackOffice = 2,
CommunicationServer = 3,
TerminalServer = 4,
SmallBusinessRestricted = 5,
EmbeddedNT = 6,
DataCenter = 7,
SingleUserTS = 8,
Personal = 9,
Blade = 10,
EmbeddedRestricted = 11,
SecurityAppliance = 12,
StorageServer = 13,
ComputeServer = 14,
WHServer = 15,
PhoneNT = 16,
MultiUserTS = 17,
MaxSuiteType = 18,
};
pub const SmallBusiness = SUITE_TYPE.SmallBusiness;
pub const Enterprise = SUITE_TYPE.Enterprise;
pub const BackOffice = SUITE_TYPE.BackOffice;
pub const CommunicationServer = SUITE_TYPE.CommunicationServer;
pub const TerminalServer = SUITE_TYPE.TerminalServer;
pub const SmallBusinessRestricted = SUITE_TYPE.SmallBusinessRestricted;
pub const EmbeddedNT = SUITE_TYPE.EmbeddedNT;
pub const DataCenter = SUITE_TYPE.DataCenter;
pub const SingleUserTS = SUITE_TYPE.SingleUserTS;
pub const Personal = SUITE_TYPE.Personal;
pub const Blade = SUITE_TYPE.Blade;
pub const EmbeddedRestricted = SUITE_TYPE.EmbeddedRestricted;
pub const SecurityAppliance = SUITE_TYPE.SecurityAppliance;
pub const StorageServer = SUITE_TYPE.StorageServer;
pub const ComputeServer = SUITE_TYPE.ComputeServer;
pub const WHServer = SUITE_TYPE.WHServer;
pub const PhoneNT = SUITE_TYPE.PhoneNT;
pub const MultiUserTS = SUITE_TYPE.MultiUserTS;
pub const MaxSuiteType = SUITE_TYPE.MaxSuiteType;
pub const SLIST_HEADER = switch(@import("../zig.zig").arch) {
.Arm64 => extern union {
Anonymous: extern struct {
Alignment: u64,
Region: u64,
},
HeaderArm64: extern struct {
_bitfield1: u64,
_bitfield2: u64,
},
},
.X64 => extern union {
Anonymous: extern struct {
Alignment: u64,
Region: u64,
},
HeaderX64: extern struct {
_bitfield1: u64,
_bitfield2: u64,
},
},
.X86 => extern union {
Alignment: u64,
Anonymous: extern struct {
Next: SLIST_ENTRY,
Depth: u16,
CpuId: u16,
},
},
};
pub const FLOATING_SAVE_AREA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ControlWord: u32,
StatusWord: u32,
TagWord: u32,
ErrorOffset: u32,
ErrorSelector: u32,
DataOffset: u32,
DataSelector: u32,
RegisterArea: [80]u8,
Cr0NpxState: u32,
},
.X86 => extern struct {
ControlWord: u32,
StatusWord: u32,
TagWord: u32,
ErrorOffset: u32,
ErrorSelector: u32,
DataOffset: u32,
DataSelector: u32,
RegisterArea: [80]u8,
Spare0: u32,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const CONTEXT = @import("../system/diagnostics/debug.zig").CONTEXT;
const EXCEPTION_RECORD = @import("../system/diagnostics/debug.zig").EXCEPTION_RECORD;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "EXCEPTION_ROUTINE")) { _ = EXCEPTION_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;
}
}
}
|
deps/zigwin32/win32/system/kernel.zig
|
const std = @import("std");
const hash_map = std.hash_map;
const math = std.math;
const testing = std.testing;
const Allocator = std.mem.Allocator;
pub const GraphError = error{
VertexNotFoundError,
};
/// A directed graph that contains nodes of a given type.
///
/// The Context is the same as the Context for std.hash_map and must
/// provide for a hash function and equality function. This is used to
/// determine graph node equality.
pub fn DirectedGraph(
comptime T: type,
comptime Context: type,
) type {
// This verifies the context has the correct functions (hash and eql)
comptime hash_map.verifyContext(Context, T, T, u64);
// The adjacency list type is used to map all edges in the graph.
// The key is the source node. The value is a map where the key is
// target node and the value is the edge weight.
const AdjMapValue = hash_map.AutoHashMap(u64, u64);
const AdjMap = hash_map.AutoHashMap(u64, AdjMapValue);
// ValueMap maps hash codes to the actual value.
const ValueMap = hash_map.AutoHashMap(u64, T);
return struct {
// allocator to use for all operations
allocator: Allocator,
// ctx is the context implementation
ctx: Context,
// adjacency lists for outbound and inbound edges and a map to
// get the real value.
adjOut: AdjMap,
adjIn: AdjMap,
values: ValueMap,
const Self = @This();
/// Size is the maximum size (as a type) that the graph can hold.
/// This is currently dictated by our usage of HashMap underneath.
const Size = AdjMap.Size;
/// initialize a new directed graph. This is used if the Context type
/// has no data (zero-sized).
pub fn init(allocator: Allocator) Self {
if (@sizeOf(Context) != 0) {
@compileError("Context is non-zero sized. Use initContext instead.");
}
return initContext(allocator, undefined);
}
/// same as init but for non-zero-sized contexts.
pub fn initContext(allocator: Allocator, ctx: Context) Self {
return .{
.allocator = allocator,
.ctx = ctx,
.adjOut = AdjMap.init(allocator),
.adjIn = AdjMap.init(allocator),
.values = ValueMap.init(allocator),
};
}
/// deinitialize all the memory associated with the graph. If you
/// deinitialize the allocator used with this graph you don't need to
/// call this.
pub fn deinit(self: *Self) void {
// Free values for our adj maps
var it = self.adjOut.iterator();
while (it.next()) |kv| {
kv.value_ptr.deinit();
}
it = self.adjIn.iterator();
while (it.next()) |kv| {
kv.value_ptr.deinit();
}
self.adjOut.deinit();
self.adjIn.deinit();
self.values.deinit();
self.* = undefined;
}
/// Add a node to the graph.
pub fn add(self: *Self, v: T) !void {
const h = self.ctx.hash(v);
// If we already have this node, then do nothing.
if (self.adjOut.contains(h)) return;
try self.adjOut.put(h, AdjMapValue.init(self.allocator));
try self.adjIn.put(h, AdjMapValue.init(self.allocator));
try self.values.put(h, v);
}
/// Remove a node and all edges to and from the node.
pub fn remove(self: *Self, v: T) void {
const h = self.ctx.hash(v);
// Forget this value
_ = self.values.remove(h);
// Delete in-edges for this vertex.
if (self.adjOut.getPtr(h)) |map| {
var it = map.iterator();
while (it.next()) |kv| {
if (self.adjIn.getPtr(kv.key_ptr.*)) |inMap| {
_ = inMap.remove(h);
}
}
map.deinit();
_ = self.adjOut.remove(h);
}
// Delete out-edges for this vertex
if (self.adjIn.getPtr(h)) |map| {
var it = map.iterator();
while (it.next()) |kv| {
if (self.adjOut.getPtr(kv.key_ptr.*)) |inMap| {
_ = inMap.remove(h);
}
}
map.deinit();
_ = self.adjIn.remove(h);
}
}
/// contains returns true if the graph has the given vertex.
pub fn contains(self: *Self, v: T) bool {
return self.values.contains(self.ctx.hash(v));
}
/// lookup looks up a vertex by hash. The hash is often used
/// as a result of algorithms such as strongly connected components
/// since it is easier to work with. This function can be called to
/// get the real value.
pub fn lookup(self: *Self, hash: u64) ?T {
return self.values.get(hash);
}
/// add an edge from one node to another. This will return an
/// error if either vertex does not exist.
pub fn addEdge(self: *Self, from: T, to: T, weight: u64) !void {
const h1 = self.ctx.hash(from);
const h2 = self.ctx.hash(to);
const mapOut = self.adjOut.getPtr(h1) orelse
return GraphError.VertexNotFoundError;
const mapIn = self.adjIn.getPtr(h2) orelse
return GraphError.VertexNotFoundError;
try mapOut.put(h2, weight);
try mapIn.put(h1, weight);
}
/// remove an edge
pub fn removeEdge(self: *Self, from: T, to: T) void {
const h1 = self.ctx.hash(from);
const h2 = self.ctx.hash(to);
if (self.adjOut.getPtr(h1)) |map| {
_ = map.remove(h2);
} else unreachable;
if (self.adjIn.getPtr(h2)) |map| {
_ = map.remove(h1);
} else unreachable;
}
/// getEdge gets the edge from one node to another and returns the
/// weight, if it exists.
pub fn getEdge(self: *const Self, from: T, to: T) ?u64 {
const h1 = self.ctx.hash(from);
const h2 = self.ctx.hash(to);
if (self.adjOut.getPtr(h1)) |map| {
return map.get(h2);
} else unreachable;
}
// reverse reverses the graph. This does NOT make any copies, so
// any changes to the original affect the reverse and vice versa.
// Likewise, only one of these graphs should be deinitialized.
pub fn reverse(self: *const Self) Self {
return Self{
.allocator = self.allocator,
.ctx = self.ctx,
.adjOut = self.adjIn,
.adjIn = self.adjOut,
.values = self.values,
};
}
/// Create a copy of this graph using the same allocator.
pub fn clone(self: *const Self) !Self {
return Self{
.allocator = self.allocator,
.ctx = self.ctx,
.adjOut = try cloneAdjMap(&self.adjOut),
.adjIn = try cloneAdjMap(&self.adjIn),
.values = try self.values.clone(),
};
}
/// clone our AdjMap including inner values.
fn cloneAdjMap(m: *const AdjMap) !AdjMap {
// Clone the outer container
var new = try m.clone();
// Clone all objects
var it = new.iterator();
while (it.next()) |kv| {
try new.put(kv.key_ptr.*, try kv.value_ptr.clone());
}
return new;
}
/// The number of vertices in the graph.
pub fn countVertices(self: *const Self) Size {
return self.values.count();
}
/// The number of edges in the graph.
///
/// O(V) where V is the # of vertices. We could cache this if we
/// wanted but its not a very common operation.
pub fn countEdges(self: *const Self) Size {
var count: Size = 0;
var it = self.adjOut.iterator();
while (it.next()) |kv| {
count += kv.value_ptr.count();
}
return count;
}
/// Cycles returns the set of cycles (if any).
pub fn cycles(
self: *const Self,
) ?StronglyConnectedComponents {
var sccs = self.connectedComponents();
var i: usize = 0;
while (i < sccs.list.items.len) {
const current = sccs.list.items[i];
if (current.items.len <= 1) {
const old = sccs.list.swapRemove(i);
old.deinit();
continue;
}
i += 1;
}
if (sccs.list.items.len == 0) {
sccs.deinit();
return null;
}
return sccs;
}
/// Returns the set of strongly connected components in this graph.
/// This allocates memory.
pub fn connectedComponents(
self: *const Self,
) StronglyConnectedComponents {
return stronglyConnectedComponents(self.allocator, self);
}
/// dfsIterator returns an iterator that iterates all reachable
/// vertices from "start". Note that the DFSIterator must have
/// deinit called. It is an error if start does not exist.
pub fn dfsIterator(self: *const Self, start: T) !DFSIterator {
const h = self.ctx.hash(start);
// Start must exist
if (!self.values.contains(h)) {
return GraphError.VertexNotFoundError;
}
// We could pre-allocate some space here and assume we'll visit
// the full graph or something. Keeping it simple for now.
var stack = std.ArrayList(u64).init(self.allocator);
var visited = std.AutoHashMap(u64, void).init(self.allocator);
return DFSIterator{
.g = self,
.stack = stack,
.visited = visited,
.current = h,
};
}
pub const DFSIterator = struct {
// Not the most efficient data structures for this, I know,
// but we can come back and optimize this later since its opaque.
//
// stack and visited must ensure capacity
g: *const Self,
stack: std.ArrayList(u64),
visited: std.AutoHashMap(u64, void),
current: ?u64,
// DFSIterator must deinit
pub fn deinit(it: *DFSIterator) void {
it.stack.deinit();
it.visited.deinit();
}
/// next returns the list of hash IDs for the vertex. This should be
/// looked up again with the graph to get the actual vertex value.
pub fn next(it: *DFSIterator) !?u64 {
// If we're out of values, then we're done.
if (it.current == null) return null;
// Our result is our current value
const result = it.current orelse unreachable;
try it.visited.put(result, {});
// Add all adjacent edges to the stack. We do a
// visited check here to avoid revisiting vertices
if (it.g.adjOut.getPtr(result)) |map| {
var iter = map.keyIterator();
while (iter.next()) |target| {
if (!it.visited.contains(target.*)) {
try it.stack.append(target.*);
}
}
}
// Advance to the next value
it.current = null;
while (it.stack.popOrNull()) |nextVal| {
if (!it.visited.contains(nextVal)) {
it.current = nextVal;
break;
}
}
return result;
}
};
};
}
test "add and remove vertex" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// No vertex
try testing.expect(!g.contains("A"));
// Add some nodes
try g.add("A");
try g.add("A");
try g.add("B");
try testing.expect(g.contains("A"));
try testing.expect(g.countVertices() == 2);
try testing.expect(g.countEdges() == 0);
// add an edge
try g.addEdge("A", "B", 1);
try testing.expect(g.countEdges() == 1);
// Remove a node
g.remove("A");
try testing.expect(g.countVertices() == 1);
// important: removing a node should remove the edge
try testing.expect(g.countEdges() == 0);
}
test "add and remove edge" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// Add some nodes
try g.add("A");
try g.add("A");
try g.add("B");
// add an edge
try g.addEdge("A", "B", 1);
try g.addEdge("A", "B", 4);
try testing.expect(g.countEdges() == 1);
try testing.expect(g.getEdge("A", "B").? == 4);
// Remove the node
g.removeEdge("A", "B");
g.removeEdge("A", "B");
try testing.expect(g.countEdges() == 0);
try testing.expect(g.countVertices() == 2);
}
test "reverse" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// Add some nodes
try g.add("A");
try g.add("B");
try g.addEdge("A", "B", 1);
// Reverse
const rev = g.reverse();
// Should have the same number
try testing.expect(rev.countEdges() == 1);
try testing.expect(rev.countVertices() == 2);
try testing.expect(rev.getEdge("A", "B") == null);
try testing.expect(rev.getEdge("B", "A").? == 1);
}
test "clone" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// Add some nodes
try g.add("A");
// Clone
var g2 = try g.clone();
defer g2.deinit();
try g.add("B");
try testing.expect(g.contains("B"));
try testing.expect(!g2.contains("B"));
}
test "cycles and strongly connected components" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// Add some nodes
try g.add("A");
var alone = g.connectedComponents();
defer alone.deinit();
const value = g.lookup(alone.list.items[0].items[0]);
try testing.expectEqual(value.?, "A");
// Add more
try g.add("B");
try g.addEdge("A", "B", 1);
var sccs = g.connectedComponents();
defer sccs.deinit();
try testing.expect(sccs.count() == 2);
try testing.expect(g.cycles() == null);
// Add a cycle
try g.addEdge("B", "A", 1);
var sccs2 = g.connectedComponents();
defer sccs2.deinit();
try testing.expect(sccs2.count() == 1);
// Should have a cycle
var cycles = g.cycles() orelse unreachable;
defer cycles.deinit();
try testing.expect(cycles.count() == 1);
}
test "dfs" {
const gtype = DirectedGraph([]const u8, std.hash_map.StringContext);
var g = gtype.init(testing.allocator);
defer g.deinit();
// Add some nodes
try g.add("A");
try g.add("B");
try g.add("C");
try g.addEdge("B", "C", 1);
try g.addEdge("C", "A", 1);
// DFS from A should only reach A
{
var list = std.ArrayList([]const u8).init(testing.allocator);
defer list.deinit();
var iter = try g.dfsIterator("A");
defer iter.deinit();
while (try iter.next()) |value| {
try list.append(g.lookup(value).?);
}
const expect = [_][]const u8{"A"};
try testing.expectEqualSlices([]const u8, list.items, &expect);
}
// DFS from B
{
var list = std.ArrayList([]const u8).init(testing.allocator);
defer list.deinit();
var iter = try g.dfsIterator("B");
defer iter.deinit();
while (try iter.next()) |value| {
try list.append(g.lookup(value).?);
}
const expect = [_][]const u8{ "B", "C", "A" };
try testing.expectEqualSlices([]const u8, &expect, list.items);
}
}
/// A list of strongly connected components.
///
/// This is effectively [][]u64 for a DirectedGraph. The u64 value is the
/// hash code, NOT the type T. You should use the lookup function to get the
/// actual vertex.
pub const StronglyConnectedComponents = struct {
const Self = @This();
const Entry = std.ArrayList(u64);
const List = std.ArrayList(Entry);
/// The list of components. Do not access this directly. This type
/// also owns all the items, so when deinit is called, all items in this
/// list will also be deinit-ed.
list: List,
/// Iterator is used to iterate through the strongly connected components.
pub const Iterator = struct {
list: *const List,
index: usize = 0,
/// next returns the list of hash IDs for the vertex. This should be
/// looked up again with the graph to get the actual vertex value.
pub fn next(it: *Iterator) ?[]u64 {
// If we're empty or at the end, we're done.
if (it.list.items.len == 0 or it.list.items.len <= it.index) return null;
// Bump the index, return our value
defer it.index += 1;
return it.list.items[it.index].items;
}
};
pub fn init(allocator: Allocator) Self {
return Self{
.list = List.init(allocator),
};
}
pub fn deinit(self: *Self) void {
for (self.list.items) |v| {
v.deinit();
}
self.list.deinit();
}
/// Iterate over all the strongly connected components
pub fn iterator(self: *const Self) Iterator {
return .{ .list = &self.list };
}
/// The number of distinct strongly connected components.
pub fn count(self: *const Self) usize {
return self.list.items.len;
}
};
/// Calculate the set of strongly connected components in the graph g.
/// The argument g must be a DirectedGraph type.
pub fn stronglyConnectedComponents(
allocator: Allocator,
g: anytype,
) StronglyConnectedComponents {
var acc = sccAcc.init(allocator);
defer acc.deinit();
var result = StronglyConnectedComponents.init(allocator);
var iter = g.values.keyIterator();
while (iter.next()) |h| {
if (!acc.map.contains(h.*)) {
_ = stronglyConnectedStep(allocator, g, &acc, &result, h.*);
}
}
return result;
}
fn stronglyConnectedStep(
allocator: Allocator,
g: anytype,
acc: *sccAcc,
result: *StronglyConnectedComponents,
current: u64,
) u32 {
// TODO(mitchellh): I don't like this unreachable here.
const idx = acc.visit(current) catch unreachable;
var minIdx = idx;
var iter = g.adjOut.getPtr(current).?.keyIterator();
while (iter.next()) |targetPtr| {
const target = targetPtr.*;
const targetIdx = acc.map.get(target) orelse 0;
if (targetIdx == 0) {
minIdx = math.min(
minIdx,
stronglyConnectedStep(allocator, g, acc, result, target),
);
} else if (acc.inStack(target)) {
minIdx = math.min(minIdx, targetIdx);
}
}
// If this is the vertex we started with then build our result.
if (idx == minIdx) {
var scc = std.ArrayList(u64).init(allocator);
while (true) {
const v = acc.pop();
scc.append(v) catch unreachable;
if (v == current) {
break;
}
}
result.list.append(scc) catch unreachable;
}
return minIdx;
}
/// Internal accumulator used to calculate the strongly connected
/// components. This should not be used publicly.
pub const sccAcc = struct {
const MapType = std.hash_map.AutoHashMap(u64, Size);
const StackType = std.ArrayList(u64);
next: Size,
map: MapType,
stack: StackType,
// Size is the maximum number of vertices that could exist. Our graph
// is limited to 32 bit numbers due to the underlying usage of HashMap.
const Size = u32;
const Self = @This();
pub fn init(allocator: Allocator) Self {
return Self{
.next = 1,
.map = MapType.init(allocator),
.stack = StackType.init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.map.deinit();
self.stack.deinit();
self.* = undefined;
}
pub fn visit(self: *Self, v: u64) !Size {
const idx = self.next;
try self.map.put(v, idx);
self.next += 1;
try self.stack.append(v);
return idx;
}
pub fn pop(self: *Self) u64 {
return self.stack.pop();
}
pub fn inStack(self: *Self, v: u64) bool {
for (self.stack.items) |i| {
if (i == v) {
return true;
}
}
return false;
}
};
test "sccAcc" {
var acc = sccAcc.init(testing.allocator);
defer acc.deinit();
// should start at nothing
try testing.expect(acc.next == 1);
try testing.expect(!acc.inStack(42));
// add vertex
try testing.expect((try acc.visit(42)) == 1);
try testing.expect(acc.next == 2);
try testing.expect(acc.inStack(42));
const v = acc.pop();
try testing.expect(v == 42);
}
test "StronglyConnectedComponents" {
var sccs = StronglyConnectedComponents.init(testing.allocator);
defer sccs.deinit();
// Initially empty
try testing.expect(sccs.count() == 0);
// Build our entries
var entries = StronglyConnectedComponents.Entry.init(testing.allocator);
try entries.append(1);
try entries.append(2);
try entries.append(3);
try sccs.list.append(entries);
// Should have one
try testing.expect(sccs.count() == 1);
// Test iteration
var iter = sccs.iterator();
var count: u8 = 0;
while (iter.next()) |set| {
const expect = [_]u64{ 1, 2, 3 };
try testing.expectEqual(set.len, 3);
try testing.expectEqualSlices(u64, set, &expect);
count += 1;
}
try testing.expect(count == 1);
}
|
lib/src/data/graph.zig
|
const std = @import("std");
const mem = std.mem;
const OtherGraphemeExtend = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 2494,
hi: u21 = 917631,
pub fn init(allocator: *mem.Allocator) !OtherGraphemeExtend {
var instance = OtherGraphemeExtend{
.allocator = allocator,
.array = try allocator.alloc(bool, 915138),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[25] = true;
instance.array[384] = true;
instance.array[409] = true;
instance.array[512] = true;
instance.array[537] = true;
instance.array[772] = true;
index = 791;
while (index <= 792) : (index += 1) {
instance.array[index] = true;
}
instance.array[896] = true;
instance.array[921] = true;
instance.array[1041] = true;
instance.array[1057] = true;
instance.array[4471] = true;
instance.array[5710] = true;
index = 9840;
while (index <= 9841) : (index += 1) {
instance.array[index] = true;
}
index = 62944;
while (index <= 62945) : (index += 1) {
instance.array[index] = true;
}
instance.array[67968] = true;
instance.array[67993] = true;
instance.array[68338] = true;
instance.array[68351] = true;
instance.array[68593] = true;
instance.array[69490] = true;
instance.array[116647] = true;
index = 116656;
while (index <= 116660) : (index += 1) {
instance.array[index] = true;
}
index = 915042;
while (index <= 915137) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *OtherGraphemeExtend) void {
self.allocator.free(self.array);
}
// isOtherGraphemeExtend checks if cp is of the kind Other_Grapheme_Extend.
pub fn isOtherGraphemeExtend(self: OtherGraphemeExtend, 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/PropList/OtherGraphemeExtend.zig
|
const std = @import("std");
const mem = std.mem;
const MathSymbol = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 43,
hi: u21 = 126705,
pub fn init(allocator: *mem.Allocator) !MathSymbol {
var instance = MathSymbol{
.allocator = allocator,
.array = try allocator.alloc(bool, 126663),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
index = 17;
while (index <= 19) : (index += 1) {
instance.array[index] = true;
}
instance.array[81] = true;
instance.array[83] = true;
instance.array[129] = true;
instance.array[134] = true;
instance.array[172] = true;
instance.array[204] = true;
instance.array[971] = true;
index = 1499;
while (index <= 1501) : (index += 1) {
instance.array[index] = true;
}
instance.array[8217] = true;
instance.array[8231] = true;
index = 8271;
while (index <= 8273) : (index += 1) {
instance.array[index] = true;
}
index = 8287;
while (index <= 8289) : (index += 1) {
instance.array[index] = true;
}
instance.array[8429] = true;
index = 8469;
while (index <= 8473) : (index += 1) {
instance.array[index] = true;
}
instance.array[8480] = true;
index = 8549;
while (index <= 8553) : (index += 1) {
instance.array[index] = true;
}
index = 8559;
while (index <= 8560) : (index += 1) {
instance.array[index] = true;
}
instance.array[8565] = true;
instance.array[8568] = true;
instance.array[8571] = true;
instance.array[8579] = true;
index = 8611;
while (index <= 8612) : (index += 1) {
instance.array[index] = true;
}
instance.array[8615] = true;
instance.array[8617] = true;
index = 8649;
while (index <= 8916) : (index += 1) {
instance.array[index] = true;
}
index = 8949;
while (index <= 8950) : (index += 1) {
instance.array[index] = true;
}
instance.array[9041] = true;
index = 9072;
while (index <= 9096) : (index += 1) {
instance.array[index] = true;
}
index = 9137;
while (index <= 9142) : (index += 1) {
instance.array[index] = true;
}
instance.array[9612] = true;
instance.array[9622] = true;
index = 9677;
while (index <= 9684) : (index += 1) {
instance.array[index] = true;
}
instance.array[9796] = true;
index = 10133;
while (index <= 10137) : (index += 1) {
instance.array[index] = true;
}
index = 10140;
while (index <= 10170) : (index += 1) {
instance.array[index] = true;
}
index = 10181;
while (index <= 10196) : (index += 1) {
instance.array[index] = true;
}
index = 10453;
while (index <= 10583) : (index += 1) {
instance.array[index] = true;
}
index = 10606;
while (index <= 10668) : (index += 1) {
instance.array[index] = true;
}
index = 10673;
while (index <= 10704) : (index += 1) {
instance.array[index] = true;
}
index = 10707;
while (index <= 10964) : (index += 1) {
instance.array[index] = true;
}
index = 11013;
while (index <= 11033) : (index += 1) {
instance.array[index] = true;
}
index = 11036;
while (index <= 11041) : (index += 1) {
instance.array[index] = true;
}
instance.array[64254] = true;
instance.array[65079] = true;
index = 65081;
while (index <= 65083) : (index += 1) {
instance.array[index] = true;
}
instance.array[65248] = true;
index = 65265;
while (index <= 65267) : (index += 1) {
instance.array[index] = true;
}
instance.array[65329] = true;
instance.array[65331] = true;
instance.array[65463] = true;
index = 65470;
while (index <= 65473) : (index += 1) {
instance.array[index] = true;
}
instance.array[120470] = true;
instance.array[120496] = true;
instance.array[120528] = true;
instance.array[120554] = true;
instance.array[120586] = true;
instance.array[120612] = true;
instance.array[120644] = true;
instance.array[120670] = true;
instance.array[120702] = true;
instance.array[120728] = true;
index = 126661;
while (index <= 126662) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *MathSymbol) void {
self.allocator.free(self.array);
}
// isMathSymbol checks if cp is of the kind Math_Symbol.
pub fn isMathSymbol(self: MathSymbol, 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/DerivedGeneralCategory/MathSymbol.zig
|
const std = @import("std");
const rg = @import("../render_graph.zig");
const shader_util = @import("../../../shaders/shader_util.zig");
const vk = @import("../../../vk.zig");
const vkctxt = @import("../../../vulkan_wrapper/vulkan_context.zig");
const RGPass = @import("../render_graph_pass.zig").RGPass;
const Swapchain = @import("../resources/swapchain.zig").Swapchain;
const ViewportTexture = @import("../resources/viewport_texture.zig").ViewportTexture;
pub const ScreenRenderPass = struct {
const VertPushConstBlock = struct {
aspect_ratio: [4]f32,
};
rg_pass: RGPass,
allocator: std.mem.Allocator,
render_pass: vk.RenderPass,
alloc_framebuffers: bool,
framebuffers: []vk.Framebuffer,
framebuffer_index: *u32,
target_image_format: vk.Format,
target_width: *u32,
target_height: *u32,
target_viewport_texture: *ViewportTexture,
pipeline_cache: vk.PipelineCache,
pipeline_layout: vk.PipelineLayout,
pipeline: vk.Pipeline,
vert_shader: vk.ShaderModule,
frag_shader: *vk.ShaderModule,
frag_push_const_size: usize,
frag_push_const_block: *const anyopaque,
custom_scissors: ?*vk.Rect2D,
// Accepts *ViewportTexture or *Swapchain as target
pub fn init(
self: *ScreenRenderPass,
comptime name: []const u8,
allocator: std.mem.Allocator,
target: anytype,
frag_shader: *vk.ShaderModule,
frag_push_const_size: usize,
frag_push_const_block: *const anyopaque,
) void {
if (@TypeOf(target) != *ViewportTexture and @TypeOf(target) != *Swapchain)
@compileError("ScreenRenderPass only accepts *ViewportTexture or *Swapchain as target");
self.alloc_framebuffers = @TypeOf(target) == *ViewportTexture;
if (@TypeOf(target) == *ViewportTexture) {
self.target_image_format = target.image_format;
self.target_width = &target.width;
self.target_height = &target.height;
self.target_viewport_texture = target;
self.framebuffer_index = &rg.global_render_graph.frame_index;
} else {
self.target_image_format = target.image_format;
self.target_width = &target.image_extent.width;
self.target_height = &target.image_extent.height;
self.framebuffer_index = &rg.global_render_graph.image_index;
}
self.allocator = allocator;
self.frag_shader = frag_shader;
self.frag_push_const_size = frag_push_const_size;
self.frag_push_const_block = frag_push_const_block;
self.rg_pass.init(name, allocator, passInit, passDeinit, passRender);
self.rg_pass.appendWriteResource(&target.rg_resource);
if (@TypeOf(target) == *ViewportTexture) {
self.framebuffers = allocator.alloc(vk.Framebuffer, target.textures.len) catch unreachable;
target.rg_resource.registerOnChangeCallback(&self.rg_pass, reinitFramebuffer);
} else {
self.framebuffers = target.framebuffers;
}
self.custom_scissors = null;
self.rg_pass.pipeline_start = .{ .fragment_shader_bit = true };
self.rg_pass.pipeline_end = .{ .color_attachment_output_bit = true };
}
pub fn deinit(self: *ScreenRenderPass) void {
if (self.alloc_framebuffers)
self.allocator.free(self.framebuffers);
}
fn passInit(render_pass: *RGPass) void {
const self: *ScreenRenderPass = @fieldParentPtr(ScreenRenderPass, "rg_pass", render_pass);
const vert_code = @embedFile("screen_render_pass.vert");
self.vert_shader = shader_util.loadShader(vert_code, .vertex);
const color_attachment: vk.AttachmentDescription = .{
.format = self.target_image_format,
.samples = .{ .@"1_bit" = true },
.load_op = self.rg_pass.load_op,
.store_op = .store,
.stencil_load_op = .dont_care,
.stencil_store_op = .dont_care,
.initial_layout = self.rg_pass.initial_layout,
.final_layout = self.rg_pass.final_layout,
.flags = .{},
};
const color_attachment_ref: vk.AttachmentReference = .{
.attachment = 0,
.layout = .color_attachment_optimal,
};
const subpass: vk.SubpassDescription = .{
.pipeline_bind_point = .graphics,
.color_attachment_count = 1,
.p_color_attachments = @ptrCast([*]const vk.AttachmentReference, &color_attachment_ref),
.flags = .{},
.input_attachment_count = 0,
.p_input_attachments = undefined,
.p_resolve_attachments = undefined,
.p_depth_stencil_attachment = undefined,
.preserve_attachment_count = 0,
.p_preserve_attachments = undefined,
};
const dependency: vk.SubpassDependency = .{
.src_subpass = vk.SUBPASS_EXTERNAL,
.dst_subpass = 0,
.src_stage_mask = .{ .color_attachment_output_bit = true },
.src_access_mask = .{},
.dst_stage_mask = .{ .color_attachment_output_bit = true },
.dst_access_mask = .{ .color_attachment_read_bit = true, .color_attachment_write_bit = true },
.dependency_flags = .{},
};
const render_pass_create_info: vk.RenderPassCreateInfo = .{
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.AttachmentDescription, &color_attachment),
.subpass_count = 1,
.p_subpasses = @ptrCast([*]const vk.SubpassDescription, &subpass),
.dependency_count = 1,
.p_dependencies = @ptrCast([*]const vk.SubpassDependency, &dependency),
.flags = .{},
};
self.render_pass = vkctxt.vkd.createRenderPass(vkctxt.vkc.device, render_pass_create_info, null) catch |err| {
vkctxt.printVulkanError("Can't create render pass for screen render pass", err, vkctxt.vkc.allocator);
return;
};
if (self.alloc_framebuffers)
self.createFramebuffers();
self.createPipelineCache();
self.createPipelineLayout();
self.createPipeline();
}
fn passDeinit(render_pass: *RGPass) void {
const self: *ScreenRenderPass = @fieldParentPtr(ScreenRenderPass, "rg_pass", render_pass);
vkctxt.vkd.destroyRenderPass(vkctxt.vkc.device, self.render_pass, null);
vkctxt.vkd.destroyPipeline(vkctxt.vkc.device, self.pipeline, null);
vkctxt.vkd.destroyPipelineLayout(vkctxt.vkc.device, self.pipeline_layout, null);
vkctxt.vkd.destroyPipelineCache(vkctxt.vkc.device, self.pipeline_cache, null);
if (self.alloc_framebuffers)
self.destroyFramebuffers();
vkctxt.vkd.destroyShaderModule(vkctxt.vkc.device, self.vert_shader, null);
}
fn passRender(render_pass: *RGPass, command_buffer: vk.CommandBuffer, frame_index: u32) void {
_ = frame_index;
const self: *ScreenRenderPass = @fieldParentPtr(ScreenRenderPass, "rg_pass", render_pass);
const clear_color: vk.ClearValue = .{ .color = .{ .float_32 = [_]f32{ 0.6, 0.3, 0.6, 1.0 } } };
const render_pass_info: vk.RenderPassBeginInfo = .{
.render_pass = self.render_pass,
.framebuffer = self.framebuffers[@intCast(usize, self.framebuffer_index.*)],
.render_area = .{
.offset = .{ .x = 0, .y = 0 },
.extent = .{
.width = self.target_width.*,
.height = self.target_height.*,
},
},
.clear_value_count = 1,
.p_clear_values = @ptrCast([*]const vk.ClearValue, &clear_color),
};
vkctxt.vkd.cmdBeginRenderPass(command_buffer, render_pass_info, .@"inline");
defer vkctxt.vkd.cmdEndRenderPass(command_buffer);
vkctxt.vkd.cmdBindPipeline(command_buffer, .graphics, self.pipeline);
const viewport_info: vk.Viewport = .{
.width = @intToFloat(f32, self.target_width.*),
.height = @intToFloat(f32, self.target_height.*),
.min_depth = 0.0,
.max_depth = 1.0,
.x = 0,
.y = 0,
};
vkctxt.vkd.cmdSetViewport(command_buffer, 0, 1, @ptrCast([*]const vk.Viewport, &viewport_info));
var scissor_rect: vk.Rect2D = .{
.offset = .{ .x = 0, .y = 0 },
.extent = .{
.width = self.target_width.*,
.height = self.target_height.*,
},
};
const scissor_rect_ptr: *vk.Rect2D = if (self.custom_scissors) |custom_scissors| custom_scissors else &scissor_rect;
vkctxt.vkd.cmdSetScissor(command_buffer, 0, 1, @ptrCast([*]const vk.Rect2D, scissor_rect_ptr));
var push_const_block: VertPushConstBlock = .{
.aspect_ratio = [4]f32{ 1.0, 1.0, 0.0, 0.0 },
};
if (self.target_width.* > self.target_height.*) {
push_const_block.aspect_ratio[0] = viewport_info.width / viewport_info.height;
} else {
push_const_block.aspect_ratio[1] = viewport_info.height / viewport_info.width;
}
vkctxt.vkd.cmdPushConstants(
command_buffer,
self.pipeline_layout,
.{ .vertex_bit = true },
0,
@sizeOf(VertPushConstBlock),
@ptrCast([*]const VertPushConstBlock, &push_const_block),
);
vkctxt.vkd.cmdPushConstants(
command_buffer,
self.pipeline_layout,
.{ .fragment_bit = true },
@sizeOf(VertPushConstBlock),
@intCast(u32, self.frag_push_const_size),
self.frag_push_const_block,
);
vkctxt.vkd.cmdDraw(command_buffer, 3, 1, 0, 0);
}
fn createFramebuffers(self: *ScreenRenderPass) void {
for (self.framebuffers) |*framebuffer, i| {
const create_info: vk.FramebufferCreateInfo = .{
.flags = .{},
.render_pass = self.render_pass,
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.ImageView, &self.target_viewport_texture.textures[i].view),
.width = self.target_width.*,
.height = self.target_height.*,
.layers = 1,
};
framebuffer.* = vkctxt.vkd.createFramebuffer(vkctxt.vkc.device, create_info, null) catch |err| {
vkctxt.printVulkanError("Can't create framebuffer for screen render pass", err, vkctxt.vkc.allocator);
return;
};
}
}
fn destroyFramebuffers(self: *ScreenRenderPass) void {
for (self.framebuffers) |f|
vkctxt.vkd.destroyFramebuffer(vkctxt.vkc.device, f, null);
}
fn reinitFramebuffer(render_pass: *RGPass) void {
const self: *ScreenRenderPass = @fieldParentPtr(ScreenRenderPass, "rg_pass", render_pass);
self.destroyFramebuffers();
self.createFramebuffers();
}
fn createPipelineCache(self: *ScreenRenderPass) void {
const pipeline_cache_create_info: vk.PipelineCacheCreateInfo = .{
.flags = .{},
.initial_data_size = 0,
.p_initial_data = undefined,
};
self.pipeline_cache = vkctxt.vkd.createPipelineCache(vkctxt.vkc.device, pipeline_cache_create_info, null) catch |err| {
vkctxt.printVulkanError("Can't create pipeline cache", err, vkctxt.vkc.allocator);
return;
};
}
fn createPipelineLayout(self: *ScreenRenderPass) void {
const push_constant_range: [2]vk.PushConstantRange = [_]vk.PushConstantRange{
.{
.stage_flags = .{ .vertex_bit = true },
.offset = 0,
.size = @sizeOf(VertPushConstBlock),
},
.{
.stage_flags = .{ .fragment_bit = true },
.offset = @sizeOf(VertPushConstBlock),
.size = @intCast(u32, self.frag_push_const_size),
},
};
const pipeline_layout_create_info: vk.PipelineLayoutCreateInfo = .{
.set_layout_count = 0,
.p_set_layouts = undefined,
.push_constant_range_count = 2,
.p_push_constant_ranges = @ptrCast([*]const vk.PushConstantRange, &push_constant_range),
.flags = .{},
};
self.pipeline_layout = vkctxt.vkd.createPipelineLayout(vkctxt.vkc.device, pipeline_layout_create_info, null) catch |err| {
vkctxt.printVulkanError("Can't create pipeline layout", err, vkctxt.vkc.allocator);
return;
};
}
fn recreatePipeline(self: *ScreenRenderPass) void {
vkctxt.vkd.destroyPipeline(vkctxt.vkc.device, self.pipeline, null);
self.createPipeline();
}
pub fn recreatePipelineOnShaderChange(pass: *RGPass) void {
const self: *ScreenRenderPass = @fieldParentPtr(ScreenRenderPass, "rg_pass", pass);
self.recreatePipeline();
}
fn createPipeline(self: *ScreenRenderPass) void {
const input_assembly_state: vk.PipelineInputAssemblyStateCreateInfo = .{
.topology = .triangle_list,
.flags = .{},
.primitive_restart_enable = vk.FALSE,
};
const rasterization_state: vk.PipelineRasterizationStateCreateInfo = .{
.polygon_mode = .fill,
.cull_mode = .{},
.front_face = .counter_clockwise,
.flags = .{},
.depth_clamp_enable = vk.FALSE,
.line_width = 1.0,
.rasterizer_discard_enable = vk.FALSE,
.depth_bias_enable = vk.FALSE,
.depth_bias_constant_factor = 0,
.depth_bias_clamp = 0,
.depth_bias_slope_factor = 0,
};
const blend_attachment_state: vk.PipelineColorBlendAttachmentState = .{
.blend_enable = vk.FALSE,
.color_write_mask = .{ .r_bit = true, .g_bit = true, .b_bit = true, .a_bit = true },
.src_color_blend_factor = .src_alpha,
.dst_color_blend_factor = .one_minus_src_alpha,
.color_blend_op = .add,
.src_alpha_blend_factor = .one,
.dst_alpha_blend_factor = .zero,
.alpha_blend_op = .add,
};
const color_blend_state: vk.PipelineColorBlendStateCreateInfo = .{
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &blend_attachment_state),
.flags = .{},
.logic_op_enable = vk.FALSE,
.logic_op = undefined,
.blend_constants = [4]f32{ 0.0, 0.0, 0.0, 0.0 },
};
const depth_stencil_state: vk.PipelineDepthStencilStateCreateInfo = .{
.depth_test_enable = vk.FALSE,
.depth_write_enable = vk.FALSE,
.depth_compare_op = .less_or_equal,
.back = .{
.compare_op = .always,
.fail_op = .keep,
.pass_op = .keep,
.depth_fail_op = .keep,
.compare_mask = 0,
.write_mask = 0,
.reference = 0,
},
.front = .{
.compare_op = .never,
.fail_op = .keep,
.pass_op = .keep,
.depth_fail_op = .keep,
.compare_mask = 0,
.write_mask = 0,
.reference = 0,
},
.depth_bounds_test_enable = vk.FALSE,
.stencil_test_enable = vk.FALSE,
.flags = .{},
.min_depth_bounds = 0.0,
.max_depth_bounds = 0.0,
};
const viewport_state: vk.PipelineViewportStateCreateInfo = .{
.viewport_count = 1,
.p_viewports = null,
.scissor_count = 1,
.p_scissors = null,
.flags = .{},
};
const multisample_state: vk.PipelineMultisampleStateCreateInfo = .{
.rasterization_samples = .{ .@"1_bit" = true },
.flags = .{},
.sample_shading_enable = vk.FALSE,
.min_sample_shading = 0,
.p_sample_mask = undefined,
.alpha_to_coverage_enable = vk.FALSE,
.alpha_to_one_enable = vk.FALSE,
};
const dynamic_enabled_states = [_]vk.DynamicState{ .viewport, .scissor };
const dynamic_state: vk.PipelineDynamicStateCreateInfo = .{
.p_dynamic_states = @ptrCast([*]const vk.DynamicState, &dynamic_enabled_states),
.dynamic_state_count = 2,
.flags = .{},
};
const vertex_input_state: vk.PipelineVertexInputStateCreateInfo = .{
.vertex_binding_description_count = 0,
.p_vertex_binding_descriptions = undefined,
.vertex_attribute_description_count = 0,
.p_vertex_attribute_descriptions = undefined,
.flags = .{},
};
const ui_vert_shader_stage: vk.PipelineShaderStageCreateInfo = .{
.stage = .{ .vertex_bit = true },
.module = self.vert_shader,
.p_name = "main",
.flags = .{},
.p_specialization_info = null,
};
const ui_frag_shader_stage: vk.PipelineShaderStageCreateInfo = .{
.stage = .{ .fragment_bit = true },
.module = self.frag_shader.*,
.p_name = "main",
.flags = .{},
.p_specialization_info = null,
};
const shader_stages = [_]vk.PipelineShaderStageCreateInfo{ ui_vert_shader_stage, ui_frag_shader_stage };
const pipeline_create_info: vk.GraphicsPipelineCreateInfo = .{
.layout = self.pipeline_layout,
.render_pass = self.render_pass,
.flags = .{},
.base_pipeline_index = -1,
.base_pipeline_handle = .null_handle,
.p_input_assembly_state = &input_assembly_state,
.p_rasterization_state = &rasterization_state,
.p_color_blend_state = &color_blend_state,
.p_multisample_state = &multisample_state,
.p_viewport_state = &viewport_state,
.p_depth_stencil_state = &depth_stencil_state,
.p_dynamic_state = &dynamic_state,
.p_vertex_input_state = &vertex_input_state,
.stage_count = 2,
.p_stages = @ptrCast([*]const vk.PipelineShaderStageCreateInfo, &shader_stages),
.p_tessellation_state = null,
.subpass = 0,
};
_ = vkctxt.vkd.createGraphicsPipelines(
vkctxt.vkc.device,
self.pipeline_cache,
1,
@ptrCast([*]const vk.GraphicsPipelineCreateInfo, &pipeline_create_info),
null,
@ptrCast([*]vk.Pipeline, &self.pipeline),
) catch |err| {
vkctxt.printVulkanError("Can't create graphics pipeline for screen render pass", err, vkctxt.vkc.allocator);
return;
};
}
};
|
src/renderer/render_graph/passes/screen_render_pass.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const c = @import("c.zig");
const odbc = @import("types.zig");
/// Errors that can be returned from Odbc functions, as indicated by the
/// SQLRETURN value.
pub const ReturnError = error{Error, NoData, InvalidHandle, StillExecuting};
fn StringEnum(comptime E: type, comptime str_map: anytype) type {
return struct {
pub const Enum = E;
pub fn fromString(str: []const u8) error{Invalid}!E {
return inline for (str_map) |mapping| {
if (std.mem.eql(u8, mapping[0], str)) break mapping[1];
} else error.Invalid;
}
pub fn toString(enum_val: E) []const u8 {
inline for (str_map) |mapping| {
if (mapping[1] == enum_val) return mapping[0];
}
unreachable;
}
};
}
pub const SqlState = enum {
Success,
GeneralWarning,
CursorOperationConflict,
DisconnectError,
NullEliminated,
StringRightTrunc,
PrivilegeNotRevoked,
PrivilegeNotGranted,
InvalidConnectionStringAttr,
ErrorInRow,
OptionValueChanged,
FetchBeforeFirstResultSet,
FractionalTruncation,
ErrorSavingFileDSN,
InvalidKeyword,
WrongNumberOfParameters,
IncorrectCountField,
PreparedStmtNotCursorSpec,
RestrictedDataTypeAttr,
InvalidDescIndex,
InvalidDefaultParam,
ClientConnectionError,
ConnectionNameInUse,
ConnectionNotOpen,
ServerRejectedConnection,
TransactionConnectionFailure,
CommunicationLinkFailure,
InsertValueColumnMismatch,
DerivedTableDegreeColumnMismatch,
IndicatorVarRequired,
NumOutOfRange,
InvalidDatetimeFormat,
DatetimeOverflow,
DivisionByZero,
IntervalFieldOverflow,
InvalidCharacterValue,
InvalidEscapeCharacter,
InvalidEscapeSequence,
StringLengthMismatch,
IntegrityConstraintViolation,
InvalidCursorState,
InvalidTransactionState,
TransactionState,
TransactionStillActive,
TransactionRolledBack,
InvalidAuthorization,
InvalidCursorName,
DuplicateCursorName,
InvalidCatalogName,
InvalidSchemaName,
SerializationFailure,
StatementCompletionUnknown,
SyntaxErrorOrAccessViolation,
BaseTableOrViewAlreadyExists,
BaseTableOrViewNotFound,
IndexAlreadyExists,
IndexNotFound,
ColumnAlreadyExists,
ColumnNotFound,
WithCheckOptionViolation,
GeneralError,
MemoryAllocationFailure,
InvalidAppBufferType,
InvalidSqlDataType,
StatementNotPrepared,
OperationCanceled,
InvalidNullPointer,
FunctionSequnceError,
AttributeCannotBeSetNow,
InvalidTransactionOpcode,
MemoryManagementError,
ExcessHandles,
NoCursorNameAvailable,
CannotModifyImplRowDesc,
InvalidDescHandleUse,
ServerDeclinedCancel,
NonCharOrBinaryDataSIP, // @note: SIP == Sent in Pieces
AttemptToConcatNull,
InconsistentDescInfo,
InvalidAttributeValue,
InvalidBufferLength,
InvalidDescFieldIdentifier,
InvalidAttributeIdentifier,
FunctionTypeOutOfRange,
InvalidInfoType,
ColumnTypeOutOfRange,
ScopeTypeOutOfRange,
NullableTypeOutOfRange,
UniquenessOptionTypeOutOfRange,
AccuracyOptionTypeOutOfRange,
InvalidRetrievalCode,
InvalidPrecisionOrScaleValue,
InvalidParamType,
FetchTypeOutOfRange,
RowValueOutOfRange,
InvalidCursorPosition,
InvalidDriverCompletion,
InvalidBookmarkValue,
OptionalFeatureNotImplemented,
TimeoutExpired,
ConnectionTimeoutExpired,
FunctionNotSupported,
DSNNotFound,
DriverCouldNotBeLoaded,
EnvHandleAllocFailed,
ConnHandleAllocFailed,
SetConnectionAttrFailed,
DialogProhibited,
DialogFailed,
UnableToLoadTranslationDLL,
DSNTooLong,
DriverNameTooLong,
DriverKeywordSyntaxError,
TraceFileError,
InvalidFileDSN,
CorruptFileDataSource,
};
pub const OdbcError = StringEnum(SqlState, .{
.{"00000", .Success},
.{"01000", .GeneralWarning},
.{"01001", .CursorOperationConflict},
.{"01002", .DisconnectError},
.{"01003", .NullEliminated},
.{"01004", .StringRightTrunc},
.{"22001", .StringRightTrunc},
.{"01006", .PrivilegeNotRevoked},
.{"01007", .PrivilegeNotGranted},
.{"01S00", .InvalidConnectionStringAttr},
.{"01S01", .ErrorInRow},
.{"01S02", .OptionValueChanged},
.{"01S06", .FetchBeforeFirstResultSet},
.{"01S07", .FractionalTruncation},
.{"01S08", .ErrorSavingFileDSN},
.{"01S09", .InvalidKeyword},
.{"07001", .WrongNumberOfParameters},
.{"07002", .IncorrectCountField},
.{"07005", .PreparedStmtNotCursorSpec},
.{"07006", .RestrictedDataTypeAttr},
.{"07009", .InvalidDescIndex},
.{"07S01", .InvalidDefaultParam},
.{"08001", .ClientConnectionError},
.{"08002", .ConnectionNameInUse},
.{"08004", .ServerRejectedConnection},
.{"08007", .TransactionConnectionFailure},
.{"08S01", .CommunicationLinkFailure},
.{"21S01", .InsertValueColumnMismatch},
.{"21S02", .DerivedTableDegreeColumnMismatch},
.{"22002", .IndicatorVarRequired},
.{"22003", .NumOutOfRange},
.{"22007", .InvalidDatetimeFormat},
.{"22008", .DatetimeOverflow},
.{"22012", .DivisionByZero},
.{"22015", .IntervalFieldOverflow},
.{"22018", .InvalidCharacterValue},
.{"22019", .InvalidEscapeCharacter},
.{"22025", .InvalidEscapeSequence},
.{"22026", .StringLengthMismatch},
.{"23000", .IntegrityConstraintViolation},
.{"24000", .InvalidCursorState},
.{"25000", .InvalidTransactionState},
.{"25S01", .TransactionState},
.{"25S02", .TransactionStillActive},
.{"25S03", .TransactionRolledBack},
.{"28000", .InvalidAuthorization},
.{"34000", .InvalidCursorName},
.{"3C000", .DuplicateCursorName},
.{"3D000", .InvalidCatalogName},
.{"3F000", .InvalidSchemaName},
.{"40001", .SerializationFailure},
.{"40002", .IntegrityConstraintViolation},
.{"40003", .StatementCompletionUnknown},
.{"42000", .SyntaxErrorOrAccessViolation},
.{"42S01", .BaseTableOrViewAlreadyExists},
.{"42S02", .BaseTableOrViewNotFound},
.{"42S11", .IndexAlreadyExists},
.{"42S12", .IndexNotFound},
.{"42S21", .ColumnAlreadyExists},
.{"42S22", .ColumnNotFound},
.{"44000", .WithCheckOptionViolation},
.{"HY000", .GeneralError},
.{"HY001", .MemoryAllocationFailure},
.{"HY003", .InvalidAppBufferType},
.{"HY004", .InvalidSqlDataType},
.{"HY007", .StatementNotPrepared},
.{"HY008", .OperationCanceled},
.{"HY009", .InvalidNullPointer},
.{"HY010", .FunctionSequnceError},
.{"HY011", .AttributeCannotBeSetNow},
.{"HY012", .InvalidTransactionOpcode},
.{"HY013", .MemoryManagementError},
.{"HY014", .ExcessHandles},
.{"HY015", .NoCursorNameAvailable},
.{"HY016", .CannotModifyImplRowDesc},
.{"HY017", .InvalidDescHandleUse},
.{"HY018", .ServerDeclinedCancel},
.{"HY019", .NonCharOrBinaryDataSIP},
.{"HY020", .AttemptToConcatNull},
.{"HY021", .InconsistentDescInfo},
.{"HY024", .InvalidAttributeValue},
.{"HY090", .InvalidBufferLength},
.{"HY091", .InvalidDescFieldIdentifier},
.{"HY092", .InvalidAttributeIdentifier},
.{"HY095", .FunctionTypeOutOfRange},
.{"HY096", .InvalidInfoType},
.{"HY097", .ColumnTypeOutOfRange},
.{"HY098", .ScopeTypeOutOfRange},
.{"HY099", .NullableTypeOutOfRange},
.{"HY100", .UniquenessOptionTypeOutOfRange},
.{"HY101", .AccuracyOptionTypeOutOfRange},
.{"HY103", .InvalidRetrievalCode},
.{"HY104", .InvalidPrecisionOrScaleValue},
.{"HY105", .InvalidParamType},
.{"HY106", .FetchTypeOutOfRange},
.{"HY107", .RowValueOutOfRange},
.{"HY109", .InvalidCursorPosition},
.{"HY110", .InvalidDriverCompletion},
.{"HY111", .InvalidBookmarkValue},
.{"HYC00", .OptionalFeatureNotImplemented},
.{"HYT00", .TimeoutExpired},
.{"HYT01", .ConnectionTimeoutExpired},
.{"IM001", .FunctionNotSupported},
.{"IM002", .DSNNotFound},
.{"IM003", .DriverCouldNotBeLoaded},
.{"IM004", .EnvHandleAllocFailed},
.{"IM005", .ConnHandleAllocFailed},
.{"IM006", .SetConnectionAttrFailed},
.{"IM007", .DialogProhibited},
.{"IM008", .DialogFailed},
.{"IM009", .UnableToLoadTranslationDLL},
.{"IM010", .DSNTooLong},
.{"IM011", .DriverNameTooLong},
.{"IM012", .DriverKeywordSyntaxError},
.{"IM013", .TraceFileError},
.{"IM014", .InvalidFileDSN},
.{"IM015", .CorruptFileDataSource},
});
pub const DiagnosticRecord = struct {
sql_state: [5:0]u8,
error_code: i32,
error_message: []const u8,
pub fn deinit(self: *DiagnosticRecord, allocator: *Allocator) void {
allocator.free(self.error_message);
}
};
pub fn getDiagnosticRecords(allocator: *Allocator, handle_type: odbc.HandleType, handle: *c_void) ![]DiagnosticRecord {
var num_records: u64 = 0;
_ = c.SQLGetDiagField(@enumToInt(handle_type), handle, 0, @enumToInt(odbc.DiagnosticIdentifier.Number), &num_records, 0, null);
var records = try allocator.alloc(DiagnosticRecord, num_records);
errdefer allocator.free(records);
// Diagnostic records start counting at 1
var record_index: i16 = 1;
while (record_index <= num_records) : (record_index += 1) {
var record: DiagnosticRecord = undefined;
var error_message_buf = try allocator.alloc(u8, 200);
var error_message_length: c.SQLSMALLINT = 0;
const result = c.SQLGetDiagRec(
@enumToInt(handle_type),
handle,
record_index,
record.sql_state[0..],
@ptrCast([*c]c_int, &record.error_code),
@intToPtr([*c]u8, @ptrToInt(error_message_buf.ptr)),
@intCast(c_short, error_message_buf.len),
&error_message_length
);
switch (@intToEnum(odbc.SqlReturn, result)) {
.Success, .SuccessWithInfo => {
error_message_buf = try allocator.realloc(error_message_buf, @intCast(usize, error_message_length));
record.error_message = error_message_buf;
records[@intCast(usize, record_index - 1)] = record;
},
.InvalidHandle => return error.InvalidHandle,
else => break
}
}
return records;
}
pub fn getErrors(allocator: *Allocator, handle_type: odbc.HandleType, handle: *c_void) ![]SqlState {
var num_records: u64 = 0;
_ = c.SQLGetDiagField(@enumToInt(handle_type), handle, 0, @enumToInt(odbc.DiagnosticIdentifier.Number), &num_records, 0, null);
var errors = try allocator.alloc(SqlState, num_records);
errdefer allocator.free(errors);
// Diagnostic records start counting at 1
var record_index: i16 = 1;
while (record_index <= num_records) : (record_index += 1) {
var sql_state: [5:0]u8 = undefined;
const result = c.SQLGetDiagRec(@enumToInt(handle_type), handle, record_index, sql_state[0..], null, null, 0, null);
switch (@intToEnum(odbc.SqlReturn, result)) {
.Success, .SuccessWithInfo => errors[@intCast(usize, record_index - 1)] = try OdbcError.fromString(&sql_state),
.InvalidHandle => return error.InvalidHandle,
else => break
}
}
return errors;
}
|
src/error.zig
|
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const RunFn = fn (input: []const u8, allocator: std.mem.Allocator) tools.RunError![2][]const u8;
// it.runFn = @import(name); -> marche pas. doit être un string litteral
const alldays = [_]struct { runFn: RunFn, input: []const u8 }{
.{ .runFn = @import("day01.zig").run, .input = @embedFile("input_day01.txt") },
.{ .runFn = @import("day02.zig").run, .input = @embedFile("input_day02.txt") },
.{ .runFn = @import("day03.zig").run, .input = @embedFile("input_day03.txt") },
.{ .runFn = @import("day04.zig").run, .input = @embedFile("input_day04.txt") },
.{ .runFn = @import("day05.zig").run, .input = @embedFile("input_day05.txt") },
.{ .runFn = @import("day06.zig").run, .input = @embedFile("input_day06.txt") },
.{ .runFn = @import("day07.zig").run, .input = @embedFile("input_day07.txt") },
.{ .runFn = @import("day08.zig").run, .input = @embedFile("input_day08.txt") },
.{ .runFn = @import("day09.zig").run, .input = @embedFile("input_day09.txt") },
.{ .runFn = @import("day10.zig").run, .input = @embedFile("input_day10.txt") },
.{ .runFn = @import("day11.zig").run, .input = @embedFile("input_day11.txt") },
.{ .runFn = @import("day12.zig").run, .input = @embedFile("input_day12.txt") },
.{ .runFn = @import("day13.zig").run, .input = "" },
.{ .runFn = @import("day14.zig").run, .input = @embedFile("input_day14.txt") },
.{ .runFn = @import("day15.zig").run, .input = "" },
.{ .runFn = @import("day16.zig").run, .input = @embedFile("input_day16.txt") },
.{ .runFn = @import("day17.zig").run, .input = @embedFile("input_day17.txt") },
.{ .runFn = @import("day18.zig").run, .input = @embedFile("input_day18.txt") },
.{ .runFn = @import("day19.zig").run, .input = @embedFile("input_day19.txt") },
.{ .runFn = @import("day20.zig").run, .input = @embedFile("input_day20.txt") },
.{ .runFn = @import("day21.zig").run, .input = @embedFile("input_day21.txt") },
.{ .runFn = @import("day22.zig").run, .input = @embedFile("input_day22.txt") },
.{ .runFn = @import("day23.zig").run, .input = "156794823" },
.{ .runFn = @import("day24.zig").run, .input = @embedFile("input_day24.txt") },
.{ .runFn = @import("day25.zig").run, .input = "" },
};
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
for (alldays) |it, day| {
const answer = try it.runFn(it.input, allocator);
defer allocator.free(answer[0]);
defer allocator.free(answer[1]);
try stdout.print("Day {d:0>2}:\n", .{day + 1});
for (answer) |ans, i| {
const multiline = (std.mem.indexOfScalar(u8, ans, '\n') != null);
if (multiline) {
try stdout.print("\tPART {d}:\n{s}", .{ i + 1, ans });
} else {
try stdout.print("\tPART {d}: {s}\n", .{ i + 1, ans });
}
}
}
}
|
2020/alldays.zig
|
const std = @import("std");
const app = @import("app");
pub const Measurement = struct {
median: u64,
mean: u64,
min: u64,
max: u64,
fn compute(all_samples: []Sample, comptime field: []const u8) Measurement {
const S = struct {
fn order(a: Sample, b: Sample) bool {
return @field(a, field) < @field(b, field);
}
};
// Remove the 2 outliers
std.sort.sort(Sample, all_samples, S.order);
const samples = all_samples[1 .. all_samples.len - 1];
// Compute stats
var total: u64 = 0;
var min: u64 = std.math.maxInt(u64);
var max: u64 = 0;
for (samples) |s| {
const v = @field(s, field);
total += v;
if (v < min) min = v;
if (v > max) max = v;
}
return .{
.median = @field(samples[samples.len / 2], field),
.mean = total / samples.len,
.min = min,
.max = max,
};
}
};
pub const Results = union(enum) {
fail: anyerror,
ok: struct {
samples_taken: usize,
wall_time: Measurement,
utime: Measurement,
stime: Measurement,
maxrss: usize,
},
};
const Sample = struct {
wall_time: u64,
utime: u64,
stime: u64,
};
fn timeval_to_ns(timeval: std.os.timeval) u64 {
const ns_per_us = std.time.ns_per_s / std.time.us_per_s;
return @bitCast(usize, timeval.tv_sec) * std.time.ns_per_s +
@bitCast(usize, timeval.tv_usec) * ns_per_us;
}
var samples_buf: [1000000]Sample = undefined;
const max_nano_seconds = std.time.ns_per_s * 10;
pub fn bench(options: Options, comptime func: var, args: var) Results {
var sample_index: usize = 0;
const timer = std.time.Timer.start() catch @panic("need timer to work");
const first_start = timer.read();
while ((sample_index < 3 or
(timer.read() - first_start) < max_nano_seconds) and
sample_index < samples_buf.len)
{
if (options.clear_zig_cache) {
std.fs.cwd().deleteTree("zig-cache") catch |err| {
std.debug.panic("unable to delete zig-cache: {}", .{@errorName(err)});
};
std.fs.cwd().deleteTree("../../zig-builds/src/zig-cache") catch |err| {
std.debug.panic("unable to delete zig-cache: {}", .{@errorName(err)});
};
std.fs.cwd().deleteTree("../../zig-builds/src/build/zig-cache") catch |err| {
std.debug.panic("unable to delete zig-cache: {}", .{@errorName(err)});
};
}
const start_rusage = std.os.getrusage(options.rusage_who);
const start = timer.read();
@call(.{}, func, args) catch |err| {
return .{ .fail = err };
};
const end = timer.read();
const end_rusage = std.os.getrusage(options.rusage_who);
samples_buf[sample_index] = .{
.wall_time = end - start,
.utime = timeval_to_ns(end_rusage.utime) - timeval_to_ns(start_rusage.utime),
.stime = timeval_to_ns(end_rusage.stime) - timeval_to_ns(start_rusage.stime),
};
sample_index += 1;
}
const all_samples = samples_buf[0..sample_index];
const wall_time = Measurement.compute(all_samples, "wall_time");
const utime = Measurement.compute(all_samples, "utime");
const stime = Measurement.compute(all_samples, "stime");
const final_rusage = std.os.getrusage(options.rusage_who);
return .{
.ok = .{
.samples_taken = all_samples.len,
.wall_time = wall_time,
.utime = utime,
.stime = stime,
.maxrss = @bitCast(usize, final_rusage.maxrss),
},
};
}
pub const Options = struct {
rusage_who: i32 = std.os.RUSAGE_SELF,
zig_exe: []const u8,
clear_zig_cache: bool = false,
};
pub fn main() !void {
const gpa = if (std.builtin.link_libc) std.heap.c_allocator else std.heap.page_allocator;
var options: Options = .{
.zig_exe = std.mem.spanZ(std.os.argv[1]),
};
const context = try app.setup(gpa, &options);
const results = bench(options, app.run, .{ gpa, context });
try std.json.stringify(results, std.json.StringifyOptions{}, std.io.getStdOut().outStream());
}
pub fn exec(
gpa: *std.mem.Allocator,
argv: []const []const u8,
options: struct {
cwd: ?[]const u8 = null,
stdin_behavior: std.ChildProcess.StdIo = .Inherit,
stdout_behavior: std.ChildProcess.StdIo = .Inherit,
stderr_behavior: std.ChildProcess.StdIo = .Inherit,
},
) !void {
const child = try std.ChildProcess.init(argv, gpa);
defer child.deinit();
child.stdin_behavior = options.stdin_behavior;
child.stdout_behavior = options.stdout_behavior;
child.stderr_behavior = options.stderr_behavior;
child.cwd = options.cwd;
const term = try child.spawnAndWait();
switch (term) {
.Exited => |code| {
if (code != 0) {
return error.ChildProcessBadExitCode;
}
},
else => {
return error.ChildProcessCrashed;
},
}
}
|
bench.zig
|
const std = @import("std");
pub const zgt = @import("zgt");
pub usingnamespace zgt;
pub fn ZervoView() zgt.Canvas_Impl {
var canvas = zgt.Canvas(.{});
return canvas;
}
pub const FontMetrics = struct {
ascent: f64,
descent: f64,
height: f64
};
pub const TextMetrics = struct {
width: f64,
height: f64
};
pub const GraphicsBackend = struct {
ctx: zgt.DrawContext,
layout: ?zgt.DrawContext.TextLayout = null,
font: zgt.DrawContext.Font = .{ .face = "monospace", .size = 12.0 },
request_next_frame: bool = false,
x: f64 = 0,
y: f64 = 0,
cursorX: f64 = 0,
cursorY: f64 = 0,
width: f64 = 0,
height: f64 = 0,
userData: usize = 0,
frame_requested: bool = false,
pub const MouseButton = enum(u2) {
Left = 0,
Right = 1,
Middle = 2,
};
pub fn getCursorX(self: *GraphicsBackend) f64 {
return self.cursorX;
}
pub fn getCursorY(self: *GraphicsBackend) f64 {
return self.cursorY;
}
pub fn getWidth(self: *GraphicsBackend) f64 {
return self.width;
}
pub fn getHeight(self: *GraphicsBackend) f64 {
return self.height;
}
// Draw functions
pub fn fill(self: *GraphicsBackend) void {
self.ctx.fill();
}
pub fn stroke(self: *GraphicsBackend) void {
_ = self;
unreachable; // TODO
}
pub fn setSourceRGB(self: *GraphicsBackend, r: f64, g: f64, b: f64) void {
self.setSourceRGBA(r, g, b, 1.0);
}
pub fn setSourceRGBA(self: *GraphicsBackend, r: f64, g: f64, b: f64, a: f64) void {
self.ctx.setColorRGBA(@floatCast(f32, r), @floatCast(f32, g), @floatCast(f32, b), @floatCast(f32, a));
}
// Path
pub fn moveTo(self: *GraphicsBackend, x: f64, y: f64) void {
self.x = x;
self.y = y;
}
pub fn moveBy(self: *GraphicsBackend, x: f64, y: f64) void {
self.x += x;
self.y += y;
}
pub fn lineTo(self: *GraphicsBackend, x: f64, y: f64) void {
_ = self;
_ = x;
_ = y;
unreachable; // TODO
}
pub fn rectangle(self: *GraphicsBackend, x: f64, y: f64, width: f64, height: f64) void {
self.ctx.rectangle(
@floatToInt(u32, @floor(x)), @floatToInt(u32, @floor(y)),
@floatToInt(u32, @floor(width)), @floatToInt(u32, @floor(height)));
}
pub fn setTextWrap(self: *GraphicsBackend, width: ?f64) void {
if (self.layout == null) {
self.layout = zgt.DrawContext.TextLayout.init();
}
self.layout.?.wrap = width;
}
pub fn text(self: *GraphicsBackend, str: [:0]const u8) void {
if (self.layout == null) {
self.layout = zgt.DrawContext.TextLayout.init();
}
self.ctx.text(@floatToInt(i32, @floor(self.x)), @floatToInt(i32, @floor(self.y)),
self.layout.?, str);
}
pub fn setFontFace(self: *GraphicsBackend, font: [:0]const u8) void {
if (self.layout == null) {
self.layout = zgt.DrawContext.TextLayout.init();
}
self.font.face = font;
self.layout.?.setFont(self.font);
}
pub fn setFontSize(self: *GraphicsBackend, size: f64) void {
if (self.layout == null) {
self.layout = zgt.DrawContext.TextLayout.init();
}
self.font.size = size;
self.layout.?.setFont(self.font);
}
pub fn getFontMetrics(self: *GraphicsBackend) FontMetrics {
_ = self;
@panic("unimplemented");
//return undefined;
}
pub fn getTextMetrics(self: *GraphicsBackend, str: [:0]const u8) TextMetrics {
_ = str;
const metrics = self.layout.?.getTextSize(str);
return TextMetrics {
.width = @intToFloat(f64, metrics.width),
.height = @intToFloat(f64, metrics.height)
};
}
pub fn clear(self: *GraphicsBackend) void {
self.setSourceRGB(1.0, 1.0, 1.0);
self.rectangle(0, 0, self.getWidth(), self.getHeight());
self.fill();
}
};
|
src/zgt.zig
|
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day23.txt");
const Input = struct {
stack1: [2]u8,
stack2: [2]u8,
stack3: [2]u8,
stack4: [2]u8,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var lines = std.mem.tokenize(u8, input_text, "\r\n");
_ = lines.next();
_ = lines.next();
const row1 = lines.next().?;
const row2 = lines.next().?;
var input = Input{
.stack1 = [2]u8{ row2[3], row1[3] },
.stack2 = [2]u8{ row2[5], row1[5] },
.stack3 = [2]u8{ row2[7], row1[7] },
.stack4 = [2]u8{ row2[9], row1[9] },
};
errdefer input.deinit();
return input;
}
pub fn deinit(self: @This()) void {
_ = self;
}
};
fn energy(pod: u8) i64 {
const POD_ENERGIES = [4]i64{ 1, 10, 100, 1000 };
return POD_ENERGIES[pod - 'A'];
}
fn goal(pod: u8) i8 {
const POD_GOALS = [4]i8{ 2, 4, 6, 8 };
return POD_GOALS[pod - 'A'];
}
// 0123456789A
//#############
//#...........#
//###A#B#C#D###
const LEFT_FROM = [11][]const usize{
&.{}, // 0
&.{0}, // 1
&.{ 1, 0 }, // 2
&.{ 1, 0 }, // 3
&.{ 3, 1, 0 }, // 4
&.{ 3, 1, 0 }, // 5
&.{ 5, 3, 1, 0 }, // 6
&.{ 5, 3, 1, 0 }, // 7
&.{ 7, 5, 3, 1, 0 }, // 8
&.{ 7, 5, 3, 1, 0 }, // 9
&.{ 9, 7, 5, 3, 1, 0 }, // 10
};
const RIGHT_FROM = [11][]const usize{
&.{ 1, 3, 5, 7, 9, 10 }, // 0
&.{ 3, 5, 7, 9, 10 }, // 1
&.{ 3, 5, 7, 9, 10 }, // 2
&.{ 5, 7, 9, 10 }, // 3
&.{ 5, 7, 9, 10 }, // 4
&.{ 7, 9, 10 }, // 5
&.{ 7, 9, 10 }, // 6
&.{ 9, 10 }, // 7
&.{ 9, 10 }, // 8
&.{10}, // 9
&.{}, // 10
};
const PodStack = struct {
array: std.BoundedArray(u8, 4) = undefined,
x: i8 = undefined,
num_to_sink: u8 = undefined,
pub fn init(pods: []const u8, x: i8) @This() {
var self = PodStack{
.array = std.BoundedArray(u8, 4).init(0) catch unreachable,
.x = x,
.num_to_sink = @truncate(u8, pods.len),
};
for (pods) |pod| {
self.array.appendAssumeCapacity(pod);
}
const sink_pod: u8 = 'A' + @intCast(u8, @divFloor(x - 2, 2));
while (!self.empty() and self.array.buffer[0] == sink_pod) {
_ = self.array.orderedRemove(0);
self.num_to_sink -= 1;
}
return self;
}
pub fn empty(self: @This()) bool {
return (self.array.len == 0);
}
pub fn top(self: @This()) ?u8 {
if (self.empty())
return null;
const top_index = self.array.len - 1;
const top_elem = self.array.buffer[top_index];
return top_elem;
}
pub fn pop(self: *@This()) ?u8 {
return self.array.popOrNull();
}
pub fn cost(self: @This()) i64 {
var total: i64 = 0;
for (self.array.constSlice()) |pod| {
const gx = goal(pod);
const e = energy(pod);
total += if (gx == self.x) e * 2 else e * @intCast(i64, std.math.absInt(self.x - gx) catch unreachable);
}
return total;
}
};
const Move = struct {
pod: u8,
x0: i8,
x1: i8,
pub fn cost(self: @This()) i64 {
return energy(self.pod) * @intCast(i64, std.math.absInt(self.x1 - self.x0) catch unreachable);
}
};
const MapState = struct {
stacks: [4]PodStack = undefined,
hallway: [11]u8 = .{'.'} ** 11,
moves: std.BoundedArray(Move, 32) = undefined,
cost: i64 = 0,
fixed_cost: i64 = 0,
pub fn init(stack1: []const u8, stack2: []const u8, stack3: []const u8, stack4: []const u8) @This() {
var self = MapState{
.stacks = [4]PodStack{
PodStack.init(stack1, 2),
PodStack.init(stack2, 4),
PodStack.init(stack3, 6),
PodStack.init(stack4, 8),
},
.moves = std.BoundedArray(Move, 32).init(0) catch unreachable,
};
// compute fixed cost: moving pods into & out of hallways.
var countA: i64 = 0;
var countB: i64 = 0;
var countC: i64 = 0;
var countD: i64 = 0;
var moveA: i64 = 0;
var moveB: i64 = 0;
var moveC: i64 = 0;
var moveD: i64 = 0;
for (self.stacks) |stack| {
const L = stack.array.len;
for (stack.array.constSlice()) |pod, i| {
if (pod == 'A') {
countA += 1;
moveA += @intCast(i64, L - i) + countA;
} else if (pod == 'B') {
countB += 1;
moveB += @intCast(i64, L - i) + countB;
} else if (pod == 'C') {
countC += 1;
moveC += @intCast(i64, L - i) + countC;
} else if (pod == 'D') {
countD += 1;
moveD += @intCast(i64, L - i) + countD;
}
}
}
self.fixed_cost = (moveA * energy('A')) + (moveB * energy('B')) + (moveC * energy('C')) + (moveD * energy('D'));
return self;
}
pub fn done(self: @This()) bool {
return (self.stacks[0].num_to_sink == 0 and self.stacks[1].num_to_sink == 0 and self.stacks[2].num_to_sink == 0 and self.stacks[3].num_to_sink == 0);
}
// conservative estimate of the cost to complete the map from this state
pub fn costEstimate(self: @This()) i64 {
var total: i64 = 0;
for (self.stacks) |stack| {
total += stack.cost();
}
for (self.hallway) |pod, x| {
if (pod == '.') {
continue;
} else {
const gx = goal(pod);
const sx = @intCast(i8, x);
const e = energy(pod);
total += e * @intCast(i64, std.math.absInt(sx - gx) catch unreachable);
}
}
return total;
}
pub fn applyMove(self: *@This(), move: Move) void {
if (move.x0 == 2 or move.x0 == 4 or move.x0 == 6 or move.x0 == 8) {
// moving a pod from a stack into the hallway
const si = @intCast(usize, @divFloor(move.x0 - 2, 2));
assert(self.stacks[si].top().? == move.pod); // is this pod actually at the top of this stack?
const hx = @intCast(usize, move.x1);
assert(self.hallway[hx] == '.'); // is the destination in the hallway empty?
_ = self.stacks[si].pop();
self.hallway[hx] = move.pod;
} else if (move.x1 == 2 or move.x1 == 4 or move.x1 == 6 or move.x1 == 8) {
// moving a pod from the hallway into its sink
const si: usize = move.pod - 'A';
assert(si == @intCast(usize, @divFloor(move.x1 - 2, 2))); // is this the correct sink for this pod?
assert(self.stacks[si].empty()); // is the sink an empty stack?
assert(self.stacks[si].num_to_sink > 0); // does it still have room to sink things?
const hx = @intCast(usize, move.x0);
assert(self.hallway[hx] == move.pod); // is the pod we're moving actually in its source pos?
self.stacks[si].num_to_sink -= 1;
self.hallway[hx] = '.';
} else {
unreachable;
}
self.moves.appendAssumeCapacity(move);
self.cost += move.cost();
}
};
fn solveMap(state: MapState, lowest_cost: *i64) void {
if (state.cost + state.costEstimate() >= lowest_cost.*) {
return; // no point in pursuing this path
}
if (state.done()) {
if (state.cost < lowest_cost.*) {
lowest_cost.* = state.cost;
//print("New shortest solution:\n", .{});
//for (state.moves.constSlice()) |move| {
// if (move.x0 == 2 or move.x0 == 4 or move.x0 == 6 or move.x0 == 8) {
// print("Move {c} from stack {d} to hall {d}\n", .{ move.pod, move.x0, move.x1 });
// } else {
// print("Move {c} from hall {d} to sink {d}\n", .{ move.pod, move.x0, move.x1 });
// }
//}
}
return;
}
// hallway moves first; it's always best to move things out of the hallway if possible.
hallway_loop: for (state.hallway) |pod, i| {
if (pod == '.' or !state.stacks[pod - 'A'].empty()) {
continue;
}
var px = @intCast(i8, i);
var gx = goal(pod);
const x0 = @intCast(usize, if (gx < px) gx else px + 1);
const x1 = @intCast(usize, if (gx < px) px else gx + 1);
for (state.hallway[x0..x1]) |c| {
if (c != '.') {
continue :hallway_loop;
}
}
// pod can move to its goal
var new_state = state;
new_state.applyMove(Move{ .pod = pod, .x0 = px, .x1 = gx });
solveMap(new_state, lowest_cost);
}
// move things out of the stacks
for (state.stacks) |stack| {
if (stack.empty()) {
continue;
}
const p = stack.top().?;
const px: i8 = stack.x;
// TODO: could be more clever here, prioritizing closer moves in either direction rather than a
// depth-first search in one direction and the other.
for (LEFT_FROM[@intCast(usize, px)]) |hx| {
if (state.hallway[hx] != '.') {
break; // this & further cells in this direction are blocked, can't move here.
}
// pod can move here
//print("Move: {c},{d},{d} [from stack]\n", .{ pod, px, hx });
var new_state = state;
new_state.applyMove(Move{ .pod = p, .x0 = px, .x1 = @intCast(i8, hx) });
solveMap(new_state, lowest_cost);
}
for (RIGHT_FROM[@intCast(usize, px)]) |hx| {
if (state.hallway[hx] != '.') {
break; // this & further cells in this direction are blocked, can't move here.
}
// pod can move here
//print("Move: {c},{d},{d} [from stack]\n", .{ pod, px, hx });
var new_state = state;
new_state.applyMove(Move{ .pod = p, .x0 = px, .x1 = @intCast(i8, hx) });
solveMap(new_state, lowest_cost);
}
}
}
fn sanityCheck() !i64 {
var lowest_cost: i64 = std.math.maxInt(i64);
var state = MapState.init("AB", "DC", "CB", "AD");
solveMap(state, &lowest_cost);
const fixed_cost = 3 * energy('A') + 5 * energy('B') + 2 * energy('C') + 6 * energy('D');
return lowest_cost + fixed_cost;
}
fn part1(input: Input) i64 {
var state = MapState.init(input.stack1[0..], input.stack2[0..], input.stack3[0..], input.stack4[0..]);
var lowest_cost: i64 = std.math.maxInt(i64);
solveMap(state, &lowest_cost);
assert(lowest_cost < std.math.maxInt(i64));
const fixed_cost = state.fixed_cost;
return lowest_cost + fixed_cost;
}
fn part2(input: Input) i64 {
const stack1 = [4]u8{ input.stack1[0], 'D', 'D', input.stack1[1] };
const stack2 = [4]u8{ input.stack2[0], 'B', 'C', input.stack2[1] };
const stack3 = [4]u8{ input.stack3[0], 'A', 'B', input.stack3[1] };
const stack4 = [4]u8{ input.stack4[0], 'C', 'A', input.stack4[1] };
var state = MapState.init(stack1[0..], stack2[0..], stack3[0..], stack4[0..]);
var lowest_cost: i64 = std.math.maxInt(i64);
solveMap(state, &lowest_cost);
assert(lowest_cost < std.math.maxInt(i64));
const fixed_cost = state.fixed_cost;
return lowest_cost + fixed_cost;
}
const test_data =
\\#############
\\#...........#
\\###B#C#B#D###
\\ #A#D#C#A#
\\ #########
;
const part1_test_solution: ?i64 = 12521;
const part1_solution: ?i64 = 11332;
const part2_test_solution: ?i64 = 44169;
const part2_solution: ?i64 = 49936;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
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/day23.zig
|
const aoc = @import("../aoc.zig");
const std = @import("std");
const Instruction = [3][]const u8;
const Computer = struct {
const Registers = std.StringHashMap(usize);
const Instructions = std.StringHashMap(fn(*Computer, Instruction)std.fmt.ParseIntError!isize);
registers: Registers,
instructions: Instructions,
fn init(allocator: std.mem.Allocator) !Computer {
var computer = Computer { .registers = Registers.init(allocator), .instructions = Instructions.init(allocator) };
try computer.instructions.putNoClobber("hlf", hlf);
try computer.instructions.putNoClobber("tpl", tpl);
try computer.instructions.putNoClobber("inc", inc);
try computer.instructions.putNoClobber("jmp", jmp);
try computer.instructions.putNoClobber("jie", jie);
try computer.instructions.putNoClobber("jio", jio);
return computer;
}
fn deinit(self: *Computer) void {
self.registers.deinit();
self.instructions.deinit();
}
fn execute(self: *Computer, instructions: []const Instruction, a: usize) !usize {
try self.registers.put("a", a);
try self.registers.put("b", 0);
var pc: isize = 0;
while (pc >= 0 and pc < instructions.len) {
const instruction = instructions[@intCast(usize, pc)];
const callback = self.instructions.get(instruction[0]).?;
pc += try callback(self, instruction);
}
return self.registers.get("b").?;
}
fn hlf(self: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
self.registers.getPtr(instruction[1]).?.* /= 2;
return 1;
}
fn tpl(self: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
self.registers.getPtr(instruction[1]).?.* *= 3;
return 1;
}
fn inc(self: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
self.registers.getPtr(instruction[1]).?.* += 1;
return 1;
}
fn jmp(_: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
return jump(instruction[1]);
}
fn jie(self: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
return if (self.registers.get(instruction[1]).? % 2 == 0) jump(instruction[2]) else 1;
}
fn jio(self: *Computer, instruction: Instruction) std.fmt.ParseIntError!isize {
return if (self.registers.get(instruction[1]).? == 1) jump(instruction[2]) else 1;
}
fn jump(offset: []const u8) std.fmt.ParseIntError!isize {
const dir: isize = if (offset[0] == '+') 1 else -1;
return dir * try std.fmt.parseInt(isize, offset[1..], 10);
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var computer = try Computer.init(problem.allocator);
defer computer.deinit();
var instructions = std.ArrayList(Instruction).init(problem.allocator);
defer instructions.deinit();
while (problem.line()) |line| {
var instruction: Instruction = undefined;
var idx: usize = 0;
var tokens = std.mem.tokenize(u8, line, " ,");
while (tokens.next()) |token| {
instruction[idx] = token;
idx += 1;
}
try instructions.append(instruction);
}
return problem.solution(
try computer.execute(instructions.items, 0),
try computer.execute(instructions.items, 1)
);
}
|
src/main/zig/2015/day23.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 Repository = opaque {
pub fn deinit(self: *Repository) void {
log.debug("Repository.deinit called", .{});
c.git_repository_free(@ptrCast(*c.git_repository, self));
log.debug("repository closed successfully", .{});
}
pub fn state(self: *Repository) RepositoryState {
log.debug("Repository.state called", .{});
const ret = @intToEnum(RepositoryState, c.git_repository_state(@ptrCast(*c.git_repository, self)));
log.debug("repository state: {s}", .{@tagName(ret)});
return ret;
}
pub const RepositoryState = enum(c_int) {
NONE,
MERGE,
REVERT,
REVERT_SEQUENCE,
CHERRYPICK,
CHERRYPICK_SEQUENCE,
BISECT,
REBASE,
REBASE_INTERACTIVE,
REBASE_MERGE,
APPLY_MAILBOX,
APPLY_MAILBOX_OR_REBASE,
};
/// Describe a commit
///
/// Perform the describe operation on the current commit and the worktree.
pub fn describe(self: *Repository, options: git.DescribeOptions) !*git.DescribeResult {
log.debug("Repository.describe called, options={}", .{options});
var result: *git.DescribeResult = undefined;
var c_options = options.makeCOptionObject();
try internal.wrapCall("git_describe_workdir", .{
@ptrCast(*?*c.git_describe_result, &result),
@ptrCast(*c.git_repository, self),
&c_options,
});
log.debug("successfully described commitish object", .{});
return result;
}
/// Retrieve the configured identity to use for reflogs
pub fn identityGet(self: *const Repository) !Identity {
log.debug("Repository.identityGet called", .{});
var c_name: [*c]u8 = undefined;
var c_email: [*c]u8 = undefined;
try internal.wrapCall("git_repository_ident", .{ &c_name, &c_email, @ptrCast(*const c.git_repository, self) });
const name: ?[:0]const u8 = if (c_name) |ptr| std.mem.sliceTo(ptr, 0) else null;
const email: ?[:0]const u8 = if (c_email) |ptr| std.mem.sliceTo(ptr, 0) else null;
log.debug("identity acquired: name={s}, email={s}", .{ name, email });
return Identity{ .name = name, .email = email };
}
/// Set the identity to be used for writing reflogs
///
/// If both are set, this name and email will be used to write to the reflog.
/// Set to `null` to unset; When unset, the identity will be taken from the repository's configuration.
pub fn identitySet(self: *Repository, identity: Identity) !void {
log.debug("Repository.identitySet called, identity.name={s}, identity.email={s}", .{ identity.name, identity.email });
const name_temp: [*c]const u8 = if (identity.name) |slice| slice.ptr else null;
const email_temp: [*c]const u8 = if (identity.email) |slice| slice.ptr else null;
try internal.wrapCall("git_repository_set_ident", .{ @ptrCast(*c.git_repository, self), name_temp, email_temp });
log.debug("successfully set identity", .{});
}
pub const Identity = struct {
name: ?[:0]const u8,
email: ?[:0]const u8,
};
pub fn namespaceGet(self: *Repository) !?[:0]const u8 {
log.debug("Repository.namespaceGet called", .{});
const ret = c.git_repository_get_namespace(@ptrCast(*c.git_repository, self));
if (ret) |ptr| {
const slice = std.mem.sliceTo(ptr, 0);
log.debug("namespace: {s}", .{slice});
return slice;
}
log.debug("no namespace", .{});
return null;
}
/// Sets the active namespace for this Git Repository
///
/// This namespace affects all reference operations for the repo. See `man gitnamespaces`
///
/// ## Parameters
/// * `namespace` - The namespace. This should not include the refs folder, e.g. to namespace all references under
/// "refs/namespaces/foo/", use "foo" as the namespace.
pub fn namespaceSet(self: *Repository, namespace: [:0]const u8) !void {
log.debug("Repository.namespaceSet called, namespace={s}", .{namespace});
try internal.wrapCall("git_repository_set_namespace", .{ @ptrCast(*c.git_repository, self), namespace.ptr });
log.debug("successfully set namespace", .{});
}
pub fn isHeadDetached(self: *Repository) !bool {
log.debug("Repository.isHeadDetached called", .{});
const ret = (try internal.wrapCallWithReturn("git_repository_head_detached", .{
@ptrCast(*c.git_repository, self),
})) == 1;
log.debug("is head detached: {}", .{ret});
return ret;
}
pub fn head(self: *Repository) !*git.Reference {
log.debug("Repository.head called", .{});
var ref: *git.Reference = undefined;
try internal.wrapCall("git_repository_head", .{
@ptrCast(*?*c.git_reference, &ref),
@ptrCast(*c.git_repository, self),
});
log.debug("reference opened successfully", .{});
return ref;
}
/// Make the repository HEAD point to the specified reference.
///
/// If the provided reference points to a Tree or a Blob, the HEAD is unaltered and an error is returned.
///
/// If the provided reference points to a branch, the HEAD will point to that branch, staying attached, or become attached if
/// it isn't yet. If the branch doesn't exist yet, the HEAD will be attached to an unborn branch.
///
/// Otherwise, the HEAD will be detached and will directly point to the commit.
///
/// ## Parameters
/// * `ref_name` - Canonical name of the reference the HEAD should point at
pub fn headSet(self: *Repository, ref_name: [:0]const u8) !void {
log.debug("Repository.headSet called, workdir={s}", .{ref_name});
try internal.wrapCall("git_repository_set_head", .{ @ptrCast(*c.git_repository, self), ref_name.ptr });
log.debug("successfully set head", .{});
}
/// Make the repository HEAD directly point to a commit.
///
/// If the provided commit cannot be found in the repository `GitError.NotFound` is returned.
/// If the provided commit cannot be peeled into a commit, the HEAD is unaltered and an error is returned.
/// Otherwise, the HEAD will eventually be detached and will directly point to the peeled commit.
///
/// ## Parameters
/// * `commit` - Object id of the commit the HEAD should point to
pub fn headDetachedSet(self: *Repository, commit: git.Oid) !void {
// 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 commit.formatHex(&buf);
log.debug("Repository.headDetachedSet called, commit={s}", .{slice});
}
try internal.wrapCall("git_repository_set_head_detached", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, &commit),
});
log.debug("successfully set head", .{});
}
/// Make the repository HEAD directly point to the commit.
///
/// This behaves like `Repository.setHeadDetached` but takes an annotated commit, which lets you specify which
/// extended sha syntax string was specified by a user, allowing for more exact reflog messages.
///
/// See the documentation for `Repository.setHeadDetached`.
pub fn setHeadDetachedFromAnnotated(self: *Repository, commitish: *git.AnnotatedCommit) !void {
// 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 oid = try commitish.commitId();
const slice = try oid.formatHex(&buf);
log.debug("Repository.setHeadDetachedFromAnnotated called, commitish={s}", .{slice});
}
try internal.wrapCall("git_repository_set_head_detached_from_annotated", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_annotated_commit, commitish),
});
log.debug("successfully set head", .{});
}
/// Detach the HEAD.
///
/// If the HEAD is already detached and points to a Tag, the HEAD is updated into making it point to the peeled commit.
/// If the HEAD is already detached and points to a non commitish, the HEAD is unaltered, and an error is returned.
///
/// Otherwise, the HEAD will be detached and point to the peeled commit.
pub fn detachHead(self: *Repository) !void {
log.debug("Repository.detachHead called", .{});
try internal.wrapCall("git_repository_detach_head", .{@ptrCast(*c.git_repository, self)});
log.debug("successfully detached the head", .{});
}
pub fn isHeadForWorktreeDetached(self: *Repository, name: [:0]const u8) !bool {
log.debug("Repository.isHeadForWorktreeDetached called, name={s}", .{name});
const ret = (try internal.wrapCallWithReturn(
"git_repository_head_detached_for_worktree",
.{ @ptrCast(*c.git_repository, self), name.ptr },
)) == 1;
log.debug("head for worktree {s} is detached: {}", .{ name, ret });
return ret;
}
pub fn headForWorktree(self: *Repository, name: [:0]const u8) !*git.Reference {
log.debug("Repository.headForWorktree called, name={s}", .{name});
var ref: *git.Reference = undefined;
try internal.wrapCall("git_repository_head_for_worktree", .{
@ptrCast(*?*c.git_reference, &ref),
@ptrCast(*c.git_repository, self),
name.ptr,
});
log.debug("reference opened successfully", .{});
return ref;
}
pub fn isHeadUnborn(self: *Repository) !bool {
log.debug("Repository.isHeadUnborn called", .{});
const ret = (try internal.wrapCallWithReturn("git_repository_head_unborn", .{@ptrCast(*c.git_repository, self)})) == 1;
log.debug("is head unborn: {}", .{ret});
return ret;
}
pub fn isShallow(self: *Repository) bool {
log.debug("Repository.isShallow called", .{});
const ret = c.git_repository_is_shallow(@ptrCast(*c.git_repository, self)) == 1;
log.debug("is repository a shallow clone: {}", .{ret});
return ret;
}
pub fn isEmpty(self: *Repository) !bool {
log.debug("Repository.isEmpty called", .{});
const ret = (try internal.wrapCallWithReturn("git_repository_is_empty", .{@ptrCast(*c.git_repository, self)})) == 1;
log.debug("is repository empty: {}", .{ret});
return ret;
}
pub fn isBare(self: *const Repository) bool {
log.debug("Repository.isBare called", .{});
const ret = c.git_repository_is_bare(@ptrCast(*const c.git_repository, self)) == 1;
log.debug("is repository bare: {}", .{ret});
return ret;
}
pub fn isWorktree(self: *const Repository) bool {
log.debug("Repository.isWorktree called", .{});
const ret = c.git_repository_is_worktree(@ptrCast(*const c.git_repository, self)) == 1;
log.debug("is repository worktree: {}", .{ret});
return ret;
}
/// Get the location of a specific repository file or directory
pub fn itemPath(self: *const Repository, item: RepositoryItem) !git.Buf {
log.debug("Repository.itemPath called, item={s}", .{item});
var buf: git.Buf = .{};
try internal.wrapCall("git_repository_item_path", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*const c.git_repository, self),
@enumToInt(item),
});
log.debug("item path: {s}", .{buf.toSlice()});
return buf;
}
pub const RepositoryItem = enum(c_uint) {
GITDIR,
WORKDIR,
COMMONDIR,
INDEX,
OBJECTS,
REFS,
PACKED_REFS,
REMOTES,
CONFIG,
INFO,
HOOKS,
LOGS,
MODULES,
WORKTREES,
};
pub fn pathGet(self: *const Repository) [:0]const u8 {
log.debug("Repository.pathGet called", .{});
const slice = std.mem.sliceTo(c.git_repository_path(@ptrCast(*const c.git_repository, self)), 0);
log.debug("path: {s}", .{slice});
return slice;
}
pub fn workdirGet(self: *const Repository) ?[:0]const u8 {
log.debug("Repository.workdirGet called", .{});
if (c.git_repository_workdir(@ptrCast(*const c.git_repository, self))) |ret| {
const slice = std.mem.sliceTo(ret, 0);
log.debug("workdir: {s}", .{slice});
return slice;
}
log.debug("no workdir", .{});
return null;
}
pub fn workdirSet(self: *Repository, workdir: [:0]const u8, update_gitlink: bool) !void {
log.debug("Repository.workdirSet called, workdir={s}, update_gitlink={}", .{ workdir, update_gitlink });
try internal.wrapCall("git_repository_set_workdir", .{
@ptrCast(*c.git_repository, self),
workdir.ptr,
@boolToInt(update_gitlink),
});
log.debug("successfully set workdir", .{});
}
pub fn commondir(self: *const Repository) ?[:0]const u8 {
log.debug("Repository.commondir called", .{});
if (c.git_repository_commondir(@ptrCast(*const c.git_repository, self))) |ret| {
const slice = std.mem.sliceTo(ret, 0);
log.debug("commondir: {s}", .{slice});
return slice;
}
log.debug("no commondir", .{});
return null;
}
/// Get the configuration file for this repository.
///
/// If a configuration file has not been set, the default config set for the repository will be returned, including any global
/// and system configurations.
pub fn configGet(self: *Repository) !*git.Config {
log.debug("Repository.configGet called", .{});
var config: *git.Config = undefined;
try internal.wrapCall("git_repository_config", .{
@ptrCast(*?*c.git_config, &config),
@ptrCast(*c.git_repository, self),
});
log.debug("repository config acquired successfully", .{});
return config;
}
/// Get a snapshot of the repository's configuration
///
/// The contents of this snapshot will not change, even if the underlying config files are modified.
pub fn configSnapshot(self: *Repository) !*git.Config {
log.debug("Repository.configSnapshot called", .{});
var config: *git.Config = undefined;
try internal.wrapCall("git_repository_config_snapshot", .{
@ptrCast(*?*c.git_config, &config),
@ptrCast(*c.git_repository, self),
});
log.debug("repository config acquired successfully", .{});
return config;
}
pub fn odbGet(self: *Repository) !*git.Odb {
log.debug("Repository.odbGet called", .{});
var odb: *git.Odb = undefined;
try internal.wrapCall("git_repository_odb", .{
@ptrCast(*?*c.git_odb, &odb),
@ptrCast(*c.git_repository, self),
});
log.debug("repository odb acquired successfully", .{});
return odb;
}
pub fn refDb(self: *Repository) !*git.RefDb {
log.debug("Repository.refDb called", .{});
var ref_db: *git.RefDb = undefined;
try internal.wrapCall("git_repository_refdb", .{
@ptrCast(*?*c.git_refdb, &ref_db),
@ptrCast(*c.git_repository, self),
});
log.debug("repository refdb acquired successfully", .{});
return ref_db;
}
pub fn indexGet(self: *Repository) !*git.Index {
log.debug("Repository.indexGet called", .{});
var index: *git.Index = undefined;
try internal.wrapCall("git_repository_index", .{
@ptrCast(*?*c.git_index, &index),
@ptrCast(*c.git_repository, self),
});
log.debug("repository index acquired successfully", .{});
return index;
}
/// Retrieve git's prepared message
///
/// Operations such as git revert/cherry-pick/merge with the -n option stop just short of creating a commit with the changes
/// and save their prepared message in .git/MERGE_MSG so the next git-commit execution can present it to the user for them to
/// amend if they wish.
///
/// Use this function to get the contents of this file. Don't forget to remove the file after you create the commit.
pub fn preparedMessage(self: *Repository) !git.Buf {
log.debug("Repository.preparedMessage called", .{});
var buf: git.Buf = .{};
try internal.wrapCall("git_repository_message", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_repository, self),
});
log.debug("prepared message: {s}", .{buf.toSlice()});
return buf;
}
/// Remove git's prepared message file.
pub fn preparedMessageRemove(self: *Repository) !void {
log.debug("Repository.preparedMessageRemove called", .{});
try internal.wrapCall("git_repository_message_remove", .{@ptrCast(*c.git_repository, self)});
log.debug("successfully removed prepared message", .{});
}
/// Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.
/// For example: MERGE_HEAD, MERGE_MSG, etc.
pub fn stateCleanup(self: *Repository) !void {
log.debug("Repository.stateCleanup called", .{});
try internal.wrapCall("git_repository_state_cleanup", .{@ptrCast(*c.git_repository, self)});
log.debug("successfully cleaned state", .{});
}
/// Invoke `callback_fn` for each entry in the given FETCH_HEAD file.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `ref_name` - The reference name
/// * `remote_url` - The remote URL
/// * `oid` - The reference OID
/// * `is_merge` - Was the reference the result of a merge
pub fn fetchHeadForeach(
self: *Repository,
comptime callback_fn: fn (
ref_name: [:0]const u8,
remote_url: [:0]const u8,
oid: *const git.Oid,
is_merge: bool,
) c_int,
) !c_int {
const cb = struct {
pub fn cb(
ref_name: [:0]const u8,
remote_url: [:0]const u8,
oid: *const git.Oid,
is_merge: bool,
_: *u8,
) c_int {
return callback_fn(ref_name, remote_url, oid, is_merge);
}
}.cb;
var dummy_data: u8 = undefined;
return self.fetchHeadForeachWithUserData(&dummy_data, cb);
}
/// Invoke `callback_fn` for each entry in the given FETCH_HEAD file.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `ref_name` - The reference name
/// * `remote_url` - The remote URL
/// * `oid` - The reference OID
/// * `is_merge` - Was the reference the result of a merge
/// * `user_data_ptr` - pointer to user data
pub fn fetchHeadForeachWithUserData(
self: *Repository,
user_data: anytype,
comptime callback_fn: fn (
ref_name: [:0]const u8,
remote_url: [:0]const u8,
oid: *const git.Oid,
is_merge: bool,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(
c_ref_name: [*c]const u8,
c_remote_url: [*c]const u8,
c_oid: [*c]const c.git_oid,
c_is_merge: c_uint,
payload: ?*anyopaque,
) callconv(.C) c_int {
return callback_fn(
std.mem.sliceTo(c_ref_name, 0),
std.mem.sliceTo(c_remote_url, 0),
@ptrCast(*const git.Oid, c_oid),
c_is_merge == 1,
@ptrCast(UserDataType, payload),
);
}
}.cb;
log.debug("Repository.fetchHeadForeachWithUserData called", .{});
const ret = try internal.wrapCallWithReturn("git_repository_fetchhead_foreach", .{
@ptrCast(*c.git_repository, self),
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// If a merge is in progress, invoke 'callback' for each commit ID in the MERGE_HEAD file.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `oid` - The merge OID
pub fn mergeHeadForeach(
self: *Repository,
comptime callback_fn: fn (oid: *const git.Oid) c_int,
) !c_int {
const cb = struct {
pub fn cb(oid: *const git.Oid, _: *u8) c_int {
return callback_fn(oid);
}
}.cb;
var dummy_data: u8 = undefined;
return self.mergeHeadForeachWithUserData(&dummy_data, cb);
}
/// If a merge is in progress, invoke 'callback' for each commit ID in the MERGE_HEAD file.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `oid` - The merge OID
/// * `user_data_ptr` - pointer to user data
pub fn mergeHeadForeachWithUserData(
self: *Repository,
user_data: anytype,
comptime callback_fn: fn (
oid: *const git.Oid,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(c_oid: [*c]const c.git_oid, payload: ?*anyopaque) callconv(.C) c_int {
return callback_fn(@ptrCast(*const git.Oid, c_oid), @ptrCast(UserDataType, payload));
}
}.cb;
log.debug("Repository.mergeHeadForeachWithUserData called", .{});
const ret = try internal.wrapCallWithReturn("git_repository_mergehead_foreach", .{
@ptrCast(*c.git_repository, self),
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Calculate hash of file using repository filtering rules.
///
/// If you simply want to calculate the hash of a file on disk with no filters, you can just use `git.Odb.hashFile`.
/// However, if you want to hash a file in the repository and you want to apply filtering rules (e.g. crlf filters) before
/// generating the SHA, then use this function.
///
/// Note: if the repository has `core.safecrlf` set to fail and the filtering triggers that failure, then this function will
/// return an error and not calculate the hash of the file.
///
/// ## Parameters
/// * `path` - Path to file on disk whose contents should be hashed. This can be a relative path.
/// * `object_type` - The object type to hash as (e.g. `ObjectType.BLOB`)
/// * `as_path` - The path to use to look up filtering rules. If this is `null`, then the `path` parameter will be used
/// instead. If this is passed as the empty string, then no filters will be applied when calculating the hash.
pub fn hashFile(
self: *Repository,
path: [:0]const u8,
object_type: git.ObjectType,
as_path: ?[:0]const u8,
) !git.Oid {
log.debug("Repository.hashFile called, path={s}, object_type={}, as_path={s}", .{ path, object_type, as_path });
var oid: git.Oid = undefined;
const as_path_temp: [*c]const u8 = if (as_path) |slice| slice.ptr else null;
try internal.wrapCall("git_repository_hashfile", .{
@ptrCast(*c.git_oid, &oid),
@ptrCast(*c.git_repository, self),
path.ptr,
@enumToInt(object_type),
as_path_temp,
});
// 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 oid.formatHex(&buf);
log.debug("file hash acquired successfully, hash={s}", .{slice});
}
return oid;
}
/// Get file status for a single file.
///
/// This tries to get status for the filename that you give. If no files match that name (in either the HEAD, index, or
/// working directory), this returns `GitError.NotFound`.
///
/// If the name matches multiple files (for example, if the `path` names a directory or if running on a case- insensitive
/// filesystem and yet the HEAD has two entries that both match the path), then this returns `GitError.Ambiguous`.
///
/// This does not do any sort of rename detection.
pub fn fileStatus(self: *Repository, path: [:0]const u8) !git.FileStatus {
log.debug("Repository.fileStatus called, path={s}", .{path});
var flags: c_uint = undefined;
try internal.wrapCall("git_status_file", .{ &flags, @ptrCast(*c.git_repository, self), path.ptr });
const ret = @bitCast(git.FileStatus, flags);
log.debug("file status: {}", .{ret});
return ret;
}
/// Gather file statuses and run a callback for each one.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `path` - The file path
/// * `status` - The status of the file
pub fn fileStatusForeach(
self: *Repository,
comptime callback_fn: fn (path: [:0]const u8, status: git.FileStatus) c_int,
) !c_int {
const cb = struct {
pub fn cb(path: [:0]const u8, status: git.FileStatus, _: *u8) c_int {
return callback_fn(path, status);
}
}.cb;
var dummy_data: u8 = undefined;
return self.foreachFileStatusWithUserData(&dummy_data, cb);
}
/// Gather file statuses and run a callback for each one.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `path` - The file path
/// * `status` - The status of the file
/// * `user_data_ptr` - pointer to user data
pub fn fileStatusForeachWithUserData(
self: *Repository,
user_data: anytype,
comptime callback_fn: fn (
path: [:0]const u8,
status: git.FileStatus,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const ptr_info = @typeInfo(UserDataType);
comptime std.debug.assert(ptr_info == .Pointer); // Must be a pointer
const alignment = ptr_info.Pointer.alignment;
const cb = struct {
pub fn cb(path: [*c]const u8, status: c_uint, payload: ?*anyopaque) callconv(.C) c_int {
return callback_fn(
std.mem.sliceTo(path, 0),
@bitCast(git.FileStatus, status),
@ptrCast(UserDataType, @alignCast(alignment, payload)),
);
}
}.cb;
log.debug("Repository.fileStatusForeachWithUserData called", .{});
const ret = try internal.wrapCallWithReturn("git_status_foreach", .{
@ptrCast(*c.git_repository, self),
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Gather file status information and run callbacks as requested.
///
/// This is an extended version of the `foreachFileStatus` function that allows for more granular control over which paths
/// will be processed. See `FileStatusOptions` for details about the additional options that this makes available.
///
/// Note that if a `pathspec` is given in the `FileStatusOptions` to filter the status, then the results from rename
/// detection (if you enable it) may not be accurate. To do rename detection properly, this must be called with no `pathspec`
/// so that all files can be considered.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `options` - callback options
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `path` - The file path
/// * `status` - The status of the file
pub fn fileStatusForeachExtended(
self: *Repository,
options: FileStatusOptions,
comptime callback_fn: fn (path: [:0]const u8, status: git.FileStatus) c_int,
) !c_int {
const cb = struct {
pub fn cb(path: [:0]const u8, status: git.FileStatus, _: *u8) c_int {
return callback_fn(path, status);
}
}.cb;
var dummy_data: u8 = undefined;
return self.foreachFileStatusExtendedWithUserData(options, &dummy_data, cb);
}
/// Gather file status information and run callbacks as requested.
///
/// This is an extended version of the `foreachFileStatus` function that allows for more granular control over which paths
/// will be processed. See `FileStatusOptions` for details about the additional options that this makes available.
///
/// Note that if a `pathspec` is given in the `FileStatusOptions` to filter the status, then the results from rename
/// detection (if you enable it) may not be accurate. To do rename detection properly, this must be called with no `pathspec`
/// so that all files can be considered.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `options` - callback options
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `path` - The file path
/// * `status` - The status of the file
/// * `user_data_ptr` - pointer to user data
pub fn fileStatusForeachExtendedWithUserData(
self: *Repository,
options: FileStatusOptions,
user_data: anytype,
comptime callback_fn: fn (
path: [:0]const u8,
status: git.FileStatus,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const ptr_info = @typeInfo(UserDataType);
comptime std.debug.assert(ptr_info == .Pointer); // Must be a pointer
const alignment = ptr_info.Pointer.alignment;
const cb = struct {
pub fn cb(path: [*c]const u8, status: c_uint, payload: ?*anyopaque) callconv(.C) c_int {
return callback_fn(
std.mem.sliceTo(path, 0),
@bitCast(git.FileStatus, status),
@ptrCast(UserDataType, @alignCast(alignment, payload)),
);
}
}.cb;
log.debug("Repository.fileStatusForeachExtendedWithUserData called, options={}", .{options});
const c_options = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_status_foreach_ext", .{
@ptrCast(*c.git_repository, self),
&c_options,
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Gather file status information and populate a `git.StatusList`.
///
/// Note that if a `pathspec` is given in the `FileStatusOptions` to filter the status, then the results from rename detection
/// (if you enable it) may not be accurate. To do rename detection properly, this must be called with no `pathspec` so that
/// all files can be considered.
///
/// ## Parameters
/// * `options` - options regarding which files to get the status of
pub fn statusList(self: *Repository, options: FileStatusOptions) !*git.StatusList {
log.debug("Repository.statusList called, options={}", .{options});
var status_list: *git.StatusList = undefined;
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_status_list_new", .{
@ptrCast(*?*c.git_status_list, &status_list),
@ptrCast(*c.git_repository, self),
&c_options,
});
log.debug("successfully fetched status list", .{});
return status_list;
}
pub const FileStatusOptions = struct {
/// which files to scan
show: Show = .INDEX_AND_WORKDIR,
/// Flags to control status callbacks
flags: Flags = .{},
/// The `pathspec` is an array of path patterns to match (using fnmatch-style matching), or just an array of paths to
/// match exactly if `Flags.DISABLE_PATHSPEC_MATCH` is specified in the flags.
pathspec: git.StrArray = .{},
/// The `baseline` is the tree to be used for comparison to the working directory and index; defaults to HEAD.
baseline: ?*git.Tree = null,
/// Select the files on which to report status.
pub const Show = enum(c_uint) {
/// The default. This roughly matches `git status --porcelain` regarding which files are included and in what order.
INDEX_AND_WORKDIR,
/// Only gives status based on HEAD to index comparison, not looking at working directory changes.
INDEX_ONLY,
/// Only gives status based on index to working directory comparison, not comparing the index to the HEAD.
WORKDIR_ONLY,
};
/// Flags to control status callbacks
///
/// Calling `Repository.forEachFileStatus` is like calling the extended version with: `INCLUDE_IGNORED`,
/// `INCLUDE_UNTRACKED`, and `RECURSE_UNTRACKED_DIRS`. Those options are provided as `Options.DEFAULTS`.
pub const Flags = packed struct {
/// Says that callbacks should be made on untracked files.
/// These will only be made if the workdir files are included in the status
/// "show" option.
INCLUDE_UNTRACKED: bool = true,
/// Says that ignored files get callbacks.
/// Again, these callbacks will only be made if the workdir files are
/// included in the status "show" option.
INCLUDE_IGNORED: bool = true,
/// Indicates that callback should be made even on unmodified files.
INCLUDE_UNMODIFIED: bool = false,
/// Indicates that submodules should be skipped.
/// This only applies if there are no pending typechanges to the submodule
/// (either from or to another type).
EXCLUDE_SUBMODULES: bool = false,
/// Indicates that all files in untracked directories should be included.
/// Normally if an entire directory is new, then just the top-level
/// directory is included (with a trailing slash on the entry name).
/// This flag says to include all of the individual files in the directory
/// instead.
RECURSE_UNTRACKED_DIRS: bool = true,
/// Indicates that the given path should be treated as a literal path,
/// and not as a pathspec pattern.
DISABLE_PATHSPEC_MATCH: bool = false,
/// Indicates that the contents of ignored directories should be included
/// in the status. This is like doing `git ls-files -o -i --exclude-standard`
/// with core git.
RECURSE_IGNORED_DIRS: bool = false,
/// Indicates that rename detection should be processed between the head and
/// the index and enables the GIT_STATUS_INDEX_RENAMED as a possible status
/// flag.
RENAMES_HEAD_TO_INDEX: bool = false,
/// Indicates that rename detection should be run between the index and the
/// working directory and enabled GIT_STATUS_WT_RENAMED as a possible status
/// flag.
RENAMES_INDEX_TO_WORKDIR: bool = false,
/// Overrides the native case sensitivity for the file system and forces
/// the output to be in case-sensitive order.
SORT_CASE_SENSITIVELY: bool = false,
/// Overrides the native case sensitivity for the file system and forces
/// the output to be in case-insensitive order.
SORT_CASE_INSENSITIVELY: bool = false,
/// Iindicates that rename detection should include rewritten files.
RENAMES_FROM_REWRITES: bool = false,
/// Bypasses the default status behavior of doing a "soft" index reload
/// (i.e. reloading the index data if the file on disk has been modified
/// outside libgit2).
NO_REFRESH: bool = false,
/// Tells libgit2 to refresh the stat cache in the index for files that are
/// unchanged but have out of date stat einformation in the index.
/// It will result in less work being done on subsequent calls to get status.
/// This is mutually exclusive with the NO_REFRESH option.
UPDATE_INDEX: bool = false,
/// Normally files that cannot be opened or read are ignored as
/// these are often transient files; this option will return
/// unreadable files as `GIT_STATUS_WT_UNREADABLE`.
INCLUDE_UNREADABLE: bool = false,
/// Unreadable files will be detected and given the status
/// untracked instead of unreadable.
INCLUDE_UNREADABLE_AS_UNTRACKED: bool = false,
z_padding: u16 = 0,
pub fn format(
value: Flags,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{"z_padding"},
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(Flags));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(Flags));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn makeCOptionObject(self: FileStatusOptions) c.git_status_options {
return .{
.version = c.GIT_STATUS_OPTIONS_VERSION,
.show = @enumToInt(self.show),
.flags = @bitCast(c_int, self.flags),
.pathspec = @bitCast(c.git_strarray, self.pathspec),
.baseline = @ptrCast(?*c.git_tree, self.baseline),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Test if the ignore rules apply to a given file.
///
/// ## Parameters
/// * `path` - The file to check ignores for, rooted at the repo's workdir.
pub fn statusShouldIgnore(self: *Repository, path: [:0]const u8) !bool {
log.debug("Repository.statusShouldIgnore called, path={s}", .{path});
var result: c_int = undefined;
try internal.wrapCall("git_status_should_ignore", .{ &result, @ptrCast(*c.git_repository, self), path.ptr });
const ret = result == 1;
log.debug("status should ignore: {}", .{ret});
return ret;
}
pub fn annotatedCommitCreateFromFetchHead(
self: *git.Repository,
branch_name: [:0]const u8,
remote_url: [:0]const u8,
id: git.Oid,
) !*git.AnnotatedCommit {
// 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 id.formatHex(&buf);
log.debug(
"Repository.annotatedCommitCreateFromFetchHead called, branch_name={s}, remote_url={s}, id={s}",
.{
branch_name,
remote_url,
slice,
},
);
}
var result: *git.AnnotatedCommit = undefined;
try internal.wrapCall("git_annotated_commit_from_fetchhead", .{
@ptrCast(*?*c.git_annotated_commit, &result),
@ptrCast(*c.git_repository, self),
branch_name.ptr,
remote_url.ptr,
@ptrCast(*const c.git_oid, &id),
});
log.debug("successfully created annotated commit", .{});
return result;
}
pub fn annotatedCommitCreateFromLookup(self: *Repository, id: git.Oid) !*git.AnnotatedCommit {
// 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 id.formatHex(&buf);
log.debug("Repository.annotatedCommitCreateFromLookup called, id={s}", .{slice});
}
var result: *git.AnnotatedCommit = undefined;
try internal.wrapCall("git_annotated_commit_lookup", .{
@ptrCast(*?*c.git_annotated_commit, &result),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, &id),
});
log.debug("successfully created annotated commit", .{});
return result;
}
pub fn annotatedCommitCreateFromRevisionString(self: *Repository, revspec: [:0]const u8) !*git.AnnotatedCommit {
log.debug("Repository.annotatedCommitCreateFromRevisionString called, revspec={s}", .{revspec});
var result: *git.AnnotatedCommit = undefined;
try internal.wrapCall("git_annotated_commit_from_revspec", .{
@ptrCast(*?*c.git_annotated_commit, &result),
@ptrCast(*c.git_repository, self),
revspec.ptr,
});
log.debug("successfully created annotated commit", .{});
return result;
}
/// Apply a `Diff` to the given repository, making changes directly in the working directory, the index, or both.
///
/// ## Parameters
/// * `diff` - the diff to apply
/// * `location` - the location to apply (workdir, index or both)
/// * `options` - the options for the apply (or null for defaults)
pub fn applyDiff(
self: *Repository,
diff: *git.Diff,
location: ApplyLocation,
options: ApplyOptions,
) !void {
log.debug("Repository.applyDiff called, diff={*}, location={}, options={}", .{ diff, location, options });
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_apply", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_diff, diff),
@enumToInt(location),
&c_options,
});
log.debug("apply completed", .{});
}
/// Apply a `Diff` to the given repository, making changes directly in the working directory, the index, or both.
///
/// ## Parameters
/// * `diff` - the diff to apply
/// * `location` - the location to apply (workdir, index or both)
/// * `user_data` - user data to be passed to callbacks
/// * `options` - the options for the apply (or null for defaults)
pub fn applyDiffWithUserData(
comptime T: type,
self: *Repository,
diff: *git.Diff,
location: ApplyLocation,
options: ApplyOptionsWithUserData(T),
) !void {
log.debug("Repository.applyDiffWithUserData(" ++ @typeName(T) ++ ") called, diff={*}, location={}, options={}", .{ diff, location, options });
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_apply", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_diff, self),
@bitCast(c_int, location),
&c_options,
});
log.debug("apply completed", .{});
}
/// Apply a `Diff` to a `Tree`, and return the resulting image as an index.
///
/// ## Parameters
/// * `diff` - the diff to apply`
/// * `preimage` - the tree to apply the diff to
/// * `options` - the options for the apply (or null for defaults)
pub fn applyDiffToTree(
self: *Repository,
diff: *git.Diff,
preimage: *git.Tree,
options: ApplyOptions,
) !*git.Index {
log.debug(
"Repository.applyDiffToTree called, diff={*}, preimage={*}, options={}",
.{ diff, preimage, options },
);
var ret: *git.Index = undefined;
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_apply_to_tree", .{
@ptrCast(*?*c.git_index, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_tree, preimage),
@ptrCast(*c.git_diff, diff),
&c_options,
});
log.debug("apply completed, index={*}", .{ret});
return ret;
}
/// Apply a `Diff` to a `Tree`, and return the resulting image as an index.
///
/// ## Parameters
/// * `diff` - the diff to apply`
/// * `preimage` - the tree to apply the diff to
/// * `options` - the options for the apply (or null for defaults)
pub fn applyDiffToTreeWithUserData(
comptime T: type,
self: *Repository,
diff: *git.Diff,
preimage: *git.Tree,
options: ApplyOptionsWithUserData(T),
) !*git.Index {
log.debug(
"Repository.applyDiffToTreeWithUserData(" ++ @typeName(T) ++ ") called, diff={*}, preimage={*}, options={}",
.{ diff, preimage, options },
);
var ret: *git.Index = undefined;
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_apply_to_tree", .{
@ptrCast(*?*c.git_index, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_tree, preimage),
@ptrCast(*c.git_diff, diff),
&c_options,
});
log.debug("apply completed, index={*}", .{ret});
return ret;
}
pub const ApplyOptions = struct {
/// callback that will be made per delta (file)
///
/// When the callback:
/// - returns < 0, the apply process will be aborted.
/// - returns > 0, the delta will not be applied, but the apply process continues
/// - returns 0, the delta is applied, and the apply process continues.
delta_cb: ?fn (delta: *const git.DiffDelta) callconv(.C) c_int = null,
/// callback that will be made per hunk
///
/// When the callback:
/// - returns < 0, the apply process will be aborted.
/// - returns > 0, the hunk will not be applied, but the apply process continues
/// - returns 0, the hunk is applied, and the apply process continues.
hunk_cb: ?fn (hunk: *const git.DiffHunk) callconv(.C) c_int = null,
flags: ApplyOptionsFlags = .{},
pub fn makeCOptionObject(self: ApplyOptions) c.git_apply_options {
return .{
.version = c.GIT_APPLY_OPTIONS_VERSION,
.delta_cb = @ptrCast(c.git_apply_delta_cb, self.delta_cb),
.hunk_cb = @ptrCast(c.git_apply_hunk_cb, self.hunk_cb),
.payload = null,
.flags = @bitCast(c_uint, self.flags),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn ApplyOptionsWithUserData(comptime T: type) type {
return struct {
/// callback that will be made per delta (file)
///
/// When the callback:
/// - returns < 0, the apply process will be aborted.
/// - returns > 0, the delta will not be applied, but the apply process continues
/// - returns 0, the delta is applied, and the apply process continues.
delta_cb: ?fn (delta: *const git.DiffDelta, user_data: T) callconv(.C) c_int = null,
/// callback that will be made per hunk
///
/// When the callback:
/// - returns < 0, the apply process will be aborted.
/// - returns > 0, the hunk will not be applied, but the apply process continues
/// - returns 0, the hunk is applied, and the apply process continues.
hunk_cb: ?fn (hunk: *const git.DiffHunk, user_data: T) callconv(.C) c_int = null,
payload: T,
flags: ApplyOptionsFlags = .{},
pub fn makeCOptionObject(self: @This()) c.git_apply_options {
return .{
.version = c.GIT_APPLY_OPTIONS_VERSION,
.delta_cb = @ptrCast(c.git_apply_delta_cb, self.delta_cb),
.hunk_cb = @ptrCast(c.git_apply_hunk_cb, self.hunk_cb),
.payload = self.payload,
.flags = @bitCast(c_uint, self.flags),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
}
pub const ApplyOptionsFlags = packed struct {
/// Don't actually make changes, just test that the patch applies. This is the equivalent of `git apply --check`.
CHECK: bool = false,
z_padding: u31 = 0,
pub fn format(
value: ApplyOptionsFlags,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{"z_padding"},
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(ApplyOptionsFlags));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(ApplyOptionsFlags));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const ApplyLocation = enum(c_uint) {
/// Apply the patch to the workdir, leaving the index untouched.
/// This is the equivalent of `git apply` with no location argument.
WORKDIR = 0,
/// Apply the patch to the index, leaving the working directory
/// untouched. This is the equivalent of `git apply --cached`.
INDEX = 1,
/// Apply the patch to both the working directory and the index.
/// This is the equivalent of `git apply --index`.
BOTH = 2,
};
/// Look up the value of one git attribute for path.
///
/// ## Parameters
/// * `flags` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `name` - The name of the attribute to look up.
pub fn attribute(self: *Repository, flags: AttributeFlags, path: [:0]const u8, name: [:0]const u8) !git.Attribute {
log.debug("Repository.attribute called, flags={}, path={s}, name={s}", .{ flags, path, name });
var result: [*c]const u8 = undefined;
try internal.wrapCall("git_attr_get", .{
&result,
@ptrCast(*c.git_repository, self),
flags.toCType(),
path.ptr,
name.ptr,
});
log.debug("fetched attribute", .{});
return git.Attribute{
.z_attr = result,
};
}
/// Look up a list of git attributes for path.
///
/// Use this if you have a known list of attributes that you want to look up in a single call. This is somewhat more efficient
/// than calling `attributeGet` multiple times.
///
/// ## Parameters
/// * `output_buffer` - output buffer, *must* be atleast as long as `names`
/// * `flags` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `names` - The names of the attributes to look up.
pub fn attributeMany(
self: *Repository,
output_buffer: [][*:0]const u8,
flags: AttributeFlags,
path: [:0]const u8,
names: [][*:0]const u8,
) ![]const [*:0]const u8 {
if (output_buffer.len < names.len) return error.BufferTooShort;
log.debug("Repository.attributeMany called, flags={}, path={s}", .{ flags, path });
try internal.wrapCall("git_attr_get_many", .{
@ptrCast([*c][*c]const u8, output_buffer.ptr),
@ptrCast(*c.git_repository, self),
flags.toCType(),
path.ptr,
names.len,
@ptrCast([*c][*c]const u8, names.ptr),
});
log.debug("fetched attributes", .{});
return output_buffer[0..names.len];
}
/// Invoke `callback_fn` for all the git attributes for a path.
///
///
/// ## Parameters
/// * `flags` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `name` - The attribute name
/// * `value` - The attribute value. May be `null` if the attribute is explicitly set to UNSPECIFIED using the '!' sign.
pub fn attributeForeach(
self: *const Repository,
flags: AttributeFlags,
path: [:0]const u8,
comptime callback_fn: fn (
name: [:0]const u8,
value: ?[:0]const u8,
) c_int,
) !c_int {
const cb = struct {
pub fn cb(
name: [*c]const u8,
value: [*c]const u8,
payload: ?*anyopaque,
) callconv(.C) c_int {
_ = payload;
return callback_fn(
std.mem.sliceTo(name, 0),
if (value) |ptr| std.mem.sliceTo(ptr, 0) else null,
);
}
}.cb;
log.debug("Repository.attributeForeach called, flags={}, path={s}", .{ flags, path });
const ret = try internal.wrapCallWithReturn("git_attr_foreach", .{
@ptrCast(*const c.git_repository, self),
flags.toCType(),
path.ptr,
cb,
null,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Invoke `callback_fn` for all the git attributes for a path.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `flags` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `name` - The attribute name
/// * `value` - The attribute value. May be `null` if the attribute is explicitly set to UNSPECIFIED using the '!' sign.
/// * `user_data_ptr` - pointer to user data
pub fn attributeForeachWithUserData(
self: *const Repository,
flags: AttributeFlags,
path: [:0]const u8,
user_data: anytype,
comptime callback_fn: fn (
name: [:0]const u8,
value: ?[:0]const u8,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(
name: [*c]const u8,
value: [*c]const u8,
payload: ?*anyopaque,
) callconv(.C) c_int {
return callback_fn(
std.mem.sliceTo(name, 0),
if (value) |ptr| std.mem.sliceTo(ptr, 0) else null,
@ptrCast(UserDataType, payload),
);
}
}.cb;
log.debug("Repository.attributeForeachWithUserData called, flags={}, path={s}", .{ flags, path });
const ret = try internal.wrapCallWithReturn("git_attr_foreach", .{
@ptrCast(*const c.git_repository, self),
flags.toCType(),
path.ptr,
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
pub const AttributeFlags = struct {
location: Location = .FILE_THEN_INDEX,
/// Controls extended attribute behavior
extended: Extended = .{},
pub const Location = enum(u32) {
FILE_THEN_INDEX = 0,
INDEX_THEN_FILE = 1,
INDEX_ONLY = 2,
};
pub const Extended = packed struct {
z_padding1: u2 = 0,
/// Normally, attribute checks include looking in the /etc (or system equivalent) directory for a `gitattributes`
/// file. Passing this flag will cause attribute checks to ignore that file. Setting the `NO_SYSTEM` flag will cause
/// attribute checks to ignore that file.
NO_SYSTEM: bool = false,
/// Passing the `INCLUDE_HEAD` flag will use attributes from a `.gitattributes` file in the repository
/// at the HEAD revision.
INCLUDE_HEAD: bool = false,
/// Passing the `INCLUDE_COMMIT` flag will use attributes from a `.gitattributes` file in a specific
/// commit.
INCLUDE_COMMIT: if (HAS_INCLUDE_COMMIT) bool else void = if (HAS_INCLUDE_COMMIT) false else {},
z_padding2: if (HAS_INCLUDE_COMMIT) u27 else u28 = 0,
const HAS_INCLUDE_COMMIT = @hasDecl(c, "GIT_ATTR_CHECK_INCLUDE_COMMIT");
pub fn format(
value: Extended,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding1", "z_padding2" },
);
}
test {
try std.testing.expectEqual(@sizeOf(u32), @sizeOf(Extended));
try std.testing.expectEqual(@bitSizeOf(u32), @bitSizeOf(Extended));
}
comptime {
std.testing.refAllDecls(@This());
}
};
fn toCType(self: AttributeFlags) u32 {
var result: u32 = 0;
switch (self.location) {
.FILE_THEN_INDEX => {},
.INDEX_THEN_FILE => result |= c.GIT_ATTR_CHECK_INDEX_THEN_FILE,
.INDEX_ONLY => result |= c.GIT_ATTR_CHECK_INDEX_ONLY,
}
if (self.extended.NO_SYSTEM) {
result |= c.GIT_ATTR_CHECK_NO_SYSTEM;
}
if (self.extended.INCLUDE_HEAD) {
result |= c.GIT_ATTR_CHECK_INCLUDE_HEAD;
}
if (self.extended.INCLUDE_COMMIT) {
result |= c.GIT_ATTR_CHECK_INCLUDE_COMMIT;
}
return result;
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn attributeCacheFlush(self: *Repository) !void {
log.debug("Repository.attributeCacheFlush called", .{});
try internal.wrapCall("git_attr_cache_flush", .{@ptrCast(*c.git_repository, self)});
log.debug("successfully flushed attribute cache", .{});
}
pub fn attributeAddMacro(self: *Repository, name: [:0]const u8, values: [:0]const u8) !void {
log.debug("Repository.attributeCacheFlush called, name={s}, values={s}", .{ name, values });
try internal.wrapCall("git_attr_add_macro", .{ @ptrCast(*c.git_repository, self), name.ptr, values.ptr });
log.debug("successfully added macro", .{});
}
pub fn blameFile(self: *Repository, path: [:0]const u8, options: BlameOptions) !*git.Blame {
log.debug("Repository.blameFile called, path={s}, options={}", .{ path, options });
var blame: *git.Blame = undefined;
var c_options = options.makeCOptionObject();
try internal.wrapCall("git_blame_file", .{
@ptrCast(*?*c.git_blame, &blame),
@ptrCast(*c.git_repository, self),
path.ptr,
&c_options,
});
log.debug("successfully fetched file blame", .{});
return blame;
}
pub const BlameOptions = struct {
flags: BlameFlags = .{},
/// The lower bound on the number of alphanumeric characters that must be detected as moving/copying within a file for it
/// to associate those lines with the parent commit. The default value is 20.
///
/// This value only takes effect if any of the `BlameFlags.TRACK_COPIES_*` flags are specified.
min_match_characters: u16 = 0,
/// The id of the newest commit to consider. The default is HEAD.
newest_commit: git.Oid = git.Oid.zero(),
/// The id of the oldest commit to consider. The default is the first commit encountered with a NULL parent.
oldest_commit: git.Oid = git.Oid.zero(),
/// The first line in the file to blame. The default is 1 (line numbers start with 1).
min_line: usize = 0,
/// The last line in the file to blame. The default is the last line of the file.
max_line: usize = 0,
pub const BlameFlags = packed struct {
NORMAL: bool = false,
/// Track lines that have moved within a file (like `git blame -M`).
///
/// This is not yet implemented and reserved for future use.
TRACK_COPIES_SAME_FILE: bool = false,
/// Track lines that have moved across files in the same commit (like `git blame -C`).
///
/// This is not yet implemented and reserved for future use.
TRACK_COPIES_SAME_COMMIT_MOVES: bool = false,
/// Track lines that have been copied from another file that exists in the same commit (like `git blame -CC`).
/// Implies SAME_FILE.
///
/// This is not yet implemented and reserved for future use.
TRACK_COPIES_SAME_COMMIT_COPIES: bool = false,
/// Track lines that have been copied from another file that exists in *any* commit (like `git blame -CCC`). Implies
/// SAME_COMMIT_COPIES.
///
/// This is not yet implemented and reserved for future use.
TRACK_COPIES_ANY_COMMIT_COPIES: bool = false,
/// Restrict the search of commits to those reachable following only the first parents.
FIRST_PARENT: bool = false,
/// Use mailmap file to map author and committer names and email addresses to canonical real names and email
/// addresses. The mailmap will be read from the working directory, or HEAD in a bare repository.
USE_MAILMAP: bool = false,
/// Ignore whitespace differences
IGNORE_WHITESPACE: bool = false,
z_padding1: u8 = 0,
z_padding2: u16 = 0,
pub fn format(
value: BlameFlags,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding1", "z_padding2" },
);
}
test {
try std.testing.expectEqual(@sizeOf(u32), @sizeOf(BlameFlags));
try std.testing.expectEqual(@bitSizeOf(u32), @bitSizeOf(BlameFlags));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn makeCOptionObject(self: BlameOptions) c.git_blame_options {
return .{
.version = c.GIT_BLAME_OPTIONS_VERSION,
.flags = @bitCast(u32, self.flags),
.min_match_characters = self.min_match_characters,
.newest_commit = @bitCast(c.git_oid, self.newest_commit),
.oldest_commit = @bitCast(c.git_oid, self.oldest_commit),
.min_line = self.min_line,
.max_line = self.max_line,
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn blobLookup(self: *Repository, id: *const git.Oid) !*git.Blob {
// 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 id.formatHex(&buf);
log.debug("Repository.blobLookup called, id={s}", .{slice});
}
var blob: *git.Blob = undefined;
try internal.wrapCall("git_blob_lookup", .{
@ptrCast(*?*c.git_blob, &blob),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
});
log.debug("successfully fetched blob {*}", .{blob});
return blob;
}
/// Lookup a blob object from a repository, given a prefix of its identifier (short id).
pub fn blobLookupPrefix(self: *Repository, id: *const git.Oid, len: usize) !*git.Blob {
// 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 id.formatHex(&buf);
log.debug("Repository.blobLookup called, id={s}, len={}", .{ slice, len });
}
var blob: *git.Blob = undefined;
try internal.wrapCall("git_blob_lookup_prefix", .{
@ptrCast(*?*c.git_blob, &blob),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
len,
});
log.debug("successfully fetched blob {*}", .{blob});
return blob;
}
/// Create a new branch pointing at a target commit
///
/// A new direct reference will be created pointing to this target commit. If `force` is true and a reference already exists
/// with the given name, it'll be replaced.
///
/// The returned reference must be freed by the user.
///
/// The branch name will be checked for validity.
///
/// ## Parameters
/// * `branch_name` - Name for the branch; this name is validated for consistency. It should also not conflict with an already
/// existing branch name.
/// * `target` - Commit to which this branch should point. This object must belong to the given `repo`.
/// * `force` - Overwrite existing branch.
pub fn branchCreate(self: *Repository, branch_name: [:0]const u8, target: *const git.Commit, force: bool) !*git.Reference {
log.debug("Repository.branchCreate called, branch_name={s}, target={*}, force={}", .{ branch_name, target, force });
var reference: *git.Reference = undefined;
try internal.wrapCall("git_branch_create", .{
@ptrCast(*?*c.git_reference, &reference),
@ptrCast(*c.git_repository, self),
branch_name.ptr,
@ptrCast(*const c.git_commit, target),
@boolToInt(force),
});
log.debug("successfully created branch", .{});
return reference;
}
/// Create a new branch pointing at a target commit
///
/// This behaves like `branchCreate` but takes an annotated commit, which lets you specify which extended sha syntax string
/// was specified by a user, allowing for more exact reflog messages.
///
/// ## Parameters
/// * `branch_name` - Name for the branch; this name is validated for consistency. It should also not conflict with an already
/// existing branch name.
/// * `target` - Commit to which this branch should point. This object must belong to the given `repo`.
/// * `force` - Overwrite existing branch.
pub fn branchCreateFromAnnotated(
self: *Repository,
branch_name: [:0]const u8,
target: *const git.AnnotatedCommit,
force: bool,
) !*git.Reference {
log.debug("Repository.branchCreateFromAnnotated called, branch_name={s}, target={*}, force={}", .{ branch_name, target, force });
var reference: *git.Reference = undefined;
try internal.wrapCall("git_branch_create_from_annotated", .{
@ptrCast(*?*c.git_reference, &reference),
@ptrCast(*c.git_repository, self),
branch_name.ptr,
@ptrCast(*const c.git_annotated_commit, target),
@boolToInt(force),
});
log.debug("successfully created branch", .{});
return reference;
}
pub fn iterateBranches(self: *Repository, branch_type: BranchType) !*BranchIterator {
log.debug("Repository.iterateBranches called", .{});
var iterator: *BranchIterator = undefined;
try internal.wrapCall("git_branch_iterator_new", .{
@ptrCast(*?*c.git_branch_iterator, &iterator),
@ptrCast(*c.git_repository, self),
@enumToInt(branch_type),
});
log.debug("branch iterator created successfully", .{});
return iterator;
}
pub const BranchType = enum(c_uint) {
LOCAL = 1,
REMOTE = 2,
ALL = 3,
};
pub const BranchIterator = opaque {
pub fn next(self: *BranchIterator) !?Item {
log.debug("BranchIterator.next called", .{});
var reference: *git.Reference = undefined;
var branch_type: c.git_branch_t = undefined;
internal.wrapCall("git_branch_next", .{
@ptrCast(*?*c.git_reference, &reference),
&branch_type,
@ptrCast(*c.git_branch_iterator, self),
}) catch |err| switch (err) {
git.GitError.IterOver => {
log.debug("end of iteration reached", .{});
return null;
},
else => return err,
};
const ret = Item{
.reference = reference,
.branch_type = @intToEnum(BranchType, branch_type),
};
log.debug("successfully fetched branch: {}", .{ret});
return ret;
}
pub const Item = struct {
reference: *git.Reference,
branch_type: BranchType,
};
pub fn deinit(self: *BranchIterator) void {
log.debug("BranchIterator.deinit called", .{});
c.git_branch_iterator_free(@ptrCast(*c.git_branch_iterator, self));
log.debug("branch iterator freed successfully", .{});
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Lookup a branch by its name in a repository.
///
/// The generated reference must be freed by the user.
/// The branch name will be checked for validity.
pub fn branchLookup(self: *Repository, branch_name: [:0]const u8, branch_type: BranchType) !*git.Reference {
log.debug("Repository.branchLookup called, branch_name={s}, branch_type={}", .{ branch_name, branch_type });
var ref: *git.Reference = undefined;
try internal.wrapCall("git_branch_lookup", .{
@ptrCast(*?*c.git_reference, &ref),
@ptrCast(*c.git_repository, self),
branch_name.ptr,
@enumToInt(branch_type),
});
log.debug("successfully fetched branch: {*}", .{ref});
return ref;
}
/// Find the remote name of a remote-tracking branch
///
/// This will return the name of the remote whose fetch refspec is matching the given branch. E.g. given a branch
/// "refs/remotes/test/master", it will extract the "test" part. If refspecs from multiple remotes match, the function will
/// return `GitError.AMBIGUOUS`.
pub fn remoteGetName(self: *Repository, refname: [:0]const u8) !git.Buf {
log.debug("Repository.remoteGetName called, refname={s}", .{refname});
var buf: git.Buf = .{};
try internal.wrapCall("git_branch_remote_name", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_repository, self),
refname.ptr,
});
log.debug("remote name acquired successfully, name={s}", .{buf.toSlice()});
return buf;
}
/// Retrieve the upstream remote of a local branch
///
/// This will return the currently configured "branch.*.remote" for a given branch. This branch must be local.
pub fn remoteUpstreamRemote(self: *Repository, refname: [:0]const u8) !git.Buf {
log.debug("Repository.remoteUpstreamRemote called, refname={s}", .{refname});
var buf: git.Buf = .{};
try internal.wrapCall("git_branch_upstream_remote", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_repository, self),
refname.ptr,
});
log.debug("upstream remote name acquired successfully, name={s}", .{buf.toSlice()});
return buf;
}
/// Get the upstream name of a branch
///
/// Given a local branch, this will return its remote-tracking branch information, as a full reference name, ie.
/// "feature/nice" would become "refs/remote/origin/feature/nice", depending on that branch's configuration.
pub fn upstreamGetName(self: *Repository, refname: [:0]const u8) !git.Buf {
log.debug("Repository.upstreamGetName called, refname={s}", .{refname});
var buf: git.Buf = .{};
try internal.wrapCall("git_branch_upstream_name", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_repository, self),
refname.ptr,
});
log.debug("upstream name acquired successfully, name={s}", .{buf.toSlice()});
return buf;
}
/// Updates files in the index and the working tree to match the content of the commit pointed at by HEAD.
///
/// Note that this is _not_ the correct mechanism used to switch branches; do not change your `HEAD` and then call this
/// method, that would leave you with checkout conflicts since your working directory would then appear to be dirty.
/// Instead, checkout the target of the branch and then update `HEAD` using `git_repository_set_head` to point to the branch
/// you checked out.
///
/// Returns a non-zero value is the `notify_cb` callback returns non-zero.
pub fn checkoutHead(self: *Repository, options: CheckoutOptions) !c_uint {
log.debug("Repository.checkoutHead called, options={}", .{options});
const c_options = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_checkout_head", .{
@ptrCast(*c.git_repository, self),
&c_options,
});
log.debug("successfully checked out HEAD", .{});
return @intCast(c_uint, ret);
}
/// Updates files in the working tree to match the content of the index.
///
/// Returns a non-zero value is the `notify_cb` callback returns non-zero.
pub fn checkoutIndex(self: *Repository, index: *git.Index, options: CheckoutOptions) !c_uint {
log.debug("Repository.checkoutHead called, options={}", .{options});
const c_options = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_checkout_index", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_index, index),
&c_options,
});
log.debug("successfully checked out index", .{});
return @intCast(c_uint, ret);
}
/// Updates files in the working tree to match the content of the index.
///
/// Returns a non-zero value is the `notify_cb` callback returns non-zero.
pub fn checkoutTree(self: *Repository, treeish: *const git.Object, options: CheckoutOptions) !c_uint {
log.debug("Repository.checkoutHead called, options={}", .{options});
const c_option = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_checkout_tree", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_object, treeish),
&c_option,
});
log.debug("successfully checked out tree", .{});
return @intCast(c_uint, ret);
}
pub const CheckoutOptions = struct {
/// default will be a safe checkout
checkout_strategy: Strategy = .{
.SAFE = true,
},
/// don't apply filters like CRLF conversion
disable_filters: bool = false,
/// default is 0o755
dir_mode: c_uint = 0,
/// default is 0o644 or 0o755 as dictated by blob
file_mode: c_uint = 0,
/// default is O_CREAT | O_TRUNC | O_WRONLY
file_open_flags: c_int = 0,
/// Optional callback to get notifications on specific file states.
notify_flags: Notification = .{},
/// Optional callback to get notifications on specific file states.
notify_cb: ?fn (
why: Notification,
path: [*:0]const u8,
baseline: *git.DiffFile,
target: *git.DiffFile,
workdir: *git.DiffFile,
payload: ?*anyopaque,
) callconv(.C) c_int = null,
/// Payload passed to notify_cb
notify_payload: ?*anyopaque = null,
/// Optional callback to notify the consumer of checkout progress
progress_cb: ?fn (
path: [*:0]const u8,
completed_steps: usize,
total_steps: usize,
payload: ?*anyopaque,
) callconv(.C) void = null,
/// Payload passed to progress_cb
progress_payload: ?*anyopaque = null,
/// A list of wildmatch patterns or paths.
///
/// By default, all paths are processed. If you pass an array of wildmatch patterns, those will be used to filter which
/// paths should be taken into account.
///
/// Use GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH to treat as a simple list.
paths: git.StrArray = .{},
/// The expected content of the working directory; defaults to HEAD.
///
/// If the working directory does not match this baseline information, that will produce a checkout conflict.
baseline: ?*git.Tree = null,
/// Like `baseline` above, though expressed as an index. This option overrides `baseline`.
baseline_index: ?*git.Index = null,
/// alternative checkout path to workdir
target_directory: ?[:0]const u8 = null,
/// the name of the common ancestor side of conflicts
ancestor_label: ?[:0]const u8 = null,
/// the name of the "our" side of conflicts
our_label: ?[:0]const u8 = null,
/// the name of the "their" side of conflicts
their_label: ?[:0]const u8 = null,
/// Optional callback to notify the consumer of performance data.
perfdata_cb: ?fn (perfdata: *const PerfData, payload: *anyopaque) callconv(.C) void = null,
/// Payload passed to perfdata_cb
perfdata_payload: ?*anyopaque = null,
pub const PerfData = extern struct {
mkdir_calls: usize,
stat_calls: usize,
chmod_calls: usize,
test {
try std.testing.expectEqual(@sizeOf(c.git_checkout_perfdata), @sizeOf(PerfData));
try std.testing.expectEqual(@bitSizeOf(c.git_checkout_perfdata), @bitSizeOf(PerfData));
}
};
pub const Strategy = packed struct {
/// Allow safe updates that cannot overwrite uncommitted data.
/// If the uncommitted changes don't conflict with the checked out files,
/// the checkout will still proceed, leaving the changes intact.
///
/// Mutually exclusive with FORCE.
/// FORCE takes precedence over SAFE.
SAFE: bool = false,
/// Allow all updates to force working directory to look like index.
///
/// Mutually exclusive with SAFE.
/// FORCE takes precedence over SAFE.
FORCE: bool = false,
/// Allow checkout to recreate missing files
RECREATE_MISSING: bool = false,
z_padding: bool = false,
/// Allow checkout to make safe updates even if conflicts are found
ALLOW_CONFLICTS: bool = false,
/// Remove untracked files not in index (that are not ignored)
REMOVE_UNTRACKED: bool = false,
/// Remove ignored files not in index
REMOVE_IGNORED: bool = false,
/// Only update existing files, don't create new ones
UPDATE_ONLY: bool = false,
/// Normally checkout updates index entries as it goes; this stops that.
/// Implies `DONT_WRITE_INDEX`.
DONT_UPDATE_INDEX: bool = false,
/// Don't refresh index/config/etc before doing checkout
NO_REFRESH: bool = false,
/// Allow checkout to skip unmerged files
SKIP_UNMERGED: bool = false,
/// For unmerged files, checkout stage 2 from index
USE_OURS: bool = false,
/// For unmerged files, checkout stage 3 from index
USE_THEIRS: bool = false,
/// Treat pathspec as simple list of exact match file paths
DISABLE_PATHSPEC_MATCH: bool = false,
z_padding2: u2 = 0,
/// Recursively checkout submodules with same options (NOT IMPLEMENTED)
UPDATE_SUBMODULES: bool = false,
/// Recursively checkout submodules if HEAD moved in super repo (NOT IMPLEMENTED)
UPDATE_SUBMODULES_IF_CHANGED: bool = false,
/// Ignore directories in use, they will be left empty
SKIP_LOCKED_DIRECTORIES: bool = false,
/// Don't overwrite ignored files that exist in the checkout target
DONT_OVERWRITE_IGNORED: bool = false,
/// Write normal merge files for conflicts
CONFLICT_STYLE_MERGE: bool = false,
/// Include common ancestor data in diff3 format files for conflicts
CONFLICT_STYLE_DIFF3: bool = false,
/// Don't overwrite existing files or folders
DONT_REMOVE_EXISTING: bool = false,
/// Normally checkout writes the index upon completion; this prevents that.
DONT_WRITE_INDEX: bool = false,
z_padding3: u8 = 0,
pub fn format(
value: Strategy,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding", "z_padding2", "z_padding3" },
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(Strategy));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(Strategy));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const Notification = packed struct {
/// Invokes checkout on conflicting paths.
CONFLICT: bool = false,
/// Notifies about "dirty" files, i.e. those that do not need an update
/// but no longer match the baseline. Core git displays these files when
/// checkout runs, but won't stop the checkout.
DIRTY: bool = false,
/// Sends notification for any file changed.
UPDATED: bool = false,
/// Notifies about untracked files.
UNTRACKED: bool = false,
/// Notifies about ignored files.
IGNORED: bool = false,
z_padding: u11 = 0,
z_padding2: u16 = 0,
pub const ALL = @bitCast(Notification, @as(c_uint, 0xFFFF));
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(Notification));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(Notification));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn makeCOptionObject(self: CheckoutOptions) c.git_checkout_options {
return .{
.version = c.GIT_CHECKOUT_OPTIONS_VERSION,
.checkout_strategy = @bitCast(c_uint, self.checkout_strategy),
.disable_filters = @boolToInt(self.disable_filters),
.dir_mode = self.dir_mode,
.file_mode = self.file_mode,
.file_open_flags = self.file_open_flags,
.notify_flags = @bitCast(c_uint, self.notify_flags),
.notify_cb = @ptrCast(c.git_checkout_notify_cb, self.notify_cb),
.notify_payload = self.notify_payload,
.progress_cb = @ptrCast(c.git_checkout_progress_cb, self.progress_cb),
.progress_payload = self.progress_payload,
.paths = @bitCast(c.git_strarray, self.paths),
.baseline = @ptrCast(?*c.git_tree, self.baseline),
.baseline_index = @ptrCast(?*c.git_index, self.baseline_index),
.target_directory = if (self.target_directory) |ptr| ptr.ptr else null,
.ancestor_label = if (self.ancestor_label) |ptr| ptr.ptr else null,
.our_label = if (self.our_label) |ptr| ptr.ptr else null,
.their_label = if (self.their_label) |ptr| ptr.ptr else null,
.perfdata_cb = @ptrCast(c.git_checkout_perfdata_cb, self.perfdata_cb),
.perfdata_payload = self.perfdata_payload,
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub fn cherrypickCommit(
self: *Repository,
cherrypick_commit: *git.Commit,
our_commit: *git.Commit,
mainline: bool,
options: git.MergeOptions,
) !*git.Index {
log.debug(
"Repository.cherrypickCommit called, cherrypick_commit={*}, our_commit={*}, mainline={}, options={}",
.{ cherrypick_commit, our_commit, mainline, options },
);
var index: *git.Index = undefined;
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_cherrypick_commit", .{
@ptrCast(*?*c.git_index, &index),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_commit, cherrypick_commit),
@ptrCast(*c.git_commit, our_commit),
@boolToInt(mainline),
&c_options,
});
log.debug("successfully cherrypicked, index={*}", .{index});
return index;
}
pub fn cherrypick(
self: *Repository,
commit: *git.Commit,
options: CherrypickOptions,
) !void {
log.debug(
"Repository.cherrypick called, commit={*}, options={}",
.{ commit, options },
);
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_cherrypick", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_commit, commit),
&c_options,
});
log.debug("successfully cherrypicked", .{});
}
pub const CherrypickOptions = struct {
mainline: bool = false,
merge_options: git.MergeOptions = .{},
checkout_options: CheckoutOptions = .{},
pub fn makeCOptionObject(self: CherrypickOptions) c.git_cherrypick_options {
return .{
.version = c.GIT_CHERRYPICK_OPTIONS_VERSION,
.mainline = @boolToInt(self.mainline),
.merge_opts = self.merge_options.makeCOptionObject(),
.checkout_opts = self.checkout_options.makeCOptionObject(),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Lookup a commit object from a repository.
pub fn commitLookup(self: *Repository, oid: *const git.Oid) !*git.Commit {
// 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 oid.formatHex(&buf);
log.debug("Repository.commitLookup called, oid={s}", .{slice});
}
var commit: *git.Commit = undefined;
try internal.wrapCall("git_commit_lookup", .{
@ptrCast(*?*c.git_commit, &commit),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, oid),
});
log.debug("successfully looked up commit, commit={*}", .{commit});
return commit;
}
/// Lookup a commit object from a repository, given a prefix of its identifier (short id).
pub fn commitLookupPrefix(self: *Repository, oid: *const git.Oid, size: usize) !*git.Commit {
// 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 oid.formatHex(&buf);
log.debug("Repository.commitLookupPrefix called, oid={s}, size={}", .{ slice, size });
}
var commit: *git.Commit = undefined;
try internal.wrapCall("git_commit_lookup_prefix", .{
@ptrCast(*?*c.git_commit, &commit),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, oid),
size,
});
log.debug("successfully looked up commit, commit={*}", .{commit});
return commit;
}
pub fn commitExtractSignature(self: *Repository, commit: *git.Oid, field: ?[:0]const u8) !ExtractSignatureResult {
// 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 commit.formatHex(&buf);
log.debug("Repository.commitExtractSignature called, commit={s}, field={s}", .{ slice, field });
}
var result: ExtractSignatureResult = .{};
const field_temp: [*c]const u8 = if (field) |slice| slice.ptr else null;
try internal.wrapCall("git_commit_extract_signature", .{
@ptrCast(*c.git_buf, &result.signature),
@ptrCast(*c.git_buf, &result.signed_data),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_oid, commit),
field_temp,
});
return result;
}
pub const ExtractSignatureResult = struct {
signature: git.Buf = .{},
signed_data: git.Buf = .{},
};
pub fn commitCreate(
self: *Repository,
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,
parents: []*const git.Commit,
) !git.Oid {
log.debug("Repository.commitCreate 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: [*c]const u8 = if (update_ref) |slice| slice.ptr else null;
const encoding_temp: [*c]const u8 = if (message_encoding) |slice| slice.ptr else null;
try internal.wrapCall("git_commit_create", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
update_ref_temp,
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, committer),
encoding_temp,
message.ptr,
@ptrCast(*const c.git_tree, tree),
parents.len,
@ptrCast([*c]?*const c.git_commit, parents.ptr),
});
// 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 created commit: {s}", .{slice});
}
return ret;
}
pub fn commitCreateBuffer(
self: *Repository,
author: *const git.Signature,
committer: *const git.Signature,
message_encoding: ?[:0]const u8,
message: [:0]const u8,
tree: *const git.Tree,
parents: []*const git.Commit,
) !git.Buf {
log.debug("Repository.commitCreateBuffer called, author={*}, committer={*}, message_encoding={s}, message={s}, tree={*}", .{
author,
committer,
message_encoding,
message,
tree,
});
var ret: git.Buf = .{};
const encoding_temp: [*c]const u8 = if (message_encoding) |slice| slice.ptr else null;
try internal.wrapCall("git_commit_create_buffer", .{
@ptrCast(*c.git_buf, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, committer),
encoding_temp,
message.ptr,
@ptrCast(*const c.git_tree, tree),
parents.len,
@ptrCast([*c]?*const c.git_commit, parents.ptr),
});
log.debug("successfully created commit: {s}", .{ret.toSlice()});
return ret;
}
pub fn commitCreateWithSignature(
self: *Repository,
commit_content: [:0]const u8,
signature: ?[:0]const u8,
signature_field: ?[:0]const u8,
) !git.Oid {
log.debug("Repository.commitCreateWithSignature called, commit_content={s}, signature={s}, signature_field={s}", .{
commit_content,
signature,
signature_field,
});
var ret: git.Oid = undefined;
const signature_temp: [*c]const u8 = if (signature) |slice| slice.ptr else null;
const signature_field_temp: [*c]const u8 = if (signature_field) |slice| slice.ptr else null;
try internal.wrapCall("git_commit_create_with_signature", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
commit_content.ptr,
signature_temp,
signature_field_temp,
});
// 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 created commit: {s}", .{slice});
}
return ret;
}
/// Create a new mailmap instance from a repository, loading mailmap files based on the repository's configuration.
///
/// Mailmaps are loaded in the following order:
/// 1. '.mailmap' in the root of the repository's working directory, if present.
/// 2. The blob object identified by the 'mailmap.blob' config entry, if set.
/// [NOTE: 'mailmap.blob' defaults to 'HEAD:.mailmap' in bare repositories]
/// 3. The path in the 'mailmap.file' config entry, if set.
pub fn mailmapFromRepo(self: *Repository) !*git.Mailmap {
log.debug("Repository.mailmapFromRepo called", .{});
var mailmap: *git.Mailmap = undefined;
try internal.wrapCall("git_mailmap_from_repository", .{
@ptrCast(*?*c.git_mailmap, &mailmap),
@ptrCast(*c.git_repository, self),
});
log.debug("successfully loaded mailmap from repo: {*}", .{mailmap});
return mailmap;
}
/// Load the filter list for a given path.
///
/// This will return null if no filters are requested for the given file.
///
/// ## Parameters
/// * `blob` - The blob to which the filter will be applied (if known)
/// * `path` - Relative path of the file to be filtered
/// * `mode` - Filtering direction (WT->ODB or ODB->WT)
/// * `flags` - Filter flags
pub fn filterListLoad(
self: *Repository,
blob: ?*git.Blob,
path: [:0]const u8,
mode: git.FilterMode,
flags: git.FilterFlags,
) !?*git.FilterList {
log.debug(
"Repository.filterListLoad called, blob={*}, path={s}, mode={}, flags={}",
.{ blob, path, mode, flags },
);
var opt: ?*git.FilterList = undefined;
try internal.wrapCall("git_filter_list_load", .{
@ptrCast(*?*c.git_filter_list, &opt),
@ptrCast(*c.git_repository, self),
@ptrCast(?*c.git_blob, blob),
path.ptr,
@enumToInt(mode),
@bitCast(c_uint, flags),
});
if (opt) |ret| {
log.debug("successfully acquired filters for the given path: {*}", .{ret});
return ret;
}
log.debug("no filters for the given path", .{});
return null;
}
/// Count the number of unique commits between two commit objects
///
/// There is no need for branches containing the commits to have any upstream relationship, but it helps to think of one as a
// branch and the other as its upstream, the `ahead` and `behind` values will be what git would report for the branches.
///
/// ## Parameters
/// * `local` - the commit for local
/// * `upstream` - the commit for upstream
pub fn graphAheadBehind(
self: *Repository,
local: *const git.Oid,
upstream: *const git.Oid,
) !GraphAheadBehindResult {
// 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 buf1: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined;
var buf2: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined;
const slice1 = try local.formatHex(&buf1);
const slice2 = try upstream.formatHex(&buf2);
log.debug("Repository.graphAheadBehind called, local={s}, upstream={s}", .{ slice1, slice2 });
}
var ret: GraphAheadBehindResult = undefined;
try internal.wrapCall("git_graph_ahead_behind", .{
&ret.ahead,
&ret.behind,
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, local),
@ptrCast(*const c.git_oid, upstream),
});
log.debug("successfully got unique commits: {}", .{ret});
return ret;
}
pub const GraphAheadBehindResult = struct { ahead: usize, behind: usize };
/// Determine if a commit is the descendant of another commit.
///
/// Note that a commit is not considered a descendant of itself, in contrast to `git merge-base --is-ancestor`.
///
/// ## Parameters
/// * `commit` - a previously loaded commit
/// * `ancestor` - a potential ancestor commit
pub fn graphDecendantOf(self: *Repository, commit: *const git.Oid, ancestor: *const git.Oid) !bool {
// 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 buf1: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined;
var buf2: [git.Oid.HEX_BUFFER_SIZE]u8 = undefined;
const slice1 = try commit.formatHex(&buf1);
const slice2 = try ancestor.formatHex(&buf2);
log.debug("Repository.graphDecendantOf called, commit={s}, ancestor={s}", .{ slice1, slice2 });
}
const ret = (try internal.wrapCallWithReturn("git_graph_descendant_of", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, commit),
@ptrCast(*const c.git_oid, ancestor),
})) != 0;
log.debug("commit is an ancestor: {}", .{ret});
return ret;
}
/// Add ignore rules for a repository.
///
/// Excludesfile rules (i.e. .gitignore rules) are generally read from .gitignore files in the repository tree or from a
/// shared system file only if a "core.excludesfile" config value is set. The library also keeps a set of per-repository
/// internal ignores that can be configured in-memory and will not persist. This function allows you to add to that internal
/// rules list.
///
/// Example usage:
/// ```zig
/// try repo.ignoreAddRule("*.c\ndir/\nFile with space\n");
/// ```
///
/// This would add three rules to the ignores.
///
/// ## Parameters
/// * `rules` - Text of rules, a la the contents of a .gitignore file. It is okay to have multiple rules in the text; if so,
/// each rule should be terminated with a newline.
pub fn ignoreAddRule(self: *Repository, rules: [:0]const u8) !void {
log.debug("Repository.ignoreAddRule called, rules={s}", .{rules});
try internal.wrapCall("git_ignore_add_rule", .{ @ptrCast(*c.git_repository, self), rules.ptr });
log.debug("successfully added ignore rules", .{});
}
/// Clear ignore rules that were explicitly added.
///
/// Resets to the default internal ignore rules. This will not turn off
/// rules in .gitignore files that actually exist in the filesystem.
///
/// The default internal ignores ignore ".", ".." and ".git" entries.
pub fn ignoreClearRules(self: *Repository) !void {
log.debug("Repository.git_ignore_clear_internal_rules called", .{});
try internal.wrapCall("git_ignore_clear_internal_rules", .{@ptrCast(*c.git_repository, self)});
log.debug("successfully cleared ignore rules", .{});
}
/// Test if the ignore rules apply to a given path.
///
/// This function checks the ignore rules to see if they would apply to the given file. This indicates if the file would be
/// ignored regardless of whether the file is already in the index or committed to the repository.
///
/// One way to think of this is if you were to do "git check-ignore --no-index" on the given file, would it be shown or not?
///
/// ## Parameters
/// * `path` - the file to check ignores for, relative to the repo's workdir.
pub fn ignorePathIsIgnored(self: *Repository, path: [:0]const u8) !bool {
log.debug("Repository.ignorePathIsIgnored called, path={s}", .{path});
var ignored: c_int = undefined;
try internal.wrapCall("git_ignore_path_is_ignored", .{
&ignored,
@ptrCast(*c.git_repository, self),
path.ptr,
});
const ret = ignored != 0;
log.debug("ignore path is ignored: {}", .{ret});
return ret;
}
/// Load the filter list for a given path.
///
/// This will return null if no filters are requested for the given file.
///
/// ## Parameters
/// * `blob` - The blob to which the filter will be applied (if known)
/// * `path` - Relative path of the file to be filtered
/// * `mode` - Filtering direction (WT->ODB or ODB->WT)
/// * `options` - Filter options
pub fn filterListLoadExtended(
self: *Repository,
blob: ?*git.Blob,
path: [:0]const u8,
mode: git.FilterMode,
options: git.FilterOptions,
) !?*git.FilterList {
log.debug(
"Repository.filterListLoad called, blob={*}, path={s}, mode={}, options={}",
.{ blob, path, mode, options },
);
var opt: ?*git.FilterList = undefined;
var c_options = options.makeCOptionObject();
try internal.wrapCall("git_filter_list_load_ext", .{
@ptrCast(*?*c.git_filter_list, &opt),
@ptrCast(*c.git_repository, self),
@ptrCast(?*c.git_blob, blob),
path.ptr,
@enumToInt(mode),
&c_options,
});
if (opt) |ret| {
log.debug("successfully acquired filters for the given path: {*}", .{ret});
return ret;
}
log.debug("no filters for the given path", .{});
return null;
}
/// Determine if a commit is reachable from any of a list of commits by following parent edges.
///
/// ## Parameters
/// * `commit` - a previously loaded commit
/// * `decendants` - oids of the commits
pub fn graphReachableFromAny(
self: *Repository,
commit: *const git.Oid,
decendants: []const git.Oid,
) !bool {
// 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 commit.formatHex(&buf);
log.debug("Repository.graphReachableFromAny called, commit={s}, number of decendants={}", .{ slice, decendants.len });
}
const ret = (try internal.wrapCallWithReturn("git_graph_reachable_from_any", .{
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, commit),
@ptrCast([*]const c.git_oid, decendants.ptr),
decendants.len,
})) != 0;
log.debug("commit is an ancestor: {}", .{ret});
return ret;
}
/// Retrieve the upstream merge of a local branch
///
/// This will return the currently configured "branch.*.remote" for a given branch. This branch must be local.
pub fn remoteUpstreamMerge(self: *Repository, refname: [:0]const u8) !git.Buf {
log.debug("Repository.remoteUpstreamMerge called, refname={s}", .{refname});
var buf: git.Buf = .{};
try internal.wrapCall("git_branch_upstream_merge", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*c.git_repository, self),
refname.ptr,
});
log.debug("upstream remote name acquired successfully, name={s}", .{buf.toSlice()});
return buf;
}
/// Look up the value of one git attribute for path with extended options.
///
/// ## Parameters
/// * `options` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `name` - The name of the attribute to look up.
pub fn attributeExtended(
self: *Repository,
options: AttributeOptions,
path: [:0]const u8,
name: [:0]const u8,
) !git.Attribute {
log.debug("Repository.attributeExtended called, options={}, path={s}, name={s}", .{ options, path, name });
var c_options = options.makeCOptionObject();
var result: [*c]const u8 = undefined;
try internal.wrapCall("git_attr_get_ext", .{
&result,
@ptrCast(*c.git_repository, self),
&c_options,
path.ptr,
name.ptr,
});
log.debug("fetched attribute", .{});
return git.Attribute{
.z_attr = result,
};
}
/// Look up a list of git attributes for path with extended options.
///
/// Use this if you have a known list of attributes that you want to look up in a single call. This is somewhat more efficient
/// than calling `attributeGet` multiple times.
///
/// ## Parameters
/// * `output_buffer` - output buffer, *must* be atleast as long as `names`
/// * `options` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `names` - The names of the attributes to look up.
pub fn attributeManyExtended(
self: *Repository,
output_buffer: [][*:0]const u8,
options: AttributeOptions,
path: [:0]const u8,
names: [][*:0]const u8,
) ![]const [*:0]const u8 {
if (output_buffer.len < names.len) return error.BufferTooShort;
log.debug("Repository.attributeManyExtended called, options={}, path={s}", .{ options, path });
var c_options = options.makeCOptionObject();
try internal.wrapCall("git_attr_get_many_ext", .{
@ptrCast([*c][*c]const u8, output_buffer.ptr),
@ptrCast(*c.git_repository, self),
&c_options,
path.ptr,
names.len,
@ptrCast([*c][*c]const u8, names.ptr),
});
log.debug("fetched attributes", .{});
return output_buffer[0..names.len];
}
/// Invoke `callback_fn` for all the git attributes for a path with extended options.
///
///
/// ## Parameters
/// * `options` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `name` - The attribute name
/// * `value` - The attribute value. May be `null` if the attribute is explicitly set to UNSPECIFIED using the '!' sign.
pub fn attributeForeachExtended(
self: *const Repository,
options: AttributeOptions,
path: [:0]const u8,
comptime callback_fn: fn (
name: [:0]const u8,
value: ?[:0]const u8,
) c_int,
) !c_int {
const cb = struct {
pub fn cb(
name: [*c]const u8,
value: [*c]const u8,
payload: ?*anyopaque,
) callconv(.C) c_int {
_ = payload;
return callback_fn(
std.mem.sliceTo(name, 0),
if (value) |ptr| std.mem.sliceTo(ptr, 0) else null,
);
}
}.cb;
log.debug("Repository.attributeForeach called, options={}, path={s}", .{ options, path });
const c_options = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_attr_foreach_ext", .{
@ptrCast(*const c.git_repository, self),
&c_options,
path.ptr,
cb,
null,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Invoke `callback_fn` for all the git attributes for a path with extended options.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `options` - options for fetching attributes
/// * `path` - The path to check for attributes. Relative paths are interpreted relative to the repo root. The file does not
/// have to exist, but if it does not, then it will be treated as a plain file (not a directory).
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `name` - The attribute name
/// * `value` - The attribute value. May be `null` if the attribute is explicitly set to UNSPECIFIED using the '!' sign.
/// * `user_data_ptr` - pointer to user data
pub fn attributeForeachWithUserDataExtended(
self: *const Repository,
options: AttributeOptions,
path: [:0]const u8,
user_data: anytype,
comptime callback_fn: fn (
name: [:0]const u8,
value: ?[:0]const u8,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(
name: [*c]const u8,
value: [*c]const u8,
payload: ?*anyopaque,
) callconv(.C) c_int {
return callback_fn(
std.mem.sliceTo(name, 0),
if (value) |ptr| std.mem.sliceTo(ptr, 0) else null,
@ptrCast(UserDataType, payload),
);
}
}.cb;
log.debug("Repository.attributeForeachWithUserData called, options={}, path={s}", .{ options, path });
const c_options = options.makeCOptionObject();
const ret = try internal.wrapCallWithReturn("git_attr_foreach_ext", .{
@ptrCast(*const c.git_repository, self),
&c_options,
path.ptr,
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
pub const AttributeOptions = struct {
flags: AttributeFlags,
commit_id: *git.Oid,
attr_commit_id: git.Oid = .{.id = [_]u8{0}**20},
pub fn makeCOptionObject(self: AttributeOptions) c.git_attr_options {
return .{
.version = c.GIT_ATTR_OPTIONS_VERSION,
.flags = self.flags.toCType(),
.commit_id = @ptrCast(*c.git_oid, self.commit_id),
.attr_commit_id = @bitCast(c.git_oid, self.attr_commit_id),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Read a file from the filesystem and write its content to the Object Database as a loose blob
pub fn blobFromBuffer(self: *Repository, buffer: []const u8) !git.Oid {
log.debug("Repository.blobFromBuffer called, buffer={s}", .{buffer});
var ret: git.Oid = undefined;
try internal.wrapCall("git_blob_create_from_buffer", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
buffer.ptr,
buffer.len,
});
// 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 read blob: {s}", .{slice});
}
return ret;
}
/// Create a stream to write a new blob into the object db
///
/// This function may need to buffer the data on disk and will in general not be the right choice if you know the size of the
/// data to write. If you have data in memory, use `blobFromBuffer()`. If you do not, but know the size of the contents
/// (and don't want/need to perform filtering), use `Odb.openWriteStream()`.
///
/// Don't close this stream yourself but pass it to `WriteStream.commit()` to commit the write to the object db and get the
/// object id.
///
/// If the `hintpath` parameter is filled, it will be used to determine what git filters should be applied to the object
/// before it is written to the object database.
pub fn blobFromStream(self: *Repository, hint_path: ?[:0]const u8) !*git.WriteStream {
log.debug("Repository.blobFromDisk called, hint_path={s}", .{hint_path});
var write_stream: *git.WriteStream = undefined;
const hint_path_c = if (hint_path) |ptr| ptr.ptr else null;
try internal.wrapCall("git_blob_create_from_stream", .{
@ptrCast(*?*c.git_writestream, &write_stream),
@ptrCast(*c.git_repository, self),
hint_path_c,
});
log.debug("successfully created writestream {*}", .{write_stream});
return write_stream;
}
/// Read a file from the filesystem and write its content to the Object Database as a loose blob
pub fn blobFromDisk(self: *Repository, path: [:0]const u8) !git.Oid {
log.debug("Repository.blobFromDisk called, path={s}", .{path});
var ret: git.Oid = undefined;
try internal.wrapCall("git_blob_create_from_disk", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
path.ptr,
});
// 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 read blob: {s}", .{slice});
}
return ret;
}
/// Read a file from the working folder of a repository and write it to the Object Database as a loose blob
pub fn blobFromWorkdir(self: *Repository, relative_path: [:0]const u8) !git.Oid {
log.debug("Repository.blobFromWorkdir called, relative_path={s}", .{relative_path});
var ret: git.Oid = undefined;
try internal.wrapCall("git_blob_create_from_workdir", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
relative_path.ptr,
});
// 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 read blob: {s}", .{slice});
}
return ret;
}
/// List names of linked working trees
///
/// The returned list needs to be `deinit`-ed
pub fn worktreeList(self: *Repository) !git.StrArray {
log.debug("Repository.worktreeList called", .{});
var ret: git.StrArray = undefined;
try internal.wrapCall("git_worktree_list", .{
@ptrCast(*c.git_strarray, &ret),
@ptrCast(*c.git_repository, self),
});
log.debug("successfully fetched worktree list of {} items", .{ret.count});
return ret;
}
/// Lookup a working tree by its name for a given repository
pub fn worktreeByName(self: *Repository, name: [:0]const u8) !*git.Worktree {
log.debug("Repository.worktreeByName called, name={s}", .{name});
var ret: *git.Worktree = undefined;
try internal.wrapCall("git_worktree_lookup", .{
@ptrCast(*?*c.git_worktree, &ret),
@ptrCast(*c.git_repository, self),
name.ptr,
});
log.debug("successfully fetched worktree {*}", .{ret});
return ret;
}
/// Open a worktree of a given repository
///
/// If a repository is not the main tree but a worktree, this function will look up the worktree inside the parent
/// repository and create a new `git.Worktree` structure.
pub fn worktreeOpenFromRepository(self: *Repository) !*git.Worktree {
log.debug("Repository.worktreeOpenFromRepository called", .{});
var ret: *git.Worktree = undefined;
try internal.wrapCall("git_worktree_open_from_repository", .{
@ptrCast(*?*c.git_worktree, &ret),
@ptrCast(*c.git_repository, self),
});
log.debug("successfully fetched worktree {*}", .{ret});
return ret;
}
pub const WorktreeAddOptions = struct {
/// lock newly created worktree
lock: bool = false,
/// reference to use for the new worktree HEAD
ref: ?*git.Reference = null,
pub fn makeCOptionObject(self: WorktreeAddOptions) c.git_worktree_add_options {
return .{
.version = c.GIT_WORKTREE_ADD_OPTIONS_VERSION,
.lock = @boolToInt(self.lock),
.ref = @ptrCast(?*c.git_reference, self.ref),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Add a new working tree
///
/// Add a new working tree for the repository, that is create the required data structures inside the repository and
/// check out the current HEAD at `path`
///
/// ## Parameters
/// * `name` - Name of the working tree
/// * `path` - Path to create working tree at
/// * `options` - Options to modify default behavior.
pub fn worktreeAdd(self: *Repository, name: [:0]const u8, path: [:0]const u8, options: WorktreeAddOptions) !*git.Worktree {
log.debug("Repository.worktreeAdd called, name={s}, path={s}, options={}", .{ name, path, options });
var ret: *git.Worktree = undefined;
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_worktree_add", .{
@ptrCast(*?*c.git_worktree, &ret),
@ptrCast(*c.git_repository, self),
name.ptr,
path.ptr,
&c_options,
});
log.debug("successfully created worktree {*}", .{ret});
return ret;
}
/// Lookup a tree object from the repository.
///
/// ## Parameters
/// * `id` - identity of the tree to locate.
pub fn treeLookup(self: *Repository, id: *const git.Oid) !*git.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 id.formatHex(&buf);
log.debug("Repository.treeLookup called, id={s}", .{slice});
}
var ret: *git.Tree = undefined;
try internal.wrapCall("git_tree_lookup", .{
@ptrCast(*?*c.git_tree, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
});
log.debug("successfully located tree: {*}", .{ret});
return ret;
}
/// Lookup a tree object from the repository, given a prefix of its identifier (short id).
///
/// ## Parameters
/// * `id` - identity of the tree to locate.
/// * `len` - the length of the short identifier
pub fn treeLookupPrefix(self: *Repository, id: *const git.Oid, len: usize) !*git.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 id.formatHexCount(&buf, len);
log.debug("Repository.treeLookupPrefix, id={s}, len={}", .{ slice, len });
}
var ret: *git.Tree = undefined;
try internal.wrapCall("git_tree_lookup_prefix", .{
@ptrCast(*?*c.git_tree, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
len,
});
log.debug("successfully located tree: {*}", .{ret});
return ret;
}
/// Convert a tree entry to the git_object it points to.
///
/// You must call `git.Object.deint` on the object when you are done with it.
pub fn treeEntrytoObject(self: *Repository, entry: *const git.Tree.Entry) !*git.Object {
log.debug("Repository.treeEntrytoObject called, entry={*}", .{entry});
var ret: *git.Object = undefined;
try internal.wrapCall("git_tree_entry_to_object", .{
@ptrCast(*?*c.git_object, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_tree_entry, entry),
});
log.debug("successfully fetched object: {*}", .{ret});
return ret;
}
/// Create a new tree builder.
///
/// The tree builder can be used to create or modify trees in memory and write them as tree objects to the database.
///
/// If the `source` parameter is not `null`, the tree builder will be initialized with the entries of the given tree.
///
/// If the `source` parameter is `null`, the tree builder will start with no entries and will have to be filled manually.
pub fn treebuilderNew(self: *Repository, source: ?*const git.Tree) !*git.TreeBuilder {
log.debug("Repository.treebuilderNew called, source={*}", .{source});
var ret: *git.TreeBuilder = undefined;
try internal.wrapCall("git_treebuilder_new", .{
@ptrCast(*?*c.git_treebuilder, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(?*const c.git_tree, source),
});
log.debug("successfully created treebuilder: {*}", .{ret});
return ret;
}
pub const TreeUpdateAction = extern struct {
/// Update action. If it's an removal, only the path is looked at
action: Action,
/// The entry's id
id: git.Oid,
/// The filemode/kind of object
filemode: git.FileMode,
// The full path from the root tree
path: [*:0]const u8,
pub const Action = enum(c_uint) {
/// Update or insert an entry at the specified path
UPSERT = 0,
/// Remove an entry from the specified path
REMOVE = 1,
};
};
/// Create a tree based on another one with the specified modifications
///
/// Given the `baseline` perform the changes described in the list of `updates` and create a new tree.
///
/// This function is optimized for common file/directory addition, removal and replacement in trees.
/// It is much more efficient than reading the tree into a `git.Index` and modifying that, but in exchange it is not as
/// flexible.
///
/// Deleting and adding the same entry is undefined behaviour, changing a tree to a blob or viceversa is not supported.
///
/// ## Parameters
/// * `baseline` - the tree to base these changes on, must be the repository `baseline` is in
/// * `updates` - the updates to perform
pub fn createUpdatedTree(self: *Repository, baseline: *git.Tree, updates: []const TreeUpdateAction) !git.Oid {
log.debug("Repository.createUpdatedTree called, baseline={*}, number of updates={}", .{ baseline, updates.len });
var ret: git.Oid = undefined;
try internal.wrapCall("git_tree_create_updated", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_tree, baseline),
updates.len,
@ptrCast([*]const c.git_tree_update, updates.ptr),
});
// 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 created new tree: {s}", .{slice});
}
return ret;
}
/// Creates a new iterator for notes
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
pub fn noteIterator(self: *Repository, notes_ref: ?[:0]const u8) !*git.NoteIterator {
log.debug("Repository.noteIterator called, notes_ref={s}", .{notes_ref});
var ret: *git.NoteIterator = undefined;
const c_notes: [*c]const u8 = if (notes_ref) |p| p.ptr else null;
try internal.wrapCall("git_note_iterator_new", .{
@ptrCast(*?*c.git_note_iterator, &ret),
@ptrCast(*c.git_repository, self),
c_notes,
});
return ret;
}
/// Read the note for an object
///
/// ## Parameters
/// * `oid` - OID of the git object to read the note from
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
pub fn noteRead(self: *Repository, oid: *const git.Oid, notes_ref: ?[:0]const u8) !*git.Note {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteRead called, oid={s}, notes_ref={s}", .{ slice, notes_ref });
}
var ret: *git.Note = undefined;
const c_notes: [*c]const u8 = if (notes_ref) |p| p.ptr else null;
try internal.wrapCall("git_note_read", .{
@ptrCast(*?*c.git_note, &ret),
@ptrCast(*c.git_repository, self),
c_notes,
@ptrCast(*const c.git_oid, oid),
});
log.debug("successfully read note: {*}", .{ret});
return ret;
}
/// Read the note for an object
///
/// ## Parameters
/// * `oid` - OID of the git object to read the note from
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
pub fn noteReadFromNoteCommit(self: *Repository, oid: *const git.Oid, note_commit: *git.Commit) !*git.Note {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteReadFromNoteCommit called, oid={s}, note_commit={*}", .{ slice, note_commit });
}
var ret: *git.Note = undefined;
try internal.wrapCall("git_note_commit_read", .{
@ptrCast(*?*c.git_note, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_commit, note_commit),
@ptrCast(*const c.git_oid, oid),
});
log.debug("successfully read note: {*}", .{ret});
return ret;
}
/// Add a note for an object
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `author` - signature of the notes commit author
/// * `commiter` - signature of the notes commit committer
/// * `oid` - OID of the git object to decorate
/// * `note` - Content of the note to add for object oid
/// * `force` - Overwrite existing note
pub fn noteCreate(
self: *Repository,
notes_ref: ?[:0]const u8,
author: *const git.Signature,
commiter: *const git.Signature,
oid: *const git.Oid,
note: [:0]const u8,
force: bool,
) !git.Oid {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteCreate called, notes_ref={s}, author={s}, commiter={s}, oid={s}, note={s}, force={}", .{
notes_ref,
author.name(),
commiter.name(),
slice,
note,
force,
});
}
var ret: git.Oid = undefined;
const c_notes: [*c]const u8 = if (notes_ref) |p| p.ptr else null;
try internal.wrapCall("git_note_create", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
c_notes,
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, commiter),
@ptrCast(*const c.git_oid, oid),
note.ptr,
@boolToInt(force),
});
log.debug("successfully created note", .{});
return ret;
}
pub const NoteCommitResult = struct {
note_commit: git.Oid,
note_blob: git.Oid,
};
/// Add a note for an object from a commit
///
/// This function will create a notes commit for a given object, the commit is a dangling commit, no reference is created.
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `author` - signature of the notes commit author
/// * `commiter` - signature of the notes commit committer
/// * `oid` - OID of the git object to decorate
/// * `note` - Content of the note to add for object oid
/// * `allow_note_overwrite` - Overwrite existing note
pub fn noteCommitCreate(
self: *Repository,
parent: *git.Commit,
author: *const git.Signature,
commiter: *const git.Signature,
oid: *const git.Oid,
note: [:0]const u8,
allow_note_overwrite: bool,
) !NoteCommitResult {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteCommitCreate called, parent={*}, author={s}, commiter={s}, oid={s}, note={s}, allow_note_overwrite={}", .{
parent,
author.name(),
commiter.name(),
slice,
note,
allow_note_overwrite,
});
}
var ret: NoteCommitResult = undefined;
try internal.wrapCall("git_note_commit_create", .{
@ptrCast(*c.git_oid, &ret.note_commit),
@ptrCast(*c.git_oid, &ret.note_blob),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_commit, parent),
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, commiter),
@ptrCast(*const c.git_oid, oid),
note.ptr,
@boolToInt(allow_note_overwrite),
});
log.debug("successfully created note commit", .{});
return ret;
}
/// Remove the note for an object
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `author` - signature of the notes commit author
/// * `commiter` - signature of the notes commit committer
/// * `oid` - OID of the git object to remove the note from
pub fn noteRemove(
self: *Repository,
notes_ref: ?[:0]const u8,
author: *const git.Signature,
commiter: *const git.Signature,
oid: *const git.Oid,
) !void {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteRemove called, notes_ref={s}, author={s}, commiter={s}, oid={s}", .{
notes_ref,
author.name(),
commiter.name(),
slice,
});
}
const c_notes: [*c]const u8 = if (notes_ref) |p| p.ptr else null;
try internal.wrapCall("git_note_remove", .{
@ptrCast(*c.git_repository, self),
c_notes,
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, commiter),
@ptrCast(*const c.git_oid, oid),
});
log.debug("successfully removed note", .{});
}
/// Remove the note for an object
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `author` - signature of the notes commit author
/// * `commiter` - signature of the notes commit committer
/// * `oid` - OID of the git object to remove the note from
pub fn noteCommitRemove(
self: *Repository,
note_commit: *git.Commit,
author: *const git.Signature,
commiter: *const git.Signature,
oid: *const git.Oid,
) !git.Oid {
// 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 oid.formatHex(&buf);
log.debug("Repository.noteCommitRemove called, note_commit={*}, author={s}, commiter={s}, oid={s}", .{
note_commit,
author.name(),
commiter.name(),
slice,
});
}
var ret: git.Oid = undefined;
try internal.wrapCall("git_note_commit_remove", .{
@ptrCast(*c.git_oid, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*c.git_commit, note_commit),
@ptrCast(*const c.git_signature, author),
@ptrCast(*const c.git_signature, commiter),
@ptrCast(*const c.git_oid, oid),
});
log.debug("successfully removed note commit", .{});
return ret;
}
/// Get the default notes reference for a repository
pub fn noteDefaultRef(self: *Repository) !git.Buf {
log.debug("Repository.noteDefaultRef called", .{});
var ret: git.Buf = .{};
try internal.wrapCall("git_note_default_ref", .{
@ptrCast(*c.git_buf, &ret),
@ptrCast(*c.git_repository, self),
});
log.debug("default ref: {s}", .{ret.toSlice()});
return ret;
}
/// Loop over all the notes within a specified namespace and issue a callback for each one.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `blob_id` - Oid of the blob containing the message
/// * `annotated_object_id` - Oid of the git object being annotated
pub fn noteForeach(
self: *Repository,
notes_ref: ?[:0]const u8,
comptime callback_fn: fn (
blob_id: *const git.Oid,
annotated_object_id: *const git.Oid,
) c_int,
) !c_int {
const cb = struct {
pub fn cb(
blob_id: *const git.Oid,
annotated_object_id: *const git.Oid,
_: *u8,
) c_int {
return callback_fn(blob_id, annotated_object_id);
}
}.cb;
var dummy_data: u8 = undefined;
return self.noteForeachWithUserData(&dummy_data, notes_ref, cb);
}
/// Loop over all the notes within a specified namespace and issue a callback for each one.
///
/// Return a non-zero value from the callback to stop the loop. This non-zero value is returned by the function.
///
/// ## Parameters
/// * `notes_ref` - canonical name of the reference to use; if `null` defaults to "refs/notes/commits"
/// * `user_data` - pointer to user data to be passed to the callback
/// * `callback_fn` - the callback function
///
/// ## Callback Parameters
/// * `blob_id` - Oid of the blob containing the message
/// * `annotated_object_id` - Oid of the git object being annotated
/// * `user_data_ptr` - pointer to user data
pub fn noteForeachWithUserData(
self: *Repository,
notes_ref: ?[:0]const u8,
user_data: anytype,
comptime callback_fn: fn (
blob_id: *const git.Oid,
annotated_object_id: *const git.Oid,
user_data_ptr: @TypeOf(user_data),
) c_int,
) !c_int {
const UserDataType = @TypeOf(user_data);
const cb = struct {
pub fn cb(
blob_id: *const c.git_oid,
annotated_object_id: *const c.git_oid,
payload: ?*anyopaque,
) callconv(.C) c_int {
return callback_fn(
@ptrCast(*const git.Oid, blob_id),
@ptrCast(*const git.Oid, annotated_object_id),
@ptrCast(UserDataType, payload),
);
}
}.cb;
log.debug("Repository.noteForeachWithUserData called, notes_ref={s}", .{notes_ref});
const c_notes: [*c]const u8 = if (notes_ref) |p| p.ptr else null;
const ret = try internal.wrapCallWithReturn("git_note_foreach", .{
@ptrCast(*c.git_repository, self),
c_notes,
cb,
user_data,
});
log.debug("callback returned: {}", .{ret});
return ret;
}
/// Lookup a reference to one of the objects in a repository.
///
/// The generated reference is owned by the repository and should be closed with `git.Object.deinit`.
///
/// The 'object_type' parameter must match the type of the object in the odb; the method will fail otherwise.
/// The special value 'git.ObjectType.ANY' may be passed to let the method guess the object's type.
///
/// ## Parameters
/// * `id` - the unique identifier for the object
/// * `object_type` - the type of the object
pub fn objectLookup(self: *Repository, id: *const git.Oid, object_type: git.ObjectType) !*git.Object {
// 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 id.formatHex(&buf);
log.debug("Repository.objectLookup called, id={s}, object_type={}", .{
slice,
object_type,
});
}
var ret: *git.Object = undefined;
try internal.wrapCall("git_object_lookup", .{
@ptrCast(*?*c.git_object, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
@enumToInt(object_type),
});
log.debug("successfully located object: {*}", .{ret});
return ret;
}
/// Lookup a reference to one of the objects in a repository, given a prefix of its identifier (short id).
///
/// The object obtained will be so that its identifier matches the first 'len' hexadecimal characters (packets of 4 bits) of
/// the given 'id'.
/// 'len' must be at least `git.Oid.MIN_PREFIX_LEN`, and long enough to identify a unique object matching/ the prefix;
/// otherwise the method will fail.
///
/// The generated reference is owned by the repository and should be closed with `git.Object.deinit`.
///
/// The 'object_type' parameter must match the type of the object in the odb; the method will fail otherwise.
/// The special value 'git.ObjectType.ANY' may be passed to let the method guess the object's type.
///
/// ## Parameters
/// * `id` - a short identifier for the object
/// * `len` - the length of the short identifier
/// * `object_type` - the type of the object
pub fn objectLookupPrefix(self: *Repository, id: *const git.Oid, len: usize, object_type: git.ObjectType) !*git.Object {
// 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 id.formatHexCount(&buf, len);
log.debug("Repository.objectLookupPrefix called, id={s}, object_type={}", .{
slice,
object_type,
});
}
var ret: *git.Object = undefined;
try internal.wrapCall("git_object_lookup_prefix", .{
@ptrCast(*?*c.git_object, &ret),
@ptrCast(*c.git_repository, self),
@ptrCast(*const c.git_oid, id),
len,
@enumToInt(object_type),
});
log.debug("successfully located object: {*}", .{ret});
return ret;
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Valid modes for index and tree entries.
pub const FileMode = enum(u16) {
UNREADABLE = 0o000000,
TREE = 0o040000,
BLOB = 0o100644,
BLOB_EXECUTABLE = 0o100755,
LINK = 0o120000,
COMMIT = 0o160000,
};
pub const FileStatus = packed struct {
CURRENT: bool = false,
INDEX_NEW: bool = false,
INDEX_MODIFIED: bool = false,
INDEX_DELETED: bool = false,
INDEX_RENAMED: bool = false,
INDEX_TYPECHANGE: bool = false,
WT_NEW: bool = false,
WT_MODIFIED: bool = false,
WT_DELETED: bool = false,
WT_TYPECHANGE: bool = false,
WT_RENAMED: bool = false,
WT_UNREADABLE: bool = false,
IGNORED: bool = false,
CONFLICTED: bool = false,
z_padding1: u2 = 0,
z_padding2: u16 = 0,
pub fn format(
value: FileStatus,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{ "z_padding1", "z_padding2" },
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(FileStatus));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(FileStatus));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
|
src/repository.zig
|
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const Vec2 = tools.Vec2;
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const Food = struct { ing: []const u16, alg: []const u16 };
const param: struct {
allergens: [][]const u8,
ingredients: [][]const u8,
foods: []Food,
} = param: {
var allergens_hash = std.StringHashMap(u16).init(allocator);
defer allergens_hash.deinit();
var ingredients_hash = std.StringHashMap(u16).init(allocator);
defer ingredients_hash.deinit();
var allergens = std.ArrayList([]const u8).init(arena.allocator());
var ingredients = std.ArrayList([]const u8).init(arena.allocator());
var foods = std.ArrayList(Food).init(arena.allocator());
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
if (tools.match_pattern("{} (contains {})", line)) |fields| {
var ings: [100]u16 = undefined;
var nb_ing: u32 = 0;
{
var it2 = std.mem.tokenize(u8, fields[0].lit, " ,");
while (it2.next()) |word| {
const ingredient_idx = blk: {
const kv = try ingredients_hash.getOrPut(word);
if (kv.found_existing)
break :blk kv.value_ptr.*;
kv.value_ptr.* = @intCast(u16, ingredients.items.len);
try ingredients.append(word);
break :blk kv.value_ptr.*;
};
ings[nb_ing] = ingredient_idx;
nb_ing += 1;
}
}
var algs: [100]u16 = undefined;
var nb_alg: u32 = 0;
{
var it2 = std.mem.tokenize(u8, fields[1].lit, " ,");
while (it2.next()) |word| {
const allergen_idx = blk: {
const kv = try allergens_hash.getOrPut(word);
if (kv.found_existing)
break :blk kv.value_ptr.*;
kv.value_ptr.* = @intCast(u16, allergens.items.len);
try allergens.append(word);
break :blk kv.value_ptr.*;
};
algs[nb_alg] = allergen_idx;
nb_alg += 1;
}
}
try foods.append(Food{
.ing = try arena.allocator().dupe(u16, ings[0..nb_ing]),
.alg = try arena.allocator().dupe(u16, algs[0..nb_alg]),
});
} else {
std.debug.print("parse error: '{s}'\n", .{line});
return error.UnsupportedInput;
}
}
// std.debug.print("got {} ingredients, {} allergens, {} foods\n", .{ ingredients.items.len, allergens.items.len, foods.items.len });
break :param .{
.allergens = allergens.items,
.ingredients = ingredients.items,
.foods = foods.items,
};
};
var inert_ings = std.ArrayList(u16).init(allocator);
defer inert_ings.deinit();
const ans1 = ans: {
var total: u32 = 0;
next_ing: for (param.ingredients) |_, i| {
for (param.allergens) |_, a| {
const can_contain_allegen = for (param.foods) |f| {
const has_allergen = std.mem.indexOfScalar(u16, f.alg, @intCast(u16, a)) != null;
if (!has_allergen) continue;
const in_food = std.mem.indexOfScalar(u16, f.ing, @intCast(u16, i)) != null;
if (!in_food) break false;
} else true;
if (can_contain_allegen) continue :next_ing;
}
try inert_ings.append(@intCast(u16, i));
var nb: u32 = 0;
for (param.foods) |f| {
for (f.ing) |x| {
if (x == i) nb += 1;
}
}
total += nb;
// std.debug.print("ingredient '{}' ({}): no allergens. appears {} times\n", .{ ingredient, i, nb });
}
break :ans total;
};
const ans2 = ans: {
// const matrix = try allocator.alloc(bool, param.ingredients.len * param.allergens.len); -> mauviase approche ... mehhh
assert(param.allergens.len == param.ingredients.len - inert_ings.items.len);
const active_ingredients = try allocator.alloc(u16, param.allergens.len);
defer allocator.free(active_ingredients);
var idx: u32 = 0;
for (param.ingredients) |_, i| {
if (std.mem.indexOfScalar(u16, inert_ings.items, @intCast(u16, i))) |_| continue;
active_ingredients[idx] = @intCast(u16, i);
idx += 1;
}
var buf: [50]u16 = undefined;
var it = tools.generate_permutations(u16, active_ingredients);
next_perm: while (it.next(&buf)) |perm| {
for (perm) |i, a| {
const possible = for (param.foods) |f| {
const has_allergen = std.mem.indexOfScalar(u16, f.alg, @intCast(u16, a)) != null;
if (!has_allergen) continue;
const in_food = std.mem.indexOfScalar(u16, f.ing, @intCast(u16, i)) != null;
if (!in_food) break false;
} else true;
if (!possible) continue :next_perm;
}
// bingo!
const Pair = struct {
ing: []const u8,
alg: []const u8,
fn lessThan(_: void, lhs: @This(), rhs: @This()) bool {
return std.mem.lessThan(u8, lhs.alg, rhs.alg);
}
};
var result: [32]Pair = undefined;
for (perm) |i, a| {
result[a] = .{
.ing = param.ingredients[i],
.alg = param.allergens[a],
};
}
std.sort.sort(Pair, result[0..perm.len], {}, Pair.lessThan);
const result_text = try arena.allocator().alloc(u8, 500);
var len: usize = 0;
for (result[0..perm.len]) |r, index| {
std.mem.copy(u8, result_text[len .. len + r.ing.len], r.ing);
len += r.ing.len;
if (index < perm.len - 1) {
result_text[len] = ',';
len += 1;
}
}
break :ans result_text[0..len];
}
unreachable;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{s}", .{ans2}),
};
}
pub const main = tools.defaultMain("2020/input_day21.txt", run);
|
2020/day21.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const mat = @import("zalgebra");
const mat4 = mat.mat4;
const vec = mat.vec3;
const model = @import("model.zig");
usingnamespace @import("utils.zig");
const base = @import("main.zig");
const roundUp = base.roundUp;
const getKey = base.getKey;
const log = std.log;
pub const app_title = "adf-box";
const Vertex = struct {
x: f32,
y: f32,
z: f32,
nx: f32,
ny: f32,
nz: f32,
u: f32,
v: f32,
};
const UniformBuffer = struct {
view: mat4,
position: mat.vec4,
buffer_size: i32,
fov: f32,
margin: f32 = 0.0001,
limit: f32 = 4,
light: mat.vec4,
screeen_size: mat.vec2,
intensity: f32 = 0.1,
};
const PipelineDesc = struct {
pipeline: vez.Pipeline = null,
shaderModules: []vk.ShaderModule,
};
var graphicsQueue: vk.Queue = null;
var vertexBuffer: Buffer = undefined;
var indexBuffer: Buffer = undefined;
var renderTexture: Image = undefined;
var values: Image = undefined;
var oct_data: Buffer = undefined;
var material_data: Buffer = undefined;
var uniform_buffer: vk.Buffer = null;
var drawPipeline: PipelineDesc = undefined;
var computePipeline: PipelineDesc = undefined;
var commandBuffer: vk.CommandBuffer = null;
var customCallback: vk.DebugUtilsMessengerEXT = null;
var lastPos = [2]i32{ 0, 0 };
var view = mat.vec2{ .x = 0, .y = 0 };
var position = vec.new(0.5, 0.5, -0.5);
var light = vec.new(-1, -2, -2);
var lookMode = false;
var bufferSize: i32 = 0;
var filename: []const u8 = "";
pub fn load(allocator: *Allocator) !void {
var args = std.process.ArgIterator.init();
var programName = if (args.next(allocator)) |program|
try program
else
fail("<adf-box>");
defer allocator.free(programName);
if (args.next(allocator)) |file|
filename = try file
else
fail(programName);
if (args.next(allocator)) |d| {
const depth = try d;
defer allocator.free(depth);
model.max_depth = std.fmt.parseInt(u32, depth, 10)
catch |err| fail(programName);
}
try createModel(allocator);
}
fn fail(program_name: []const u8) noreturn {
std.debug.print("usage: ${s} <filename> [depth]", .{program_name});
std.os.exit(0);
}
pub fn initialize(allocator: *Allocator) !void {
try createQuad();
try createRenderTexture();
try createUniformBuffer();
try createPipeline(allocator);
try createCommandBuffer();
}
pub fn cleanup() !void {
var device = base.getDevice();
vertexBuffer.deinit(device);
indexBuffer.deinit(device);
renderTexture.deinit(device);
values.deinit(device);
oct_data.deinit(device);
material_data.deinit(device);
vez.destroyBuffer(device, uniform_buffer);
vez.destroyPipeline(device, drawPipeline.pipeline);
for (drawPipeline.shaderModules) |shaderModule| {
vez.destroyShaderModule(device, shaderModule);
}
vez.destroyPipeline(device, computePipeline.pipeline);
for (computePipeline.shaderModules) |shaderModule| {
vez.destroyShaderModule(device, shaderModule);
}
vez.freeCommandBuffers(device, 1, &commandBuffer);
}
pub fn draw() !void {
var semaphore: vk.Semaphore = null;
// var fence: vk.Fence = null;
try convert(vez.deviceWaitIdle(base.getDevice()));
const submitInfo = vez.SubmitInfo{
.waitSemaphoreCount = 0, // default
.pWaitSemaphores = null, // default
.pWaitDstStageMask = null, // default
.commandBufferCount = 1,
.pCommandBuffers = &commandBuffer,
.signalSemaphoreCount = 1,
.pSignalSemaphores = &semaphore,
};
try convert(vez.queueSubmit(graphicsQueue, 1, &submitInfo, null));
try convert(vez.deviceWaitIdle(base.getDevice()));
// _ = vez.waitForFences(base.getDevice(), 1, &fence, 1, 10_000_000_000);
// _ = vez.destroyFence(base.getDevice(), fence);
// Present the swapchain framebuffer to the window.
const waitDstStageMask = @intCast(u32, vk.PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); //VkPipelineStageFlags
const swapchain = base.getSwapchain();
const srcImage = base.framebuffer.colorImage;
// The glfw windowSizeCallback seems to sometimes come one frame late;
// because V-EZ automatically resizes the swapchain (but not the framebuffer)
// to fit the surface, we need to explicitly check this.
var new_size: [2]c_int = undefined;
const old_size = base.getWindowSize();
c.glfwGetWindowSize(base.getWindow(), &new_size[0], &new_size[1]);
if (new_size[0] != old_size[0] or new_size[1] != old_size[1]) {
try base.resize();
return;
}
const presentInfo = vez.PresentInfo{
.signalSemaphoreCount = 0, // default
.pSignalSemaphores = null, // default
.pResults = null, // default
.waitSemaphoreCount = 1,
.pWaitSemaphores = &semaphore,
.pWaitDstStageMask = &waitDstStageMask,
.swapchainCount = 1,
.pSwapchains = &swapchain,
.pImages = &srcImage,
};
try convert(vez.queuePresent(graphicsQueue, &presentInfo)) catch |err| switch (err) {
VulkanError.Suboptimal, // hmmst
VulkanError.OutOfDate => {
try base.resize();
},
else => err,
};
}
pub fn onResize(width: u32, height: u32) !void {
renderTexture.deinit(base.getDevice());
try createRenderTexture();
vez.freeCommandBuffers(base.getDevice(), 1, &commandBuffer);
try createCommandBuffer();
}
pub fn onKey(key: i32, down: bool) anyerror!void {
if (key == c.KEY_TAB and down) {
base.toggleFullscreen();
}
if (key == c.KEY_ESCAPE and down) {
base.quitSignaled = true;
}
}
pub fn onMouseButton(button: i32, down: bool, x: i32, y: i32) anyerror!void {
if (down) {
lookMode = !lookMode;
c.glfwSetInputMode(base.getWindow(), c.CURSOR, if (lookMode) c.CURSOR_HIDDEN else c.CURSOR_NORMAL);
}
}
fn movePos(v: vec, time: f32) void {
position = position.add(v.scale(transformSpeed * time));
}
fn matmul(matrix: mat4, v: vec) vec {
var r = matrix.mult_by_vec4(mat.vec4.new(v.x, v.y, v.z, 1));
return vec.new(r.x, r.y, r.z);
}
const turnSpeed = 0.1;
const transformSpeed = 0.3;
pub fn update(delta: f32) !void {
var size = base.getWindowSize();
if (lookMode) {
const newPos = base.getCursorPos();
var mouseDelta = mat.vec2{
.x = @intToFloat(f32, -lastPos[0] + newPos[0]),
.y = @intToFloat(f32, lastPos[1] - newPos[1]),
};
view.x = try std.math.mod(f32, view.x + mouseDelta.x * turnSpeed, 360);
view.y = std.math.clamp(view.y + mouseDelta.y * turnSpeed, -90, 90);
c.glfwSetCursorPos(base.getWindow(), @intToFloat(f64, size[0] / 2), @intToFloat(f64, size[1] / 2));
}
lastPos = base.getCursorPos();
var viewMat = mat4.identity().rotate(view.x, vec.up()).rotate(view.y, vec.right());
var v = delta;
if (getKey(c.KEY_SPACE)) {
v *= 0.25;
}
if (getKey(c.KEY_W) or getKey(c.KEY_KP_8)) {
movePos(matmul(viewMat, vec.new(0, 0, 1)), v);
}
if (getKey(c.KEY_S) or getKey(c.KEY_KP_2)) {
movePos(matmul(viewMat, vec.new(0, 0, -1)), v);
}
if (getKey(c.KEY_D) or getKey(c.KEY_KP_6)) {
movePos(matmul(viewMat, vec.new(1, 0, 0)), v);
}
if (getKey(c.KEY_A) or getKey(c.KEY_KP_4)) {
movePos(matmul(viewMat, vec.new(-1, 0, 0)), v);
}
if (getKey(c.KEY_LEFT_SHIFT) or getKey(c.KEY_KP_9)) {
movePos(vec.new(0, -1, 0), v);
}
if (getKey(c.KEY_LEFT_CONTROL) or getKey(c.KEY_KP_3)) {
movePos(vec.new(0, 1, 0), v);
}
var c0 = v * 2; // get it?
if (getKey(c.KEY_U)) {
light.x += c0;
}
if (getKey(c.KEY_J)) {
light.x -= c0;
}
if (getKey(c.KEY_K)) {
light.y += c0;
}
if (getKey(c.KEY_I)) {
light.y -= c0;
}
if (getKey(c.KEY_O)) {
light.z += c0;
}
if (getKey(c.KEY_L)) {
light.z -= c0;
}
var ub = UniformBuffer{
.view = viewMat,
.position = mat.vec4.new(position.x, position.y, position.z, 1),
.buffer_size = bufferSize,
.fov = 0.4,
.light = mat.vec4.new(light.x, light.y, light.z, 1),
.intensity = 2,
.screeen_size = mat.vec2.new(@intToFloat(f32, size[0]), @intToFloat(f32, size[1])),
};
var data: *UniformBuffer = undefined;
try convert(vez.mapBuffer(base.getDevice(), uniform_buffer, 0, @sizeOf(UniformBuffer), @ptrCast(*?*c_void, &data)));
data.* = ub;
vez.unmapBuffer(base.getDevice(), uniform_buffer);
}
fn createQuad() VulkanError!void {
// A single quad with positions, normals and uvs.
var vertices: []const Vertex = &[_]Vertex{
.{ .x = -1, .y = -1, .z = 0, .nx = 0, .ny = 0, .nz = 1, .u = 0, .v = 0 },
.{ .x = 1, .y = -1, .z = 0, .nx = 0, .ny = 0, .nz = 1, .u = 1, .v = 0 },
.{ .x = 1, .y = 1, .z = 0, .nx = 0, .ny = 0, .nz = 1, .u = 1, .v = 1 },
.{ .x = -1, .y = 1, .z = 0, .nx = 0, .ny = 0, .nz = 1, .u = 0, .v = 1 },
};
try vertexBuffer.init(base.getDevice(), vk.BUFFER_USAGE_VERTEX_BUFFER_BIT, @sizeOf(Vertex)*vertices.len);
try vertexBuffer.load(vertices);
const indices: []const u32 = &[_]u32{
0, 1, 2,
0, 2, 3,
};
try indexBuffer.init(base.getDevice(), vk.BUFFER_USAGE_INDEX_BUFFER_BIT, @sizeOf(u32)*indices.len);
try indexBuffer.load(indices);
}
fn createRenderTexture() !void {
var extent = base.getWindowSize();
const channels: u32 = 4;
// Create the base.GetDevice() side image.
var imageCreateInfo = vez.ImageCreateInfo{
.format = .FORMAT_R8G8B8A8_UNORM,
.extent = .{ .width = extent[0], .height = extent[1], .depth = 1 },
.usage = vk.IMAGE_USAGE_TRANSFER_DST_BIT | vk.IMAGE_USAGE_SAMPLED_BIT | vk.IMAGE_USAGE_STORAGE_BIT,
};
try renderTexture.init(imageCreateInfo, .FILTER_LINEAR, .SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
}
fn createModel(allocator: *Allocator) !void {
var arena = std.heap.ArenaAllocator.init(allocator);
var data = try model.load(&arena.allocator, filename);
allocator.free(filename);
// defer data.deinit(allocator);
defer arena.deinit();
// Create the device side image.
var imageCreateInfo = vez.ImageCreateInfo{
.format = .FORMAT_R8G8B8A8_UNORM,
.extent = .{ .width = data.width, .height = data.height, .depth = 1 },
.usage = vk.IMAGE_USAGE_TRANSFER_DST_BIT | vk.IMAGE_USAGE_SAMPLED_BIT,
};
try values.init(imageCreateInfo, .FILTER_LINEAR, .SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
var subDataInfo = vez.ImageSubDataInfo{
.imageExtent = .{ .width = data.width, .height = data.height, .depth = 1 },
};
try convert(vez.vezImageSubData(base.getDevice(), values.texture, &subDataInfo, data.values.ptr));
bufferSize = @intCast(i32, data.tree.len);
try oct_data.init(base.getDevice(), vk.BUFFER_USAGE_STORAGE_BUFFER_BIT, data.tree.len * @sizeOf(model.ChildRefs));
try oct_data.load(data.tree);
try material_data.init(base.getDevice(), vk.BUFFER_USAGE_STORAGE_BUFFER_BIT, data.tree.len * @sizeOf(u32));
try material_data.load(data.material);
}
fn createUniformBuffer() VulkanError!void {
const createInfo = vez.BufferCreateInfo{
.size = @sizeOf(UniformBuffer),
.usage = vk.BUFFER_USAGE_TRANSFER_DST_BIT | vk.BUFFER_USAGE_UNIFORM_BUFFER_BIT,
};
try convert(vez.createBuffer(base.getDevice(), vez.MEMORY_CPU_TO_GPU, &createInfo, &uniform_buffer));
}
fn createPipeline(allocator: *Allocator) !void {
drawPipeline = PipelineDesc{
.shaderModules = try allocator.alloc(vk.ShaderModule, 2),
};
try base.createPipeline(allocator, &[_]base.PipelineShaderInfo{
.{ .filename = "Vertex.vert", .spirv = true, .stage = .SHADER_STAGE_VERTEX_BIT },
.{ .filename = "Fragment.frag", .spirv = true, .stage = .SHADER_STAGE_FRAGMENT_BIT },
}, &drawPipeline.pipeline, drawPipeline.shaderModules);
computePipeline = PipelineDesc{
.shaderModules = try allocator.alloc(vk.ShaderModule, 1),
};
try base.createPipeline(allocator, &[_]base.PipelineShaderInfo{
.{ .filename = "Compute.comp", .spirv = true, .stage = .SHADER_STAGE_COMPUTE_BIT },
}, &computePipeline.pipeline, computePipeline.shaderModules);
}
fn createCommandBuffer() !void {
vez.getDeviceGraphicsQueue(base.getDevice(), 0, &graphicsQueue);
try convert(vez.allocateCommandBuffers(base.getDevice(), &vez.CommandBufferAllocateInfo{
.queue = graphicsQueue,
.commandBufferCount = 1,
}, &commandBuffer));
// Command buffer recording
try convert(vez.beginCommandBuffer(commandBuffer, vk.COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT));
vez.cmdBindPipeline(computePipeline.pipeline);
vez.cmdBindBuffer(uniform_buffer, 0, vk.WHOLE_SIZE, 0, 0, 0);
vez.cmdBindBuffer(oct_data.handle, 0, vk.WHOLE_SIZE, 0, 1, 0);
vez.cmdBindBuffer(material_data.handle, 0, vk.WHOLE_SIZE, 0, 2, 0);
renderTexture.cmdBind(0, 3);
values.cmdBind(0, 4);
const extents = base.getWindowSize();
const groupSize = 8;
vez.cmdDispatch(roundUp(extents[0], groupSize), roundUp(extents[1], groupSize), 1);
base.cmdSetFullViewport();
vez.cmdSetViewportState(1);
var attachmentReferences = [2]vez.AttachmentReference{
.{ .clearValue = .{ .color = .{ .float32 = .{ 0.3, 0.3, 0.3, 0.0 } } } },
.{ .clearValue = .{ .depthStencil = .{ .depth = 1.0, .stencil = 0 } } },
};
const beginInfo = vez.RenderPassBeginInfo{
.framebuffer = base.framebuffer.handle,
.attachmentCount = @intCast(u32, attachmentReferences.len),
.pAttachments = &attachmentReferences,
};
vez.cmdBeginRenderPass(&beginInfo);
vez.cmdBindPipeline(drawPipeline.pipeline);
vez.cmdBindBuffer(uniform_buffer, 0, vk.WHOLE_SIZE, 0, 0, 0);
renderTexture.cmdBind(0, 1);
// Set depth stencil state.
const depthStencilState = vez.PipelineDepthStencilState{
.depthBoundsTestEnable = 0,
.stencilTestEnable = 0,
.depthCompareOp = .COMPARE_OP_LESS_OR_EQUAL,
.depthTestEnable = vk.TRUE,
.depthWriteEnable = vk.TRUE,
.front = .{
.failOp = .STENCIL_OP_KEEP,
.passOp = .STENCIL_OP_KEEP,
.depthFailOp = .STENCIL_OP_KEEP,
}, // default?
.back = .{
.failOp = .STENCIL_OP_KEEP,
.passOp = .STENCIL_OP_KEEP,
.depthFailOp = .STENCIL_OP_KEEP,
}, // default?
};
vez.cmdSetDepthStencilState(&depthStencilState);
vez.cmdBindVertexBuffers(0, 1, &[_]vk.Buffer{vertexBuffer.handle}, &[_]u64{0});
vez.cmdBindIndexBuffer(indexBuffer.handle, 0, .INDEX_TYPE_UINT32);
vez.cmdDrawIndexed(6, 1, 0, 0, 0);
vez.cmdEndRenderPass();
try convert(vez.endCommandBuffer());
}
|
src/app.zig
|
const col = struct {
usingnamespace @import("./colors.zig");
};
const color = @import("colors.zig");
const Spec = color.Spec;
const Brightness = color.Spec.Brightness;
const Location = color.Spec.Location;
const Color = color.Color;
const code = @import("./code.zig");
const std = @import("std");
const fmt = std.fmt;
const print = std.debug.print;
const reader = std.io.getStdIn().reader();
const writer = std.io.getStdIn().writer();
const util = @import("../util.zig");
pub const Style = enum(u8) {
reset = 0,
bold = 1,
dim = 2,
italic = 3,
underline = 4,
blink = 5,
reverse = 6,
hidden = 7,
default,
const Self = @This();
pub fn toCode(self: Self) []const u8 {
return switch (self) {
.reset => ";0m",
.bold => ";1m",
.dim => ";2m",
.italic => ";3m",
.underline => ";4m",
.blink => ";5m",
.reverse => ";6m",
.hidden => ";7m",
.default => "m",
};
}
pub fn none() []const u8 {
return "m";
}
};
pub const FmtOpts = struct {
bri: Brightness.normal,
loc: Location = Location.fg,
color: Color.white,
styles: []Style,
const Self = @This();
pub fn init(bri: ?Brightness, loc: ?Location, co: ?Color) Self {
return Self{
.color = if (co) |c| c else Color.white,
.loc = if (loc) |p| p else Location.fg,
.bri = if (bri) |b| b else Brightness.normal,
.styles = undefined,
};
}
};
pub const StyledStr = struct {
str: []u8,
style: Style = Style.default,
color: Color = Color.white,
spec: Spec = Spec.default(),
args: anytype = .{},
const Self = @This();
pub fn init(buf: []const u8, args: anytype, style: ?Style, clr: ?Color, spec: ?Spec) Self {
return Self{
.buf = buf,
.args = args,
.color = clr orelse Color.white,
.spec = spec orelse Spec.normal_fg,
.style = style orelse Style.default,
};
}
pub fn withSpec(self: Self, spec: Spec) Self {
self.spec = spec;
return self;
}
pub fn withStyle(self: Self, style: Style) Self {
self.style = style;
return self;
}
pub fn toString(self: Self) []const u8 {
return self.color.styled(self.style, self.spec);
}
pub fn withBold(self: Self) []const u8 {
return self.color.bold(self.spec);
}
pub fn print(self: Self) void {
std.debug.print(self.buf, self.args);
}
pub fn write(self: Self, file: std.fs.File) !void {
_ = try file.writer().writeAll(self.toString());
}
};
const expect = std.testing.expect;
test "Style toCode" {
const cd = Style.toCode(.bold);
std.log.warn("{s}", .{cd});
try expect(std.mem.eql(u8, cd, ";1m"));
}
|
src/term/style.zig
|
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const bu = @import("./bits.zig"); // bits utilities
const hm = @import("./huffman.zig");
test "huffman_decode_basic" {
const lens = [_]u8{
3, // sym 0: 000
3, // sym 1: 001
3, // sym 2: 010
3, // sym 3: 011
3, // sym 4: 100
3, // sym 5: 101
4, // sym 6: 1100
4, // sym 7: 1101
0, // sym 8:
0, // sym 9:
0, // sym 10:
0, // sym 11:
0, // sym 12:
0, // sym 13:
0, // sym 14:
0, // sym 15:
6, // sym 16: 111110
5, // sym 17: 11110
4, // sym 18: 1110
};
var d: hm.huffman_decoder_t = undefined;
var used: usize = 0;
try expect(hm.huffman_decoder_init(&d, &lens, lens.len));
// 000 (msb-first) -> 000 (lsb-first)
try expect((try hm.huffman_decode(&d, 0x0, &used)) == 0);
try expect(used == 3);
// 011 (msb-first) -> 110 (lsb-first)
try expect((try hm.huffman_decode(&d, 0x6, &used)) == 3);
try expect(used == 3);
// 11110 (msb-first) -> 01111 (lsb-first)
try expect((try hm.huffman_decode(&d, 0x0f, &used)) == 17);
try expect(used == 5);
// 111110 (msb-first) -> 011111 (lsb-first)
try expect((try hm.huffman_decode(&d, 0x1f, &used)) == 16);
try expect(used == 6);
// 1111111 (msb-first) -> 1111111 (lsb-first)
try expectError(hm.Error.FailedToDecode, hm.huffman_decode(&d, 0x7f, &used));
// Make sure used is set even when decoding fails.
try expect(used == 0);
}
test "huffman_decode_canonical" {
// Long enough codewords to not just hit the lookup table.
const lens = [_]u8{
3, // sym 0: 0000 (0x0)
3, // sym 1: 0001 (0x1)
3, // sym 2: 0010 (0x2)
15, // sym 3: 0011 0000 0000 0000 (0x3000)
15, // sym 4: 0011 0000 0000 0001 (0x3001)
15, // sym 5: 0011 0000 0000 0010 (0x3002)
};
var d: hm.huffman_decoder_t = undefined;
var used: usize = 0;
try expect(hm.huffman_decoder_init(&d, &lens, lens.len));
try expect((try hm.huffman_decode(&d, bu.reverse16(0x0, 3), &used)) == 0);
try expect(used == 3);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x1, 3), &used)) == 1);
try expect(used == 3);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x2, 3), &used)) == 2);
try expect(used == 3);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x3000, 15), &used)) == 3);
try expect(used == 15);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x3001, 15), &used)) == 4);
try expect(used == 15);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x3002, 15), &used)) == 5);
try expect(used == 15);
try expect((try hm.huffman_decode(&d, bu.reverse16(0x3000, 15), &used)) == 3);
try expect(used == 15);
}
test "huffman_decode_evil" {
// More length-4 symbols than are possible.
const lens = [53]u8{
1, 2, 3, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4,
};
var d: hm.huffman_decoder_t = undefined;
try expect(!hm.huffman_decoder_init(&d, &lens, lens.len));
}
// Check that codewords up to MAX_HUFFMAN_BITS can be decoded.
test "huffman_decode_max_bits" {
const lens = [_]u8{
1, // sym 0: 0
2, // sym 1: 10
3, // sym 2: 110
4, // sym 3: 1110
5, // sym 4: 1111 0
6, // sym 5: 1111 10
7, // sym 6: 1111 110
8, // sym 7: ...
9,
10,
11,
12,
13,
14,
15,
16, // sym 15: 1111 1111 1111 1110
16, // sym 16: 1111 1111 1111 1111
};
var d: hm.huffman_decoder_t = undefined;
var used: usize = 0;
try expect(hm.huffman_decoder_init(&d, &lens, lens.len));
// 10 (msb-first) -> 01 (lsb-first)
try expect((try hm.huffman_decode(&d, 0x1, &used)) == 1);
try expect(used == 2);
try expect((try hm.huffman_decode(&d, 0xffff, &used)) == 16);
try expect(used == hm.MAX_HUFFMAN_BITS);
}
test "huffman_decode_empty" {
var d: hm.huffman_decoder_t = undefined;
var used: usize = 0;
var dummy: []const u8 = undefined;
try expect(hm.huffman_decoder_init(&d, dummy.ptr, 0));
// Hit the lookup table.
try expectError(hm.Error.FailedToDecode, hm.huffman_decode(&d, 0x0, &used));
// Hit the canonical decoder.
try expectError(hm.Error.FailedToDecode, hm.huffman_decode(&d, 0xffff, &used));
}
test "huffman_encoder_init" {
const freqs = [_]u16{
8, // 0
1, // 1
1, // 2
2, // 3
5, // 4
10, // 5
9, // 6
1, // 7
0, // 8
0, // 9
0, // 10
0, // 11
0, // 12
0, // 13
0, // 14
0, // 15
1, // 16
3, // 17
5, // 18
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 6);
// Test expectations from running Huffman with pen and paper.
try expect(e.lengths[0] == 3);
try expect(e.lengths[1] == 6);
try expect(e.lengths[2] == 6);
try expect(e.lengths[3] == 5);
try expect(e.lengths[4] == 3);
try expect(e.lengths[5] == 2);
try expect(e.lengths[6] == 2);
try expect(e.lengths[7] == 6);
try expect(e.lengths[8] == 0);
try expect(e.lengths[9] == 0);
try expect(e.lengths[10] == 0);
try expect(e.lengths[11] == 0);
try expect(e.lengths[12] == 0);
try expect(e.lengths[13] == 0);
try expect(e.lengths[14] == 0);
try expect(e.lengths[15] == 0);
try expect(e.lengths[16] == 6);
try expect(e.lengths[17] == 5);
try expect(e.lengths[18] == 3);
try expect(e.codewords[5] == 0x0);
try expect(e.codewords[6] == 0x2);
try expect(e.codewords[0] == 0x1);
try expect(e.codewords[4] == 0x5);
try expect(e.codewords[18] == 0x3);
try expect(e.codewords[3] == 0x7);
try expect(e.codewords[17] == 0x17);
try expect(e.codewords[1] == 0x0f);
try expect(e.codewords[2] == 0x2f);
try expect(e.codewords[7] == 0x1f);
try expect(e.codewords[16] == 0x3f);
}
test "huffman_lengths_one" {
const freqs = [_]u16{
0, // 0
0, // 1
0, // 2
4, // 3
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 6);
try expect(e.lengths[0] == 0);
try expect(e.lengths[1] == 0);
try expect(e.lengths[2] == 0);
try expect(e.lengths[3] == 1);
}
test "huffman_lengths_two" {
const freqs = [_]u16{
1, // 0
0, // 1
0, // 2
4, // 3
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 6);
try expect(e.lengths[0] == 1);
try expect(e.lengths[1] == 0);
try expect(e.lengths[2] == 0);
try expect(e.lengths[3] == 1);
}
test "huffman_lengths_none" {
const freqs = [_]u16{
0, // 0
0, // 1
0, // 2
0, // 3
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 6);
try expect(e.lengths[0] == 0);
try expect(e.lengths[1] == 0);
try expect(e.lengths[2] == 0);
try expect(e.lengths[3] == 0);
}
test "huffman_lengths_limited" {
const freqs = [_]u16{
1, // 0
2, // 1
4, // 2
8, // 3
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 2);
try expect(e.lengths[0] == 2);
try expect(e.lengths[1] == 2);
try expect(e.lengths[2] == 2);
try expect(e.lengths[3] == 2);
}
test "huffman_lengths_max_freq" {
const freqs = [_]u16{
16383, // 0
16384, // 1
16384, // 2
16384, // 3
};
var e: hm.huffman_encoder_t = undefined;
assert(freqs[0] + freqs[1] + freqs[2] + freqs[3] == math.maxInt(u16));
hm.huffman_encoder_init(&e, &freqs, freqs.len, 10);
try expect(e.lengths[0] == 2);
try expect(e.lengths[1] == 2);
try expect(e.lengths[2] == 2);
try expect(e.lengths[3] == 2);
}
test "huffman_lengths_max_syms" {
var freqs: [hm.MAX_HUFFMAN_SYMBOLS]u16 = undefined;
var e: hm.huffman_encoder_t = undefined;
var i: usize = 0;
i = 0;
while (i < freqs.len) : (i += 1) {
freqs[i] = 1;
}
hm.huffman_encoder_init(&e, &freqs, freqs.len, 15);
i = 0;
while (i < hm.MAX_HUFFMAN_SYMBOLS) : (i += 1) {
try expect((e.lengths[i] == 8) or (e.lengths[i] == 9));
}
}
test "huffman_encoder_init2" {
var lens: [288]u8 = undefined;
var i: usize = 0;
var e: hm.huffman_encoder_t = undefined;
// Code lengths used for fixed Huffman code deflate blocks.
i = 0;
while (i <= 143) : (i += 1) {
lens[i] = 8;
}
while (i <= 255) : (i += 1) {
lens[i] = 9;
}
while (i <= 279) : (i += 1) {
lens[i] = 7;
}
while (i <= 287) : (i += 1) {
lens[i] = 8;
}
hm.huffman_encoder_init2(&e, &lens, lens.len);
try expect(e.codewords[255] == 0x1ff);
}
// Check that codewords up to MAX_HUFFMAN_BITS are generated.
test "huffman_encoder_max_bits" {
const freqs = [_]u16{
1, // 0
1, // 1
2, // 2
3, // 3
5, // 4
8, // 5
13, // 6
21, // 7
34, // 8
55, // 9
89, // 10
144, // 11
233, // 12
377, // 13
610, // 14
987, // 15
1597, // 16
};
var e: hm.huffman_encoder_t = undefined;
hm.huffman_encoder_init(&e, &freqs, freqs.len, 16);
try expect(e.lengths[0] == 16);
try expect(e.lengths[1] == 16);
try expect(e.lengths[16] == 1);
try expect(e.codewords[0] == 0x7fff);
try expect(e.codewords[1] == 0xffff);
try expect(e.codewords[16] == 0x0);
}
|
src/huffman_test.zig
|
const std = @import("std");
const Builder = std.build.Builder;
pub fn build(b: *Builder) void {
const build_mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
var exe = b.addExecutable("buzz", "src/main.zig");
exe.setTarget(target);
exe.install();
exe.setBuildMode(build_mode);
exe.setMainPkgPath(".");
var lib = b.addSharedLibrary("buzz", "src/buzz_api.zig", .{ .unversioned = {} });
lib.setTarget(target);
lib.install();
lib.setMainPkgPath(".");
lib.setBuildMode(build_mode);
var std_lib = b.addSharedLibrary("std", "lib/buzz_std.zig", .{ .unversioned = {} });
std_lib.setTarget(target);
std_lib.install();
std_lib.setMainPkgPath(".");
std_lib.setBuildMode(build_mode);
std_lib.linkLibrary(lib);
var io_lib = b.addSharedLibrary("io", "lib/buzz_io.zig", .{ .unversioned = {} });
io_lib.setTarget(target);
io_lib.install();
io_lib.setMainPkgPath(".");
io_lib.setBuildMode(build_mode);
io_lib.linkLibrary(lib);
var gc_lib = b.addSharedLibrary("gc", "lib/buzz_gc.zig", .{ .unversioned = {} });
gc_lib.setTarget(target);
gc_lib.install();
gc_lib.setMainPkgPath(".");
gc_lib.setBuildMode(build_mode);
gc_lib.linkLibrary(lib);
var os_lib = b.addSharedLibrary("os", "lib/buzz_os.zig", .{ .unversioned = {} });
os_lib.setTarget(target);
os_lib.install();
os_lib.setMainPkgPath(".");
os_lib.setBuildMode(build_mode);
os_lib.linkLibrary(lib);
var fs_lib = b.addSharedLibrary("fs", "lib/buzz_fs.zig", .{ .unversioned = {} });
fs_lib.setTarget(target);
fs_lib.install();
fs_lib.setMainPkgPath(".");
fs_lib.setBuildMode(build_mode);
fs_lib.linkLibrary(lib);
var math_lib = b.addSharedLibrary("math", "lib/buzz_math.zig", .{ .unversioned = {} });
math_lib.setTarget(target);
math_lib.install();
math_lib.setMainPkgPath(".");
math_lib.setBuildMode(build_mode);
math_lib.linkLibrary(lib);
b.default_step.dependOn(&exe.step);
b.default_step.dependOn(&lib.step);
b.default_step.dependOn(&std_lib.step);
b.default_step.dependOn(&io_lib.step);
b.default_step.dependOn(&gc_lib.step);
b.default_step.dependOn(&os_lib.step);
b.default_step.dependOn(&fs_lib.step);
b.default_step.dependOn(&math_lib.step);
const play = b.step("run", "Run buzz");
const run = exe.run();
run.step.dependOn(b.getInstallStep());
play.dependOn(&run.step);
}
|
build.zig
|
const std = @import("std");
const is_windows = @import("builtin").os.tag == .windows;
pub const Color = enum {
reset,
red,
green,
blue,
cyan,
purple,
yellow,
white,
};
pub fn setColor(color: Color, w: anytype) void {
if (is_windows) {
const stderr_file = std.io.getStdErr();
if (!stderr_file.isTty()) return;
const windows = std.os.windows;
const S = struct {
var attrs: windows.WORD = undefined;
var init_attrs = false;
};
if (!S.init_attrs) {
S.init_attrs = true;
var info: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined;
_ = windows.kernel32.GetConsoleScreenBufferInfo(stderr_file.handle, &info);
S.attrs = info.wAttributes;
_ = windows.kernel32.SetConsoleOutputCP(65001);
}
// need to flush bufferedWriter
const T = if (@typeInfo(@TypeOf(w.context)) == .Pointer) @TypeOf(w.context.*) else @TypeOf(w.context);
if (T != void and @hasDecl(T, "flush")) w.context.flush() catch {};
switch (color) {
.reset => _ = windows.SetConsoleTextAttribute(stderr_file.handle, S.attrs) catch {},
.red => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_INTENSITY) catch {},
.green => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_GREEN | windows.FOREGROUND_INTENSITY) catch {},
.blue => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {},
.cyan => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_GREEN | windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {},
.purple => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {},
.yellow => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_GREEN | windows.FOREGROUND_INTENSITY) catch {},
.white => _ = windows.SetConsoleTextAttribute(stderr_file.handle, windows.FOREGROUND_RED | windows.FOREGROUND_GREEN | windows.FOREGROUND_BLUE | windows.FOREGROUND_INTENSITY) catch {},
}
} else switch (color) {
.reset => w.writeAll("\x1b[0m") catch {},
.red => w.writeAll("\x1b[31;1m") catch {},
.green => w.writeAll("\x1b[32;1m") catch {},
.blue => w.writeAll("\x1b[34;1m") catch {},
.cyan => w.writeAll("\x1b[36;1m") catch {},
.purple => w.writeAll("\x1b[35;1m") catch {},
.yellow => w.writeAll("\x1b[93;1m") catch {},
.white => w.writeAll("\x1b[0m\x1b[1m") catch {},
}
}
|
src/util.zig
|
const std = @import("std");
const stdx = @import("stdx");
const Function = stdx.Function;
const graphics = @import("graphics");
const Color = graphics.Color;
const platform = @import("platform");
const MouseUpEvent = platform.MouseUpEvent;
const MouseDownEvent = platform.MouseDownEvent;
const MouseMoveEvent = platform.MouseMoveEvent;
const log = stdx.log.scoped(.slider);
const ui = @import("../ui.zig");
const Node = ui.Node;
pub const Slider = struct {
props: struct {
init_val: i32 = 0,
min_val: i32 = 0,
max_val: i32 = 100,
onChangeEnd: ?Function(fn (i32) void) = null,
onChange: ?Function(fn (i32) void) = null,
thumb_color: Color = Color.Blue,
},
drag_start_value: i32,
last_value: i32,
value: i32,
pressed: bool,
node: *ui.Node,
const Self = @This();
const ThumbWidth = 25;
const Height = 25;
pub fn init(self: *Self, c: *ui.InitContext) void {
std.debug.assert(self.props.min_val <= self.props.max_val);
self.node = c.node;
self.value = self.props.init_val;
self.pressed = false;
if (self.value < self.props.min_val) {
self.value = self.props.min_val;
} else if (self.value > self.props.max_val) {
self.value = self.props.max_val;
}
c.addMouseDownHandler(c.node, handleMouseDownEvent);
}
fn handleMouseUpEvent(node: *Node, e: ui.Event(MouseUpEvent)) void {
var self = node.getWidget(Self);
if (e.val.button == .Left and self.pressed) {
self.pressed = false;
e.ctx.removeMouseUpHandler(*Node, handleMouseUpEvent);
e.ctx.removeMouseMoveHandler(*Node, handleMouseMoveEvent);
self.updateValueFromMouseX(node, e.val.x);
if (self.drag_start_value != self.value) {
if (self.props.onChange) |cb| {
cb.call(.{ self.value });
}
if (self.props.onChangeEnd) |cb| {
cb.call(.{ self.value });
}
}
}
}
fn handleMouseDownEvent(node: *Node, e: ui.Event(MouseDownEvent)) ui.EventResult {
var self = node.getWidget(Self);
if (e.val.button == .Left) {
self.pressed = true;
self.last_value = self.value;
self.drag_start_value = self.value;
e.ctx.removeMouseUpHandler(*Node, handleMouseUpEvent);
e.ctx.addGlobalMouseUpHandler(node, handleMouseUpEvent);
e.ctx.addMouseMoveHandler(node, handleMouseMoveEvent);
}
return .Continue;
}
fn updateValueFromMouseX(self: *Self, node: *Node, mouse_x: i16) void {
const num_values = self.props.max_val - self.props.min_val + 1;
const rel_x = @intToFloat(f32, mouse_x) - node.abs_pos.x - @intToFloat(f32, ThumbWidth)/2;
const ratio = rel_x / (node.layout.width - ThumbWidth);
self.value = @floatToInt(i32, @intToFloat(f32, self.props.min_val) + ratio * @intToFloat(f32, num_values));
if (self.value > self.props.max_val) {
self.value = self.props.max_val;
} else if (self.value < self.props.min_val) {
self.value = self.props.min_val;
}
}
fn handleMouseMoveEvent(node: *Node, e: ui.Event(MouseMoveEvent)) void {
var self = node.getWidget(Self);
self.updateValueFromMouseX(node, e.val.x);
if (self.last_value != self.value) {
if (self.props.onChange) |cb| {
cb.call(.{ self.value });
}
}
self.last_value = self.value;
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
_ = self;
_ = c;
return ui.NullFrameId;
}
pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize {
_ = self;
const min_width: f32 = 200;
const min_height = Height;
const cstr = c.getSizeConstraint();
var res = ui.LayoutSize.init(min_width, min_height);
if (c.prefer_exact_width) {
res.width = cstr.width;
}
return res;
}
pub fn getBarLayout(self: Self) ui.Layout {
return ui.Layout.init(ThumbWidth/2, self.node.layout.height/2 - 5, self.node.layout.width - ThumbWidth, 10);
}
pub fn getThumbLayoutX(self: Self) f32 {
const val_range = self.props.max_val - self.props.min_val;
const ratio = @intToFloat(f32, self.value - self.props.min_val) / @intToFloat(f32, val_range);
return (self.node.layout.width - ThumbWidth) * ratio + ThumbWidth/2;
}
pub fn render(self: *Self, ctx: *ui.RenderContext) void {
const g = ctx.g;
const alo = ctx.getAbsLayout();
g.setFillColor(Color.LightGray);
g.fillRect(alo.x + ThumbWidth/2, alo.y+alo.height/2 - 5, alo.width - ThumbWidth, 10);
const val_range = self.props.max_val - self.props.min_val;
const ratio = @intToFloat(f32, self.value - self.props.min_val) / @intToFloat(f32, val_range);
const thumb_x = alo.x + (alo.width - ThumbWidth) * ratio;
g.setFillColor(self.props.thumb_color);
g.fillRect(thumb_x, alo.y, ThumbWidth, Height);
}
};
|
ui/src/widgets/slider.zig
|
const expect = @import("std").testing.expect;
const builtin = @import("builtin");
var foo: u8 align(4) = 100;
test "global variable alignment" {
expect(@typeOf(&foo).alignment == 4);
expect(@typeOf(&foo) == *align(4) u8);
const slice = (*[1]u8)(&foo)[0..];
expect(@typeOf(slice) == []align(4) u8);
}
fn derp() align(@sizeOf(usize) * 2) i32 {
return 1234;
}
fn noop1() align(1) void {}
fn noop4() align(4) void {}
test "function alignment" {
expect(derp() == 1234);
expect(@typeOf(noop1) == fn () align(1) void);
expect(@typeOf(noop4) == fn () align(4) void);
noop1();
noop4();
}
var baz: packed struct {
a: u32,
b: u32,
} = undefined;
test "packed struct alignment" {
expect(@typeOf(&baz.b) == *align(1) u32);
}
const blah: packed struct {
a: u3,
b: u3,
c: u2,
} = undefined;
test "bit field alignment" {
expect(@typeOf(&blah.b) == *align(1:3:1) const u3);
}
test "default alignment allows unspecified in type syntax" {
expect(*u32 == *align(@alignOf(u32)) u32);
}
test "implicitly decreasing pointer alignment" {
const a: u32 align(4) = 3;
const b: u32 align(8) = 4;
expect(addUnaligned(&a, &b) == 7);
}
fn addUnaligned(a: *align(1) const u32, b: *align(1) const u32) u32 {
return a.* + b.*;
}
test "implicitly decreasing slice alignment" {
const a: u32 align(4) = 3;
const b: u32 align(8) = 4;
expect(addUnalignedSlice((*const [1]u32)(&a)[0..], (*const [1]u32)(&b)[0..]) == 7);
}
fn addUnalignedSlice(a: []align(1) const u32, b: []align(1) const u32) u32 {
return a[0] + b[0];
}
test "specifying alignment allows pointer cast" {
testBytesAlign(0x33);
}
fn testBytesAlign(b: u8) void {
var bytes align(4) = [_]u8{
b,
b,
b,
b,
};
const ptr = @ptrCast(*u32, &bytes[0]);
expect(ptr.* == 0x33333333);
}
test "specifying alignment allows slice cast" {
testBytesAlignSlice(0x33);
}
fn testBytesAlignSlice(b: u8) void {
var bytes align(4) = [_]u8{
b,
b,
b,
b,
};
const slice: []u32 = @bytesToSlice(u32, bytes[0..]);
expect(slice[0] == 0x33333333);
}
test "@alignCast pointers" {
var x: u32 align(4) = 1;
expectsOnly1(&x);
expect(x == 2);
}
fn expectsOnly1(x: *align(1) u32) void {
expects4(@alignCast(4, x));
}
fn expects4(x: *align(4) u32) void {
x.* += 1;
}
test "@alignCast slices" {
var array align(4) = [_]u32{
1,
1,
};
const slice = array[0..];
sliceExpectsOnly1(slice);
expect(slice[0] == 2);
}
fn sliceExpectsOnly1(slice: []align(1) u32) void {
sliceExpects4(@alignCast(4, slice));
}
fn sliceExpects4(slice: []align(4) u32) void {
slice[0] += 1;
}
test "implicitly decreasing fn alignment" {
testImplicitlyDecreaseFnAlign(alignedSmall, 1234);
testImplicitlyDecreaseFnAlign(alignedBig, 5678);
}
fn testImplicitlyDecreaseFnAlign(ptr: fn () align(1) i32, answer: i32) void {
expect(ptr() == answer);
}
fn alignedSmall() align(8) i32 {
return 1234;
}
fn alignedBig() align(16) i32 {
return 5678;
}
test "@alignCast functions" {
expect(fnExpectsOnly1(simple4) == 0x19);
}
fn fnExpectsOnly1(ptr: fn () align(1) i32) i32 {
return fnExpects4(@alignCast(4, ptr));
}
fn fnExpects4(ptr: fn () align(4) i32) i32 {
return ptr();
}
fn simple4() align(4) i32 {
return 0x19;
}
test "generic function with align param" {
expect(whyWouldYouEverDoThis(1) == 0x1);
expect(whyWouldYouEverDoThis(4) == 0x1);
expect(whyWouldYouEverDoThis(8) == 0x1);
}
fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 {
return 0x1;
}
test "@ptrCast preserves alignment of bigger source" {
var x: u32 align(16) = 1234;
const ptr = @ptrCast(*u8, &x);
expect(@typeOf(ptr) == *align(16) u8);
}
test "runtime known array index has best alignment possible" {
// take full advantage of over-alignment
var array align(4) = [_]u8{ 1, 2, 3, 4 };
expect(@typeOf(&array[0]) == *align(4) u8);
expect(@typeOf(&array[1]) == *u8);
expect(@typeOf(&array[2]) == *align(2) u8);
expect(@typeOf(&array[3]) == *u8);
// because align is too small but we still figure out to use 2
var bigger align(2) = [_]u64{ 1, 2, 3, 4 };
expect(@typeOf(&bigger[0]) == *align(2) u64);
expect(@typeOf(&bigger[1]) == *align(2) u64);
expect(@typeOf(&bigger[2]) == *align(2) u64);
expect(@typeOf(&bigger[3]) == *align(2) u64);
// because pointer is align 2 and u32 align % 2 == 0 we can assume align 2
var smaller align(2) = [_]u32{ 1, 2, 3, 4 };
comptime expect(@typeOf(smaller[0..]) == []align(2) u32);
comptime expect(@typeOf(smaller[0..].ptr) == [*]align(2) u32);
testIndex(smaller[0..].ptr, 0, *align(2) u32);
testIndex(smaller[0..].ptr, 1, *align(2) u32);
testIndex(smaller[0..].ptr, 2, *align(2) u32);
testIndex(smaller[0..].ptr, 3, *align(2) u32);
// has to use ABI alignment because index known at runtime only
testIndex2(array[0..].ptr, 0, *u8);
testIndex2(array[0..].ptr, 1, *u8);
testIndex2(array[0..].ptr, 2, *u8);
testIndex2(array[0..].ptr, 3, *u8);
}
fn testIndex(smaller: [*]align(2) u32, index: usize, comptime T: type) void {
comptime expect(@typeOf(&smaller[index]) == T);
}
fn testIndex2(ptr: [*]align(4) u8, index: usize, comptime T: type) void {
comptime expect(@typeOf(&ptr[index]) == T);
}
test "alignstack" {
expect(fnWithAlignedStack() == 1234);
}
fn fnWithAlignedStack() i32 {
@setAlignStack(256);
return 1234;
}
test "alignment of structs" {
expect(@alignOf(struct {
a: i32,
b: *i32,
}) == @alignOf(usize));
}
test "alignment of extern() void" {
var runtime_nothing = nothing;
const casted1 = @ptrCast(*const u8, runtime_nothing);
const casted2 = @ptrCast(extern fn () void, casted1);
casted2();
}
extern fn nothing() void {}
test "return error union with 128-bit integer" {
expect(3 == try give());
}
fn give() anyerror!u128 {
return 3;
}
test "alignment of >= 128-bit integer type" {
expect(@alignOf(u128) == 16);
expect(@alignOf(u129) == 16);
}
test "alignment of struct with 128-bit field" {
expect(@alignOf(struct {
x: u128,
}) == 16);
comptime {
expect(@alignOf(struct {
x: u128,
}) == 16);
}
}
test "size of extern struct with 128-bit field" {
expect(@sizeOf(extern struct {
x: u128,
y: u8,
}) == 32);
comptime {
expect(@sizeOf(extern struct {
x: u128,
y: u8,
}) == 32);
}
}
const DefaultAligned = struct {
nevermind: u32,
badguy: i128,
};
test "read 128-bit field from default aligned struct in stack memory" {
var default_aligned = DefaultAligned{
.nevermind = 1,
.badguy = 12,
};
expect((@ptrToInt(&default_aligned.badguy) % 16) == 0);
expect(12 == default_aligned.badguy);
}
var default_aligned_global = DefaultAligned{
.nevermind = 1,
.badguy = 12,
};
test "read 128-bit field from default aligned struct in global memory" {
expect((@ptrToInt(&default_aligned_global.badguy) % 16) == 0);
expect(12 == default_aligned_global.badguy);
}
test "struct field explicit alignment" {
const S = struct {
const Node = struct {
next: *Node,
massive_byte: u8 align(64),
};
};
var node: S.Node = undefined;
node.massive_byte = 100;
expect(node.massive_byte == 100);
comptime expect(@typeOf(&node.massive_byte) == *align(64) u8);
expect(@ptrToInt(&node.massive_byte) % 64 == 0);
}
|
test/stage1/behavior/align.zig
|
const std = @import("../index.zig");
const builtin = @import("builtin");
const Endian = builtin.Endian;
const readIntSliceLittle = std.mem.readIntSliceLittle;
const writeIntSliceLittle = std.mem.writeIntSliceLittle;
pub const Poly1305 = struct {
const Self = @This();
pub const mac_length = 16;
pub const minimum_key_length = 32;
// constant multiplier (from the secret key)
r: [4]u32,
// accumulated hash
h: [5]u32,
// chunk of the message
c: [5]u32,
// random number added at the end (from the secret key)
pad: [4]u32,
// How many bytes are there in the chunk.
c_idx: usize,
fn secureZero(self: *Self) void {
std.mem.secureZero(u8, @ptrCast([*]u8, self)[0..@sizeOf(Poly1305)]);
}
pub fn create(out: []u8, msg: []const u8, key: []const u8) void {
std.debug.assert(out.len >= mac_length);
std.debug.assert(key.len >= minimum_key_length);
var ctx = Poly1305.init(key);
ctx.update(msg);
ctx.final(out);
}
// Initialize the MAC context.
// - key.len is sufficient size.
pub fn init(key: []const u8) Self {
var ctx: Poly1305 = undefined;
// Initial hash is zero
{
var i: usize = 0;
while (i < 5) : (i += 1) {
ctx.h[i] = 0;
}
}
// add 2^130 to every input block
ctx.c[4] = 1;
polyClearC(&ctx);
// load r and pad (r has some of its bits cleared)
{
var i: usize = 0;
while (i < 1) : (i += 1) {
ctx.r[0] = readIntSliceLittle(u32, key[0..4]) & 0x0fffffff;
}
}
{
var i: usize = 1;
while (i < 4) : (i += 1) {
ctx.r[i] = readIntSliceLittle(u32, key[i * 4 .. i * 4 + 4]) & 0x0ffffffc;
}
}
{
var i: usize = 0;
while (i < 4) : (i += 1) {
ctx.pad[i] = readIntSliceLittle(u32, key[i * 4 + 16 .. i * 4 + 16 + 4]);
}
}
return ctx;
}
// h = (h + c) * r
// preconditions:
// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff
// ctx->c <= 1_ffffffff_ffffffff_ffffffff_ffffffff
// ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff
// Postcondition:
// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff
fn polyBlock(ctx: *Self) void {
// s = h + c, without carry propagation
const s0 = u64(ctx.h[0]) + ctx.c[0]; // s0 <= 1_fffffffe
const s1 = u64(ctx.h[1]) + ctx.c[1]; // s1 <= 1_fffffffe
const s2 = u64(ctx.h[2]) + ctx.c[2]; // s2 <= 1_fffffffe
const s3 = u64(ctx.h[3]) + ctx.c[3]; // s3 <= 1_fffffffe
const s4 = u64(ctx.h[4]) + ctx.c[4]; // s4 <= 5
// Local all the things!
const r0 = ctx.r[0]; // r0 <= 0fffffff
const r1 = ctx.r[1]; // r1 <= 0ffffffc
const r2 = ctx.r[2]; // r2 <= 0ffffffc
const r3 = ctx.r[3]; // r3 <= 0ffffffc
const rr0 = (r0 >> 2) * 5; // rr0 <= 13fffffb // lose 2 bits...
const rr1 = (r1 >> 2) + r1; // rr1 <= 13fffffb // rr1 == (r1 >> 2) * 5
const rr2 = (r2 >> 2) + r2; // rr2 <= 13fffffb // rr1 == (r2 >> 2) * 5
const rr3 = (r3 >> 2) + r3; // rr3 <= 13fffffb // rr1 == (r3 >> 2) * 5
// (h + c) * r, without carry propagation
const x0 = s0 * r0 + s1 * rr3 + s2 * rr2 + s3 * rr1 + s4 * rr0; //<=97ffffe007fffff8
const x1 = s0 * r1 + s1 * r0 + s2 * rr3 + s3 * rr2 + s4 * rr1; //<=8fffffe20ffffff6
const x2 = s0 * r2 + s1 * r1 + s2 * r0 + s3 * rr3 + s4 * rr2; //<=87ffffe417fffff4
const x3 = s0 * r3 + s1 * r2 + s2 * r1 + s3 * r0 + s4 * rr3; //<=7fffffe61ffffff2
const x4 = s4 * (r0 & 3); // ...recover 2 bits //<= f
// partial reduction modulo 2^130 - 5
const _u5 = @truncate(u32, x4 + (x3 >> 32)); // u5 <= 7ffffff5
const _u0 = (_u5 >> 2) * 5 + (x0 & 0xffffffff);
const _u1 = (_u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32);
const _u2 = (_u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32);
const _u3 = (_u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32);
const _u4 = (_u3 >> 32) + (_u5 & 3);
// Update the hash
ctx.h[0] = @truncate(u32, _u0); // u0 <= 1_9ffffff0
ctx.h[1] = @truncate(u32, _u1); // u1 <= 1_97ffffe0
ctx.h[2] = @truncate(u32, _u2); // u2 <= 1_8fffffe2
ctx.h[3] = @truncate(u32, _u3); // u3 <= 1_87ffffe4
ctx.h[4] = @truncate(u32, _u4); // u4 <= 4
}
// (re-)initializes the input counter and input buffer
fn polyClearC(ctx: *Self) void {
ctx.c[0] = 0;
ctx.c[1] = 0;
ctx.c[2] = 0;
ctx.c[3] = 0;
ctx.c_idx = 0;
}
fn polyTakeInput(ctx: *Self, input: u8) void {
const word = ctx.c_idx >> 2;
const byte = ctx.c_idx & 3;
ctx.c[word] |= std.math.shl(u32, input, byte * 8);
ctx.c_idx += 1;
}
fn polyUpdate(ctx: *Self, msg: []const u8) void {
for (msg) |b| {
polyTakeInput(ctx, b);
if (ctx.c_idx == 16) {
polyBlock(ctx);
polyClearC(ctx);
}
}
}
fn alignTo(x: usize, block_size: usize) usize {
return ((~x) +% 1) & (block_size - 1);
}
// Feed data into the MAC context.
pub fn update(ctx: *Self, msg: []const u8) void {
// Align ourselves with block boundaries
const alignm = std.math.min(alignTo(ctx.c_idx, 16), msg.len);
polyUpdate(ctx, msg[0..alignm]);
var nmsg = msg[alignm..];
// Process the msg block by block
const nb_blocks = nmsg.len >> 4;
var i: usize = 0;
while (i < nb_blocks) : (i += 1) {
ctx.c[0] = readIntSliceLittle(u32, nmsg[0..4]);
ctx.c[1] = readIntSliceLittle(u32, nmsg[4..8]);
ctx.c[2] = readIntSliceLittle(u32, nmsg[8..12]);
ctx.c[3] = readIntSliceLittle(u32, nmsg[12..16]);
polyBlock(ctx);
nmsg = nmsg[16..];
}
if (nb_blocks > 0) {
polyClearC(ctx);
}
// remaining bytes
polyUpdate(ctx, nmsg[0..]);
}
// Finalize the MAC and output into buffer provided by caller.
pub fn final(ctx: *Self, out: []u8) void {
// Process the last block (if any)
if (ctx.c_idx != 0) {
// move the final 1 according to remaining input length
// (We may add less than 2^130 to the last input block)
ctx.c[4] = 0;
polyTakeInput(ctx, 1);
// one last hash update
polyBlock(ctx);
}
// check if we should subtract 2^130-5 by performing the
// corresponding carry propagation.
const _u0 = u64(5) + ctx.h[0]; // <= 1_00000004
const _u1 = (_u0 >> 32) + ctx.h[1]; // <= 1_00000000
const _u2 = (_u1 >> 32) + ctx.h[2]; // <= 1_00000000
const _u3 = (_u2 >> 32) + ctx.h[3]; // <= 1_00000000
const _u4 = (_u3 >> 32) + ctx.h[4]; // <= 5
// u4 indicates how many times we should subtract 2^130-5 (0 or 1)
// h + pad, minus 2^130-5 if u4 exceeds 3
const uu0 = (_u4 >> 2) * 5 + ctx.h[0] + ctx.pad[0]; // <= 2_00000003
const uu1 = (uu0 >> 32) + ctx.h[1] + ctx.pad[1]; // <= 2_00000000
const uu2 = (uu1 >> 32) + ctx.h[2] + ctx.pad[2]; // <= 2_00000000
const uu3 = (uu2 >> 32) + ctx.h[3] + ctx.pad[3]; // <= 2_00000000
// TODO https://github.com/ziglang/zig/issues/863
writeIntSliceLittle(u32, out[0..], @truncate(u32, uu0));
writeIntSliceLittle(u32, out[4..], @truncate(u32, uu1));
writeIntSliceLittle(u32, out[8..], @truncate(u32, uu2));
writeIntSliceLittle(u32, out[12..], @truncate(u32, uu3));
ctx.secureZero();
}
};
test "poly1305 rfc7439 vector1" {
const expected_mac = "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9";
const msg = "Cryptographic Forum Research Group";
const key = <KEY>" ++
<KEY>";
var mac: [16]u8 = undefined;
Poly1305.create(mac[0..], msg, key);
std.debug.assert(std.mem.eql(u8, mac, expected_mac));
}
|
std/crypto/poly1305.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const debug = @import("./debug.zig");
const Chunk = @import("./chunk.zig").Chunk;
const OpCode = @import("./chunk.zig").OpCode;
const Value = @import("./value.zig").Value;
const debug_trace_execution = true;
const debug_stack_execution = false;
const stack_max = 256;
pub const InterpretError = error {
CompileError,
RuntimeError,
};
pub const Vm = struct {
const Self = @This();
chunk: *Chunk,
ip: usize,
stack: [stack_max]Value,
stack_top: usize,
allocator: *Allocator,
pub fn init(allocator: *Allocator) Self {
return Self {
.ip = 0,
.stack_top = 0,
.stack = undefined,
.chunk = undefined,
.allocator = allocator
};
}
pub fn interpret(self: *Self, chunk: *Chunk) InterpretError!void {
self.chunk = chunk;
try self.run();
}
pub fn run(self: *Self) InterpretError!void {
while(true) {
if (comptime debug_stack_execution) { debug.printStack(self.stack[0..self.stack_top]); }
if (comptime debug_trace_execution) { debug.disassembleInstruction(self.chunk, self.ip); }
const instruction = self.readInstruction();
switch(instruction) {
.op_constant => { self.push(self.readConstant()); },
.op_negate => { self.push(-self.pop()); },
.op_add => { self.push(self.pop() + self.pop()); },
.op_subtract => { self.push(self.pop() - self.pop()); },
.op_multiply => { self.push(self.pop() * self.pop()); },
.op_divide => { self.push(self.pop() / self.pop()); },
.op_return => {
debug.printValue(self.pop());
std.debug.print("\n", .{});
return;
},
}
}
}
pub fn resetStack(self: *Self) void {
self.stack_top = 0;
}
pub fn push(self: *Self, value: Value) void {
self.stack[self.stack_top] = value;
self.stack_top += 1;
}
pub fn pop(self: *Self) Value {
self.stack_top -= 1;
return self.stack[self.stack_top];
}
inline fn readInstruction(self: *Self) OpCode {
const instruction = OpCode.fromU8(self.chunk.code.items[self.ip]);
self.ip += 1;
return instruction;
}
inline fn readConstant(self: *Self) Value {
const constant = self.chunk.constants.items[self.chunk.code.items[self.ip]];
self.ip += 1;
return constant;
}
};
|
src/vm.zig
|
mod: *Module,
/// Alias to `mod.gpa`.
gpa: *Allocator,
/// Points to the arena allocator of the Decl.
arena: *Allocator,
code: Zir,
/// Maps ZIR to AIR.
inst_map: InstMap = .{},
/// When analyzing an inline function call, owner_decl is the Decl of the caller
/// and `src_decl` of `Scope.Block` is the `Decl` of the callee.
/// This `Decl` owns the arena memory of this `Sema`.
owner_decl: *Decl,
/// How to look up decl names.
namespace: *Scope.Namespace,
/// For an inline or comptime function call, this will be the root parent function
/// which contains the callsite. Corresponds to `owner_decl`.
owner_func: ?*Module.Fn,
/// The function this ZIR code is the body of, according to the source code.
/// This starts out the same as `owner_func` and then diverges in the case of
/// an inline or comptime function call.
func: ?*Module.Fn,
/// For now, AIR requires arg instructions to be the first N instructions in the
/// AIR code. We store references here for the purpose of `resolveInst`.
/// This can get reworked with AIR memory layout changes, into simply:
/// > Denormalized data to make `resolveInst` faster. This is 0 if not inside a function,
/// > otherwise it is the number of parameters of the function.
/// > param_count: u32
param_inst_list: []const *ir.Inst,
branch_quota: u32 = 1000,
branch_count: u32 = 0,
/// This field is updated when a new source location becomes active, so that
/// instructions which do not have explicitly mapped source locations still have
/// access to the source location set by the previous instruction which did
/// contain a mapped source location.
src: LazySrcLoc = .{ .token_offset = 0 },
next_arg_index: usize = 0,
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.sema);
const Sema = @This();
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const TypedValue = @import("TypedValue.zig");
const ir = @import("ir.zig");
const Zir = @import("Zir.zig");
const Module = @import("Module.zig");
const Inst = ir.Inst;
const Body = ir.Body;
const trace = @import("tracy.zig").trace;
const Scope = Module.Scope;
const InnerError = Module.InnerError;
const Decl = Module.Decl;
const LazySrcLoc = Module.LazySrcLoc;
const RangeSet = @import("RangeSet.zig");
const target_util = @import("target.zig");
pub const InstMap = std.AutoHashMapUnmanaged(Zir.Inst.Index, *ir.Inst);
pub fn deinit(sema: *Sema) void {
sema.inst_map.deinit(sema.gpa);
sema.* = undefined;
}
pub fn analyzeFnBody(
sema: *Sema,
block: *Scope.Block,
fn_body_inst: Zir.Inst.Index,
) InnerError!void {
const tags = sema.code.instructions.items(.tag);
const datas = sema.code.instructions.items(.data);
const body: []const Zir.Inst.Index = switch (tags[fn_body_inst]) {
.func, .func_inferred => blk: {
const inst_data = datas[fn_body_inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
const param_types_len = extra.data.param_types_len;
const body = sema.code.extra[extra.end + param_types_len ..][0..extra.data.body_len];
break :blk body;
},
.extended => blk: {
const extended = datas[fn_body_inst].extended;
assert(extended.opcode == .func);
const extra = sema.code.extraData(Zir.Inst.ExtendedFunc, extended.operand);
const small = @bitCast(Zir.Inst.ExtendedFunc.Small, extended.small);
var extra_index: usize = extra.end;
extra_index += @boolToInt(small.has_lib_name);
extra_index += @boolToInt(small.has_cc);
extra_index += @boolToInt(small.has_align);
extra_index += extra.data.param_types_len;
const body = sema.code.extra[extra_index..][0..extra.data.body_len];
break :blk body;
},
else => unreachable,
};
_ = try sema.analyzeBody(block, body);
}
/// Returns only the result from the body that is specified.
/// Only appropriate to call when it is determined at comptime that this body
/// has no peers.
fn resolveBody(sema: *Sema, block: *Scope.Block, body: []const Zir.Inst.Index) InnerError!*Inst {
const break_inst = try sema.analyzeBody(block, body);
const operand_ref = sema.code.instructions.items(.data)[break_inst].@"break".operand;
return sema.resolveInst(operand_ref);
}
/// ZIR instructions which are always `noreturn` return this. This matches the
/// return type of `analyzeBody` so that we can tail call them.
/// Only appropriate to return when the instruction is known to be NoReturn
/// solely based on the ZIR tag.
const always_noreturn: InnerError!Zir.Inst.Index = @as(Zir.Inst.Index, undefined);
/// This function is the main loop of `Sema` and it can be used in two different ways:
/// * The traditional way where there are N breaks out of the block and peer type
/// resolution is done on the break operands. In this case, the `Zir.Inst.Index`
/// part of the return value will be `undefined`, and callsites should ignore it,
/// finding the block result value via the block scope.
/// * The "flat" way. There is only 1 break out of the block, and it is with a `break_inline`
/// instruction. In this case, the `Zir.Inst.Index` part of the return value will be
/// the break instruction. This communicates both which block the break applies to, as
/// well as the operand. No block scope needs to be created for this strategy.
pub fn analyzeBody(
sema: *Sema,
block: *Scope.Block,
body: []const Zir.Inst.Index,
) InnerError!Zir.Inst.Index {
// No tracy calls here, to avoid interfering with the tail call mechanism.
const map = &block.sema.inst_map;
const tags = block.sema.code.instructions.items(.tag);
const datas = block.sema.code.instructions.items(.data);
// We use a while(true) loop here to avoid a redundant way of breaking out of
// the loop. The only way to break out of the loop is with a `noreturn`
// instruction.
// TODO: As an optimization, make sure the codegen for these switch prongs
// directly jump to the next one, rather than detouring through the loop
// continue expression. Related: https://github.com/ziglang/zig/issues/8220
var i: usize = 0;
while (true) : (i += 1) {
const inst = body[i];
const air_inst = switch (tags[inst]) {
// zig fmt: off
.arg => try sema.zirArg(block, inst),
.alloc => try sema.zirAlloc(block, inst),
.alloc_inferred => try sema.zirAllocInferred(block, inst, Type.initTag(.inferred_alloc_const)),
.alloc_inferred_mut => try sema.zirAllocInferred(block, inst, Type.initTag(.inferred_alloc_mut)),
.alloc_inferred_comptime => try sema.zirAllocInferredComptime(block, inst),
.alloc_mut => try sema.zirAllocMut(block, inst),
.alloc_comptime => try sema.zirAllocComptime(block, inst),
.anyframe_type => try sema.zirAnyframeType(block, inst),
.array_cat => try sema.zirArrayCat(block, inst),
.array_mul => try sema.zirArrayMul(block, inst),
.array_type => try sema.zirArrayType(block, inst),
.array_type_sentinel => try sema.zirArrayTypeSentinel(block, inst),
.vector_type => try sema.zirVectorType(block, inst),
.as => try sema.zirAs(block, inst),
.as_node => try sema.zirAsNode(block, inst),
.bit_and => try sema.zirBitwise(block, inst, .bit_and),
.bit_not => try sema.zirBitNot(block, inst),
.bit_or => try sema.zirBitwise(block, inst, .bit_or),
.bitcast => try sema.zirBitcast(block, inst),
.bitcast_result_ptr => try sema.zirBitcastResultPtr(block, inst),
.block => try sema.zirBlock(block, inst),
.suspend_block => try sema.zirSuspendBlock(block, inst),
.bool_not => try sema.zirBoolNot(block, inst),
.bool_and => try sema.zirBoolOp(block, inst, false),
.bool_or => try sema.zirBoolOp(block, inst, true),
.bool_br_and => try sema.zirBoolBr(block, inst, false),
.bool_br_or => try sema.zirBoolBr(block, inst, true),
.c_import => try sema.zirCImport(block, inst),
.call => try sema.zirCall(block, inst, .auto, false),
.call_chkused => try sema.zirCall(block, inst, .auto, true),
.call_compile_time => try sema.zirCall(block, inst, .compile_time, false),
.call_nosuspend => try sema.zirCall(block, inst, .no_async, false),
.call_async => try sema.zirCall(block, inst, .async_kw, false),
.cmp_eq => try sema.zirCmp(block, inst, .eq),
.cmp_gt => try sema.zirCmp(block, inst, .gt),
.cmp_gte => try sema.zirCmp(block, inst, .gte),
.cmp_lt => try sema.zirCmp(block, inst, .lt),
.cmp_lte => try sema.zirCmp(block, inst, .lte),
.cmp_neq => try sema.zirCmp(block, inst, .neq),
.coerce_result_ptr => try sema.zirCoerceResultPtr(block, inst),
.decl_ref => try sema.zirDeclRef(block, inst),
.decl_val => try sema.zirDeclVal(block, inst),
.load => try sema.zirLoad(block, inst),
.elem_ptr => try sema.zirElemPtr(block, inst),
.elem_ptr_node => try sema.zirElemPtrNode(block, inst),
.elem_val => try sema.zirElemVal(block, inst),
.elem_val_node => try sema.zirElemValNode(block, inst),
.elem_type => try sema.zirElemType(block, inst),
.enum_literal => try sema.zirEnumLiteral(block, inst),
.enum_to_int => try sema.zirEnumToInt(block, inst),
.int_to_enum => try sema.zirIntToEnum(block, inst),
.err_union_code => try sema.zirErrUnionCode(block, inst),
.err_union_code_ptr => try sema.zirErrUnionCodePtr(block, inst),
.err_union_payload_safe => try sema.zirErrUnionPayload(block, inst, true),
.err_union_payload_safe_ptr => try sema.zirErrUnionPayloadPtr(block, inst, true),
.err_union_payload_unsafe => try sema.zirErrUnionPayload(block, inst, false),
.err_union_payload_unsafe_ptr => try sema.zirErrUnionPayloadPtr(block, inst, false),
.error_union_type => try sema.zirErrorUnionType(block, inst),
.error_value => try sema.zirErrorValue(block, inst),
.error_to_int => try sema.zirErrorToInt(block, inst),
.int_to_error => try sema.zirIntToError(block, inst),
.field_ptr => try sema.zirFieldPtr(block, inst),
.field_ptr_named => try sema.zirFieldPtrNamed(block, inst),
.field_val => try sema.zirFieldVal(block, inst),
.field_val_named => try sema.zirFieldValNamed(block, inst),
.func => try sema.zirFunc(block, inst, false),
.func_inferred => try sema.zirFunc(block, inst, true),
.import => try sema.zirImport(block, inst),
.indexable_ptr_len => try sema.zirIndexablePtrLen(block, inst),
.int => try sema.zirInt(block, inst),
.int_big => try sema.zirIntBig(block, inst),
.float => try sema.zirFloat(block, inst),
.float128 => try sema.zirFloat128(block, inst),
.int_type => try sema.zirIntType(block, inst),
.is_err => try sema.zirIsErr(block, inst),
.is_err_ptr => try sema.zirIsErrPtr(block, inst),
.is_non_null => try sema.zirIsNull(block, inst, true),
.is_non_null_ptr => try sema.zirIsNullPtr(block, inst, true),
.is_null => try sema.zirIsNull(block, inst, false),
.is_null_ptr => try sema.zirIsNullPtr(block, inst, false),
.loop => try sema.zirLoop(block, inst),
.merge_error_sets => try sema.zirMergeErrorSets(block, inst),
.negate => try sema.zirNegate(block, inst, .sub),
.negate_wrap => try sema.zirNegate(block, inst, .subwrap),
.optional_payload_safe => try sema.zirOptionalPayload(block, inst, true),
.optional_payload_safe_ptr => try sema.zirOptionalPayloadPtr(block, inst, true),
.optional_payload_unsafe => try sema.zirOptionalPayload(block, inst, false),
.optional_payload_unsafe_ptr => try sema.zirOptionalPayloadPtr(block, inst, false),
.optional_type => try sema.zirOptionalType(block, inst),
.param_type => try sema.zirParamType(block, inst),
.ptr_type => try sema.zirPtrType(block, inst),
.ptr_type_simple => try sema.zirPtrTypeSimple(block, inst),
.ref => try sema.zirRef(block, inst),
.shl => try sema.zirShl(block, inst),
.shr => try sema.zirShr(block, inst),
.slice_end => try sema.zirSliceEnd(block, inst),
.slice_sentinel => try sema.zirSliceSentinel(block, inst),
.slice_start => try sema.zirSliceStart(block, inst),
.str => try sema.zirStr(block, inst),
.switch_block => try sema.zirSwitchBlock(block, inst, false, .none),
.switch_block_multi => try sema.zirSwitchBlockMulti(block, inst, false, .none),
.switch_block_else => try sema.zirSwitchBlock(block, inst, false, .@"else"),
.switch_block_else_multi => try sema.zirSwitchBlockMulti(block, inst, false, .@"else"),
.switch_block_under => try sema.zirSwitchBlock(block, inst, false, .under),
.switch_block_under_multi => try sema.zirSwitchBlockMulti(block, inst, false, .under),
.switch_block_ref => try sema.zirSwitchBlock(block, inst, true, .none),
.switch_block_ref_multi => try sema.zirSwitchBlockMulti(block, inst, true, .none),
.switch_block_ref_else => try sema.zirSwitchBlock(block, inst, true, .@"else"),
.switch_block_ref_else_multi => try sema.zirSwitchBlockMulti(block, inst, true, .@"else"),
.switch_block_ref_under => try sema.zirSwitchBlock(block, inst, true, .under),
.switch_block_ref_under_multi => try sema.zirSwitchBlockMulti(block, inst, true, .under),
.switch_capture => try sema.zirSwitchCapture(block, inst, false, false),
.switch_capture_ref => try sema.zirSwitchCapture(block, inst, false, true),
.switch_capture_multi => try sema.zirSwitchCapture(block, inst, true, false),
.switch_capture_multi_ref => try sema.zirSwitchCapture(block, inst, true, true),
.switch_capture_else => try sema.zirSwitchCaptureElse(block, inst, false),
.switch_capture_else_ref => try sema.zirSwitchCaptureElse(block, inst, true),
.type_info => try sema.zirTypeInfo(block, inst),
.size_of => try sema.zirSizeOf(block, inst),
.bit_size_of => try sema.zirBitSizeOf(block, inst),
.typeof => try sema.zirTypeof(block, inst),
.typeof_elem => try sema.zirTypeofElem(block, inst),
.log2_int_type => try sema.zirLog2IntType(block, inst),
.typeof_log2_int_type => try sema.zirTypeofLog2IntType(block, inst),
.xor => try sema.zirBitwise(block, inst, .xor),
.struct_init_empty => try sema.zirStructInitEmpty(block, inst),
.struct_init => try sema.zirStructInit(block, inst, false),
.struct_init_ref => try sema.zirStructInit(block, inst, true),
.struct_init_anon => try sema.zirStructInitAnon(block, inst, false),
.struct_init_anon_ref => try sema.zirStructInitAnon(block, inst, true),
.array_init => try sema.zirArrayInit(block, inst, false),
.array_init_ref => try sema.zirArrayInit(block, inst, true),
.array_init_anon => try sema.zirArrayInitAnon(block, inst, false),
.array_init_anon_ref => try sema.zirArrayInitAnon(block, inst, true),
.union_init_ptr => try sema.zirUnionInitPtr(block, inst),
.field_type => try sema.zirFieldType(block, inst),
.field_type_ref => try sema.zirFieldTypeRef(block, inst),
.ptr_to_int => try sema.zirPtrToInt(block, inst),
.align_of => try sema.zirAlignOf(block, inst),
.bool_to_int => try sema.zirBoolToInt(block, inst),
.embed_file => try sema.zirEmbedFile(block, inst),
.error_name => try sema.zirErrorName(block, inst),
.tag_name => try sema.zirTagName(block, inst),
.reify => try sema.zirReify(block, inst),
.type_name => try sema.zirTypeName(block, inst),
.frame_type => try sema.zirFrameType(block, inst),
.frame_size => try sema.zirFrameSize(block, inst),
.float_to_int => try sema.zirFloatToInt(block, inst),
.int_to_float => try sema.zirIntToFloat(block, inst),
.int_to_ptr => try sema.zirIntToPtr(block, inst),
.float_cast => try sema.zirFloatCast(block, inst),
.int_cast => try sema.zirIntCast(block, inst),
.err_set_cast => try sema.zirErrSetCast(block, inst),
.ptr_cast => try sema.zirPtrCast(block, inst),
.truncate => try sema.zirTruncate(block, inst),
.align_cast => try sema.zirAlignCast(block, inst),
.has_decl => try sema.zirHasDecl(block, inst),
.has_field => try sema.zirHasField(block, inst),
.clz => try sema.zirClz(block, inst),
.ctz => try sema.zirCtz(block, inst),
.pop_count => try sema.zirPopCount(block, inst),
.byte_swap => try sema.zirByteSwap(block, inst),
.bit_reverse => try sema.zirBitReverse(block, inst),
.div_exact => try sema.zirDivExact(block, inst),
.div_floor => try sema.zirDivFloor(block, inst),
.div_trunc => try sema.zirDivTrunc(block, inst),
.mod => try sema.zirMod(block, inst),
.rem => try sema.zirRem(block, inst),
.shl_exact => try sema.zirShlExact(block, inst),
.shr_exact => try sema.zirShrExact(block, inst),
.bit_offset_of => try sema.zirBitOffsetOf(block, inst),
.byte_offset_of => try sema.zirByteOffsetOf(block, inst),
.cmpxchg_strong => try sema.zirCmpxchg(block, inst),
.cmpxchg_weak => try sema.zirCmpxchg(block, inst),
.splat => try sema.zirSplat(block, inst),
.reduce => try sema.zirReduce(block, inst),
.shuffle => try sema.zirShuffle(block, inst),
.atomic_load => try sema.zirAtomicLoad(block, inst),
.atomic_rmw => try sema.zirAtomicRmw(block, inst),
.atomic_store => try sema.zirAtomicStore(block, inst),
.mul_add => try sema.zirMulAdd(block, inst),
.builtin_call => try sema.zirBuiltinCall(block, inst),
.field_ptr_type => try sema.zirFieldPtrType(block, inst),
.field_parent_ptr => try sema.zirFieldParentPtr(block, inst),
.memcpy => try sema.zirMemcpy(block, inst),
.memset => try sema.zirMemset(block, inst),
.builtin_async_call => try sema.zirBuiltinAsyncCall(block, inst),
.@"resume" => try sema.zirResume(block, inst),
.@"await" => try sema.zirAwait(block, inst, false),
.await_nosuspend => try sema.zirAwait(block, inst, true),
.extended => try sema.zirExtended(block, inst),
.sqrt => try sema.zirUnaryMath(block, inst),
.sin => try sema.zirUnaryMath(block, inst),
.cos => try sema.zirUnaryMath(block, inst),
.exp => try sema.zirUnaryMath(block, inst),
.exp2 => try sema.zirUnaryMath(block, inst),
.log => try sema.zirUnaryMath(block, inst),
.log2 => try sema.zirUnaryMath(block, inst),
.log10 => try sema.zirUnaryMath(block, inst),
.fabs => try sema.zirUnaryMath(block, inst),
.floor => try sema.zirUnaryMath(block, inst),
.ceil => try sema.zirUnaryMath(block, inst),
.trunc => try sema.zirUnaryMath(block, inst),
.round => try sema.zirUnaryMath(block, inst),
.opaque_decl => try sema.zirOpaqueDecl(block, inst, .parent),
.opaque_decl_anon => try sema.zirOpaqueDecl(block, inst, .anon),
.opaque_decl_func => try sema.zirOpaqueDecl(block, inst, .func),
.error_set_decl => try sema.zirErrorSetDecl(block, inst, .parent),
.error_set_decl_anon => try sema.zirErrorSetDecl(block, inst, .anon),
.error_set_decl_func => try sema.zirErrorSetDecl(block, inst, .func),
.add => try sema.zirArithmetic(block, inst),
.addwrap => try sema.zirArithmetic(block, inst),
.div => try sema.zirArithmetic(block, inst),
.mod_rem => try sema.zirArithmetic(block, inst),
.mul => try sema.zirArithmetic(block, inst),
.mulwrap => try sema.zirArithmetic(block, inst),
.sub => try sema.zirArithmetic(block, inst),
.subwrap => try sema.zirArithmetic(block, inst),
// Instructions that we know to *always* be noreturn based solely on their tag.
// These functions match the return type of analyzeBody so that we can
// tail call them here.
.break_inline => return inst,
.condbr => return sema.zirCondbr(block, inst),
.@"break" => return sema.zirBreak(block, inst),
.compile_error => return sema.zirCompileError(block, inst),
.ret_coerce => return sema.zirRetTok(block, inst, true),
.ret_node => return sema.zirRetNode(block, inst),
.@"unreachable" => return sema.zirUnreachable(block, inst),
.repeat => return sema.zirRepeat(block, inst),
.panic => return sema.zirPanic(block, inst),
// zig fmt: on
// Instructions that we know can *never* be noreturn based solely on
// their tag. We avoid needlessly checking if they are noreturn and
// continue the loop.
// We also know that they cannot be referenced later, so we avoid
// putting them into the map.
.breakpoint => {
try sema.zirBreakpoint(block, inst);
continue;
},
.fence => {
try sema.zirFence(block, inst);
continue;
},
.dbg_stmt => {
try sema.zirDbgStmt(block, inst);
continue;
},
.ensure_err_payload_void => {
try sema.zirEnsureErrPayloadVoid(block, inst);
continue;
},
.ensure_result_non_error => {
try sema.zirEnsureResultNonError(block, inst);
continue;
},
.ensure_result_used => {
try sema.zirEnsureResultUsed(block, inst);
continue;
},
.set_eval_branch_quota => {
try sema.zirSetEvalBranchQuota(block, inst);
continue;
},
.store => {
try sema.zirStore(block, inst);
continue;
},
.store_node => {
try sema.zirStoreNode(block, inst);
continue;
},
.store_to_block_ptr => {
try sema.zirStoreToBlockPtr(block, inst);
continue;
},
.store_to_inferred_ptr => {
try sema.zirStoreToInferredPtr(block, inst);
continue;
},
.resolve_inferred_alloc => {
try sema.zirResolveInferredAlloc(block, inst);
continue;
},
.validate_struct_init_ptr => {
try sema.zirValidateStructInitPtr(block, inst);
continue;
},
.validate_array_init_ptr => {
try sema.zirValidateArrayInitPtr(block, inst);
continue;
},
.@"export" => {
try sema.zirExport(block, inst);
continue;
},
.set_align_stack => {
try sema.zirSetAlignStack(block, inst);
continue;
},
.set_cold => {
try sema.zirSetAlignStack(block, inst);
continue;
},
.set_float_mode => {
try sema.zirSetFloatMode(block, inst);
continue;
},
.set_runtime_safety => {
try sema.zirSetRuntimeSafety(block, inst);
continue;
},
// Special case instructions to handle comptime control flow.
.repeat_inline => {
// Send comptime control flow back to the beginning of this block.
const src: LazySrcLoc = .{ .node_offset = datas[inst].node };
try sema.emitBackwardBranch(block, src);
i = 0;
continue;
},
.block_inline => blk: {
// Directly analyze the block body without introducing a new block.
const inst_data = datas[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
const break_inst = try sema.analyzeBody(block, inline_body);
const break_data = datas[break_inst].@"break";
if (inst == break_data.block_inst) {
break :blk try sema.resolveInst(break_data.operand);
} else {
return break_inst;
}
},
.condbr_inline => blk: {
const inst_data = datas[inst].pl_node;
const cond_src: LazySrcLoc = .{ .node_offset_if_cond = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
const then_body = sema.code.extra[extra.end..][0..extra.data.then_body_len];
const else_body = sema.code.extra[extra.end + then_body.len ..][0..extra.data.else_body_len];
const cond = try sema.resolveInstConst(block, cond_src, extra.data.condition);
const inline_body = if (cond.val.toBool()) then_body else else_body;
const break_inst = try sema.analyzeBody(block, inline_body);
const break_data = datas[break_inst].@"break";
if (inst == break_data.block_inst) {
break :blk try sema.resolveInst(break_data.operand);
} else {
return break_inst;
}
},
};
if (air_inst.ty.isNoReturn())
return always_noreturn;
try map.putNoClobber(sema.gpa, inst, air_inst);
}
}
fn zirExtended(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const extended = sema.code.instructions.items(.data)[inst].extended;
switch (extended.opcode) {
// zig fmt: off
.func => return sema.zirFuncExtended( block, extended, inst),
.variable => return sema.zirVarExtended( block, extended),
.struct_decl => return sema.zirStructDecl( block, extended, inst),
.enum_decl => return sema.zirEnumDecl( block, extended),
.union_decl => return sema.zirUnionDecl( block, extended, inst),
.ret_ptr => return sema.zirRetPtr( block, extended),
.ret_type => return sema.zirRetType( block, extended),
.this => return sema.zirThis( block, extended),
.ret_addr => return sema.zirRetAddr( block, extended),
.builtin_src => return sema.zirBuiltinSrc( block, extended),
.error_return_trace => return sema.zirErrorReturnTrace( block, extended),
.frame => return sema.zirFrame( block, extended),
.frame_address => return sema.zirFrameAddress( block, extended),
.alloc => return sema.zirAllocExtended( block, extended),
.builtin_extern => return sema.zirBuiltinExtern( block, extended),
.@"asm" => return sema.zirAsm( block, extended),
.typeof_peer => return sema.zirTypeofPeer( block, extended),
.compile_log => return sema.zirCompileLog( block, extended),
.add_with_overflow => return sema.zirOverflowArithmetic(block, extended),
.sub_with_overflow => return sema.zirOverflowArithmetic(block, extended),
.mul_with_overflow => return sema.zirOverflowArithmetic(block, extended),
.shl_with_overflow => return sema.zirOverflowArithmetic(block, extended),
.c_undef => return sema.zirCUndef( block, extended),
.c_include => return sema.zirCInclude( block, extended),
.c_define => return sema.zirCDefine( block, extended),
.wasm_memory_size => return sema.zirWasmMemorySize( block, extended),
.wasm_memory_grow => return sema.zirWasmMemoryGrow( block, extended),
// zig fmt: on
}
}
/// TODO when we rework AIR memory layout, this function will no longer have a possible error.
pub fn resolveInst(sema: *Sema, zir_ref: Zir.Inst.Ref) error{OutOfMemory}!*ir.Inst {
var i: usize = @enumToInt(zir_ref);
// First section of indexes correspond to a set number of constant values.
if (i < Zir.Inst.Ref.typed_value_map.len) {
// TODO when we rework AIR memory layout, this function can be as simple as:
// if (zir_ref < Zir.const_inst_list.len + sema.param_count)
// return zir_ref;
// Until then we allocate memory for a new, mutable `ir.Inst` to match what
// AIR expects.
return sema.mod.constInst(sema.arena, .unneeded, Zir.Inst.Ref.typed_value_map[i]);
}
i -= Zir.Inst.Ref.typed_value_map.len;
// Finally, the last section of indexes refers to the map of ZIR=>AIR.
return sema.inst_map.get(@intCast(u32, i)).?;
}
fn resolveConstString(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
zir_ref: Zir.Inst.Ref,
) ![]u8 {
const air_inst = try sema.resolveInst(zir_ref);
const wanted_type = Type.initTag(.const_slice_u8);
const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
const val = try sema.resolveConstValue(block, src, coerced_inst);
return val.toAllocatedBytes(sema.arena);
}
pub fn resolveType(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) !Type {
const air_inst = try sema.resolveInst(zir_ref);
return sema.resolveAirAsType(block, src, air_inst);
}
fn resolveAirAsType(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, air_inst: *ir.Inst) !Type {
const wanted_type = Type.initTag(.@"type");
const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
const val = try sema.resolveConstValue(block, src, coerced_inst);
return val.toType(sema.arena);
}
fn resolveConstValue(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, base: *ir.Inst) !Value {
return (try sema.resolveDefinedValue(block, src, base)) orelse
return sema.failWithNeededComptime(block, src);
}
fn resolveDefinedValue(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, base: *ir.Inst) !?Value {
if (try sema.resolvePossiblyUndefinedValue(block, src, base)) |val| {
if (val.isUndef()) {
return sema.failWithUseOfUndef(block, src);
}
return val;
}
return null;
}
fn resolvePossiblyUndefinedValue(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
base: *ir.Inst,
) !?Value {
if (try sema.typeHasOnePossibleValue(block, src, base.ty)) |opv| {
return opv;
}
const inst = base.castTag(.constant) orelse return null;
return inst.val;
}
fn failWithNeededComptime(sema: *Sema, block: *Scope.Block, src: LazySrcLoc) InnerError {
return sema.mod.fail(&block.base, src, "unable to resolve comptime value", .{});
}
fn failWithUseOfUndef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc) InnerError {
return sema.mod.fail(&block.base, src, "use of undefined value here causes undefined behavior", .{});
}
/// Appropriate to call when the coercion has already been done by result
/// location semantics. Asserts the value fits in the provided `Int` type.
/// Only supports `Int` types 64 bits or less.
fn resolveAlreadyCoercedInt(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
zir_ref: Zir.Inst.Ref,
comptime Int: type,
) !Int {
comptime assert(@typeInfo(Int).Int.bits <= 64);
const air_inst = try sema.resolveInst(zir_ref);
const val = try sema.resolveConstValue(block, src, air_inst);
switch (@typeInfo(Int).Int.signedness) {
.signed => return @intCast(Int, val.toSignedInt()),
.unsigned => return @intCast(Int, val.toUnsignedInt()),
}
}
fn resolveInt(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
zir_ref: Zir.Inst.Ref,
dest_type: Type,
) !u64 {
const air_inst = try sema.resolveInst(zir_ref);
const coerced = try sema.coerce(block, dest_type, air_inst, src);
const val = try sema.resolveConstValue(block, src, coerced);
return val.toUnsignedInt();
}
pub fn resolveInstConst(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
zir_ref: Zir.Inst.Ref,
) InnerError!TypedValue {
const air_inst = try sema.resolveInst(zir_ref);
const val = try sema.resolveConstValue(block, src, air_inst);
return TypedValue{
.ty = air_inst.ty,
.val = val,
};
}
fn zirBitcastResultPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO implement zir_sema.zirBitcastResultPtr", .{});
}
fn zirCoerceResultPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirCoerceResultPtr", .{});
}
pub fn analyzeStructDecl(
sema: *Sema,
new_decl: *Decl,
inst: Zir.Inst.Index,
struct_obj: *Module.Struct,
) InnerError!void {
const extended = sema.code.instructions.items(.data)[inst].extended;
assert(extended.opcode == .struct_decl);
const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
var extra_index: usize = extended.operand;
extra_index += @boolToInt(small.has_src_node);
extra_index += @boolToInt(small.has_body_len);
extra_index += @boolToInt(small.has_fields_len);
const decls_len = if (small.has_decls_len) blk: {
const decls_len = sema.code.extra[extra_index];
extra_index += 1;
break :blk decls_len;
} else 0;
_ = try sema.mod.scanNamespace(&struct_obj.namespace, extra_index, decls_len, new_decl);
}
fn zirStructDecl(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
inst: Zir.Inst.Index,
) InnerError!*Inst {
const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
const src: LazySrcLoc = if (small.has_src_node) blk: {
const node_offset = @bitCast(i32, sema.code.extra[extended.operand]);
break :blk .{ .node_offset = node_offset };
} else sema.src;
var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
errdefer new_decl_arena.deinit();
const struct_obj = try new_decl_arena.allocator.create(Module.Struct);
const struct_ty = try Type.Tag.@"struct".create(&new_decl_arena.allocator, struct_obj);
const struct_val = try Value.Tag.ty.create(&new_decl_arena.allocator, struct_ty);
const type_name = try sema.createTypeName(block, small.name_strategy);
const new_decl = try sema.mod.createAnonymousDeclNamed(&block.base, .{
.ty = Type.initTag(.type),
.val = struct_val,
}, type_name);
errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
struct_obj.* = .{
.owner_decl = new_decl,
.fields = .{},
.node_offset = src.node_offset,
.zir_index = inst,
.layout = small.layout,
.status = .none,
.namespace = .{
.parent = sema.owner_decl.namespace,
.ty = struct_ty,
.file_scope = block.getFileScope(),
},
};
std.log.scoped(.module).debug("create struct {*} owned by {*} ({s})", .{
&struct_obj.namespace, new_decl, new_decl.name,
});
try sema.analyzeStructDecl(new_decl, inst, struct_obj);
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclVal(block, src, new_decl);
}
fn createTypeName(sema: *Sema, block: *Scope.Block, name_strategy: Zir.Inst.NameStrategy) ![:0]u8 {
switch (name_strategy) {
.anon => {
// It would be neat to have "struct:line:column" but this name has
// to survive incremental updates, where it may have been shifted down
// or up to a different line, but unchanged, and thus not unnecessarily
// semantically analyzed.
const name_index = sema.mod.getNextAnonNameIndex();
return std.fmt.allocPrintZ(sema.gpa, "{s}__anon_{d}", .{
sema.owner_decl.name, name_index,
});
},
.parent => return sema.gpa.dupeZ(u8, mem.spanZ(sema.owner_decl.name)),
.func => {
const name_index = sema.mod.getNextAnonNameIndex();
const name = try std.fmt.allocPrintZ(sema.gpa, "{s}__anon_{d}", .{
sema.owner_decl.name, name_index,
});
log.warn("TODO: handle NameStrategy.func correctly instead of using anon name '{s}'", .{
name,
});
return name;
},
}
}
fn zirEnumDecl(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const mod = sema.mod;
const gpa = sema.gpa;
const small = @bitCast(Zir.Inst.EnumDecl.Small, extended.small);
var extra_index: usize = extended.operand;
const src: LazySrcLoc = if (small.has_src_node) blk: {
const node_offset = @bitCast(i32, sema.code.extra[extra_index]);
extra_index += 1;
break :blk .{ .node_offset = node_offset };
} else sema.src;
const tag_type_ref = if (small.has_tag_type) blk: {
const tag_type_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
break :blk tag_type_ref;
} else .none;
const body_len = if (small.has_body_len) blk: {
const body_len = sema.code.extra[extra_index];
extra_index += 1;
break :blk body_len;
} else 0;
const fields_len = if (small.has_fields_len) blk: {
const fields_len = sema.code.extra[extra_index];
extra_index += 1;
break :blk fields_len;
} else 0;
const decls_len = if (small.has_decls_len) blk: {
const decls_len = sema.code.extra[extra_index];
extra_index += 1;
break :blk decls_len;
} else 0;
var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
errdefer new_decl_arena.deinit();
const tag_ty = blk: {
if (tag_type_ref != .none) {
// TODO better source location
// TODO (needs AstGen fix too) move this eval to the block so it gets allocated
// in the new decl arena.
break :blk try sema.resolveType(block, src, tag_type_ref);
}
const bits = std.math.log2_int_ceil(usize, fields_len);
break :blk try Type.Tag.int_unsigned.create(&new_decl_arena.allocator, bits);
};
const enum_obj = try new_decl_arena.allocator.create(Module.EnumFull);
const enum_ty_payload = try new_decl_arena.allocator.create(Type.Payload.EnumFull);
enum_ty_payload.* = .{
.base = .{ .tag = if (small.nonexhaustive) .enum_nonexhaustive else .enum_full },
.data = enum_obj,
};
const enum_ty = Type.initPayload(&enum_ty_payload.base);
const enum_val = try Value.Tag.ty.create(&new_decl_arena.allocator, enum_ty);
const type_name = try sema.createTypeName(block, small.name_strategy);
const new_decl = try mod.createAnonymousDeclNamed(&block.base, .{
.ty = Type.initTag(.type),
.val = enum_val,
}, type_name);
errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
enum_obj.* = .{
.owner_decl = new_decl,
.tag_ty = tag_ty,
.fields = .{},
.values = .{},
.node_offset = src.node_offset,
.namespace = .{
.parent = sema.owner_decl.namespace,
.ty = enum_ty,
.file_scope = block.getFileScope(),
},
};
std.log.scoped(.module).debug("create enum {*} owned by {*} ({s})", .{
&enum_obj.namespace, new_decl, new_decl.name,
});
extra_index = try mod.scanNamespace(&enum_obj.namespace, extra_index, decls_len, new_decl);
const body = sema.code.extra[extra_index..][0..body_len];
if (fields_len == 0) {
assert(body.len == 0);
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclVal(block, src, new_decl);
}
extra_index += body.len;
const bit_bags_count = std.math.divCeil(usize, fields_len, 32) catch unreachable;
const body_end = extra_index;
extra_index += bit_bags_count;
try enum_obj.fields.ensureCapacity(&new_decl_arena.allocator, fields_len);
const any_values = for (sema.code.extra[body_end..][0..bit_bags_count]) |bag| {
if (bag != 0) break true;
} else false;
if (any_values) {
try enum_obj.values.ensureCapacity(&new_decl_arena.allocator, fields_len);
}
{
// We create a block for the field type instructions because they
// may need to reference Decls from inside the enum namespace.
// Within the field type, default value, and alignment expressions, the "owner decl"
// should be the enum itself. Thus we need a new Sema.
var enum_sema: Sema = .{
.mod = mod,
.gpa = gpa,
.arena = &new_decl_arena.allocator,
.code = sema.code,
.inst_map = sema.inst_map,
.owner_decl = new_decl,
.namespace = &enum_obj.namespace,
.owner_func = null,
.func = null,
.param_inst_list = &.{},
.branch_quota = sema.branch_quota,
.branch_count = sema.branch_count,
};
var enum_block: Scope.Block = .{
.parent = null,
.sema = &enum_sema,
.src_decl = new_decl,
.instructions = .{},
.inlining = null,
.is_comptime = true,
};
defer assert(enum_block.instructions.items.len == 0); // should all be comptime instructions
if (body.len != 0) {
_ = try enum_sema.analyzeBody(&enum_block, body);
}
sema.branch_count = enum_sema.branch_count;
sema.branch_quota = enum_sema.branch_quota;
}
var bit_bag_index: usize = body_end;
var cur_bit_bag: u32 = undefined;
var field_i: u32 = 0;
while (field_i < fields_len) : (field_i += 1) {
if (field_i % 32 == 0) {
cur_bit_bag = sema.code.extra[bit_bag_index];
bit_bag_index += 1;
}
const has_tag_value = @truncate(u1, cur_bit_bag) != 0;
cur_bit_bag >>= 1;
const field_name_zir = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
extra_index += 1;
// This string needs to outlive the ZIR code.
const field_name = try new_decl_arena.allocator.dupe(u8, field_name_zir);
const gop = enum_obj.fields.getOrPutAssumeCapacity(field_name);
if (gop.found_existing) {
const tree = try sema.getAstTree(block);
const field_src = enumFieldSrcLoc(block.src_decl, tree.*, src.node_offset, field_i);
const other_tag_src = enumFieldSrcLoc(block.src_decl, tree.*, src.node_offset, gop.index);
const msg = msg: {
const msg = try mod.errMsg(&block.base, field_src, "duplicate enum tag", .{});
errdefer msg.destroy(gpa);
try mod.errNote(&block.base, other_tag_src, msg, "other tag here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
if (has_tag_value) {
const tag_val_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
// TODO: if we need to report an error here, use a source location
// that points to this default value expression rather than the struct.
// But only resolve the source location if we need to emit a compile error.
const tag_val = (try sema.resolveInstConst(block, src, tag_val_ref)).val;
enum_obj.values.putAssumeCapacityNoClobber(tag_val, {});
} else if (any_values) {
const tag_val = try Value.Tag.int_u64.create(&new_decl_arena.allocator, field_i);
enum_obj.values.putAssumeCapacityNoClobber(tag_val, {});
}
}
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclVal(block, src, new_decl);
}
fn zirUnionDecl(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
inst: Zir.Inst.Index,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const small = @bitCast(Zir.Inst.UnionDecl.Small, extended.small);
var extra_index: usize = extended.operand;
const src: LazySrcLoc = if (small.has_src_node) blk: {
const node_offset = @bitCast(i32, sema.code.extra[extra_index]);
extra_index += 1;
break :blk .{ .node_offset = node_offset };
} else sema.src;
extra_index += @boolToInt(small.has_tag_type);
extra_index += @boolToInt(small.has_body_len);
extra_index += @boolToInt(small.has_fields_len);
const decls_len = if (small.has_decls_len) blk: {
const decls_len = sema.code.extra[extra_index];
extra_index += 1;
break :blk decls_len;
} else 0;
var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
errdefer new_decl_arena.deinit();
const union_obj = try new_decl_arena.allocator.create(Module.Union);
const union_ty = try Type.Tag.@"union".create(&new_decl_arena.allocator, union_obj);
const union_val = try Value.Tag.ty.create(&new_decl_arena.allocator, union_ty);
const type_name = try sema.createTypeName(block, small.name_strategy);
const new_decl = try sema.mod.createAnonymousDeclNamed(&block.base, .{
.ty = Type.initTag(.type),
.val = union_val,
}, type_name);
errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
union_obj.* = .{
.owner_decl = new_decl,
.tag_ty = Type.initTag(.@"null"),
.fields = .{},
.node_offset = src.node_offset,
.zir_index = inst,
.layout = small.layout,
.status = .none,
.namespace = .{
.parent = sema.owner_decl.namespace,
.ty = union_ty,
.file_scope = block.getFileScope(),
},
};
std.log.scoped(.module).debug("create union {*} owned by {*} ({s})", .{
&union_obj.namespace, new_decl, new_decl.name,
});
_ = try sema.mod.scanNamespace(&union_obj.namespace, extra_index, decls_len, new_decl);
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclVal(block, src, new_decl);
}
fn zirOpaqueDecl(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
name_strategy: Zir.Inst.NameStrategy,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
return sema.mod.fail(&block.base, sema.src, "TODO implement zirOpaqueDecl", .{});
}
fn zirErrorSetDecl(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
name_strategy: Zir.Inst.NameStrategy,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const gpa = sema.gpa;
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.ErrorSetDecl, inst_data.payload_index);
const fields = sema.code.extra[extra.end..][0..extra.data.fields_len];
var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
errdefer new_decl_arena.deinit();
const error_set = try new_decl_arena.allocator.create(Module.ErrorSet);
const error_set_ty = try Type.Tag.error_set.create(&new_decl_arena.allocator, error_set);
const error_set_val = try Value.Tag.ty.create(&new_decl_arena.allocator, error_set_ty);
const type_name = try sema.createTypeName(block, name_strategy);
const new_decl = try sema.mod.createAnonymousDeclNamed(&block.base, .{
.ty = Type.initTag(.type),
.val = error_set_val,
}, type_name);
errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
const names = try new_decl_arena.allocator.alloc([]const u8, fields.len);
for (fields) |str_index, i| {
names[i] = try new_decl_arena.allocator.dupe(u8, sema.code.nullTerminatedString(str_index));
}
error_set.* = .{
.owner_decl = new_decl,
.node_offset = inst_data.src_node,
.names_ptr = names.ptr,
.names_len = @intCast(u32, names.len),
};
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclVal(block, src, new_decl);
}
fn zirRetPtr(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
try sema.requireFunctionBlock(block, src);
const fn_ty = sema.func.?.owner_decl.ty;
const ret_type = fn_ty.fnReturnType();
const ptr_type = try sema.mod.simplePtrType(sema.arena, ret_type, true, .One);
return block.addNoOp(src, ptr_type, .alloc);
}
fn zirRef(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
const operand = try sema.resolveInst(inst_data.operand);
return sema.analyzeRef(block, inst_data.src(), operand);
}
fn zirRetType(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
try sema.requireFunctionBlock(block, src);
const fn_ty = sema.func.?.owner_decl.ty;
const ret_type = fn_ty.fnReturnType();
return sema.mod.constType(sema.arena, src, ret_type);
}
fn zirEnsureResultUsed(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const operand = try sema.resolveInst(inst_data.operand);
const src = inst_data.src();
return sema.ensureResultUsed(block, operand, src);
}
fn ensureResultUsed(
sema: *Sema,
block: *Scope.Block,
operand: *Inst,
src: LazySrcLoc,
) InnerError!void {
switch (operand.ty.zigTypeTag()) {
.Void, .NoReturn => return,
else => return sema.mod.fail(&block.base, src, "expression value is ignored", .{}),
}
}
fn zirEnsureResultNonError(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const operand = try sema.resolveInst(inst_data.operand);
const src = inst_data.src();
switch (operand.ty.zigTypeTag()) {
.ErrorSet, .ErrorUnion => return sema.mod.fail(&block.base, src, "error is discarded", .{}),
else => return,
}
}
fn zirIndexablePtrLen(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const array_ptr = try sema.resolveInst(inst_data.operand);
const elem_ty = array_ptr.ty.elemType();
if (!elem_ty.isIndexable()) {
const cond_src: LazySrcLoc = .{ .node_offset_for_cond = inst_data.src_node };
const msg = msg: {
const msg = try sema.mod.errMsg(
&block.base,
cond_src,
"type '{}' does not support indexing",
.{elem_ty},
);
errdefer msg.destroy(sema.gpa);
try sema.mod.errNote(
&block.base,
cond_src,
msg,
"for loop operand must be an array, slice, tuple, or vector",
.{},
);
break :msg msg;
};
return sema.mod.failWithOwnedErrorMsg(&block.base, msg);
}
const result_ptr = try sema.namedFieldPtr(block, src, array_ptr, "len", src);
return sema.analyzeLoad(block, src, result_ptr, result_ptr.src);
}
fn zirArg(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const arg_name = inst_data.get(sema.code);
const arg_index = sema.next_arg_index;
sema.next_arg_index += 1;
// TODO check if arg_name shadows a Decl
if (block.inlining) |inlining| {
return sema.param_inst_list[arg_index];
}
// Need to set the name of the Air.Arg instruction.
const air_arg = sema.param_inst_list[arg_index].castTag(.arg).?;
air_arg.name = arg_name;
return &air_arg.base;
}
fn zirAllocExtended(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.AllocExtended, extended.operand);
const src: LazySrcLoc = .{ .node_offset = extra.data.src_node };
return sema.mod.fail(&block.base, src, "TODO implement Sema.zirAllocExtended", .{});
}
fn zirAllocComptime(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO implement Sema.zirAllocComptime", .{});
}
fn zirAllocInferredComptime(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const src_node = sema.code.instructions.items(.data)[inst].node;
const src: LazySrcLoc = .{ .node_offset = src_node };
return sema.mod.fail(&block.base, src, "TODO implement Sema.zirAllocInferredComptime", .{});
}
fn zirAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
const var_decl_src = inst_data.src();
const var_type = try sema.resolveType(block, ty_src, inst_data.operand);
const ptr_type = try sema.mod.simplePtrType(sema.arena, var_type, true, .One);
try sema.requireRuntimeBlock(block, var_decl_src);
return block.addNoOp(var_decl_src, ptr_type, .alloc);
}
fn zirAllocMut(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const var_decl_src = inst_data.src();
const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
const var_type = try sema.resolveType(block, ty_src, inst_data.operand);
try sema.validateVarType(block, ty_src, var_type);
const ptr_type = try sema.mod.simplePtrType(sema.arena, var_type, true, .One);
try sema.requireRuntimeBlock(block, var_decl_src);
return block.addNoOp(var_decl_src, ptr_type, .alloc);
}
fn zirAllocInferred(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
inferred_alloc_ty: Type,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src_node = sema.code.instructions.items(.data)[inst].node;
const src: LazySrcLoc = .{ .node_offset = src_node };
const val_payload = try sema.arena.create(Value.Payload.InferredAlloc);
val_payload.* = .{
.data = .{},
};
// `Module.constInst` does not add the instruction to the block because it is
// not needed in the case of constant values. However here, we plan to "downgrade"
// to a normal instruction when we hit `resolve_inferred_alloc`. So we append
// to the block even though it is currently a `.constant`.
const result = try sema.mod.constInst(sema.arena, src, .{
.ty = inferred_alloc_ty,
.val = Value.initPayload(&val_payload.base),
});
try sema.requireFunctionBlock(block, src);
try block.instructions.append(sema.gpa, result);
return result;
}
fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
const ptr = try sema.resolveInst(inst_data.operand);
const ptr_val = ptr.castTag(.constant).?.val;
const inferred_alloc = ptr_val.castTag(.inferred_alloc).?;
const peer_inst_list = inferred_alloc.data.stored_inst_list.items;
const final_elem_ty = try sema.resolvePeerTypes(block, ty_src, peer_inst_list);
const var_is_mut = switch (ptr.ty.tag()) {
.inferred_alloc_const => false,
.inferred_alloc_mut => true,
else => unreachable,
};
if (var_is_mut) {
try sema.validateVarType(block, ty_src, final_elem_ty);
}
const final_ptr_ty = try sema.mod.simplePtrType(sema.arena, final_elem_ty, true, .One);
// Change it to a normal alloc.
ptr.ty = final_ptr_ty;
ptr.tag = .alloc;
}
fn zirValidateStructInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const gpa = sema.gpa;
const mod = sema.mod;
const validate_inst = sema.code.instructions.items(.data)[inst].pl_node;
const struct_init_src = validate_inst.src();
const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
const instrs = sema.code.extra[validate_extra.end..][0..validate_extra.data.body_len];
const struct_obj: *Module.Struct = s: {
const field_ptr_data = sema.code.instructions.items(.data)[instrs[0]].pl_node;
const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
const object_ptr = try sema.resolveInst(field_ptr_extra.lhs);
break :s object_ptr.ty.elemType().castTag(.@"struct").?.data;
};
// Maps field index to field_ptr index of where it was already initialized.
const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.entries.items.len);
defer gpa.free(found_fields);
mem.set(Zir.Inst.Index, found_fields, 0);
for (instrs) |field_ptr| {
const field_ptr_data = sema.code.instructions.items(.data)[field_ptr].pl_node;
const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_ptr_data.src_node };
const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
const field_name = sema.code.nullTerminatedString(field_ptr_extra.field_name_start);
const field_index = struct_obj.fields.getIndex(field_name) orelse
return sema.failWithBadFieldAccess(block, struct_obj, field_src, field_name);
if (found_fields[field_index] != 0) {
const other_field_ptr = found_fields[field_index];
const other_field_ptr_data = sema.code.instructions.items(.data)[other_field_ptr].pl_node;
const other_field_src: LazySrcLoc = .{ .node_offset_back2tok = other_field_ptr_data.src_node };
const msg = msg: {
const msg = try mod.errMsg(&block.base, field_src, "duplicate field", .{});
errdefer msg.destroy(gpa);
try mod.errNote(&block.base, other_field_src, msg, "other field here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
found_fields[field_index] = field_ptr;
}
var root_msg: ?*Module.ErrorMsg = null;
// TODO handle default struct field values
for (found_fields) |field_ptr, i| {
if (field_ptr != 0) continue;
const field_name = struct_obj.fields.entries.items[i].key;
const template = "missing struct field: {s}";
const args = .{field_name};
if (root_msg) |msg| {
try mod.errNote(&block.base, struct_init_src, msg, template, args);
} else {
root_msg = try mod.errMsg(&block.base, struct_init_src, template, args);
}
}
if (root_msg) |msg| {
const fqn = try struct_obj.getFullyQualifiedName(gpa);
defer gpa.free(fqn);
try mod.errNoteNonLazy(
struct_obj.srcLoc(),
msg,
"struct '{s}' declared here",
.{fqn},
);
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
}
fn zirValidateArrayInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO implement Sema.zirValidateArrayInitPtr", .{});
}
fn failWithBadFieldAccess(
sema: *Sema,
block: *Scope.Block,
struct_obj: *Module.Struct,
field_src: LazySrcLoc,
field_name: []const u8,
) InnerError {
const mod = sema.mod;
const gpa = sema.gpa;
const fqn = try struct_obj.getFullyQualifiedName(gpa);
defer gpa.free(fqn);
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
field_src,
"no field named '{s}' in struct '{s}'",
.{ field_name, fqn },
);
errdefer msg.destroy(gpa);
try mod.errNoteNonLazy(struct_obj.srcLoc(), msg, "struct declared here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
fn failWithBadUnionFieldAccess(
sema: *Sema,
block: *Scope.Block,
union_obj: *Module.Union,
field_src: LazySrcLoc,
field_name: []const u8,
) InnerError {
const mod = sema.mod;
const gpa = sema.gpa;
const fqn = try union_obj.getFullyQualifiedName(gpa);
defer gpa.free(fqn);
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
field_src,
"no field named '{s}' in union '{s}'",
.{ field_name, fqn },
);
errdefer msg.destroy(gpa);
try mod.errNoteNonLazy(union_obj.srcLoc(), msg, "union declared here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
fn zirStoreToBlockPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
if (bin_inst.lhs == .none) {
// This is an elided instruction, but AstGen was not smart enough
// to omit it.
return;
}
const ptr = try sema.resolveInst(bin_inst.lhs);
const value = try sema.resolveInst(bin_inst.rhs);
const ptr_ty = try sema.mod.simplePtrType(sema.arena, value.ty, true, .One);
// TODO detect when this store should be done at compile-time. For example,
// if expressions should force it when the condition is compile-time known.
const src: LazySrcLoc = .unneeded;
try sema.requireRuntimeBlock(block, src);
const bitcasted_ptr = try block.addUnOp(src, ptr_ty, .bitcast, ptr);
return sema.storePtr(block, src, bitcasted_ptr, value);
}
fn zirStoreToInferredPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .unneeded;
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const ptr = try sema.resolveInst(bin_inst.lhs);
const value = try sema.resolveInst(bin_inst.rhs);
const inferred_alloc = ptr.castTag(.constant).?.val.castTag(.inferred_alloc).?;
// Add the stored instruction to the set we will use to resolve peer types
// for the inferred allocation.
try inferred_alloc.data.stored_inst_list.append(sema.arena, value);
// Create a runtime bitcast instruction with exactly the type the pointer wants.
const ptr_ty = try sema.mod.simplePtrType(sema.arena, value.ty, true, .One);
try sema.requireRuntimeBlock(block, src);
const bitcasted_ptr = try block.addUnOp(src, ptr_ty, .bitcast, ptr);
return sema.storePtr(block, src, bitcasted_ptr, value);
}
fn zirSetEvalBranchQuota(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const quota = try sema.resolveAlreadyCoercedInt(block, src, inst_data.operand, u32);
if (sema.branch_quota < quota)
sema.branch_quota = quota;
}
fn zirStore(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const ptr = try sema.resolveInst(bin_inst.lhs);
const value = try sema.resolveInst(bin_inst.rhs);
return sema.storePtr(block, sema.src, ptr, value);
}
fn zirStoreNode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const ptr = try sema.resolveInst(extra.lhs);
const value = try sema.resolveInst(extra.rhs);
return sema.storePtr(block, src, ptr, value);
}
fn zirParamType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .unneeded;
const inst_data = sema.code.instructions.items(.data)[inst].param_type;
const fn_inst = try sema.resolveInst(inst_data.callee);
const param_index = inst_data.param_index;
const fn_ty: Type = switch (fn_inst.ty.zigTypeTag()) {
.Fn => fn_inst.ty,
.BoundFn => {
return sema.mod.fail(&block.base, fn_inst.src, "TODO implement zirParamType for method call syntax", .{});
},
else => {
return sema.mod.fail(&block.base, fn_inst.src, "expected function, found '{}'", .{fn_inst.ty});
},
};
const param_count = fn_ty.fnParamLen();
if (param_index >= param_count) {
if (fn_ty.fnIsVarArgs()) {
return sema.mod.constType(sema.arena, src, Type.initTag(.var_args_param));
}
return sema.mod.fail(&block.base, src, "arg index {d} out of bounds; '{}' has {d} argument(s)", .{
param_index,
fn_ty,
param_count,
});
}
// TODO support generic functions
const param_type = fn_ty.fnParamType(param_index);
return sema.mod.constType(sema.arena, src, param_type);
}
fn zirStr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const zir_bytes = sema.code.instructions.items(.data)[inst].str.get(sema.code);
// `zir_bytes` references memory inside the ZIR module, which can get deallocated
// after semantic analysis is complete, for example in the case of the initialization
// expression of a variable declaration. We need the memory to be in the new
// anonymous Decl's arena.
var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
errdefer new_decl_arena.deinit();
const bytes = try new_decl_arena.allocator.dupe(u8, zir_bytes);
const decl_ty = try Type.Tag.array_u8_sentinel_0.create(&new_decl_arena.allocator, bytes.len);
const decl_val = try Value.Tag.bytes.create(&new_decl_arena.allocator, bytes);
const new_decl = try sema.mod.createAnonymousDecl(&block.base, .{
.ty = decl_ty,
.val = decl_val,
});
errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
try new_decl.finalizeNewArena(&new_decl_arena);
return sema.analyzeDeclRef(block, .unneeded, new_decl);
}
fn zirInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const int = sema.code.instructions.items(.data)[inst].int;
return sema.mod.constIntUnsigned(sema.arena, .unneeded, Type.initTag(.comptime_int), int);
}
fn zirIntBig(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const arena = sema.arena;
const int = sema.code.instructions.items(.data)[inst].str;
const byte_count = int.len * @sizeOf(std.math.big.Limb);
const limb_bytes = sema.code.string_bytes[int.start..][0..byte_count];
const limbs = try arena.alloc(std.math.big.Limb, int.len);
mem.copy(u8, mem.sliceAsBytes(limbs), limb_bytes);
return sema.mod.constInst(arena, .unneeded, .{
.ty = Type.initTag(.comptime_int),
.val = try Value.Tag.int_big_positive.create(arena, limbs),
});
}
fn zirFloat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const arena = sema.arena;
const inst_data = sema.code.instructions.items(.data)[inst].float;
const src = inst_data.src();
const number = inst_data.number;
return sema.mod.constInst(arena, src, .{
.ty = Type.initTag(.comptime_float),
.val = try Value.Tag.float_32.create(arena, number),
});
}
fn zirFloat128(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const arena = sema.arena;
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;
const src = inst_data.src();
const number = extra.get();
return sema.mod.constInst(arena, src, .{
.ty = Type.initTag(.comptime_float),
.val = try Value.Tag.float_128.create(arena, number),
});
}
fn zirCompileError(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const msg = try sema.resolveConstString(block, operand_src, inst_data.operand);
return sema.mod.fail(&block.base, src, "{s}", .{msg});
}
fn zirCompileLog(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
var managed = sema.mod.compile_log_text.toManaged(sema.gpa);
defer sema.mod.compile_log_text = managed.moveToUnmanaged();
const writer = managed.writer();
const extra = sema.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
const src_node = extra.data.src_node;
const src: LazySrcLoc = .{ .node_offset = src_node };
const args = sema.code.refSlice(extra.end, extended.small);
for (args) |arg_ref, i| {
if (i != 0) try writer.print(", ", .{});
const arg = try sema.resolveInst(arg_ref);
if (try sema.resolvePossiblyUndefinedValue(block, src, arg)) |val| {
try writer.print("@as({}, {})", .{ arg.ty, val });
} else {
try writer.print("@as({}, [runtime value])", .{arg.ty});
}
}
try writer.print("\n", .{});
const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, sema.owner_decl);
if (!gop.found_existing) {
gop.entry.value = src_node;
}
return sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.void),
.val = Value.initTag(.void_value),
});
}
fn zirRepeat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const src_node = sema.code.instructions.items(.data)[inst].node;
const src: LazySrcLoc = .{ .node_offset = src_node };
try sema.requireRuntimeBlock(block, src);
return always_noreturn;
}
fn zirPanic(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirPanic", .{});
//return always_noreturn;
}
fn zirLoop(sema: *Sema, parent_block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
const body = sema.code.extra[extra.end..][0..extra.data.body_len];
// AIR expects a block outside the loop block too.
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = undefined,
.src = src,
},
.body = undefined,
};
var label: Scope.Block.Label = .{
.zir_block = inst,
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
};
var child_block = parent_block.makeSubBlock();
child_block.label = &label;
const merges = &child_block.label.?.merges;
defer child_block.instructions.deinit(sema.gpa);
defer merges.results.deinit(sema.gpa);
defer merges.br_list.deinit(sema.gpa);
// Reserve space for a Loop instruction so that generated Break instructions can
// point to it, even if it doesn't end up getting used because the code ends up being
// comptime evaluated.
const loop_inst = try sema.arena.create(Inst.Loop);
loop_inst.* = .{
.base = .{
.tag = Inst.Loop.base_tag,
.ty = Type.initTag(.noreturn),
.src = src,
},
.body = undefined,
};
var loop_block = child_block.makeSubBlock();
defer loop_block.instructions.deinit(sema.gpa);
_ = try sema.analyzeBody(&loop_block, body);
// Loop repetition is implied so the last instruction may or may not be a noreturn instruction.
try child_block.instructions.append(sema.gpa, &loop_inst.base);
loop_inst.body = .{ .instructions = try sema.arena.dupe(*Inst, loop_block.instructions.items) };
return sema.analyzeBlockBody(parent_block, src, &child_block, merges);
}
fn zirCImport(sema: *Sema, parent_block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&parent_block.base, src, "TODO: implement Sema.zirCImport", .{});
}
fn zirSuspendBlock(sema: *Sema, parent_block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&parent_block.base, src, "TODO: implement Sema.zirSuspendBlock", .{});
}
fn zirBlock(sema: *Sema, parent_block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
const body = sema.code.extra[extra.end..][0..extra.data.body_len];
// Reserve space for a Block instruction so that generated Break instructions can
// point to it, even if it doesn't end up getting used because the code ends up being
// comptime evaluated.
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = undefined, // Set after analysis.
.src = src,
},
.body = undefined,
};
var label: Scope.Block.Label = .{
.zir_block = inst,
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
};
var child_block: Scope.Block = .{
.parent = parent_block,
.sema = sema,
.src_decl = parent_block.src_decl,
.instructions = .{},
.label = &label,
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
};
const merges = &child_block.label.?.merges;
defer child_block.instructions.deinit(sema.gpa);
defer merges.results.deinit(sema.gpa);
defer merges.br_list.deinit(sema.gpa);
_ = try sema.analyzeBody(&child_block, body);
return sema.analyzeBlockBody(parent_block, src, &child_block, merges);
}
fn resolveBlockBody(
sema: *Sema,
parent_block: *Scope.Block,
src: LazySrcLoc,
child_block: *Scope.Block,
body: []const Zir.Inst.Index,
merges: *Scope.Block.Merges,
) InnerError!*Inst {
_ = try sema.analyzeBody(child_block, body);
return sema.analyzeBlockBody(parent_block, src, child_block, merges);
}
fn analyzeBlockBody(
sema: *Sema,
parent_block: *Scope.Block,
src: LazySrcLoc,
child_block: *Scope.Block,
merges: *Scope.Block.Merges,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// Blocks must terminate with noreturn instruction.
assert(child_block.instructions.items.len != 0);
assert(child_block.instructions.items[child_block.instructions.items.len - 1].ty.isNoReturn());
if (merges.results.items.len == 0) {
// No need for a block instruction. We can put the new instructions
// directly into the parent block.
const copied_instructions = try sema.arena.dupe(*Inst, child_block.instructions.items);
try parent_block.instructions.appendSlice(sema.gpa, copied_instructions);
return copied_instructions[copied_instructions.len - 1];
}
if (merges.results.items.len == 1) {
const last_inst_index = child_block.instructions.items.len - 1;
const last_inst = child_block.instructions.items[last_inst_index];
if (last_inst.breakBlock()) |br_block| {
if (br_block == merges.block_inst) {
// No need for a block instruction. We can put the new instructions directly
// into the parent block. Here we omit the break instruction.
const copied_instructions = try sema.arena.dupe(*Inst, child_block.instructions.items[0..last_inst_index]);
try parent_block.instructions.appendSlice(sema.gpa, copied_instructions);
return merges.results.items[0];
}
}
}
// It is impossible to have the number of results be > 1 in a comptime scope.
assert(!child_block.is_comptime); // Should already got a compile error in the condbr condition.
// Need to set the type and emit the Block instruction. This allows machine code generation
// to emit a jump instruction to after the block when it encounters the break.
try parent_block.instructions.append(sema.gpa, &merges.block_inst.base);
const resolved_ty = try sema.resolvePeerTypes(parent_block, src, merges.results.items);
merges.block_inst.base.ty = resolved_ty;
merges.block_inst.body = .{
.instructions = try sema.arena.dupe(*Inst, child_block.instructions.items),
};
// Now that the block has its type resolved, we need to go back into all the break
// instructions, and insert type coercion on the operands.
for (merges.br_list.items) |br| {
if (br.operand.ty.eql(resolved_ty)) {
// No type coercion needed.
continue;
}
var coerce_block = parent_block.makeSubBlock();
defer coerce_block.instructions.deinit(sema.gpa);
const coerced_operand = try sema.coerce(&coerce_block, resolved_ty, br.operand, br.operand.src);
// If no instructions were produced, such as in the case of a coercion of a
// constant value to a new type, we can simply point the br operand to it.
if (coerce_block.instructions.items.len == 0) {
br.operand = coerced_operand;
continue;
}
assert(coerce_block.instructions.items[coerce_block.instructions.items.len - 1] == coerced_operand);
// Here we depend on the br instruction having been over-allocated (if necessary)
// inside zirBreak so that it can be converted into a br_block_flat instruction.
const br_src = br.base.src;
const br_ty = br.base.ty;
const br_block_flat = @ptrCast(*Inst.BrBlockFlat, br);
br_block_flat.* = .{
.base = .{
.src = br_src,
.ty = br_ty,
.tag = .br_block_flat,
},
.block = merges.block_inst,
.body = .{
.instructions = try sema.arena.dupe(*Inst, coerce_block.instructions.items),
},
};
}
return &merges.block_inst.base;
}
fn zirExport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;
const src = inst_data.src();
const lhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const decl_name = sema.code.nullTerminatedString(extra.decl_name);
const decl = try sema.lookupIdentifier(block, lhs_src, decl_name);
const options = try sema.resolveInstConst(block, rhs_src, extra.options);
const struct_obj = options.ty.castTag(.@"struct").?.data;
const fields = options.val.castTag(.@"struct").?.data[0..struct_obj.fields.count()];
const name_index = struct_obj.fields.getIndex("name").?;
const linkage_index = struct_obj.fields.getIndex("linkage").?;
const section_index = struct_obj.fields.getIndex("section").?;
const export_name = try fields[name_index].toAllocatedBytes(sema.arena);
const linkage = fields[linkage_index].toEnum(
struct_obj.fields.items()[linkage_index].value.ty,
std.builtin.GlobalLinkage,
);
if (linkage != .Strong) {
return sema.mod.fail(&block.base, src, "TODO: implement exporting with non-strong linkage", .{});
}
if (!fields[section_index].isNull()) {
return sema.mod.fail(&block.base, src, "TODO: implement exporting with linksection", .{});
}
try sema.mod.analyzeExport(&block.base, src, export_name, decl);
}
fn zirSetAlignStack(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirSetAlignStack", .{});
}
fn zirSetCold(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirSetCold", .{});
}
fn zirSetFloatMode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirSetFloatMode", .{});
}
fn zirSetRuntimeSafety(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirSetRuntimeSafety", .{});
}
fn zirBreakpoint(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const src_node = sema.code.instructions.items(.data)[inst].node;
const src: LazySrcLoc = .{ .node_offset = src_node };
try sema.requireRuntimeBlock(block, src);
_ = try block.addNoOp(src, Type.initTag(.void), .breakpoint);
}
fn zirFence(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const src_node = sema.code.instructions.items(.data)[inst].node;
const src: LazySrcLoc = .{ .node_offset = src_node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirFence", .{});
}
fn zirBreak(sema: *Sema, start_block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].@"break";
const src = sema.src;
const operand = try sema.resolveInst(inst_data.operand);
const zir_block = inst_data.block_inst;
var block = start_block;
while (true) {
if (block.label) |label| {
if (label.zir_block == zir_block) {
// Here we add a br instruction, but we over-allocate a little bit
// (if necessary) to make it possible to convert the instruction into
// a br_block_flat instruction later.
const br = @ptrCast(*Inst.Br, try sema.arena.alignedAlloc(
u8,
Inst.convertable_br_align,
Inst.convertable_br_size,
));
br.* = .{
.base = .{
.tag = .br,
.ty = Type.initTag(.noreturn),
.src = src,
},
.operand = operand,
.block = label.merges.block_inst,
};
try start_block.instructions.append(sema.gpa, &br.base);
try label.merges.results.append(sema.gpa, operand);
try label.merges.br_list.append(sema.gpa, br);
return inst;
}
}
block = block.parent.?;
}
}
fn zirDbgStmt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
// We do not set sema.src here because dbg_stmt instructions are only emitted for
// ZIR code that possibly will need to generate runtime code. So error messages
// and other source locations must not rely on sema.src being set from dbg_stmt
// instructions.
if (block.is_comptime) return;
const inst_data = sema.code.instructions.items(.data)[inst].dbg_stmt;
_ = try block.addDbgStmt(.unneeded, inst_data.line, inst_data.column);
}
fn zirDeclRef(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const decl_name = inst_data.get(sema.code);
const decl = try sema.lookupIdentifier(block, src, decl_name);
return sema.analyzeDeclRef(block, src, decl);
}
fn zirDeclVal(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const decl_name = inst_data.get(sema.code);
const decl = try sema.lookupIdentifier(block, src, decl_name);
return sema.analyzeDeclVal(block, src, decl);
}
fn lookupIdentifier(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, name: []const u8) !*Decl {
// TODO emit a compile error if more than one decl would be matched.
var namespace = sema.namespace;
while (true) {
if (try sema.lookupInNamespace(namespace, name)) |decl| {
return decl;
}
namespace = namespace.parent orelse break;
}
return sema.mod.fail(&block.base, src, "use of undeclared identifier '{s}'", .{name});
}
/// This looks up a member of a specific namespace. It is affected by `usingnamespace` but
/// only for ones in the specified namespace.
fn lookupInNamespace(
sema: *Sema,
namespace: *Scope.Namespace,
ident_name: []const u8,
) InnerError!?*Decl {
const namespace_decl = namespace.getDecl();
if (namespace_decl.analysis == .file_failure) {
try sema.mod.declareDeclDependency(sema.owner_decl, namespace_decl);
return error.AnalysisFail;
}
// TODO implement usingnamespace
if (namespace.decls.get(ident_name)) |decl| {
try sema.mod.declareDeclDependency(sema.owner_decl, decl);
return decl;
}
log.debug("{*} ({s}) depends on non-existence of '{s}' in {*} ({s})", .{
sema.owner_decl, sema.owner_decl.name, ident_name, namespace_decl, namespace_decl.name,
});
// TODO This dependency is too strong. Really, it should only be a dependency
// on the non-existence of `ident_name` in the namespace. We can lessen the number of
// outdated declarations by making this dependency more sophisticated.
try sema.mod.declareDeclDependency(sema.owner_decl, namespace_decl);
return null;
}
fn zirCall(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
modifier: std.builtin.CallOptions.Modifier,
ensure_result_used: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const func_src: LazySrcLoc = .{ .node_offset_call_func = inst_data.src_node };
const call_src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Call, inst_data.payload_index);
const args = sema.code.refSlice(extra.end, extra.data.args_len);
return sema.analyzeCall(block, extra.data.callee, func_src, call_src, modifier, ensure_result_used, args);
}
fn analyzeCall(
sema: *Sema,
block: *Scope.Block,
zir_func: Zir.Inst.Ref,
func_src: LazySrcLoc,
call_src: LazySrcLoc,
modifier: std.builtin.CallOptions.Modifier,
ensure_result_used: bool,
zir_args: []const Zir.Inst.Ref,
) InnerError!*ir.Inst {
const func = try sema.resolveInst(zir_func);
if (func.ty.zigTypeTag() != .Fn)
return sema.mod.fail(&block.base, func_src, "type '{}' not a function", .{func.ty});
const cc = func.ty.fnCallingConvention();
if (cc == .Naked) {
// TODO add error note: declared here
return sema.mod.fail(
&block.base,
func_src,
"unable to call function with naked calling convention",
.{},
);
}
const fn_params_len = func.ty.fnParamLen();
if (func.ty.fnIsVarArgs()) {
assert(cc == .C);
if (zir_args.len < fn_params_len) {
// TODO add error note: declared here
return sema.mod.fail(
&block.base,
func_src,
"expected at least {d} argument(s), found {d}",
.{ fn_params_len, zir_args.len },
);
}
} else if (fn_params_len != zir_args.len) {
// TODO add error note: declared here
return sema.mod.fail(
&block.base,
func_src,
"expected {d} argument(s), found {d}",
.{ fn_params_len, zir_args.len },
);
}
switch (modifier) {
.auto,
.always_inline,
.compile_time,
=> {},
.async_kw,
.never_tail,
.never_inline,
.no_async,
.always_tail,
=> return sema.mod.fail(&block.base, call_src, "TODO implement call with modifier {}", .{
modifier,
}),
}
// TODO handle function calls of generic functions
const casted_args = try sema.arena.alloc(*Inst, zir_args.len);
for (zir_args) |zir_arg, i| {
// the args are already casted to the result of a param type instruction.
casted_args[i] = try sema.resolveInst(zir_arg);
}
const ret_type = func.ty.fnReturnType();
const is_comptime_call = block.is_comptime or modifier == .compile_time;
const is_inline_call = is_comptime_call or modifier == .always_inline or
func.ty.fnCallingConvention() == .Inline;
const result: *Inst = if (is_inline_call) res: {
const func_val = try sema.resolveConstValue(block, func_src, func);
const module_fn = switch (func_val.tag()) {
.function => func_val.castTag(.function).?.data,
.extern_fn => return sema.mod.fail(&block.base, call_src, "{s} call of extern function", .{
@as([]const u8, if (is_comptime_call) "comptime" else "inline"),
}),
else => unreachable,
};
// Analyze the ZIR. The same ZIR gets analyzed into a runtime function
// or an inlined call depending on what union tag the `label` field is
// set to in the `Scope.Block`.
// This block instruction will be used to capture the return value from the
// inlined function.
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = ret_type,
.src = call_src,
},
.body = undefined,
};
// This one is shared among sub-blocks within the same callee, but not
// shared among the entire inline/comptime call stack.
var inlining: Scope.Block.Inlining = .{
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
};
// In order to save a bit of stack space, directly modify Sema rather
// than create a child one.
const parent_zir = sema.code;
sema.code = module_fn.owner_decl.namespace.file_scope.zir;
defer sema.code = parent_zir;
const parent_inst_map = sema.inst_map;
sema.inst_map = .{};
defer {
sema.inst_map.deinit(sema.gpa);
sema.inst_map = parent_inst_map;
}
const parent_namespace = sema.namespace;
sema.namespace = module_fn.owner_decl.namespace;
defer sema.namespace = parent_namespace;
const parent_func = sema.func;
sema.func = module_fn;
defer sema.func = parent_func;
const parent_param_inst_list = sema.param_inst_list;
sema.param_inst_list = casted_args;
defer sema.param_inst_list = parent_param_inst_list;
const parent_next_arg_index = sema.next_arg_index;
sema.next_arg_index = 0;
defer sema.next_arg_index = parent_next_arg_index;
var child_block: Scope.Block = .{
.parent = null,
.sema = sema,
.src_decl = module_fn.owner_decl,
.instructions = .{},
.label = null,
.inlining = &inlining,
.is_comptime = is_comptime_call,
};
const merges = &child_block.inlining.?.merges;
defer child_block.instructions.deinit(sema.gpa);
defer merges.results.deinit(sema.gpa);
defer merges.br_list.deinit(sema.gpa);
try sema.emitBackwardBranch(&child_block, call_src);
// This will have return instructions analyzed as break instructions to
// the block_inst above.
try sema.analyzeFnBody(&child_block, module_fn.zir_body_inst);
const result = try sema.analyzeBlockBody(block, call_src, &child_block, merges);
break :res result;
} else res: {
try sema.requireRuntimeBlock(block, call_src);
break :res try block.addCall(call_src, ret_type, func, casted_args);
};
if (ensure_result_used) {
try sema.ensureResultUsed(block, result, call_src);
}
return result;
}
fn zirIntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const int_type = sema.code.instructions.items(.data)[inst].int_type;
const src = int_type.src();
const ty = try Module.makeIntType(sema.arena, int_type.signedness, int_type.bit_count);
return sema.mod.constType(sema.arena, src, ty);
}
fn zirOptionalType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const child_type = try sema.resolveType(block, src, inst_data.operand);
const opt_type = try sema.mod.optionalType(sema.arena, child_type);
return sema.mod.constType(sema.arena, src, opt_type);
}
fn zirElemType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const array_type = try sema.resolveType(block, src, inst_data.operand);
const elem_type = array_type.elemType();
return sema.mod.constType(sema.arena, src, elem_type);
}
fn zirVectorType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const elem_type_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const len = try sema.resolveAlreadyCoercedInt(block, len_src, extra.lhs, u32);
const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);
const vector_type = try Type.Tag.vector.create(sema.arena, .{
.len = len,
.elem_type = elem_type,
});
return sema.mod.constType(sema.arena, src, vector_type);
}
fn zirArrayType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// TODO these should be lazily evaluated
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const len = try sema.resolveInstConst(block, .unneeded, bin_inst.lhs);
const elem_type = try sema.resolveType(block, .unneeded, bin_inst.rhs);
const array_ty = try sema.mod.arrayType(sema.arena, len.val.toUnsignedInt(), null, elem_type);
return sema.mod.constType(sema.arena, .unneeded, array_ty);
}
fn zirArrayTypeSentinel(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// TODO these should be lazily evaluated
const inst_data = sema.code.instructions.items(.data)[inst].array_type_sentinel;
const len = try sema.resolveInstConst(block, .unneeded, inst_data.len);
const extra = sema.code.extraData(Zir.Inst.ArrayTypeSentinel, inst_data.payload_index).data;
const sentinel = try sema.resolveInstConst(block, .unneeded, extra.sentinel);
const elem_type = try sema.resolveType(block, .unneeded, extra.elem_type);
const array_ty = try sema.mod.arrayType(sema.arena, len.val.toUnsignedInt(), sentinel.val, elem_type);
return sema.mod.constType(sema.arena, .unneeded, array_ty);
}
fn zirAnyframeType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_anyframe_type = inst_data.src_node };
const return_type = try sema.resolveType(block, operand_src, inst_data.operand);
const anyframe_type = try Type.Tag.anyframe_T.create(sema.arena, return_type);
return sema.mod.constType(sema.arena, src, anyframe_type);
}
fn zirErrorUnionType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const error_union = try sema.resolveType(block, lhs_src, extra.lhs);
const payload = try sema.resolveType(block, rhs_src, extra.rhs);
if (error_union.zigTypeTag() != .ErrorSet) {
return sema.mod.fail(&block.base, lhs_src, "expected error set type, found {}", .{
error_union.elemType(),
});
}
const err_union_ty = try sema.mod.errorUnionType(sema.arena, error_union, payload);
return sema.mod.constType(sema.arena, src, err_union_ty);
}
fn zirErrorValue(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
// Create an anonymous error set type with only this error value, and return the value.
const entry = try sema.mod.getErrorValue(inst_data.get(sema.code));
const result_type = try Type.Tag.error_set_single.create(sema.arena, entry.key);
return sema.mod.constInst(sema.arena, src, .{
.ty = result_type,
.val = try Value.Tag.@"error".create(sema.arena, .{
.name = entry.key,
}),
});
}
fn zirErrorToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const op = try sema.resolveInst(inst_data.operand);
const op_coerced = try sema.coerce(block, Type.initTag(.anyerror), op, operand_src);
const result_ty = Type.initTag(.u16);
if (try sema.resolvePossiblyUndefinedValue(block, src, op_coerced)) |val| {
if (val.isUndef()) {
return sema.mod.constUndef(sema.arena, src, result_ty);
}
const payload = try sema.arena.create(Value.Payload.U64);
payload.* = .{
.base = .{ .tag = .int_u64 },
.data = (try sema.mod.getErrorValue(val.castTag(.@"error").?.data.name)).value,
};
return sema.mod.constInst(sema.arena, src, .{
.ty = result_ty,
.val = Value.initPayload(&payload.base),
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, result_ty, .error_to_int, op_coerced);
}
fn zirIntToError(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const op = try sema.resolveInst(inst_data.operand);
if (try sema.resolveDefinedValue(block, operand_src, op)) |value| {
const int = value.toUnsignedInt();
if (int > sema.mod.global_error_set.count() or int == 0)
return sema.mod.fail(&block.base, operand_src, "integer value {d} represents no error", .{int});
const payload = try sema.arena.create(Value.Payload.Error);
payload.* = .{
.base = .{ .tag = .@"error" },
.data = .{ .name = sema.mod.error_name_list.items[int] },
};
return sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.anyerror),
.val = Value.initPayload(&payload.base),
});
}
try sema.requireRuntimeBlock(block, src);
if (block.wantSafety()) {
return sema.mod.fail(&block.base, src, "TODO: get max errors in compilation", .{});
// const is_gt_max = @panic("TODO get max errors in compilation");
// try sema.addSafetyCheck(block, is_gt_max, .invalid_error_code);
}
return block.addUnOp(src, Type.initTag(.anyerror), .int_to_error, op);
}
fn zirMergeErrorSets(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const lhs_ty = try sema.resolveType(block, lhs_src, extra.lhs);
const rhs_ty = try sema.resolveType(block, rhs_src, extra.rhs);
if (rhs_ty.zigTypeTag() != .ErrorSet)
return sema.mod.fail(&block.base, rhs_src, "expected error set type, found {}", .{rhs_ty});
if (lhs_ty.zigTypeTag() != .ErrorSet)
return sema.mod.fail(&block.base, lhs_src, "expected error set type, found {}", .{lhs_ty});
// Anything merged with anyerror is anyerror.
if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror) {
return sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.type),
.val = Value.initTag(.anyerror_type),
});
}
// When we support inferred error sets, we'll want to use a data structure that can
// represent a merged set of errors without forcing them to be resolved here. Until then
// we re-use the same data structure that is used for explicit error set declarations.
var set: std.StringHashMapUnmanaged(void) = .{};
defer set.deinit(sema.gpa);
switch (lhs_ty.tag()) {
.error_set_single => {
const name = lhs_ty.castTag(.error_set_single).?.data;
try set.put(sema.gpa, name, {});
},
.error_set => {
const lhs_set = lhs_ty.castTag(.error_set).?.data;
try set.ensureCapacity(sema.gpa, set.count() + lhs_set.names_len);
for (lhs_set.names_ptr[0..lhs_set.names_len]) |name| {
set.putAssumeCapacityNoClobber(name, {});
}
},
else => unreachable,
}
switch (rhs_ty.tag()) {
.error_set_single => {
const name = rhs_ty.castTag(.error_set_single).?.data;
try set.put(sema.gpa, name, {});
},
.error_set => {
const rhs_set = rhs_ty.castTag(.error_set).?.data;
try set.ensureCapacity(sema.gpa, set.count() + rhs_set.names_len);
for (rhs_set.names_ptr[0..rhs_set.names_len]) |name| {
set.putAssumeCapacity(name, {});
}
},
else => unreachable,
}
const new_names = try sema.arena.alloc([]const u8, set.count());
var it = set.iterator();
var i: usize = 0;
while (it.next()) |entry| : (i += 1) {
new_names[i] = entry.key;
}
const new_error_set = try sema.arena.create(Module.ErrorSet);
new_error_set.* = .{
.owner_decl = sema.owner_decl,
.node_offset = inst_data.src_node,
.names_ptr = new_names.ptr,
.names_len = @intCast(u32, new_names.len),
};
const error_set_ty = try Type.Tag.error_set.create(sema.arena, new_error_set);
return sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.type),
.val = try Value.Tag.ty.create(sema.arena, error_set_ty),
});
}
fn zirEnumLiteral(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const duped_name = try sema.arena.dupe(u8, inst_data.get(sema.code));
return sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.enum_literal),
.val = try Value.Tag.enum_literal.create(sema.arena, duped_name),
});
}
fn zirEnumToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const mod = sema.mod;
const arena = sema.arena;
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand = try sema.resolveInst(inst_data.operand);
const enum_tag: *Inst = switch (operand.ty.zigTypeTag()) {
.Enum => operand,
.Union => {
//if (!operand.ty.unionHasTag()) {
// return mod.fail(
// &block.base,
// operand_src,
// "untagged union '{}' cannot be converted to integer",
// .{dest_ty_src},
// );
//}
return mod.fail(&block.base, operand_src, "TODO zirEnumToInt for tagged unions", .{});
},
else => {
return mod.fail(&block.base, operand_src, "expected enum or tagged union, found {}", .{
operand.ty,
});
},
};
var int_tag_type_buffer: Type.Payload.Bits = undefined;
const int_tag_ty = try enum_tag.ty.intTagType(&int_tag_type_buffer).copy(arena);
if (try sema.typeHasOnePossibleValue(block, src, enum_tag.ty)) |opv| {
return mod.constInst(arena, src, .{
.ty = int_tag_ty,
.val = opv,
});
}
if (enum_tag.value()) |enum_tag_val| {
if (enum_tag_val.castTag(.enum_field_index)) |enum_field_payload| {
const field_index = enum_field_payload.data;
switch (enum_tag.ty.tag()) {
.enum_full => {
const enum_full = enum_tag.ty.castTag(.enum_full).?.data;
if (enum_full.values.count() != 0) {
const val = enum_full.values.entries.items[field_index].key;
return mod.constInst(arena, src, .{
.ty = int_tag_ty,
.val = val,
});
} else {
// Field index and integer values are the same.
const val = try Value.Tag.int_u64.create(arena, field_index);
return mod.constInst(arena, src, .{
.ty = int_tag_ty,
.val = val,
});
}
},
.enum_simple => {
// Field index and integer values are the same.
const val = try Value.Tag.int_u64.create(arena, field_index);
return mod.constInst(arena, src, .{
.ty = int_tag_ty,
.val = val,
});
},
else => unreachable,
}
} else {
// Assume it is already an integer and return it directly.
return mod.constInst(arena, src, .{
.ty = int_tag_ty,
.val = enum_tag_val,
});
}
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, int_tag_ty, .bitcast, enum_tag);
}
fn zirIntToEnum(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const mod = sema.mod;
const target = mod.getTarget();
const arena = sema.arena;
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src = inst_data.src();
const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
const operand = try sema.resolveInst(extra.rhs);
if (dest_ty.zigTypeTag() != .Enum) {
return mod.fail(&block.base, dest_ty_src, "expected enum, found {}", .{dest_ty});
}
if (dest_ty.isNonexhaustiveEnum()) {
if (operand.value()) |int_val| {
return mod.constInst(arena, src, .{
.ty = dest_ty,
.val = int_val,
});
}
}
if (try sema.resolveDefinedValue(block, operand_src, operand)) |int_val| {
if (!dest_ty.enumHasInt(int_val, target)) {
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
src,
"enum '{}' has no tag with value {}",
.{ dest_ty, int_val },
);
errdefer msg.destroy(sema.gpa);
try mod.errNoteNonLazy(
dest_ty.declSrcLoc(),
msg,
"enum declared here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
return mod.constInst(arena, src, .{
.ty = dest_ty,
.val = int_val,
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, dest_ty, .bitcast, operand);
}
/// Pointer in, pointer out.
fn zirOptionalPayloadPtr(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const optional_ptr = try sema.resolveInst(inst_data.operand);
assert(optional_ptr.ty.zigTypeTag() == .Pointer);
const src = inst_data.src();
const opt_type = optional_ptr.ty.elemType();
if (opt_type.zigTypeTag() != .Optional) {
return sema.mod.fail(&block.base, src, "expected optional type, found {}", .{opt_type});
}
const child_type = try opt_type.optionalChildAlloc(sema.arena);
const child_pointer = try sema.mod.simplePtrType(sema.arena, child_type, !optional_ptr.ty.isConstPtr(), .One);
if (optional_ptr.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(sema.arena);
if (val.isNull()) {
return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
}
// The same Value represents the pointer to the optional and the payload.
return sema.mod.constInst(sema.arena, src, .{
.ty = child_pointer,
.val = pointer_val,
});
}
try sema.requireRuntimeBlock(block, src);
if (safety_check and block.wantSafety()) {
const is_non_null = try block.addUnOp(src, Type.initTag(.bool), .is_non_null_ptr, optional_ptr);
try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
}
return block.addUnOp(src, child_pointer, .optional_payload_ptr, optional_ptr);
}
/// Value in, value out.
fn zirOptionalPayload(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
const opt_type = operand.ty;
if (opt_type.zigTypeTag() != .Optional) {
return sema.mod.fail(&block.base, src, "expected optional type, found {}", .{opt_type});
}
const child_type = try opt_type.optionalChildAlloc(sema.arena);
if (operand.value()) |val| {
if (val.isNull()) {
return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
}
return sema.mod.constInst(sema.arena, src, .{
.ty = child_type,
.val = val,
});
}
try sema.requireRuntimeBlock(block, src);
if (safety_check and block.wantSafety()) {
const is_non_null = try block.addUnOp(src, Type.initTag(.bool), .is_non_null, operand);
try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
}
return block.addUnOp(src, child_type, .optional_payload, operand);
}
/// Value in, value out
fn zirErrUnionPayload(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return sema.mod.fail(&block.base, operand.src, "expected error union type, found '{}'", .{operand.ty});
if (operand.value()) |val| {
if (val.getError()) |name| {
return sema.mod.fail(&block.base, src, "caught unexpected error '{s}'", .{name});
}
const data = val.castTag(.error_union).?.data;
return sema.mod.constInst(sema.arena, src, .{
.ty = operand.ty.castTag(.error_union).?.data.payload,
.val = data,
});
}
try sema.requireRuntimeBlock(block, src);
if (safety_check and block.wantSafety()) {
const is_non_err = try block.addUnOp(src, Type.initTag(.bool), .is_err, operand);
try sema.addSafetyCheck(block, is_non_err, .unwrap_errunion);
}
return block.addUnOp(src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_payload, operand);
}
/// Pointer in, pointer out.
fn zirErrUnionPayloadPtr(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
assert(operand.ty.zigTypeTag() == .Pointer);
if (operand.ty.elemType().zigTypeTag() != .ErrorUnion)
return sema.mod.fail(&block.base, src, "expected error union type, found {}", .{operand.ty.elemType()});
const operand_pointer_ty = try sema.mod.simplePtrType(sema.arena, operand.ty.elemType().castTag(.error_union).?.data.payload, !operand.ty.isConstPtr(), .One);
if (operand.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(sema.arena);
if (val.getError()) |name| {
return sema.mod.fail(&block.base, src, "caught unexpected error '{s}'", .{name});
}
const data = val.castTag(.error_union).?.data;
// The same Value represents the pointer to the error union and the payload.
return sema.mod.constInst(sema.arena, src, .{
.ty = operand_pointer_ty,
.val = try Value.Tag.ref_val.create(
sema.arena,
data,
),
});
}
try sema.requireRuntimeBlock(block, src);
if (safety_check and block.wantSafety()) {
const is_non_err = try block.addUnOp(src, Type.initTag(.bool), .is_err, operand);
try sema.addSafetyCheck(block, is_non_err, .unwrap_errunion);
}
return block.addUnOp(src, operand_pointer_ty, .unwrap_errunion_payload_ptr, operand);
}
/// Value in, value out
fn zirErrUnionCode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return sema.mod.fail(&block.base, src, "expected error union type, found '{}'", .{operand.ty});
if (operand.value()) |val| {
assert(val.getError() != null);
const data = val.castTag(.error_union).?.data;
return sema.mod.constInst(sema.arena, src, .{
.ty = operand.ty.castTag(.error_union).?.data.error_set,
.val = data,
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_err, operand);
}
/// Pointer in, value out
fn zirErrUnionCodePtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
assert(operand.ty.zigTypeTag() == .Pointer);
if (operand.ty.elemType().zigTypeTag() != .ErrorUnion)
return sema.mod.fail(&block.base, src, "expected error union type, found {}", .{operand.ty.elemType()});
if (operand.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(sema.arena);
assert(val.getError() != null);
const data = val.castTag(.error_union).?.data;
return sema.mod.constInst(sema.arena, src, .{
.ty = operand.ty.elemType().castTag(.error_union).?.data.error_set,
.val = data,
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_err_ptr, operand);
}
fn zirEnsureErrPayloadVoid(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return sema.mod.fail(&block.base, src, "expected error union type, found '{}'", .{operand.ty});
if (operand.ty.castTag(.error_union).?.data.payload.zigTypeTag() != .Void) {
return sema.mod.fail(&block.base, src, "expression value is ignored", .{});
}
}
fn zirFunc(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
inferred_error_set: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
const param_types = sema.code.refSlice(extra.end, extra.data.param_types_len);
var body_inst: Zir.Inst.Index = 0;
var src_locs: Zir.Inst.Func.SrcLocs = undefined;
if (extra.data.body_len != 0) {
body_inst = inst;
const extra_index = extra.end + extra.data.param_types_len + extra.data.body_len;
src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
}
const cc: std.builtin.CallingConvention = if (sema.owner_decl.is_exported)
.C
else
.Unspecified;
return sema.funcCommon(
block,
inst_data.src_node,
param_types,
body_inst,
extra.data.return_type,
cc,
Value.initTag(.null_value),
false,
inferred_error_set,
false,
src_locs,
null,
);
}
fn funcCommon(
sema: *Sema,
block: *Scope.Block,
src_node_offset: i32,
zir_param_types: []const Zir.Inst.Ref,
body_inst: Zir.Inst.Index,
zir_return_type: Zir.Inst.Ref,
cc: std.builtin.CallingConvention,
align_val: Value,
var_args: bool,
inferred_error_set: bool,
is_extern: bool,
src_locs: Zir.Inst.Func.SrcLocs,
opt_lib_name: ?[]const u8,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = src_node_offset };
const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = src_node_offset };
const return_type = try sema.resolveType(block, ret_ty_src, zir_return_type);
const mod = sema.mod;
const fn_ty: Type = fn_ty: {
// Hot path for some common function types.
if (zir_param_types.len == 0 and !var_args and align_val.tag() == .null_value) {
if (return_type.zigTypeTag() == .NoReturn and cc == .Unspecified) {
break :fn_ty Type.initTag(.fn_noreturn_no_args);
}
if (return_type.zigTypeTag() == .Void and cc == .Unspecified) {
break :fn_ty Type.initTag(.fn_void_no_args);
}
if (return_type.zigTypeTag() == .NoReturn and cc == .Naked) {
break :fn_ty Type.initTag(.fn_naked_noreturn_no_args);
}
if (return_type.zigTypeTag() == .Void and cc == .C) {
break :fn_ty Type.initTag(.fn_ccc_void_no_args);
}
}
const param_types = try sema.arena.alloc(Type, zir_param_types.len);
for (zir_param_types) |param_type, i| {
// TODO make a compile error from `resolveType` report the source location
// of the specific parameter. Will need to take a similar strategy as
// `resolveSwitchItemVal` to avoid resolving the source location unless
// we actually need to report an error.
param_types[i] = try sema.resolveType(block, src, param_type);
}
if (align_val.tag() != .null_value) {
return mod.fail(&block.base, src, "TODO implement support for function prototypes to have alignment specified", .{});
}
break :fn_ty try Type.Tag.function.create(sema.arena, .{
.param_types = param_types,
.return_type = return_type,
.cc = cc,
.is_var_args = var_args,
});
};
if (opt_lib_name) |lib_name| blk: {
const lib_name_src: LazySrcLoc = .{ .node_offset_lib_name = src_node_offset };
log.debug("extern fn symbol expected in lib '{s}'", .{lib_name});
mod.comp.stage1AddLinkLib(lib_name) catch |err| {
return mod.fail(&block.base, lib_name_src, "unable to add link lib '{s}': {s}", .{
lib_name, @errorName(err),
});
};
const target = mod.getTarget();
if (target_util.is_libc_lib_name(target, lib_name)) {
if (!mod.comp.bin_file.options.link_libc) {
return mod.fail(
&block.base,
lib_name_src,
"dependency on libc must be explicitly specified in the build command",
.{},
);
}
break :blk;
}
if (target_util.is_libcpp_lib_name(target, lib_name)) {
if (!mod.comp.bin_file.options.link_libcpp) {
return mod.fail(
&block.base,
lib_name_src,
"dependency on libc++ must be explicitly specified in the build command",
.{},
);
}
break :blk;
}
if (!target.isWasm() and !mod.comp.bin_file.options.pic) {
return mod.fail(
&block.base,
lib_name_src,
"dependency on dynamic library '{s}' requires enabling Position Independent Code. Fixed by `-l{s}` or `-fPIC`.",
.{ lib_name, lib_name },
);
}
}
if (is_extern) {
return sema.mod.constInst(sema.arena, src, .{
.ty = fn_ty,
.val = try Value.Tag.extern_fn.create(sema.arena, sema.owner_decl),
});
}
if (body_inst == 0) {
return mod.constType(sema.arena, src, fn_ty);
}
const is_inline = fn_ty.fnCallingConvention() == .Inline;
const anal_state: Module.Fn.Analysis = if (is_inline) .inline_only else .queued;
const fn_payload = try sema.arena.create(Value.Payload.Function);
const new_func = try sema.gpa.create(Module.Fn);
new_func.* = .{
.state = anal_state,
.zir_body_inst = body_inst,
.owner_decl = sema.owner_decl,
.body = undefined,
.lbrace_line = src_locs.lbrace_line,
.rbrace_line = src_locs.rbrace_line,
.lbrace_column = @truncate(u16, src_locs.columns),
.rbrace_column = @truncate(u16, src_locs.columns >> 16),
};
fn_payload.* = .{
.base = .{ .tag = .function },
.data = new_func,
};
const result = try sema.mod.constInst(sema.arena, src, .{
.ty = fn_ty,
.val = Value.initPayload(&fn_payload.base),
});
return result;
}
fn zirAs(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
return sema.analyzeAs(block, .unneeded, bin_inst.lhs, bin_inst.rhs);
}
fn zirAsNode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.As, inst_data.payload_index).data;
return sema.analyzeAs(block, src, extra.dest_type, extra.operand);
}
fn analyzeAs(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
zir_dest_type: Zir.Inst.Ref,
zir_operand: Zir.Inst.Ref,
) InnerError!*Inst {
const dest_type = try sema.resolveType(block, src, zir_dest_type);
const operand = try sema.resolveInst(zir_operand);
return sema.coerce(block, dest_type, operand, src);
}
fn zirPtrToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const ptr = try sema.resolveInst(inst_data.operand);
if (ptr.ty.zigTypeTag() != .Pointer) {
const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
return sema.mod.fail(&block.base, ptr_src, "expected pointer, found '{}'", .{ptr.ty});
}
// TODO handle known-pointer-address
const src = inst_data.src();
try sema.requireRuntimeBlock(block, src);
const ty = Type.initTag(.usize);
return block.addUnOp(src, ty, .ptrtoint, ptr);
}
fn zirFieldVal(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
const field_name = sema.code.nullTerminatedString(extra.field_name_start);
const object = try sema.resolveInst(extra.lhs);
const object_ptr = if (object.ty.zigTypeTag() == .Pointer)
object
else
try sema.analyzeRef(block, src, object);
const result_ptr = try sema.namedFieldPtr(block, src, object_ptr, field_name, field_name_src);
return sema.analyzeLoad(block, src, result_ptr, result_ptr.src);
}
fn zirFieldPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
const field_name = sema.code.nullTerminatedString(extra.field_name_start);
const object_ptr = try sema.resolveInst(extra.lhs);
return sema.namedFieldPtr(block, src, object_ptr, field_name, field_name_src);
}
fn zirFieldValNamed(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const field_name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
const object = try sema.resolveInst(extra.lhs);
const field_name = try sema.resolveConstString(block, field_name_src, extra.field_name);
const object_ptr = try sema.analyzeRef(block, src, object);
const result_ptr = try sema.namedFieldPtr(block, src, object_ptr, field_name, field_name_src);
return sema.analyzeLoad(block, src, result_ptr, src);
}
fn zirFieldPtrNamed(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const field_name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
const object_ptr = try sema.resolveInst(extra.lhs);
const field_name = try sema.resolveConstString(block, field_name_src, extra.field_name);
return sema.namedFieldPtr(block, src, object_ptr, field_name, field_name_src);
}
fn zirIntCast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const dest_type = try sema.resolveType(block, dest_ty_src, extra.lhs);
const operand = try sema.resolveInst(extra.rhs);
const dest_is_comptime_int = switch (dest_type.zigTypeTag()) {
.ComptimeInt => true,
.Int => false,
else => return sema.mod.fail(
&block.base,
dest_ty_src,
"expected integer type, found '{}'",
.{dest_type},
),
};
switch (operand.ty.zigTypeTag()) {
.ComptimeInt, .Int => {},
else => return sema.mod.fail(
&block.base,
operand_src,
"expected integer type, found '{}'",
.{operand.ty},
),
}
if (operand.value() != null) {
return sema.coerce(block, dest_type, operand, operand_src);
} else if (dest_is_comptime_int) {
return sema.mod.fail(&block.base, src, "unable to cast runtime value to 'comptime_int'", .{});
}
return sema.mod.fail(&block.base, src, "TODO implement analyze widen or shorten int", .{});
}
fn zirBitcast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const dest_type = try sema.resolveType(block, dest_ty_src, extra.lhs);
const operand = try sema.resolveInst(extra.rhs);
return sema.bitcast(block, dest_type, operand);
}
fn zirFloatCast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const dest_type = try sema.resolveType(block, dest_ty_src, extra.lhs);
const operand = try sema.resolveInst(extra.rhs);
const dest_is_comptime_float = switch (dest_type.zigTypeTag()) {
.ComptimeFloat => true,
.Float => false,
else => return sema.mod.fail(
&block.base,
dest_ty_src,
"expected float type, found '{}'",
.{dest_type},
),
};
switch (operand.ty.zigTypeTag()) {
.ComptimeFloat, .Float, .ComptimeInt => {},
else => return sema.mod.fail(
&block.base,
operand_src,
"expected float type, found '{}'",
.{operand.ty},
),
}
if (operand.value() != null) {
return sema.coerce(block, dest_type, operand, operand_src);
} else if (dest_is_comptime_float) {
return sema.mod.fail(&block.base, src, "unable to cast runtime value to 'comptime_float'", .{});
}
return sema.mod.fail(&block.base, src, "TODO implement analyze widen or shorten float", .{});
}
fn zirElemVal(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const array = try sema.resolveInst(bin_inst.lhs);
const array_ptr = if (array.ty.zigTypeTag() == .Pointer)
array
else
try sema.analyzeRef(block, sema.src, array);
const elem_index = try sema.resolveInst(bin_inst.rhs);
const result_ptr = try sema.elemPtr(block, sema.src, array_ptr, elem_index, sema.src);
return sema.analyzeLoad(block, sema.src, result_ptr, sema.src);
}
fn zirElemValNode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const elem_index_src: LazySrcLoc = .{ .node_offset_array_access_index = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const array = try sema.resolveInst(extra.lhs);
const array_ptr = if (array.ty.zigTypeTag() == .Pointer)
array
else
try sema.analyzeRef(block, src, array);
const elem_index = try sema.resolveInst(extra.rhs);
const result_ptr = try sema.elemPtr(block, src, array_ptr, elem_index, elem_index_src);
return sema.analyzeLoad(block, src, result_ptr, src);
}
fn zirElemPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const array_ptr = try sema.resolveInst(bin_inst.lhs);
const elem_index = try sema.resolveInst(bin_inst.rhs);
return sema.elemPtr(block, sema.src, array_ptr, elem_index, sema.src);
}
fn zirElemPtrNode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const elem_index_src: LazySrcLoc = .{ .node_offset_array_access_index = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const array_ptr = try sema.resolveInst(extra.lhs);
const elem_index = try sema.resolveInst(extra.rhs);
return sema.elemPtr(block, src, array_ptr, elem_index, elem_index_src);
}
fn zirSliceStart(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.SliceStart, inst_data.payload_index).data;
const array_ptr = try sema.resolveInst(extra.lhs);
const start = try sema.resolveInst(extra.start);
return sema.analyzeSlice(block, src, array_ptr, start, null, null, .unneeded);
}
fn zirSliceEnd(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const extra = sema.code.extraData(Zir.Inst.SliceEnd, inst_data.payload_index).data;
const array_ptr = try sema.resolveInst(extra.lhs);
const start = try sema.resolveInst(extra.start);
const end = try sema.resolveInst(extra.end);
return sema.analyzeSlice(block, src, array_ptr, start, end, null, .unneeded);
}
fn zirSliceSentinel(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const sentinel_src: LazySrcLoc = .{ .node_offset_slice_sentinel = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.SliceSentinel, inst_data.payload_index).data;
const array_ptr = try sema.resolveInst(extra.lhs);
const start = try sema.resolveInst(extra.start);
const end = try sema.resolveInst(extra.end);
const sentinel = try sema.resolveInst(extra.sentinel);
return sema.analyzeSlice(block, src, array_ptr, start, end, sentinel, sentinel_src);
}
fn zirSwitchCapture(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
is_multi: bool,
is_ref: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const zir_datas = sema.code.instructions.items(.data);
const capture_info = zir_datas[inst].switch_capture;
const switch_info = zir_datas[capture_info.switch_inst].pl_node;
const src = switch_info.src();
return sema.mod.fail(&block.base, src, "TODO implement Sema for zirSwitchCapture", .{});
}
fn zirSwitchCaptureElse(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
is_ref: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const zir_datas = sema.code.instructions.items(.data);
const capture_info = zir_datas[inst].switch_capture;
const switch_info = zir_datas[capture_info.switch_inst].pl_node;
const src = switch_info.src();
return sema.mod.fail(&block.base, src, "TODO implement Sema for zirSwitchCaptureElse", .{});
}
fn zirSwitchBlock(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
is_ref: bool,
special_prong: Zir.SpecialProng,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.SwitchBlock, inst_data.payload_index);
const operand_ptr = try sema.resolveInst(extra.data.operand);
const operand = if (is_ref)
try sema.analyzeLoad(block, src, operand_ptr, operand_src)
else
operand_ptr;
return sema.analyzeSwitch(
block,
operand,
extra.end,
special_prong,
extra.data.cases_len,
0,
inst,
inst_data.src_node,
);
}
fn zirSwitchBlockMulti(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
is_ref: bool,
special_prong: Zir.SpecialProng,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.SwitchBlockMulti, inst_data.payload_index);
const operand_ptr = try sema.resolveInst(extra.data.operand);
const operand = if (is_ref)
try sema.analyzeLoad(block, src, operand_ptr, operand_src)
else
operand_ptr;
return sema.analyzeSwitch(
block,
operand,
extra.end,
special_prong,
extra.data.scalar_cases_len,
extra.data.multi_cases_len,
inst,
inst_data.src_node,
);
}
fn analyzeSwitch(
sema: *Sema,
block: *Scope.Block,
operand: *Inst,
extra_end: usize,
special_prong: Zir.SpecialProng,
scalar_cases_len: usize,
multi_cases_len: usize,
switch_inst: Zir.Inst.Index,
src_node_offset: i32,
) InnerError!*Inst {
const gpa = sema.gpa;
const mod = sema.mod;
const special: struct { body: []const Zir.Inst.Index, end: usize } = switch (special_prong) {
.none => .{ .body = &.{}, .end = extra_end },
.under, .@"else" => blk: {
const body_len = sema.code.extra[extra_end];
const extra_body_start = extra_end + 1;
break :blk .{
.body = sema.code.extra[extra_body_start..][0..body_len],
.end = extra_body_start + body_len,
};
},
};
const src: LazySrcLoc = .{ .node_offset = src_node_offset };
const special_prong_src: LazySrcLoc = .{ .node_offset_switch_special_prong = src_node_offset };
const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = src_node_offset };
// Validate usage of '_' prongs.
if (special_prong == .under and !operand.ty.isNonexhaustiveEnum()) {
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
src,
"'_' prong only allowed when switching on non-exhaustive enums",
.{},
);
errdefer msg.destroy(gpa);
try mod.errNote(
&block.base,
special_prong_src,
msg,
"'_' prong here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
// Validate for duplicate items, missing else prong, and invalid range.
switch (operand.ty.zigTypeTag()) {
.Enum => {
var seen_fields = try gpa.alloc(?Module.SwitchProngSrc, operand.ty.enumFieldCount());
defer gpa.free(seen_fields);
mem.set(?Module.SwitchProngSrc, seen_fields, null);
var extra_index: usize = special.end;
{
var scalar_i: u32 = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
try sema.validateSwitchItemEnum(
block,
seen_fields,
item_ref,
src_node_offset,
.{ .scalar = scalar_i },
);
}
}
{
var multi_i: u32 = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len + body_len;
for (items) |item_ref, item_i| {
try sema.validateSwitchItemEnum(
block,
seen_fields,
item_ref,
src_node_offset,
.{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
);
}
try sema.validateSwitchNoRange(block, ranges_len, operand.ty, src_node_offset);
}
}
const all_tags_handled = for (seen_fields) |seen_src| {
if (seen_src == null) break false;
} else true;
switch (special_prong) {
.none => {
if (!all_tags_handled) {
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
src,
"switch must handle all possibilities",
.{},
);
errdefer msg.destroy(sema.gpa);
for (seen_fields) |seen_src, i| {
if (seen_src != null) continue;
const field_name = operand.ty.enumFieldName(i);
// TODO have this point to the tag decl instead of here
try mod.errNote(
&block.base,
src,
msg,
"unhandled enumeration value: '{s}'",
.{field_name},
);
}
try mod.errNoteNonLazy(
operand.ty.declSrcLoc(),
msg,
"enum '{}' declared here",
.{operand.ty},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
},
.under => {
if (all_tags_handled) return mod.fail(
&block.base,
special_prong_src,
"unreachable '_' prong; all cases already handled",
.{},
);
},
.@"else" => {
if (all_tags_handled) return mod.fail(
&block.base,
special_prong_src,
"unreachable else prong; all cases already handled",
.{},
);
},
}
},
.ErrorSet => return mod.fail(&block.base, src, "TODO validate switch .ErrorSet", .{}),
.Union => return mod.fail(&block.base, src, "TODO validate switch .Union", .{}),
.Int, .ComptimeInt => {
var range_set = RangeSet.init(gpa);
defer range_set.deinit();
var extra_index: usize = special.end;
{
var scalar_i: u32 = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
try sema.validateSwitchItem(
block,
&range_set,
item_ref,
src_node_offset,
.{ .scalar = scalar_i },
);
}
}
{
var multi_i: u32 = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len;
for (items) |item_ref, item_i| {
try sema.validateSwitchItem(
block,
&range_set,
item_ref,
src_node_offset,
.{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
);
}
var range_i: u32 = 0;
while (range_i < ranges_len) : (range_i += 1) {
const item_first = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const item_last = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
try sema.validateSwitchRange(
block,
&range_set,
item_first,
item_last,
src_node_offset,
.{ .range = .{ .prong = multi_i, .item = range_i } },
);
}
extra_index += body_len;
}
}
check_range: {
if (operand.ty.zigTypeTag() == .Int) {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const min_int = try operand.ty.minInt(&arena, mod.getTarget());
const max_int = try operand.ty.maxInt(&arena, mod.getTarget());
if (try range_set.spans(min_int, max_int)) {
if (special_prong == .@"else") {
return mod.fail(
&block.base,
special_prong_src,
"unreachable else prong; all cases already handled",
.{},
);
}
break :check_range;
}
}
if (special_prong != .@"else") {
return mod.fail(
&block.base,
src,
"switch must handle all possibilities",
.{},
);
}
}
},
.Bool => {
var true_count: u8 = 0;
var false_count: u8 = 0;
var extra_index: usize = special.end;
{
var scalar_i: u32 = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
try sema.validateSwitchItemBool(
block,
&true_count,
&false_count,
item_ref,
src_node_offset,
.{ .scalar = scalar_i },
);
}
}
{
var multi_i: u32 = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len + body_len;
for (items) |item_ref, item_i| {
try sema.validateSwitchItemBool(
block,
&true_count,
&false_count,
item_ref,
src_node_offset,
.{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
);
}
try sema.validateSwitchNoRange(block, ranges_len, operand.ty, src_node_offset);
}
}
switch (special_prong) {
.@"else" => {
if (true_count + false_count == 2) {
return mod.fail(
&block.base,
src,
"unreachable else prong; all cases already handled",
.{},
);
}
},
.under, .none => {
if (true_count + false_count < 2) {
return mod.fail(
&block.base,
src,
"switch must handle all possibilities",
.{},
);
}
},
}
},
.EnumLiteral, .Void, .Fn, .Pointer, .Type => {
if (special_prong != .@"else") {
return mod.fail(
&block.base,
src,
"else prong required when switching on type '{}'",
.{operand.ty},
);
}
var seen_values = ValueSrcMap.init(gpa);
defer seen_values.deinit();
var extra_index: usize = special.end;
{
var scalar_i: u32 = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
try sema.validateSwitchItemSparse(
block,
&seen_values,
item_ref,
src_node_offset,
.{ .scalar = scalar_i },
);
}
}
{
var multi_i: u32 = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len + body_len;
for (items) |item_ref, item_i| {
try sema.validateSwitchItemSparse(
block,
&seen_values,
item_ref,
src_node_offset,
.{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
);
}
try sema.validateSwitchNoRange(block, ranges_len, operand.ty, src_node_offset);
}
}
},
.ErrorUnion,
.NoReturn,
.Array,
.Struct,
.Undefined,
.Null,
.Optional,
.BoundFn,
.Opaque,
.Vector,
.Frame,
.AnyFrame,
.ComptimeFloat,
.Float,
=> return mod.fail(&block.base, operand_src, "invalid switch operand type '{}'", .{
operand.ty,
}),
}
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = undefined, // Set after analysis.
.src = src,
},
.body = undefined,
};
var label: Scope.Block.Label = .{
.zir_block = switch_inst,
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
};
var child_block: Scope.Block = .{
.parent = block,
.sema = sema,
.src_decl = block.src_decl,
.instructions = .{},
.label = &label,
.inlining = block.inlining,
.is_comptime = block.is_comptime,
};
const merges = &child_block.label.?.merges;
defer child_block.instructions.deinit(gpa);
defer merges.results.deinit(gpa);
defer merges.br_list.deinit(gpa);
if (try sema.resolveDefinedValue(&child_block, src, operand)) |operand_val| {
var extra_index: usize = special.end;
{
var scalar_i: usize = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
// Validation above ensured these will succeed.
const item = sema.resolveInst(item_ref) catch unreachable;
const item_val = sema.resolveConstValue(&child_block, .unneeded, item) catch unreachable;
if (operand_val.eql(item_val)) {
return sema.resolveBlockBody(block, src, &child_block, body, merges);
}
}
}
{
var multi_i: usize = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len;
const body = sema.code.extra[extra_index + 2 * ranges_len ..][0..body_len];
for (items) |item_ref| {
// Validation above ensured these will succeed.
const item = sema.resolveInst(item_ref) catch unreachable;
const item_val = sema.resolveConstValue(&child_block, item.src, item) catch unreachable;
if (operand_val.eql(item_val)) {
return sema.resolveBlockBody(block, src, &child_block, body, merges);
}
}
var range_i: usize = 0;
while (range_i < ranges_len) : (range_i += 1) {
const item_first = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const item_last = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
// Validation above ensured these will succeed.
const first_tv = sema.resolveInstConst(&child_block, .unneeded, item_first) catch unreachable;
const last_tv = sema.resolveInstConst(&child_block, .unneeded, item_last) catch unreachable;
if (Value.compare(operand_val, .gte, first_tv.val) and
Value.compare(operand_val, .lte, last_tv.val))
{
return sema.resolveBlockBody(block, src, &child_block, body, merges);
}
}
extra_index += body_len;
}
}
return sema.resolveBlockBody(block, src, &child_block, special.body, merges);
}
if (scalar_cases_len + multi_cases_len == 0) {
return sema.resolveBlockBody(block, src, &child_block, special.body, merges);
}
try sema.requireRuntimeBlock(block, src);
// TODO when reworking AIR memory layout make multi cases get generated as cases,
// not as part of the "else" block.
const cases = try sema.arena.alloc(Inst.SwitchBr.Case, scalar_cases_len);
var case_block = child_block.makeSubBlock();
defer case_block.instructions.deinit(gpa);
var extra_index: usize = special.end;
var scalar_i: usize = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
case_block.instructions.shrinkRetainingCapacity(0);
// We validate these above; these two calls are guaranteed to succeed.
const item = sema.resolveInst(item_ref) catch unreachable;
const item_val = sema.resolveConstValue(&case_block, .unneeded, item) catch unreachable;
_ = try sema.analyzeBody(&case_block, body);
cases[scalar_i] = .{
.item = item_val,
.body = .{ .instructions = try sema.arena.dupe(*Inst, case_block.instructions.items) },
};
}
var first_else_body: Body = undefined;
var prev_condbr: ?*Inst.CondBr = null;
var multi_i: usize = 0;
while (multi_i < multi_cases_len) : (multi_i += 1) {
const items_len = sema.code.extra[extra_index];
extra_index += 1;
const ranges_len = sema.code.extra[extra_index];
extra_index += 1;
const body_len = sema.code.extra[extra_index];
extra_index += 1;
const items = sema.code.refSlice(extra_index, items_len);
extra_index += items_len;
case_block.instructions.shrinkRetainingCapacity(0);
var any_ok: ?*Inst = null;
const bool_ty = comptime Type.initTag(.bool);
for (items) |item_ref| {
const item = try sema.resolveInst(item_ref);
_ = try sema.resolveConstValue(&child_block, item.src, item);
const cmp_ok = try case_block.addBinOp(item.src, bool_ty, .cmp_eq, operand, item);
if (any_ok) |some| {
any_ok = try case_block.addBinOp(item.src, bool_ty, .bool_or, some, cmp_ok);
} else {
any_ok = cmp_ok;
}
}
var range_i: usize = 0;
while (range_i < ranges_len) : (range_i += 1) {
const first_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const last_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const item_first = try sema.resolveInst(first_ref);
const item_last = try sema.resolveInst(last_ref);
_ = try sema.resolveConstValue(&child_block, item_first.src, item_first);
_ = try sema.resolveConstValue(&child_block, item_last.src, item_last);
const range_src = item_first.src;
// operand >= first and operand <= last
const range_first_ok = try case_block.addBinOp(
item_first.src,
bool_ty,
.cmp_gte,
operand,
item_first,
);
const range_last_ok = try case_block.addBinOp(
item_last.src,
bool_ty,
.cmp_lte,
operand,
item_last,
);
const range_ok = try case_block.addBinOp(
range_src,
bool_ty,
.bool_and,
range_first_ok,
range_last_ok,
);
if (any_ok) |some| {
any_ok = try case_block.addBinOp(range_src, bool_ty, .bool_or, some, range_ok);
} else {
any_ok = range_ok;
}
}
const new_condbr = try sema.arena.create(Inst.CondBr);
new_condbr.* = .{
.base = .{
.tag = .condbr,
.ty = Type.initTag(.noreturn),
.src = src,
},
.condition = any_ok.?,
.then_body = undefined,
.else_body = undefined,
};
try case_block.instructions.append(gpa, &new_condbr.base);
const cond_body: Body = .{
.instructions = try sema.arena.dupe(*Inst, case_block.instructions.items),
};
case_block.instructions.shrinkRetainingCapacity(0);
const body = sema.code.extra[extra_index..][0..body_len];
extra_index += body_len;
_ = try sema.analyzeBody(&case_block, body);
new_condbr.then_body = .{
.instructions = try sema.arena.dupe(*Inst, case_block.instructions.items),
};
if (prev_condbr) |condbr| {
condbr.else_body = cond_body;
} else {
first_else_body = cond_body;
}
prev_condbr = new_condbr;
}
const final_else_body: Body = blk: {
if (special.body.len != 0) {
case_block.instructions.shrinkRetainingCapacity(0);
_ = try sema.analyzeBody(&case_block, special.body);
const else_body: Body = .{
.instructions = try sema.arena.dupe(*Inst, case_block.instructions.items),
};
if (prev_condbr) |condbr| {
condbr.else_body = else_body;
break :blk first_else_body;
} else {
break :blk else_body;
}
} else {
break :blk .{ .instructions = &.{} };
}
};
_ = try child_block.addSwitchBr(src, operand, cases, final_else_body);
return sema.analyzeBlockBody(block, src, &child_block, merges);
}
fn resolveSwitchItemVal(
sema: *Sema,
block: *Scope.Block,
item_ref: Zir.Inst.Ref,
switch_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
range_expand: Module.SwitchProngSrc.RangeExpand,
) InnerError!TypedValue {
const item = try sema.resolveInst(item_ref);
// We have to avoid the other helper functions here because we cannot construct a LazySrcLoc
// because we only have the switch AST node. Only if we know for sure we need to report
// a compile error do we resolve the full source locations.
if (item.value()) |val| {
if (val.isUndef()) {
const src = switch_prong_src.resolve(sema.gpa, block.src_decl, switch_node_offset, range_expand);
return sema.failWithUseOfUndef(block, src);
}
return TypedValue{ .ty = item.ty, .val = val };
}
const src = switch_prong_src.resolve(sema.gpa, block.src_decl, switch_node_offset, range_expand);
return sema.failWithNeededComptime(block, src);
}
fn validateSwitchRange(
sema: *Sema,
block: *Scope.Block,
range_set: *RangeSet,
first_ref: Zir.Inst.Ref,
last_ref: Zir.Inst.Ref,
src_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
) InnerError!void {
const first_val = (try sema.resolveSwitchItemVal(block, first_ref, src_node_offset, switch_prong_src, .first)).val;
const last_val = (try sema.resolveSwitchItemVal(block, last_ref, src_node_offset, switch_prong_src, .last)).val;
const maybe_prev_src = try range_set.add(first_val, last_val, switch_prong_src);
return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}
fn validateSwitchItem(
sema: *Sema,
block: *Scope.Block,
range_set: *RangeSet,
item_ref: Zir.Inst.Ref,
src_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
) InnerError!void {
const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
const maybe_prev_src = try range_set.add(item_val, item_val, switch_prong_src);
return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}
fn validateSwitchItemEnum(
sema: *Sema,
block: *Scope.Block,
seen_fields: []?Module.SwitchProngSrc,
item_ref: Zir.Inst.Ref,
src_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
) InnerError!void {
const mod = sema.mod;
const item_tv = try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none);
const field_index = item_tv.ty.enumTagFieldIndex(item_tv.val) orelse {
const msg = msg: {
const src = switch_prong_src.resolve(sema.gpa, block.src_decl, src_node_offset, .none);
const msg = try mod.errMsg(
&block.base,
src,
"enum '{}' has no tag with value '{}'",
.{ item_tv.ty, item_tv.val },
);
errdefer msg.destroy(sema.gpa);
try mod.errNoteNonLazy(
item_tv.ty.declSrcLoc(),
msg,
"enum declared here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
};
const maybe_prev_src = seen_fields[field_index];
seen_fields[field_index] = switch_prong_src;
return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}
fn validateSwitchDupe(
sema: *Sema,
block: *Scope.Block,
maybe_prev_src: ?Module.SwitchProngSrc,
switch_prong_src: Module.SwitchProngSrc,
src_node_offset: i32,
) InnerError!void {
const prev_prong_src = maybe_prev_src orelse return;
const mod = sema.mod;
const gpa = sema.gpa;
const src = switch_prong_src.resolve(gpa, block.src_decl, src_node_offset, .none);
const prev_src = prev_prong_src.resolve(gpa, block.src_decl, src_node_offset, .none);
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
src,
"duplicate switch value",
.{},
);
errdefer msg.destroy(sema.gpa);
try mod.errNote(
&block.base,
prev_src,
msg,
"previous value here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
fn validateSwitchItemBool(
sema: *Sema,
block: *Scope.Block,
true_count: *u8,
false_count: *u8,
item_ref: Zir.Inst.Ref,
src_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
) InnerError!void {
const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
if (item_val.toBool()) {
true_count.* += 1;
} else {
false_count.* += 1;
}
if (true_count.* + false_count.* > 2) {
const src = switch_prong_src.resolve(sema.gpa, block.src_decl, src_node_offset, .none);
return sema.mod.fail(&block.base, src, "duplicate switch value", .{});
}
}
const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.hash, Value.eql, std.hash_map.DefaultMaxLoadPercentage);
fn validateSwitchItemSparse(
sema: *Sema,
block: *Scope.Block,
seen_values: *ValueSrcMap,
item_ref: Zir.Inst.Ref,
src_node_offset: i32,
switch_prong_src: Module.SwitchProngSrc,
) InnerError!void {
const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
const entry = (try seen_values.fetchPut(item_val, switch_prong_src)) orelse return;
return sema.validateSwitchDupe(block, entry.value, switch_prong_src, src_node_offset);
}
fn validateSwitchNoRange(
sema: *Sema,
block: *Scope.Block,
ranges_len: u32,
operand_ty: Type,
src_node_offset: i32,
) InnerError!void {
if (ranges_len == 0)
return;
const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = src_node_offset };
const range_src: LazySrcLoc = .{ .node_offset_switch_range = src_node_offset };
const msg = msg: {
const msg = try sema.mod.errMsg(
&block.base,
operand_src,
"ranges not allowed when switching on type '{}'",
.{operand_ty},
);
errdefer msg.destroy(sema.gpa);
try sema.mod.errNote(
&block.base,
range_src,
msg,
"range here",
.{},
);
break :msg msg;
};
return sema.mod.failWithOwnedErrorMsg(&block.base, msg);
}
fn zirHasField(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO implement zirHasField", .{});
}
fn zirHasDecl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src = inst_data.src();
const lhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
const container_type = try sema.resolveType(block, lhs_src, extra.lhs);
const decl_name = try sema.resolveConstString(block, rhs_src, extra.rhs);
const mod = sema.mod;
const arena = sema.arena;
const namespace = container_type.getNamespace() orelse return mod.fail(
&block.base,
lhs_src,
"expected struct, enum, union, or opaque, found '{}'",
.{container_type},
);
if (try sema.lookupInNamespace(namespace, decl_name)) |decl| {
if (decl.is_pub or decl.namespace.file_scope == block.base.namespace().file_scope) {
return mod.constBool(arena, src, true);
}
}
return mod.constBool(arena, src, false);
}
fn zirImport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const mod = sema.mod;
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const operand = inst_data.get(sema.code);
const result = mod.importFile(block.getFileScope(), operand) catch |err| switch (err) {
error.ImportOutsidePkgPath => {
return mod.fail(&block.base, src, "import of file outside package path: '{s}'", .{operand});
},
else => {
// TODO: these errors are file system errors; make sure an update() will
// retry this and not cache the file system error, which may be transient.
return mod.fail(&block.base, src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
},
};
try mod.semaFile(result.file);
const file_root_decl = result.file.root_decl.?;
try sema.mod.declareDeclDependency(sema.owner_decl, file_root_decl);
return mod.constType(sema.arena, src, file_root_decl.ty);
}
fn zirShl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirShl", .{});
}
fn zirShr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirShr", .{});
}
fn zirBitwise(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
ir_tag: ir.Inst.Tag,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const lhs = try sema.resolveInst(extra.lhs);
const rhs = try sema.resolveInst(extra.rhs);
const instructions = &[_]*Inst{ lhs, rhs };
const resolved_type = try sema.resolvePeerTypes(block, src, instructions);
const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);
const scalar_type = if (resolved_type.zigTypeTag() == .Vector)
resolved_type.elemType()
else
resolved_type;
const scalar_tag = scalar_type.zigTypeTag();
if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) {
if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) {
return sema.mod.fail(&block.base, src, "vector length mismatch: {d} and {d}", .{
lhs.ty.arrayLen(),
rhs.ty.arrayLen(),
});
}
return sema.mod.fail(&block.base, src, "TODO implement support for vectors in zirBitwise", .{});
} else if (lhs.ty.zigTypeTag() == .Vector or rhs.ty.zigTypeTag() == .Vector) {
return sema.mod.fail(&block.base, src, "mixed scalar and vector operands to binary expression: '{}' and '{}'", .{
lhs.ty,
rhs.ty,
});
}
const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;
if (!is_int) {
return sema.mod.fail(&block.base, src, "invalid operands to binary bitwise expression: '{s}' and '{s}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) });
}
if (casted_lhs.value()) |lhs_val| {
if (casted_rhs.value()) |rhs_val| {
if (lhs_val.isUndef() or rhs_val.isUndef()) {
return sema.mod.constUndef(sema.arena, src, resolved_type);
}
return sema.mod.fail(&block.base, src, "TODO implement comptime bitwise operations", .{});
}
}
try sema.requireRuntimeBlock(block, src);
return block.addBinOp(src, scalar_type, ir_tag, casted_lhs, casted_rhs);
}
fn zirBitNot(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirBitNot", .{});
}
fn zirArrayCat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirArrayCat", .{});
}
fn zirArrayMul(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return sema.mod.fail(&block.base, sema.src, "TODO implement zirArrayMul", .{});
}
fn zirNegate(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
tag_override: Zir.Inst.Tag,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const lhs = try sema.resolveInst(.zero);
const rhs = try sema.resolveInst(inst_data.operand);
return sema.analyzeArithmetic(block, tag_override, lhs, rhs, src, lhs_src, rhs_src);
}
fn zirArithmetic(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const tag_override = block.sema.code.instructions.items(.tag)[inst];
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const lhs = try sema.resolveInst(extra.lhs);
const rhs = try sema.resolveInst(extra.rhs);
return sema.analyzeArithmetic(block, tag_override, lhs, rhs, src, lhs_src, rhs_src);
}
fn zirOverflowArithmetic(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const extra = sema.code.extraData(Zir.Inst.OverflowArithmetic, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO implement Sema.zirOverflowArithmetic", .{});
}
fn analyzeArithmetic(
sema: *Sema,
block: *Scope.Block,
zir_tag: Zir.Inst.Tag,
lhs: *Inst,
rhs: *Inst,
src: LazySrcLoc,
lhs_src: LazySrcLoc,
rhs_src: LazySrcLoc,
) InnerError!*Inst {
const instructions = &[_]*Inst{ lhs, rhs };
const resolved_type = try sema.resolvePeerTypes(block, src, instructions);
const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);
const scalar_type = if (resolved_type.zigTypeTag() == .Vector)
resolved_type.elemType()
else
resolved_type;
const scalar_tag = scalar_type.zigTypeTag();
if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) {
if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) {
return sema.mod.fail(&block.base, src, "vector length mismatch: {d} and {d}", .{
lhs.ty.arrayLen(),
rhs.ty.arrayLen(),
});
}
return sema.mod.fail(&block.base, src, "TODO implement support for vectors in zirBinOp", .{});
} else if (lhs.ty.zigTypeTag() == .Vector or rhs.ty.zigTypeTag() == .Vector) {
return sema.mod.fail(&block.base, src, "mixed scalar and vector operands to binary expression: '{}' and '{}'", .{
lhs.ty,
rhs.ty,
});
}
const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;
const is_float = scalar_tag == .Float or scalar_tag == .ComptimeFloat;
if (!is_int and !(is_float and floatOpAllowed(zir_tag))) {
return sema.mod.fail(&block.base, src, "invalid operands to binary expression: '{s}' and '{s}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) });
}
if (casted_lhs.value()) |lhs_val| {
if (casted_rhs.value()) |rhs_val| {
if (lhs_val.isUndef() or rhs_val.isUndef()) {
return sema.mod.constUndef(sema.arena, src, resolved_type);
}
// incase rhs is 0, simply return lhs without doing any calculations
// TODO Once division is implemented we should throw an error when dividing by 0.
if (rhs_val.compareWithZero(.eq)) {
switch (zir_tag) {
.add, .addwrap, .sub, .subwrap => {
return sema.mod.constInst(sema.arena, src, .{
.ty = scalar_type,
.val = lhs_val,
});
},
else => {},
}
}
const value = switch (zir_tag) {
.add => blk: {
const val = if (is_int)
try Module.intAdd(sema.arena, lhs_val, rhs_val)
else
try Module.floatAdd(sema.arena, scalar_type, src, lhs_val, rhs_val);
break :blk val;
},
.sub => blk: {
const val = if (is_int)
try Module.intSub(sema.arena, lhs_val, rhs_val)
else
try Module.floatSub(sema.arena, scalar_type, src, lhs_val, rhs_val);
break :blk val;
},
.div => blk: {
const val = if (is_int)
try Module.intDiv(sema.arena, lhs_val, rhs_val)
else
try Module.floatDiv(sema.arena, scalar_type, src, lhs_val, rhs_val);
break :blk val;
},
.mul => blk: {
const val = if (is_int)
try Module.intMul(sema.arena, lhs_val, rhs_val)
else
try Module.floatMul(sema.arena, scalar_type, src, lhs_val, rhs_val);
break :blk val;
},
else => return sema.mod.fail(&block.base, src, "TODO Implement arithmetic operand '{s}'", .{@tagName(zir_tag)}),
};
log.debug("{s}({}, {}) result: {}", .{ @tagName(zir_tag), lhs_val, rhs_val, value });
return sema.mod.constInst(sema.arena, src, .{
.ty = scalar_type,
.val = value,
});
}
}
try sema.requireRuntimeBlock(block, src);
const ir_tag: Inst.Tag = switch (zir_tag) {
.add => .add,
.addwrap => .addwrap,
.sub => .sub,
.subwrap => .subwrap,
.mul => .mul,
.mulwrap => .mulwrap,
.div => .div,
else => return sema.mod.fail(&block.base, src, "TODO implement arithmetic for operand '{s}''", .{@tagName(zir_tag)}),
};
return block.addBinOp(src, scalar_type, ir_tag, casted_lhs, casted_rhs);
}
fn zirLoad(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const ptr_src: LazySrcLoc = .{ .node_offset_deref_ptr = inst_data.src_node };
const ptr = try sema.resolveInst(inst_data.operand);
return sema.analyzeLoad(block, src, ptr, ptr_src);
}
fn zirAsm(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const extra = sema.code.extraData(Zir.Inst.Asm, extended.operand);
const src: LazySrcLoc = .{ .node_offset = extra.data.src_node };
const asm_source_src: LazySrcLoc = .{ .node_offset_asm_source = extra.data.src_node };
const ret_ty_src: LazySrcLoc = .{ .node_offset_asm_ret_ty = extra.data.src_node };
const asm_source = try sema.resolveConstString(block, asm_source_src, extra.data.asm_source);
const outputs_len = @truncate(u5, extended.small);
const inputs_len = @truncate(u5, extended.small >> 5);
const clobbers_len = @truncate(u5, extended.small >> 10);
const is_volatile = @truncate(u1, extended.small >> 15) != 0;
if (outputs_len > 1) {
return sema.mod.fail(&block.base, src, "TODO implement Sema for asm with more than 1 output", .{});
}
var extra_i = extra.end;
var output_type_bits = extra.data.output_type_bits;
const Output = struct { constraint: []const u8, ty: Type };
const output: ?Output = if (outputs_len == 0) null else blk: {
const output = sema.code.extraData(Zir.Inst.Asm.Output, extra_i);
extra_i = output.end;
const is_type = @truncate(u1, output_type_bits) != 0;
output_type_bits >>= 1;
if (!is_type) {
return sema.mod.fail(&block.base, src, "TODO implement Sema for asm with non `->` output", .{});
}
const constraint = sema.code.nullTerminatedString(output.data.constraint);
break :blk Output{
.constraint = constraint,
.ty = try sema.resolveType(block, ret_ty_src, output.data.operand),
};
};
const args = try sema.arena.alloc(*Inst, inputs_len);
const inputs = try sema.arena.alloc([]const u8, inputs_len);
for (args) |*arg, arg_i| {
const input = sema.code.extraData(Zir.Inst.Asm.Input, extra_i);
extra_i = input.end;
const name = sema.code.nullTerminatedString(input.data.name);
_ = name; // TODO: use the name
arg.* = try sema.resolveInst(input.data.operand);
inputs[arg_i] = sema.code.nullTerminatedString(input.data.constraint);
}
const clobbers = try sema.arena.alloc([]const u8, clobbers_len);
for (clobbers) |*name| {
name.* = sema.code.nullTerminatedString(sema.code.extra[extra_i]);
extra_i += 1;
}
try sema.requireRuntimeBlock(block, src);
const asm_air = try sema.arena.create(Inst.Assembly);
asm_air.* = .{
.base = .{
.tag = .assembly,
.ty = if (output) |o| o.ty else Type.initTag(.void),
.src = src,
},
.asm_source = asm_source,
.is_volatile = is_volatile,
.output_constraint = if (output) |o| o.constraint else null,
.inputs = inputs,
.clobbers = clobbers,
.args = args,
};
try block.instructions.append(sema.gpa, &asm_air.base);
return &asm_air.base;
}
fn zirCmp(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
op: std.math.CompareOperator,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const mod = sema.mod;
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
const src: LazySrcLoc = inst_data.src();
const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
const lhs = try sema.resolveInst(extra.lhs);
const rhs = try sema.resolveInst(extra.rhs);
const is_equality_cmp = switch (op) {
.eq, .neq => true,
else => false,
};
const lhs_ty_tag = lhs.ty.zigTypeTag();
const rhs_ty_tag = rhs.ty.zigTypeTag();
if (is_equality_cmp and lhs_ty_tag == .Null and rhs_ty_tag == .Null) {
// null == null, null != null
return mod.constBool(sema.arena, src, op == .eq);
} else if (is_equality_cmp and
((lhs_ty_tag == .Null and rhs_ty_tag == .Optional) or
rhs_ty_tag == .Null and lhs_ty_tag == .Optional))
{
// comparing null with optionals
const opt_operand = if (lhs_ty_tag == .Optional) lhs else rhs;
return sema.analyzeIsNull(block, src, opt_operand, op == .neq);
} else if (is_equality_cmp and
((lhs_ty_tag == .Null and rhs.ty.isCPtr()) or (rhs_ty_tag == .Null and lhs.ty.isCPtr())))
{
return mod.fail(&block.base, src, "TODO implement C pointer cmp", .{});
} else if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
const non_null_type = if (lhs_ty_tag == .Null) rhs.ty else lhs.ty;
return mod.fail(&block.base, src, "comparison of '{}' with null", .{non_null_type});
} else if (is_equality_cmp and
((lhs_ty_tag == .EnumLiteral and rhs_ty_tag == .Union) or
(rhs_ty_tag == .EnumLiteral and lhs_ty_tag == .Union)))
{
return mod.fail(&block.base, src, "TODO implement equality comparison between a union's tag value and an enum literal", .{});
} else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) {
if (!is_equality_cmp) {
return mod.fail(&block.base, src, "{s} operator not allowed for errors", .{@tagName(op)});
}
if (rhs.value()) |rval| {
if (lhs.value()) |lval| {
// TODO optimisation oppurtunity: evaluate if std.mem.eql is faster with the names, or calling to Module.getErrorValue to get the values and then compare them is faster
return mod.constBool(sema.arena, src, std.mem.eql(u8, lval.castTag(.@"error").?.data.name, rval.castTag(.@"error").?.data.name) == (op == .eq));
}
}
try sema.requireRuntimeBlock(block, src);
return block.addBinOp(src, Type.initTag(.bool), if (op == .eq) .cmp_eq else .cmp_neq, lhs, rhs);
} else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) {
// This operation allows any combination of integer and float types, regardless of the
// signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for
// numeric types.
return sema.cmpNumeric(block, src, lhs, rhs, op);
} else if (lhs_ty_tag == .Type and rhs_ty_tag == .Type) {
if (!is_equality_cmp) {
return mod.fail(&block.base, src, "{s} operator not allowed for types", .{@tagName(op)});
}
return mod.constBool(sema.arena, src, lhs.value().?.eql(rhs.value().?) == (op == .eq));
}
const instructions = &[_]*Inst{ lhs, rhs };
const resolved_type = try sema.resolvePeerTypes(block, src, instructions);
if (!resolved_type.isSelfComparable(is_equality_cmp)) {
return mod.fail(&block.base, src, "operator not allowed for type '{}'", .{resolved_type});
}
const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);
if (casted_lhs.value()) |lhs_val| {
if (casted_rhs.value()) |rhs_val| {
if (lhs_val.isUndef() or rhs_val.isUndef()) {
return sema.mod.constUndef(sema.arena, src, resolved_type);
}
const result = lhs_val.compare(op, rhs_val);
return sema.mod.constBool(sema.arena, src, result);
}
}
try sema.requireRuntimeBlock(block, src);
const tag: Inst.Tag = switch (op) {
.lt => .cmp_lt,
.lte => .cmp_lte,
.eq => .cmp_eq,
.gte => .cmp_gte,
.gt => .cmp_gt,
.neq => .cmp_neq,
};
const bool_type = Type.initTag(.bool); // TODO handle vectors
return block.addBinOp(src, bool_type, tag, casted_lhs, casted_rhs);
}
fn zirSizeOf(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_ty = try sema.resolveType(block, operand_src, inst_data.operand);
const target = sema.mod.getTarget();
const abi_size = operand_ty.abiSize(target);
return sema.mod.constIntUnsigned(sema.arena, src, Type.initTag(.comptime_int), abi_size);
}
fn zirBitSizeOf(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand_ty = try sema.resolveType(block, operand_src, inst_data.operand);
const target = sema.mod.getTarget();
const bit_size = operand_ty.bitSize(target);
return sema.mod.constIntUnsigned(sema.arena, src, Type.initTag(.comptime_int), bit_size);
}
fn zirThis(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirThis", .{});
}
fn zirRetAddr(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirRetAddr", .{});
}
fn zirBuiltinSrc(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirBuiltinSrc", .{});
}
fn zirTypeInfo(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const ty = try sema.resolveType(block, src, inst_data.operand);
const type_info_ty = try sema.getBuiltinType(block, src, "TypeInfo");
const target = sema.mod.getTarget();
switch (ty.zigTypeTag()) {
.Fn => {
const field_values = try sema.arena.alloc(Value, 6);
// calling_convention: CallingConvention,
field_values[0] = try Value.Tag.enum_field_index.create(
sema.arena,
@enumToInt(ty.fnCallingConvention()),
);
// alignment: comptime_int,
field_values[1] = try Value.Tag.int_u64.create(sema.arena, ty.abiAlignment(target));
// is_generic: bool,
field_values[2] = Value.initTag(.bool_false); // TODO
// is_var_args: bool,
field_values[3] = Value.initTag(.bool_false); // TODO
// return_type: ?type,
field_values[4] = try Value.Tag.ty.create(sema.arena, ty.fnReturnType());
// args: []const FnArg,
field_values[5] = Value.initTag(.null_value); // TODO
return sema.mod.constInst(sema.arena, src, .{
.ty = type_info_ty,
.val = try Value.Tag.@"union".create(sema.arena, .{
.tag = try Value.Tag.enum_field_index.create(
sema.arena,
@enumToInt(@typeInfo(std.builtin.TypeInfo).Union.tag_type.?.Fn),
),
.val = try Value.Tag.@"struct".create(sema.arena, field_values.ptr),
}),
});
},
else => |t| return sema.mod.fail(&block.base, src, "TODO: implement zirTypeInfo for {s}", .{
@tagName(t),
}),
}
}
fn zirTypeof(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const zir_datas = sema.code.instructions.items(.data);
const inst_data = zir_datas[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
return sema.mod.constType(sema.arena, src, operand.ty);
}
fn zirTypeofElem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand_ptr = try sema.resolveInst(inst_data.operand);
const elem_ty = operand_ptr.ty.elemType();
return sema.mod.constType(sema.arena, src, elem_ty);
}
fn zirTypeofLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirTypeofLog2IntType", .{});
}
fn zirLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirLog2IntType", .{});
}
fn zirTypeofPeer(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const extra = sema.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
const src: LazySrcLoc = .{ .node_offset = extra.data.src_node };
const args = sema.code.refSlice(extra.end, extended.small);
const inst_list = try sema.gpa.alloc(*ir.Inst, args.len);
defer sema.gpa.free(inst_list);
for (args) |arg_ref, i| {
inst_list[i] = try sema.resolveInst(arg_ref);
}
const result_type = try sema.resolvePeerTypes(block, src, inst_list);
return sema.mod.constType(sema.arena, src, result_type);
}
fn zirBoolNot(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const uncasted_operand = try sema.resolveInst(inst_data.operand);
const bool_type = Type.initTag(.bool);
const operand = try sema.coerce(block, bool_type, uncasted_operand, uncasted_operand.src);
if (try sema.resolveDefinedValue(block, src, operand)) |val| {
return sema.mod.constBool(sema.arena, src, !val.toBool());
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, bool_type, .not, operand);
}
fn zirBoolOp(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
comptime is_bool_or: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .unneeded;
const bool_type = Type.initTag(.bool);
const bin_inst = sema.code.instructions.items(.data)[inst].bin;
const uncasted_lhs = try sema.resolveInst(bin_inst.lhs);
const lhs = try sema.coerce(block, bool_type, uncasted_lhs, uncasted_lhs.src);
const uncasted_rhs = try sema.resolveInst(bin_inst.rhs);
const rhs = try sema.coerce(block, bool_type, uncasted_rhs, uncasted_rhs.src);
if (lhs.value()) |lhs_val| {
if (rhs.value()) |rhs_val| {
if (is_bool_or) {
return sema.mod.constBool(sema.arena, src, lhs_val.toBool() or rhs_val.toBool());
} else {
return sema.mod.constBool(sema.arena, src, lhs_val.toBool() and rhs_val.toBool());
}
}
}
try sema.requireRuntimeBlock(block, src);
const tag: ir.Inst.Tag = if (is_bool_or) .bool_or else .bool_and;
return block.addBinOp(src, bool_type, tag, lhs, rhs);
}
fn zirBoolBr(
sema: *Sema,
parent_block: *Scope.Block,
inst: Zir.Inst.Index,
is_bool_or: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const datas = sema.code.instructions.items(.data);
const inst_data = datas[inst].bool_br;
const src: LazySrcLoc = .unneeded;
const lhs = try sema.resolveInst(inst_data.lhs);
const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
const body = sema.code.extra[extra.end..][0..extra.data.body_len];
if (try sema.resolveDefinedValue(parent_block, src, lhs)) |lhs_val| {
if (lhs_val.toBool() == is_bool_or) {
return sema.mod.constBool(sema.arena, src, is_bool_or);
}
// comptime-known left-hand side. No need for a block here; the result
// is simply the rhs expression. Here we rely on there only being 1
// break instruction (`break_inline`).
return sema.resolveBody(parent_block, body);
}
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = Type.initTag(.bool),
.src = src,
},
.body = undefined,
};
var child_block = parent_block.makeSubBlock();
defer child_block.instructions.deinit(sema.gpa);
var then_block = child_block.makeSubBlock();
defer then_block.instructions.deinit(sema.gpa);
var else_block = child_block.makeSubBlock();
defer else_block.instructions.deinit(sema.gpa);
const lhs_block = if (is_bool_or) &then_block else &else_block;
const rhs_block = if (is_bool_or) &else_block else &then_block;
const lhs_result = try sema.mod.constInst(sema.arena, src, .{
.ty = Type.initTag(.bool),
.val = if (is_bool_or) Value.initTag(.bool_true) else Value.initTag(.bool_false),
});
_ = try lhs_block.addBr(src, block_inst, lhs_result);
const rhs_result = try sema.resolveBody(rhs_block, body);
_ = try rhs_block.addBr(src, block_inst, rhs_result);
const air_then_body: ir.Body = .{ .instructions = try sema.arena.dupe(*Inst, then_block.instructions.items) };
const air_else_body: ir.Body = .{ .instructions = try sema.arena.dupe(*Inst, else_block.instructions.items) };
_ = try child_block.addCondBr(src, lhs, air_then_body, air_else_body);
block_inst.body = .{
.instructions = try sema.arena.dupe(*Inst, child_block.instructions.items),
};
try parent_block.instructions.append(sema.gpa, &block_inst.base);
return &block_inst.base;
}
fn zirIsNull(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
invert_logic: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const operand = try sema.resolveInst(inst_data.operand);
return sema.analyzeIsNull(block, src, operand, invert_logic);
}
fn zirIsNullPtr(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
invert_logic: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const ptr = try sema.resolveInst(inst_data.operand);
const loaded = try sema.analyzeLoad(block, src, ptr, src);
return sema.analyzeIsNull(block, src, loaded, invert_logic);
}
fn zirIsErr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const operand = try sema.resolveInst(inst_data.operand);
return sema.analyzeIsErr(block, inst_data.src(), operand);
}
fn zirIsErrPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const ptr = try sema.resolveInst(inst_data.operand);
const loaded = try sema.analyzeLoad(block, src, ptr, src);
return sema.analyzeIsErr(block, src, loaded);
}
fn zirCondbr(
sema: *Sema,
parent_block: *Scope.Block,
inst: Zir.Inst.Index,
) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
const cond_src: LazySrcLoc = .{ .node_offset_if_cond = inst_data.src_node };
const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
const then_body = sema.code.extra[extra.end..][0..extra.data.then_body_len];
const else_body = sema.code.extra[extra.end + then_body.len ..][0..extra.data.else_body_len];
const uncasted_cond = try sema.resolveInst(extra.data.condition);
const cond = try sema.coerce(parent_block, Type.initTag(.bool), uncasted_cond, cond_src);
if (try sema.resolveDefinedValue(parent_block, src, cond)) |cond_val| {
const body = if (cond_val.toBool()) then_body else else_body;
_ = try sema.analyzeBody(parent_block, body);
return always_noreturn;
}
var sub_block = parent_block.makeSubBlock();
defer sub_block.instructions.deinit(sema.gpa);
_ = try sema.analyzeBody(&sub_block, then_body);
const air_then_body: ir.Body = .{
.instructions = try sema.arena.dupe(*Inst, sub_block.instructions.items),
};
sub_block.instructions.shrinkRetainingCapacity(0);
_ = try sema.analyzeBody(&sub_block, else_body);
const air_else_body: ir.Body = .{
.instructions = try sema.arena.dupe(*Inst, sub_block.instructions.items),
};
_ = try parent_block.addCondBr(src, cond, air_then_body, air_else_body);
return always_noreturn;
}
fn zirUnreachable(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].@"unreachable";
const src = inst_data.src();
const safety_check = inst_data.safety;
try sema.requireRuntimeBlock(block, src);
// TODO Add compile error for @optimizeFor occurring too late in a scope.
if (safety_check and block.wantSafety()) {
return sema.safetyPanic(block, src, .unreach);
} else {
_ = try block.addNoOp(src, Type.initTag(.noreturn), .unreach);
return always_noreturn;
}
}
fn zirRetTok(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
need_coercion: bool,
) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
const operand = try sema.resolveInst(inst_data.operand);
const src = inst_data.src();
return sema.analyzeRet(block, operand, src, need_coercion);
}
fn zirRetNode(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!Zir.Inst.Index {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const operand = try sema.resolveInst(inst_data.operand);
const src = inst_data.src();
return sema.analyzeRet(block, operand, src, false);
}
fn analyzeRet(
sema: *Sema,
block: *Scope.Block,
operand: *Inst,
src: LazySrcLoc,
need_coercion: bool,
) InnerError!Zir.Inst.Index {
if (block.inlining) |inlining| {
// We are inlining a function call; rewrite the `ret` as a `break`.
try inlining.merges.results.append(sema.gpa, operand);
_ = try block.addBr(src, inlining.merges.block_inst, operand);
return always_noreturn;
}
if (need_coercion) {
if (sema.func) |func| {
const fn_ty = func.owner_decl.ty;
const fn_ret_ty = fn_ty.fnReturnType();
const casted_operand = try sema.coerce(block, fn_ret_ty, operand, src);
if (fn_ret_ty.zigTypeTag() == .Void)
_ = try block.addNoOp(src, Type.initTag(.noreturn), .retvoid)
else
_ = try block.addUnOp(src, Type.initTag(.noreturn), .ret, casted_operand);
return always_noreturn;
}
}
_ = try block.addUnOp(src, Type.initTag(.noreturn), .ret, operand);
return always_noreturn;
}
fn floatOpAllowed(tag: Zir.Inst.Tag) bool {
// extend this swich as additional operators are implemented
return switch (tag) {
.add, .sub => true,
else => false,
};
}
fn zirPtrTypeSimple(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].ptr_type_simple;
const elem_type = try sema.resolveType(block, .unneeded, inst_data.elem_type);
const ty = try sema.mod.ptrType(
sema.arena,
elem_type,
null,
0,
0,
0,
inst_data.is_mutable,
inst_data.is_allowzero,
inst_data.is_volatile,
inst_data.size,
);
return sema.mod.constType(sema.arena, .unneeded, ty);
}
fn zirPtrType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const src: LazySrcLoc = .unneeded;
const inst_data = sema.code.instructions.items(.data)[inst].ptr_type;
const extra = sema.code.extraData(Zir.Inst.PtrType, inst_data.payload_index);
var extra_i = extra.end;
const sentinel = if (inst_data.flags.has_sentinel) blk: {
const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
extra_i += 1;
break :blk (try sema.resolveInstConst(block, .unneeded, ref)).val;
} else null;
const abi_align = if (inst_data.flags.has_align) blk: {
const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
extra_i += 1;
break :blk try sema.resolveAlreadyCoercedInt(block, .unneeded, ref, u32);
} else 0;
const bit_start = if (inst_data.flags.has_bit_range) blk: {
const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
extra_i += 1;
break :blk try sema.resolveAlreadyCoercedInt(block, .unneeded, ref, u16);
} else 0;
const bit_end = if (inst_data.flags.has_bit_range) blk: {
const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
extra_i += 1;
break :blk try sema.resolveAlreadyCoercedInt(block, .unneeded, ref, u16);
} else 0;
if (bit_end != 0 and bit_start >= bit_end * 8)
return sema.mod.fail(&block.base, src, "bit offset starts after end of host integer", .{});
const elem_type = try sema.resolveType(block, .unneeded, extra.data.elem_type);
const ty = try sema.mod.ptrType(
sema.arena,
elem_type,
sentinel,
abi_align,
bit_start,
bit_end,
inst_data.flags.is_mutable,
inst_data.flags.is_allowzero,
inst_data.flags.is_volatile,
inst_data.size,
);
return sema.mod.constType(sema.arena, src, ty);
}
fn zirStructInitEmpty(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
const struct_type = try sema.resolveType(block, src, inst_data.operand);
return sema.mod.constInst(sema.arena, src, .{
.ty = struct_type,
.val = Value.initTag(.empty_struct_value),
});
}
fn zirUnionInitPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirUnionInitPtr", .{});
}
fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst {
const mod = sema.mod;
const gpa = sema.gpa;
const zir_datas = sema.code.instructions.items(.data);
const inst_data = zir_datas[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);
const src = inst_data.src();
const first_item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end).data;
const first_field_type_data = zir_datas[first_item.field_type].pl_node;
const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;
const unresolved_struct_type = try sema.resolveType(block, src, first_field_type_extra.container_type);
const struct_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);
const struct_obj = struct_ty.castTag(.@"struct").?.data;
// Maps field index to field_type index of where it was already initialized.
// For making sure all fields are accounted for and no fields are duplicated.
const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.entries.items.len);
defer gpa.free(found_fields);
mem.set(Zir.Inst.Index, found_fields, 0);
// The init values to use for the struct instance.
const field_inits = try gpa.alloc(*ir.Inst, struct_obj.fields.entries.items.len);
defer gpa.free(field_inits);
var field_i: u32 = 0;
var extra_index = extra.end;
while (field_i < extra.data.fields_len) : (field_i += 1) {
const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra_index);
extra_index = item.end;
const field_type_data = zir_datas[item.data.field_type].pl_node;
const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_type_data.src_node };
const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
const field_index = struct_obj.fields.getIndex(field_name) orelse
return sema.failWithBadFieldAccess(block, struct_obj, field_src, field_name);
if (found_fields[field_index] != 0) {
const other_field_type = found_fields[field_index];
const other_field_type_data = zir_datas[other_field_type].pl_node;
const other_field_src: LazySrcLoc = .{ .node_offset_back2tok = other_field_type_data.src_node };
const msg = msg: {
const msg = try mod.errMsg(&block.base, field_src, "duplicate field", .{});
errdefer msg.destroy(gpa);
try mod.errNote(&block.base, other_field_src, msg, "other field here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
found_fields[field_index] = item.data.field_type;
field_inits[field_index] = try sema.resolveInst(item.data.init);
}
var root_msg: ?*Module.ErrorMsg = null;
for (found_fields) |field_type_inst, i| {
if (field_type_inst != 0) continue;
// Check if the field has a default init.
const field = struct_obj.fields.entries.items[i].value;
if (field.default_val.tag() == .unreachable_value) {
const field_name = struct_obj.fields.entries.items[i].key;
const template = "missing struct field: {s}";
const args = .{field_name};
if (root_msg) |msg| {
try mod.errNote(&block.base, src, msg, template, args);
} else {
root_msg = try mod.errMsg(&block.base, src, template, args);
}
} else {
field_inits[i] = try mod.constInst(sema.arena, src, .{
.ty = field.ty,
.val = field.default_val,
});
}
}
if (root_msg) |msg| {
const fqn = try struct_obj.getFullyQualifiedName(gpa);
defer gpa.free(fqn);
try mod.errNoteNonLazy(
struct_obj.srcLoc(),
msg,
"struct '{s}' declared here",
.{fqn},
);
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
const is_comptime = for (field_inits) |field_init| {
if (field_init.value() == null) {
break false;
}
} else true;
if (is_comptime) {
const values = try sema.arena.alloc(Value, field_inits.len);
for (field_inits) |field_init, i| {
values[i] = field_init.value().?;
}
return mod.constInst(sema.arena, src, .{
.ty = struct_ty,
.val = try Value.Tag.@"struct".create(sema.arena, values.ptr),
});
}
return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known struct values", .{});
}
fn zirStructInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirStructInitAnon", .{});
}
fn zirArrayInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirArrayInit", .{});
}
fn zirArrayInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirArrayInitAnon", .{});
}
fn zirFieldTypeRef(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFieldTypeRef", .{});
}
fn zirFieldType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
const src = inst_data.src();
const field_name = sema.code.nullTerminatedString(extra.name_start);
const unresolved_struct_type = try sema.resolveType(block, src, extra.container_type);
if (unresolved_struct_type.zigTypeTag() != .Struct) {
return sema.mod.fail(&block.base, src, "expected struct; found '{}'", .{
unresolved_struct_type,
});
}
const struct_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);
const struct_obj = struct_ty.castTag(.@"struct").?.data;
const field = struct_obj.fields.get(field_name) orelse
return sema.failWithBadFieldAccess(block, struct_obj, src, field_name);
return sema.mod.constType(sema.arena, src, field.ty);
}
fn zirErrorReturnTrace(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: Sema.zirErrorReturnTrace", .{});
}
fn zirFrame(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFrame", .{});
}
fn zirFrameAddress(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFrameAddress", .{});
}
fn zirAlignOf(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAlignOf", .{});
}
fn zirBoolToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirBoolToInt", .{});
}
fn zirEmbedFile(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirEmbedFile", .{});
}
fn zirErrorName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirErrorName", .{});
}
fn zirUnaryMath(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirUnaryMath", .{});
}
fn zirTagName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirTagName", .{});
}
fn zirReify(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify", .{});
}
fn zirTypeName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirTypeName", .{});
}
fn zirFrameType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFrameType", .{});
}
fn zirFrameSize(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFrameSize", .{});
}
fn zirFloatToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFloatToInt", .{});
}
fn zirIntToFloat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirIntToFloat", .{});
}
fn zirIntToPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirIntToPtr", .{});
}
fn zirErrSetCast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirErrSetCast", .{});
}
fn zirPtrCast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirPtrCast", .{});
}
fn zirTruncate(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirTruncate", .{});
}
fn zirAlignCast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAlignCast", .{});
}
fn zirClz(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirClz", .{});
}
fn zirCtz(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirCtz", .{});
}
fn zirPopCount(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirPopCount", .{});
}
fn zirByteSwap(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirByteSwap", .{});
}
fn zirBitReverse(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirBitReverse", .{});
}
fn zirDivExact(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirDivExact", .{});
}
fn zirDivFloor(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirDivFloor", .{});
}
fn zirDivTrunc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirDivTrunc", .{});
}
fn zirMod(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirMod", .{});
}
fn zirRem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirRem", .{});
}
fn zirShlExact(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirShlExact", .{});
}
fn zirShrExact(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirShrExact", .{});
}
fn zirBitOffsetOf(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirBitOffsetOf", .{});
}
fn zirByteOffsetOf(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirByteOffsetOf", .{});
}
fn zirCmpxchg(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirCmpxchg", .{});
}
fn zirSplat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirSplat", .{});
}
fn zirReduce(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirReduce", .{});
}
fn zirShuffle(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirShuffle", .{});
}
fn zirAtomicLoad(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAtomicLoad", .{});
}
fn zirAtomicRmw(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAtomicRmw", .{});
}
fn zirAtomicStore(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAtomicStore", .{});
}
fn zirMulAdd(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirMulAdd", .{});
}
fn zirBuiltinCall(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirBuiltinCall", .{});
}
fn zirFieldPtrType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFieldPtrType", .{});
}
fn zirFieldParentPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirFieldParentPtr", .{});
}
fn zirMemcpy(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirMemcpy", .{});
}
fn zirMemset(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirMemset", .{});
}
fn zirBuiltinAsyncCall(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirBuiltinAsyncCall", .{});
}
fn zirResume(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirResume", .{});
}
fn zirAwait(
sema: *Sema,
block: *Scope.Block,
inst: Zir.Inst.Index,
is_nosuspend: bool,
) InnerError!*Inst {
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const src = inst_data.src();
return sema.mod.fail(&block.base, src, "TODO: Sema.zirAwait", .{});
}
fn zirVarExtended(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.ExtendedVar, extended.operand);
const src = sema.src;
const align_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at align
const ty_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at type
const mut_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at mut token
const init_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at init expr
const small = @bitCast(Zir.Inst.ExtendedVar.Small, extended.small);
const var_ty = try sema.resolveType(block, ty_src, extra.data.var_type);
var extra_index: usize = extra.end;
const lib_name: ?[]const u8 = if (small.has_lib_name) blk: {
const lib_name = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
extra_index += 1;
break :blk lib_name;
} else null;
// ZIR supports encoding this information but it is not used; the information
// is encoded via the Decl entry.
assert(!small.has_align);
//const align_val: Value = if (small.has_align) blk: {
// const align_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
// extra_index += 1;
// const align_tv = try sema.resolveInstConst(block, align_src, align_ref);
// break :blk align_tv.val;
//} else Value.initTag(.null_value);
const init_val: Value = if (small.has_init) blk: {
const init_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const init_tv = try sema.resolveInstConst(block, init_src, init_ref);
break :blk init_tv.val;
} else Value.initTag(.unreachable_value);
if (!var_ty.isValidVarType(small.is_extern)) {
return sema.mod.fail(&block.base, mut_src, "variable of type '{}' must be const", .{
var_ty,
});
}
if (lib_name != null) {
// Look at the sema code for functions which has this logic, it just needs to
// be extracted and shared by both var and func
return sema.mod.fail(&block.base, src, "TODO: handle var with lib_name in Sema", .{});
}
const new_var = try sema.gpa.create(Module.Var);
new_var.* = .{
.owner_decl = sema.owner_decl,
.init = init_val,
.is_extern = small.is_extern,
.is_mutable = true, // TODO get rid of this unused field
.is_threadlocal = small.is_threadlocal,
};
const result = try sema.mod.constInst(sema.arena, src, .{
.ty = var_ty,
.val = try Value.Tag.variable.create(sema.arena, new_var),
});
return result;
}
fn zirFuncExtended(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
inst: Zir.Inst.Index,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const extra = sema.code.extraData(Zir.Inst.ExtendedFunc, extended.operand);
const src: LazySrcLoc = .{ .node_offset = extra.data.src_node };
const cc_src: LazySrcLoc = .{ .node_offset_fn_type_cc = extra.data.src_node };
const align_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at align
const small = @bitCast(Zir.Inst.ExtendedFunc.Small, extended.small);
var extra_index: usize = extra.end;
const lib_name: ?[]const u8 = if (small.has_lib_name) blk: {
const lib_name = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
extra_index += 1;
break :blk lib_name;
} else null;
const cc: std.builtin.CallingConvention = if (small.has_cc) blk: {
const cc_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const cc_tv = try sema.resolveInstConst(block, cc_src, cc_ref);
break :blk cc_tv.val.toEnum(cc_tv.ty, std.builtin.CallingConvention);
} else .Unspecified;
const align_val: Value = if (small.has_align) blk: {
const align_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
extra_index += 1;
const align_tv = try sema.resolveInstConst(block, align_src, align_ref);
break :blk align_tv.val;
} else Value.initTag(.null_value);
const param_types = sema.code.refSlice(extra_index, extra.data.param_types_len);
extra_index += param_types.len;
var body_inst: Zir.Inst.Index = 0;
var src_locs: Zir.Inst.Func.SrcLocs = undefined;
if (extra.data.body_len != 0) {
body_inst = inst;
extra_index += extra.data.body_len;
src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
}
return sema.funcCommon(
block,
extra.data.src_node,
param_types,
body_inst,
extra.data.return_type,
cc,
align_val,
small.is_var_args,
small.is_inferred_error,
small.is_extern,
src_locs,
lib_name,
);
}
fn zirCUndef(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirCUndef", .{});
}
fn zirCInclude(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirCInclude", .{});
}
fn zirCDefine(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirCDefine", .{});
}
fn zirWasmMemorySize(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirWasmMemorySize", .{});
}
fn zirWasmMemoryGrow(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirWasmMemoryGrow", .{});
}
fn zirBuiltinExtern(
sema: *Sema,
block: *Scope.Block,
extended: Zir.Inst.Extended.InstData,
) InnerError!*Inst {
const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
const src: LazySrcLoc = .{ .node_offset = extra.node };
return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirBuiltinExtern", .{});
}
fn requireFunctionBlock(sema: *Sema, block: *Scope.Block, src: LazySrcLoc) !void {
if (sema.func == null) {
return sema.mod.fail(&block.base, src, "instruction illegal outside function body", .{});
}
}
fn requireRuntimeBlock(sema: *Sema, block: *Scope.Block, src: LazySrcLoc) !void {
if (block.is_comptime) {
return sema.failWithNeededComptime(block, src);
}
try sema.requireFunctionBlock(block, src);
}
fn validateVarType(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) !void {
if (!ty.isValidVarType(false)) {
return sema.mod.fail(&block.base, src, "variable of type '{}' must be const or comptime", .{ty});
}
}
pub const PanicId = enum {
unreach,
unwrap_null,
unwrap_errunion,
invalid_error_code,
};
fn addSafetyCheck(sema: *Sema, parent_block: *Scope.Block, ok: *Inst, panic_id: PanicId) !void {
const block_inst = try sema.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = Type.initTag(.void),
.src = ok.src,
},
.body = .{
.instructions = try sema.arena.alloc(*Inst, 1), // Only need space for the condbr.
},
};
const ok_body: ir.Body = .{
.instructions = try sema.arena.alloc(*Inst, 1), // Only need space for the br_void.
};
const br_void = try sema.arena.create(Inst.BrVoid);
br_void.* = .{
.base = .{
.tag = .br_void,
.ty = Type.initTag(.noreturn),
.src = ok.src,
},
.block = block_inst,
};
ok_body.instructions[0] = &br_void.base;
var fail_block: Scope.Block = .{
.parent = parent_block,
.sema = sema,
.src_decl = parent_block.src_decl,
.instructions = .{},
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
};
defer fail_block.instructions.deinit(sema.gpa);
_ = try sema.safetyPanic(&fail_block, ok.src, panic_id);
const fail_body: ir.Body = .{ .instructions = try sema.arena.dupe(*Inst, fail_block.instructions.items) };
const condbr = try sema.arena.create(Inst.CondBr);
condbr.* = .{
.base = .{
.tag = .condbr,
.ty = Type.initTag(.noreturn),
.src = ok.src,
},
.condition = ok,
.then_body = ok_body,
.else_body = fail_body,
};
block_inst.body.instructions[0] = &condbr.base;
try parent_block.instructions.append(sema.gpa, &block_inst.base);
}
fn safetyPanic(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, panic_id: PanicId) !Zir.Inst.Index {
// TODO Once we have a panic function to call, call it here instead of breakpoint.
_ = try block.addNoOp(src, Type.initTag(.void), .breakpoint);
_ = try block.addNoOp(src, Type.initTag(.noreturn), .unreach);
return always_noreturn;
}
fn emitBackwardBranch(sema: *Sema, block: *Scope.Block, src: LazySrcLoc) !void {
sema.branch_count += 1;
if (sema.branch_count > sema.branch_quota) {
// TODO show the "called from here" stack
return sema.mod.fail(&block.base, src, "evaluation exceeded {d} backwards branches", .{sema.branch_quota});
}
}
fn namedFieldPtr(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
object_ptr: *Inst,
field_name: []const u8,
field_name_src: LazySrcLoc,
) InnerError!*Inst {
const mod = sema.mod;
const arena = sema.arena;
const elem_ty = switch (object_ptr.ty.zigTypeTag()) {
.Pointer => object_ptr.ty.elemType(),
else => return mod.fail(&block.base, object_ptr.src, "expected pointer, found '{}'", .{object_ptr.ty}),
};
switch (elem_ty.zigTypeTag()) {
.Array => {
if (mem.eql(u8, field_name, "len")) {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.single_const_pointer_to_comptime_int),
.val = try Value.Tag.ref_val.create(
arena,
try Value.Tag.int_u64.create(arena, elem_ty.arrayLen()),
),
});
} else {
return mod.fail(
&block.base,
field_name_src,
"no member named '{s}' in '{}'",
.{ field_name, elem_ty },
);
}
},
.Pointer => {
const ptr_child = elem_ty.elemType();
switch (ptr_child.zigTypeTag()) {
.Array => {
if (mem.eql(u8, field_name, "len")) {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.single_const_pointer_to_comptime_int),
.val = try Value.Tag.ref_val.create(
arena,
try Value.Tag.int_u64.create(arena, ptr_child.arrayLen()),
),
});
} else {
return mod.fail(
&block.base,
field_name_src,
"no member named '{s}' in '{}'",
.{ field_name, elem_ty },
);
}
},
else => {},
}
},
.Type => {
_ = try sema.resolveConstValue(block, object_ptr.src, object_ptr);
const result = try sema.analyzeLoad(block, src, object_ptr, object_ptr.src);
const val = result.value().?;
const child_type = try val.toType(arena);
switch (child_type.zigTypeTag()) {
.ErrorSet => {
// TODO resolve inferred error sets
const name: []const u8 = if (child_type.castTag(.error_set)) |payload| blk: {
const error_set = payload.data;
// TODO this is O(N). I'm putting off solving this until we solve inferred
// error sets at the same time.
const names = error_set.names_ptr[0..error_set.names_len];
for (names) |name| {
if (mem.eql(u8, field_name, name)) {
break :blk name;
}
}
return mod.fail(&block.base, src, "no error named '{s}' in '{}'", .{
field_name,
child_type,
});
} else (try mod.getErrorValue(field_name)).key;
return mod.constInst(arena, src, .{
.ty = try mod.simplePtrType(arena, child_type, false, .One),
.val = try Value.Tag.ref_val.create(
arena,
try Value.Tag.@"error".create(arena, .{
.name = name,
}),
),
});
},
.Struct, .Opaque, .Union => {
if (child_type.getNamespace()) |namespace| {
if (try sema.analyzeNamespaceLookup(block, src, namespace, field_name)) |inst| {
return inst;
}
}
// TODO add note: declared here
const kw_name = switch (child_type.zigTypeTag()) {
.Struct => "struct",
.Opaque => "opaque",
.Union => "union",
else => unreachable,
};
return mod.fail(&block.base, src, "{s} '{}' has no member named '{s}'", .{
kw_name, child_type, field_name,
});
},
.Enum => {
if (child_type.getNamespace()) |namespace| {
if (try sema.analyzeNamespaceLookup(block, src, namespace, field_name)) |inst| {
return inst;
}
}
const field_index = child_type.enumFieldIndex(field_name) orelse {
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
src,
"enum '{}' has no member named '{s}'",
.{ child_type, field_name },
);
errdefer msg.destroy(sema.gpa);
try mod.errNoteNonLazy(
child_type.declSrcLoc(),
msg,
"enum declared here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
};
const field_index_u32 = @intCast(u32, field_index);
const enum_val = try Value.Tag.enum_field_index.create(arena, field_index_u32);
return mod.constInst(arena, src, .{
.ty = try mod.simplePtrType(arena, child_type, false, .One),
.val = try Value.Tag.ref_val.create(arena, enum_val),
});
},
else => return mod.fail(&block.base, src, "type '{}' has no members", .{child_type}),
}
},
.Struct => return sema.analyzeStructFieldPtr(block, src, object_ptr, field_name, field_name_src, elem_ty),
.Union => return sema.analyzeUnionFieldPtr(block, src, object_ptr, field_name, field_name_src, elem_ty),
else => {},
}
return mod.fail(&block.base, src, "type '{}' does not support field access", .{elem_ty});
}
fn analyzeNamespaceLookup(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
namespace: *Scope.Namespace,
decl_name: []const u8,
) InnerError!?*Inst {
const mod = sema.mod;
const gpa = sema.gpa;
if (try sema.lookupInNamespace(namespace, decl_name)) |decl| {
if (!decl.is_pub and decl.namespace.file_scope != block.getFileScope()) {
const msg = msg: {
const msg = try mod.errMsg(&block.base, src, "'{s}' is not marked 'pub'", .{
decl_name,
});
errdefer msg.destroy(gpa);
try mod.errNoteNonLazy(decl.srcLoc(), msg, "declared here", .{});
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
}
return try sema.analyzeDeclRef(block, src, decl);
}
return null;
}
fn analyzeStructFieldPtr(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
struct_ptr: *Inst,
field_name: []const u8,
field_name_src: LazySrcLoc,
unresolved_struct_ty: Type,
) InnerError!*Inst {
const mod = sema.mod;
const arena = sema.arena;
assert(unresolved_struct_ty.zigTypeTag() == .Struct);
const struct_ty = try sema.resolveTypeFields(block, src, unresolved_struct_ty);
const struct_obj = struct_ty.castTag(.@"struct").?.data;
const field_index = struct_obj.fields.getIndex(field_name) orelse
return sema.failWithBadFieldAccess(block, struct_obj, field_name_src, field_name);
const field = struct_obj.fields.entries.items[field_index].value;
const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One);
if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| {
return mod.constInst(arena, src, .{
.ty = ptr_field_ty,
.val = try Value.Tag.field_ptr.create(arena, .{
.container_ptr = struct_ptr_val,
.field_index = field_index,
}),
});
}
try sema.requireRuntimeBlock(block, src);
return block.addStructFieldPtr(src, ptr_field_ty, struct_ptr, @intCast(u32, field_index));
}
fn analyzeUnionFieldPtr(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
union_ptr: *Inst,
field_name: []const u8,
field_name_src: LazySrcLoc,
unresolved_union_ty: Type,
) InnerError!*Inst {
const mod = sema.mod;
const arena = sema.arena;
assert(unresolved_union_ty.zigTypeTag() == .Union);
const union_ty = try sema.resolveTypeFields(block, src, unresolved_union_ty);
const union_obj = union_ty.cast(Type.Payload.Union).?.data;
const field_index = union_obj.fields.getIndex(field_name) orelse
return sema.failWithBadUnionFieldAccess(block, union_obj, field_name_src, field_name);
const field = union_obj.fields.entries.items[field_index].value;
const ptr_field_ty = try mod.simplePtrType(arena, field.ty, true, .One);
if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| {
// TODO detect inactive union field and emit compile error
return mod.constInst(arena, src, .{
.ty = ptr_field_ty,
.val = try Value.Tag.field_ptr.create(arena, .{
.container_ptr = union_ptr_val,
.field_index = field_index,
}),
});
}
try sema.requireRuntimeBlock(block, src);
return mod.fail(&block.base, src, "TODO implement runtime union field access", .{});
}
fn elemPtr(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
array_ptr: *Inst,
elem_index: *Inst,
elem_index_src: LazySrcLoc,
) InnerError!*Inst {
const array_ty = switch (array_ptr.ty.zigTypeTag()) {
.Pointer => array_ptr.ty.elemType(),
else => return sema.mod.fail(&block.base, array_ptr.src, "expected pointer, found '{}'", .{array_ptr.ty}),
};
if (!array_ty.isIndexable()) {
return sema.mod.fail(&block.base, src, "array access of non-array type '{}'", .{array_ty});
}
if (array_ty.isSinglePointer() and array_ty.elemType().zigTypeTag() == .Array) {
// we have to deref the ptr operand to get the actual array pointer
const array_ptr_deref = try sema.analyzeLoad(block, src, array_ptr, array_ptr.src);
return sema.elemPtrArray(block, src, array_ptr_deref, elem_index, elem_index_src);
}
if (array_ty.zigTypeTag() == .Array) {
return sema.elemPtrArray(block, src, array_ptr, elem_index, elem_index_src);
}
return sema.mod.fail(&block.base, src, "TODO implement more analyze elemptr", .{});
}
fn elemPtrArray(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
array_ptr: *Inst,
elem_index: *Inst,
elem_index_src: LazySrcLoc,
) InnerError!*Inst {
if (array_ptr.value()) |array_ptr_val| {
if (elem_index.value()) |index_val| {
// Both array pointer and index are compile-time known.
const index_u64 = index_val.toUnsignedInt();
// @intCast here because it would have been impossible to construct a value that
// required a larger index.
const elem_ptr = try array_ptr_val.elemPtr(sema.arena, @intCast(usize, index_u64));
const pointee_type = array_ptr.ty.elemType().elemType();
return sema.mod.constInst(sema.arena, src, .{
.ty = try Type.Tag.single_const_pointer.create(sema.arena, pointee_type),
.val = elem_ptr,
});
}
}
return sema.mod.fail(&block.base, src, "TODO implement more analyze elemptr for arrays", .{});
}
fn coerce(
sema: *Sema,
block: *Scope.Block,
dest_type: Type,
inst: *Inst,
inst_src: LazySrcLoc,
) InnerError!*Inst {
if (dest_type.tag() == .var_args_param) {
return sema.coerceVarArgParam(block, inst);
}
// If the types are the same, we can return the operand.
if (dest_type.eql(inst.ty))
return inst;
const in_memory_result = coerceInMemoryAllowed(dest_type, inst.ty);
if (in_memory_result == .ok) {
return sema.bitcast(block, dest_type, inst);
}
const mod = sema.mod;
const arena = sema.arena;
// undefined to anything
if (inst.value()) |val| {
if (val.isUndef() or inst.ty.zigTypeTag() == .Undefined) {
return mod.constInst(arena, inst_src, .{ .ty = dest_type, .val = val });
}
}
assert(inst.ty.zigTypeTag() != .Undefined);
// T to E!T or E to E!T
if (dest_type.tag() == .error_union) {
return try sema.wrapErrorUnion(block, dest_type, inst);
}
// comptime known number to other number
if (try sema.coerceNum(block, dest_type, inst)) |some|
return some;
const target = mod.getTarget();
switch (dest_type.zigTypeTag()) {
.Optional => {
// null to ?T
if (inst.ty.zigTypeTag() == .Null) {
return mod.constInst(arena, inst_src, .{ .ty = dest_type, .val = Value.initTag(.null_value) });
}
// T to ?T
var buf: Type.Payload.ElemType = undefined;
const child_type = dest_type.optionalChild(&buf);
if (child_type.eql(inst.ty)) {
return sema.wrapOptional(block, dest_type, inst);
} else if (try sema.coerceNum(block, child_type, inst)) |some| {
return sema.wrapOptional(block, dest_type, some);
}
},
.Pointer => {
// Coercions where the source is a single pointer to an array.
src_array_ptr: {
if (!inst.ty.isSinglePointer()) break :src_array_ptr;
const array_type = inst.ty.elemType();
if (array_type.zigTypeTag() != .Array) break :src_array_ptr;
const array_elem_type = array_type.elemType();
if (inst.ty.isConstPtr() and !dest_type.isConstPtr()) break :src_array_ptr;
if (inst.ty.isVolatilePtr() and !dest_type.isVolatilePtr()) break :src_array_ptr;
const dst_elem_type = dest_type.elemType();
switch (coerceInMemoryAllowed(dst_elem_type, array_elem_type)) {
.ok => {},
.no_match => break :src_array_ptr,
}
switch (dest_type.ptrSize()) {
.Slice => {
// *[N]T to []T
return sema.coerceArrayPtrToSlice(block, dest_type, inst);
},
.C => {
// *[N]T to [*c]T
return sema.coerceArrayPtrToMany(block, dest_type, inst);
},
.Many => {
// *[N]T to [*]T
// *[N:s]T to [*:s]T
const src_sentinel = array_type.sentinel();
const dst_sentinel = dest_type.sentinel();
if (src_sentinel == null and dst_sentinel == null)
return sema.coerceArrayPtrToMany(block, dest_type, inst);
if (src_sentinel) |src_s| {
if (dst_sentinel) |dst_s| {
if (src_s.eql(dst_s)) {
return sema.coerceArrayPtrToMany(block, dest_type, inst);
}
}
}
},
.One => {},
}
}
},
.Int => {
// integer widening
if (inst.ty.zigTypeTag() == .Int) {
assert(inst.value() == null); // handled above
const dst_info = dest_type.intInfo(target);
const src_info = inst.ty.intInfo(target);
if ((src_info.signedness == dst_info.signedness and dst_info.bits >= src_info.bits) or
// small enough unsigned ints can get casted to large enough signed ints
(src_info.signedness == .signed and dst_info.signedness == .unsigned and dst_info.bits > src_info.bits))
{
try sema.requireRuntimeBlock(block, inst_src);
return block.addUnOp(inst_src, dest_type, .intcast, inst);
}
}
},
.Float => {
// float widening
if (inst.ty.zigTypeTag() == .Float) {
assert(inst.value() == null); // handled above
const src_bits = inst.ty.floatBits(target);
const dst_bits = dest_type.floatBits(target);
if (dst_bits >= src_bits) {
try sema.requireRuntimeBlock(block, inst_src);
return block.addUnOp(inst_src, dest_type, .floatcast, inst);
}
}
},
.Enum => {
// enum literal to enum
if (inst.ty.zigTypeTag() == .EnumLiteral) {
const val = try sema.resolveConstValue(block, inst_src, inst);
const bytes = val.castTag(.enum_literal).?.data;
const resolved_dest_type = try sema.resolveTypeFields(block, inst_src, dest_type);
const field_index = resolved_dest_type.enumFieldIndex(bytes) orelse {
const msg = msg: {
const msg = try mod.errMsg(
&block.base,
inst_src,
"enum '{}' has no field named '{s}'",
.{ resolved_dest_type, bytes },
);
errdefer msg.destroy(sema.gpa);
try mod.errNoteNonLazy(
resolved_dest_type.declSrcLoc(),
msg,
"enum declared here",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(&block.base, msg);
};
return mod.constInst(arena, inst_src, .{
.ty = resolved_dest_type,
.val = try Value.Tag.enum_field_index.create(arena, @intCast(u32, field_index)),
});
}
},
else => {},
}
return mod.fail(&block.base, inst_src, "expected {}, found {}", .{ dest_type, inst.ty });
}
const InMemoryCoercionResult = enum {
ok,
no_match,
};
fn coerceInMemoryAllowed(dest_type: Type, src_type: Type) InMemoryCoercionResult {
if (dest_type.eql(src_type))
return .ok;
// TODO: implement more of this function
return .no_match;
}
fn coerceNum(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) InnerError!?*Inst {
const val = inst.value() orelse return null;
const src_zig_tag = inst.ty.zigTypeTag();
const dst_zig_tag = dest_type.zigTypeTag();
const target = sema.mod.getTarget();
if (dst_zig_tag == .ComptimeInt or dst_zig_tag == .Int) {
if (src_zig_tag == .Float or src_zig_tag == .ComptimeFloat) {
if (val.floatHasFraction()) {
return sema.mod.fail(&block.base, inst.src, "fractional component prevents float value {} from being casted to type '{}'", .{ val, inst.ty });
}
return sema.mod.fail(&block.base, inst.src, "TODO float to int", .{});
} else if (src_zig_tag == .Int or src_zig_tag == .ComptimeInt) {
if (!val.intFitsInType(dest_type, target)) {
return sema.mod.fail(&block.base, inst.src, "type {} cannot represent integer value {}", .{ inst.ty, val });
}
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = val });
}
} else if (dst_zig_tag == .ComptimeFloat or dst_zig_tag == .Float) {
if (src_zig_tag == .Float or src_zig_tag == .ComptimeFloat) {
const res = val.floatCast(sema.arena, dest_type, target) catch |err| switch (err) {
error.Overflow => return sema.mod.fail(
&block.base,
inst.src,
"cast of value {} to type '{}' loses information",
.{ val, dest_type },
),
error.OutOfMemory => return error.OutOfMemory,
};
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = res });
} else if (src_zig_tag == .Int or src_zig_tag == .ComptimeInt) {
return sema.mod.fail(&block.base, inst.src, "TODO int to float", .{});
}
}
return null;
}
fn coerceVarArgParam(sema: *Sema, block: *Scope.Block, inst: *Inst) !*Inst {
switch (inst.ty.zigTypeTag()) {
.ComptimeInt, .ComptimeFloat => return sema.mod.fail(&block.base, inst.src, "integer and float literals in var args function must be casted", .{}),
else => {},
}
// TODO implement more of this function.
return inst;
}
fn storePtr(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
ptr: *Inst,
uncasted_value: *Inst,
) !void {
if (ptr.ty.isConstPtr())
return sema.mod.fail(&block.base, src, "cannot assign to constant", .{});
const elem_ty = ptr.ty.elemType();
const value = try sema.coerce(block, elem_ty, uncasted_value, src);
if ((try sema.typeHasOnePossibleValue(block, src, elem_ty)) != null)
return;
// TODO handle comptime pointer writes
// TODO handle if the element type requires comptime
try sema.requireRuntimeBlock(block, src);
_ = try block.addBinOp(src, Type.initTag(.void), .store, ptr, value);
}
fn bitcast(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
// Keep the comptime Value representation; take the new type.
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = val });
}
// TODO validate the type size and other compile errors
try sema.requireRuntimeBlock(block, inst.src);
return block.addUnOp(inst.src, dest_type, .bitcast, inst);
}
fn coerceArrayPtrToSlice(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
// The comptime Value representation is compatible with both types.
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = val });
}
return sema.mod.fail(&block.base, inst.src, "TODO implement coerceArrayPtrToSlice runtime instruction", .{});
}
fn coerceArrayPtrToMany(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
// The comptime Value representation is compatible with both types.
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = val });
}
return sema.mod.fail(&block.base, inst.src, "TODO implement coerceArrayPtrToMany runtime instruction", .{});
}
fn analyzeDeclVal(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, decl: *Decl) InnerError!*Inst {
const decl_ref = try sema.analyzeDeclRef(block, src, decl);
return sema.analyzeLoad(block, src, decl_ref, src);
}
fn analyzeDeclRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, decl: *Decl) InnerError!*Inst {
try sema.mod.declareDeclDependency(sema.owner_decl, decl);
sema.mod.ensureDeclAnalyzed(decl) catch |err| {
if (sema.func) |func| {
func.state = .dependency_failure;
} else {
sema.owner_decl.analysis = .dependency_failure;
}
return err;
};
const decl_tv = try decl.typedValue();
if (decl_tv.val.tag() == .variable) {
return sema.analyzeVarRef(block, src, decl_tv);
}
return sema.mod.constInst(sema.arena, src, .{
.ty = try sema.mod.simplePtrType(sema.arena, decl_tv.ty, false, .One),
.val = try Value.Tag.decl_ref.create(sema.arena, decl),
});
}
fn analyzeVarRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, tv: TypedValue) InnerError!*Inst {
const variable = tv.val.castTag(.variable).?.data;
const ty = try sema.mod.simplePtrType(sema.arena, tv.ty, variable.is_mutable, .One);
if (!variable.is_mutable and !variable.is_extern) {
return sema.mod.constInst(sema.arena, src, .{
.ty = ty,
.val = try Value.Tag.ref_val.create(sema.arena, variable.init),
});
}
try sema.requireRuntimeBlock(block, src);
const inst = try sema.arena.create(Inst.VarPtr);
inst.* = .{
.base = .{
.tag = .varptr,
.ty = ty,
.src = src,
},
.variable = variable,
};
try block.instructions.append(sema.gpa, &inst.base);
return &inst.base;
}
fn analyzeRef(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
operand: *Inst,
) InnerError!*Inst {
const ptr_type = try sema.mod.simplePtrType(sema.arena, operand.ty, false, .One);
if (try sema.resolvePossiblyUndefinedValue(block, src, operand)) |val| {
return sema.mod.constInst(sema.arena, src, .{
.ty = ptr_type,
.val = try Value.Tag.ref_val.create(sema.arena, val),
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, ptr_type, .ref, operand);
}
fn analyzeLoad(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
ptr: *Inst,
ptr_src: LazySrcLoc,
) InnerError!*Inst {
const elem_ty = switch (ptr.ty.zigTypeTag()) {
.Pointer => ptr.ty.elemType(),
else => return sema.mod.fail(&block.base, ptr_src, "expected pointer, found '{}'", .{ptr.ty}),
};
if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
return sema.mod.constInst(sema.arena, src, .{
.ty = elem_ty,
.val = try ptr_val.pointerDeref(sema.arena),
});
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, elem_ty, .load, ptr);
}
fn analyzeIsNull(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
operand: *Inst,
invert_logic: bool,
) InnerError!*Inst {
const result_ty = Type.initTag(.bool);
if (try sema.resolvePossiblyUndefinedValue(block, src, operand)) |opt_val| {
if (opt_val.isUndef()) {
return sema.mod.constUndef(sema.arena, src, result_ty);
}
const is_null = opt_val.isNull();
const bool_value = if (invert_logic) !is_null else is_null;
return sema.mod.constBool(sema.arena, src, bool_value);
}
try sema.requireRuntimeBlock(block, src);
const inst_tag: Inst.Tag = if (invert_logic) .is_non_null else .is_null;
return block.addUnOp(src, result_ty, inst_tag, operand);
}
fn analyzeIsErr(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, operand: *Inst) InnerError!*Inst {
const ot = operand.ty.zigTypeTag();
if (ot != .ErrorSet and ot != .ErrorUnion) return sema.mod.constBool(sema.arena, src, false);
if (ot == .ErrorSet) return sema.mod.constBool(sema.arena, src, true);
assert(ot == .ErrorUnion);
const result_ty = Type.initTag(.bool);
if (try sema.resolvePossiblyUndefinedValue(block, src, operand)) |err_union| {
if (err_union.isUndef()) {
return sema.mod.constUndef(sema.arena, src, result_ty);
}
return sema.mod.constBool(sema.arena, src, err_union.getError() != null);
}
try sema.requireRuntimeBlock(block, src);
return block.addUnOp(src, result_ty, .is_err, operand);
}
fn analyzeSlice(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
array_ptr: *Inst,
start: *Inst,
end_opt: ?*Inst,
sentinel_opt: ?*Inst,
sentinel_src: LazySrcLoc,
) InnerError!*Inst {
const ptr_child = switch (array_ptr.ty.zigTypeTag()) {
.Pointer => array_ptr.ty.elemType(),
else => return sema.mod.fail(&block.base, src, "expected pointer, found '{}'", .{array_ptr.ty}),
};
var array_type = ptr_child;
const elem_type = switch (ptr_child.zigTypeTag()) {
.Array => ptr_child.elemType(),
.Pointer => blk: {
if (ptr_child.isSinglePointer()) {
if (ptr_child.elemType().zigTypeTag() == .Array) {
array_type = ptr_child.elemType();
break :blk ptr_child.elemType().elemType();
}
return sema.mod.fail(&block.base, src, "slice of single-item pointer", .{});
}
break :blk ptr_child.elemType();
},
else => return sema.mod.fail(&block.base, src, "slice of non-array type '{}'", .{ptr_child}),
};
const slice_sentinel = if (sentinel_opt) |sentinel| blk: {
const casted = try sema.coerce(block, elem_type, sentinel, sentinel.src);
break :blk try sema.resolveConstValue(block, sentinel_src, casted);
} else null;
var return_ptr_size: std.builtin.TypeInfo.Pointer.Size = .Slice;
var return_elem_type = elem_type;
if (end_opt) |end| {
if (end.value()) |end_val| {
if (start.value()) |start_val| {
const start_u64 = start_val.toUnsignedInt();
const end_u64 = end_val.toUnsignedInt();
if (start_u64 > end_u64) {
return sema.mod.fail(&block.base, src, "out of bounds slice", .{});
}
const len = end_u64 - start_u64;
const array_sentinel = if (array_type.zigTypeTag() == .Array and end_u64 == array_type.arrayLen())
array_type.sentinel()
else
slice_sentinel;
return_elem_type = try sema.mod.arrayType(sema.arena, len, array_sentinel, elem_type);
return_ptr_size = .One;
}
}
}
const return_type = try sema.mod.ptrType(
sema.arena,
return_elem_type,
if (end_opt == null) slice_sentinel else null,
0, // TODO alignment
0,
0,
!ptr_child.isConstPtr(),
ptr_child.isAllowzeroPtr(),
ptr_child.isVolatilePtr(),
return_ptr_size,
);
return sema.mod.fail(&block.base, src, "TODO implement analysis of slice", .{});
}
/// Asserts that lhs and rhs types are both numeric.
fn cmpNumeric(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
lhs: *Inst,
rhs: *Inst,
op: std.math.CompareOperator,
) InnerError!*Inst {
assert(lhs.ty.isNumeric());
assert(rhs.ty.isNumeric());
const lhs_ty_tag = lhs.ty.zigTypeTag();
const rhs_ty_tag = rhs.ty.zigTypeTag();
if (lhs_ty_tag == .Vector and rhs_ty_tag == .Vector) {
if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) {
return sema.mod.fail(&block.base, src, "vector length mismatch: {d} and {d}", .{
lhs.ty.arrayLen(),
rhs.ty.arrayLen(),
});
}
return sema.mod.fail(&block.base, src, "TODO implement support for vectors in cmpNumeric", .{});
} else if (lhs_ty_tag == .Vector or rhs_ty_tag == .Vector) {
return sema.mod.fail(&block.base, src, "mixed scalar and vector operands to comparison operator: '{}' and '{}'", .{
lhs.ty,
rhs.ty,
});
}
if (lhs.value()) |lhs_val| {
if (rhs.value()) |rhs_val| {
return sema.mod.constBool(sema.arena, src, Value.compare(lhs_val, op, rhs_val));
}
}
// TODO handle comparisons against lazy zero values
// Some values can be compared against zero without being runtime known or without forcing
// a full resolution of their value, for example `@sizeOf(@Frame(function))` is known to
// always be nonzero, and we benefit from not forcing the full evaluation and stack frame layout
// of this function if we don't need to.
// It must be a runtime comparison.
try sema.requireRuntimeBlock(block, src);
// For floats, emit a float comparison instruction.
const lhs_is_float = switch (lhs_ty_tag) {
.Float, .ComptimeFloat => true,
else => false,
};
const rhs_is_float = switch (rhs_ty_tag) {
.Float, .ComptimeFloat => true,
else => false,
};
const target = sema.mod.getTarget();
if (lhs_is_float and rhs_is_float) {
// Implicit cast the smaller one to the larger one.
const dest_type = x: {
if (lhs_ty_tag == .ComptimeFloat) {
break :x rhs.ty;
} else if (rhs_ty_tag == .ComptimeFloat) {
break :x lhs.ty;
}
if (lhs.ty.floatBits(target) >= rhs.ty.floatBits(target)) {
break :x lhs.ty;
} else {
break :x rhs.ty;
}
};
const casted_lhs = try sema.coerce(block, dest_type, lhs, lhs.src);
const casted_rhs = try sema.coerce(block, dest_type, rhs, rhs.src);
return block.addBinOp(src, dest_type, Inst.Tag.fromCmpOp(op), casted_lhs, casted_rhs);
}
// For mixed unsigned integer sizes, implicit cast both operands to the larger integer.
// For mixed signed and unsigned integers, implicit cast both operands to a signed
// integer with + 1 bit.
// For mixed floats and integers, extract the integer part from the float, cast that to
// a signed integer with mantissa bits + 1, and if there was any non-integral part of the float,
// add/subtract 1.
const lhs_is_signed = if (lhs.value()) |lhs_val|
lhs_val.compareWithZero(.lt)
else
(lhs.ty.isFloat() or lhs.ty.isSignedInt());
const rhs_is_signed = if (rhs.value()) |rhs_val|
rhs_val.compareWithZero(.lt)
else
(rhs.ty.isFloat() or rhs.ty.isSignedInt());
const dest_int_is_signed = lhs_is_signed or rhs_is_signed;
var dest_float_type: ?Type = null;
var lhs_bits: usize = undefined;
if (lhs.value()) |lhs_val| {
if (lhs_val.isUndef())
return sema.mod.constUndef(sema.arena, src, Type.initTag(.bool));
const is_unsigned = if (lhs_is_float) x: {
var bigint_space: Value.BigIntSpace = undefined;
var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(sema.gpa);
defer bigint.deinit();
const zcmp = lhs_val.orderAgainstZero();
if (lhs_val.floatHasFraction()) {
switch (op) {
.eq => return sema.mod.constBool(sema.arena, src, false),
.neq => return sema.mod.constBool(sema.arena, src, true),
else => {},
}
if (zcmp == .lt) {
try bigint.addScalar(bigint.toConst(), -1);
} else {
try bigint.addScalar(bigint.toConst(), 1);
}
}
lhs_bits = bigint.toConst().bitCountTwosComp();
break :x (zcmp != .lt);
} else x: {
lhs_bits = lhs_val.intBitCountTwosComp();
break :x (lhs_val.orderAgainstZero() != .lt);
};
lhs_bits += @boolToInt(is_unsigned and dest_int_is_signed);
} else if (lhs_is_float) {
dest_float_type = lhs.ty;
} else {
const int_info = lhs.ty.intInfo(target);
lhs_bits = int_info.bits + @boolToInt(int_info.signedness == .unsigned and dest_int_is_signed);
}
var rhs_bits: usize = undefined;
if (rhs.value()) |rhs_val| {
if (rhs_val.isUndef())
return sema.mod.constUndef(sema.arena, src, Type.initTag(.bool));
const is_unsigned = if (rhs_is_float) x: {
var bigint_space: Value.BigIntSpace = undefined;
var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(sema.gpa);
defer bigint.deinit();
const zcmp = rhs_val.orderAgainstZero();
if (rhs_val.floatHasFraction()) {
switch (op) {
.eq => return sema.mod.constBool(sema.arena, src, false),
.neq => return sema.mod.constBool(sema.arena, src, true),
else => {},
}
if (zcmp == .lt) {
try bigint.addScalar(bigint.toConst(), -1);
} else {
try bigint.addScalar(bigint.toConst(), 1);
}
}
rhs_bits = bigint.toConst().bitCountTwosComp();
break :x (zcmp != .lt);
} else x: {
rhs_bits = rhs_val.intBitCountTwosComp();
break :x (rhs_val.orderAgainstZero() != .lt);
};
rhs_bits += @boolToInt(is_unsigned and dest_int_is_signed);
} else if (rhs_is_float) {
dest_float_type = rhs.ty;
} else {
const int_info = rhs.ty.intInfo(target);
rhs_bits = int_info.bits + @boolToInt(int_info.signedness == .unsigned and dest_int_is_signed);
}
const dest_type = if (dest_float_type) |ft| ft else blk: {
const max_bits = std.math.max(lhs_bits, rhs_bits);
const casted_bits = std.math.cast(u16, max_bits) catch |err| switch (err) {
error.Overflow => return sema.mod.fail(&block.base, src, "{d} exceeds maximum integer bit count", .{max_bits}),
};
const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;
break :blk try Module.makeIntType(sema.arena, signedness, casted_bits);
};
const casted_lhs = try sema.coerce(block, dest_type, lhs, lhs.src);
const casted_rhs = try sema.coerce(block, dest_type, rhs, rhs.src);
return block.addBinOp(src, Type.initTag(.bool), Inst.Tag.fromCmpOp(op), casted_lhs, casted_rhs);
}
fn wrapOptional(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) !*Inst {
if (inst.value()) |val| {
return sema.mod.constInst(sema.arena, inst.src, .{ .ty = dest_type, .val = val });
}
try sema.requireRuntimeBlock(block, inst.src);
return block.addUnOp(inst.src, dest_type, .wrap_optional, inst);
}
fn wrapErrorUnion(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst) !*Inst {
// TODO deal with inferred error sets
const err_union = dest_type.castTag(.error_union).?;
if (inst.value()) |val| {
const to_wrap = if (inst.ty.zigTypeTag() != .ErrorSet) blk: {
_ = try sema.coerce(block, err_union.data.payload, inst, inst.src);
break :blk val;
} else switch (err_union.data.error_set.tag()) {
.anyerror => val,
.error_set_single => blk: {
const expected_name = val.castTag(.@"error").?.data.name;
const n = err_union.data.error_set.castTag(.error_set_single).?.data;
if (!mem.eql(u8, expected_name, n)) {
return sema.mod.fail(
&block.base,
inst.src,
"expected type '{}', found type '{}'",
.{ err_union.data.error_set, inst.ty },
);
}
break :blk val;
},
.error_set => blk: {
const expected_name = val.castTag(.@"error").?.data.name;
const error_set = err_union.data.error_set.castTag(.error_set).?.data;
const names = error_set.names_ptr[0..error_set.names_len];
// TODO this is O(N). I'm putting off solving this until we solve inferred
// error sets at the same time.
const found = for (names) |name| {
if (mem.eql(u8, expected_name, name)) break true;
} else false;
if (!found) {
return sema.mod.fail(
&block.base,
inst.src,
"expected type '{}', found type '{}'",
.{ err_union.data.error_set, inst.ty },
);
}
break :blk val;
},
else => unreachable,
};
return sema.mod.constInst(sema.arena, inst.src, .{
.ty = dest_type,
// creating a SubValue for the error_union payload
.val = try Value.Tag.error_union.create(
sema.arena,
to_wrap,
),
});
}
try sema.requireRuntimeBlock(block, inst.src);
// we are coercing from E to E!T
if (inst.ty.zigTypeTag() == .ErrorSet) {
var coerced = try sema.coerce(block, err_union.data.error_set, inst, inst.src);
return block.addUnOp(inst.src, dest_type, .wrap_errunion_err, coerced);
} else {
var coerced = try sema.coerce(block, err_union.data.payload, inst, inst.src);
return block.addUnOp(inst.src, dest_type, .wrap_errunion_payload, coerced);
}
}
fn resolvePeerTypes(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, instructions: []*Inst) !Type {
if (instructions.len == 0)
return Type.initTag(.noreturn);
if (instructions.len == 1)
return instructions[0].ty;
const target = sema.mod.getTarget();
var chosen = instructions[0];
for (instructions[1..]) |candidate| {
if (candidate.ty.eql(chosen.ty))
continue;
if (candidate.ty.zigTypeTag() == .NoReturn)
continue;
if (chosen.ty.zigTypeTag() == .NoReturn) {
chosen = candidate;
continue;
}
if (candidate.ty.zigTypeTag() == .Undefined)
continue;
if (chosen.ty.zigTypeTag() == .Undefined) {
chosen = candidate;
continue;
}
if (chosen.ty.isInt() and
candidate.ty.isInt() and
chosen.ty.isSignedInt() == candidate.ty.isSignedInt())
{
if (chosen.ty.intInfo(target).bits < candidate.ty.intInfo(target).bits) {
chosen = candidate;
}
continue;
}
if (chosen.ty.isFloat() and candidate.ty.isFloat()) {
if (chosen.ty.floatBits(target) < candidate.ty.floatBits(target)) {
chosen = candidate;
}
continue;
}
if (chosen.ty.zigTypeTag() == .ComptimeInt and candidate.ty.isInt()) {
chosen = candidate;
continue;
}
if (chosen.ty.isInt() and candidate.ty.zigTypeTag() == .ComptimeInt) {
continue;
}
if (chosen.ty.zigTypeTag() == .Enum and candidate.ty.zigTypeTag() == .EnumLiteral) {
continue;
}
if (chosen.ty.zigTypeTag() == .EnumLiteral and candidate.ty.zigTypeTag() == .Enum) {
chosen = candidate;
continue;
}
// TODO error notes pointing out each type
return sema.mod.fail(&block.base, src, "incompatible types: '{}' and '{}'", .{ chosen.ty, candidate.ty });
}
return chosen.ty;
}
fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) InnerError!Type {
switch (ty.tag()) {
.@"struct" => {
const struct_obj = ty.castTag(.@"struct").?.data;
switch (struct_obj.status) {
.none => {},
.field_types_wip => {
return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{
ty,
});
},
.have_field_types, .have_layout, .layout_wip => return ty,
}
struct_obj.status = .field_types_wip;
try sema.mod.analyzeStructFields(struct_obj);
struct_obj.status = .have_field_types;
return ty;
},
.extern_options => return sema.resolveBuiltinTypeFields(block, src, ty, "ExternOptions"),
.export_options => return sema.resolveBuiltinTypeFields(block, src, ty, "ExportOptions"),
.atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, ty, "AtomicOrdering"),
.atomic_rmw_op => return sema.resolveBuiltinTypeFields(block, src, ty, "AtomicRmwOp"),
.calling_convention => return sema.resolveBuiltinTypeFields(block, src, ty, "CallingConvention"),
.float_mode => return sema.resolveBuiltinTypeFields(block, src, ty, "FloatMode"),
.reduce_op => return sema.resolveBuiltinTypeFields(block, src, ty, "ReduceOp"),
.call_options => return sema.resolveBuiltinTypeFields(block, src, ty, "CallOptions"),
.@"union", .union_tagged => {
const union_obj = ty.cast(Type.Payload.Union).?.data;
switch (union_obj.status) {
.none => {},
.field_types_wip => {
return sema.mod.fail(&block.base, src, "union {} depends on itself", .{
ty,
});
},
.have_field_types, .have_layout, .layout_wip => return ty,
}
union_obj.status = .field_types_wip;
try sema.mod.analyzeUnionFields(union_obj);
union_obj.status = .have_field_types;
return ty;
},
else => return ty,
}
}
fn resolveBuiltinTypeFields(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
name: []const u8,
) InnerError!Type {
const resolved_ty = try sema.getBuiltinType(block, src, name);
return sema.resolveTypeFields(block, src, resolved_ty);
}
fn getBuiltinType(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
name: []const u8,
) InnerError!Type {
const mod = sema.mod;
const std_pkg = mod.root_pkg.table.get("std").?;
const std_file = (mod.importPkg(mod.root_pkg, std_pkg) catch unreachable).file;
const opt_builtin_inst = try sema.analyzeNamespaceLookup(
block,
src,
std_file.root_decl.?.namespace,
"builtin",
);
const builtin_inst = try sema.analyzeLoad(block, src, opt_builtin_inst.?, src);
const builtin_ty = try sema.resolveAirAsType(block, src, builtin_inst);
const opt_ty_inst = try sema.analyzeNamespaceLookup(
block,
src,
builtin_ty.getNamespace().?,
name,
);
const ty_inst = try sema.analyzeLoad(block, src, opt_ty_inst.?, src);
return sema.resolveAirAsType(block, src, ty_inst);
}
/// There is another implementation of this in `Type.onePossibleValue`. This one
/// in `Sema` is for calling during semantic analysis, and peforms field resolution
/// to get the answer. The one in `Type` is for calling during codegen and asserts
/// that the types are already resolved.
fn typeHasOnePossibleValue(
sema: *Sema,
block: *Scope.Block,
src: LazySrcLoc,
starting_type: Type,
) InnerError!?Value {
var ty = starting_type;
while (true) switch (ty.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.comptime_int,
.comptime_float,
.u8,
.i8,
.u16,
.i16,
.u32,
.i32,
.u64,
.i64,
.u128,
.i128,
.usize,
.isize,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.bool,
.type,
.anyerror,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.single_const_pointer_to_comptime_int,
.array_sentinel,
.array_u8_sentinel_0,
.const_slice_u8,
.const_slice,
.mut_slice,
.c_void,
.optional,
.optional_single_mut_pointer,
.optional_single_const_pointer,
.enum_literal,
.anyerror_void_error_union,
.error_union,
.error_set,
.error_set_single,
.@"opaque",
.var_args_param,
.manyptr_u8,
.manyptr_const_u8,
.atomic_ordering,
.atomic_rmw_op,
.calling_convention,
.float_mode,
.reduce_op,
.call_options,
.export_options,
.extern_options,
.@"anyframe",
.anyframe_T,
.many_const_pointer,
.many_mut_pointer,
.c_const_pointer,
.c_mut_pointer,
.single_const_pointer,
.single_mut_pointer,
.pointer,
=> return null,
.@"struct" => {
const resolved_ty = try sema.resolveTypeFields(block, src, ty);
const s = resolved_ty.castTag(.@"struct").?.data;
for (s.fields.entries.items) |entry| {
const field_ty = entry.value.ty;
if ((try sema.typeHasOnePossibleValue(block, src, field_ty)) == null) {
return null;
}
}
return Value.initTag(.empty_struct_value);
},
.enum_full => {
const resolved_ty = try sema.resolveTypeFields(block, src, ty);
const enum_full = resolved_ty.castTag(.enum_full).?.data;
if (enum_full.fields.count() == 1) {
return enum_full.values.entries.items[0].key;
} else {
return null;
}
},
.enum_simple => {
const resolved_ty = try sema.resolveTypeFields(block, src, ty);
const enum_simple = resolved_ty.castTag(.enum_simple).?.data;
if (enum_simple.fields.count() == 1) {
return Value.initTag(.zero);
} else {
return null;
}
},
.enum_nonexhaustive => ty = ty.castTag(.enum_nonexhaustive).?.data.tag_ty,
.@"union" => {
return null; // TODO
},
.union_tagged => {
return null; // TODO
},
.empty_struct, .empty_struct_literal => return Value.initTag(.empty_struct_value),
.void => return Value.initTag(.void_value),
.noreturn => return Value.initTag(.unreachable_value),
.@"null" => return Value.initTag(.null_value),
.@"undefined" => return Value.initTag(.undef),
.int_unsigned, .int_signed => {
if (ty.cast(Type.Payload.Bits).?.data == 0) {
return Value.initTag(.zero);
} else {
return null;
}
},
.vector, .array, .array_u8 => {
if (ty.arrayLen() == 0)
return Value.initTag(.empty_array);
ty = ty.elemType();
continue;
},
.inferred_alloc_const => unreachable,
.inferred_alloc_mut => unreachable,
};
}
fn getAstTree(sema: *Sema, block: *Scope.Block) InnerError!*const std.zig.ast.Tree {
return block.src_decl.namespace.file_scope.getTree(sema.gpa) catch |err| {
log.err("unable to load AST to report compile error: {s}", .{@errorName(err)});
return error.AnalysisFail;
};
}
fn enumFieldSrcLoc(
decl: *Decl,
tree: std.zig.ast.Tree,
node_offset: i32,
field_index: usize,
) LazySrcLoc {
@setCold(true);
const enum_node = decl.relativeToNodeIndex(node_offset);
const node_tags = tree.nodes.items(.tag);
var buffer: [2]std.zig.ast.Node.Index = undefined;
const container_decl = switch (node_tags[enum_node]) {
.container_decl,
.container_decl_trailing,
=> tree.containerDecl(enum_node),
.container_decl_two,
.container_decl_two_trailing,
=> tree.containerDeclTwo(&buffer, enum_node),
.container_decl_arg,
.container_decl_arg_trailing,
=> tree.containerDeclArg(enum_node),
else => unreachable,
};
var it_index: usize = 0;
for (container_decl.ast.members) |member_node| {
switch (node_tags[member_node]) {
.container_field_init,
.container_field_align,
.container_field,
=> {
if (it_index == field_index) {
return .{ .node_offset = decl.nodeIndexToRelative(member_node) };
}
it_index += 1;
},
else => continue,
}
} else unreachable;
}
|
src/Sema.zig
|
const uefi = @import("std").os.uefi;
const Event = uefi.Event;
const Guid = uefi.Guid;
const Status = uefi.Status;
pub const SimpleNetworkProtocol = extern struct {
revision: u64,
_start: fn (*const SimpleNetworkProtocol) callconv(.C) Status,
_stop: fn (*const SimpleNetworkProtocol) callconv(.C) Status,
_initialize: fn (*const SimpleNetworkProtocol, usize, usize) callconv(.C) Status,
_reset: fn (*const SimpleNetworkProtocol, bool) callconv(.C) Status,
_shutdown: fn (*const SimpleNetworkProtocol) callconv(.C) Status,
_receive_filters: fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) callconv(.C) Status,
_station_address: fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) callconv(.C) Status,
_statistics: fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) callconv(.C) Status,
_mcast_ip_to_mac: fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) callconv(.C) Status,
_nvdata: fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) callconv(.C) Status,
_get_status: fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) callconv(.C) Status,
_transmit: fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) callconv(.C) Status,
_receive: fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) callconv(.C) Status,
wait_for_packet: Event,
mode: *SimpleNetworkMode,
/// Changes the state of a network interface from "stopped" to "started".
pub fn start(self: *const SimpleNetworkProtocol) Status {
return self._start(self);
}
/// Changes the state of a network interface from "started" to "stopped".
pub fn stop(self: *const SimpleNetworkProtocol) Status {
return self._stop(self);
}
/// Resets a network adapter and allocates the transmit and receive buffers required by the network interface.
pub fn initialize(self: *const SimpleNetworkProtocol, extra_rx_buffer_size: usize, extra_tx_buffer_size: usize) Status {
return self._initialize(self, extra_rx_buffer_size, extra_tx_buffer_size);
}
/// Resets a network adapter and reinitializes it with the parameters that were provided in the previous call to initialize().
pub fn reset(self: *const SimpleNetworkProtocol, extended_verification: bool) Status {
return self._reset(self, extended_verification);
}
/// Resets a network adapter and leaves it in a state that is safe for another driver to initialize.
pub fn shutdown(self: *const SimpleNetworkProtocol) Status {
return self._shutdown(self);
}
/// Manages the multicast receive filters of a network interface.
pub fn receiveFilters(self: *const SimpleNetworkProtocol, enable: SimpleNetworkReceiveFilter, disable: SimpleNetworkReceiveFilter, reset_mcast_filter: bool, mcast_filter_cnt: usize, mcast_filter: ?[*]const MacAddress) Status {
return self._receive_filters(self, enable, disable, reset_mcast_filter, mcast_filter_cnt, mcast_filter);
}
/// Modifies or resets the current station address, if supported.
pub fn stationAddress(self: *const SimpleNetworkProtocol, reset: bool, new: ?*const MacAddress) Status {
return self._station_address(self, reset, new);
}
/// Resets or collects the statistics on a network interface.
pub fn statistics(self: *const SimpleNetworkProtocol, reset_: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) Status {
return self._statistics(self, reset_, statistics_size, statistics_table);
}
/// Converts a multicast IP address to a multicast HW MAC address.
pub fn mcastIpToMac(self: *const SimpleNetworkProtocol, ipv6: bool, ip: *const c_void, mac: *MacAddress) Status {
return self._mcast_ip_to_mac(self, ipv6, ip, mac);
}
/// Performs read and write operations on the NVRAM device attached to a network interface.
pub fn nvdata(self: *const SimpleNetworkProtocol, read_write: bool, offset: usize, buffer_size: usize, buffer: [*]u8) Status {
return self._nvdata(self, read_write, offset, buffer_size, buffer);
}
/// Reads the current interrupt status and recycled transmit buffer status from a network interface.
pub fn getStatus(self: *const SimpleNetworkProtocol, interrupt_status: *SimpleNetworkInterruptStatus, tx_buf: ?*?[*]u8) Status {
return self._get_status(self, interrupt_status, tx_buf);
}
/// Places a packet in the transmit queue of a network interface.
pub fn transmit(self: *const SimpleNetworkProtocol, header_size: usize, buffer_size: usize, buffer: [*]const u8, src_addr: ?*const MacAddress, dest_addr: ?*const MacAddress, protocol: ?*const u16) Status {
return self._transmit(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
}
/// Receives a packet from a network interface.
pub fn receive(self: *const SimpleNetworkProtocol, header_size: ?*usize, buffer_size: *usize, buffer: [*]u8, src_addr: ?*MacAddress, dest_addr: ?*MacAddress, protocol: ?*u16) Status {
return self._receive(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
}
pub const guid align(8) = Guid{
.time_low = 0xa19832b9,
.time_mid = 0xac25,
.time_high_and_version = 0x11d3,
.clock_seq_high_and_reserved = 0x9a,
.clock_seq_low = 0x2d,
.node = [_]u8{ 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d },
};
};
pub const MacAddress = [32]u8;
pub const SimpleNetworkMode = extern struct {
state: SimpleNetworkState,
hw_address_size: u32,
media_header_size: u32,
max_packet_size: u32,
nvram_size: u32,
nvram_access_size: u32,
receive_filter_mask: SimpleNetworkReceiveFilter,
receive_filter_setting: SimpleNetworkReceiveFilter,
max_mcast_filter_count: u32,
mcast_filter_count: u32,
mcast_filter: [16]MacAddress,
current_address: MacAddress,
broadcast_address: MacAddress,
permanent_address: MacAddress,
if_type: u8,
mac_address_changeable: bool,
multiple_tx_supported: bool,
media_present_supported: bool,
media_present: bool,
};
pub const SimpleNetworkReceiveFilter = packed struct {
receive_unicast: bool,
receive_multicast: bool,
receive_broadcast: bool,
receive_promiscuous: bool,
receive_promiscuous_multicast: bool,
_pad1: u3 = undefined,
_pad2: u8 = undefined,
_pad3: u16 = undefined,
};
pub const SimpleNetworkState = enum(u32) {
Stopped,
Started,
Initialized,
};
pub const NetworkStatistics = extern struct {
rx_total_frames: u64,
rx_good_frames: u64,
rx_undersize_frames: u64,
rx_oversize_frames: u64,
rx_dropped_frames: u64,
rx_unicast_frames: u64,
rx_broadcast_frames: u64,
rx_multicast_frames: u64,
rx_crc_error_frames: u64,
rx_total_bytes: u64,
tx_total_frames: u64,
tx_good_frames: u64,
tx_undersize_frames: u64,
tx_oversize_frames: u64,
tx_dropped_frames: u64,
tx_unicast_frames: u64,
tx_broadcast_frames: u64,
tx_multicast_frames: u64,
tx_crc_error_frames: u64,
tx_total_bytes: u64,
collisions: u64,
unsupported_protocol: u64,
rx_duplicated_frames: u64,
rx_decryptError_frames: u64,
tx_error_frames: u64,
tx_retry_frames: u64,
};
pub const SimpleNetworkInterruptStatus = packed struct {
receive_interrupt: bool,
transmit_interrupt: bool,
command_interrupt: bool,
software_interrupt: bool,
_pad1: u4,
_pad2: u8,
_pad3: u16,
};
|
lib/std/os/uefi/protocols/simple_network_protocol.zig
|
const std = @import("std");
const Builder = std.build.Builder;
pub fn createPackage(comptime root: []const u8) std.build.Pkg {
return std.build.Pkg{
.name = "zzz",
.path = root ++ "/src/main.zig",
.dependencies = &[_]std.build.Pkg{},
};
}
const pkgs = struct {
const zzz = std.build.Pkg{
.name = "zzz",
.path = "src/main.zig",
.dependencies = &[_]std.build.Pkg{
},
};
};
const Example = struct {
name: []const u8,
path: []const u8,
};
const examples = [_]Example{
Example{
.name = "building-tree",
.path = "examples/building_tree.zig",
},
Example{
.name = "loading-particles",
.path = "examples/loading_particles.zig",
},
Example{
.name = "static-imprint",
.path = "examples/static_imprint.zig",
},
Example{
.name = "static-tree",
.path = "examples/static_tree.zig",
},
};
pub fn build(b: *Builder) !void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{
.default_target = if (std.builtin.os.tag == .windows)
std.zig.CrossTarget.parse(.{ .arch_os_abi = "native-native-gnu" }) catch unreachable
else if (std.builtin.os.tag == .linux)
std.zig.CrossTarget.fromTarget(.{
.cpu = std.builtin.cpu,
.os = std.builtin.os,
.abi = .musl,
})
else
std.zig.CrossTarget{},
});
const examples_step = b.step("examples", "Compiles all examples");
inline for (examples) |example| {
const example_exe = b.addExecutable(example.name, example.path);
example_exe.setOutputDir("bin");
example_exe.setBuildMode(mode);
example_exe.setTarget(target);
example_exe.addPackage(pkgs.zzz);
examples_step.dependOn(&b.addInstallArtifact(example_exe).step);
}
var main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
const test_step = b.step("test", "Run test suite");
test_step.dependOn(&main_tests.step);
}
|
build.zig
|
const std = @import("std");
const math = std.math;
const expect = std.testing.expect;
pub fn __roundh(x: f16) callconv(.C) f16 {
// TODO: more efficient implementation
return @floatCast(f16, roundf(x));
}
pub fn roundf(x_: f32) callconv(.C) f32 {
const f32_toint = 1.0 / math.floatEps(f32);
var x = x_;
const u = @bitCast(u32, x);
const e = (u >> 23) & 0xFF;
var y: f32 = undefined;
if (e >= 0x7F + 23) {
return x;
}
if (u >> 31 != 0) {
x = -x;
}
if (e < 0x7F - 1) {
math.doNotOptimizeAway(x + f32_toint);
return 0 * @bitCast(f32, u);
}
y = x + f32_toint - f32_toint - x;
if (y > 0.5) {
y = y + x - 1;
} else if (y <= -0.5) {
y = y + x + 1;
} else {
y = y + x;
}
if (u >> 31 != 0) {
return -y;
} else {
return y;
}
}
pub fn round(x_: f64) callconv(.C) f64 {
const f64_toint = 1.0 / math.floatEps(f64);
var x = x_;
const u = @bitCast(u64, x);
const e = (u >> 52) & 0x7FF;
var y: f64 = undefined;
if (e >= 0x3FF + 52) {
return x;
}
if (u >> 63 != 0) {
x = -x;
}
if (e < 0x3ff - 1) {
math.doNotOptimizeAway(x + f64_toint);
return 0 * @bitCast(f64, u);
}
y = x + f64_toint - f64_toint - x;
if (y > 0.5) {
y = y + x - 1;
} else if (y <= -0.5) {
y = y + x + 1;
} else {
y = y + x;
}
if (u >> 63 != 0) {
return -y;
} else {
return y;
}
}
pub fn __roundx(x: f80) callconv(.C) f80 {
// TODO: more efficient implementation
return @floatCast(f80, roundq(x));
}
pub fn roundq(x_: f128) callconv(.C) f128 {
const f128_toint = 1.0 / math.floatEps(f128);
var x = x_;
const u = @bitCast(u128, x);
const e = (u >> 112) & 0x7FFF;
var y: f128 = undefined;
if (e >= 0x3FFF + 112) {
return x;
}
if (u >> 127 != 0) {
x = -x;
}
if (e < 0x3FFF - 1) {
math.doNotOptimizeAway(x + f128_toint);
return 0 * @bitCast(f128, u);
}
y = x + f128_toint - f128_toint - x;
if (y > 0.5) {
y = y + x - 1;
} else if (y <= -0.5) {
y = y + x + 1;
} else {
y = y + x;
}
if (u >> 127 != 0) {
return -y;
} else {
return y;
}
}
test "round32" {
try expect(roundf(1.3) == 1.0);
try expect(roundf(-1.3) == -1.0);
try expect(roundf(0.2) == 0.0);
try expect(roundf(1.8) == 2.0);
}
test "round64" {
try expect(round(1.3) == 1.0);
try expect(round(-1.3) == -1.0);
try expect(round(0.2) == 0.0);
try expect(round(1.8) == 2.0);
}
test "round128" {
try expect(roundq(1.3) == 1.0);
try expect(roundq(-1.3) == -1.0);
try expect(roundq(0.2) == 0.0);
try expect(roundq(1.8) == 2.0);
}
test "round32.special" {
try expect(roundf(0.0) == 0.0);
try expect(roundf(-0.0) == -0.0);
try expect(math.isPositiveInf(roundf(math.inf(f32))));
try expect(math.isNegativeInf(roundf(-math.inf(f32))));
try expect(math.isNan(roundf(math.nan(f32))));
}
test "round64.special" {
try expect(round(0.0) == 0.0);
try expect(round(-0.0) == -0.0);
try expect(math.isPositiveInf(round(math.inf(f64))));
try expect(math.isNegativeInf(round(-math.inf(f64))));
try expect(math.isNan(round(math.nan(f64))));
}
test "round128.special" {
try expect(roundq(0.0) == 0.0);
try expect(roundq(-0.0) == -0.0);
try expect(math.isPositiveInf(roundq(math.inf(f128))));
try expect(math.isNegativeInf(roundq(-math.inf(f128))));
try expect(math.isNan(roundq(math.nan(f128))));
}
|
lib/std/special/compiler_rt/round.zig
|
const builtin = @import("builtin");
const std = @import("std");
const testing = std.testing;
const expect = testing.expect;
test "tuple concatenation" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
const S = struct {
fn doTheTest() !void {
var a: i32 = 1;
var b: i32 = 2;
var x = .{a};
var y = .{b};
var c = x ++ y;
try expect(@as(i32, 1) == c[0]);
try expect(@as(i32, 2) == c[1]);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "tuple multiplication" {
const S = struct {
fn doTheTest() !void {
{
const t = .{} ** 4;
try expect(@typeInfo(@TypeOf(t)).Struct.fields.len == 0);
}
{
const t = .{'a'} ** 4;
try expect(@typeInfo(@TypeOf(t)).Struct.fields.len == 4);
inline for (t) |x| try expect(x == 'a');
}
{
const t = .{ 1, 2, 3 } ** 4;
try expect(@typeInfo(@TypeOf(t)).Struct.fields.len == 12);
inline for (t) |x, i| try expect(x == 1 + i % 3);
}
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "more tuple concatenation" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
const T = struct {
fn consume_tuple(tuple: anytype, len: usize) !void {
try expect(tuple.len == len);
}
fn doTheTest() !void {
const t1 = .{};
var rt_var: u8 = 42;
const t2 = .{rt_var} ++ .{};
try expect(t2.len == 1);
try expect(t2.@"0" == rt_var);
try expect(t2.@"0" == 42);
try expect(&t2.@"0" != &rt_var);
try consume_tuple(t1 ++ t1, 0);
try consume_tuple(.{} ++ .{}, 0);
try consume_tuple(.{0} ++ .{}, 1);
try consume_tuple(.{0} ++ .{1}, 2);
try consume_tuple(.{ 0, 1, 2 } ++ .{ u8, 1, noreturn }, 6);
try consume_tuple(t2 ++ t1, 1);
try consume_tuple(t1 ++ t2, 1);
try consume_tuple(t2 ++ t2, 2);
try consume_tuple(.{rt_var} ++ .{}, 1);
try consume_tuple(.{rt_var} ++ t1, 1);
try consume_tuple(.{} ++ .{rt_var}, 1);
try consume_tuple(t2 ++ .{void}, 2);
try consume_tuple(t2 ++ .{0}, 2);
try consume_tuple(.{0} ++ t2, 2);
try consume_tuple(.{void} ++ t2, 2);
try consume_tuple(.{u8} ++ .{rt_var} ++ .{true}, 3);
}
};
try T.doTheTest();
comptime try T.doTheTest();
}
test "pass tuple to comptime var parameter" {
const S = struct {
fn Foo(comptime args: anytype) !void {
try expect(args[0] == 1);
}
fn doTheTest() !void {
try Foo(.{1});
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "tuple initializer for var" {
const S = struct {
fn doTheTest() void {
const Bytes = struct {
id: usize,
};
var tmp = .{
.id = @as(usize, 2),
.name = Bytes{ .id = 20 },
};
_ = tmp;
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "array-like initializer for tuple types" {
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
const T = @Type(.{
.Struct = .{
.is_tuple = true,
.layout = .Auto,
.decls = &.{},
.fields = &.{
.{
.name = "0",
.field_type = i32,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(i32),
},
.{
.name = "1",
.field_type = u8,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(i32),
},
},
},
});
const S = struct {
fn doTheTest() !void {
var obj: T = .{ -1234, 128 };
try expect(@as(i32, -1234) == obj[0]);
try expect(@as(u8, 128) == obj[1]);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "anon struct as the result from a labeled block" {
const S = struct {
fn doTheTest() !void {
const precomputed = comptime blk: {
var x: i32 = 1234;
break :blk .{
.x = x,
};
};
try expect(precomputed.x == 1234);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "tuple as the result from a labeled block" {
const S = struct {
fn doTheTest() !void {
const precomputed = comptime blk: {
var x: i32 = 1234;
break :blk .{x};
};
try expect(precomputed[0] == 1234);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
|
test/behavior/tuple.zig
|
const std = @import("std");
const a5 = @cImport({
@cInclude("allegro5/allegro.h");
@cInclude("allegro5/allegro_font.h");
@cInclude("allegro5/allegro_image.h");
@cInclude("allegro5/allegro_color.h");
@cInclude("shim.h");
});
// Soon these shims can go away...
fn al_color_name(name: []const u8) a5.ALLEGRO_COLOR {
var c: a5.ALLEGRO_COLOR = undefined;
a5.shim_color_name(@ptrCast([*c]const u8, name), &c);
return c;
}
fn al_color_hsv(h: f32, s: f32, v: f32) a5.ALLEGRO_COLOR {
var c: a5.ALLEGRO_COLOR = undefined;
a5.shim_color_hsv(h, s, v, &c);
return c;
}
fn al_init() bool {
return a5.shim_init();
}
// end shim
const Timer = struct {
timer: f64 = 0.0,
counter: f64 = 0.0,
fn start(self: *Timer) void {
self.*.timer -= a5.al_get_time();
self.*.counter += 1.0;
}
fn stop(self: *Timer) void {
self.*.timer += a5.al_get_time();
}
fn fps(self: Timer) f64 {
if (self.timer == 0.0) {
return 0.0;
} else {
return self.counter / self.timer;
}
}
};
const Example = struct {
pattern: *a5.ALLEGRO_BITMAP, font: *a5.ALLEGRO_FONT, queue: *a5.ALLEGRO_EVENT_QUEUE, background: a5.ALLEGRO_COLOR, text: a5.ALLEGRO_COLOR, white: a5.ALLEGRO_COLOR, timer: [4]Timer, FPS: i32, text_x: f32, text_y: f32
};
var ex = Example{
.pattern = undefined,
.font = undefined,
.queue = undefined,
.background = undefined,
.text = undefined,
.white = undefined,
.timer = [_]Timer{.{}} ** 4,
.FPS = undefined,
.text_x = undefined,
.text_y = undefined,
};
fn example_bitmap(w: i32, h: i32) *a5.ALLEGRO_BITMAP {
const mx: f32 = @intToFloat(f32, w) * 0.5;
const my: f32 = @intToFloat(f32, h) * 0.5;
var state = a5.ALLEGRO_STATE{ ._tls = undefined };
if (a5.al_create_bitmap(w, h)) |pattern| {
a5.al_store_state(@ptrCast([*c]a5.ALLEGRO_STATE, &state), a5.ALLEGRO_STATE_TARGET_BITMAP);
a5.al_set_target_bitmap(pattern);
_ = a5.al_lock_bitmap(pattern, a5.ALLEGRO_PIXEL_FORMAT_ANY, a5.ALLEGRO_LOCK_WRITEONLY);
var i: i32 = 0;
while (i < w) : (i += 1) {
var j: i32 = 0;
while (j < h) : (j += 1) {
const x = @intToFloat(f32, i) - mx;
const y = @intToFloat(f32, j) - my;
const a = std.math.atan2(f32, y, x);
const d = std.math.sqrt(std.math.pow(f32, x, 2) + std.math.pow(f32, y, 2));
const sat = std.math.pow(f32, 1.0 - 1.0 / (1.0 + d * 0.1), 5);
var hue = 3.0 * a * 180 / std.math.pi;
hue = (hue / 360 - std.math.floor(hue / 360.0)) * 360.0;
var color: a5.ALLEGRO_COLOR = al_color_hsv(hue, sat, 1.0);
a5.al_put_pixel(i, j, color);
}
}
var black: a5.ALLEGRO_COLOR = al_color_name("black");
a5.al_put_pixel(0, 0, black);
a5.al_unlock_bitmap(pattern);
a5.al_restore_state(&state);
return pattern;
} else {
abort_example("Unable to create bitmap");
}
}
fn set_xy(x: f32, y: f32) void {
ex.text_x = x;
ex.text_y = y;
}
fn get_xy(px: *f32, py: *f32) void {
px.* = ex.text_x;
py.* = ex.text_y;
}
fn print(comptime format: []const u8, args: anytype) void {
var buffer: [1024]u8 = undefined;
const message = std.fmt.bufPrint(buffer[0..], format, args) catch "???";
const th = @intToFloat(f32, a5.al_get_font_line_height(ex.font));
a5.al_set_blender(a5.ALLEGRO_ADD, a5.ALLEGRO_ONE, a5.ALLEGRO_INVERSE_ALPHA);
// not yet! compiler error
// a5.al_draw_text(ex.font, ex.text, ex.text_x, ex.text_y, 0, @ptrCast([*c]const u8, message));
a5.shim_draw_text(ex.font, &ex.text, ex.text_x, ex.text_y, 0, @ptrCast([*c]const u8, message));
ex.text_y += th;
}
fn pixrow(lock: *a5.ALLEGRO_LOCKED_REGION, row: usize) [*]u8 {
const pitch = @intCast(isize, lock.*.pitch);
const data = @ptrCast([*]u8, lock.*.data);
if (pitch > 0) {
const upitch = @intCast(usize, pitch);
return data + row * upitch;
} else {
const upitch = @intCast(usize, -pitch);
return data - row * upitch;
}
}
fn draw() void {
const iw = a5.al_get_bitmap_width(ex.pattern);
const ih = a5.al_get_bitmap_height(ex.pattern);
a5.al_set_blender(a5.ALLEGRO_ADD, a5.ALLEGRO_ONE, a5.ALLEGRO_ZERO);
a5.al_clear_to_color(ex.background);
var screen = a5.al_get_target_bitmap();
set_xy(8, 8);
var x: f32 = undefined;
var y: f32 = undefined;
var red: a5.ALLEGRO_COLOR = al_color_name("red");
// Test 2
{
print("Screen -> Bitmap -> Screen ({d:.2} fps)", .{ex.timer[1].fps()});
get_xy(&x, &y);
a5.al_draw_bitmap(ex.pattern, x, y, 0);
var temp = a5.al_create_bitmap(iw, ih);
a5.al_set_target_bitmap(temp);
a5.al_clear_to_color(red);
ex.timer[1].start();
a5.al_draw_bitmap_region(screen, x, y, @intToFloat(f32, iw), @intToFloat(f32, ih), 0, 0, 0);
a5.al_set_target_bitmap(screen);
a5.al_draw_bitmap(temp, x + 8.0 + @intToFloat(f32, iw), y, 0);
ex.timer[1].stop();
set_xy(x, y + @intToFloat(f32, ih));
a5.al_destroy_bitmap(temp);
}
// Test 3
{
print("Screen -> Memory -> Screen ({d:.2} fps)", .{ex.timer[2].fps()});
get_xy(&x, &y);
a5.al_draw_bitmap(ex.pattern, x, y, 0);
a5.al_set_new_bitmap_flags(a5.ALLEGRO_MEMORY_BITMAP);
var temp = a5.al_create_bitmap(iw, ih);
a5.al_set_target_bitmap(temp);
a5.al_clear_to_color(red);
ex.timer[2].start();
a5.al_draw_bitmap_region(screen, x, y, @intToFloat(f32, iw), @intToFloat(f32, ih), 0, 0, 0);
a5.al_set_target_bitmap(screen);
a5.al_draw_bitmap(temp, x + 8.0 + @intToFloat(f32, iw), y, 0);
ex.timer[2].stop();
set_xy(x, y + @intToFloat(f32, ih));
a5.al_destroy_bitmap(temp);
a5.al_set_new_bitmap_flags(a5.ALLEGRO_VIDEO_BITMAP);
}
// Test 4
{
print("Screen -> Locked -> Screen ({d:.2} fps)", .{ex.timer[3].fps()});
get_xy(&x, &y);
a5.al_draw_bitmap(ex.pattern, x, y, 0);
ex.timer[3].start();
const lock = a5.al_lock_bitmap_region(screen, @floatToInt(c_int, x), @floatToInt(c_int, y), iw, ih, a5.ALLEGRO_PIXEL_FORMAT_ANY, a5.ALLEGRO_LOCK_READONLY);
const size = @intCast(usize, lock.*.pixel_size);
const data = std.heap.c_allocator.alloc(u8, size * @intCast(usize, iw * ih)) catch unreachable;
const w = @intCast(usize, iw);
var i: usize = 0;
while (i < ih) : (i += 1) {
const sdata = pixrow(lock, i);
std.mem.copy(u8, data[i * size * w .. (i + 1) * size * w], sdata[0 .. size * w]);
}
a5.al_unlock_bitmap(screen);
const wlock = a5.al_lock_bitmap_region(screen, @floatToInt(c_int, x) + 8 + iw, @floatToInt(c_int, y), iw, ih, a5.ALLEGRO_PIXEL_FORMAT_ANY, a5.ALLEGRO_LOCK_WRITEONLY);
i = 0;
while (i < ih) : (i += 1) {
const wdata = pixrow(wlock, i);
std.mem.copy(u8, wdata[0 .. size * w], data[i * size * w .. (i + 1) * size * w]);
}
a5.al_unlock_bitmap(screen);
std.heap.c_allocator.free(data);
ex.timer[3].stop();
set_xy(x, y + @intToFloat(f32, ih));
}
}
fn tick() void {
draw();
a5.al_flip_display();
}
fn init() void {
ex.FPS = 60;
ex.font = (a5.al_load_font("data/fixed_font.tga", 0, 0) orelse
abort_example("data/fixed_font.tga not found\n"));
ex.background = al_color_name("beige");
ex.text = al_color_name("black");
ex.white = al_color_name("white");
ex.pattern = example_bitmap(100, 100);
}
export fn user_main(argc: c_int, argv: [*c][*c]u8) c_int {
if (!al_init()) {
abort_example("Could not init Allegro.\n");
}
_ = a5.al_install_keyboard();
_ = a5.al_install_mouse();
_ = a5.al_init_image_addon();
_ = a5.al_init_font_addon();
init_platform_specific();
const display = (a5.al_create_display(640, 480) orelse
abort_example("Error creating display\n"));
init();
var timer = a5.al_create_timer(1.0 / @intToFloat(f32, ex.FPS)).?;
ex.queue = a5.al_create_event_queue().?;
defer a5.al_destroy_event_queue(ex.queue);
a5.al_register_event_source(ex.queue, a5.al_get_keyboard_event_source());
a5.al_register_event_source(ex.queue, a5.al_get_mouse_event_source());
a5.al_register_event_source(ex.queue, a5.al_get_display_event_source(display));
a5.al_register_event_source(ex.queue, a5.al_get_timer_event_source(timer));
a5.al_start_timer(timer);
run();
return 0;
}
fn run() void {
var need_draw = true;
while (true) {
if (need_draw and a5.al_is_event_queue_empty(ex.queue)) {
tick();
need_draw = false;
}
var event: a5.ALLEGRO_EVENT = undefined;
a5.al_wait_for_event(ex.queue, &event);
switch (event.type) {
a5.ALLEGRO_EVENT_DISPLAY_CLOSE => return,
a5.ALLEGRO_EVENT_KEY_DOWN => if (event.keyboard.keycode == a5.ALLEGRO_KEY_ESCAPE) {
return;
},
a5.ALLEGRO_EVENT_TIMER => need_draw = true,
else => {},
}
}
}
pub fn main() anyerror!void {
const arg0 = "app";
const argv = null; //[][]u8{&arg0[0]};
_ = a5.al_run_main(1, argv, user_main);
}
fn abort_example(msg: []const u8) noreturn {
std.debug.panic("Example aborted:\n{}\n", .{msg});
}
fn init_platform_specific() void {}
|
src/main.zig
|
const std = @import("std");
const prompt = @import("./prompt.zig");
const rng = @import("../main.zig").rng;
const State = @import("../main.zig").State;
const CommandLineOptions = @import("../args.zig").CommandLineOptions;
fn doComputerTurn(state: *State) void {
const current = state.getCurrentPlayer();
state.reroll();
var points = state.computePoints();
std.debug.print("Computer rolled: {any}. It has {d} points.\n", .{ state.dices, points });
var dices_to_reroll = state.dicesToReroll();
while (dices_to_reroll > 0) {
state.reroll();
points = state.computePoints();
std.debug.print("Computer rolls again {d} dices. It has {any} points.\n", .{ dices_to_reroll, points });
dices_to_reroll = state.dicesToReroll();
}
std.debug.print("Computer finally got {d} points.\n", .{points});
current.points += points;
}
// 1. Generate first dice set
// 1a. If reroll is possible: add reroll button
// 1b. Add Next Player button
//
// When computer
pub fn doTurn(state: *State) void {
var current = state.player;
state.forceReroll();
std.debug.print("You rolled: {any}\n", .{state.dices});
var points = state.computePoints();
std.debug.print("You have got {d} points\n", .{points});
var dices_to_reroll = state.dicesToReroll();
while (dices_to_reroll > 0) {
std.debug.print("You can reroll {d} dices.\n ", .{dices_to_reroll});
const choice = prompt.boolean("Do you want to reroll them? y/n:") catch false;
if (!choice) return;
state.reroll();
points = state.computePoints();
std.debug.print("You have got {d} points\n", .{points});
dices_to_reroll = state.dicesToReroll();
}
current.points += points;
std.debug.print("After turn player {s} has {d} points.\n", .{ current.name, current.points });
}
fn won(game_state: *State) bool {
return game_state.getCurrentPlayer().points >= WINNING_CONDITION;
}
pub fn start(options: CommandLineOptions, state: *State) !void {
_ = options;
while (true) {
// turn starts here
const choice: bool = prompt.boolean("Do you want to roll dices? y/n: ") catch false;
if (!choice) {
break;
}
doTurn(state);
}
}
|
src/cli/ui.zig
|
/// The function fiatP224AddcarryxU32 is an addition with carry.
/// Postconditions:
/// out1 = (arg1 + arg2 + arg3) mod 2^32
/// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
fn fiatP224AddcarryxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void {
const x1: u64 = ((@intCast(u64, arg1) + @intCast(u64, arg2)) + @intCast(u64, arg3));
const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff)));
const x3: u1 = @intCast(u1, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function fiatP224SubborrowxU32 is a subtraction with borrow.
/// Postconditions:
/// out1 = (-arg1 + arg2 + -arg3) mod 2^32
/// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
fn fiatP224SubborrowxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void {
const x1: i64 = ((@intCast(i64, arg2) - @intCast(i64, arg1)) - @intCast(i64, arg3));
const x2: i1 = @intCast(i1, (x1 >> 32));
const x3: u32 = @intCast(u32, (x1 & @intCast(i64, 0xffffffff)));
out1.* = x3;
out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2)));
}
/// The function fiatP224MulxU32 is a multiplication, returning the full double-width result.
/// Postconditions:
/// out1 = (arg1 * arg2) mod 2^32
/// out2 = ⌊arg1 * arg2 / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0xffffffff]
fn fiatP224MulxU32(out1: *u32, out2: *u32, arg1: u32, arg2: u32) callconv(.Inline) void {
const x1: u64 = (@intCast(u64, arg1) * @intCast(u64, arg2));
const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff)));
const x3: u32 = @intCast(u32, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function fiatP224CmovznzU32 is a single-word conditional move.
/// Postconditions:
/// out1 = (if arg1 = 0 then arg2 else arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
fn fiatP224CmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void {
const x1: u1 = (~(~arg1));
const x2: u32 = @intCast(u32, (@intCast(i64, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i64, 0xffffffff)));
const x3: u32 = ((x2 & arg3) | ((~x2) & arg2));
out1.* = x3;
}
/// The function fiatP224Mul multiplies two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Mul(out1: *[7]u32, arg1: [7]u32, arg2: [7]u32) void {
const x1: u32 = (arg1[1]);
const x2: u32 = (arg1[2]);
const x3: u32 = (arg1[3]);
const x4: u32 = (arg1[4]);
const x5: u32 = (arg1[5]);
const x6: u32 = (arg1[6]);
const x7: u32 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
fiatP224MulxU32(&x8, &x9, x7, (arg2[6]));
var x10: u32 = undefined;
var x11: u32 = undefined;
fiatP224MulxU32(&x10, &x11, x7, (arg2[5]));
var x12: u32 = undefined;
var x13: u32 = undefined;
fiatP224MulxU32(&x12, &x13, x7, (arg2[4]));
var x14: u32 = undefined;
var x15: u32 = undefined;
fiatP224MulxU32(&x14, &x15, x7, (arg2[3]));
var x16: u32 = undefined;
var x17: u32 = undefined;
fiatP224MulxU32(&x16, &x17, x7, (arg2[2]));
var x18: u32 = undefined;
var x19: u32 = undefined;
fiatP224MulxU32(&x18, &x19, x7, (arg2[1]));
var x20: u32 = undefined;
var x21: u32 = undefined;
fiatP224MulxU32(&x20, &x21, x7, (arg2[0]));
var x22: u32 = undefined;
var x23: u1 = undefined;
fiatP224AddcarryxU32(&x22, &x23, 0x0, x21, x18);
var x24: u32 = undefined;
var x25: u1 = undefined;
fiatP224AddcarryxU32(&x24, &x25, x23, x19, x16);
var x26: u32 = undefined;
var x27: u1 = undefined;
fiatP224AddcarryxU32(&x26, &x27, x25, x17, x14);
var x28: u32 = undefined;
var x29: u1 = undefined;
fiatP224AddcarryxU32(&x28, &x29, x27, x15, x12);
var x30: u32 = undefined;
var x31: u1 = undefined;
fiatP224AddcarryxU32(&x30, &x31, x29, x13, x10);
var x32: u32 = undefined;
var x33: u1 = undefined;
fiatP224AddcarryxU32(&x32, &x33, x31, x11, x8);
const x34: u32 = (@intCast(u32, x33) + x9);
var x35: u32 = undefined;
var x36: u32 = undefined;
fiatP224MulxU32(&x35, &x36, x20, 0xffffffff);
var x37: u32 = undefined;
var x38: u32 = undefined;
fiatP224MulxU32(&x37, &x38, x35, 0xffffffff);
var x39: u32 = undefined;
var x40: u32 = undefined;
fiatP224MulxU32(&x39, &x40, x35, 0xffffffff);
var x41: u32 = undefined;
var x42: u32 = undefined;
fiatP224MulxU32(&x41, &x42, x35, 0xffffffff);
var x43: u32 = undefined;
var x44: u32 = undefined;
fiatP224MulxU32(&x43, &x44, x35, 0xffffffff);
var x45: u32 = undefined;
var x46: u1 = undefined;
fiatP224AddcarryxU32(&x45, &x46, 0x0, x44, x41);
var x47: u32 = undefined;
var x48: u1 = undefined;
fiatP224AddcarryxU32(&x47, &x48, x46, x42, x39);
var x49: u32 = undefined;
var x50: u1 = undefined;
fiatP224AddcarryxU32(&x49, &x50, x48, x40, x37);
const x51: u32 = (@intCast(u32, x50) + x38);
var x52: u32 = undefined;
var x53: u1 = undefined;
fiatP224AddcarryxU32(&x52, &x53, 0x0, x20, x35);
var x54: u32 = undefined;
var x55: u1 = undefined;
fiatP224AddcarryxU32(&x54, &x55, x53, x22, @intCast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
fiatP224AddcarryxU32(&x56, &x57, x55, x24, @intCast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
fiatP224AddcarryxU32(&x58, &x59, x57, x26, x43);
var x60: u32 = undefined;
var x61: u1 = undefined;
fiatP224AddcarryxU32(&x60, &x61, x59, x28, x45);
var x62: u32 = undefined;
var x63: u1 = undefined;
fiatP224AddcarryxU32(&x62, &x63, x61, x30, x47);
var x64: u32 = undefined;
var x65: u1 = undefined;
fiatP224AddcarryxU32(&x64, &x65, x63, x32, x49);
var x66: u32 = undefined;
var x67: u1 = undefined;
fiatP224AddcarryxU32(&x66, &x67, x65, x34, x51);
var x68: u32 = undefined;
var x69: u32 = undefined;
fiatP224MulxU32(&x68, &x69, x1, (arg2[6]));
var x70: u32 = undefined;
var x71: u32 = undefined;
fiatP224MulxU32(&x70, &x71, x1, (arg2[5]));
var x72: u32 = undefined;
var x73: u32 = undefined;
fiatP224MulxU32(&x72, &x73, x1, (arg2[4]));
var x74: u32 = undefined;
var x75: u32 = undefined;
fiatP224MulxU32(&x74, &x75, x1, (arg2[3]));
var x76: u32 = undefined;
var x77: u32 = undefined;
fiatP224MulxU32(&x76, &x77, x1, (arg2[2]));
var x78: u32 = undefined;
var x79: u32 = undefined;
fiatP224MulxU32(&x78, &x79, x1, (arg2[1]));
var x80: u32 = undefined;
var x81: u32 = undefined;
fiatP224MulxU32(&x80, &x81, x1, (arg2[0]));
var x82: u32 = undefined;
var x83: u1 = undefined;
fiatP224AddcarryxU32(&x82, &x83, 0x0, x81, x78);
var x84: u32 = undefined;
var x85: u1 = undefined;
fiatP224AddcarryxU32(&x84, &x85, x83, x79, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
fiatP224AddcarryxU32(&x86, &x87, x85, x77, x74);
var x88: u32 = undefined;
var x89: u1 = undefined;
fiatP224AddcarryxU32(&x88, &x89, x87, x75, x72);
var x90: u32 = undefined;
var x91: u1 = undefined;
fiatP224AddcarryxU32(&x90, &x91, x89, x73, x70);
var x92: u32 = undefined;
var x93: u1 = undefined;
fiatP224AddcarryxU32(&x92, &x93, x91, x71, x68);
const x94: u32 = (@intCast(u32, x93) + x69);
var x95: u32 = undefined;
var x96: u1 = undefined;
fiatP224AddcarryxU32(&x95, &x96, 0x0, x54, x80);
var x97: u32 = undefined;
var x98: u1 = undefined;
fiatP224AddcarryxU32(&x97, &x98, x96, x56, x82);
var x99: u32 = undefined;
var x100: u1 = undefined;
fiatP224AddcarryxU32(&x99, &x100, x98, x58, x84);
var x101: u32 = undefined;
var x102: u1 = undefined;
fiatP224AddcarryxU32(&x101, &x102, x100, x60, x86);
var x103: u32 = undefined;
var x104: u1 = undefined;
fiatP224AddcarryxU32(&x103, &x104, x102, x62, x88);
var x105: u32 = undefined;
var x106: u1 = undefined;
fiatP224AddcarryxU32(&x105, &x106, x104, x64, x90);
var x107: u32 = undefined;
var x108: u1 = undefined;
fiatP224AddcarryxU32(&x107, &x108, x106, x66, x92);
var x109: u32 = undefined;
var x110: u1 = undefined;
fiatP224AddcarryxU32(&x109, &x110, x108, @intCast(u32, x67), x94);
var x111: u32 = undefined;
var x112: u32 = undefined;
fiatP224MulxU32(&x111, &x112, x95, 0xffffffff);
var x113: u32 = undefined;
var x114: u32 = undefined;
fiatP224MulxU32(&x113, &x114, x111, 0xffffffff);
var x115: u32 = undefined;
var x116: u32 = undefined;
fiatP224MulxU32(&x115, &x116, x111, 0xffffffff);
var x117: u32 = undefined;
var x118: u32 = undefined;
fiatP224MulxU32(&x117, &x118, x111, 0xffffffff);
var x119: u32 = undefined;
var x120: u32 = undefined;
fiatP224MulxU32(&x119, &x120, x111, 0xffffffff);
var x121: u32 = undefined;
var x122: u1 = undefined;
fiatP224AddcarryxU32(&x121, &x122, 0x0, x120, x117);
var x123: u32 = undefined;
var x124: u1 = undefined;
fiatP224AddcarryxU32(&x123, &x124, x122, x118, x115);
var x125: u32 = undefined;
var x126: u1 = undefined;
fiatP224AddcarryxU32(&x125, &x126, x124, x116, x113);
const x127: u32 = (@intCast(u32, x126) + x114);
var x128: u32 = undefined;
var x129: u1 = undefined;
fiatP224AddcarryxU32(&x128, &x129, 0x0, x95, x111);
var x130: u32 = undefined;
var x131: u1 = undefined;
fiatP224AddcarryxU32(&x130, &x131, x129, x97, @intCast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
fiatP224AddcarryxU32(&x132, &x133, x131, x99, @intCast(u32, 0x0));
var x134: u32 = undefined;
var x135: u1 = undefined;
fiatP224AddcarryxU32(&x134, &x135, x133, x101, x119);
var x136: u32 = undefined;
var x137: u1 = undefined;
fiatP224AddcarryxU32(&x136, &x137, x135, x103, x121);
var x138: u32 = undefined;
var x139: u1 = undefined;
fiatP224AddcarryxU32(&x138, &x139, x137, x105, x123);
var x140: u32 = undefined;
var x141: u1 = undefined;
fiatP224AddcarryxU32(&x140, &x141, x139, x107, x125);
var x142: u32 = undefined;
var x143: u1 = undefined;
fiatP224AddcarryxU32(&x142, &x143, x141, x109, x127);
const x144: u32 = (@intCast(u32, x143) + @intCast(u32, x110));
var x145: u32 = undefined;
var x146: u32 = undefined;
fiatP224MulxU32(&x145, &x146, x2, (arg2[6]));
var x147: u32 = undefined;
var x148: u32 = undefined;
fiatP224MulxU32(&x147, &x148, x2, (arg2[5]));
var x149: u32 = undefined;
var x150: u32 = undefined;
fiatP224MulxU32(&x149, &x150, x2, (arg2[4]));
var x151: u32 = undefined;
var x152: u32 = undefined;
fiatP224MulxU32(&x151, &x152, x2, (arg2[3]));
var x153: u32 = undefined;
var x154: u32 = undefined;
fiatP224MulxU32(&x153, &x154, x2, (arg2[2]));
var x155: u32 = undefined;
var x156: u32 = undefined;
fiatP224MulxU32(&x155, &x156, x2, (arg2[1]));
var x157: u32 = undefined;
var x158: u32 = undefined;
fiatP224MulxU32(&x157, &x158, x2, (arg2[0]));
var x159: u32 = undefined;
var x160: u1 = undefined;
fiatP224AddcarryxU32(&x159, &x160, 0x0, x158, x155);
var x161: u32 = undefined;
var x162: u1 = undefined;
fiatP224AddcarryxU32(&x161, &x162, x160, x156, x153);
var x163: u32 = undefined;
var x164: u1 = undefined;
fiatP224AddcarryxU32(&x163, &x164, x162, x154, x151);
var x165: u32 = undefined;
var x166: u1 = undefined;
fiatP224AddcarryxU32(&x165, &x166, x164, x152, x149);
var x167: u32 = undefined;
var x168: u1 = undefined;
fiatP224AddcarryxU32(&x167, &x168, x166, x150, x147);
var x169: u32 = undefined;
var x170: u1 = undefined;
fiatP224AddcarryxU32(&x169, &x170, x168, x148, x145);
const x171: u32 = (@intCast(u32, x170) + x146);
var x172: u32 = undefined;
var x173: u1 = undefined;
fiatP224AddcarryxU32(&x172, &x173, 0x0, x130, x157);
var x174: u32 = undefined;
var x175: u1 = undefined;
fiatP224AddcarryxU32(&x174, &x175, x173, x132, x159);
var x176: u32 = undefined;
var x177: u1 = undefined;
fiatP224AddcarryxU32(&x176, &x177, x175, x134, x161);
var x178: u32 = undefined;
var x179: u1 = undefined;
fiatP224AddcarryxU32(&x178, &x179, x177, x136, x163);
var x180: u32 = undefined;
var x181: u1 = undefined;
fiatP224AddcarryxU32(&x180, &x181, x179, x138, x165);
var x182: u32 = undefined;
var x183: u1 = undefined;
fiatP224AddcarryxU32(&x182, &x183, x181, x140, x167);
var x184: u32 = undefined;
var x185: u1 = undefined;
fiatP224AddcarryxU32(&x184, &x185, x183, x142, x169);
var x186: u32 = undefined;
var x187: u1 = undefined;
fiatP224AddcarryxU32(&x186, &x187, x185, x144, x171);
var x188: u32 = undefined;
var x189: u32 = undefined;
fiatP224MulxU32(&x188, &x189, x172, 0xffffffff);
var x190: u32 = undefined;
var x191: u32 = undefined;
fiatP224MulxU32(&x190, &x191, x188, 0xffffffff);
var x192: u32 = undefined;
var x193: u32 = undefined;
fiatP224MulxU32(&x192, &x193, x188, 0xffffffff);
var x194: u32 = undefined;
var x195: u32 = undefined;
fiatP224MulxU32(&x194, &x195, x188, 0xffffffff);
var x196: u32 = undefined;
var x197: u32 = undefined;
fiatP224MulxU32(&x196, &x197, x188, 0xffffffff);
var x198: u32 = undefined;
var x199: u1 = undefined;
fiatP224AddcarryxU32(&x198, &x199, 0x0, x197, x194);
var x200: u32 = undefined;
var x201: u1 = undefined;
fiatP224AddcarryxU32(&x200, &x201, x199, x195, x192);
var x202: u32 = undefined;
var x203: u1 = undefined;
fiatP224AddcarryxU32(&x202, &x203, x201, x193, x190);
const x204: u32 = (@intCast(u32, x203) + x191);
var x205: u32 = undefined;
var x206: u1 = undefined;
fiatP224AddcarryxU32(&x205, &x206, 0x0, x172, x188);
var x207: u32 = undefined;
var x208: u1 = undefined;
fiatP224AddcarryxU32(&x207, &x208, x206, x174, @intCast(u32, 0x0));
var x209: u32 = undefined;
var x210: u1 = undefined;
fiatP224AddcarryxU32(&x209, &x210, x208, x176, @intCast(u32, 0x0));
var x211: u32 = undefined;
var x212: u1 = undefined;
fiatP224AddcarryxU32(&x211, &x212, x210, x178, x196);
var x213: u32 = undefined;
var x214: u1 = undefined;
fiatP224AddcarryxU32(&x213, &x214, x212, x180, x198);
var x215: u32 = undefined;
var x216: u1 = undefined;
fiatP224AddcarryxU32(&x215, &x216, x214, x182, x200);
var x217: u32 = undefined;
var x218: u1 = undefined;
fiatP224AddcarryxU32(&x217, &x218, x216, x184, x202);
var x219: u32 = undefined;
var x220: u1 = undefined;
fiatP224AddcarryxU32(&x219, &x220, x218, x186, x204);
const x221: u32 = (@intCast(u32, x220) + @intCast(u32, x187));
var x222: u32 = undefined;
var x223: u32 = undefined;
fiatP224MulxU32(&x222, &x223, x3, (arg2[6]));
var x224: u32 = undefined;
var x225: u32 = undefined;
fiatP224MulxU32(&x224, &x225, x3, (arg2[5]));
var x226: u32 = undefined;
var x227: u32 = undefined;
fiatP224MulxU32(&x226, &x227, x3, (arg2[4]));
var x228: u32 = undefined;
var x229: u32 = undefined;
fiatP224MulxU32(&x228, &x229, x3, (arg2[3]));
var x230: u32 = undefined;
var x231: u32 = undefined;
fiatP224MulxU32(&x230, &x231, x3, (arg2[2]));
var x232: u32 = undefined;
var x233: u32 = undefined;
fiatP224MulxU32(&x232, &x233, x3, (arg2[1]));
var x234: u32 = undefined;
var x235: u32 = undefined;
fiatP224MulxU32(&x234, &x235, x3, (arg2[0]));
var x236: u32 = undefined;
var x237: u1 = undefined;
fiatP224AddcarryxU32(&x236, &x237, 0x0, x235, x232);
var x238: u32 = undefined;
var x239: u1 = undefined;
fiatP224AddcarryxU32(&x238, &x239, x237, x233, x230);
var x240: u32 = undefined;
var x241: u1 = undefined;
fiatP224AddcarryxU32(&x240, &x241, x239, x231, x228);
var x242: u32 = undefined;
var x243: u1 = undefined;
fiatP224AddcarryxU32(&x242, &x243, x241, x229, x226);
var x244: u32 = undefined;
var x245: u1 = undefined;
fiatP224AddcarryxU32(&x244, &x245, x243, x227, x224);
var x246: u32 = undefined;
var x247: u1 = undefined;
fiatP224AddcarryxU32(&x246, &x247, x245, x225, x222);
const x248: u32 = (@intCast(u32, x247) + x223);
var x249: u32 = undefined;
var x250: u1 = undefined;
fiatP224AddcarryxU32(&x249, &x250, 0x0, x207, x234);
var x251: u32 = undefined;
var x252: u1 = undefined;
fiatP224AddcarryxU32(&x251, &x252, x250, x209, x236);
var x253: u32 = undefined;
var x254: u1 = undefined;
fiatP224AddcarryxU32(&x253, &x254, x252, x211, x238);
var x255: u32 = undefined;
var x256: u1 = undefined;
fiatP224AddcarryxU32(&x255, &x256, x254, x213, x240);
var x257: u32 = undefined;
var x258: u1 = undefined;
fiatP224AddcarryxU32(&x257, &x258, x256, x215, x242);
var x259: u32 = undefined;
var x260: u1 = undefined;
fiatP224AddcarryxU32(&x259, &x260, x258, x217, x244);
var x261: u32 = undefined;
var x262: u1 = undefined;
fiatP224AddcarryxU32(&x261, &x262, x260, x219, x246);
var x263: u32 = undefined;
var x264: u1 = undefined;
fiatP224AddcarryxU32(&x263, &x264, x262, x221, x248);
var x265: u32 = undefined;
var x266: u32 = undefined;
fiatP224MulxU32(&x265, &x266, x249, 0xffffffff);
var x267: u32 = undefined;
var x268: u32 = undefined;
fiatP224MulxU32(&x267, &x268, x265, 0xffffffff);
var x269: u32 = undefined;
var x270: u32 = undefined;
fiatP224MulxU32(&x269, &x270, x265, 0xffffffff);
var x271: u32 = undefined;
var x272: u32 = undefined;
fiatP224MulxU32(&x271, &x272, x265, 0xffffffff);
var x273: u32 = undefined;
var x274: u32 = undefined;
fiatP224MulxU32(&x273, &x274, x265, 0xffffffff);
var x275: u32 = undefined;
var x276: u1 = undefined;
fiatP224AddcarryxU32(&x275, &x276, 0x0, x274, x271);
var x277: u32 = undefined;
var x278: u1 = undefined;
fiatP224AddcarryxU32(&x277, &x278, x276, x272, x269);
var x279: u32 = undefined;
var x280: u1 = undefined;
fiatP224AddcarryxU32(&x279, &x280, x278, x270, x267);
const x281: u32 = (@intCast(u32, x280) + x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
fiatP224AddcarryxU32(&x282, &x283, 0x0, x249, x265);
var x284: u32 = undefined;
var x285: u1 = undefined;
fiatP224AddcarryxU32(&x284, &x285, x283, x251, @intCast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
fiatP224AddcarryxU32(&x286, &x287, x285, x253, @intCast(u32, 0x0));
var x288: u32 = undefined;
var x289: u1 = undefined;
fiatP224AddcarryxU32(&x288, &x289, x287, x255, x273);
var x290: u32 = undefined;
var x291: u1 = undefined;
fiatP224AddcarryxU32(&x290, &x291, x289, x257, x275);
var x292: u32 = undefined;
var x293: u1 = undefined;
fiatP224AddcarryxU32(&x292, &x293, x291, x259, x277);
var x294: u32 = undefined;
var x295: u1 = undefined;
fiatP224AddcarryxU32(&x294, &x295, x293, x261, x279);
var x296: u32 = undefined;
var x297: u1 = undefined;
fiatP224AddcarryxU32(&x296, &x297, x295, x263, x281);
const x298: u32 = (@intCast(u32, x297) + @intCast(u32, x264));
var x299: u32 = undefined;
var x300: u32 = undefined;
fiatP224MulxU32(&x299, &x300, x4, (arg2[6]));
var x301: u32 = undefined;
var x302: u32 = undefined;
fiatP224MulxU32(&x301, &x302, x4, (arg2[5]));
var x303: u32 = undefined;
var x304: u32 = undefined;
fiatP224MulxU32(&x303, &x304, x4, (arg2[4]));
var x305: u32 = undefined;
var x306: u32 = undefined;
fiatP224MulxU32(&x305, &x306, x4, (arg2[3]));
var x307: u32 = undefined;
var x308: u32 = undefined;
fiatP224MulxU32(&x307, &x308, x4, (arg2[2]));
var x309: u32 = undefined;
var x310: u32 = undefined;
fiatP224MulxU32(&x309, &x310, x4, (arg2[1]));
var x311: u32 = undefined;
var x312: u32 = undefined;
fiatP224MulxU32(&x311, &x312, x4, (arg2[0]));
var x313: u32 = undefined;
var x314: u1 = undefined;
fiatP224AddcarryxU32(&x313, &x314, 0x0, x312, x309);
var x315: u32 = undefined;
var x316: u1 = undefined;
fiatP224AddcarryxU32(&x315, &x316, x314, x310, x307);
var x317: u32 = undefined;
var x318: u1 = undefined;
fiatP224AddcarryxU32(&x317, &x318, x316, x308, x305);
var x319: u32 = undefined;
var x320: u1 = undefined;
fiatP224AddcarryxU32(&x319, &x320, x318, x306, x303);
var x321: u32 = undefined;
var x322: u1 = undefined;
fiatP224AddcarryxU32(&x321, &x322, x320, x304, x301);
var x323: u32 = undefined;
var x324: u1 = undefined;
fiatP224AddcarryxU32(&x323, &x324, x322, x302, x299);
const x325: u32 = (@intCast(u32, x324) + x300);
var x326: u32 = undefined;
var x327: u1 = undefined;
fiatP224AddcarryxU32(&x326, &x327, 0x0, x284, x311);
var x328: u32 = undefined;
var x329: u1 = undefined;
fiatP224AddcarryxU32(&x328, &x329, x327, x286, x313);
var x330: u32 = undefined;
var x331: u1 = undefined;
fiatP224AddcarryxU32(&x330, &x331, x329, x288, x315);
var x332: u32 = undefined;
var x333: u1 = undefined;
fiatP224AddcarryxU32(&x332, &x333, x331, x290, x317);
var x334: u32 = undefined;
var x335: u1 = undefined;
fiatP224AddcarryxU32(&x334, &x335, x333, x292, x319);
var x336: u32 = undefined;
var x337: u1 = undefined;
fiatP224AddcarryxU32(&x336, &x337, x335, x294, x321);
var x338: u32 = undefined;
var x339: u1 = undefined;
fiatP224AddcarryxU32(&x338, &x339, x337, x296, x323);
var x340: u32 = undefined;
var x341: u1 = undefined;
fiatP224AddcarryxU32(&x340, &x341, x339, x298, x325);
var x342: u32 = undefined;
var x343: u32 = undefined;
fiatP224MulxU32(&x342, &x343, x326, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
fiatP224MulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
fiatP224MulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
fiatP224MulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
fiatP224MulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
fiatP224AddcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
fiatP224AddcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
fiatP224AddcarryxU32(&x356, &x357, x355, x347, x344);
const x358: u32 = (@intCast(u32, x357) + x345);
var x359: u32 = undefined;
var x360: u1 = undefined;
fiatP224AddcarryxU32(&x359, &x360, 0x0, x326, x342);
var x361: u32 = undefined;
var x362: u1 = undefined;
fiatP224AddcarryxU32(&x361, &x362, x360, x328, @intCast(u32, 0x0));
var x363: u32 = undefined;
var x364: u1 = undefined;
fiatP224AddcarryxU32(&x363, &x364, x362, x330, @intCast(u32, 0x0));
var x365: u32 = undefined;
var x366: u1 = undefined;
fiatP224AddcarryxU32(&x365, &x366, x364, x332, x350);
var x367: u32 = undefined;
var x368: u1 = undefined;
fiatP224AddcarryxU32(&x367, &x368, x366, x334, x352);
var x369: u32 = undefined;
var x370: u1 = undefined;
fiatP224AddcarryxU32(&x369, &x370, x368, x336, x354);
var x371: u32 = undefined;
var x372: u1 = undefined;
fiatP224AddcarryxU32(&x371, &x372, x370, x338, x356);
var x373: u32 = undefined;
var x374: u1 = undefined;
fiatP224AddcarryxU32(&x373, &x374, x372, x340, x358);
const x375: u32 = (@intCast(u32, x374) + @intCast(u32, x341));
var x376: u32 = undefined;
var x377: u32 = undefined;
fiatP224MulxU32(&x376, &x377, x5, (arg2[6]));
var x378: u32 = undefined;
var x379: u32 = undefined;
fiatP224MulxU32(&x378, &x379, x5, (arg2[5]));
var x380: u32 = undefined;
var x381: u32 = undefined;
fiatP224MulxU32(&x380, &x381, x5, (arg2[4]));
var x382: u32 = undefined;
var x383: u32 = undefined;
fiatP224MulxU32(&x382, &x383, x5, (arg2[3]));
var x384: u32 = undefined;
var x385: u32 = undefined;
fiatP224MulxU32(&x384, &x385, x5, (arg2[2]));
var x386: u32 = undefined;
var x387: u32 = undefined;
fiatP224MulxU32(&x386, &x387, x5, (arg2[1]));
var x388: u32 = undefined;
var x389: u32 = undefined;
fiatP224MulxU32(&x388, &x389, x5, (arg2[0]));
var x390: u32 = undefined;
var x391: u1 = undefined;
fiatP224AddcarryxU32(&x390, &x391, 0x0, x389, x386);
var x392: u32 = undefined;
var x393: u1 = undefined;
fiatP224AddcarryxU32(&x392, &x393, x391, x387, x384);
var x394: u32 = undefined;
var x395: u1 = undefined;
fiatP224AddcarryxU32(&x394, &x395, x393, x385, x382);
var x396: u32 = undefined;
var x397: u1 = undefined;
fiatP224AddcarryxU32(&x396, &x397, x395, x383, x380);
var x398: u32 = undefined;
var x399: u1 = undefined;
fiatP224AddcarryxU32(&x398, &x399, x397, x381, x378);
var x400: u32 = undefined;
var x401: u1 = undefined;
fiatP224AddcarryxU32(&x400, &x401, x399, x379, x376);
const x402: u32 = (@intCast(u32, x401) + x377);
var x403: u32 = undefined;
var x404: u1 = undefined;
fiatP224AddcarryxU32(&x403, &x404, 0x0, x361, x388);
var x405: u32 = undefined;
var x406: u1 = undefined;
fiatP224AddcarryxU32(&x405, &x406, x404, x363, x390);
var x407: u32 = undefined;
var x408: u1 = undefined;
fiatP224AddcarryxU32(&x407, &x408, x406, x365, x392);
var x409: u32 = undefined;
var x410: u1 = undefined;
fiatP224AddcarryxU32(&x409, &x410, x408, x367, x394);
var x411: u32 = undefined;
var x412: u1 = undefined;
fiatP224AddcarryxU32(&x411, &x412, x410, x369, x396);
var x413: u32 = undefined;
var x414: u1 = undefined;
fiatP224AddcarryxU32(&x413, &x414, x412, x371, x398);
var x415: u32 = undefined;
var x416: u1 = undefined;
fiatP224AddcarryxU32(&x415, &x416, x414, x373, x400);
var x417: u32 = undefined;
var x418: u1 = undefined;
fiatP224AddcarryxU32(&x417, &x418, x416, x375, x402);
var x419: u32 = undefined;
var x420: u32 = undefined;
fiatP224MulxU32(&x419, &x420, x403, 0xffffffff);
var x421: u32 = undefined;
var x422: u32 = undefined;
fiatP224MulxU32(&x421, &x422, x419, 0xffffffff);
var x423: u32 = undefined;
var x424: u32 = undefined;
fiatP224MulxU32(&x423, &x424, x419, 0xffffffff);
var x425: u32 = undefined;
var x426: u32 = undefined;
fiatP224MulxU32(&x425, &x426, x419, 0xffffffff);
var x427: u32 = undefined;
var x428: u32 = undefined;
fiatP224MulxU32(&x427, &x428, x419, 0xffffffff);
var x429: u32 = undefined;
var x430: u1 = undefined;
fiatP224AddcarryxU32(&x429, &x430, 0x0, x428, x425);
var x431: u32 = undefined;
var x432: u1 = undefined;
fiatP224AddcarryxU32(&x431, &x432, x430, x426, x423);
var x433: u32 = undefined;
var x434: u1 = undefined;
fiatP224AddcarryxU32(&x433, &x434, x432, x424, x421);
const x435: u32 = (@intCast(u32, x434) + x422);
var x436: u32 = undefined;
var x437: u1 = undefined;
fiatP224AddcarryxU32(&x436, &x437, 0x0, x403, x419);
var x438: u32 = undefined;
var x439: u1 = undefined;
fiatP224AddcarryxU32(&x438, &x439, x437, x405, @intCast(u32, 0x0));
var x440: u32 = undefined;
var x441: u1 = undefined;
fiatP224AddcarryxU32(&x440, &x441, x439, x407, @intCast(u32, 0x0));
var x442: u32 = undefined;
var x443: u1 = undefined;
fiatP224AddcarryxU32(&x442, &x443, x441, x409, x427);
var x444: u32 = undefined;
var x445: u1 = undefined;
fiatP224AddcarryxU32(&x444, &x445, x443, x411, x429);
var x446: u32 = undefined;
var x447: u1 = undefined;
fiatP224AddcarryxU32(&x446, &x447, x445, x413, x431);
var x448: u32 = undefined;
var x449: u1 = undefined;
fiatP224AddcarryxU32(&x448, &x449, x447, x415, x433);
var x450: u32 = undefined;
var x451: u1 = undefined;
fiatP224AddcarryxU32(&x450, &x451, x449, x417, x435);
const x452: u32 = (@intCast(u32, x451) + @intCast(u32, x418));
var x453: u32 = undefined;
var x454: u32 = undefined;
fiatP224MulxU32(&x453, &x454, x6, (arg2[6]));
var x455: u32 = undefined;
var x456: u32 = undefined;
fiatP224MulxU32(&x455, &x456, x6, (arg2[5]));
var x457: u32 = undefined;
var x458: u32 = undefined;
fiatP224MulxU32(&x457, &x458, x6, (arg2[4]));
var x459: u32 = undefined;
var x460: u32 = undefined;
fiatP224MulxU32(&x459, &x460, x6, (arg2[3]));
var x461: u32 = undefined;
var x462: u32 = undefined;
fiatP224MulxU32(&x461, &x462, x6, (arg2[2]));
var x463: u32 = undefined;
var x464: u32 = undefined;
fiatP224MulxU32(&x463, &x464, x6, (arg2[1]));
var x465: u32 = undefined;
var x466: u32 = undefined;
fiatP224MulxU32(&x465, &x466, x6, (arg2[0]));
var x467: u32 = undefined;
var x468: u1 = undefined;
fiatP224AddcarryxU32(&x467, &x468, 0x0, x466, x463);
var x469: u32 = undefined;
var x470: u1 = undefined;
fiatP224AddcarryxU32(&x469, &x470, x468, x464, x461);
var x471: u32 = undefined;
var x472: u1 = undefined;
fiatP224AddcarryxU32(&x471, &x472, x470, x462, x459);
var x473: u32 = undefined;
var x474: u1 = undefined;
fiatP224AddcarryxU32(&x473, &x474, x472, x460, x457);
var x475: u32 = undefined;
var x476: u1 = undefined;
fiatP224AddcarryxU32(&x475, &x476, x474, x458, x455);
var x477: u32 = undefined;
var x478: u1 = undefined;
fiatP224AddcarryxU32(&x477, &x478, x476, x456, x453);
const x479: u32 = (@intCast(u32, x478) + x454);
var x480: u32 = undefined;
var x481: u1 = undefined;
fiatP224AddcarryxU32(&x480, &x481, 0x0, x438, x465);
var x482: u32 = undefined;
var x483: u1 = undefined;
fiatP224AddcarryxU32(&x482, &x483, x481, x440, x467);
var x484: u32 = undefined;
var x485: u1 = undefined;
fiatP224AddcarryxU32(&x484, &x485, x483, x442, x469);
var x486: u32 = undefined;
var x487: u1 = undefined;
fiatP224AddcarryxU32(&x486, &x487, x485, x444, x471);
var x488: u32 = undefined;
var x489: u1 = undefined;
fiatP224AddcarryxU32(&x488, &x489, x487, x446, x473);
var x490: u32 = undefined;
var x491: u1 = undefined;
fiatP224AddcarryxU32(&x490, &x491, x489, x448, x475);
var x492: u32 = undefined;
var x493: u1 = undefined;
fiatP224AddcarryxU32(&x492, &x493, x491, x450, x477);
var x494: u32 = undefined;
var x495: u1 = undefined;
fiatP224AddcarryxU32(&x494, &x495, x493, x452, x479);
var x496: u32 = undefined;
var x497: u32 = undefined;
fiatP224MulxU32(&x496, &x497, x480, 0xffffffff);
var x498: u32 = undefined;
var x499: u32 = undefined;
fiatP224MulxU32(&x498, &x499, x496, 0xffffffff);
var x500: u32 = undefined;
var x501: u32 = undefined;
fiatP224MulxU32(&x500, &x501, x496, 0xffffffff);
var x502: u32 = undefined;
var x503: u32 = undefined;
fiatP224MulxU32(&x502, &x503, x496, 0xffffffff);
var x504: u32 = undefined;
var x505: u32 = undefined;
fiatP224MulxU32(&x504, &x505, x496, 0xffffffff);
var x506: u32 = undefined;
var x507: u1 = undefined;
fiatP224AddcarryxU32(&x506, &x507, 0x0, x505, x502);
var x508: u32 = undefined;
var x509: u1 = undefined;
fiatP224AddcarryxU32(&x508, &x509, x507, x503, x500);
var x510: u32 = undefined;
var x511: u1 = undefined;
fiatP224AddcarryxU32(&x510, &x511, x509, x501, x498);
const x512: u32 = (@intCast(u32, x511) + x499);
var x513: u32 = undefined;
var x514: u1 = undefined;
fiatP224AddcarryxU32(&x513, &x514, 0x0, x480, x496);
var x515: u32 = undefined;
var x516: u1 = undefined;
fiatP224AddcarryxU32(&x515, &x516, x514, x482, @intCast(u32, 0x0));
var x517: u32 = undefined;
var x518: u1 = undefined;
fiatP224AddcarryxU32(&x517, &x518, x516, x484, @intCast(u32, 0x0));
var x519: u32 = undefined;
var x520: u1 = undefined;
fiatP224AddcarryxU32(&x519, &x520, x518, x486, x504);
var x521: u32 = undefined;
var x522: u1 = undefined;
fiatP224AddcarryxU32(&x521, &x522, x520, x488, x506);
var x523: u32 = undefined;
var x524: u1 = undefined;
fiatP224AddcarryxU32(&x523, &x524, x522, x490, x508);
var x525: u32 = undefined;
var x526: u1 = undefined;
fiatP224AddcarryxU32(&x525, &x526, x524, x492, x510);
var x527: u32 = undefined;
var x528: u1 = undefined;
fiatP224AddcarryxU32(&x527, &x528, x526, x494, x512);
const x529: u32 = (@intCast(u32, x528) + @intCast(u32, x495));
var x530: u32 = undefined;
var x531: u1 = undefined;
fiatP224SubborrowxU32(&x530, &x531, 0x0, x515, @intCast(u32, 0x1));
var x532: u32 = undefined;
var x533: u1 = undefined;
fiatP224SubborrowxU32(&x532, &x533, x531, x517, @intCast(u32, 0x0));
var x534: u32 = undefined;
var x535: u1 = undefined;
fiatP224SubborrowxU32(&x534, &x535, x533, x519, @intCast(u32, 0x0));
var x536: u32 = undefined;
var x537: u1 = undefined;
fiatP224SubborrowxU32(&x536, &x537, x535, x521, 0xffffffff);
var x538: u32 = undefined;
var x539: u1 = undefined;
fiatP224SubborrowxU32(&x538, &x539, x537, x523, 0xffffffff);
var x540: u32 = undefined;
var x541: u1 = undefined;
fiatP224SubborrowxU32(&x540, &x541, x539, x525, 0xffffffff);
var x542: u32 = undefined;
var x543: u1 = undefined;
fiatP224SubborrowxU32(&x542, &x543, x541, x527, 0xffffffff);
var x544: u32 = undefined;
var x545: u1 = undefined;
fiatP224SubborrowxU32(&x544, &x545, x543, x529, @intCast(u32, 0x0));
var x546: u32 = undefined;
fiatP224CmovznzU32(&x546, x545, x530, x515);
var x547: u32 = undefined;
fiatP224CmovznzU32(&x547, x545, x532, x517);
var x548: u32 = undefined;
fiatP224CmovznzU32(&x548, x545, x534, x519);
var x549: u32 = undefined;
fiatP224CmovznzU32(&x549, x545, x536, x521);
var x550: u32 = undefined;
fiatP224CmovznzU32(&x550, x545, x538, x523);
var x551: u32 = undefined;
fiatP224CmovznzU32(&x551, x545, x540, x525);
var x552: u32 = undefined;
fiatP224CmovznzU32(&x552, x545, x542, x527);
out1[0] = x546;
out1[1] = x547;
out1[2] = x548;
out1[3] = x549;
out1[4] = x550;
out1[5] = x551;
out1[6] = x552;
}
/// The function fiatP224Square squares a field element in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Square(out1: *[7]u32, arg1: [7]u32) void {
const x1: u32 = (arg1[1]);
const x2: u32 = (arg1[2]);
const x3: u32 = (arg1[3]);
const x4: u32 = (arg1[4]);
const x5: u32 = (arg1[5]);
const x6: u32 = (arg1[6]);
const x7: u32 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
fiatP224MulxU32(&x8, &x9, x7, (arg1[6]));
var x10: u32 = undefined;
var x11: u32 = undefined;
fiatP224MulxU32(&x10, &x11, x7, (arg1[5]));
var x12: u32 = undefined;
var x13: u32 = undefined;
fiatP224MulxU32(&x12, &x13, x7, (arg1[4]));
var x14: u32 = undefined;
var x15: u32 = undefined;
fiatP224MulxU32(&x14, &x15, x7, (arg1[3]));
var x16: u32 = undefined;
var x17: u32 = undefined;
fiatP224MulxU32(&x16, &x17, x7, (arg1[2]));
var x18: u32 = undefined;
var x19: u32 = undefined;
fiatP224MulxU32(&x18, &x19, x7, (arg1[1]));
var x20: u32 = undefined;
var x21: u32 = undefined;
fiatP224MulxU32(&x20, &x21, x7, (arg1[0]));
var x22: u32 = undefined;
var x23: u1 = undefined;
fiatP224AddcarryxU32(&x22, &x23, 0x0, x21, x18);
var x24: u32 = undefined;
var x25: u1 = undefined;
fiatP224AddcarryxU32(&x24, &x25, x23, x19, x16);
var x26: u32 = undefined;
var x27: u1 = undefined;
fiatP224AddcarryxU32(&x26, &x27, x25, x17, x14);
var x28: u32 = undefined;
var x29: u1 = undefined;
fiatP224AddcarryxU32(&x28, &x29, x27, x15, x12);
var x30: u32 = undefined;
var x31: u1 = undefined;
fiatP224AddcarryxU32(&x30, &x31, x29, x13, x10);
var x32: u32 = undefined;
var x33: u1 = undefined;
fiatP224AddcarryxU32(&x32, &x33, x31, x11, x8);
const x34: u32 = (@intCast(u32, x33) + x9);
var x35: u32 = undefined;
var x36: u32 = undefined;
fiatP224MulxU32(&x35, &x36, x20, 0xffffffff);
var x37: u32 = undefined;
var x38: u32 = undefined;
fiatP224MulxU32(&x37, &x38, x35, 0xffffffff);
var x39: u32 = undefined;
var x40: u32 = undefined;
fiatP224MulxU32(&x39, &x40, x35, 0xffffffff);
var x41: u32 = undefined;
var x42: u32 = undefined;
fiatP224MulxU32(&x41, &x42, x35, 0xffffffff);
var x43: u32 = undefined;
var x44: u32 = undefined;
fiatP224MulxU32(&x43, &x44, x35, 0xffffffff);
var x45: u32 = undefined;
var x46: u1 = undefined;
fiatP224AddcarryxU32(&x45, &x46, 0x0, x44, x41);
var x47: u32 = undefined;
var x48: u1 = undefined;
fiatP224AddcarryxU32(&x47, &x48, x46, x42, x39);
var x49: u32 = undefined;
var x50: u1 = undefined;
fiatP224AddcarryxU32(&x49, &x50, x48, x40, x37);
const x51: u32 = (@intCast(u32, x50) + x38);
var x52: u32 = undefined;
var x53: u1 = undefined;
fiatP224AddcarryxU32(&x52, &x53, 0x0, x20, x35);
var x54: u32 = undefined;
var x55: u1 = undefined;
fiatP224AddcarryxU32(&x54, &x55, x53, x22, @intCast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
fiatP224AddcarryxU32(&x56, &x57, x55, x24, @intCast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
fiatP224AddcarryxU32(&x58, &x59, x57, x26, x43);
var x60: u32 = undefined;
var x61: u1 = undefined;
fiatP224AddcarryxU32(&x60, &x61, x59, x28, x45);
var x62: u32 = undefined;
var x63: u1 = undefined;
fiatP224AddcarryxU32(&x62, &x63, x61, x30, x47);
var x64: u32 = undefined;
var x65: u1 = undefined;
fiatP224AddcarryxU32(&x64, &x65, x63, x32, x49);
var x66: u32 = undefined;
var x67: u1 = undefined;
fiatP224AddcarryxU32(&x66, &x67, x65, x34, x51);
var x68: u32 = undefined;
var x69: u32 = undefined;
fiatP224MulxU32(&x68, &x69, x1, (arg1[6]));
var x70: u32 = undefined;
var x71: u32 = undefined;
fiatP224MulxU32(&x70, &x71, x1, (arg1[5]));
var x72: u32 = undefined;
var x73: u32 = undefined;
fiatP224MulxU32(&x72, &x73, x1, (arg1[4]));
var x74: u32 = undefined;
var x75: u32 = undefined;
fiatP224MulxU32(&x74, &x75, x1, (arg1[3]));
var x76: u32 = undefined;
var x77: u32 = undefined;
fiatP224MulxU32(&x76, &x77, x1, (arg1[2]));
var x78: u32 = undefined;
var x79: u32 = undefined;
fiatP224MulxU32(&x78, &x79, x1, (arg1[1]));
var x80: u32 = undefined;
var x81: u32 = undefined;
fiatP224MulxU32(&x80, &x81, x1, (arg1[0]));
var x82: u32 = undefined;
var x83: u1 = undefined;
fiatP224AddcarryxU32(&x82, &x83, 0x0, x81, x78);
var x84: u32 = undefined;
var x85: u1 = undefined;
fiatP224AddcarryxU32(&x84, &x85, x83, x79, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
fiatP224AddcarryxU32(&x86, &x87, x85, x77, x74);
var x88: u32 = undefined;
var x89: u1 = undefined;
fiatP224AddcarryxU32(&x88, &x89, x87, x75, x72);
var x90: u32 = undefined;
var x91: u1 = undefined;
fiatP224AddcarryxU32(&x90, &x91, x89, x73, x70);
var x92: u32 = undefined;
var x93: u1 = undefined;
fiatP224AddcarryxU32(&x92, &x93, x91, x71, x68);
const x94: u32 = (@intCast(u32, x93) + x69);
var x95: u32 = undefined;
var x96: u1 = undefined;
fiatP224AddcarryxU32(&x95, &x96, 0x0, x54, x80);
var x97: u32 = undefined;
var x98: u1 = undefined;
fiatP224AddcarryxU32(&x97, &x98, x96, x56, x82);
var x99: u32 = undefined;
var x100: u1 = undefined;
fiatP224AddcarryxU32(&x99, &x100, x98, x58, x84);
var x101: u32 = undefined;
var x102: u1 = undefined;
fiatP224AddcarryxU32(&x101, &x102, x100, x60, x86);
var x103: u32 = undefined;
var x104: u1 = undefined;
fiatP224AddcarryxU32(&x103, &x104, x102, x62, x88);
var x105: u32 = undefined;
var x106: u1 = undefined;
fiatP224AddcarryxU32(&x105, &x106, x104, x64, x90);
var x107: u32 = undefined;
var x108: u1 = undefined;
fiatP224AddcarryxU32(&x107, &x108, x106, x66, x92);
var x109: u32 = undefined;
var x110: u1 = undefined;
fiatP224AddcarryxU32(&x109, &x110, x108, @intCast(u32, x67), x94);
var x111: u32 = undefined;
var x112: u32 = undefined;
fiatP224MulxU32(&x111, &x112, x95, 0xffffffff);
var x113: u32 = undefined;
var x114: u32 = undefined;
fiatP224MulxU32(&x113, &x114, x111, 0xffffffff);
var x115: u32 = undefined;
var x116: u32 = undefined;
fiatP224MulxU32(&x115, &x116, x111, 0xffffffff);
var x117: u32 = undefined;
var x118: u32 = undefined;
fiatP224MulxU32(&x117, &x118, x111, 0xffffffff);
var x119: u32 = undefined;
var x120: u32 = undefined;
fiatP224MulxU32(&x119, &x120, x111, 0xffffffff);
var x121: u32 = undefined;
var x122: u1 = undefined;
fiatP224AddcarryxU32(&x121, &x122, 0x0, x120, x117);
var x123: u32 = undefined;
var x124: u1 = undefined;
fiatP224AddcarryxU32(&x123, &x124, x122, x118, x115);
var x125: u32 = undefined;
var x126: u1 = undefined;
fiatP224AddcarryxU32(&x125, &x126, x124, x116, x113);
const x127: u32 = (@intCast(u32, x126) + x114);
var x128: u32 = undefined;
var x129: u1 = undefined;
fiatP224AddcarryxU32(&x128, &x129, 0x0, x95, x111);
var x130: u32 = undefined;
var x131: u1 = undefined;
fiatP224AddcarryxU32(&x130, &x131, x129, x97, @intCast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
fiatP224AddcarryxU32(&x132, &x133, x131, x99, @intCast(u32, 0x0));
var x134: u32 = undefined;
var x135: u1 = undefined;
fiatP224AddcarryxU32(&x134, &x135, x133, x101, x119);
var x136: u32 = undefined;
var x137: u1 = undefined;
fiatP224AddcarryxU32(&x136, &x137, x135, x103, x121);
var x138: u32 = undefined;
var x139: u1 = undefined;
fiatP224AddcarryxU32(&x138, &x139, x137, x105, x123);
var x140: u32 = undefined;
var x141: u1 = undefined;
fiatP224AddcarryxU32(&x140, &x141, x139, x107, x125);
var x142: u32 = undefined;
var x143: u1 = undefined;
fiatP224AddcarryxU32(&x142, &x143, x141, x109, x127);
const x144: u32 = (@intCast(u32, x143) + @intCast(u32, x110));
var x145: u32 = undefined;
var x146: u32 = undefined;
fiatP224MulxU32(&x145, &x146, x2, (arg1[6]));
var x147: u32 = undefined;
var x148: u32 = undefined;
fiatP224MulxU32(&x147, &x148, x2, (arg1[5]));
var x149: u32 = undefined;
var x150: u32 = undefined;
fiatP224MulxU32(&x149, &x150, x2, (arg1[4]));
var x151: u32 = undefined;
var x152: u32 = undefined;
fiatP224MulxU32(&x151, &x152, x2, (arg1[3]));
var x153: u32 = undefined;
var x154: u32 = undefined;
fiatP224MulxU32(&x153, &x154, x2, (arg1[2]));
var x155: u32 = undefined;
var x156: u32 = undefined;
fiatP224MulxU32(&x155, &x156, x2, (arg1[1]));
var x157: u32 = undefined;
var x158: u32 = undefined;
fiatP224MulxU32(&x157, &x158, x2, (arg1[0]));
var x159: u32 = undefined;
var x160: u1 = undefined;
fiatP224AddcarryxU32(&x159, &x160, 0x0, x158, x155);
var x161: u32 = undefined;
var x162: u1 = undefined;
fiatP224AddcarryxU32(&x161, &x162, x160, x156, x153);
var x163: u32 = undefined;
var x164: u1 = undefined;
fiatP224AddcarryxU32(&x163, &x164, x162, x154, x151);
var x165: u32 = undefined;
var x166: u1 = undefined;
fiatP224AddcarryxU32(&x165, &x166, x164, x152, x149);
var x167: u32 = undefined;
var x168: u1 = undefined;
fiatP224AddcarryxU32(&x167, &x168, x166, x150, x147);
var x169: u32 = undefined;
var x170: u1 = undefined;
fiatP224AddcarryxU32(&x169, &x170, x168, x148, x145);
const x171: u32 = (@intCast(u32, x170) + x146);
var x172: u32 = undefined;
var x173: u1 = undefined;
fiatP224AddcarryxU32(&x172, &x173, 0x0, x130, x157);
var x174: u32 = undefined;
var x175: u1 = undefined;
fiatP224AddcarryxU32(&x174, &x175, x173, x132, x159);
var x176: u32 = undefined;
var x177: u1 = undefined;
fiatP224AddcarryxU32(&x176, &x177, x175, x134, x161);
var x178: u32 = undefined;
var x179: u1 = undefined;
fiatP224AddcarryxU32(&x178, &x179, x177, x136, x163);
var x180: u32 = undefined;
var x181: u1 = undefined;
fiatP224AddcarryxU32(&x180, &x181, x179, x138, x165);
var x182: u32 = undefined;
var x183: u1 = undefined;
fiatP224AddcarryxU32(&x182, &x183, x181, x140, x167);
var x184: u32 = undefined;
var x185: u1 = undefined;
fiatP224AddcarryxU32(&x184, &x185, x183, x142, x169);
var x186: u32 = undefined;
var x187: u1 = undefined;
fiatP224AddcarryxU32(&x186, &x187, x185, x144, x171);
var x188: u32 = undefined;
var x189: u32 = undefined;
fiatP224MulxU32(&x188, &x189, x172, 0xffffffff);
var x190: u32 = undefined;
var x191: u32 = undefined;
fiatP224MulxU32(&x190, &x191, x188, 0xffffffff);
var x192: u32 = undefined;
var x193: u32 = undefined;
fiatP224MulxU32(&x192, &x193, x188, 0xffffffff);
var x194: u32 = undefined;
var x195: u32 = undefined;
fiatP224MulxU32(&x194, &x195, x188, 0xffffffff);
var x196: u32 = undefined;
var x197: u32 = undefined;
fiatP224MulxU32(&x196, &x197, x188, 0xffffffff);
var x198: u32 = undefined;
var x199: u1 = undefined;
fiatP224AddcarryxU32(&x198, &x199, 0x0, x197, x194);
var x200: u32 = undefined;
var x201: u1 = undefined;
fiatP224AddcarryxU32(&x200, &x201, x199, x195, x192);
var x202: u32 = undefined;
var x203: u1 = undefined;
fiatP224AddcarryxU32(&x202, &x203, x201, x193, x190);
const x204: u32 = (@intCast(u32, x203) + x191);
var x205: u32 = undefined;
var x206: u1 = undefined;
fiatP224AddcarryxU32(&x205, &x206, 0x0, x172, x188);
var x207: u32 = undefined;
var x208: u1 = undefined;
fiatP224AddcarryxU32(&x207, &x208, x206, x174, @intCast(u32, 0x0));
var x209: u32 = undefined;
var x210: u1 = undefined;
fiatP224AddcarryxU32(&x209, &x210, x208, x176, @intCast(u32, 0x0));
var x211: u32 = undefined;
var x212: u1 = undefined;
fiatP224AddcarryxU32(&x211, &x212, x210, x178, x196);
var x213: u32 = undefined;
var x214: u1 = undefined;
fiatP224AddcarryxU32(&x213, &x214, x212, x180, x198);
var x215: u32 = undefined;
var x216: u1 = undefined;
fiatP224AddcarryxU32(&x215, &x216, x214, x182, x200);
var x217: u32 = undefined;
var x218: u1 = undefined;
fiatP224AddcarryxU32(&x217, &x218, x216, x184, x202);
var x219: u32 = undefined;
var x220: u1 = undefined;
fiatP224AddcarryxU32(&x219, &x220, x218, x186, x204);
const x221: u32 = (@intCast(u32, x220) + @intCast(u32, x187));
var x222: u32 = undefined;
var x223: u32 = undefined;
fiatP224MulxU32(&x222, &x223, x3, (arg1[6]));
var x224: u32 = undefined;
var x225: u32 = undefined;
fiatP224MulxU32(&x224, &x225, x3, (arg1[5]));
var x226: u32 = undefined;
var x227: u32 = undefined;
fiatP224MulxU32(&x226, &x227, x3, (arg1[4]));
var x228: u32 = undefined;
var x229: u32 = undefined;
fiatP224MulxU32(&x228, &x229, x3, (arg1[3]));
var x230: u32 = undefined;
var x231: u32 = undefined;
fiatP224MulxU32(&x230, &x231, x3, (arg1[2]));
var x232: u32 = undefined;
var x233: u32 = undefined;
fiatP224MulxU32(&x232, &x233, x3, (arg1[1]));
var x234: u32 = undefined;
var x235: u32 = undefined;
fiatP224MulxU32(&x234, &x235, x3, (arg1[0]));
var x236: u32 = undefined;
var x237: u1 = undefined;
fiatP224AddcarryxU32(&x236, &x237, 0x0, x235, x232);
var x238: u32 = undefined;
var x239: u1 = undefined;
fiatP224AddcarryxU32(&x238, &x239, x237, x233, x230);
var x240: u32 = undefined;
var x241: u1 = undefined;
fiatP224AddcarryxU32(&x240, &x241, x239, x231, x228);
var x242: u32 = undefined;
var x243: u1 = undefined;
fiatP224AddcarryxU32(&x242, &x243, x241, x229, x226);
var x244: u32 = undefined;
var x245: u1 = undefined;
fiatP224AddcarryxU32(&x244, &x245, x243, x227, x224);
var x246: u32 = undefined;
var x247: u1 = undefined;
fiatP224AddcarryxU32(&x246, &x247, x245, x225, x222);
const x248: u32 = (@intCast(u32, x247) + x223);
var x249: u32 = undefined;
var x250: u1 = undefined;
fiatP224AddcarryxU32(&x249, &x250, 0x0, x207, x234);
var x251: u32 = undefined;
var x252: u1 = undefined;
fiatP224AddcarryxU32(&x251, &x252, x250, x209, x236);
var x253: u32 = undefined;
var x254: u1 = undefined;
fiatP224AddcarryxU32(&x253, &x254, x252, x211, x238);
var x255: u32 = undefined;
var x256: u1 = undefined;
fiatP224AddcarryxU32(&x255, &x256, x254, x213, x240);
var x257: u32 = undefined;
var x258: u1 = undefined;
fiatP224AddcarryxU32(&x257, &x258, x256, x215, x242);
var x259: u32 = undefined;
var x260: u1 = undefined;
fiatP224AddcarryxU32(&x259, &x260, x258, x217, x244);
var x261: u32 = undefined;
var x262: u1 = undefined;
fiatP224AddcarryxU32(&x261, &x262, x260, x219, x246);
var x263: u32 = undefined;
var x264: u1 = undefined;
fiatP224AddcarryxU32(&x263, &x264, x262, x221, x248);
var x265: u32 = undefined;
var x266: u32 = undefined;
fiatP224MulxU32(&x265, &x266, x249, 0xffffffff);
var x267: u32 = undefined;
var x268: u32 = undefined;
fiatP224MulxU32(&x267, &x268, x265, 0xffffffff);
var x269: u32 = undefined;
var x270: u32 = undefined;
fiatP224MulxU32(&x269, &x270, x265, 0xffffffff);
var x271: u32 = undefined;
var x272: u32 = undefined;
fiatP224MulxU32(&x271, &x272, x265, 0xffffffff);
var x273: u32 = undefined;
var x274: u32 = undefined;
fiatP224MulxU32(&x273, &x274, x265, 0xffffffff);
var x275: u32 = undefined;
var x276: u1 = undefined;
fiatP224AddcarryxU32(&x275, &x276, 0x0, x274, x271);
var x277: u32 = undefined;
var x278: u1 = undefined;
fiatP224AddcarryxU32(&x277, &x278, x276, x272, x269);
var x279: u32 = undefined;
var x280: u1 = undefined;
fiatP224AddcarryxU32(&x279, &x280, x278, x270, x267);
const x281: u32 = (@intCast(u32, x280) + x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
fiatP224AddcarryxU32(&x282, &x283, 0x0, x249, x265);
var x284: u32 = undefined;
var x285: u1 = undefined;
fiatP224AddcarryxU32(&x284, &x285, x283, x251, @intCast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
fiatP224AddcarryxU32(&x286, &x287, x285, x253, @intCast(u32, 0x0));
var x288: u32 = undefined;
var x289: u1 = undefined;
fiatP224AddcarryxU32(&x288, &x289, x287, x255, x273);
var x290: u32 = undefined;
var x291: u1 = undefined;
fiatP224AddcarryxU32(&x290, &x291, x289, x257, x275);
var x292: u32 = undefined;
var x293: u1 = undefined;
fiatP224AddcarryxU32(&x292, &x293, x291, x259, x277);
var x294: u32 = undefined;
var x295: u1 = undefined;
fiatP224AddcarryxU32(&x294, &x295, x293, x261, x279);
var x296: u32 = undefined;
var x297: u1 = undefined;
fiatP224AddcarryxU32(&x296, &x297, x295, x263, x281);
const x298: u32 = (@intCast(u32, x297) + @intCast(u32, x264));
var x299: u32 = undefined;
var x300: u32 = undefined;
fiatP224MulxU32(&x299, &x300, x4, (arg1[6]));
var x301: u32 = undefined;
var x302: u32 = undefined;
fiatP224MulxU32(&x301, &x302, x4, (arg1[5]));
var x303: u32 = undefined;
var x304: u32 = undefined;
fiatP224MulxU32(&x303, &x304, x4, (arg1[4]));
var x305: u32 = undefined;
var x306: u32 = undefined;
fiatP224MulxU32(&x305, &x306, x4, (arg1[3]));
var x307: u32 = undefined;
var x308: u32 = undefined;
fiatP224MulxU32(&x307, &x308, x4, (arg1[2]));
var x309: u32 = undefined;
var x310: u32 = undefined;
fiatP224MulxU32(&x309, &x310, x4, (arg1[1]));
var x311: u32 = undefined;
var x312: u32 = undefined;
fiatP224MulxU32(&x311, &x312, x4, (arg1[0]));
var x313: u32 = undefined;
var x314: u1 = undefined;
fiatP224AddcarryxU32(&x313, &x314, 0x0, x312, x309);
var x315: u32 = undefined;
var x316: u1 = undefined;
fiatP224AddcarryxU32(&x315, &x316, x314, x310, x307);
var x317: u32 = undefined;
var x318: u1 = undefined;
fiatP224AddcarryxU32(&x317, &x318, x316, x308, x305);
var x319: u32 = undefined;
var x320: u1 = undefined;
fiatP224AddcarryxU32(&x319, &x320, x318, x306, x303);
var x321: u32 = undefined;
var x322: u1 = undefined;
fiatP224AddcarryxU32(&x321, &x322, x320, x304, x301);
var x323: u32 = undefined;
var x324: u1 = undefined;
fiatP224AddcarryxU32(&x323, &x324, x322, x302, x299);
const x325: u32 = (@intCast(u32, x324) + x300);
var x326: u32 = undefined;
var x327: u1 = undefined;
fiatP224AddcarryxU32(&x326, &x327, 0x0, x284, x311);
var x328: u32 = undefined;
var x329: u1 = undefined;
fiatP224AddcarryxU32(&x328, &x329, x327, x286, x313);
var x330: u32 = undefined;
var x331: u1 = undefined;
fiatP224AddcarryxU32(&x330, &x331, x329, x288, x315);
var x332: u32 = undefined;
var x333: u1 = undefined;
fiatP224AddcarryxU32(&x332, &x333, x331, x290, x317);
var x334: u32 = undefined;
var x335: u1 = undefined;
fiatP224AddcarryxU32(&x334, &x335, x333, x292, x319);
var x336: u32 = undefined;
var x337: u1 = undefined;
fiatP224AddcarryxU32(&x336, &x337, x335, x294, x321);
var x338: u32 = undefined;
var x339: u1 = undefined;
fiatP224AddcarryxU32(&x338, &x339, x337, x296, x323);
var x340: u32 = undefined;
var x341: u1 = undefined;
fiatP224AddcarryxU32(&x340, &x341, x339, x298, x325);
var x342: u32 = undefined;
var x343: u32 = undefined;
fiatP224MulxU32(&x342, &x343, x326, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
fiatP224MulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
fiatP224MulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
fiatP224MulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
fiatP224MulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
fiatP224AddcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
fiatP224AddcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
fiatP224AddcarryxU32(&x356, &x357, x355, x347, x344);
const x358: u32 = (@intCast(u32, x357) + x345);
var x359: u32 = undefined;
var x360: u1 = undefined;
fiatP224AddcarryxU32(&x359, &x360, 0x0, x326, x342);
var x361: u32 = undefined;
var x362: u1 = undefined;
fiatP224AddcarryxU32(&x361, &x362, x360, x328, @intCast(u32, 0x0));
var x363: u32 = undefined;
var x364: u1 = undefined;
fiatP224AddcarryxU32(&x363, &x364, x362, x330, @intCast(u32, 0x0));
var x365: u32 = undefined;
var x366: u1 = undefined;
fiatP224AddcarryxU32(&x365, &x366, x364, x332, x350);
var x367: u32 = undefined;
var x368: u1 = undefined;
fiatP224AddcarryxU32(&x367, &x368, x366, x334, x352);
var x369: u32 = undefined;
var x370: u1 = undefined;
fiatP224AddcarryxU32(&x369, &x370, x368, x336, x354);
var x371: u32 = undefined;
var x372: u1 = undefined;
fiatP224AddcarryxU32(&x371, &x372, x370, x338, x356);
var x373: u32 = undefined;
var x374: u1 = undefined;
fiatP224AddcarryxU32(&x373, &x374, x372, x340, x358);
const x375: u32 = (@intCast(u32, x374) + @intCast(u32, x341));
var x376: u32 = undefined;
var x377: u32 = undefined;
fiatP224MulxU32(&x376, &x377, x5, (arg1[6]));
var x378: u32 = undefined;
var x379: u32 = undefined;
fiatP224MulxU32(&x378, &x379, x5, (arg1[5]));
var x380: u32 = undefined;
var x381: u32 = undefined;
fiatP224MulxU32(&x380, &x381, x5, (arg1[4]));
var x382: u32 = undefined;
var x383: u32 = undefined;
fiatP224MulxU32(&x382, &x383, x5, (arg1[3]));
var x384: u32 = undefined;
var x385: u32 = undefined;
fiatP224MulxU32(&x384, &x385, x5, (arg1[2]));
var x386: u32 = undefined;
var x387: u32 = undefined;
fiatP224MulxU32(&x386, &x387, x5, (arg1[1]));
var x388: u32 = undefined;
var x389: u32 = undefined;
fiatP224MulxU32(&x388, &x389, x5, (arg1[0]));
var x390: u32 = undefined;
var x391: u1 = undefined;
fiatP224AddcarryxU32(&x390, &x391, 0x0, x389, x386);
var x392: u32 = undefined;
var x393: u1 = undefined;
fiatP224AddcarryxU32(&x392, &x393, x391, x387, x384);
var x394: u32 = undefined;
var x395: u1 = undefined;
fiatP224AddcarryxU32(&x394, &x395, x393, x385, x382);
var x396: u32 = undefined;
var x397: u1 = undefined;
fiatP224AddcarryxU32(&x396, &x397, x395, x383, x380);
var x398: u32 = undefined;
var x399: u1 = undefined;
fiatP224AddcarryxU32(&x398, &x399, x397, x381, x378);
var x400: u32 = undefined;
var x401: u1 = undefined;
fiatP224AddcarryxU32(&x400, &x401, x399, x379, x376);
const x402: u32 = (@intCast(u32, x401) + x377);
var x403: u32 = undefined;
var x404: u1 = undefined;
fiatP224AddcarryxU32(&x403, &x404, 0x0, x361, x388);
var x405: u32 = undefined;
var x406: u1 = undefined;
fiatP224AddcarryxU32(&x405, &x406, x404, x363, x390);
var x407: u32 = undefined;
var x408: u1 = undefined;
fiatP224AddcarryxU32(&x407, &x408, x406, x365, x392);
var x409: u32 = undefined;
var x410: u1 = undefined;
fiatP224AddcarryxU32(&x409, &x410, x408, x367, x394);
var x411: u32 = undefined;
var x412: u1 = undefined;
fiatP224AddcarryxU32(&x411, &x412, x410, x369, x396);
var x413: u32 = undefined;
var x414: u1 = undefined;
fiatP224AddcarryxU32(&x413, &x414, x412, x371, x398);
var x415: u32 = undefined;
var x416: u1 = undefined;
fiatP224AddcarryxU32(&x415, &x416, x414, x373, x400);
var x417: u32 = undefined;
var x418: u1 = undefined;
fiatP224AddcarryxU32(&x417, &x418, x416, x375, x402);
var x419: u32 = undefined;
var x420: u32 = undefined;
fiatP224MulxU32(&x419, &x420, x403, 0xffffffff);
var x421: u32 = undefined;
var x422: u32 = undefined;
fiatP224MulxU32(&x421, &x422, x419, 0xffffffff);
var x423: u32 = undefined;
var x424: u32 = undefined;
fiatP224MulxU32(&x423, &x424, x419, 0xffffffff);
var x425: u32 = undefined;
var x426: u32 = undefined;
fiatP224MulxU32(&x425, &x426, x419, 0xffffffff);
var x427: u32 = undefined;
var x428: u32 = undefined;
fiatP224MulxU32(&x427, &x428, x419, 0xffffffff);
var x429: u32 = undefined;
var x430: u1 = undefined;
fiatP224AddcarryxU32(&x429, &x430, 0x0, x428, x425);
var x431: u32 = undefined;
var x432: u1 = undefined;
fiatP224AddcarryxU32(&x431, &x432, x430, x426, x423);
var x433: u32 = undefined;
var x434: u1 = undefined;
fiatP224AddcarryxU32(&x433, &x434, x432, x424, x421);
const x435: u32 = (@intCast(u32, x434) + x422);
var x436: u32 = undefined;
var x437: u1 = undefined;
fiatP224AddcarryxU32(&x436, &x437, 0x0, x403, x419);
var x438: u32 = undefined;
var x439: u1 = undefined;
fiatP224AddcarryxU32(&x438, &x439, x437, x405, @intCast(u32, 0x0));
var x440: u32 = undefined;
var x441: u1 = undefined;
fiatP224AddcarryxU32(&x440, &x441, x439, x407, @intCast(u32, 0x0));
var x442: u32 = undefined;
var x443: u1 = undefined;
fiatP224AddcarryxU32(&x442, &x443, x441, x409, x427);
var x444: u32 = undefined;
var x445: u1 = undefined;
fiatP224AddcarryxU32(&x444, &x445, x443, x411, x429);
var x446: u32 = undefined;
var x447: u1 = undefined;
fiatP224AddcarryxU32(&x446, &x447, x445, x413, x431);
var x448: u32 = undefined;
var x449: u1 = undefined;
fiatP224AddcarryxU32(&x448, &x449, x447, x415, x433);
var x450: u32 = undefined;
var x451: u1 = undefined;
fiatP224AddcarryxU32(&x450, &x451, x449, x417, x435);
const x452: u32 = (@intCast(u32, x451) + @intCast(u32, x418));
var x453: u32 = undefined;
var x454: u32 = undefined;
fiatP224MulxU32(&x453, &x454, x6, (arg1[6]));
var x455: u32 = undefined;
var x456: u32 = undefined;
fiatP224MulxU32(&x455, &x456, x6, (arg1[5]));
var x457: u32 = undefined;
var x458: u32 = undefined;
fiatP224MulxU32(&x457, &x458, x6, (arg1[4]));
var x459: u32 = undefined;
var x460: u32 = undefined;
fiatP224MulxU32(&x459, &x460, x6, (arg1[3]));
var x461: u32 = undefined;
var x462: u32 = undefined;
fiatP224MulxU32(&x461, &x462, x6, (arg1[2]));
var x463: u32 = undefined;
var x464: u32 = undefined;
fiatP224MulxU32(&x463, &x464, x6, (arg1[1]));
var x465: u32 = undefined;
var x466: u32 = undefined;
fiatP224MulxU32(&x465, &x466, x6, (arg1[0]));
var x467: u32 = undefined;
var x468: u1 = undefined;
fiatP224AddcarryxU32(&x467, &x468, 0x0, x466, x463);
var x469: u32 = undefined;
var x470: u1 = undefined;
fiatP224AddcarryxU32(&x469, &x470, x468, x464, x461);
var x471: u32 = undefined;
var x472: u1 = undefined;
fiatP224AddcarryxU32(&x471, &x472, x470, x462, x459);
var x473: u32 = undefined;
var x474: u1 = undefined;
fiatP224AddcarryxU32(&x473, &x474, x472, x460, x457);
var x475: u32 = undefined;
var x476: u1 = undefined;
fiatP224AddcarryxU32(&x475, &x476, x474, x458, x455);
var x477: u32 = undefined;
var x478: u1 = undefined;
fiatP224AddcarryxU32(&x477, &x478, x476, x456, x453);
const x479: u32 = (@intCast(u32, x478) + x454);
var x480: u32 = undefined;
var x481: u1 = undefined;
fiatP224AddcarryxU32(&x480, &x481, 0x0, x438, x465);
var x482: u32 = undefined;
var x483: u1 = undefined;
fiatP224AddcarryxU32(&x482, &x483, x481, x440, x467);
var x484: u32 = undefined;
var x485: u1 = undefined;
fiatP224AddcarryxU32(&x484, &x485, x483, x442, x469);
var x486: u32 = undefined;
var x487: u1 = undefined;
fiatP224AddcarryxU32(&x486, &x487, x485, x444, x471);
var x488: u32 = undefined;
var x489: u1 = undefined;
fiatP224AddcarryxU32(&x488, &x489, x487, x446, x473);
var x490: u32 = undefined;
var x491: u1 = undefined;
fiatP224AddcarryxU32(&x490, &x491, x489, x448, x475);
var x492: u32 = undefined;
var x493: u1 = undefined;
fiatP224AddcarryxU32(&x492, &x493, x491, x450, x477);
var x494: u32 = undefined;
var x495: u1 = undefined;
fiatP224AddcarryxU32(&x494, &x495, x493, x452, x479);
var x496: u32 = undefined;
var x497: u32 = undefined;
fiatP224MulxU32(&x496, &x497, x480, 0xffffffff);
var x498: u32 = undefined;
var x499: u32 = undefined;
fiatP224MulxU32(&x498, &x499, x496, 0xffffffff);
var x500: u32 = undefined;
var x501: u32 = undefined;
fiatP224MulxU32(&x500, &x501, x496, 0xffffffff);
var x502: u32 = undefined;
var x503: u32 = undefined;
fiatP224MulxU32(&x502, &x503, x496, 0xffffffff);
var x504: u32 = undefined;
var x505: u32 = undefined;
fiatP224MulxU32(&x504, &x505, x496, 0xffffffff);
var x506: u32 = undefined;
var x507: u1 = undefined;
fiatP224AddcarryxU32(&x506, &x507, 0x0, x505, x502);
var x508: u32 = undefined;
var x509: u1 = undefined;
fiatP224AddcarryxU32(&x508, &x509, x507, x503, x500);
var x510: u32 = undefined;
var x511: u1 = undefined;
fiatP224AddcarryxU32(&x510, &x511, x509, x501, x498);
const x512: u32 = (@intCast(u32, x511) + x499);
var x513: u32 = undefined;
var x514: u1 = undefined;
fiatP224AddcarryxU32(&x513, &x514, 0x0, x480, x496);
var x515: u32 = undefined;
var x516: u1 = undefined;
fiatP224AddcarryxU32(&x515, &x516, x514, x482, @intCast(u32, 0x0));
var x517: u32 = undefined;
var x518: u1 = undefined;
fiatP224AddcarryxU32(&x517, &x518, x516, x484, @intCast(u32, 0x0));
var x519: u32 = undefined;
var x520: u1 = undefined;
fiatP224AddcarryxU32(&x519, &x520, x518, x486, x504);
var x521: u32 = undefined;
var x522: u1 = undefined;
fiatP224AddcarryxU32(&x521, &x522, x520, x488, x506);
var x523: u32 = undefined;
var x524: u1 = undefined;
fiatP224AddcarryxU32(&x523, &x524, x522, x490, x508);
var x525: u32 = undefined;
var x526: u1 = undefined;
fiatP224AddcarryxU32(&x525, &x526, x524, x492, x510);
var x527: u32 = undefined;
var x528: u1 = undefined;
fiatP224AddcarryxU32(&x527, &x528, x526, x494, x512);
const x529: u32 = (@intCast(u32, x528) + @intCast(u32, x495));
var x530: u32 = undefined;
var x531: u1 = undefined;
fiatP224SubborrowxU32(&x530, &x531, 0x0, x515, @intCast(u32, 0x1));
var x532: u32 = undefined;
var x533: u1 = undefined;
fiatP224SubborrowxU32(&x532, &x533, x531, x517, @intCast(u32, 0x0));
var x534: u32 = undefined;
var x535: u1 = undefined;
fiatP224SubborrowxU32(&x534, &x535, x533, x519, @intCast(u32, 0x0));
var x536: u32 = undefined;
var x537: u1 = undefined;
fiatP224SubborrowxU32(&x536, &x537, x535, x521, 0xffffffff);
var x538: u32 = undefined;
var x539: u1 = undefined;
fiatP224SubborrowxU32(&x538, &x539, x537, x523, 0xffffffff);
var x540: u32 = undefined;
var x541: u1 = undefined;
fiatP224SubborrowxU32(&x540, &x541, x539, x525, 0xffffffff);
var x542: u32 = undefined;
var x543: u1 = undefined;
fiatP224SubborrowxU32(&x542, &x543, x541, x527, 0xffffffff);
var x544: u32 = undefined;
var x545: u1 = undefined;
fiatP224SubborrowxU32(&x544, &x545, x543, x529, @intCast(u32, 0x0));
var x546: u32 = undefined;
fiatP224CmovznzU32(&x546, x545, x530, x515);
var x547: u32 = undefined;
fiatP224CmovznzU32(&x547, x545, x532, x517);
var x548: u32 = undefined;
fiatP224CmovznzU32(&x548, x545, x534, x519);
var x549: u32 = undefined;
fiatP224CmovznzU32(&x549, x545, x536, x521);
var x550: u32 = undefined;
fiatP224CmovznzU32(&x550, x545, x538, x523);
var x551: u32 = undefined;
fiatP224CmovznzU32(&x551, x545, x540, x525);
var x552: u32 = undefined;
fiatP224CmovznzU32(&x552, x545, x542, x527);
out1[0] = x546;
out1[1] = x547;
out1[2] = x548;
out1[3] = x549;
out1[4] = x550;
out1[5] = x551;
out1[6] = x552;
}
/// The function fiatP224Add adds two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Add(out1: *[7]u32, arg1: [7]u32, arg2: [7]u32) void {
var x1: u32 = undefined;
var x2: u1 = undefined;
fiatP224AddcarryxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
fiatP224AddcarryxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
fiatP224AddcarryxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
fiatP224AddcarryxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
fiatP224AddcarryxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
fiatP224AddcarryxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
fiatP224AddcarryxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
var x16: u1 = undefined;
fiatP224SubborrowxU32(&x15, &x16, 0x0, x1, @intCast(u32, 0x1));
var x17: u32 = undefined;
var x18: u1 = undefined;
fiatP224SubborrowxU32(&x17, &x18, x16, x3, @intCast(u32, 0x0));
var x19: u32 = undefined;
var x20: u1 = undefined;
fiatP224SubborrowxU32(&x19, &x20, x18, x5, @intCast(u32, 0x0));
var x21: u32 = undefined;
var x22: u1 = undefined;
fiatP224SubborrowxU32(&x21, &x22, x20, x7, 0xffffffff);
var x23: u32 = undefined;
var x24: u1 = undefined;
fiatP224SubborrowxU32(&x23, &x24, x22, x9, 0xffffffff);
var x25: u32 = undefined;
var x26: u1 = undefined;
fiatP224SubborrowxU32(&x25, &x26, x24, x11, 0xffffffff);
var x27: u32 = undefined;
var x28: u1 = undefined;
fiatP224SubborrowxU32(&x27, &x28, x26, x13, 0xffffffff);
var x29: u32 = undefined;
var x30: u1 = undefined;
fiatP224SubborrowxU32(&x29, &x30, x28, @intCast(u32, x14), @intCast(u32, 0x0));
var x31: u32 = undefined;
fiatP224CmovznzU32(&x31, x30, x15, x1);
var x32: u32 = undefined;
fiatP224CmovznzU32(&x32, x30, x17, x3);
var x33: u32 = undefined;
fiatP224CmovznzU32(&x33, x30, x19, x5);
var x34: u32 = undefined;
fiatP224CmovznzU32(&x34, x30, x21, x7);
var x35: u32 = undefined;
fiatP224CmovznzU32(&x35, x30, x23, x9);
var x36: u32 = undefined;
fiatP224CmovznzU32(&x36, x30, x25, x11);
var x37: u32 = undefined;
fiatP224CmovznzU32(&x37, x30, x27, x13);
out1[0] = x31;
out1[1] = x32;
out1[2] = x33;
out1[3] = x34;
out1[4] = x35;
out1[5] = x36;
out1[6] = x37;
}
/// The function fiatP224Sub subtracts two field elements in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Sub(out1: *[7]u32, arg1: [7]u32, arg2: [7]u32) void {
var x1: u32 = undefined;
var x2: u1 = undefined;
fiatP224SubborrowxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
fiatP224SubborrowxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
fiatP224SubborrowxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
fiatP224SubborrowxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
fiatP224SubborrowxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
fiatP224SubborrowxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
fiatP224SubborrowxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
fiatP224CmovznzU32(&x15, x14, @intCast(u32, 0x0), 0xffffffff);
var x16: u32 = undefined;
var x17: u1 = undefined;
fiatP224AddcarryxU32(&x16, &x17, 0x0, x1, @intCast(u32, @intCast(u1, (x15 & @intCast(u32, 0x1)))));
var x18: u32 = undefined;
var x19: u1 = undefined;
fiatP224AddcarryxU32(&x18, &x19, x17, x3, @intCast(u32, 0x0));
var x20: u32 = undefined;
var x21: u1 = undefined;
fiatP224AddcarryxU32(&x20, &x21, x19, x5, @intCast(u32, 0x0));
var x22: u32 = undefined;
var x23: u1 = undefined;
fiatP224AddcarryxU32(&x22, &x23, x21, x7, x15);
var x24: u32 = undefined;
var x25: u1 = undefined;
fiatP224AddcarryxU32(&x24, &x25, x23, x9, x15);
var x26: u32 = undefined;
var x27: u1 = undefined;
fiatP224AddcarryxU32(&x26, &x27, x25, x11, x15);
var x28: u32 = undefined;
var x29: u1 = undefined;
fiatP224AddcarryxU32(&x28, &x29, x27, x13, x15);
out1[0] = x16;
out1[1] = x18;
out1[2] = x20;
out1[3] = x22;
out1[4] = x24;
out1[5] = x26;
out1[6] = x28;
}
/// The function fiatP224Opp negates a field element in the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Opp(out1: *[7]u32, arg1: [7]u32) void {
var x1: u32 = undefined;
var x2: u1 = undefined;
fiatP224SubborrowxU32(&x1, &x2, 0x0, @intCast(u32, 0x0), (arg1[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
fiatP224SubborrowxU32(&x3, &x4, x2, @intCast(u32, 0x0), (arg1[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
fiatP224SubborrowxU32(&x5, &x6, x4, @intCast(u32, 0x0), (arg1[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
fiatP224SubborrowxU32(&x7, &x8, x6, @intCast(u32, 0x0), (arg1[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
fiatP224SubborrowxU32(&x9, &x10, x8, @intCast(u32, 0x0), (arg1[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
fiatP224SubborrowxU32(&x11, &x12, x10, @intCast(u32, 0x0), (arg1[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
fiatP224SubborrowxU32(&x13, &x14, x12, @intCast(u32, 0x0), (arg1[6]));
var x15: u32 = undefined;
fiatP224CmovznzU32(&x15, x14, @intCast(u32, 0x0), 0xffffffff);
var x16: u32 = undefined;
var x17: u1 = undefined;
fiatP224AddcarryxU32(&x16, &x17, 0x0, x1, @intCast(u32, @intCast(u1, (x15 & @intCast(u32, 0x1)))));
var x18: u32 = undefined;
var x19: u1 = undefined;
fiatP224AddcarryxU32(&x18, &x19, x17, x3, @intCast(u32, 0x0));
var x20: u32 = undefined;
var x21: u1 = undefined;
fiatP224AddcarryxU32(&x20, &x21, x19, x5, @intCast(u32, 0x0));
var x22: u32 = undefined;
var x23: u1 = undefined;
fiatP224AddcarryxU32(&x22, &x23, x21, x7, x15);
var x24: u32 = undefined;
var x25: u1 = undefined;
fiatP224AddcarryxU32(&x24, &x25, x23, x9, x15);
var x26: u32 = undefined;
var x27: u1 = undefined;
fiatP224AddcarryxU32(&x26, &x27, x25, x11, x15);
var x28: u32 = undefined;
var x29: u1 = undefined;
fiatP224AddcarryxU32(&x28, &x29, x27, x13, x15);
out1[0] = x16;
out1[1] = x18;
out1[2] = x20;
out1[3] = x22;
out1[4] = x24;
out1[5] = x26;
out1[6] = x28;
}
/// The function fiatP224FromMontgomery translates a field element out of the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^7) mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224FromMontgomery(out1: *[7]u32, arg1: [7]u32) void {
const x1: u32 = (arg1[0]);
var x2: u32 = undefined;
var x3: u32 = undefined;
fiatP224MulxU32(&x2, &x3, x1, 0xffffffff);
var x4: u32 = undefined;
var x5: u32 = undefined;
fiatP224MulxU32(&x4, &x5, x2, 0xffffffff);
var x6: u32 = undefined;
var x7: u32 = undefined;
fiatP224MulxU32(&x6, &x7, x2, 0xffffffff);
var x8: u32 = undefined;
var x9: u32 = undefined;
fiatP224MulxU32(&x8, &x9, x2, 0xffffffff);
var x10: u32 = undefined;
var x11: u32 = undefined;
fiatP224MulxU32(&x10, &x11, x2, 0xffffffff);
var x12: u32 = undefined;
var x13: u1 = undefined;
fiatP224AddcarryxU32(&x12, &x13, 0x0, x11, x8);
var x14: u32 = undefined;
var x15: u1 = undefined;
fiatP224AddcarryxU32(&x14, &x15, x13, x9, x6);
var x16: u32 = undefined;
var x17: u1 = undefined;
fiatP224AddcarryxU32(&x16, &x17, x15, x7, x4);
var x18: u32 = undefined;
var x19: u1 = undefined;
fiatP224AddcarryxU32(&x18, &x19, 0x0, x1, x2);
var x20: u32 = undefined;
var x21: u1 = undefined;
fiatP224AddcarryxU32(&x20, &x21, 0x0, @intCast(u32, x19), (arg1[1]));
var x22: u32 = undefined;
var x23: u32 = undefined;
fiatP224MulxU32(&x22, &x23, x20, 0xffffffff);
var x24: u32 = undefined;
var x25: u32 = undefined;
fiatP224MulxU32(&x24, &x25, x22, 0xffffffff);
var x26: u32 = undefined;
var x27: u32 = undefined;
fiatP224MulxU32(&x26, &x27, x22, 0xffffffff);
var x28: u32 = undefined;
var x29: u32 = undefined;
fiatP224MulxU32(&x28, &x29, x22, 0xffffffff);
var x30: u32 = undefined;
var x31: u32 = undefined;
fiatP224MulxU32(&x30, &x31, x22, 0xffffffff);
var x32: u32 = undefined;
var x33: u1 = undefined;
fiatP224AddcarryxU32(&x32, &x33, 0x0, x31, x28);
var x34: u32 = undefined;
var x35: u1 = undefined;
fiatP224AddcarryxU32(&x34, &x35, x33, x29, x26);
var x36: u32 = undefined;
var x37: u1 = undefined;
fiatP224AddcarryxU32(&x36, &x37, x35, x27, x24);
var x38: u32 = undefined;
var x39: u1 = undefined;
fiatP224AddcarryxU32(&x38, &x39, 0x0, x12, x30);
var x40: u32 = undefined;
var x41: u1 = undefined;
fiatP224AddcarryxU32(&x40, &x41, x39, x14, x32);
var x42: u32 = undefined;
var x43: u1 = undefined;
fiatP224AddcarryxU32(&x42, &x43, x41, x16, x34);
var x44: u32 = undefined;
var x45: u1 = undefined;
fiatP224AddcarryxU32(&x44, &x45, x43, (@intCast(u32, x17) + x5), x36);
var x46: u32 = undefined;
var x47: u1 = undefined;
fiatP224AddcarryxU32(&x46, &x47, x45, @intCast(u32, 0x0), (@intCast(u32, x37) + x25));
var x48: u32 = undefined;
var x49: u1 = undefined;
fiatP224AddcarryxU32(&x48, &x49, 0x0, x20, x22);
var x50: u32 = undefined;
var x51: u1 = undefined;
fiatP224AddcarryxU32(&x50, &x51, 0x0, (@intCast(u32, x49) + @intCast(u32, x21)), (arg1[2]));
var x52: u32 = undefined;
var x53: u1 = undefined;
fiatP224AddcarryxU32(&x52, &x53, x51, x10, @intCast(u32, 0x0));
var x54: u32 = undefined;
var x55: u1 = undefined;
fiatP224AddcarryxU32(&x54, &x55, x53, x38, @intCast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
fiatP224AddcarryxU32(&x56, &x57, x55, x40, @intCast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
fiatP224AddcarryxU32(&x58, &x59, x57, x42, @intCast(u32, 0x0));
var x60: u32 = undefined;
var x61: u1 = undefined;
fiatP224AddcarryxU32(&x60, &x61, x59, x44, @intCast(u32, 0x0));
var x62: u32 = undefined;
var x63: u1 = undefined;
fiatP224AddcarryxU32(&x62, &x63, x61, x46, @intCast(u32, 0x0));
var x64: u32 = undefined;
var x65: u32 = undefined;
fiatP224MulxU32(&x64, &x65, x50, 0xffffffff);
var x66: u32 = undefined;
var x67: u32 = undefined;
fiatP224MulxU32(&x66, &x67, x64, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
fiatP224MulxU32(&x68, &x69, x64, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
fiatP224MulxU32(&x70, &x71, x64, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
fiatP224MulxU32(&x72, &x73, x64, 0xffffffff);
var x74: u32 = undefined;
var x75: u1 = undefined;
fiatP224AddcarryxU32(&x74, &x75, 0x0, x73, x70);
var x76: u32 = undefined;
var x77: u1 = undefined;
fiatP224AddcarryxU32(&x76, &x77, x75, x71, x68);
var x78: u32 = undefined;
var x79: u1 = undefined;
fiatP224AddcarryxU32(&x78, &x79, x77, x69, x66);
var x80: u32 = undefined;
var x81: u1 = undefined;
fiatP224AddcarryxU32(&x80, &x81, 0x0, x50, x64);
var x82: u32 = undefined;
var x83: u1 = undefined;
fiatP224AddcarryxU32(&x82, &x83, x81, x52, @intCast(u32, 0x0));
var x84: u32 = undefined;
var x85: u1 = undefined;
fiatP224AddcarryxU32(&x84, &x85, x83, x54, @intCast(u32, 0x0));
var x86: u32 = undefined;
var x87: u1 = undefined;
fiatP224AddcarryxU32(&x86, &x87, x85, x56, x72);
var x88: u32 = undefined;
var x89: u1 = undefined;
fiatP224AddcarryxU32(&x88, &x89, x87, x58, x74);
var x90: u32 = undefined;
var x91: u1 = undefined;
fiatP224AddcarryxU32(&x90, &x91, x89, x60, x76);
var x92: u32 = undefined;
var x93: u1 = undefined;
fiatP224AddcarryxU32(&x92, &x93, x91, x62, x78);
var x94: u32 = undefined;
var x95: u1 = undefined;
fiatP224AddcarryxU32(&x94, &x95, x93, (@intCast(u32, x63) + @intCast(u32, x47)), (@intCast(u32, x79) + x67));
var x96: u32 = undefined;
var x97: u1 = undefined;
fiatP224AddcarryxU32(&x96, &x97, 0x0, x82, (arg1[3]));
var x98: u32 = undefined;
var x99: u1 = undefined;
fiatP224AddcarryxU32(&x98, &x99, x97, x84, @intCast(u32, 0x0));
var x100: u32 = undefined;
var x101: u1 = undefined;
fiatP224AddcarryxU32(&x100, &x101, x99, x86, @intCast(u32, 0x0));
var x102: u32 = undefined;
var x103: u1 = undefined;
fiatP224AddcarryxU32(&x102, &x103, x101, x88, @intCast(u32, 0x0));
var x104: u32 = undefined;
var x105: u1 = undefined;
fiatP224AddcarryxU32(&x104, &x105, x103, x90, @intCast(u32, 0x0));
var x106: u32 = undefined;
var x107: u1 = undefined;
fiatP224AddcarryxU32(&x106, &x107, x105, x92, @intCast(u32, 0x0));
var x108: u32 = undefined;
var x109: u1 = undefined;
fiatP224AddcarryxU32(&x108, &x109, x107, x94, @intCast(u32, 0x0));
var x110: u32 = undefined;
var x111: u32 = undefined;
fiatP224MulxU32(&x110, &x111, x96, 0xffffffff);
var x112: u32 = undefined;
var x113: u32 = undefined;
fiatP224MulxU32(&x112, &x113, x110, 0xffffffff);
var x114: u32 = undefined;
var x115: u32 = undefined;
fiatP224MulxU32(&x114, &x115, x110, 0xffffffff);
var x116: u32 = undefined;
var x117: u32 = undefined;
fiatP224MulxU32(&x116, &x117, x110, 0xffffffff);
var x118: u32 = undefined;
var x119: u32 = undefined;
fiatP224MulxU32(&x118, &x119, x110, 0xffffffff);
var x120: u32 = undefined;
var x121: u1 = undefined;
fiatP224AddcarryxU32(&x120, &x121, 0x0, x119, x116);
var x122: u32 = undefined;
var x123: u1 = undefined;
fiatP224AddcarryxU32(&x122, &x123, x121, x117, x114);
var x124: u32 = undefined;
var x125: u1 = undefined;
fiatP224AddcarryxU32(&x124, &x125, x123, x115, x112);
var x126: u32 = undefined;
var x127: u1 = undefined;
fiatP224AddcarryxU32(&x126, &x127, 0x0, x96, x110);
var x128: u32 = undefined;
var x129: u1 = undefined;
fiatP224AddcarryxU32(&x128, &x129, x127, x98, @intCast(u32, 0x0));
var x130: u32 = undefined;
var x131: u1 = undefined;
fiatP224AddcarryxU32(&x130, &x131, x129, x100, @intCast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
fiatP224AddcarryxU32(&x132, &x133, x131, x102, x118);
var x134: u32 = undefined;
var x135: u1 = undefined;
fiatP224AddcarryxU32(&x134, &x135, x133, x104, x120);
var x136: u32 = undefined;
var x137: u1 = undefined;
fiatP224AddcarryxU32(&x136, &x137, x135, x106, x122);
var x138: u32 = undefined;
var x139: u1 = undefined;
fiatP224AddcarryxU32(&x138, &x139, x137, x108, x124);
var x140: u32 = undefined;
var x141: u1 = undefined;
fiatP224AddcarryxU32(&x140, &x141, x139, (@intCast(u32, x109) + @intCast(u32, x95)), (@intCast(u32, x125) + x113));
var x142: u32 = undefined;
var x143: u1 = undefined;
fiatP224AddcarryxU32(&x142, &x143, 0x0, x128, (arg1[4]));
var x144: u32 = undefined;
var x145: u1 = undefined;
fiatP224AddcarryxU32(&x144, &x145, x143, x130, @intCast(u32, 0x0));
var x146: u32 = undefined;
var x147: u1 = undefined;
fiatP224AddcarryxU32(&x146, &x147, x145, x132, @intCast(u32, 0x0));
var x148: u32 = undefined;
var x149: u1 = undefined;
fiatP224AddcarryxU32(&x148, &x149, x147, x134, @intCast(u32, 0x0));
var x150: u32 = undefined;
var x151: u1 = undefined;
fiatP224AddcarryxU32(&x150, &x151, x149, x136, @intCast(u32, 0x0));
var x152: u32 = undefined;
var x153: u1 = undefined;
fiatP224AddcarryxU32(&x152, &x153, x151, x138, @intCast(u32, 0x0));
var x154: u32 = undefined;
var x155: u1 = undefined;
fiatP224AddcarryxU32(&x154, &x155, x153, x140, @intCast(u32, 0x0));
var x156: u32 = undefined;
var x157: u32 = undefined;
fiatP224MulxU32(&x156, &x157, x142, 0xffffffff);
var x158: u32 = undefined;
var x159: u32 = undefined;
fiatP224MulxU32(&x158, &x159, x156, 0xffffffff);
var x160: u32 = undefined;
var x161: u32 = undefined;
fiatP224MulxU32(&x160, &x161, x156, 0xffffffff);
var x162: u32 = undefined;
var x163: u32 = undefined;
fiatP224MulxU32(&x162, &x163, x156, 0xffffffff);
var x164: u32 = undefined;
var x165: u32 = undefined;
fiatP224MulxU32(&x164, &x165, x156, 0xffffffff);
var x166: u32 = undefined;
var x167: u1 = undefined;
fiatP224AddcarryxU32(&x166, &x167, 0x0, x165, x162);
var x168: u32 = undefined;
var x169: u1 = undefined;
fiatP224AddcarryxU32(&x168, &x169, x167, x163, x160);
var x170: u32 = undefined;
var x171: u1 = undefined;
fiatP224AddcarryxU32(&x170, &x171, x169, x161, x158);
var x172: u32 = undefined;
var x173: u1 = undefined;
fiatP224AddcarryxU32(&x172, &x173, 0x0, x142, x156);
var x174: u32 = undefined;
var x175: u1 = undefined;
fiatP224AddcarryxU32(&x174, &x175, x173, x144, @intCast(u32, 0x0));
var x176: u32 = undefined;
var x177: u1 = undefined;
fiatP224AddcarryxU32(&x176, &x177, x175, x146, @intCast(u32, 0x0));
var x178: u32 = undefined;
var x179: u1 = undefined;
fiatP224AddcarryxU32(&x178, &x179, x177, x148, x164);
var x180: u32 = undefined;
var x181: u1 = undefined;
fiatP224AddcarryxU32(&x180, &x181, x179, x150, x166);
var x182: u32 = undefined;
var x183: u1 = undefined;
fiatP224AddcarryxU32(&x182, &x183, x181, x152, x168);
var x184: u32 = undefined;
var x185: u1 = undefined;
fiatP224AddcarryxU32(&x184, &x185, x183, x154, x170);
var x186: u32 = undefined;
var x187: u1 = undefined;
fiatP224AddcarryxU32(&x186, &x187, x185, (@intCast(u32, x155) + @intCast(u32, x141)), (@intCast(u32, x171) + x159));
var x188: u32 = undefined;
var x189: u1 = undefined;
fiatP224AddcarryxU32(&x188, &x189, 0x0, x174, (arg1[5]));
var x190: u32 = undefined;
var x191: u1 = undefined;
fiatP224AddcarryxU32(&x190, &x191, x189, x176, @intCast(u32, 0x0));
var x192: u32 = undefined;
var x193: u1 = undefined;
fiatP224AddcarryxU32(&x192, &x193, x191, x178, @intCast(u32, 0x0));
var x194: u32 = undefined;
var x195: u1 = undefined;
fiatP224AddcarryxU32(&x194, &x195, x193, x180, @intCast(u32, 0x0));
var x196: u32 = undefined;
var x197: u1 = undefined;
fiatP224AddcarryxU32(&x196, &x197, x195, x182, @intCast(u32, 0x0));
var x198: u32 = undefined;
var x199: u1 = undefined;
fiatP224AddcarryxU32(&x198, &x199, x197, x184, @intCast(u32, 0x0));
var x200: u32 = undefined;
var x201: u1 = undefined;
fiatP224AddcarryxU32(&x200, &x201, x199, x186, @intCast(u32, 0x0));
var x202: u32 = undefined;
var x203: u32 = undefined;
fiatP224MulxU32(&x202, &x203, x188, 0xffffffff);
var x204: u32 = undefined;
var x205: u32 = undefined;
fiatP224MulxU32(&x204, &x205, x202, 0xffffffff);
var x206: u32 = undefined;
var x207: u32 = undefined;
fiatP224MulxU32(&x206, &x207, x202, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
fiatP224MulxU32(&x208, &x209, x202, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
fiatP224MulxU32(&x210, &x211, x202, 0xffffffff);
var x212: u32 = undefined;
var x213: u1 = undefined;
fiatP224AddcarryxU32(&x212, &x213, 0x0, x211, x208);
var x214: u32 = undefined;
var x215: u1 = undefined;
fiatP224AddcarryxU32(&x214, &x215, x213, x209, x206);
var x216: u32 = undefined;
var x217: u1 = undefined;
fiatP224AddcarryxU32(&x216, &x217, x215, x207, x204);
var x218: u32 = undefined;
var x219: u1 = undefined;
fiatP224AddcarryxU32(&x218, &x219, 0x0, x188, x202);
var x220: u32 = undefined;
var x221: u1 = undefined;
fiatP224AddcarryxU32(&x220, &x221, x219, x190, @intCast(u32, 0x0));
var x222: u32 = undefined;
var x223: u1 = undefined;
fiatP224AddcarryxU32(&x222, &x223, x221, x192, @intCast(u32, 0x0));
var x224: u32 = undefined;
var x225: u1 = undefined;
fiatP224AddcarryxU32(&x224, &x225, x223, x194, x210);
var x226: u32 = undefined;
var x227: u1 = undefined;
fiatP224AddcarryxU32(&x226, &x227, x225, x196, x212);
var x228: u32 = undefined;
var x229: u1 = undefined;
fiatP224AddcarryxU32(&x228, &x229, x227, x198, x214);
var x230: u32 = undefined;
var x231: u1 = undefined;
fiatP224AddcarryxU32(&x230, &x231, x229, x200, x216);
var x232: u32 = undefined;
var x233: u1 = undefined;
fiatP224AddcarryxU32(&x232, &x233, x231, (@intCast(u32, x201) + @intCast(u32, x187)), (@intCast(u32, x217) + x205));
var x234: u32 = undefined;
var x235: u1 = undefined;
fiatP224AddcarryxU32(&x234, &x235, 0x0, x220, (arg1[6]));
var x236: u32 = undefined;
var x237: u1 = undefined;
fiatP224AddcarryxU32(&x236, &x237, x235, x222, @intCast(u32, 0x0));
var x238: u32 = undefined;
var x239: u1 = undefined;
fiatP224AddcarryxU32(&x238, &x239, x237, x224, @intCast(u32, 0x0));
var x240: u32 = undefined;
var x241: u1 = undefined;
fiatP224AddcarryxU32(&x240, &x241, x239, x226, @intCast(u32, 0x0));
var x242: u32 = undefined;
var x243: u1 = undefined;
fiatP224AddcarryxU32(&x242, &x243, x241, x228, @intCast(u32, 0x0));
var x244: u32 = undefined;
var x245: u1 = undefined;
fiatP224AddcarryxU32(&x244, &x245, x243, x230, @intCast(u32, 0x0));
var x246: u32 = undefined;
var x247: u1 = undefined;
fiatP224AddcarryxU32(&x246, &x247, x245, x232, @intCast(u32, 0x0));
var x248: u32 = undefined;
var x249: u32 = undefined;
fiatP224MulxU32(&x248, &x249, x234, 0xffffffff);
var x250: u32 = undefined;
var x251: u32 = undefined;
fiatP224MulxU32(&x250, &x251, x248, 0xffffffff);
var x252: u32 = undefined;
var x253: u32 = undefined;
fiatP224MulxU32(&x252, &x253, x248, 0xffffffff);
var x254: u32 = undefined;
var x255: u32 = undefined;
fiatP224MulxU32(&x254, &x255, x248, 0xffffffff);
var x256: u32 = undefined;
var x257: u32 = undefined;
fiatP224MulxU32(&x256, &x257, x248, 0xffffffff);
var x258: u32 = undefined;
var x259: u1 = undefined;
fiatP224AddcarryxU32(&x258, &x259, 0x0, x257, x254);
var x260: u32 = undefined;
var x261: u1 = undefined;
fiatP224AddcarryxU32(&x260, &x261, x259, x255, x252);
var x262: u32 = undefined;
var x263: u1 = undefined;
fiatP224AddcarryxU32(&x262, &x263, x261, x253, x250);
var x264: u32 = undefined;
var x265: u1 = undefined;
fiatP224AddcarryxU32(&x264, &x265, 0x0, x234, x248);
var x266: u32 = undefined;
var x267: u1 = undefined;
fiatP224AddcarryxU32(&x266, &x267, x265, x236, @intCast(u32, 0x0));
var x268: u32 = undefined;
var x269: u1 = undefined;
fiatP224AddcarryxU32(&x268, &x269, x267, x238, @intCast(u32, 0x0));
var x270: u32 = undefined;
var x271: u1 = undefined;
fiatP224AddcarryxU32(&x270, &x271, x269, x240, x256);
var x272: u32 = undefined;
var x273: u1 = undefined;
fiatP224AddcarryxU32(&x272, &x273, x271, x242, x258);
var x274: u32 = undefined;
var x275: u1 = undefined;
fiatP224AddcarryxU32(&x274, &x275, x273, x244, x260);
var x276: u32 = undefined;
var x277: u1 = undefined;
fiatP224AddcarryxU32(&x276, &x277, x275, x246, x262);
var x278: u32 = undefined;
var x279: u1 = undefined;
fiatP224AddcarryxU32(&x278, &x279, x277, (@intCast(u32, x247) + @intCast(u32, x233)), (@intCast(u32, x263) + x251));
var x280: u32 = undefined;
var x281: u1 = undefined;
fiatP224SubborrowxU32(&x280, &x281, 0x0, x266, @intCast(u32, 0x1));
var x282: u32 = undefined;
var x283: u1 = undefined;
fiatP224SubborrowxU32(&x282, &x283, x281, x268, @intCast(u32, 0x0));
var x284: u32 = undefined;
var x285: u1 = undefined;
fiatP224SubborrowxU32(&x284, &x285, x283, x270, @intCast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
fiatP224SubborrowxU32(&x286, &x287, x285, x272, 0xffffffff);
var x288: u32 = undefined;
var x289: u1 = undefined;
fiatP224SubborrowxU32(&x288, &x289, x287, x274, 0xffffffff);
var x290: u32 = undefined;
var x291: u1 = undefined;
fiatP224SubborrowxU32(&x290, &x291, x289, x276, 0xffffffff);
var x292: u32 = undefined;
var x293: u1 = undefined;
fiatP224SubborrowxU32(&x292, &x293, x291, x278, 0xffffffff);
var x294: u32 = undefined;
var x295: u1 = undefined;
fiatP224SubborrowxU32(&x294, &x295, x293, @intCast(u32, x279), @intCast(u32, 0x0));
var x296: u32 = undefined;
fiatP224CmovznzU32(&x296, x295, x280, x266);
var x297: u32 = undefined;
fiatP224CmovznzU32(&x297, x295, x282, x268);
var x298: u32 = undefined;
fiatP224CmovznzU32(&x298, x295, x284, x270);
var x299: u32 = undefined;
fiatP224CmovznzU32(&x299, x295, x286, x272);
var x300: u32 = undefined;
fiatP224CmovznzU32(&x300, x295, x288, x274);
var x301: u32 = undefined;
fiatP224CmovznzU32(&x301, x295, x290, x276);
var x302: u32 = undefined;
fiatP224CmovznzU32(&x302, x295, x292, x278);
out1[0] = x296;
out1[1] = x297;
out1[2] = x298;
out1[3] = x299;
out1[4] = x300;
out1[5] = x301;
out1[6] = x302;
}
/// The function fiatP224ToMontgomery translates a field element into the Montgomery domain.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224ToMontgomery(out1: *[7]u32, arg1: [7]u32) void {
const x1: u32 = (arg1[1]);
const x2: u32 = (arg1[2]);
const x3: u32 = (arg1[3]);
const x4: u32 = (arg1[4]);
const x5: u32 = (arg1[5]);
const x6: u32 = (arg1[6]);
const x7: u32 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
fiatP224MulxU32(&x8, &x9, x7, 0xffffffff);
var x10: u32 = undefined;
var x11: u32 = undefined;
fiatP224MulxU32(&x10, &x11, x7, 0xffffffff);
var x12: u32 = undefined;
var x13: u32 = undefined;
fiatP224MulxU32(&x12, &x13, x7, 0xfffffffe);
var x14: u32 = undefined;
var x15: u1 = undefined;
fiatP224AddcarryxU32(&x14, &x15, 0x0, x13, x10);
var x16: u32 = undefined;
var x17: u1 = undefined;
fiatP224AddcarryxU32(&x16, &x17, x15, x11, x8);
var x18: u32 = undefined;
var x19: u32 = undefined;
fiatP224MulxU32(&x18, &x19, x7, 0xffffffff);
var x20: u32 = undefined;
var x21: u32 = undefined;
fiatP224MulxU32(&x20, &x21, x18, 0xffffffff);
var x22: u32 = undefined;
var x23: u32 = undefined;
fiatP224MulxU32(&x22, &x23, x18, 0xffffffff);
var x24: u32 = undefined;
var x25: u32 = undefined;
fiatP224MulxU32(&x24, &x25, x18, 0xffffffff);
var x26: u32 = undefined;
var x27: u32 = undefined;
fiatP224MulxU32(&x26, &x27, x18, 0xffffffff);
var x28: u32 = undefined;
var x29: u1 = undefined;
fiatP224AddcarryxU32(&x28, &x29, 0x0, x27, x24);
var x30: u32 = undefined;
var x31: u1 = undefined;
fiatP224AddcarryxU32(&x30, &x31, x29, x25, x22);
var x32: u32 = undefined;
var x33: u1 = undefined;
fiatP224AddcarryxU32(&x32, &x33, x31, x23, x20);
var x34: u32 = undefined;
var x35: u1 = undefined;
fiatP224AddcarryxU32(&x34, &x35, 0x0, x12, x26);
var x36: u32 = undefined;
var x37: u1 = undefined;
fiatP224AddcarryxU32(&x36, &x37, x35, x14, x28);
var x38: u32 = undefined;
var x39: u1 = undefined;
fiatP224AddcarryxU32(&x38, &x39, x37, x16, x30);
var x40: u32 = undefined;
var x41: u1 = undefined;
fiatP224AddcarryxU32(&x40, &x41, x39, (@intCast(u32, x17) + x9), x32);
var x42: u32 = undefined;
var x43: u1 = undefined;
fiatP224AddcarryxU32(&x42, &x43, x41, @intCast(u32, 0x0), (@intCast(u32, x33) + x21));
var x44: u32 = undefined;
var x45: u32 = undefined;
fiatP224MulxU32(&x44, &x45, x1, 0xffffffff);
var x46: u32 = undefined;
var x47: u32 = undefined;
fiatP224MulxU32(&x46, &x47, x1, 0xffffffff);
var x48: u32 = undefined;
var x49: u32 = undefined;
fiatP224MulxU32(&x48, &x49, x1, 0xfffffffe);
var x50: u32 = undefined;
var x51: u1 = undefined;
fiatP224AddcarryxU32(&x50, &x51, 0x0, x49, x46);
var x52: u32 = undefined;
var x53: u1 = undefined;
fiatP224AddcarryxU32(&x52, &x53, x51, x47, x44);
var x54: u32 = undefined;
var x55: u1 = undefined;
fiatP224AddcarryxU32(&x54, &x55, 0x0, x7, x18);
var x56: u32 = undefined;
var x57: u1 = undefined;
fiatP224AddcarryxU32(&x56, &x57, 0x0, @intCast(u32, x55), x1);
var x58: u32 = undefined;
var x59: u1 = undefined;
fiatP224AddcarryxU32(&x58, &x59, 0x0, x36, x48);
var x60: u32 = undefined;
var x61: u1 = undefined;
fiatP224AddcarryxU32(&x60, &x61, x59, x38, x50);
var x62: u32 = undefined;
var x63: u1 = undefined;
fiatP224AddcarryxU32(&x62, &x63, x61, x40, x52);
var x64: u32 = undefined;
var x65: u1 = undefined;
fiatP224AddcarryxU32(&x64, &x65, x63, x42, (@intCast(u32, x53) + x45));
var x66: u32 = undefined;
var x67: u32 = undefined;
fiatP224MulxU32(&x66, &x67, x56, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
fiatP224MulxU32(&x68, &x69, x66, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
fiatP224MulxU32(&x70, &x71, x66, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
fiatP224MulxU32(&x72, &x73, x66, 0xffffffff);
var x74: u32 = undefined;
var x75: u32 = undefined;
fiatP224MulxU32(&x74, &x75, x66, 0xffffffff);
var x76: u32 = undefined;
var x77: u1 = undefined;
fiatP224AddcarryxU32(&x76, &x77, 0x0, x75, x72);
var x78: u32 = undefined;
var x79: u1 = undefined;
fiatP224AddcarryxU32(&x78, &x79, x77, x73, x70);
var x80: u32 = undefined;
var x81: u1 = undefined;
fiatP224AddcarryxU32(&x80, &x81, x79, x71, x68);
var x82: u32 = undefined;
var x83: u1 = undefined;
fiatP224AddcarryxU32(&x82, &x83, 0x0, x58, x74);
var x84: u32 = undefined;
var x85: u1 = undefined;
fiatP224AddcarryxU32(&x84, &x85, x83, x60, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
fiatP224AddcarryxU32(&x86, &x87, x85, x62, x78);
var x88: u32 = undefined;
var x89: u1 = undefined;
fiatP224AddcarryxU32(&x88, &x89, x87, x64, x80);
var x90: u32 = undefined;
var x91: u1 = undefined;
fiatP224AddcarryxU32(&x90, &x91, x89, (@intCast(u32, x65) + @intCast(u32, x43)), (@intCast(u32, x81) + x69));
var x92: u32 = undefined;
var x93: u32 = undefined;
fiatP224MulxU32(&x92, &x93, x2, 0xffffffff);
var x94: u32 = undefined;
var x95: u32 = undefined;
fiatP224MulxU32(&x94, &x95, x2, 0xffffffff);
var x96: u32 = undefined;
var x97: u32 = undefined;
fiatP224MulxU32(&x96, &x97, x2, 0xfffffffe);
var x98: u32 = undefined;
var x99: u1 = undefined;
fiatP224AddcarryxU32(&x98, &x99, 0x0, x97, x94);
var x100: u32 = undefined;
var x101: u1 = undefined;
fiatP224AddcarryxU32(&x100, &x101, x99, x95, x92);
var x102: u32 = undefined;
var x103: u1 = undefined;
fiatP224AddcarryxU32(&x102, &x103, 0x0, x56, x66);
var x104: u32 = undefined;
var x105: u1 = undefined;
fiatP224AddcarryxU32(&x104, &x105, 0x0, (@intCast(u32, x103) + @intCast(u32, x57)), x2);
var x106: u32 = undefined;
var x107: u1 = undefined;
fiatP224AddcarryxU32(&x106, &x107, x105, x34, @intCast(u32, 0x0));
var x108: u32 = undefined;
var x109: u1 = undefined;
fiatP224AddcarryxU32(&x108, &x109, x107, x82, @intCast(u32, 0x0));
var x110: u32 = undefined;
var x111: u1 = undefined;
fiatP224AddcarryxU32(&x110, &x111, x109, x84, x96);
var x112: u32 = undefined;
var x113: u1 = undefined;
fiatP224AddcarryxU32(&x112, &x113, x111, x86, x98);
var x114: u32 = undefined;
var x115: u1 = undefined;
fiatP224AddcarryxU32(&x114, &x115, x113, x88, x100);
var x116: u32 = undefined;
var x117: u1 = undefined;
fiatP224AddcarryxU32(&x116, &x117, x115, x90, (@intCast(u32, x101) + x93));
var x118: u32 = undefined;
var x119: u32 = undefined;
fiatP224MulxU32(&x118, &x119, x104, 0xffffffff);
var x120: u32 = undefined;
var x121: u32 = undefined;
fiatP224MulxU32(&x120, &x121, x118, 0xffffffff);
var x122: u32 = undefined;
var x123: u32 = undefined;
fiatP224MulxU32(&x122, &x123, x118, 0xffffffff);
var x124: u32 = undefined;
var x125: u32 = undefined;
fiatP224MulxU32(&x124, &x125, x118, 0xffffffff);
var x126: u32 = undefined;
var x127: u32 = undefined;
fiatP224MulxU32(&x126, &x127, x118, 0xffffffff);
var x128: u32 = undefined;
var x129: u1 = undefined;
fiatP224AddcarryxU32(&x128, &x129, 0x0, x127, x124);
var x130: u32 = undefined;
var x131: u1 = undefined;
fiatP224AddcarryxU32(&x130, &x131, x129, x125, x122);
var x132: u32 = undefined;
var x133: u1 = undefined;
fiatP224AddcarryxU32(&x132, &x133, x131, x123, x120);
var x134: u32 = undefined;
var x135: u1 = undefined;
fiatP224AddcarryxU32(&x134, &x135, 0x0, x104, x118);
var x136: u32 = undefined;
var x137: u1 = undefined;
fiatP224AddcarryxU32(&x136, &x137, x135, x106, @intCast(u32, 0x0));
var x138: u32 = undefined;
var x139: u1 = undefined;
fiatP224AddcarryxU32(&x138, &x139, x137, x108, @intCast(u32, 0x0));
var x140: u32 = undefined;
var x141: u1 = undefined;
fiatP224AddcarryxU32(&x140, &x141, x139, x110, x126);
var x142: u32 = undefined;
var x143: u1 = undefined;
fiatP224AddcarryxU32(&x142, &x143, x141, x112, x128);
var x144: u32 = undefined;
var x145: u1 = undefined;
fiatP224AddcarryxU32(&x144, &x145, x143, x114, x130);
var x146: u32 = undefined;
var x147: u1 = undefined;
fiatP224AddcarryxU32(&x146, &x147, x145, x116, x132);
var x148: u32 = undefined;
var x149: u1 = undefined;
fiatP224AddcarryxU32(&x148, &x149, x147, (@intCast(u32, x117) + @intCast(u32, x91)), (@intCast(u32, x133) + x121));
var x150: u32 = undefined;
var x151: u32 = undefined;
fiatP224MulxU32(&x150, &x151, x3, 0xffffffff);
var x152: u32 = undefined;
var x153: u32 = undefined;
fiatP224MulxU32(&x152, &x153, x3, 0xffffffff);
var x154: u32 = undefined;
var x155: u32 = undefined;
fiatP224MulxU32(&x154, &x155, x3, 0xfffffffe);
var x156: u32 = undefined;
var x157: u1 = undefined;
fiatP224AddcarryxU32(&x156, &x157, 0x0, x155, x152);
var x158: u32 = undefined;
var x159: u1 = undefined;
fiatP224AddcarryxU32(&x158, &x159, x157, x153, x150);
var x160: u32 = undefined;
var x161: u1 = undefined;
fiatP224AddcarryxU32(&x160, &x161, 0x0, x136, x3);
var x162: u32 = undefined;
var x163: u1 = undefined;
fiatP224AddcarryxU32(&x162, &x163, x161, x138, @intCast(u32, 0x0));
var x164: u32 = undefined;
var x165: u1 = undefined;
fiatP224AddcarryxU32(&x164, &x165, x163, x140, @intCast(u32, 0x0));
var x166: u32 = undefined;
var x167: u1 = undefined;
fiatP224AddcarryxU32(&x166, &x167, x165, x142, x154);
var x168: u32 = undefined;
var x169: u1 = undefined;
fiatP224AddcarryxU32(&x168, &x169, x167, x144, x156);
var x170: u32 = undefined;
var x171: u1 = undefined;
fiatP224AddcarryxU32(&x170, &x171, x169, x146, x158);
var x172: u32 = undefined;
var x173: u1 = undefined;
fiatP224AddcarryxU32(&x172, &x173, x171, x148, (@intCast(u32, x159) + x151));
var x174: u32 = undefined;
var x175: u32 = undefined;
fiatP224MulxU32(&x174, &x175, x160, 0xffffffff);
var x176: u32 = undefined;
var x177: u32 = undefined;
fiatP224MulxU32(&x176, &x177, x174, 0xffffffff);
var x178: u32 = undefined;
var x179: u32 = undefined;
fiatP224MulxU32(&x178, &x179, x174, 0xffffffff);
var x180: u32 = undefined;
var x181: u32 = undefined;
fiatP224MulxU32(&x180, &x181, x174, 0xffffffff);
var x182: u32 = undefined;
var x183: u32 = undefined;
fiatP224MulxU32(&x182, &x183, x174, 0xffffffff);
var x184: u32 = undefined;
var x185: u1 = undefined;
fiatP224AddcarryxU32(&x184, &x185, 0x0, x183, x180);
var x186: u32 = undefined;
var x187: u1 = undefined;
fiatP224AddcarryxU32(&x186, &x187, x185, x181, x178);
var x188: u32 = undefined;
var x189: u1 = undefined;
fiatP224AddcarryxU32(&x188, &x189, x187, x179, x176);
var x190: u32 = undefined;
var x191: u1 = undefined;
fiatP224AddcarryxU32(&x190, &x191, 0x0, x160, x174);
var x192: u32 = undefined;
var x193: u1 = undefined;
fiatP224AddcarryxU32(&x192, &x193, x191, x162, @intCast(u32, 0x0));
var x194: u32 = undefined;
var x195: u1 = undefined;
fiatP224AddcarryxU32(&x194, &x195, x193, x164, @intCast(u32, 0x0));
var x196: u32 = undefined;
var x197: u1 = undefined;
fiatP224AddcarryxU32(&x196, &x197, x195, x166, x182);
var x198: u32 = undefined;
var x199: u1 = undefined;
fiatP224AddcarryxU32(&x198, &x199, x197, x168, x184);
var x200: u32 = undefined;
var x201: u1 = undefined;
fiatP224AddcarryxU32(&x200, &x201, x199, x170, x186);
var x202: u32 = undefined;
var x203: u1 = undefined;
fiatP224AddcarryxU32(&x202, &x203, x201, x172, x188);
var x204: u32 = undefined;
var x205: u1 = undefined;
fiatP224AddcarryxU32(&x204, &x205, x203, (@intCast(u32, x173) + @intCast(u32, x149)), (@intCast(u32, x189) + x177));
var x206: u32 = undefined;
var x207: u32 = undefined;
fiatP224MulxU32(&x206, &x207, x4, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
fiatP224MulxU32(&x208, &x209, x4, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
fiatP224MulxU32(&x210, &x211, x4, 0xfffffffe);
var x212: u32 = undefined;
var x213: u1 = undefined;
fiatP224AddcarryxU32(&x212, &x213, 0x0, x211, x208);
var x214: u32 = undefined;
var x215: u1 = undefined;
fiatP224AddcarryxU32(&x214, &x215, x213, x209, x206);
var x216: u32 = undefined;
var x217: u1 = undefined;
fiatP224AddcarryxU32(&x216, &x217, 0x0, x192, x4);
var x218: u32 = undefined;
var x219: u1 = undefined;
fiatP224AddcarryxU32(&x218, &x219, x217, x194, @intCast(u32, 0x0));
var x220: u32 = undefined;
var x221: u1 = undefined;
fiatP224AddcarryxU32(&x220, &x221, x219, x196, @intCast(u32, 0x0));
var x222: u32 = undefined;
var x223: u1 = undefined;
fiatP224AddcarryxU32(&x222, &x223, x221, x198, x210);
var x224: u32 = undefined;
var x225: u1 = undefined;
fiatP224AddcarryxU32(&x224, &x225, x223, x200, x212);
var x226: u32 = undefined;
var x227: u1 = undefined;
fiatP224AddcarryxU32(&x226, &x227, x225, x202, x214);
var x228: u32 = undefined;
var x229: u1 = undefined;
fiatP224AddcarryxU32(&x228, &x229, x227, x204, (@intCast(u32, x215) + x207));
var x230: u32 = undefined;
var x231: u32 = undefined;
fiatP224MulxU32(&x230, &x231, x216, 0xffffffff);
var x232: u32 = undefined;
var x233: u32 = undefined;
fiatP224MulxU32(&x232, &x233, x230, 0xffffffff);
var x234: u32 = undefined;
var x235: u32 = undefined;
fiatP224MulxU32(&x234, &x235, x230, 0xffffffff);
var x236: u32 = undefined;
var x237: u32 = undefined;
fiatP224MulxU32(&x236, &x237, x230, 0xffffffff);
var x238: u32 = undefined;
var x239: u32 = undefined;
fiatP224MulxU32(&x238, &x239, x230, 0xffffffff);
var x240: u32 = undefined;
var x241: u1 = undefined;
fiatP224AddcarryxU32(&x240, &x241, 0x0, x239, x236);
var x242: u32 = undefined;
var x243: u1 = undefined;
fiatP224AddcarryxU32(&x242, &x243, x241, x237, x234);
var x244: u32 = undefined;
var x245: u1 = undefined;
fiatP224AddcarryxU32(&x244, &x245, x243, x235, x232);
var x246: u32 = undefined;
var x247: u1 = undefined;
fiatP224AddcarryxU32(&x246, &x247, 0x0, x216, x230);
var x248: u32 = undefined;
var x249: u1 = undefined;
fiatP224AddcarryxU32(&x248, &x249, x247, x218, @intCast(u32, 0x0));
var x250: u32 = undefined;
var x251: u1 = undefined;
fiatP224AddcarryxU32(&x250, &x251, x249, x220, @intCast(u32, 0x0));
var x252: u32 = undefined;
var x253: u1 = undefined;
fiatP224AddcarryxU32(&x252, &x253, x251, x222, x238);
var x254: u32 = undefined;
var x255: u1 = undefined;
fiatP224AddcarryxU32(&x254, &x255, x253, x224, x240);
var x256: u32 = undefined;
var x257: u1 = undefined;
fiatP224AddcarryxU32(&x256, &x257, x255, x226, x242);
var x258: u32 = undefined;
var x259: u1 = undefined;
fiatP224AddcarryxU32(&x258, &x259, x257, x228, x244);
var x260: u32 = undefined;
var x261: u1 = undefined;
fiatP224AddcarryxU32(&x260, &x261, x259, (@intCast(u32, x229) + @intCast(u32, x205)), (@intCast(u32, x245) + x233));
var x262: u32 = undefined;
var x263: u32 = undefined;
fiatP224MulxU32(&x262, &x263, x5, 0xffffffff);
var x264: u32 = undefined;
var x265: u32 = undefined;
fiatP224MulxU32(&x264, &x265, x5, 0xffffffff);
var x266: u32 = undefined;
var x267: u32 = undefined;
fiatP224MulxU32(&x266, &x267, x5, 0xfffffffe);
var x268: u32 = undefined;
var x269: u1 = undefined;
fiatP224AddcarryxU32(&x268, &x269, 0x0, x267, x264);
var x270: u32 = undefined;
var x271: u1 = undefined;
fiatP224AddcarryxU32(&x270, &x271, x269, x265, x262);
var x272: u32 = undefined;
var x273: u1 = undefined;
fiatP224AddcarryxU32(&x272, &x273, 0x0, x248, x5);
var x274: u32 = undefined;
var x275: u1 = undefined;
fiatP224AddcarryxU32(&x274, &x275, x273, x250, @intCast(u32, 0x0));
var x276: u32 = undefined;
var x277: u1 = undefined;
fiatP224AddcarryxU32(&x276, &x277, x275, x252, @intCast(u32, 0x0));
var x278: u32 = undefined;
var x279: u1 = undefined;
fiatP224AddcarryxU32(&x278, &x279, x277, x254, x266);
var x280: u32 = undefined;
var x281: u1 = undefined;
fiatP224AddcarryxU32(&x280, &x281, x279, x256, x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
fiatP224AddcarryxU32(&x282, &x283, x281, x258, x270);
var x284: u32 = undefined;
var x285: u1 = undefined;
fiatP224AddcarryxU32(&x284, &x285, x283, x260, (@intCast(u32, x271) + x263));
var x286: u32 = undefined;
var x287: u32 = undefined;
fiatP224MulxU32(&x286, &x287, x272, 0xffffffff);
var x288: u32 = undefined;
var x289: u32 = undefined;
fiatP224MulxU32(&x288, &x289, x286, 0xffffffff);
var x290: u32 = undefined;
var x291: u32 = undefined;
fiatP224MulxU32(&x290, &x291, x286, 0xffffffff);
var x292: u32 = undefined;
var x293: u32 = undefined;
fiatP224MulxU32(&x292, &x293, x286, 0xffffffff);
var x294: u32 = undefined;
var x295: u32 = undefined;
fiatP224MulxU32(&x294, &x295, x286, 0xffffffff);
var x296: u32 = undefined;
var x297: u1 = undefined;
fiatP224AddcarryxU32(&x296, &x297, 0x0, x295, x292);
var x298: u32 = undefined;
var x299: u1 = undefined;
fiatP224AddcarryxU32(&x298, &x299, x297, x293, x290);
var x300: u32 = undefined;
var x301: u1 = undefined;
fiatP224AddcarryxU32(&x300, &x301, x299, x291, x288);
var x302: u32 = undefined;
var x303: u1 = undefined;
fiatP224AddcarryxU32(&x302, &x303, 0x0, x272, x286);
var x304: u32 = undefined;
var x305: u1 = undefined;
fiatP224AddcarryxU32(&x304, &x305, x303, x274, @intCast(u32, 0x0));
var x306: u32 = undefined;
var x307: u1 = undefined;
fiatP224AddcarryxU32(&x306, &x307, x305, x276, @intCast(u32, 0x0));
var x308: u32 = undefined;
var x309: u1 = undefined;
fiatP224AddcarryxU32(&x308, &x309, x307, x278, x294);
var x310: u32 = undefined;
var x311: u1 = undefined;
fiatP224AddcarryxU32(&x310, &x311, x309, x280, x296);
var x312: u32 = undefined;
var x313: u1 = undefined;
fiatP224AddcarryxU32(&x312, &x313, x311, x282, x298);
var x314: u32 = undefined;
var x315: u1 = undefined;
fiatP224AddcarryxU32(&x314, &x315, x313, x284, x300);
var x316: u32 = undefined;
var x317: u1 = undefined;
fiatP224AddcarryxU32(&x316, &x317, x315, (@intCast(u32, x285) + @intCast(u32, x261)), (@intCast(u32, x301) + x289));
var x318: u32 = undefined;
var x319: u32 = undefined;
fiatP224MulxU32(&x318, &x319, x6, 0xffffffff);
var x320: u32 = undefined;
var x321: u32 = undefined;
fiatP224MulxU32(&x320, &x321, x6, 0xffffffff);
var x322: u32 = undefined;
var x323: u32 = undefined;
fiatP224MulxU32(&x322, &x323, x6, 0xfffffffe);
var x324: u32 = undefined;
var x325: u1 = undefined;
fiatP224AddcarryxU32(&x324, &x325, 0x0, x323, x320);
var x326: u32 = undefined;
var x327: u1 = undefined;
fiatP224AddcarryxU32(&x326, &x327, x325, x321, x318);
var x328: u32 = undefined;
var x329: u1 = undefined;
fiatP224AddcarryxU32(&x328, &x329, 0x0, x304, x6);
var x330: u32 = undefined;
var x331: u1 = undefined;
fiatP224AddcarryxU32(&x330, &x331, x329, x306, @intCast(u32, 0x0));
var x332: u32 = undefined;
var x333: u1 = undefined;
fiatP224AddcarryxU32(&x332, &x333, x331, x308, @intCast(u32, 0x0));
var x334: u32 = undefined;
var x335: u1 = undefined;
fiatP224AddcarryxU32(&x334, &x335, x333, x310, x322);
var x336: u32 = undefined;
var x337: u1 = undefined;
fiatP224AddcarryxU32(&x336, &x337, x335, x312, x324);
var x338: u32 = undefined;
var x339: u1 = undefined;
fiatP224AddcarryxU32(&x338, &x339, x337, x314, x326);
var x340: u32 = undefined;
var x341: u1 = undefined;
fiatP224AddcarryxU32(&x340, &x341, x339, x316, (@intCast(u32, x327) + x319));
var x342: u32 = undefined;
var x343: u32 = undefined;
fiatP224MulxU32(&x342, &x343, x328, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
fiatP224MulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
fiatP224MulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
fiatP224MulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
fiatP224MulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
fiatP224AddcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
fiatP224AddcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
fiatP224AddcarryxU32(&x356, &x357, x355, x347, x344);
var x358: u32 = undefined;
var x359: u1 = undefined;
fiatP224AddcarryxU32(&x358, &x359, 0x0, x328, x342);
var x360: u32 = undefined;
var x361: u1 = undefined;
fiatP224AddcarryxU32(&x360, &x361, x359, x330, @intCast(u32, 0x0));
var x362: u32 = undefined;
var x363: u1 = undefined;
fiatP224AddcarryxU32(&x362, &x363, x361, x332, @intCast(u32, 0x0));
var x364: u32 = undefined;
var x365: u1 = undefined;
fiatP224AddcarryxU32(&x364, &x365, x363, x334, x350);
var x366: u32 = undefined;
var x367: u1 = undefined;
fiatP224AddcarryxU32(&x366, &x367, x365, x336, x352);
var x368: u32 = undefined;
var x369: u1 = undefined;
fiatP224AddcarryxU32(&x368, &x369, x367, x338, x354);
var x370: u32 = undefined;
var x371: u1 = undefined;
fiatP224AddcarryxU32(&x370, &x371, x369, x340, x356);
var x372: u32 = undefined;
var x373: u1 = undefined;
fiatP224AddcarryxU32(&x372, &x373, x371, (@intCast(u32, x341) + @intCast(u32, x317)), (@intCast(u32, x357) + x345));
var x374: u32 = undefined;
var x375: u1 = undefined;
fiatP224SubborrowxU32(&x374, &x375, 0x0, x360, @intCast(u32, 0x1));
var x376: u32 = undefined;
var x377: u1 = undefined;
fiatP224SubborrowxU32(&x376, &x377, x375, x362, @intCast(u32, 0x0));
var x378: u32 = undefined;
var x379: u1 = undefined;
fiatP224SubborrowxU32(&x378, &x379, x377, x364, @intCast(u32, 0x0));
var x380: u32 = undefined;
var x381: u1 = undefined;
fiatP224SubborrowxU32(&x380, &x381, x379, x366, 0xffffffff);
var x382: u32 = undefined;
var x383: u1 = undefined;
fiatP224SubborrowxU32(&x382, &x383, x381, x368, 0xffffffff);
var x384: u32 = undefined;
var x385: u1 = undefined;
fiatP224SubborrowxU32(&x384, &x385, x383, x370, 0xffffffff);
var x386: u32 = undefined;
var x387: u1 = undefined;
fiatP224SubborrowxU32(&x386, &x387, x385, x372, 0xffffffff);
var x388: u32 = undefined;
var x389: u1 = undefined;
fiatP224SubborrowxU32(&x388, &x389, x387, @intCast(u32, x373), @intCast(u32, 0x0));
var x390: u32 = undefined;
fiatP224CmovznzU32(&x390, x389, x374, x360);
var x391: u32 = undefined;
fiatP224CmovznzU32(&x391, x389, x376, x362);
var x392: u32 = undefined;
fiatP224CmovznzU32(&x392, x389, x378, x364);
var x393: u32 = undefined;
fiatP224CmovznzU32(&x393, x389, x380, x366);
var x394: u32 = undefined;
fiatP224CmovznzU32(&x394, x389, x382, x368);
var x395: u32 = undefined;
fiatP224CmovznzU32(&x395, x389, x384, x370);
var x396: u32 = undefined;
fiatP224CmovznzU32(&x396, x389, x386, x372);
out1[0] = x390;
out1[1] = x391;
out1[2] = x392;
out1[3] = x393;
out1[4] = x394;
out1[5] = x395;
out1[6] = x396;
}
/// The function fiatP224Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
pub fn fiatP224Nonzero(out1: *u32, arg1: [7]u32) void {
const x1: u32 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | (arg1[6])))))));
out1.* = x1;
}
/// The function fiatP224Selectznz is a multi-limb conditional select.
/// Postconditions:
/// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Selectznz(out1: *[7]u32, arg1: u1, arg2: [7]u32, arg3: [7]u32) void {
var x1: u32 = undefined;
fiatP224CmovznzU32(&x1, arg1, (arg2[0]), (arg3[0]));
var x2: u32 = undefined;
fiatP224CmovznzU32(&x2, arg1, (arg2[1]), (arg3[1]));
var x3: u32 = undefined;
fiatP224CmovznzU32(&x3, arg1, (arg2[2]), (arg3[2]));
var x4: u32 = undefined;
fiatP224CmovznzU32(&x4, arg1, (arg2[3]), (arg3[3]));
var x5: u32 = undefined;
fiatP224CmovznzU32(&x5, arg1, (arg2[4]), (arg3[4]));
var x6: u32 = undefined;
fiatP224CmovznzU32(&x6, arg1, (arg2[5]), (arg3[5]));
var x7: u32 = undefined;
fiatP224CmovznzU32(&x7, arg1, (arg2[6]), (arg3[6]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
}
/// The function fiatP224ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order.
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..27]
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
pub fn fiatP224ToBytes(out1: *[28]u8, arg1: [7]u32) void {
const x1: u32 = (arg1[6]);
const x2: u32 = (arg1[5]);
const x3: u32 = (arg1[4]);
const x4: u32 = (arg1[3]);
const x5: u32 = (arg1[2]);
const x6: u32 = (arg1[1]);
const x7: u32 = (arg1[0]);
const x8: u8 = @intCast(u8, (x7 & @intCast(u32, 0xff)));
const x9: u32 = (x7 >> 8);
const x10: u8 = @intCast(u8, (x9 & @intCast(u32, 0xff)));
const x11: u32 = (x9 >> 8);
const x12: u8 = @intCast(u8, (x11 & @intCast(u32, 0xff)));
const x13: u8 = @intCast(u8, (x11 >> 8));
const x14: u8 = @intCast(u8, (x6 & @intCast(u32, 0xff)));
const x15: u32 = (x6 >> 8);
const x16: u8 = @intCast(u8, (x15 & @intCast(u32, 0xff)));
const x17: u32 = (x15 >> 8);
const x18: u8 = @intCast(u8, (x17 & @intCast(u32, 0xff)));
const x19: u8 = @intCast(u8, (x17 >> 8));
const x20: u8 = @intCast(u8, (x5 & @intCast(u32, 0xff)));
const x21: u32 = (x5 >> 8);
const x22: u8 = @intCast(u8, (x21 & @intCast(u32, 0xff)));
const x23: u32 = (x21 >> 8);
const x24: u8 = @intCast(u8, (x23 & @intCast(u32, 0xff)));
const x25: u8 = @intCast(u8, (x23 >> 8));
const x26: u8 = @intCast(u8, (x4 & @intCast(u32, 0xff)));
const x27: u32 = (x4 >> 8);
const x28: u8 = @intCast(u8, (x27 & @intCast(u32, 0xff)));
const x29: u32 = (x27 >> 8);
const x30: u8 = @intCast(u8, (x29 & @intCast(u32, 0xff)));
const x31: u8 = @intCast(u8, (x29 >> 8));
const x32: u8 = @intCast(u8, (x3 & @intCast(u32, 0xff)));
const x33: u32 = (x3 >> 8);
const x34: u8 = @intCast(u8, (x33 & @intCast(u32, 0xff)));
const x35: u32 = (x33 >> 8);
const x36: u8 = @intCast(u8, (x35 & @intCast(u32, 0xff)));
const x37: u8 = @intCast(u8, (x35 >> 8));
const x38: u8 = @intCast(u8, (x2 & @intCast(u32, 0xff)));
const x39: u32 = (x2 >> 8);
const x40: u8 = @intCast(u8, (x39 & @intCast(u32, 0xff)));
const x41: u32 = (x39 >> 8);
const x42: u8 = @intCast(u8, (x41 & @intCast(u32, 0xff)));
const x43: u8 = @intCast(u8, (x41 >> 8));
const x44: u8 = @intCast(u8, (x1 & @intCast(u32, 0xff)));
const x45: u32 = (x1 >> 8);
const x46: u8 = @intCast(u8, (x45 & @intCast(u32, 0xff)));
const x47: u32 = (x45 >> 8);
const x48: u8 = @intCast(u8, (x47 & @intCast(u32, 0xff)));
const x49: u8 = @intCast(u8, (x47 >> 8));
out1[0] = x8;
out1[1] = x10;
out1[2] = x12;
out1[3] = x13;
out1[4] = x14;
out1[5] = x16;
out1[6] = x18;
out1[7] = x19;
out1[8] = x20;
out1[9] = x22;
out1[10] = x24;
out1[11] = x25;
out1[12] = x26;
out1[13] = x28;
out1[14] = x30;
out1[15] = x31;
out1[16] = x32;
out1[17] = x34;
out1[18] = x36;
out1[19] = x37;
out1[20] = x38;
out1[21] = x40;
out1[22] = x42;
out1[23] = x43;
out1[24] = x44;
out1[25] = x46;
out1[26] = x48;
out1[27] = x49;
}
/// The function fiatP224FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order.
/// Preconditions:
/// 0 ≤ bytes_eval arg1 < m
/// Postconditions:
/// eval out1 mod m = bytes_eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224FromBytes(out1: *[7]u32, arg1: [28]u8) void {
const x1: u32 = (@intCast(u32, (arg1[27])) << 24);
const x2: u32 = (@intCast(u32, (arg1[26])) << 16);
const x3: u32 = (@intCast(u32, (arg1[25])) << 8);
const x4: u8 = (arg1[24]);
const x5: u32 = (@intCast(u32, (arg1[23])) << 24);
const x6: u32 = (@intCast(u32, (arg1[22])) << 16);
const x7: u32 = (@intCast(u32, (arg1[21])) << 8);
const x8: u8 = (arg1[20]);
const x9: u32 = (@intCast(u32, (arg1[19])) << 24);
const x10: u32 = (@intCast(u32, (arg1[18])) << 16);
const x11: u32 = (@intCast(u32, (arg1[17])) << 8);
const x12: u8 = (arg1[16]);
const x13: u32 = (@intCast(u32, (arg1[15])) << 24);
const x14: u32 = (@intCast(u32, (arg1[14])) << 16);
const x15: u32 = (@intCast(u32, (arg1[13])) << 8);
const x16: u8 = (arg1[12]);
const x17: u32 = (@intCast(u32, (arg1[11])) << 24);
const x18: u32 = (@intCast(u32, (arg1[10])) << 16);
const x19: u32 = (@intCast(u32, (arg1[9])) << 8);
const x20: u8 = (arg1[8]);
const x21: u32 = (@intCast(u32, (arg1[7])) << 24);
const x22: u32 = (@intCast(u32, (arg1[6])) << 16);
const x23: u32 = (@intCast(u32, (arg1[5])) << 8);
const x24: u8 = (arg1[4]);
const x25: u32 = (@intCast(u32, (arg1[3])) << 24);
const x26: u32 = (@intCast(u32, (arg1[2])) << 16);
const x27: u32 = (@intCast(u32, (arg1[1])) << 8);
const x28: u8 = (arg1[0]);
const x29: u32 = (x27 + @intCast(u32, x28));
const x30: u32 = (x26 + x29);
const x31: u32 = (x25 + x30);
const x32: u32 = (x23 + @intCast(u32, x24));
const x33: u32 = (x22 + x32);
const x34: u32 = (x21 + x33);
const x35: u32 = (x19 + @intCast(u32, x20));
const x36: u32 = (x18 + x35);
const x37: u32 = (x17 + x36);
const x38: u32 = (x15 + @intCast(u32, x16));
const x39: u32 = (x14 + x38);
const x40: u32 = (x13 + x39);
const x41: u32 = (x11 + @intCast(u32, x12));
const x42: u32 = (x10 + x41);
const x43: u32 = (x9 + x42);
const x44: u32 = (x7 + @intCast(u32, x8));
const x45: u32 = (x6 + x44);
const x46: u32 = (x5 + x45);
const x47: u32 = (x3 + @intCast(u32, x4));
const x48: u32 = (x2 + x47);
const x49: u32 = (x1 + x48);
out1[0] = x31;
out1[1] = x34;
out1[2] = x37;
out1[3] = x40;
out1[4] = x43;
out1[5] = x46;
out1[6] = x49;
}
/// The function fiatP224SetOne returns the field element one in the Montgomery domain.
/// Postconditions:
/// eval (from_montgomery out1) mod m = 1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224SetOne(out1: *[7]u32) void {
out1[0] = 0xffffffff;
out1[1] = 0xffffffff;
out1[2] = 0xffffffff;
out1[3] = @intCast(u32, 0x0);
out1[4] = @intCast(u32, 0x0);
out1[5] = @intCast(u32, 0x0);
out1[6] = @intCast(u32, 0x0);
}
/// The function fiatP224Msat returns the saturated representation of the prime modulus.
/// Postconditions:
/// twos_complement_eval out1 = m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Msat(out1: *[8]u32) void {
out1[0] = @intCast(u32, 0x1);
out1[1] = @intCast(u32, 0x0);
out1[2] = @intCast(u32, 0x0);
out1[3] = 0xffffffff;
out1[4] = 0xffffffff;
out1[5] = 0xffffffff;
out1[6] = 0xffffffff;
out1[7] = @intCast(u32, 0x0);
}
/// The function fiatP224Divstep computes a divstep.
/// Preconditions:
/// 0 ≤ eval arg4 < m
/// 0 ≤ eval arg5 < m
/// Postconditions:
/// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1)
/// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2)
/// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋)
/// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m)
/// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m)
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out2 < m
/// 0 ≤ eval out3 < m
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224Divstep(out1: *u32, out2: *[8]u32, out3: *[8]u32, out4: *[7]u32, out5: *[7]u32, arg1: u32, arg2: [8]u32, arg3: [8]u32, arg4: [7]u32, arg5: [7]u32) void {
var x1: u32 = undefined;
var x2: u1 = undefined;
fiatP224AddcarryxU32(&x1, &x2, 0x0, (~arg1), @intCast(u32, 0x1));
const x3: u1 = (@intCast(u1, (x1 >> 31)) & @intCast(u1, ((arg3[0]) & @intCast(u32, 0x1))));
var x4: u32 = undefined;
var x5: u1 = undefined;
fiatP224AddcarryxU32(&x4, &x5, 0x0, (~arg1), @intCast(u32, 0x1));
var x6: u32 = undefined;
fiatP224CmovznzU32(&x6, x3, arg1, x4);
var x7: u32 = undefined;
fiatP224CmovznzU32(&x7, x3, (arg2[0]), (arg3[0]));
var x8: u32 = undefined;
fiatP224CmovznzU32(&x8, x3, (arg2[1]), (arg3[1]));
var x9: u32 = undefined;
fiatP224CmovznzU32(&x9, x3, (arg2[2]), (arg3[2]));
var x10: u32 = undefined;
fiatP224CmovznzU32(&x10, x3, (arg2[3]), (arg3[3]));
var x11: u32 = undefined;
fiatP224CmovznzU32(&x11, x3, (arg2[4]), (arg3[4]));
var x12: u32 = undefined;
fiatP224CmovznzU32(&x12, x3, (arg2[5]), (arg3[5]));
var x13: u32 = undefined;
fiatP224CmovznzU32(&x13, x3, (arg2[6]), (arg3[6]));
var x14: u32 = undefined;
fiatP224CmovznzU32(&x14, x3, (arg2[7]), (arg3[7]));
var x15: u32 = undefined;
var x16: u1 = undefined;
fiatP224AddcarryxU32(&x15, &x16, 0x0, @intCast(u32, 0x1), (~(arg2[0])));
var x17: u32 = undefined;
var x18: u1 = undefined;
fiatP224AddcarryxU32(&x17, &x18, x16, @intCast(u32, 0x0), (~(arg2[1])));
var x19: u32 = undefined;
var x20: u1 = undefined;
fiatP224AddcarryxU32(&x19, &x20, x18, @intCast(u32, 0x0), (~(arg2[2])));
var x21: u32 = undefined;
var x22: u1 = undefined;
fiatP224AddcarryxU32(&x21, &x22, x20, @intCast(u32, 0x0), (~(arg2[3])));
var x23: u32 = undefined;
var x24: u1 = undefined;
fiatP224AddcarryxU32(&x23, &x24, x22, @intCast(u32, 0x0), (~(arg2[4])));
var x25: u32 = undefined;
var x26: u1 = undefined;
fiatP224AddcarryxU32(&x25, &x26, x24, @intCast(u32, 0x0), (~(arg2[5])));
var x27: u32 = undefined;
var x28: u1 = undefined;
fiatP224AddcarryxU32(&x27, &x28, x26, @intCast(u32, 0x0), (~(arg2[6])));
var x29: u32 = undefined;
var x30: u1 = undefined;
fiatP224AddcarryxU32(&x29, &x30, x28, @intCast(u32, 0x0), (~(arg2[7])));
var x31: u32 = undefined;
fiatP224CmovznzU32(&x31, x3, (arg3[0]), x15);
var x32: u32 = undefined;
fiatP224CmovznzU32(&x32, x3, (arg3[1]), x17);
var x33: u32 = undefined;
fiatP224CmovznzU32(&x33, x3, (arg3[2]), x19);
var x34: u32 = undefined;
fiatP224CmovznzU32(&x34, x3, (arg3[3]), x21);
var x35: u32 = undefined;
fiatP224CmovznzU32(&x35, x3, (arg3[4]), x23);
var x36: u32 = undefined;
fiatP224CmovznzU32(&x36, x3, (arg3[5]), x25);
var x37: u32 = undefined;
fiatP224CmovznzU32(&x37, x3, (arg3[6]), x27);
var x38: u32 = undefined;
fiatP224CmovznzU32(&x38, x3, (arg3[7]), x29);
var x39: u32 = undefined;
fiatP224CmovznzU32(&x39, x3, (arg4[0]), (arg5[0]));
var x40: u32 = undefined;
fiatP224CmovznzU32(&x40, x3, (arg4[1]), (arg5[1]));
var x41: u32 = undefined;
fiatP224CmovznzU32(&x41, x3, (arg4[2]), (arg5[2]));
var x42: u32 = undefined;
fiatP224CmovznzU32(&x42, x3, (arg4[3]), (arg5[3]));
var x43: u32 = undefined;
fiatP224CmovznzU32(&x43, x3, (arg4[4]), (arg5[4]));
var x44: u32 = undefined;
fiatP224CmovznzU32(&x44, x3, (arg4[5]), (arg5[5]));
var x45: u32 = undefined;
fiatP224CmovznzU32(&x45, x3, (arg4[6]), (arg5[6]));
var x46: u32 = undefined;
var x47: u1 = undefined;
fiatP224AddcarryxU32(&x46, &x47, 0x0, x39, x39);
var x48: u32 = undefined;
var x49: u1 = undefined;
fiatP224AddcarryxU32(&x48, &x49, x47, x40, x40);
var x50: u32 = undefined;
var x51: u1 = undefined;
fiatP224AddcarryxU32(&x50, &x51, x49, x41, x41);
var x52: u32 = undefined;
var x53: u1 = undefined;
fiatP224AddcarryxU32(&x52, &x53, x51, x42, x42);
var x54: u32 = undefined;
var x55: u1 = undefined;
fiatP224AddcarryxU32(&x54, &x55, x53, x43, x43);
var x56: u32 = undefined;
var x57: u1 = undefined;
fiatP224AddcarryxU32(&x56, &x57, x55, x44, x44);
var x58: u32 = undefined;
var x59: u1 = undefined;
fiatP224AddcarryxU32(&x58, &x59, x57, x45, x45);
var x60: u32 = undefined;
var x61: u1 = undefined;
fiatP224SubborrowxU32(&x60, &x61, 0x0, x46, @intCast(u32, 0x1));
var x62: u32 = undefined;
var x63: u1 = undefined;
fiatP224SubborrowxU32(&x62, &x63, x61, x48, @intCast(u32, 0x0));
var x64: u32 = undefined;
var x65: u1 = undefined;
fiatP224SubborrowxU32(&x64, &x65, x63, x50, @intCast(u32, 0x0));
var x66: u32 = undefined;
var x67: u1 = undefined;
fiatP224SubborrowxU32(&x66, &x67, x65, x52, 0xffffffff);
var x68: u32 = undefined;
var x69: u1 = undefined;
fiatP224SubborrowxU32(&x68, &x69, x67, x54, 0xffffffff);
var x70: u32 = undefined;
var x71: u1 = undefined;
fiatP224SubborrowxU32(&x70, &x71, x69, x56, 0xffffffff);
var x72: u32 = undefined;
var x73: u1 = undefined;
fiatP224SubborrowxU32(&x72, &x73, x71, x58, 0xffffffff);
var x74: u32 = undefined;
var x75: u1 = undefined;
fiatP224SubborrowxU32(&x74, &x75, x73, @intCast(u32, x59), @intCast(u32, 0x0));
const x76: u32 = (arg4[6]);
const x77: u32 = (arg4[5]);
const x78: u32 = (arg4[4]);
const x79: u32 = (arg4[3]);
const x80: u32 = (arg4[2]);
const x81: u32 = (arg4[1]);
const x82: u32 = (arg4[0]);
var x83: u32 = undefined;
var x84: u1 = undefined;
fiatP224SubborrowxU32(&x83, &x84, 0x0, @intCast(u32, 0x0), x82);
var x85: u32 = undefined;
var x86: u1 = undefined;
fiatP224SubborrowxU32(&x85, &x86, x84, @intCast(u32, 0x0), x81);
var x87: u32 = undefined;
var x88: u1 = undefined;
fiatP224SubborrowxU32(&x87, &x88, x86, @intCast(u32, 0x0), x80);
var x89: u32 = undefined;
var x90: u1 = undefined;
fiatP224SubborrowxU32(&x89, &x90, x88, @intCast(u32, 0x0), x79);
var x91: u32 = undefined;
var x92: u1 = undefined;
fiatP224SubborrowxU32(&x91, &x92, x90, @intCast(u32, 0x0), x78);
var x93: u32 = undefined;
var x94: u1 = undefined;
fiatP224SubborrowxU32(&x93, &x94, x92, @intCast(u32, 0x0), x77);
var x95: u32 = undefined;
var x96: u1 = undefined;
fiatP224SubborrowxU32(&x95, &x96, x94, @intCast(u32, 0x0), x76);
var x97: u32 = undefined;
fiatP224CmovznzU32(&x97, x96, @intCast(u32, 0x0), 0xffffffff);
var x98: u32 = undefined;
var x99: u1 = undefined;
fiatP224AddcarryxU32(&x98, &x99, 0x0, x83, @intCast(u32, @intCast(u1, (x97 & @intCast(u32, 0x1)))));
var x100: u32 = undefined;
var x101: u1 = undefined;
fiatP224AddcarryxU32(&x100, &x101, x99, x85, @intCast(u32, 0x0));
var x102: u32 = undefined;
var x103: u1 = undefined;
fiatP224AddcarryxU32(&x102, &x103, x101, x87, @intCast(u32, 0x0));
var x104: u32 = undefined;
var x105: u1 = undefined;
fiatP224AddcarryxU32(&x104, &x105, x103, x89, x97);
var x106: u32 = undefined;
var x107: u1 = undefined;
fiatP224AddcarryxU32(&x106, &x107, x105, x91, x97);
var x108: u32 = undefined;
var x109: u1 = undefined;
fiatP224AddcarryxU32(&x108, &x109, x107, x93, x97);
var x110: u32 = undefined;
var x111: u1 = undefined;
fiatP224AddcarryxU32(&x110, &x111, x109, x95, x97);
var x112: u32 = undefined;
fiatP224CmovznzU32(&x112, x3, (arg5[0]), x98);
var x113: u32 = undefined;
fiatP224CmovznzU32(&x113, x3, (arg5[1]), x100);
var x114: u32 = undefined;
fiatP224CmovznzU32(&x114, x3, (arg5[2]), x102);
var x115: u32 = undefined;
fiatP224CmovznzU32(&x115, x3, (arg5[3]), x104);
var x116: u32 = undefined;
fiatP224CmovznzU32(&x116, x3, (arg5[4]), x106);
var x117: u32 = undefined;
fiatP224CmovznzU32(&x117, x3, (arg5[5]), x108);
var x118: u32 = undefined;
fiatP224CmovznzU32(&x118, x3, (arg5[6]), x110);
const x119: u1 = @intCast(u1, (x31 & @intCast(u32, 0x1)));
var x120: u32 = undefined;
fiatP224CmovznzU32(&x120, x119, @intCast(u32, 0x0), x7);
var x121: u32 = undefined;
fiatP224CmovznzU32(&x121, x119, @intCast(u32, 0x0), x8);
var x122: u32 = undefined;
fiatP224CmovznzU32(&x122, x119, @intCast(u32, 0x0), x9);
var x123: u32 = undefined;
fiatP224CmovznzU32(&x123, x119, @intCast(u32, 0x0), x10);
var x124: u32 = undefined;
fiatP224CmovznzU32(&x124, x119, @intCast(u32, 0x0), x11);
var x125: u32 = undefined;
fiatP224CmovznzU32(&x125, x119, @intCast(u32, 0x0), x12);
var x126: u32 = undefined;
fiatP224CmovznzU32(&x126, x119, @intCast(u32, 0x0), x13);
var x127: u32 = undefined;
fiatP224CmovznzU32(&x127, x119, @intCast(u32, 0x0), x14);
var x128: u32 = undefined;
var x129: u1 = undefined;
fiatP224AddcarryxU32(&x128, &x129, 0x0, x31, x120);
var x130: u32 = undefined;
var x131: u1 = undefined;
fiatP224AddcarryxU32(&x130, &x131, x129, x32, x121);
var x132: u32 = undefined;
var x133: u1 = undefined;
fiatP224AddcarryxU32(&x132, &x133, x131, x33, x122);
var x134: u32 = undefined;
var x135: u1 = undefined;
fiatP224AddcarryxU32(&x134, &x135, x133, x34, x123);
var x136: u32 = undefined;
var x137: u1 = undefined;
fiatP224AddcarryxU32(&x136, &x137, x135, x35, x124);
var x138: u32 = undefined;
var x139: u1 = undefined;
fiatP224AddcarryxU32(&x138, &x139, x137, x36, x125);
var x140: u32 = undefined;
var x141: u1 = undefined;
fiatP224AddcarryxU32(&x140, &x141, x139, x37, x126);
var x142: u32 = undefined;
var x143: u1 = undefined;
fiatP224AddcarryxU32(&x142, &x143, x141, x38, x127);
var x144: u32 = undefined;
fiatP224CmovznzU32(&x144, x119, @intCast(u32, 0x0), x39);
var x145: u32 = undefined;
fiatP224CmovznzU32(&x145, x119, @intCast(u32, 0x0), x40);
var x146: u32 = undefined;
fiatP224CmovznzU32(&x146, x119, @intCast(u32, 0x0), x41);
var x147: u32 = undefined;
fiatP224CmovznzU32(&x147, x119, @intCast(u32, 0x0), x42);
var x148: u32 = undefined;
fiatP224CmovznzU32(&x148, x119, @intCast(u32, 0x0), x43);
var x149: u32 = undefined;
fiatP224CmovznzU32(&x149, x119, @intCast(u32, 0x0), x44);
var x150: u32 = undefined;
fiatP224CmovznzU32(&x150, x119, @intCast(u32, 0x0), x45);
var x151: u32 = undefined;
var x152: u1 = undefined;
fiatP224AddcarryxU32(&x151, &x152, 0x0, x112, x144);
var x153: u32 = undefined;
var x154: u1 = undefined;
fiatP224AddcarryxU32(&x153, &x154, x152, x113, x145);
var x155: u32 = undefined;
var x156: u1 = undefined;
fiatP224AddcarryxU32(&x155, &x156, x154, x114, x146);
var x157: u32 = undefined;
var x158: u1 = undefined;
fiatP224AddcarryxU32(&x157, &x158, x156, x115, x147);
var x159: u32 = undefined;
var x160: u1 = undefined;
fiatP224AddcarryxU32(&x159, &x160, x158, x116, x148);
var x161: u32 = undefined;
var x162: u1 = undefined;
fiatP224AddcarryxU32(&x161, &x162, x160, x117, x149);
var x163: u32 = undefined;
var x164: u1 = undefined;
fiatP224AddcarryxU32(&x163, &x164, x162, x118, x150);
var x165: u32 = undefined;
var x166: u1 = undefined;
fiatP224SubborrowxU32(&x165, &x166, 0x0, x151, @intCast(u32, 0x1));
var x167: u32 = undefined;
var x168: u1 = undefined;
fiatP224SubborrowxU32(&x167, &x168, x166, x153, @intCast(u32, 0x0));
var x169: u32 = undefined;
var x170: u1 = undefined;
fiatP224SubborrowxU32(&x169, &x170, x168, x155, @intCast(u32, 0x0));
var x171: u32 = undefined;
var x172: u1 = undefined;
fiatP224SubborrowxU32(&x171, &x172, x170, x157, 0xffffffff);
var x173: u32 = undefined;
var x174: u1 = undefined;
fiatP224SubborrowxU32(&x173, &x174, x172, x159, 0xffffffff);
var x175: u32 = undefined;
var x176: u1 = undefined;
fiatP224SubborrowxU32(&x175, &x176, x174, x161, 0xffffffff);
var x177: u32 = undefined;
var x178: u1 = undefined;
fiatP224SubborrowxU32(&x177, &x178, x176, x163, 0xffffffff);
var x179: u32 = undefined;
var x180: u1 = undefined;
fiatP224SubborrowxU32(&x179, &x180, x178, @intCast(u32, x164), @intCast(u32, 0x0));
var x181: u32 = undefined;
var x182: u1 = undefined;
fiatP224AddcarryxU32(&x181, &x182, 0x0, x6, @intCast(u32, 0x1));
const x183: u32 = ((x128 >> 1) | ((x130 << 31) & 0xffffffff));
const x184: u32 = ((x130 >> 1) | ((x132 << 31) & 0xffffffff));
const x185: u32 = ((x132 >> 1) | ((x134 << 31) & 0xffffffff));
const x186: u32 = ((x134 >> 1) | ((x136 << 31) & 0xffffffff));
const x187: u32 = ((x136 >> 1) | ((x138 << 31) & 0xffffffff));
const x188: u32 = ((x138 >> 1) | ((x140 << 31) & 0xffffffff));
const x189: u32 = ((x140 >> 1) | ((x142 << 31) & 0xffffffff));
const x190: u32 = ((x142 & 0x80000000) | (x142 >> 1));
var x191: u32 = undefined;
fiatP224CmovznzU32(&x191, x75, x60, x46);
var x192: u32 = undefined;
fiatP224CmovznzU32(&x192, x75, x62, x48);
var x193: u32 = undefined;
fiatP224CmovznzU32(&x193, x75, x64, x50);
var x194: u32 = undefined;
fiatP224CmovznzU32(&x194, x75, x66, x52);
var x195: u32 = undefined;
fiatP224CmovznzU32(&x195, x75, x68, x54);
var x196: u32 = undefined;
fiatP224CmovznzU32(&x196, x75, x70, x56);
var x197: u32 = undefined;
fiatP224CmovznzU32(&x197, x75, x72, x58);
var x198: u32 = undefined;
fiatP224CmovznzU32(&x198, x180, x165, x151);
var x199: u32 = undefined;
fiatP224CmovznzU32(&x199, x180, x167, x153);
var x200: u32 = undefined;
fiatP224CmovznzU32(&x200, x180, x169, x155);
var x201: u32 = undefined;
fiatP224CmovznzU32(&x201, x180, x171, x157);
var x202: u32 = undefined;
fiatP224CmovznzU32(&x202, x180, x173, x159);
var x203: u32 = undefined;
fiatP224CmovznzU32(&x203, x180, x175, x161);
var x204: u32 = undefined;
fiatP224CmovznzU32(&x204, x180, x177, x163);
out1.* = x181;
out2[0] = x7;
out2[1] = x8;
out2[2] = x9;
out2[3] = x10;
out2[4] = x11;
out2[5] = x12;
out2[6] = x13;
out2[7] = x14;
out3[0] = x183;
out3[1] = x184;
out3[2] = x185;
out3[3] = x186;
out3[4] = x187;
out3[5] = x188;
out3[6] = x189;
out3[7] = x190;
out4[0] = x191;
out4[1] = x192;
out4[2] = x193;
out4[3] = x194;
out4[4] = x195;
out4[5] = x196;
out4[6] = x197;
out5[0] = x198;
out5[1] = x199;
out5[2] = x200;
out5[3] = x201;
out5[4] = x202;
out5[5] = x203;
out5[6] = x204;
}
/// The function fiatP224DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form).
/// Postconditions:
/// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋)
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fiatP224DivstepPrecomp(out1: *[7]u32) void {
out1[0] = 0x800000;
out1[1] = 0x800000;
out1[2] = 0xfe000000;
out1[3] = 0xffffff;
out1[4] = @intCast(u32, 0x0);
out1[5] = 0xff800000;
out1[6] = 0x17fffff;
}
|
fiat-zig/src/p224_32.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const assert = std.debug.assert;
pub const main = tools.defaultMain("2021/day16.txt", run);
const BitStream = struct {
hexdata: []const u8,
cur: u32 = 0,
accu: u32 = 0,
accu_bits: u5 = 0, // how many valid bits in the accumulator?
fn fillAccu(self: *@This()) void {
while (self.accu_bits < 15) {
if (self.cur >= self.hexdata.len) return; // EOS
const c = self.hexdata[self.cur];
self.cur += 1;
const val: u32 = switch (c) {
'0'...'9' => c - '0',
'A'...'F' => 10 + c - 'A',
else => continue, //skip garbage
};
self.accu = (self.accu << 4) | val;
self.accu_bits += 4;
}
}
fn readBits(self: *@This(), bits: u4) ?u32 {
fillAccu(self);
if (self.accu_bits < bits) return null; // EOS
const v = (self.accu >> (self.accu_bits - bits));
self.accu_bits -= bits;
return v;
}
pub fn curBit(self: *@This()) u32 {
return self.cur * 4 - self.accu_bits;
}
pub fn read1(self: *@This()) !u1 {
if (readBits(self, 1)) |v| return @intCast(u1, v & 0x01) else return error.UnexpectedEOS;
}
pub fn read3(self: *@This()) !u3 {
if (readBits(self, 3)) |v| return @intCast(u3, v & 0x07) else return error.UnexpectedEOS;
}
pub fn read4(self: *@This()) !u4 {
if (readBits(self, 4)) |v| return @intCast(u4, v & 0x0F) else return error.UnexpectedEOS;
}
pub fn read11(self: *@This()) !u11 {
if (readBits(self, 11)) |v| return @intCast(u11, v & 0x03FF) else return error.UnexpectedEOS;
}
pub fn read15(self: *@This()) !u15 {
if (readBits(self, 15)) |v| return @intCast(u15, v & 0x7FFF) else return error.UnexpectedEOS;
}
pub fn flushTrailingZeroes(self: *@This()) !void {
while (true) {
const b = self.read1() catch |err| switch (err) {
error.UnexpectedEOS => return,
};
if (b != 0) return error.UnsupportedInput;
}
}
};
const TypeId = enum(u3) {
sum,
product,
minimum,
maximum,
litteral, // 4
gt,
lt,
eq,
};
const TreeIndex = u16;
const Packet = struct { // "packed" -> zig crash "Assertion failed at zig/src/stage1/analyze.cpp:530 in get_pointer_to_type_extra2."
version: u3,
type_id: TypeId,
payload: union {
litteral: u64,
pair: struct {
idx: [2]TreeIndex = undefined,
},
list: struct {
len: u16 = 0,
entry_in_indexes_table: u16 = undefined,
},
},
};
/// returns parsed packet index in the packet_tree
const ParseError = std.mem.Allocator.Error || error{ UnsupportedInput, UnexpectedEOS };
fn parse(stream: *BitStream, packet_tree: *std.ArrayList(Packet), indexes_table: *std.ArrayList(TreeIndex)) ParseError!TreeIndex {
const version = try stream.read3();
const type_id = @intToEnum(TypeId, try stream.read3());
switch (type_id) {
.litteral => {
var lit: u64 = 0;
var continuation = true;
while (continuation) {
continuation = (try stream.read1()) != 0;
lit = (lit << 4) | (try stream.read4());
}
try packet_tree.append(Packet{ .version = version, .type_id = type_id, .payload = .{ .litteral = @intCast(u64, lit) } });
return @intCast(TreeIndex, packet_tree.items.len - 1);
},
else => {
var children = std.BoundedArray(TreeIndex, 128).init(0) catch unreachable; // TODO: is there copy elision?
const mode = try stream.read1();
if (mode == 0) { // mode "len"
const bitlen = try stream.read15();
const startbit = stream.curBit();
while (stream.curBit() < startbit + bitlen) {
const idx = try parse(stream, packet_tree, indexes_table);
children.append(idx) catch return error.UnsupportedInput;
}
} else { // mode "count"
const count = try stream.read11();
var i: u32 = 0;
while (i < count) : (i += 1) {
const idx = try parse(stream, packet_tree, indexes_table);
children.append(idx) catch return error.UnsupportedInput;
}
}
if (children.len == 0) return error.UnsupportedInput; // sinon les operteurs sont pas très bien définis.
switch (type_id) {
.litteral => unreachable,
.gt, .lt, .eq => {
if (children.len != 2) return error.UnsupportedInput;
try packet_tree.append(Packet{
.version = version,
.type_id = type_id,
.payload = .{ .pair = .{ .idx = .{ children.buffer[0], children.buffer[1] } } },
});
},
else => {
const first = indexes_table.items.len;
try indexes_table.appendSlice(children.slice());
try packet_tree.append(Packet{
.version = version,
.type_id = type_id,
.payload = .{ .list = .{ .len = @intCast(u16, children.len), .entry_in_indexes_table = @intCast(u16, first) } },
});
},
}
return @intCast(TreeIndex, packet_tree.items.len - 1);
},
}
}
const PacketTree = struct {
items: []const Packet,
indexes_table: []const u16,
};
fn eval(tree: PacketTree, root: TreeIndex) u64 {
const p = tree.items[root];
switch (p.type_id) {
.litteral => {
return p.payload.litteral;
},
.gt, .lt, .eq => {
const left = eval(tree, p.payload.pair.idx[0]);
const right = eval(tree, p.payload.pair.idx[1]);
return switch (p.type_id) {
.gt => @boolToInt(left > right),
.lt => @boolToInt(left < right),
.eq => @boolToInt(left == right),
else => unreachable,
};
},
.sum => {
const list = tree.indexes_table[p.payload.list.entry_in_indexes_table .. p.payload.list.entry_in_indexes_table + p.payload.list.len];
var v: u64 = 0;
for (list) |idx| v += eval(tree, idx);
return v;
},
.product => {
const list = tree.indexes_table[p.payload.list.entry_in_indexes_table .. p.payload.list.entry_in_indexes_table + p.payload.list.len];
var v: u64 = 1;
for (list) |idx| v *= eval(tree, idx);
return v;
},
.minimum => {
const list = tree.indexes_table[p.payload.list.entry_in_indexes_table .. p.payload.list.entry_in_indexes_table + p.payload.list.len];
var v: u64 = 0xFFFFFFFFFFFFFFFF;
for (list) |idx| v = @minimum(v, eval(tree, idx));
return v;
},
.maximum => {
const list = tree.indexes_table[p.payload.list.entry_in_indexes_table .. p.payload.list.entry_in_indexes_table + p.payload.list.len];
var v: u64 = 0;
for (list) |idx| v = @maximum(v, eval(tree, idx));
return v;
},
}
}
fn dumpPacketTree(tree: PacketTree, root: TreeIndex, indentation: u8) void {
const indent_spaces = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
const p = tree.items[root];
trace("{s}ver={} type={} ", .{ indent_spaces[0..indentation], p.version, p.type_id });
switch (p.type_id) {
.litteral => {
trace("litteral={}\n", .{p.payload.litteral});
},
.gt, .lt, .eq => {
trace("pair:\n", .{});
for (p.payload.pair.idx) |idx| {
dumpPacketTree(tree, idx, indentation + 1);
}
},
else => {
trace("subpackets[{}]:\n", .{p.payload.list.len});
for (tree.indexes_table[p.payload.list.entry_in_indexes_table .. p.payload.list.entry_in_indexes_table + p.payload.list.len]) |idx| {
dumpPacketTree(tree, idx, indentation + 1);
}
},
}
}
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
//var arena_alloc = std.heap.ArenaAllocator.init(gpa);
//defer arena_alloc.deinit();
//const arena = arena_alloc.allocator();
var stream = BitStream{ .hexdata = input };
var packet_tree = std.ArrayList(Packet).init(gpa);
defer packet_tree.deinit();
var indexes_table = std.ArrayList(u16).init(gpa);
defer indexes_table.deinit();
const root = try parse(&stream, &packet_tree, &indexes_table);
try stream.flushTrailingZeroes();
const tree = PacketTree{ .items = packet_tree.items, .indexes_table = indexes_table.items };
dumpPacketTree(tree, root, 0);
const ans1 = ans: {
var totalversion: u32 = 0;
for (tree.items) |p| totalversion += p.version;
break :ans totalversion;
};
const ans2 = eval(tree, root);
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans1}),
try std.fmt.allocPrint(gpa, "{}", .{ans2}),
};
}
test {
const examples = [_]struct { in: []const u8, ans1: []const u8, ans2: []const u8 }{
.{ .in = "D2FE28", .ans1 = "6", .ans2 = "2021" },
.{ .in = "38006F45291200", .ans1 = "9", .ans2 = "1" },
.{ .in = "EE00D40C823060", .ans1 = "14", .ans2 = "3" },
.{ .in = "8A004A801A8002F478", .ans1 = "16", .ans2 = "15" },
.{ .in = "620080001611562C8802118E34", .ans1 = "12", .ans2 = "46" },
.{ .in = "C0015000016115A2E0802F182340", .ans1 = "23", .ans2 = "46" },
.{ .in = "A0016C880162017C3686B18A3D4780", .ans1 = "31", .ans2 = "54" },
.{ .in = "C200B40A82", .ans1 = "14", .ans2 = "3" },
.{ .in = "04005AC33890", .ans1 = "8", .ans2 = "54" },
.{ .in = "880086C3E88112", .ans1 = "15", .ans2 = "7" },
.{ .in = "CE00C43D881120", .ans1 = "11", .ans2 = "9" },
.{ .in = "D8005AC2A8F0", .ans1 = "13", .ans2 = "1" },
.{ .in = "F600BC2D8F", .ans1 = "19", .ans2 = "0" },
.{ .in = "9C005AC2F8F0", .ans1 = "16", .ans2 = "0" },
.{ .in = "9C0141080250320F1802104A08", .ans1 = "20", .ans2 = "1" },
};
for (examples) |e| {
const res = try run(e.in, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings(e.ans1, res[0]);
try std.testing.expectEqualStrings(e.ans2, res[1]);
}
}
|
2021/day16.zig
|
pub usingnamespace @import("std").c.builtins;
pub const __m64 = @import("std").meta.Vector(1, c_longlong);
pub const __v1di = @import("std").meta.Vector(1, c_longlong);
pub const __v2si = @import("std").meta.Vector(2, c_int);
pub const __v4hi = @import("std").meta.Vector(4, c_short);
pub const __v8qi = @import("std").meta.Vector(8, u8); // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:33:5: warning: TODO implement function '__builtin_ia32_emms' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:31:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_empty() callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:50:19: warning: TODO implement function '__builtin_ia32_vec_init_v2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:48:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtsi32_si64(arg___i: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:67:12: warning: TODO implement function '__builtin_ia32_vec_ext_v2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:65:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtsi64_si32(arg___m: __m64) callconv(.C) c_int;
pub fn _mm_cvtsi64_m64(arg___i: c_longlong) callconv(.C) __m64 {
var __i = arg___i;
return @bitCast(__m64, __i);
}
pub fn _mm_cvtm64_si64(arg___m: __m64) callconv(.C) c_longlong {
var __m = arg___m;
return @bitCast(c_longlong, __m);
} // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:129:19: warning: TODO implement function '__builtin_ia32_packsswb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:127:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packs_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:159:19: warning: TODO implement function '__builtin_ia32_packssdw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:157:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packs_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:189:19: warning: TODO implement function '__builtin_ia32_packuswb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:187:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packs_pu16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:216:19: warning: TODO implement function '__builtin_ia32_punpckhbw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:214:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpackhi_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:239:19: warning: TODO implement function '__builtin_ia32_punpckhwd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:237:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpackhi_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:260:19: warning: TODO implement function '__builtin_ia32_punpckhdq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:258:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpackhi_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:287:19: warning: TODO implement function '__builtin_ia32_punpcklbw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:285:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpacklo_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:310:19: warning: TODO implement function '__builtin_ia32_punpcklwd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:308:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpacklo_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:331:19: warning: TODO implement function '__builtin_ia32_punpckldq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:329:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_unpacklo_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:352:19: warning: TODO implement function '__builtin_ia32_paddb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:350:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_add_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:373:19: warning: TODO implement function '__builtin_ia32_paddw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:371:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_add_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:394:19: warning: TODO implement function '__builtin_ia32_paddd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:392:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_add_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:416:19: warning: TODO implement function '__builtin_ia32_paddsb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:414:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:439:19: warning: TODO implement function '__builtin_ia32_paddsw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:437:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:461:19: warning: TODO implement function '__builtin_ia32_paddusb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:459:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_pu8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:483:19: warning: TODO implement function '__builtin_ia32_paddusw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:481:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_pu16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:504:19: warning: TODO implement function '__builtin_ia32_psubb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:502:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sub_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:525:19: warning: TODO implement function '__builtin_ia32_psubw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:523:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sub_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:546:19: warning: TODO implement function '__builtin_ia32_psubd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:544:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sub_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:569:19: warning: TODO implement function '__builtin_ia32_psubsb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:567:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:592:19: warning: TODO implement function '__builtin_ia32_psubsw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:590:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:616:19: warning: TODO implement function '__builtin_ia32_psubusb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:614:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_pu8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:640:19: warning: TODO implement function '__builtin_ia32_psubusw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:638:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_pu16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:667:19: warning: TODO implement function '__builtin_ia32_pmaddwd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:665:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_madd_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:688:19: warning: TODO implement function '__builtin_ia32_pmulhw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:686:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mulhi_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:709:19: warning: TODO implement function '__builtin_ia32_pmullw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:707:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mullo_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:732:19: warning: TODO implement function '__builtin_ia32_psllw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:730:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_pi16(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:754:19: warning: TODO implement function '__builtin_ia32_psllwi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:752:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_pi16(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:777:19: warning: TODO implement function '__builtin_ia32_pslld' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:775:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_pi32(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:799:19: warning: TODO implement function '__builtin_ia32_pslldi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:797:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_pi32(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:819:19: warning: TODO implement function '__builtin_ia32_psllq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:817:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_si64(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:839:19: warning: TODO implement function '__builtin_ia32_psllqi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:837:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_si64(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:863:19: warning: TODO implement function '__builtin_ia32_psraw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:861:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sra_pi16(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:886:19: warning: TODO implement function '__builtin_ia32_psrawi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:884:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srai_pi16(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:910:19: warning: TODO implement function '__builtin_ia32_psrad' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:908:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sra_pi32(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:933:19: warning: TODO implement function '__builtin_ia32_psradi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:931:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srai_pi32(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:956:19: warning: TODO implement function '__builtin_ia32_psrlw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:954:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_pi16(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:978:19: warning: TODO implement function '__builtin_ia32_psrlwi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:976:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_pi16(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1001:19: warning: TODO implement function '__builtin_ia32_psrld' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:999:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_pi32(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1023:19: warning: TODO implement function '__builtin_ia32_psrldi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1021:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_pi32(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1043:19: warning: TODO implement function '__builtin_ia32_psrlq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1041:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_si64(arg___m: __m64, arg___count: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1064:19: warning: TODO implement function '__builtin_ia32_psrlqi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1062:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_si64(arg___m: __m64, arg___count: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1082:12: warning: TODO implement function '__builtin_ia32_pand' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1080:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_and_si64(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1103:12: warning: TODO implement function '__builtin_ia32_pandn' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1101:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_andnot_si64(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1121:12: warning: TODO implement function '__builtin_ia32_por' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1119:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_or_si64(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1139:12: warning: TODO implement function '__builtin_ia32_pxor' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1137:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_xor_si64(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1161:19: warning: TODO implement function '__builtin_ia32_pcmpeqb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1159:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1183:19: warning: TODO implement function '__builtin_ia32_pcmpeqw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1181:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1205:19: warning: TODO implement function '__builtin_ia32_pcmpeqd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1203:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1227:19: warning: TODO implement function '__builtin_ia32_pcmpgtb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1225:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_pi8(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1249:19: warning: TODO implement function '__builtin_ia32_pcmpgtw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1247:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_pi16(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1271:19: warning: TODO implement function '__builtin_ia32_pcmpgtd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1269:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_pi32(arg___m1: __m64, arg___m2: __m64) callconv(.C) __m64;
pub fn _mm_setzero_si64() callconv(.C) __m64 {
return blk: {
const tmp = @as(c_longlong, 0);
break :blk __m64{
tmp,
};
};
} // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1305:19: warning: TODO implement function '__builtin_ia32_vec_init_v2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1303:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_set_pi32(arg___i1: c_int, arg___i0: c_int) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1328:19: warning: TODO implement function '__builtin_ia32_vec_init_v4hi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1326:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_set_pi16(arg___s3: c_short, arg___s2: c_short, arg___s1: c_short, arg___s0: c_short) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1360:19: warning: TODO implement function '__builtin_ia32_vec_init_v8qi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\mmintrin.h:1357:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_set_pi8(arg___b7: u8, arg___b6: u8, arg___b5: u8, arg___b4: u8, arg___b3: u8, arg___b2: u8, arg___b1: u8, arg___b0: u8) callconv(.C) __m64;
pub fn _mm_set1_pi32(arg___i: c_int) callconv(.C) __m64 {
var __i = arg___i;
return _mm_set_pi32(__i, __i);
}
pub fn _mm_set1_pi16(arg___w: c_short) callconv(.C) __m64 {
var __w = arg___w;
return _mm_set_pi16(__w, __w, __w, __w);
}
pub fn _mm_set1_pi8(arg___b: u8) callconv(.C) __m64 {
var __b = arg___b;
return _mm_set_pi8(__b, __b, __b, __b, __b, __b, __b, __b);
}
pub fn _mm_setr_pi32(arg___i0: c_int, arg___i1: c_int) callconv(.C) __m64 {
var __i0 = arg___i0;
var __i1 = arg___i1;
return _mm_set_pi32(__i1, __i0);
}
pub fn _mm_setr_pi16(arg___w0: c_short, arg___w1: c_short, arg___w2: c_short, arg___w3: c_short) callconv(.C) __m64 {
var __w0 = arg___w0;
var __w1 = arg___w1;
var __w2 = arg___w2;
var __w3 = arg___w3;
return _mm_set_pi16(__w3, __w2, __w1, __w0);
}
pub fn _mm_setr_pi8(arg___b0: u8, arg___b1: u8, arg___b2: u8, arg___b3: u8, arg___b4: u8, arg___b5: u8, arg___b6: u8, arg___b7: u8) callconv(.C) __m64 {
var __b0 = arg___b0;
var __b1 = arg___b1;
var __b2 = arg___b2;
var __b3 = arg___b3;
var __b4 = arg___b4;
var __b5 = arg___b5;
var __b6 = arg___b6;
var __b7 = arg___b7;
return _mm_set_pi8(__b7, __b6, __b5, __b4, __b3, __b2, __b1, __b0);
}
pub const __v4si = @import("std").meta.Vector(4, c_int);
pub const __v4sf = @import("std").meta.Vector(4, f32);
pub const __m128 = @import("std").meta.Vector(4, f32);
pub const __m128_u = @import("std").meta.Vector(4, f32);
pub const __v4su = @import("std").meta.Vector(4, c_uint);
pub const __builtin_va_list = [*c]u8;
pub const __gnuc_va_list = __builtin_va_list;
pub const va_list = __gnuc_va_list; // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:584:3: warning: TODO implement translation of stmt class GCCAsmStmtClass
// C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:581:36: warning: unable to translate function, demoted to extern
pub extern fn __debugbreak() callconv(.C) void;
pub extern fn __mingw_get_crt_info() [*c]const u8;
pub const rsize_t = usize;
pub const ptrdiff_t = c_longlong;
pub const wchar_t = c_ushort;
pub const wint_t = c_ushort;
pub const wctype_t = c_ushort;
pub const errno_t = c_int;
pub const __time32_t = c_long;
pub const __time64_t = c_longlong;
pub const time_t = __time64_t;
pub const struct_tagLC_ID = extern struct {
wLanguage: c_ushort,
wCountry: c_ushort,
wCodePage: c_ushort,
};
pub const LC_ID = struct_tagLC_ID;
const struct_unnamed_1 = extern struct {
locale: [*c]u8,
wlocale: [*c]wchar_t,
refcount: [*c]c_int,
wrefcount: [*c]c_int,
};
pub const struct_lconv = opaque {};
pub const struct___lc_time_data = opaque {};
pub const struct_threadlocaleinfostruct = extern struct {
refcount: c_int,
lc_codepage: c_uint,
lc_collate_cp: c_uint,
lc_handle: [6]c_ulong,
lc_id: [6]LC_ID,
lc_category: [6]struct_unnamed_1,
lc_clike: c_int,
mb_cur_max: c_int,
lconv_intl_refcount: [*c]c_int,
lconv_num_refcount: [*c]c_int,
lconv_mon_refcount: [*c]c_int,
lconv: ?*struct_lconv,
ctype1_refcount: [*c]c_int,
ctype1: [*c]c_ushort,
pctype: [*c]const c_ushort,
pclmap: [*c]const u8,
pcumap: [*c]const u8,
lc_time_curr: ?*struct___lc_time_data,
};
pub const struct_threadmbcinfostruct = opaque {};
pub const pthreadlocinfo = [*c]struct_threadlocaleinfostruct;
pub const pthreadmbcinfo = ?*struct_threadmbcinfostruct;
pub const struct_localeinfo_struct = extern struct {
locinfo: pthreadlocinfo,
mbcinfo: pthreadmbcinfo,
};
pub const _locale_tstruct = struct_localeinfo_struct;
pub const _locale_t = [*c]struct_localeinfo_struct;
pub const LPLC_ID = [*c]struct_tagLC_ID;
pub const threadlocinfo = struct_threadlocaleinfostruct;
pub extern fn _itow_s(_Val: c_int, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _Radix: c_int) errno_t;
pub extern fn _ltow_s(_Val: c_long, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _Radix: c_int) errno_t;
pub extern fn _ultow_s(_Val: c_ulong, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _Radix: c_int) errno_t;
pub extern fn _wgetenv_s(_ReturnSize: [*c]usize, _DstBuf: [*c]wchar_t, _DstSizeInWords: usize, _VarName: [*c]const wchar_t) errno_t;
pub extern fn _wdupenv_s(_Buffer: [*c][*c]wchar_t, _BufferSizeInWords: [*c]usize, _VarName: [*c]const wchar_t) errno_t;
pub extern fn _i64tow_s(_Val: c_longlong, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _Radix: c_int) errno_t;
pub extern fn _ui64tow_s(_Val: c_ulonglong, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _Radix: c_int) errno_t;
pub extern fn _wmakepath_s(_PathResult: [*c]wchar_t, _SizeInWords: usize, _Drive: [*c]const wchar_t, _Dir: [*c]const wchar_t, _Filename: [*c]const wchar_t, _Ext: [*c]const wchar_t) errno_t;
pub extern fn _wputenv_s(_Name: [*c]const wchar_t, _Value: [*c]const wchar_t) errno_t;
pub extern fn _wsearchenv_s(_Filename: [*c]const wchar_t, _EnvVar: [*c]const wchar_t, _ResultPath: [*c]wchar_t, _SizeInWords: usize) errno_t;
pub extern fn _wsplitpath_s(_FullPath: [*c]const wchar_t, _Drive: [*c]wchar_t, _DriveSizeInWords: usize, _Dir: [*c]wchar_t, _DirSizeInWords: usize, _Filename: [*c]wchar_t, _FilenameSizeInWords: usize, _Ext: [*c]wchar_t, _ExtSizeInWords: usize) errno_t;
pub const _onexit_t = ?fn () callconv(.C) c_int;
pub const struct__div_t = extern struct {
quot: c_int,
rem: c_int,
};
pub const div_t = struct__div_t;
pub const struct__ldiv_t = extern struct {
quot: c_long,
rem: c_long,
};
pub const ldiv_t = struct__ldiv_t;
pub const _LDOUBLE = extern struct {
ld: [10]u8,
};
pub const _CRT_DOUBLE = extern struct {
x: f64,
};
pub const _CRT_FLOAT = extern struct {
f: f32,
};
pub const _LONGDOUBLE = extern struct {
x: c_longdouble,
};
pub const _LDBL12 = extern struct {
ld12: [12]u8,
};
pub extern var __imp___mb_cur_max: [*c]c_int;
pub extern fn ___mb_cur_max_func() c_int;
pub const _purecall_handler = ?fn () callconv(.C) void;
pub extern fn _set_purecall_handler(_Handler: _purecall_handler) _purecall_handler;
pub extern fn _get_purecall_handler() _purecall_handler;
pub const _invalid_parameter_handler = ?fn ([*c]const wchar_t, [*c]const wchar_t, [*c]const wchar_t, c_uint, usize) callconv(.C) void;
pub extern fn _set_invalid_parameter_handler(_Handler: _invalid_parameter_handler) _invalid_parameter_handler;
pub extern fn _get_invalid_parameter_handler() _invalid_parameter_handler;
pub extern fn _errno() [*c]c_int;
pub extern fn _set_errno(_Value: c_int) errno_t;
pub extern fn _get_errno(_Value: [*c]c_int) errno_t;
pub extern fn __doserrno() [*c]c_ulong;
pub extern fn _set_doserrno(_Value: c_ulong) errno_t;
pub extern fn _get_doserrno(_Value: [*c]c_ulong) errno_t;
pub extern var _sys_errlist: [1][*c]u8;
pub extern var _sys_nerr: c_int;
pub extern fn __p___argv() [*c][*c][*c]u8;
pub extern fn __p__fmode() [*c]c_int;
pub extern fn _get_pgmptr(_Value: [*c][*c]u8) errno_t;
pub extern fn _get_wpgmptr(_Value: [*c][*c]wchar_t) errno_t;
pub extern fn _set_fmode(_Mode: c_int) errno_t;
pub extern fn _get_fmode(_PMode: [*c]c_int) errno_t;
pub extern var __imp___argc: [*c]c_int;
pub extern var __imp___argv: [*c][*c][*c]u8;
pub extern var __imp___wargv: [*c][*c][*c]wchar_t;
pub extern var __imp__environ: [*c][*c][*c]u8;
pub extern var __imp__wenviron: [*c][*c][*c]wchar_t;
pub extern var __imp__pgmptr: [*c][*c]u8;
pub extern var __imp__wpgmptr: [*c][*c]wchar_t;
pub extern var __imp__osplatform: [*c]c_uint;
pub extern var __imp__osver: [*c]c_uint;
pub extern var __imp__winver: [*c]c_uint;
pub extern var __imp__winmajor: [*c]c_uint;
pub extern var __imp__winminor: [*c]c_uint;
pub extern fn _get_osplatform(_Value: [*c]c_uint) errno_t;
pub extern fn _get_osver(_Value: [*c]c_uint) errno_t;
pub extern fn _get_winver(_Value: [*c]c_uint) errno_t;
pub extern fn _get_winmajor(_Value: [*c]c_uint) errno_t;
pub extern fn _get_winminor(_Value: [*c]c_uint) errno_t;
pub extern fn exit(_Code: c_int) noreturn;
pub extern fn _exit(_Code: c_int) noreturn;
pub fn _Exit(arg_status: c_int) callconv(.C) noreturn {
var status = arg_status;
_exit(status);
}
pub extern fn abort() noreturn;
pub extern fn _set_abort_behavior(_Flags: c_uint, _Mask: c_uint) c_uint;
pub extern fn abs(_X: c_int) c_int;
pub extern fn labs(_X: c_long) c_long; // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\stdlib.h:421:12: warning: TODO implement function '__builtin_llabs' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\stdlib.h:420:41: warning: unable to translate function, demoted to extern
pub extern fn _abs64(arg_x: c_longlong) callconv(.C) c_longlong;
pub extern fn atexit(?fn () callconv(.C) void) c_int;
pub extern fn atof(_String: [*c]const u8) f64;
pub extern fn _atof_l(_String: [*c]const u8, _Locale: _locale_t) f64;
pub extern fn atoi(_Str: [*c]const u8) c_int;
pub extern fn _atoi_l(_Str: [*c]const u8, _Locale: _locale_t) c_int;
pub extern fn atol(_Str: [*c]const u8) c_long;
pub extern fn _atol_l(_Str: [*c]const u8, _Locale: _locale_t) c_long;
pub extern fn bsearch(_Key: ?*const c_void, _Base: ?*const c_void, _NumOfElements: usize, _SizeOfElements: usize, _PtFuncCompare: ?fn (?*const c_void, ?*const c_void) callconv(.C) c_int) ?*c_void;
pub extern fn qsort(_Base: ?*c_void, _NumOfElements: usize, _SizeOfElements: usize, _PtFuncCompare: ?fn (?*const c_void, ?*const c_void) callconv(.C) c_int) void;
pub extern fn _byteswap_ushort(_Short: c_ushort) c_ushort;
pub extern fn _byteswap_ulong(_Long: c_ulong) c_ulong;
pub extern fn _byteswap_uint64(_Int64: c_ulonglong) c_ulonglong;
pub extern fn div(_Numerator: c_int, _Denominator: c_int) div_t;
pub extern fn getenv(_VarName: [*c]const u8) [*c]u8;
pub extern fn _itoa(_Value: c_int, _Dest: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn _i64toa(_Val: c_longlong, _DstBuf: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn _ui64toa(_Val: c_ulonglong, _DstBuf: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn _atoi64(_String: [*c]const u8) c_longlong;
pub extern fn _atoi64_l(_String: [*c]const u8, _Locale: _locale_t) c_longlong;
pub extern fn _strtoi64(_String: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int) c_longlong;
pub extern fn _strtoi64_l(_String: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int, _Locale: _locale_t) c_longlong;
pub extern fn _strtoui64(_String: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int) c_ulonglong;
pub extern fn _strtoui64_l(_String: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int, _Locale: _locale_t) c_ulonglong;
pub extern fn ldiv(_Numerator: c_long, _Denominator: c_long) ldiv_t;
pub extern fn _ltoa(_Value: c_long, _Dest: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn mblen(_Ch: [*c]const u8, _MaxCount: usize) c_int;
pub extern fn _mblen_l(_Ch: [*c]const u8, _MaxCount: usize, _Locale: _locale_t) c_int;
pub extern fn _mbstrlen(_Str: [*c]const u8) usize;
pub extern fn _mbstrlen_l(_Str: [*c]const u8, _Locale: _locale_t) usize;
pub extern fn _mbstrnlen(_Str: [*c]const u8, _MaxCount: usize) usize;
pub extern fn _mbstrnlen_l(_Str: [*c]const u8, _MaxCount: usize, _Locale: _locale_t) usize;
pub extern fn mbtowc(noalias _DstCh: [*c]wchar_t, noalias _SrcCh: [*c]const u8, _SrcSizeInBytes: usize) c_int;
pub extern fn _mbtowc_l(noalias _DstCh: [*c]wchar_t, noalias _SrcCh: [*c]const u8, _SrcSizeInBytes: usize, _Locale: _locale_t) c_int;
pub extern fn mbstowcs(noalias _Dest: [*c]wchar_t, noalias _Source: [*c]const u8, _MaxCount: usize) usize;
pub extern fn _mbstowcs_l(noalias _Dest: [*c]wchar_t, noalias _Source: [*c]const u8, _MaxCount: usize, _Locale: _locale_t) usize;
pub extern fn mkstemp(template_name: [*c]u8) c_int;
pub extern fn rand() c_int;
pub extern fn _set_error_mode(_Mode: c_int) c_int;
pub extern fn srand(_Seed: c_uint) void;
pub extern fn __mingw_strtod(noalias [*c]const u8, noalias [*c][*c]u8) f64;
pub fn strtod(noalias arg__Str: [*c]const u8, noalias arg__EndPtr: [*c][*c]u8) callconv(.C) f64 {
var _Str = arg__Str;
var _EndPtr = arg__EndPtr;
return __mingw_strtod(_Str, _EndPtr);
}
pub extern fn __mingw_strtof(noalias [*c]const u8, noalias [*c][*c]u8) f32;
pub fn strtof(noalias arg__Str: [*c]const u8, noalias arg__EndPtr: [*c][*c]u8) callconv(.C) f32 {
var _Str = arg__Str;
var _EndPtr = arg__EndPtr;
return __mingw_strtof(_Str, _EndPtr);
}
pub extern fn strtold([*c]const u8, [*c][*c]u8) c_longdouble;
pub extern fn __strtod(noalias [*c]const u8, noalias [*c][*c]u8) f64;
pub extern fn __mingw_strtold(noalias [*c]const u8, noalias [*c][*c]u8) c_longdouble;
pub extern fn _strtod_l(noalias _Str: [*c]const u8, noalias _EndPtr: [*c][*c]u8, _Locale: _locale_t) f64;
pub extern fn strtol(_Str: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int) c_long;
pub extern fn _strtol_l(noalias _Str: [*c]const u8, noalias _EndPtr: [*c][*c]u8, _Radix: c_int, _Locale: _locale_t) c_long;
pub extern fn strtoul(_Str: [*c]const u8, _EndPtr: [*c][*c]u8, _Radix: c_int) c_ulong;
pub extern fn _strtoul_l(noalias _Str: [*c]const u8, noalias _EndPtr: [*c][*c]u8, _Radix: c_int, _Locale: _locale_t) c_ulong;
pub extern fn system(_Command: [*c]const u8) c_int;
pub extern fn _ultoa(_Value: c_ulong, _Dest: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn wctomb(_MbCh: [*c]u8, _WCh: wchar_t) c_int;
pub extern fn _wctomb_l(_MbCh: [*c]u8, _WCh: wchar_t, _Locale: _locale_t) c_int;
pub extern fn wcstombs(noalias _Dest: [*c]u8, noalias _Source: [*c]const wchar_t, _MaxCount: usize) usize;
pub extern fn _wcstombs_l(noalias _Dest: [*c]u8, noalias _Source: [*c]const wchar_t, _MaxCount: usize, _Locale: _locale_t) usize;
pub extern fn calloc(_NumOfElements: c_ulonglong, _SizeOfElements: c_ulonglong) ?*c_void;
pub extern fn free(_Memory: ?*c_void) void;
pub extern fn malloc(_Size: c_ulonglong) ?*c_void;
pub extern fn realloc(_Memory: ?*c_void, _NewSize: c_ulonglong) ?*c_void;
pub extern fn _recalloc(_Memory: ?*c_void, _Count: usize, _Size: usize) ?*c_void;
pub extern fn _aligned_free(_Memory: ?*c_void) void;
pub extern fn _aligned_malloc(_Size: usize, _Alignment: usize) ?*c_void;
pub extern fn _aligned_offset_malloc(_Size: usize, _Alignment: usize, _Offset: usize) ?*c_void;
pub extern fn _aligned_realloc(_Memory: ?*c_void, _Size: usize, _Alignment: usize) ?*c_void;
pub extern fn _aligned_recalloc(_Memory: ?*c_void, _Count: usize, _Size: usize, _Alignment: usize) ?*c_void;
pub extern fn _aligned_offset_realloc(_Memory: ?*c_void, _Size: usize, _Alignment: usize, _Offset: usize) ?*c_void;
pub extern fn _aligned_offset_recalloc(_Memory: ?*c_void, _Count: usize, _Size: usize, _Alignment: usize, _Offset: usize) ?*c_void;
pub extern fn _itow(_Value: c_int, _Dest: [*c]wchar_t, _Radix: c_int) [*c]wchar_t;
pub extern fn _ltow(_Value: c_long, _Dest: [*c]wchar_t, _Radix: c_int) [*c]wchar_t;
pub extern fn _ultow(_Value: c_ulong, _Dest: [*c]wchar_t, _Radix: c_int) [*c]wchar_t;
pub extern fn __mingw_wcstod(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t) f64;
pub extern fn __mingw_wcstof(noalias nptr: [*c]const wchar_t, noalias endptr: [*c][*c]wchar_t) f32;
pub extern fn __mingw_wcstold(noalias [*c]const wchar_t, noalias [*c][*c]wchar_t) c_longdouble;
pub fn wcstod(noalias arg__Str: [*c]const wchar_t, noalias arg__EndPtr: [*c][*c]wchar_t) callconv(.C) f64 {
var _Str = arg__Str;
var _EndPtr = arg__EndPtr;
return __mingw_wcstod(_Str, _EndPtr);
}
pub fn wcstof(noalias arg__Str: [*c]const wchar_t, noalias arg__EndPtr: [*c][*c]wchar_t) callconv(.C) f32 {
var _Str = arg__Str;
var _EndPtr = arg__EndPtr;
return __mingw_wcstof(_Str, _EndPtr);
}
pub extern fn wcstold(noalias [*c]const wchar_t, noalias [*c][*c]wchar_t) c_longdouble;
pub extern fn _wcstod_l(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t, _Locale: _locale_t) f64;
pub extern fn wcstol(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t, _Radix: c_int) c_long;
pub extern fn _wcstol_l(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t, _Radix: c_int, _Locale: _locale_t) c_long;
pub extern fn wcstoul(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t, _Radix: c_int) c_ulong;
pub extern fn _wcstoul_l(noalias _Str: [*c]const wchar_t, noalias _EndPtr: [*c][*c]wchar_t, _Radix: c_int, _Locale: _locale_t) c_ulong;
pub extern fn _wgetenv(_VarName: [*c]const wchar_t) [*c]wchar_t;
pub extern fn _wsystem(_Command: [*c]const wchar_t) c_int;
pub extern fn _wtof(_Str: [*c]const wchar_t) f64;
pub extern fn _wtof_l(_Str: [*c]const wchar_t, _Locale: _locale_t) f64;
pub extern fn _wtoi(_Str: [*c]const wchar_t) c_int;
pub extern fn _wtoi_l(_Str: [*c]const wchar_t, _Locale: _locale_t) c_int;
pub extern fn _wtol(_Str: [*c]const wchar_t) c_long;
pub extern fn _wtol_l(_Str: [*c]const wchar_t, _Locale: _locale_t) c_long;
pub extern fn _i64tow(_Val: c_longlong, _DstBuf: [*c]wchar_t, _Radix: c_int) [*c]wchar_t;
pub extern fn _ui64tow(_Val: c_ulonglong, _DstBuf: [*c]wchar_t, _Radix: c_int) [*c]wchar_t;
pub extern fn _wtoi64(_Str: [*c]const wchar_t) c_longlong;
pub extern fn _wtoi64_l(_Str: [*c]const wchar_t, _Locale: _locale_t) c_longlong;
pub extern fn _wcstoi64(_Str: [*c]const wchar_t, _EndPtr: [*c][*c]wchar_t, _Radix: c_int) c_longlong;
pub extern fn _wcstoi64_l(_Str: [*c]const wchar_t, _EndPtr: [*c][*c]wchar_t, _Radix: c_int, _Locale: _locale_t) c_longlong;
pub extern fn _wcstoui64(_Str: [*c]const wchar_t, _EndPtr: [*c][*c]wchar_t, _Radix: c_int) c_ulonglong;
pub extern fn _wcstoui64_l(_Str: [*c]const wchar_t, _EndPtr: [*c][*c]wchar_t, _Radix: c_int, _Locale: _locale_t) c_ulonglong;
pub extern fn _putenv(_EnvString: [*c]const u8) c_int;
pub extern fn _wputenv(_EnvString: [*c]const wchar_t) c_int;
pub extern fn _fullpath(_FullPath: [*c]u8, _Path: [*c]const u8, _SizeInBytes: usize) [*c]u8;
pub extern fn _ecvt(_Val: f64, _NumOfDigits: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) [*c]u8;
pub extern fn _fcvt(_Val: f64, _NumOfDec: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) [*c]u8;
pub extern fn _gcvt(_Val: f64, _NumOfDigits: c_int, _DstBuf: [*c]u8) [*c]u8;
pub extern fn _atodbl(_Result: [*c]_CRT_DOUBLE, _Str: [*c]u8) c_int;
pub extern fn _atoldbl(_Result: [*c]_LDOUBLE, _Str: [*c]u8) c_int;
pub extern fn _atoflt(_Result: [*c]_CRT_FLOAT, _Str: [*c]u8) c_int;
pub extern fn _atodbl_l(_Result: [*c]_CRT_DOUBLE, _Str: [*c]u8, _Locale: _locale_t) c_int;
pub extern fn _atoldbl_l(_Result: [*c]_LDOUBLE, _Str: [*c]u8, _Locale: _locale_t) c_int;
pub extern fn _atoflt_l(_Result: [*c]_CRT_FLOAT, _Str: [*c]u8, _Locale: _locale_t) c_int;
pub extern fn _lrotl(c_ulong, c_int) c_ulong;
pub extern fn _lrotr(c_ulong, c_int) c_ulong;
pub extern fn _makepath(_Path: [*c]u8, _Drive: [*c]const u8, _Dir: [*c]const u8, _Filename: [*c]const u8, _Ext: [*c]const u8) void;
pub extern fn _onexit(_Func: _onexit_t) _onexit_t;
pub extern fn perror(_ErrMsg: [*c]const u8) void;
pub extern fn _rotl64(_Val: c_ulonglong, _Shift: c_int) c_ulonglong;
pub extern fn _rotr64(Value: c_ulonglong, Shift: c_int) c_ulonglong;
pub extern fn _rotr(_Val: c_uint, _Shift: c_int) c_uint;
pub extern fn _rotl(_Val: c_uint, _Shift: c_int) c_uint;
pub extern fn _searchenv(_Filename: [*c]const u8, _EnvVar: [*c]const u8, _ResultPath: [*c]u8) void;
pub extern fn _splitpath(_FullPath: [*c]const u8, _Drive: [*c]u8, _Dir: [*c]u8, _Filename: [*c]u8, _Ext: [*c]u8) void;
pub extern fn _swab(_Buf1: [*c]u8, _Buf2: [*c]u8, _SizeInBytes: c_int) void;
pub extern fn _wfullpath(_FullPath: [*c]wchar_t, _Path: [*c]const wchar_t, _SizeInWords: usize) [*c]wchar_t;
pub extern fn _wmakepath(_ResultPath: [*c]wchar_t, _Drive: [*c]const wchar_t, _Dir: [*c]const wchar_t, _Filename: [*c]const wchar_t, _Ext: [*c]const wchar_t) void;
pub extern fn _wperror(_ErrMsg: [*c]const wchar_t) void;
pub extern fn _wsearchenv(_Filename: [*c]const wchar_t, _EnvVar: [*c]const wchar_t, _ResultPath: [*c]wchar_t) void;
pub extern fn _wsplitpath(_FullPath: [*c]const wchar_t, _Drive: [*c]wchar_t, _Dir: [*c]wchar_t, _Filename: [*c]wchar_t, _Ext: [*c]wchar_t) void;
pub const _beep = @compileError("unable to resolve function type TypeClass.MacroQualified"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\stdlib.h:681:24
pub const _seterrormode = @compileError("unable to resolve function type TypeClass.MacroQualified"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\stdlib.h:683:24
pub const _sleep = @compileError("unable to resolve function type TypeClass.MacroQualified"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\stdlib.h:684:24
pub extern fn ecvt(_Val: f64, _NumOfDigits: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) [*c]u8;
pub extern fn fcvt(_Val: f64, _NumOfDec: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) [*c]u8;
pub extern fn gcvt(_Val: f64, _NumOfDigits: c_int, _DstBuf: [*c]u8) [*c]u8;
pub extern fn itoa(_Val: c_int, _DstBuf: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn ltoa(_Val: c_long, _DstBuf: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn putenv(_EnvString: [*c]const u8) c_int;
pub extern fn swab(_Buf1: [*c]u8, _Buf2: [*c]u8, _SizeInBytes: c_int) void;
pub extern fn ultoa(_Val: c_ulong, _Dstbuf: [*c]u8, _Radix: c_int) [*c]u8;
pub extern fn onexit(_Func: _onexit_t) _onexit_t;
pub const lldiv_t = extern struct {
quot: c_longlong,
rem: c_longlong,
};
pub extern fn lldiv(c_longlong, c_longlong) lldiv_t;
pub fn llabs(arg__j: c_longlong) callconv(.C) c_longlong {
var _j = arg__j;
return if (_j >= @bitCast(c_longlong, @as(c_longlong, @as(c_int, 0)))) _j else -_j;
}
pub extern fn strtoll([*c]const u8, [*c][*c]u8, c_int) c_longlong;
pub extern fn strtoull([*c]const u8, [*c][*c]u8, c_int) c_ulonglong;
pub fn atoll(arg__c: [*c]const u8) callconv(.C) c_longlong {
var _c = arg__c;
return _atoi64(_c);
}
pub fn wtoll(arg__w: [*c]const wchar_t) callconv(.C) c_longlong {
var _w = arg__w;
return _wtoi64(_w);
}
pub fn lltoa(arg__n: c_longlong, arg__c: [*c]u8, arg__i: c_int) callconv(.C) [*c]u8 {
var _n = arg__n;
var _c = arg__c;
var _i = arg__i;
return _i64toa(_n, _c, _i);
}
pub fn ulltoa(arg__n: c_ulonglong, arg__c: [*c]u8, arg__i: c_int) callconv(.C) [*c]u8 {
var _n = arg__n;
var _c = arg__c;
var _i = arg__i;
return _ui64toa(_n, _c, _i);
}
pub fn lltow(arg__n: c_longlong, arg__w: [*c]wchar_t, arg__i: c_int) callconv(.C) [*c]wchar_t {
var _n = arg__n;
var _w = arg__w;
var _i = arg__i;
return _i64tow(_n, _w, _i);
}
pub fn ulltow(arg__n: c_ulonglong, arg__w: [*c]wchar_t, arg__i: c_int) callconv(.C) [*c]wchar_t {
var _n = arg__n;
var _w = arg__w;
var _i = arg__i;
return _ui64tow(_n, _w, _i);
}
pub extern fn bsearch_s(_Key: ?*const c_void, _Base: ?*const c_void, _NumOfElements: rsize_t, _SizeOfElements: rsize_t, _PtFuncCompare: ?fn (?*c_void, ?*const c_void, ?*const c_void) callconv(.C) c_int, _Context: ?*c_void) ?*c_void;
pub extern fn _dupenv_s(_PBuffer: [*c][*c]u8, _PBufferSizeInBytes: [*c]usize, _VarName: [*c]const u8) errno_t;
pub extern fn getenv_s(_ReturnSize: [*c]usize, _DstBuf: [*c]u8, _DstSize: rsize_t, _VarName: [*c]const u8) errno_t;
pub extern fn _itoa_s(_Value: c_int, _DstBuf: [*c]u8, _Size: usize, _Radix: c_int) errno_t;
pub extern fn _i64toa_s(_Val: c_longlong, _DstBuf: [*c]u8, _Size: usize, _Radix: c_int) errno_t;
pub extern fn _ui64toa_s(_Val: c_ulonglong, _DstBuf: [*c]u8, _Size: usize, _Radix: c_int) errno_t;
pub extern fn _ltoa_s(_Val: c_long, _DstBuf: [*c]u8, _Size: usize, _Radix: c_int) errno_t;
pub extern fn mbstowcs_s(_PtNumOfCharConverted: [*c]usize, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _SrcBuf: [*c]const u8, _MaxCount: usize) errno_t;
pub extern fn _mbstowcs_s_l(_PtNumOfCharConverted: [*c]usize, _DstBuf: [*c]wchar_t, _SizeInWords: usize, _SrcBuf: [*c]const u8, _MaxCount: usize, _Locale: _locale_t) errno_t;
pub extern fn _ultoa_s(_Val: c_ulong, _DstBuf: [*c]u8, _Size: usize, _Radix: c_int) errno_t;
pub extern fn wctomb_s(_SizeConverted: [*c]c_int, _MbCh: [*c]u8, _SizeInBytes: rsize_t, _WCh: wchar_t) errno_t;
pub extern fn _wctomb_s_l(_SizeConverted: [*c]c_int, _MbCh: [*c]u8, _SizeInBytes: usize, _WCh: wchar_t, _Locale: _locale_t) errno_t;
pub extern fn wcstombs_s(_PtNumOfCharConverted: [*c]usize, _Dst: [*c]u8, _DstSizeInBytes: usize, _Src: [*c]const wchar_t, _MaxCountInBytes: usize) errno_t;
pub extern fn _wcstombs_s_l(_PtNumOfCharConverted: [*c]usize, _Dst: [*c]u8, _DstSizeInBytes: usize, _Src: [*c]const wchar_t, _MaxCountInBytes: usize, _Locale: _locale_t) errno_t;
pub extern fn _ecvt_s(_DstBuf: [*c]u8, _Size: usize, _Val: f64, _NumOfDights: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) errno_t;
pub extern fn _fcvt_s(_DstBuf: [*c]u8, _Size: usize, _Val: f64, _NumOfDec: c_int, _PtDec: [*c]c_int, _PtSign: [*c]c_int) errno_t;
pub extern fn _gcvt_s(_DstBuf: [*c]u8, _Size: usize, _Val: f64, _NumOfDigits: c_int) errno_t;
pub extern fn _makepath_s(_PathResult: [*c]u8, _Size: usize, _Drive: [*c]const u8, _Dir: [*c]const u8, _Filename: [*c]const u8, _Ext: [*c]const u8) errno_t;
pub extern fn _putenv_s(_Name: [*c]const u8, _Value: [*c]const u8) errno_t;
pub extern fn _searchenv_s(_Filename: [*c]const u8, _EnvVar: [*c]const u8, _ResultPath: [*c]u8, _SizeInBytes: usize) errno_t;
pub extern fn _splitpath_s(_FullPath: [*c]const u8, _Drive: [*c]u8, _DriveSize: usize, _Dir: [*c]u8, _DirSize: usize, _Filename: [*c]u8, _FilenameSize: usize, _Ext: [*c]u8, _ExtSize: usize) errno_t;
pub extern fn qsort_s(_Base: ?*c_void, _NumOfElements: usize, _SizeOfElements: usize, _PtFuncCompare: ?fn (?*c_void, ?*const c_void, ?*const c_void) callconv(.C) c_int, _Context: ?*c_void) void;
pub const struct__heapinfo = extern struct {
_pentry: [*c]c_int,
_size: usize,
_useflag: c_int,
};
pub const _HEAPINFO = struct__heapinfo;
pub extern var _amblksiz: c_uint;
pub extern fn __mingw_aligned_malloc(_Size: usize, _Alignment: usize) ?*c_void;
pub extern fn __mingw_aligned_free(_Memory: ?*c_void) void;
pub extern fn __mingw_aligned_offset_realloc(_Memory: ?*c_void, _Size: usize, _Alignment: usize, _Offset: usize) ?*c_void;
pub extern fn __mingw_aligned_realloc(_Memory: ?*c_void, _Size: usize, _Offset: usize) ?*c_void;
pub extern fn _resetstkoflw() c_int;
pub extern fn _set_malloc_crt_max_wait(_NewValue: c_ulong) c_ulong;
pub extern fn _expand(_Memory: ?*c_void, _NewSize: usize) ?*c_void;
pub extern fn _msize(_Memory: ?*c_void) usize;
pub extern fn _get_sbh_threshold() usize;
pub extern fn _set_sbh_threshold(_NewValue: usize) c_int;
pub extern fn _set_amblksiz(_Value: usize) errno_t;
pub extern fn _get_amblksiz(_Value: [*c]usize) errno_t;
pub extern fn _heapadd(_Memory: ?*c_void, _Size: usize) c_int;
pub extern fn _heapchk() c_int;
pub extern fn _heapmin() c_int;
pub extern fn _heapset(_Fill: c_uint) c_int;
pub extern fn _heapwalk(_EntryInfo: [*c]_HEAPINFO) c_int;
pub extern fn _heapused(_Used: [*c]usize, _Commit: [*c]usize) usize;
pub extern fn _get_heap_handle() isize;
pub fn _MarkAllocaS(arg__Ptr: ?*c_void, arg__Marker: c_uint) callconv(.C) ?*c_void {
var _Ptr = arg__Ptr;
var _Marker = arg__Marker;
if (_Ptr != null) {
@ptrCast([*c]c_uint, @alignCast(@import("std").meta.alignment(c_uint), _Ptr)).?.* = _Marker;
_Ptr = @ptrCast(?*c_void, @ptrCast([*c]u8, @alignCast(@import("std").meta.alignment(u8), _Ptr)) + @bitCast(usize, @intCast(isize, @as(c_int, 16))));
}
return _Ptr;
}
pub fn _freea(arg__Memory: ?*c_void) callconv(.C) void {
var _Memory = arg__Memory;
var _Marker: c_uint = undefined;
if (_Memory != null) {
_Memory = @ptrCast(?*c_void, @ptrCast([*c]u8, @alignCast(@import("std").meta.alignment(u8), _Memory)) - @bitCast(usize, @intCast(isize, @as(c_int, 16))));
_Marker = @ptrCast([*c]c_uint, @alignCast(@import("std").meta.alignment(c_uint), _Memory)).?.*;
if (_Marker == @bitCast(c_uint, @as(c_int, 56797))) {
free(_Memory);
}
}
}
pub fn _mm_malloc(arg___size: usize, arg___align: usize) callconv(.C) ?*c_void {
var __size = arg___size;
var __align = arg___align;
if (__align == @bitCast(c_ulonglong, @as(c_longlong, @as(c_int, 1)))) {
return malloc(__size);
}
if (!((__align & (__align -% @bitCast(c_ulonglong, @as(c_longlong, @as(c_int, 1))))) != 0) and (__align < @sizeOf(?*c_void))) {
__align = @sizeOf(?*c_void);
}
var __mallocedMemory: ?*c_void = undefined;
__mallocedMemory = __mingw_aligned_malloc(__size, __align);
return __mallocedMemory;
}
pub fn _mm_free(arg___p: ?*c_void) callconv(.C) void {
var __p = arg___p;
__mingw_aligned_free(__p);
}
pub fn _mm_add_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] += __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_add_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4sf, __a) + @bitCast(__v4sf, __b));
}
pub fn _mm_sub_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] -= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_sub_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4sf, __a) - @bitCast(__v4sf, __b));
}
pub fn _mm_mul_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] *= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_mul_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4sf, __a) * @bitCast(__v4sf, __b));
}
pub fn _mm_div_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] /= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_div_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4sf, __a) / @bitCast(__v4sf, __b));
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:216:18: warning: TODO implement function '__builtin_ia32_sqrtss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:214:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sqrt_ss(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:233:10: warning: TODO implement function '__builtin_ia32_sqrtps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:231:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sqrt_ps(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:251:18: warning: TODO implement function '__builtin_ia32_rcpss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:249:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_rcp_ss(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:268:18: warning: TODO implement function '__builtin_ia32_rcpps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:266:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_rcp_ps(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:287:10: warning: TODO implement function '__builtin_ia32_rsqrtss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:285:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_rsqrt_ss(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:304:10: warning: TODO implement function '__builtin_ia32_rsqrtps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:302:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_rsqrt_ps(arg___a: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:327:10: warning: TODO implement function '__builtin_ia32_minss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:325:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:346:10: warning: TODO implement function '__builtin_ia32_minps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:344:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:369:10: warning: TODO implement function '__builtin_ia32_maxss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:367:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:388:10: warning: TODO implement function '__builtin_ia32_maxps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:386:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128;
pub fn _mm_and_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4su, __a) & @bitCast(__v4su, __b));
}
pub fn _mm_andnot_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, ~@bitCast(__v4su, __a) & @bitCast(__v4su, __b));
}
pub fn _mm_or_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4su, __a) | @bitCast(__v4su, __b));
}
pub fn _mm_xor_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128, @bitCast(__v4su, __a) ^ @bitCast(__v4su, __b));
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:487:18: warning: TODO implement function '__builtin_ia32_cmpeqss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:485:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:505:18: warning: TODO implement function '__builtin_ia32_cmpeqps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:503:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:528:18: warning: TODO implement function '__builtin_ia32_cmpltss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:526:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmplt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:547:18: warning: TODO implement function '__builtin_ia32_cmpltps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:545:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmplt_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:571:18: warning: TODO implement function '__builtin_ia32_cmpless' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:569:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmple_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:590:18: warning: TODO implement function '__builtin_ia32_cmpleps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:588:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmple_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:614:50: warning: TODO implement function '__builtin_ia32_cmpltss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:611:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:634:18: warning: TODO implement function '__builtin_ia32_cmpltps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:632:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:659:50: warning: TODO implement function '__builtin_ia32_cmpless' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:656:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpge_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:679:18: warning: TODO implement function '__builtin_ia32_cmpleps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:677:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpge_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:702:18: warning: TODO implement function '__builtin_ia32_cmpneqss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:700:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpneq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:721:18: warning: TODO implement function '__builtin_ia32_cmpneqps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:719:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpneq_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:745:18: warning: TODO implement function '__builtin_ia32_cmpnltss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:743:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnlt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:765:18: warning: TODO implement function '__builtin_ia32_cmpnltps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:763:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnlt_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:790:18: warning: TODO implement function '__builtin_ia32_cmpnless' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:788:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnle_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:810:18: warning: TODO implement function '__builtin_ia32_cmpnleps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:808:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnle_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:836:50: warning: TODO implement function '__builtin_ia32_cmpnltss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:833:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpngt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:857:18: warning: TODO implement function '__builtin_ia32_cmpnltps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:855:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpngt_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:883:50: warning: TODO implement function '__builtin_ia32_cmpnless' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:880:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnge_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:904:18: warning: TODO implement function '__builtin_ia32_cmpnleps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:902:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnge_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:929:18: warning: TODO implement function '__builtin_ia32_cmpordss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:927:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpord_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:949:18: warning: TODO implement function '__builtin_ia32_cmpordps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:947:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpord_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:974:18: warning: TODO implement function '__builtin_ia32_cmpunordss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:972:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpunord_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:994:18: warning: TODO implement function '__builtin_ia32_cmpunordps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:992:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpunord_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1018:10: warning: TODO implement function '__builtin_ia32_comieq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1016:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comieq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1043:10: warning: TODO implement function '__builtin_ia32_comilt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1041:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comilt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1067:10: warning: TODO implement function '__builtin_ia32_comile' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1065:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comile_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1091:10: warning: TODO implement function '__builtin_ia32_comigt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1089:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comigt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1115:10: warning: TODO implement function '__builtin_ia32_comige' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1113:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comige_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1139:10: warning: TODO implement function '__builtin_ia32_comineq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1137:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comineq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1163:10: warning: TODO implement function '__builtin_ia32_ucomieq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1161:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomieq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1187:10: warning: TODO implement function '__builtin_ia32_ucomilt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1185:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomilt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1212:10: warning: TODO implement function '__builtin_ia32_ucomile' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1210:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomile_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1237:10: warning: TODO implement function '__builtin_ia32_ucomigt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1235:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomigt_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1262:10: warning: TODO implement function '__builtin_ia32_ucomige' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1260:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomige_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1286:10: warning: TODO implement function '__builtin_ia32_ucomineq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1284:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomineq_ss(arg___a: __m128, arg___b: __m128) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1304:10: warning: TODO implement function '__builtin_ia32_cvtss2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1302:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtss_si32(arg___a: __m128) callconv(.C) c_int;
pub fn _mm_cvt_ss2si(arg___a: __m128) callconv(.C) c_int {
var __a = arg___a;
return _mm_cvtss_si32(__a);
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1342:10: warning: TODO implement function '__builtin_ia32_cvtss2si64' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1340:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtss_si64(arg___a: __m128) callconv(.C) c_longlong; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1360:17: warning: TODO implement function '__builtin_ia32_cvtps2pi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1358:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtps_pi32(arg___a: __m128) callconv(.C) __m64;
pub fn _mm_cvt_ps2pi(arg___a: __m128) callconv(.C) __m64 {
var __a = arg___a;
return _mm_cvtps_pi32(__a);
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1395:10: warning: TODO implement function '__builtin_ia32_cvttss2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1393:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttss_si32(arg___a: __m128) callconv(.C) c_int;
pub fn _mm_cvtt_ss2si(arg___a: __m128) callconv(.C) c_int {
var __a = arg___a;
return _mm_cvttss_si32(__a);
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1434:10: warning: TODO implement function '__builtin_ia32_cvttss2si64' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1432:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttss_si64(arg___a: __m128) callconv(.C) c_longlong; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1453:17: warning: TODO implement function '__builtin_ia32_cvttps2pi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1451:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttps_pi32(arg___a: __m128) callconv(.C) __m64;
pub fn _mm_cvtt_ps2pi(arg___a: __m128) callconv(.C) __m64 {
var __a = arg___a;
return _mm_cvttps_pi32(__a);
}
pub fn _mm_cvtsi32_ss(arg___a: __m128, arg___b: c_int) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = @intToFloat(f32, __b);
return __a;
}
pub fn _mm_cvt_si2ss(arg___a: __m128, arg___b: c_int) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return _mm_cvtsi32_ss(__a, __b);
}
pub fn _mm_cvtsi64_ss(arg___a: __m128, arg___b: c_longlong) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = @intToFloat(f32, __b);
return __a;
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1565:10: warning: TODO implement function '__builtin_ia32_cvtpi2ps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1563:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtpi32_ps(arg___a: __m128, arg___b: __m64) callconv(.C) __m128;
pub fn _mm_cvt_pi2ps(arg___a: __m128, arg___b: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return _mm_cvtpi32_ps(__a, __b);
}
pub fn _mm_cvtss_f32(arg___a: __m128) callconv(.C) f32 {
var __a = arg___a;
return __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_loadh_pi(arg___a: __m128, arg___p: [*c]const __m64) callconv(.C) __m128 {
var __a = arg___a;
var __p = arg___p;
const __mm_loadh_pi_v2f32 = @import("std").meta.Vector(2, f32);
const struct___mm_loadh_pi_struct = packed struct {
__u: __mm_loadh_pi_v2f32,
};
var __b: __mm_loadh_pi_v2f32 = @ptrCast([*c]const struct___mm_loadh_pi_struct, @alignCast(@import("std").meta.alignment(struct___mm_loadh_pi_struct), __p)).*.__u;
var __bb: __m128 = @shuffle(@typeInfo(@TypeOf(__b)).Vector.child, __b, __b, comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__b)).Vector.len),
});
return @shuffle(@typeInfo(@TypeOf(__a)).Vector.child, __a, __bb, comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(__a)).Vector.len),
});
}
pub fn _mm_loadl_pi(arg___a: __m128, arg___p: [*c]const __m64) callconv(.C) __m128 {
var __a = arg___a;
var __p = arg___p;
const __mm_loadl_pi_v2f32 = @import("std").meta.Vector(2, f32);
const struct___mm_loadl_pi_struct = packed struct {
__u: __mm_loadl_pi_v2f32,
};
var __b: __mm_loadl_pi_v2f32 = @ptrCast([*c]const struct___mm_loadl_pi_struct, @alignCast(@import("std").meta.alignment(struct___mm_loadl_pi_struct), __p)).*.__u;
var __bb: __m128 = @shuffle(@typeInfo(@TypeOf(__b)).Vector.child, __b, __b, comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__b)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__b)).Vector.len),
});
return @shuffle(@typeInfo(@TypeOf(__a)).Vector.child, __a, __bb, comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(__a)).Vector.len),
});
}
pub fn _mm_load_ss(arg___p: [*c]const f32) callconv(.C) __m128 {
var __p = arg___p;
const struct___mm_load_ss_struct = packed struct {
__u: f32,
};
var __u: f32 = @ptrCast([*c]const struct___mm_load_ss_struct, @alignCast(@import("std").meta.alignment(struct___mm_load_ss_struct), __p)).*.__u;
return blk: {
const tmp = __u;
const tmp_1 = @intToFloat(f32, @as(c_int, 0));
const tmp_2 = @intToFloat(f32, @as(c_int, 0));
const tmp_3 = @intToFloat(f32, @as(c_int, 0));
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_load1_ps(arg___p: [*c]const f32) callconv(.C) __m128 {
var __p = arg___p;
const struct___mm_load1_ps_struct = packed struct {
__u: f32,
};
var __u: f32 = @ptrCast([*c]const struct___mm_load1_ps_struct, @alignCast(@import("std").meta.alignment(struct___mm_load1_ps_struct), __p)).*.__u;
return blk: {
const tmp = __u;
const tmp_1 = __u;
const tmp_2 = __u;
const tmp_3 = __u;
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_load_ps(arg___p: [*c]const f32) callconv(.C) __m128 {
var __p = arg___p;
return @ptrCast([*c]const __m128, @alignCast(@import("std").meta.alignment(__m128), __p)).?.*;
}
pub fn _mm_loadu_ps(arg___p: [*c]const f32) callconv(.C) __m128 {
var __p = arg___p;
const struct___loadu_ps = packed struct {
__v: __m128_u,
};
return @ptrCast([*c]const struct___loadu_ps, @alignCast(@import("std").meta.alignment(struct___loadu_ps), __p)).*.__v;
}
pub fn _mm_loadr_ps(arg___p: [*c]const f32) callconv(.C) __m128 {
var __p = arg___p;
var __a: __m128 = _mm_load_ps(__p);
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __a), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1778:18: warning: TODO implement function '__builtin_ia32_undef128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:1776:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_undefined_ps() callconv(.C) __m128;
pub fn _mm_set_ss(arg___w: f32) callconv(.C) __m128 {
var __w = arg___w;
return blk: {
const tmp = __w;
const tmp_1 = @intToFloat(f32, @as(c_int, 0));
const tmp_2 = @intToFloat(f32, @as(c_int, 0));
const tmp_3 = @intToFloat(f32, @as(c_int, 0));
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_set1_ps(arg___w: f32) callconv(.C) __m128 {
var __w = arg___w;
return blk: {
const tmp = __w;
const tmp_1 = __w;
const tmp_2 = __w;
const tmp_3 = __w;
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_set_ps1(arg___w: f32) callconv(.C) __m128 {
var __w = arg___w;
return _mm_set1_ps(__w);
}
pub fn _mm_set_ps(arg___z: f32, arg___y: f32, arg___x: f32, arg___w: f32) callconv(.C) __m128 {
var __z = arg___z;
var __y = arg___y;
var __x = arg___x;
var __w = arg___w;
return blk: {
const tmp = __w;
const tmp_1 = __x;
const tmp_2 = __y;
const tmp_3 = __z;
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_setr_ps(arg___z: f32, arg___y: f32, arg___x: f32, arg___w: f32) callconv(.C) __m128 {
var __z = arg___z;
var __y = arg___y;
var __x = arg___x;
var __w = arg___w;
return blk: {
const tmp = __z;
const tmp_1 = __y;
const tmp_2 = __x;
const tmp_3 = __w;
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_setzero_ps() callconv(.C) __m128 {
return blk: {
const tmp = @intToFloat(f32, @as(c_int, 0));
const tmp_1 = @intToFloat(f32, @as(c_int, 0));
const tmp_2 = @intToFloat(f32, @as(c_int, 0));
const tmp_3 = @intToFloat(f32, @as(c_int, 0));
break :blk __m128{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
};
}
pub fn _mm_storeh_pi(arg___p: [*c]__m64, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
const __mm_storeh_pi_v2f32 = @import("std").meta.Vector(2, f32);
const struct___mm_storeh_pi_struct = packed struct {
__u: __mm_storeh_pi_v2f32,
};
@ptrCast([*c]struct___mm_storeh_pi_struct, @alignCast(@import("std").meta.alignment(struct___mm_storeh_pi_struct), __p)).*.__u = @shuffle(@typeInfo(@TypeOf(__a)).Vector.child, __a, __a, comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(__a)).Vector.len),
});
}
pub fn _mm_storel_pi(arg___p: [*c]__m64, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
const __mm_storeh_pi_v2f32 = @import("std").meta.Vector(2, f32);
const struct___mm_storeh_pi_struct = packed struct {
__u: __mm_storeh_pi_v2f32,
};
@ptrCast([*c]struct___mm_storeh_pi_struct, @alignCast(@import("std").meta.alignment(struct___mm_storeh_pi_struct), __p)).*.__u = @shuffle(@typeInfo(@TypeOf(__a)).Vector.child, __a, __a, comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(__a)).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(__a)).Vector.len),
});
}
pub fn _mm_store_ss(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
const struct___mm_store_ss_struct = packed struct {
__u: f32,
};
@ptrCast([*c]struct___mm_store_ss_struct, @alignCast(@import("std").meta.alignment(struct___mm_store_ss_struct), __p)).*.__u = __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_storeu_ps(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
const struct___storeu_ps = packed struct {
__v: __m128_u,
};
@ptrCast([*c]struct___storeu_ps, @alignCast(@import("std").meta.alignment(struct___storeu_ps), __p)).*.__v = __a;
}
pub fn _mm_store_ps(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
@ptrCast([*c]__m128, @alignCast(@import("std").meta.alignment(__m128), __p)).?.* = __a;
}
pub fn _mm_store1_ps(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
__a = @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __a), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
_mm_store_ps(__p, __a);
}
pub fn _mm_store_ps1(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
_mm_store1_ps(__p, __a);
}
pub fn _mm_storer_ps(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
__a = @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __a), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
_mm_store_ps(__p, __a);
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2122:3: warning: TODO implement function '__builtin_ia32_movntq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2120:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_pi(arg___p: [*c]__m64, arg___a: __m64) callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2141:3: warning: TODO implement function '__builtin_nontemporal_store' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2139:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_ps(arg___p: [*c]f32, arg___a: __m128) callconv(.C) void;
pub extern fn _mm_sfence() void; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2233:17: warning: TODO implement function '__builtin_ia32_pmaxsw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2231:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_pi16(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2252:17: warning: TODO implement function '__builtin_ia32_pmaxub' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2250:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_pu8(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2271:17: warning: TODO implement function '__builtin_ia32_pminsw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2269:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_pi16(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2290:17: warning: TODO implement function '__builtin_ia32_pminub' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2288:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_pu8(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2308:10: warning: TODO implement function '__builtin_ia32_pmovmskb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2306:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_movemask_pi8(arg___a: __m64) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2327:17: warning: TODO implement function '__builtin_ia32_pmulhuw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2325:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mulhi_pu16(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2390:3: warning: TODO implement function '__builtin_ia32_maskmovq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2388:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_maskmove_si64(arg___d: __m64, arg___n: __m64, arg___p: [*c]u8) callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2409:17: warning: TODO implement function '__builtin_ia32_pavgb' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2407:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_avg_pu8(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2428:17: warning: TODO implement function '__builtin_ia32_pavgw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2426:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_avg_pu16(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2450:17: warning: TODO implement function '__builtin_ia32_psadbw' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2448:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sad_pu8(arg___a: __m64, arg___b: __m64) callconv(.C) __m64;
pub extern fn _mm_getcsr() c_uint;
pub extern fn _mm_setcsr(__i: c_uint) void;
pub fn _mm_unpackhi_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(6, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(7, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
}
pub fn _mm_unpacklo_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
}
pub fn _mm_move_ss(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_movehl_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(6, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(7, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
}
pub fn _mm_movelh_ps(arg___a: __m128, arg___b: __m128) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
});
}
pub fn _mm_cvtpi16_ps(arg___a: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b: __m64 = undefined;
var __c: __m64 = undefined;
var __r: __m128 = undefined;
__b = _mm_setzero_si64();
__b = _mm_cmpgt_pi16(__b, __a);
__c = _mm_unpackhi_pi16(__a, __b);
__r = _mm_setzero_ps();
__r = _mm_cvtpi32_ps(__r, __c);
__r = _mm_movelh_ps(__r, __r);
__c = _mm_unpacklo_pi16(__a, __b);
__r = _mm_cvtpi32_ps(__r, __c);
return __r;
}
pub fn _mm_cvtpu16_ps(arg___a: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b: __m64 = undefined;
var __c: __m64 = undefined;
var __r: __m128 = undefined;
__b = _mm_setzero_si64();
__c = _mm_unpackhi_pi16(__a, __b);
__r = _mm_setzero_ps();
__r = _mm_cvtpi32_ps(__r, __c);
__r = _mm_movelh_ps(__r, __r);
__c = _mm_unpacklo_pi16(__a, __b);
__r = _mm_cvtpi32_ps(__r, __c);
return __r;
}
pub fn _mm_cvtpi8_ps(arg___a: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b: __m64 = undefined;
__b = _mm_setzero_si64();
__b = _mm_cmpgt_pi8(__b, __a);
__b = _mm_unpacklo_pi8(__a, __b);
return _mm_cvtpi16_ps(__b);
}
pub fn _mm_cvtpu8_ps(arg___a: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b: __m64 = undefined;
__b = _mm_setzero_si64();
__b = _mm_unpacklo_pi8(__a, __b);
return _mm_cvtpi16_ps(__b);
}
pub fn _mm_cvtpi32x2_ps(arg___a: __m64, arg___b: __m64) callconv(.C) __m128 {
var __a = arg___a;
var __b = arg___b;
var __c: __m128 = undefined;
__c = _mm_setzero_ps();
__c = _mm_cvtpi32_ps(__c, __b);
__c = _mm_movelh_ps(__c, __c);
return _mm_cvtpi32_ps(__c, __a);
}
pub fn _mm_cvtps_pi16(arg___a: __m128) callconv(.C) __m64 {
var __a = arg___a;
var __b: __m64 = undefined;
var __c: __m64 = undefined;
__b = _mm_cvtps_pi32(__a);
__a = _mm_movehl_ps(__a, __a);
__c = _mm_cvtps_pi32(__a);
return _mm_packs_pi32(__b, __c);
}
pub fn _mm_cvtps_pi8(arg___a: __m128) callconv(.C) __m64 {
var __a = arg___a;
var __b: __m64 = undefined;
var __c: __m64 = undefined;
__b = _mm_cvtps_pi16(__a);
__c = _mm_setzero_si64();
return _mm_packs_pi16(__b, __c);
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2926:10: warning: TODO implement function '__builtin_ia32_movmskps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2924:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_movemask_ps(arg___a: __m128) callconv(.C) c_int;
pub const __m128d = @import("std").meta.Vector(2, f64);
pub const __m128i = @import("std").meta.Vector(2, c_longlong);
pub const __m128d_u = @import("std").meta.Vector(2, f64);
pub const __m128i_u = @import("std").meta.Vector(2, c_longlong);
pub const __v2df = @import("std").meta.Vector(2, f64);
pub const __v2di = @import("std").meta.Vector(2, c_longlong);
pub const __v8hi = @import("std").meta.Vector(8, c_short);
pub const __v16qi = @import("std").meta.Vector(16, u8);
pub const __v2du = @import("std").meta.Vector(2, c_ulonglong);
pub const __v8hu = @import("std").meta.Vector(8, c_ushort);
pub const __v16qu = @import("std").meta.Vector(16, u8);
pub const __v16qs = @import("std").meta.Vector(16, i8);
pub fn _mm_add_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] += __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_add_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2df, __a) + @bitCast(__v2df, __b));
}
pub fn _mm_sub_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] -= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_sub_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2df, __a) - @bitCast(__v2df, __b));
}
pub fn _mm_mul_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] *= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_mul_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2df, __a) * @bitCast(__v2df, __b));
}
pub fn _mm_div_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] /= __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_div_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2df, __a) / @bitCast(__v2df, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:228:17: warning: TODO implement function '__builtin_ia32_sqrtsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:226:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sqrt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:246:10: warning: TODO implement function '__builtin_ia32_sqrtpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:244:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sqrt_pd(arg___a: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:270:10: warning: TODO implement function '__builtin_ia32_minsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:268:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:290:10: warning: TODO implement function '__builtin_ia32_minpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:288:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:314:10: warning: TODO implement function '__builtin_ia32_maxsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:312:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:334:10: warning: TODO implement function '__builtin_ia32_maxpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:332:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d;
pub fn _mm_and_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2du, __a) & @bitCast(__v2du, __b));
}
pub fn _mm_andnot_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, ~@bitCast(__v2du, __a) & @bitCast(__v2du, __b));
}
pub fn _mm_or_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2du, __a) | @bitCast(__v2du, __b));
}
pub fn _mm_xor_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128d, @bitCast(__v2du, __a) ^ @bitCast(__v2du, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:428:19: warning: TODO implement function '__builtin_ia32_cmpeqpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:426:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:448:19: warning: TODO implement function '__builtin_ia32_cmpltpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:446:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmplt_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:469:19: warning: TODO implement function '__builtin_ia32_cmplepd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:467:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmple_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:490:19: warning: TODO implement function '__builtin_ia32_cmpltpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:488:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:511:19: warning: TODO implement function '__builtin_ia32_cmplepd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:509:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpge_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:534:19: warning: TODO implement function '__builtin_ia32_cmpordpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:532:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpord_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:558:19: warning: TODO implement function '__builtin_ia32_cmpunordpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:556:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpunord_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:579:19: warning: TODO implement function '__builtin_ia32_cmpneqpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:577:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpneq_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:600:19: warning: TODO implement function '__builtin_ia32_cmpnltpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:598:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnlt_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:621:19: warning: TODO implement function '__builtin_ia32_cmpnlepd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:619:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnle_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:642:19: warning: TODO implement function '__builtin_ia32_cmpnltpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:640:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpngt_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:663:19: warning: TODO implement function '__builtin_ia32_cmpnlepd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:661:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnge_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:686:19: warning: TODO implement function '__builtin_ia32_cmpeqsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:684:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpeq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:711:19: warning: TODO implement function '__builtin_ia32_cmpltsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:709:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmplt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:736:19: warning: TODO implement function '__builtin_ia32_cmplesd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:734:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmple_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:761:17: warning: TODO implement function '__builtin_ia32_cmpltsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:759:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpgt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:787:17: warning: TODO implement function '__builtin_ia32_cmplesd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:785:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpge_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:815:19: warning: TODO implement function '__builtin_ia32_cmpordsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:813:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpord_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:843:19: warning: TODO implement function '__builtin_ia32_cmpunordsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:841:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpunord_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:868:19: warning: TODO implement function '__builtin_ia32_cmpneqsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:866:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpneq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:893:19: warning: TODO implement function '__builtin_ia32_cmpnltsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:891:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnlt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:918:19: warning: TODO implement function '__builtin_ia32_cmpnlesd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:916:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnle_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:943:17: warning: TODO implement function '__builtin_ia32_cmpnltsd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:941:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpngt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:969:17: warning: TODO implement function '__builtin_ia32_cmpnlesd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:967:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cmpnge_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:994:10: warning: TODO implement function '__builtin_ia32_comisdeq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:992:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comieq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1020:10: warning: TODO implement function '__builtin_ia32_comisdlt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1018:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comilt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1046:10: warning: TODO implement function '__builtin_ia32_comisdle' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1044:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comile_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1072:10: warning: TODO implement function '__builtin_ia32_comisdgt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1070:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comigt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1098:10: warning: TODO implement function '__builtin_ia32_comisdge' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1096:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comige_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1124:10: warning: TODO implement function '__builtin_ia32_comisdneq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1122:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_comineq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1148:10: warning: TODO implement function '__builtin_ia32_ucomisdeq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1146:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomieq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1174:10: warning: TODO implement function '__builtin_ia32_ucomisdlt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1172:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomilt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1200:10: warning: TODO implement function '__builtin_ia32_ucomisdle' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1198:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomile_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1226:10: warning: TODO implement function '__builtin_ia32_ucomisdgt' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1224:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomigt_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1252:10: warning: TODO implement function '__builtin_ia32_ucomisdge' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1250:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomige_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1278:10: warning: TODO implement function '__builtin_ia32_ucomisdneq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1276:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_ucomineq_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1297:10: warning: TODO implement function '__builtin_ia32_cvtpd2ps' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1295:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtpd_ps(arg___a: __m128d) callconv(.C) __m128;
pub fn _mm_cvtps_pd(arg___a: __m128) callconv(.C) __m128d {
var __a = arg___a;
return @bitCast(__m128d, blk: {
const tmp = @floatCast(f64, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
})[0]);
const tmp_1 = @floatCast(f64, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.child, @bitCast(__v4sf, __a), @bitCast(__v4sf, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4sf, __a))).Vector.len),
})[1]);
break :blk __v2df{
tmp,
tmp_1,
};
});
}
pub fn _mm_cvtepi32_pd(arg___a: __m128i) callconv(.C) __m128d {
var __a = arg___a;
return @bitCast(__m128d, blk: {
const tmp = @intToFloat(f64, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.child, @bitCast(__v4si, __a), @bitCast(__v4si, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
})[0]);
const tmp_1 = @intToFloat(f64, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.child, @bitCast(__v4si, __a), @bitCast(__v4si, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
})[1]);
break :blk __v2df{
tmp,
tmp_1,
};
});
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1360:10: warning: TODO implement function '__builtin_ia32_cvtpd2dq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1358:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtpd_epi32(arg___a: __m128d) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1377:10: warning: TODO implement function '__builtin_ia32_cvtsd2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1375:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtsd_si32(arg___a: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1402:18: warning: TODO implement function '__builtin_ia32_cvtsd2ss' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1400:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtsd_ss(arg___a: __m128, arg___b: __m128d) callconv(.C) __m128;
pub fn _mm_cvtsi32_sd(arg___a: __m128d, arg___b: c_int) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = @intToFloat(f64, __b);
return __a;
}
pub fn _mm_cvtss_sd(arg___a: __m128d, arg___b: __m128) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = @floatCast(f64, __b[@intCast(c_uint, @as(c_int, 0))]);
return __a;
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1475:19: warning: TODO implement function '__builtin_ia32_cvttpd2dq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1473:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttpd_epi32(arg___a: __m128d) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1493:10: warning: TODO implement function '__builtin_ia32_cvttsd2si' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1491:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttsd_si32(arg___a: __m128d) callconv(.C) c_int; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1510:17: warning: TODO implement function '__builtin_ia32_cvtpd2pi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1508:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtpd_pi32(arg___a: __m128d) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1530:17: warning: TODO implement function '__builtin_ia32_cvttpd2pi' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1528:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttpd_pi32(arg___a: __m128d) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1547:10: warning: TODO implement function '__builtin_ia32_cvtpi2pd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1545:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtpi32_pd(arg___a: __m64) callconv(.C) __m128d;
pub fn _mm_cvtsd_f64(arg___a: __m128d) callconv(.C) f64 {
var __a = arg___a;
return __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_load_pd(arg___dp: [*c]const f64) callconv(.C) __m128d {
var __dp = arg___dp;
return @ptrCast([*c]const __m128d, @alignCast(@import("std").meta.alignment(__m128d), __dp)).?.*;
}
pub fn _mm_load1_pd(arg___dp: [*c]const f64) callconv(.C) __m128d {
var __dp = arg___dp;
const struct___mm_load1_pd_struct = packed struct {
__u: f64,
};
var __u: f64 = @ptrCast([*c]const struct___mm_load1_pd_struct, @alignCast(@import("std").meta.alignment(struct___mm_load1_pd_struct), __dp)).*.__u;
return blk: {
const tmp = __u;
const tmp_1 = __u;
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_loadr_pd(arg___dp: [*c]const f64) callconv(.C) __m128d {
var __dp = arg___dp;
var __u: __m128d = @ptrCast([*c]const __m128d, @alignCast(@import("std").meta.alignment(__m128d), __dp)).?.*;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v2df, __u))).Vector.child, @bitCast(__v2df, __u), @bitCast(__v2df, __u), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v2df, __u))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2df, __u))).Vector.len),
});
}
pub fn _mm_loadu_pd(arg___dp: [*c]const f64) callconv(.C) __m128d {
var __dp = arg___dp;
const struct___loadu_pd = packed struct {
__v: __m128d_u,
};
return @ptrCast([*c]const struct___loadu_pd, @alignCast(@import("std").meta.alignment(struct___loadu_pd), __dp)).*.__v;
}
pub fn _mm_loadu_si64(arg___a: ?*const c_void) callconv(.C) __m128i {
var __a = arg___a;
const struct___loadu_si64 = packed struct {
__v: c_longlong,
};
var __u: c_longlong = @ptrCast([*c]const struct___loadu_si64, @alignCast(@import("std").meta.alignment(struct___loadu_si64), __a)).*.__v;
return @bitCast(__m128i, blk: {
const tmp = __u;
const tmp_1 = @as(c_longlong, 0);
break :blk __v2di{
tmp,
tmp_1,
};
});
}
pub fn _mm_loadu_si32(arg___a: ?*const c_void) callconv(.C) __m128i {
var __a = arg___a;
const struct___loadu_si32 = packed struct {
__v: c_int,
};
var __u: c_int = @ptrCast([*c]const struct___loadu_si32, @alignCast(@import("std").meta.alignment(struct___loadu_si32), __a)).*.__v;
return @bitCast(__m128i, blk: {
const tmp = __u;
const tmp_1 = @as(c_int, 0);
const tmp_2 = @as(c_int, 0);
const tmp_3 = @as(c_int, 0);
break :blk __v4si{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
});
}
pub fn _mm_loadu_si16(arg___a: ?*const c_void) callconv(.C) __m128i {
var __a = arg___a;
const struct___loadu_si16 = packed struct {
__v: c_short,
};
var __u: c_short = @ptrCast([*c]const struct___loadu_si16, @alignCast(@import("std").meta.alignment(struct___loadu_si16), __a)).*.__v;
return @bitCast(__m128i, blk: {
const tmp = __u;
const tmp_1 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_2 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_3 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_4 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_5 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_6 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
const tmp_7 = @bitCast(c_short, @truncate(c_short, @as(c_int, 0)));
break :blk __v8hi{
tmp,
tmp_1,
tmp_2,
tmp_3,
tmp_4,
tmp_5,
tmp_6,
tmp_7,
};
});
}
pub fn _mm_load_sd(arg___dp: [*c]const f64) callconv(.C) __m128d {
var __dp = arg___dp;
const struct___mm_load_sd_struct = packed struct {
__u: f64,
};
var __u: f64 = @ptrCast([*c]const struct___mm_load_sd_struct, @alignCast(@import("std").meta.alignment(struct___mm_load_sd_struct), __dp)).*.__u;
return blk: {
const tmp = __u;
const tmp_1 = @intToFloat(f64, @as(c_int, 0));
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_loadh_pd(arg___a: __m128d, arg___dp: [*c]const f64) callconv(.C) __m128d {
var __a = arg___a;
var __dp = arg___dp;
const struct___mm_loadh_pd_struct = packed struct {
__u: f64,
};
var __u: f64 = @ptrCast([*c]const struct___mm_loadh_pd_struct, @alignCast(@import("std").meta.alignment(struct___mm_loadh_pd_struct), __dp)).*.__u;
return blk: {
const tmp = __a[@intCast(c_uint, @as(c_int, 0))];
const tmp_1 = __u;
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_loadl_pd(arg___a: __m128d, arg___dp: [*c]const f64) callconv(.C) __m128d {
var __a = arg___a;
var __dp = arg___dp;
const struct___mm_loadl_pd_struct = packed struct {
__u: f64,
};
var __u: f64 = @ptrCast([*c]const struct___mm_loadl_pd_struct, @alignCast(@import("std").meta.alignment(struct___mm_loadl_pd_struct), __dp)).*.__u;
return blk: {
const tmp = __u;
const tmp_1 = __a[@intCast(c_uint, @as(c_int, 1))];
break :blk __m128d{
tmp,
tmp_1,
};
};
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1801:19: warning: TODO implement function '__builtin_ia32_undef128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:1799:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_undefined_pd() callconv(.C) __m128d;
pub fn _mm_set_sd(arg___w: f64) callconv(.C) __m128d {
var __w = arg___w;
return blk: {
const tmp = __w;
const tmp_1 = @intToFloat(f64, @as(c_int, 0));
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_set1_pd(arg___w: f64) callconv(.C) __m128d {
var __w = arg___w;
return blk: {
const tmp = __w;
const tmp_1 = __w;
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_set_pd1(arg___w: f64) callconv(.C) __m128d {
var __w = arg___w;
return _mm_set1_pd(__w);
}
pub fn _mm_set_pd(arg___w: f64, arg___x: f64) callconv(.C) __m128d {
var __w = arg___w;
var __x = arg___x;
return blk: {
const tmp = __x;
const tmp_1 = __w;
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_setr_pd(arg___w: f64, arg___x: f64) callconv(.C) __m128d {
var __w = arg___w;
var __x = arg___x;
return blk: {
const tmp = __w;
const tmp_1 = __x;
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_setzero_pd() callconv(.C) __m128d {
return blk: {
const tmp = @intToFloat(f64, @as(c_int, 0));
const tmp_1 = @intToFloat(f64, @as(c_int, 0));
break :blk __m128d{
tmp,
tmp_1,
};
};
}
pub fn _mm_move_sd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = __b[@intCast(c_uint, @as(c_int, 0))];
return __a;
}
pub fn _mm_store_sd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
const struct___mm_store_sd_struct = packed struct {
__u: f64,
};
@ptrCast([*c]struct___mm_store_sd_struct, @alignCast(@import("std").meta.alignment(struct___mm_store_sd_struct), __dp)).*.__u = __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_store_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
@ptrCast([*c]__m128d, @alignCast(@import("std").meta.alignment(__m128d), __dp)).?.* = __a;
}
pub fn _mm_store1_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
__a = @shuffle(@typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.child, @bitCast(__v2df, __a), @bitCast(__v2df, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
});
_mm_store_pd(__dp, __a);
}
pub fn _mm_store_pd1(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
_mm_store1_pd(__dp, __a);
}
pub fn _mm_storeu_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
const struct___storeu_pd = packed struct {
__v: __m128d_u,
};
@ptrCast([*c]struct___storeu_pd, @alignCast(@import("std").meta.alignment(struct___storeu_pd), __dp)).*.__v = __a;
}
pub fn _mm_storer_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
__a = @shuffle(@typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.child, @bitCast(__v2df, __a), @bitCast(__v2df, __a), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
});
@ptrCast([*c]__m128d, @alignCast(@import("std").meta.alignment(__m128d), __dp)).?.* = __a;
}
pub fn _mm_storeh_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
const struct___mm_storeh_pd_struct = packed struct {
__u: f64,
};
@ptrCast([*c]struct___mm_storeh_pd_struct, @alignCast(@import("std").meta.alignment(struct___mm_storeh_pd_struct), __dp)).*.__u = __a[@intCast(c_uint, @as(c_int, 1))];
}
pub fn _mm_storel_pd(arg___dp: [*c]f64, arg___a: __m128d) callconv(.C) void {
var __dp = arg___dp;
var __a = arg___a;
const struct___mm_storeh_pd_struct = packed struct {
__u: f64,
};
@ptrCast([*c]struct___mm_storeh_pd_struct, @alignCast(@import("std").meta.alignment(struct___mm_storeh_pd_struct), __dp)).*.__u = __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_add_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v16qu, __a) + @bitCast(__v16qu, __b));
}
pub fn _mm_add_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v8hu, __a) + @bitCast(__v8hu, __b));
}
pub fn _mm_add_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v4su, __a) + @bitCast(__v4su, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2181:17: warning: TODO implement function '__builtin_ia32_paddq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2179:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_add_si64(arg___a: __m64, arg___b: __m64) callconv(.C) __m64;
pub fn _mm_add_epi64(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v2du, __a) + @bitCast(__v2du, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2224:19: warning: TODO implement function '__builtin_ia32_paddsb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2222:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2246:19: warning: TODO implement function '__builtin_ia32_paddsw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2244:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2267:19: warning: TODO implement function '__builtin_ia32_paddusb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2265:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2288:19: warning: TODO implement function '__builtin_ia32_paddusw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2286:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_adds_epu16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2308:19: warning: TODO implement function '__builtin_ia32_pavgb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2306:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_avg_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2328:19: warning: TODO implement function '__builtin_ia32_pavgw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2326:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_avg_epu16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2354:19: warning: TODO implement function '__builtin_ia32_pmaddwd128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2352:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_madd_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2374:19: warning: TODO implement function '__builtin_ia32_pmaxsw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2372:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2394:19: warning: TODO implement function '__builtin_ia32_pmaxub128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2392:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_max_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2414:19: warning: TODO implement function '__builtin_ia32_pminsw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2412:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2434:19: warning: TODO implement function '__builtin_ia32_pminub128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2432:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_min_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2454:19: warning: TODO implement function '__builtin_ia32_pmulhw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2452:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mulhi_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2474:19: warning: TODO implement function '__builtin_ia32_pmulhuw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2472:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mulhi_epu16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i;
pub fn _mm_mullo_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v8hu, __a) * @bitCast(__v8hu, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2513:10: warning: TODO implement function '__builtin_ia32_pmuludq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2511:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mul_su32(arg___a: __m64, arg___b: __m64) callconv(.C) __m64; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2532:10: warning: TODO implement function '__builtin_ia32_pmuludq128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2530:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_mul_epu32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2554:10: warning: TODO implement function '__builtin_ia32_psadbw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2552:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sad_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i;
pub fn _mm_sub_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v16qu, __a) - @bitCast(__v16qu, __b));
}
pub fn _mm_sub_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v8hu, __a) - @bitCast(__v8hu, __b));
}
pub fn _mm_sub_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v4su, __a) - @bitCast(__v4su, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2627:17: warning: TODO implement function '__builtin_ia32_psubq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2625:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sub_si64(arg___a: __m64, arg___b: __m64) callconv(.C) __m64;
pub fn _mm_sub_epi64(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v2du, __a) - @bitCast(__v2du, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2666:19: warning: TODO implement function '__builtin_ia32_psubsb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2664:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2687:19: warning: TODO implement function '__builtin_ia32_psubsw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2685:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2707:19: warning: TODO implement function '__builtin_ia32_psubusb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2705:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_epu8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2727:19: warning: TODO implement function '__builtin_ia32_psubusw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2725:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_subs_epu16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i;
pub fn _mm_and_si128(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v2du, __a) & @bitCast(__v2du, __b));
}
pub fn _mm_andnot_si128(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, ~@bitCast(__v2du, __a) & @bitCast(__v2du, __b));
}
pub fn _mm_or_si128(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v2du, __a) | @bitCast(__v2du, __b));
}
pub fn _mm_xor_si128(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v2du, __a) ^ @bitCast(__v2du, __b));
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2842:19: warning: TODO implement function '__builtin_ia32_psllwi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2840:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_epi16(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2861:19: warning: TODO implement function '__builtin_ia32_psllw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2859:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_epi16(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2880:19: warning: TODO implement function '__builtin_ia32_pslldi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2878:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_epi32(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2899:19: warning: TODO implement function '__builtin_ia32_pslld128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2897:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_epi32(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2918:10: warning: TODO implement function '__builtin_ia32_psllqi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2916:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_slli_epi64(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2937:10: warning: TODO implement function '__builtin_ia32_psllq128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2935:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sll_epi64(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2957:19: warning: TODO implement function '__builtin_ia32_psrawi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2955:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srai_epi16(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2977:19: warning: TODO implement function '__builtin_ia32_psraw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2975:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sra_epi16(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2997:19: warning: TODO implement function '__builtin_ia32_psradi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2995:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srai_epi32(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3017:19: warning: TODO implement function '__builtin_ia32_psrad128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3015:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_sra_epi32(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3059:19: warning: TODO implement function '__builtin_ia32_psrlwi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3057:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_epi16(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3078:19: warning: TODO implement function '__builtin_ia32_psrlw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3076:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_epi16(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3097:19: warning: TODO implement function '__builtin_ia32_psrldi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3095:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_epi32(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3116:19: warning: TODO implement function '__builtin_ia32_psrld128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3114:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_epi32(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3135:10: warning: TODO implement function '__builtin_ia32_psrlqi128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3133:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srli_epi64(arg___a: __m128i, arg___count: c_int) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3154:10: warning: TODO implement function '__builtin_ia32_psrlq128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3152:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_srl_epi64(arg___a: __m128i, arg___count: __m128i) callconv(.C) __m128i;
pub fn _mm_cmpeq_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v16qi, __a) == @bitCast(__v16qi, __b));
}
pub fn _mm_cmpeq_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v8hi, __a) == @bitCast(__v8hi, __b));
}
pub fn _mm_cmpeq_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v4si, __a) == @bitCast(__v4si, __b));
}
pub fn _mm_cmpgt_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v16qs, __a) > @bitCast(__v16qs, __b));
}
pub fn _mm_cmpgt_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v8hi, __a) > @bitCast(__v8hi, __b));
}
pub fn _mm_cmpgt_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @bitCast(__v4si, __a) > @bitCast(__v4si, __b));
}
pub fn _mm_cmplt_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return _mm_cmpgt_epi8(__b, __a);
}
pub fn _mm_cmplt_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return _mm_cmpgt_epi16(__b, __a);
}
pub fn _mm_cmplt_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return _mm_cmpgt_epi32(__b, __a);
}
pub fn _mm_cvtsi64_sd(arg___a: __m128d, arg___b: c_longlong) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
__a[@intCast(c_uint, @as(c_int, 0))] = @intToFloat(f64, __b);
return __a;
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3380:10: warning: TODO implement function '__builtin_ia32_cvtsd2si64' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3378:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtsd_si64(arg___a: __m128d) callconv(.C) c_longlong; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3398:10: warning: TODO implement function '__builtin_ia32_cvttsd2si64' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3396:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttsd_si64(arg___a: __m128d) callconv(.C) c_longlong;
pub fn _mm_cvtepi32_ps(arg___a: __m128i) callconv(.C) __m128 {
var __a = arg___a;
return @bitCast(__m128, blk: {
const tmp = @intToFloat(f32, @bitCast(__v4si, __a)[0]);
const tmp_1 = @intToFloat(f32, @bitCast(__v4si, __a)[1]);
const tmp_2 = @intToFloat(f32, @bitCast(__v4si, __a)[2]);
const tmp_3 = @intToFloat(f32, @bitCast(__v4si, __a)[3]);
break :blk __v4sf{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
});
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3430:19: warning: TODO implement function '__builtin_ia32_cvtps2dq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3428:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvtps_epi32(arg___a: __m128) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3447:19: warning: TODO implement function '__builtin_ia32_cvttps2dq' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3445:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_cvttps_epi32(arg___a: __m128) callconv(.C) __m128i;
pub fn _mm_cvtsi32_si128(arg___a: c_int) callconv(.C) __m128i {
var __a = arg___a;
return @bitCast(__m128i, blk: {
const tmp = __a;
const tmp_1 = @as(c_int, 0);
const tmp_2 = @as(c_int, 0);
const tmp_3 = @as(c_int, 0);
break :blk __v4si{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
});
}
pub fn _mm_cvtsi64_si128(arg___a: c_longlong) callconv(.C) __m128i {
var __a = arg___a;
return @bitCast(__m128i, blk: {
const tmp = __a;
const tmp_1 = @bitCast(c_longlong, @as(c_longlong, @as(c_int, 0)));
break :blk __v2di{
tmp,
tmp_1,
};
});
}
pub fn _mm_cvtsi128_si32(arg___a: __m128i) callconv(.C) c_int {
var __a = arg___a;
var __b: __v4si = @bitCast(__v4si, __a);
return __b[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_cvtsi128_si64(arg___a: __m128i) callconv(.C) c_longlong {
var __a = arg___a;
return __a[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_load_si128(arg___p: [*c]const __m128i) callconv(.C) __m128i {
var __p = arg___p;
return __p.?.*;
}
pub fn _mm_loadu_si128(arg___p: [*c]const __m128i_u) callconv(.C) __m128i {
var __p = arg___p;
const struct___loadu_si128 = packed struct {
__v: __m128i_u,
};
return @ptrCast([*c]const struct___loadu_si128, @alignCast(@import("std").meta.alignment(struct___loadu_si128), __p)).*.__v;
}
pub fn _mm_loadl_epi64(arg___p: [*c]const __m128i_u) callconv(.C) __m128i {
var __p = arg___p;
const struct___mm_loadl_epi64_struct = packed struct {
__u: c_longlong,
};
return blk: {
const tmp = @ptrCast([*c]const struct___mm_loadl_epi64_struct, @alignCast(@import("std").meta.alignment(struct___mm_loadl_epi64_struct), __p)).*.__u;
const tmp_1 = @bitCast(c_longlong, @as(c_longlong, @as(c_int, 0)));
break :blk __m128i{
tmp,
tmp_1,
};
};
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3589:19: warning: TODO implement function '__builtin_ia32_undef128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3587:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_undefined_si128() callconv(.C) __m128i;
pub fn _mm_set_epi64x(arg___q1: c_longlong, arg___q0: c_longlong) callconv(.C) __m128i {
var __q1 = arg___q1;
var __q0 = arg___q0;
return @bitCast(__m128i, blk: {
const tmp = __q0;
const tmp_1 = __q1;
break :blk __v2di{
tmp,
tmp_1,
};
});
}
pub fn _mm_set_epi64(arg___q1: __m64, arg___q0: __m64) callconv(.C) __m128i {
var __q1 = arg___q1;
var __q0 = arg___q0;
return _mm_set_epi64x(@bitCast(c_longlong, __q1), @bitCast(c_longlong, __q0));
}
pub fn _mm_set_epi32(arg___i3: c_int, arg___i2: c_int, arg___i1: c_int, arg___i0: c_int) callconv(.C) __m128i {
var __i3 = arg___i3;
var __i2 = arg___i2;
var __i1 = arg___i1;
var __i0 = arg___i0;
return @bitCast(__m128i, blk: {
const tmp = __i0;
const tmp_1 = __i1;
const tmp_2 = __i2;
const tmp_3 = __i3;
break :blk __v4si{
tmp,
tmp_1,
tmp_2,
tmp_3,
};
});
}
pub fn _mm_set_epi16(arg___w7: c_short, arg___w6: c_short, arg___w5: c_short, arg___w4: c_short, arg___w3: c_short, arg___w2: c_short, arg___w1: c_short, arg___w0: c_short) callconv(.C) __m128i {
var __w7 = arg___w7;
var __w6 = arg___w6;
var __w5 = arg___w5;
var __w4 = arg___w4;
var __w3 = arg___w3;
var __w2 = arg___w2;
var __w1 = arg___w1;
var __w0 = arg___w0;
return @bitCast(__m128i, blk: {
const tmp = __w0;
const tmp_1 = __w1;
const tmp_2 = __w2;
const tmp_3 = __w3;
const tmp_4 = __w4;
const tmp_5 = __w5;
const tmp_6 = __w6;
const tmp_7 = __w7;
break :blk __v8hi{
tmp,
tmp_1,
tmp_2,
tmp_3,
tmp_4,
tmp_5,
tmp_6,
tmp_7,
};
});
}
pub fn _mm_set_epi8(arg___b15: u8, arg___b14: u8, arg___b13: u8, arg___b12: u8, arg___b11: u8, arg___b10: u8, arg___b9: u8, arg___b8: u8, arg___b7: u8, arg___b6: u8, arg___b5: u8, arg___b4: u8, arg___b3: u8, arg___b2: u8, arg___b1: u8, arg___b0: u8) callconv(.C) __m128i {
var __b15 = arg___b15;
var __b14 = arg___b14;
var __b13 = arg___b13;
var __b12 = arg___b12;
var __b11 = arg___b11;
var __b10 = arg___b10;
var __b9 = arg___b9;
var __b8 = arg___b8;
var __b7 = arg___b7;
var __b6 = arg___b6;
var __b5 = arg___b5;
var __b4 = arg___b4;
var __b3 = arg___b3;
var __b2 = arg___b2;
var __b1 = arg___b1;
var __b0 = arg___b0;
return @bitCast(__m128i, blk: {
const tmp = __b0;
const tmp_1 = __b1;
const tmp_2 = __b2;
const tmp_3 = __b3;
const tmp_4 = __b4;
const tmp_5 = __b5;
const tmp_6 = __b6;
const tmp_7 = __b7;
const tmp_8 = __b8;
const tmp_9 = __b9;
const tmp_10 = __b10;
const tmp_11 = __b11;
const tmp_12 = __b12;
const tmp_13 = __b13;
const tmp_14 = __b14;
const tmp_15 = __b15;
break :blk __v16qi{
tmp,
tmp_1,
tmp_2,
tmp_3,
tmp_4,
tmp_5,
tmp_6,
tmp_7,
tmp_8,
tmp_9,
tmp_10,
tmp_11,
tmp_12,
tmp_13,
tmp_14,
tmp_15,
};
});
}
pub fn _mm_set1_epi64x(arg___q: c_longlong) callconv(.C) __m128i {
var __q = arg___q;
return _mm_set_epi64x(__q, __q);
}
pub fn _mm_set1_epi64(arg___q: __m64) callconv(.C) __m128i {
var __q = arg___q;
return _mm_set_epi64(__q, __q);
}
pub fn _mm_set1_epi32(arg___i: c_int) callconv(.C) __m128i {
var __i = arg___i;
return _mm_set_epi32(__i, __i, __i, __i);
}
pub fn _mm_set1_epi16(arg___w: c_short) callconv(.C) __m128i {
var __w = arg___w;
return _mm_set_epi16(__w, __w, __w, __w, __w, __w, __w, __w);
}
pub fn _mm_set1_epi8(arg___b: u8) callconv(.C) __m128i {
var __b = arg___b;
return _mm_set_epi8(__b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b, __b);
}
pub fn _mm_setr_epi64(arg___q0: __m64, arg___q1: __m64) callconv(.C) __m128i {
var __q0 = arg___q0;
var __q1 = arg___q1;
return _mm_set_epi64(__q1, __q0);
}
pub fn _mm_setr_epi32(arg___i0: c_int, arg___i1: c_int, arg___i2: c_int, arg___i3: c_int) callconv(.C) __m128i {
var __i0 = arg___i0;
var __i1 = arg___i1;
var __i2 = arg___i2;
var __i3 = arg___i3;
return _mm_set_epi32(__i3, __i2, __i1, __i0);
}
pub fn _mm_setr_epi16(arg___w0: c_short, arg___w1: c_short, arg___w2: c_short, arg___w3: c_short, arg___w4: c_short, arg___w5: c_short, arg___w6: c_short, arg___w7: c_short) callconv(.C) __m128i {
var __w0 = arg___w0;
var __w1 = arg___w1;
var __w2 = arg___w2;
var __w3 = arg___w3;
var __w4 = arg___w4;
var __w5 = arg___w5;
var __w6 = arg___w6;
var __w7 = arg___w7;
return _mm_set_epi16(__w7, __w6, __w5, __w4, __w3, __w2, __w1, __w0);
}
pub fn _mm_setr_epi8(arg___b0: u8, arg___b1: u8, arg___b2: u8, arg___b3: u8, arg___b4: u8, arg___b5: u8, arg___b6: u8, arg___b7: u8, arg___b8: u8, arg___b9: u8, arg___b10: u8, arg___b11: u8, arg___b12: u8, arg___b13: u8, arg___b14: u8, arg___b15: u8) callconv(.C) __m128i {
var __b0 = arg___b0;
var __b1 = arg___b1;
var __b2 = arg___b2;
var __b3 = arg___b3;
var __b4 = arg___b4;
var __b5 = arg___b5;
var __b6 = arg___b6;
var __b7 = arg___b7;
var __b8 = arg___b8;
var __b9 = arg___b9;
var __b10 = arg___b10;
var __b11 = arg___b11;
var __b12 = arg___b12;
var __b13 = arg___b13;
var __b14 = arg___b14;
var __b15 = arg___b15;
return _mm_set_epi8(__b15, __b14, __b13, __b12, __b11, __b10, __b9, __b8, __b7, __b6, __b5, __b4, __b3, __b2, __b1, __b0);
}
pub fn _mm_setzero_si128() callconv(.C) __m128i {
return @bitCast(__m128i, blk: {
const tmp = @as(c_longlong, 0);
const tmp_1 = @as(c_longlong, 0);
break :blk __v2di{
tmp,
tmp_1,
};
});
}
pub fn _mm_store_si128(arg___p: [*c]__m128i, arg___b: __m128i) callconv(.C) void {
var __p = arg___p;
var __b = arg___b;
__p.?.* = __b;
}
pub fn _mm_storeu_si128(arg___p: [*c]__m128i_u, arg___b: __m128i) callconv(.C) void {
var __p = arg___p;
var __b = arg___b;
const struct___storeu_si128 = packed struct {
__v: __m128i_u,
};
@ptrCast([*c]struct___storeu_si128, @alignCast(@import("std").meta.alignment(struct___storeu_si128), __p)).*.__v = __b;
}
pub fn _mm_storeu_si64(arg___p: ?*c_void, arg___b: __m128i) callconv(.C) void {
var __p = arg___p;
var __b = arg___b;
const struct___storeu_si64 = packed struct {
__v: c_longlong,
};
@ptrCast([*c]struct___storeu_si64, @alignCast(@import("std").meta.alignment(struct___storeu_si64), __p)).*.__v = @bitCast(__v2di, __b)[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_storeu_si32(arg___p: ?*c_void, arg___b: __m128i) callconv(.C) void {
var __p = arg___p;
var __b = arg___b;
const struct___storeu_si32 = packed struct {
__v: c_int,
};
@ptrCast([*c]struct___storeu_si32, @alignCast(@import("std").meta.alignment(struct___storeu_si32), __p)).*.__v = @bitCast(__v4si, __b)[@intCast(c_uint, @as(c_int, 0))];
}
pub fn _mm_storeu_si16(arg___p: ?*c_void, arg___b: __m128i) callconv(.C) void {
var __p = arg___p;
var __b = arg___b;
const struct___storeu_si16 = packed struct {
__v: c_short,
};
@ptrCast([*c]struct___storeu_si16, @alignCast(@import("std").meta.alignment(struct___storeu_si16), __p)).*.__v = @bitCast(__v8hi, __b)[@intCast(c_uint, @as(c_int, 0))];
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4106:3: warning: TODO implement function '__builtin_ia32_maskmovdqu' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4104:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_maskmoveu_si128(arg___d: __m128i, arg___n: __m128i, arg___p: [*c]u8) callconv(.C) void;
pub fn _mm_storel_epi64(arg___p: [*c]__m128i_u, arg___a: __m128i) callconv(.C) void {
var __p = arg___p;
var __a = arg___a;
const struct___mm_storel_epi64_struct = packed struct {
__u: c_longlong,
};
@ptrCast([*c]struct___mm_storel_epi64_struct, @alignCast(@import("std").meta.alignment(struct___mm_storel_epi64_struct), __p)).*.__u = __a[@intCast(c_uint, @as(c_int, 0))];
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4148:3: warning: TODO implement function '__builtin_nontemporal_store' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4146:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_pd(arg___p: [*c]f64, arg___a: __m128d) callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4167:3: warning: TODO implement function '__builtin_nontemporal_store' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4165:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_si128(arg___p: [*c]__m128i, arg___a: __m128i) callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4186:3: warning: TODO implement function '__builtin_ia32_movnti' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4184:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_si32(arg___p: [*c]c_int, arg___a: c_int) callconv(.C) void; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4206:3: warning: TODO implement function '__builtin_ia32_movnti64' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4204:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_stream_si64(arg___p: [*c]c_longlong, arg___a: c_longlong) callconv(.C) void;
pub extern fn _mm_clflush(__p: ?*const c_void) void;
pub extern fn _mm_lfence() void;
pub extern fn _mm_mfence() void; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4277:19: warning: TODO implement function '__builtin_ia32_packsswb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4275:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packs_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4305:19: warning: TODO implement function '__builtin_ia32_packssdw128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4303:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packs_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4333:19: warning: TODO implement function '__builtin_ia32_packuswb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4331:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_packus_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i; // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4401:10: warning: TODO implement function '__builtin_ia32_pmovmskb128' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4399:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_movemask_epi8(arg___a: __m128i) callconv(.C) c_int;
pub fn _mm_unpackhi_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.child, @bitCast(__v16qi, __a), @bitCast(__v16qi, __b), comptime @import("std").meta.Vector(16, i32){
@import("std").meta.shuffleVectorIndex(8, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 8), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(9, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 9), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(10, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 10), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(11, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 11), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(12, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 12), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(13, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 13), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(14, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 14), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(15, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 15), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
}));
}
pub fn _mm_unpackhi_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.child, @bitCast(__v8hi, __a), @bitCast(__v8hi, __b), comptime @import("std").meta.Vector(8, i32){
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 4), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 5), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(6, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 6), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(7, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 7), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
}));
}
pub fn _mm_unpackhi_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.child, @bitCast(__v4si, __a), @bitCast(__v4si, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 4) + @as(c_int, 2), @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 4) + @as(c_int, 3), @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
}));
}
pub fn _mm_unpackhi_epi64(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.child, @bitCast(__v2di, __a), @bitCast(__v2di, __b), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 2) + @as(c_int, 1), @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
}));
}
pub fn _mm_unpacklo_epi8(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.child, @bitCast(__v16qi, __a), @bitCast(__v16qi, __b), comptime @import("std").meta.Vector(16, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 0), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 1), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 2), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 3), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(4, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 4), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(5, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 5), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(6, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 6), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(7, @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 16) + @as(c_int, 7), @typeInfo(@TypeOf(@bitCast(__v16qi, __a))).Vector.len),
}));
}
pub fn _mm_unpacklo_epi16(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.child, @bitCast(__v8hi, __a), @bitCast(__v8hi, __b), comptime @import("std").meta.Vector(8, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 0), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 1), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 2), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(3, @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 8) + @as(c_int, 3), @typeInfo(@TypeOf(@bitCast(__v8hi, __a))).Vector.len),
}));
}
pub fn _mm_unpacklo_epi32(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.child, @bitCast(__v4si, __a), @bitCast(__v4si, __b), comptime @import("std").meta.Vector(4, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 4) + @as(c_int, 0), @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 4) + @as(c_int, 1), @typeInfo(@TypeOf(@bitCast(__v4si, __a))).Vector.len),
}));
}
pub fn _mm_unpacklo_epi64(arg___a: __m128i, arg___b: __m128i) callconv(.C) __m128i {
var __a = arg___a;
var __b = arg___b;
return @bitCast(__m128i, @shuffle(@typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.child, @bitCast(__v2di, __a), @bitCast(__v2di, __b), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 2) + @as(c_int, 0), @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
}));
}
pub fn _mm_movepi64_pi64(arg___a: __m128i) callconv(.C) __m64 {
var __a = arg___a;
return @bitCast(__m64, __a[@intCast(c_uint, @as(c_int, 0))]);
}
pub fn _mm_movpi64_epi64(arg___a: __m64) callconv(.C) __m128i {
var __a = arg___a;
return @bitCast(__m128i, blk: {
const tmp = @bitCast(c_longlong, __a);
const tmp_1 = @bitCast(c_longlong, @as(c_longlong, @as(c_int, 0)));
break :blk __v2di{
tmp,
tmp_1,
};
});
}
pub fn _mm_move_epi64(arg___a: __m128i) callconv(.C) __m128i {
var __a = arg___a;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.child, @bitCast(__v2di, __a), _mm_setzero_si128(), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(2, @typeInfo(@TypeOf(@bitCast(__v2di, __a))).Vector.len),
});
}
pub fn _mm_unpackhi_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.child, @bitCast(__v2df, __a), @bitCast(__v2df, __b), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(1, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 2) + @as(c_int, 1), @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
});
}
pub fn _mm_unpacklo_pd(arg___a: __m128d, arg___b: __m128d) callconv(.C) __m128d {
var __a = arg___a;
var __b = arg___b;
return @shuffle(@typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.child, @bitCast(__v2df, __a), @bitCast(__v2df, __b), comptime @import("std").meta.Vector(2, i32){
@import("std").meta.shuffleVectorIndex(0, @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
@import("std").meta.shuffleVectorIndex(@as(c_int, 2) + @as(c_int, 0), @typeInfo(@TypeOf(@bitCast(__v2df, __a))).Vector.len),
});
} // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4818:10: warning: TODO implement function '__builtin_ia32_movmskpd' in std.c.builtins
// C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4816:1: warning: unable to translate function, demoted to extern
pub extern fn _mm_movemask_pd(arg___a: __m128d) callconv(.C) c_int;
pub fn _mm_castpd_ps(arg___a: __m128d) callconv(.C) __m128 {
var __a = arg___a;
return @bitCast(__m128, __a);
}
pub fn _mm_castpd_si128(arg___a: __m128d) callconv(.C) __m128i {
var __a = arg___a;
return @bitCast(__m128i, __a);
}
pub fn _mm_castps_pd(arg___a: __m128) callconv(.C) __m128d {
var __a = arg___a;
return @bitCast(__m128d, __a);
}
pub fn _mm_castps_si128(arg___a: __m128) callconv(.C) __m128i {
var __a = arg___a;
return @bitCast(__m128i, __a);
}
pub fn _mm_castsi128_ps(arg___a: __m128i) callconv(.C) __m128 {
var __a = arg___a;
return @bitCast(__m128, __a);
}
pub fn _mm_castsi128_pd(arg___a: __m128i) callconv(.C) __m128d {
var __a = arg___a;
return @bitCast(__m128d, __a);
}
pub extern fn _mm_pause() void;
pub const struct__exception = extern struct {
type: c_int,
name: [*c]const u8,
arg1: f64,
arg2: f64,
retval: f64,
};
const struct_unnamed_2 = extern struct {
low: c_uint,
high: c_uint,
};
pub const union___mingw_dbl_type_t = extern union {
x: f64,
val: c_ulonglong,
lh: struct_unnamed_2,
};
pub const __mingw_dbl_type_t = union___mingw_dbl_type_t;
pub const union___mingw_flt_type_t = extern union {
x: f32,
val: c_uint,
};
pub const __mingw_flt_type_t = union___mingw_flt_type_t; // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:137:11: warning: struct demoted to opaque type - has bitfield
const struct_unnamed_3 = opaque {};
pub const union___mingw_ldbl_type_t = extern union {
x: c_longdouble,
lh: struct_unnamed_3,
};
pub const __mingw_ldbl_type_t = union___mingw_ldbl_type_t;
pub extern var __imp__HUGE: [*c]f64;
pub extern fn __mingw_raise_matherr(typ: c_int, name: [*c]const u8, a1: f64, a2: f64, rslt: f64) void;
pub extern fn __mingw_setusermatherr(?fn ([*c]struct__exception) callconv(.C) c_int) void;
pub extern fn __setusermatherr(?fn ([*c]struct__exception) callconv(.C) c_int) void;
pub extern fn sin(_X: f64) f64;
pub extern fn cos(_X: f64) f64;
pub extern fn tan(_X: f64) f64;
pub extern fn sinh(_X: f64) f64;
pub extern fn cosh(_X: f64) f64;
pub extern fn tanh(_X: f64) f64;
pub extern fn asin(_X: f64) f64;
pub extern fn acos(_X: f64) f64;
pub extern fn atan(_X: f64) f64;
pub extern fn atan2(_Y: f64, _X: f64) f64;
pub extern fn exp(_X: f64) f64;
pub extern fn log(_X: f64) f64;
pub extern fn log10(_X: f64) f64;
pub extern fn pow(_X: f64, _Y: f64) f64;
pub extern fn sqrt(_X: f64) f64;
pub extern fn ceil(_X: f64) f64;
pub extern fn floor(_X: f64) f64;
pub fn fabsf(arg_x: f32) callconv(.C) f32 {
var x = arg_x;
return __builtin_fabsf(x);
} // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:219:23: warning: unsupported floating point constant format APFloatBaseSemantics.x86DoubleExtended
// C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:214:36: warning: unable to translate function, demoted to extern
pub extern fn fabsl(arg_x: c_longdouble) callconv(.C) c_longdouble;
pub fn fabs(arg_x: f64) callconv(.C) f64 {
var x = arg_x;
return __builtin_fabs(x);
}
pub extern fn ldexp(_X: f64, _Y: c_int) f64;
pub extern fn frexp(_X: f64, _Y: [*c]c_int) f64;
pub extern fn modf(_X: f64, _Y: [*c]f64) f64;
pub extern fn fmod(_X: f64, _Y: f64) f64;
pub extern fn sincos(__x: f64, p_sin: [*c]f64, p_cos: [*c]f64) void;
pub extern fn sincosl(__x: c_longdouble, p_sin: [*c]c_longdouble, p_cos: [*c]c_longdouble) void;
pub extern fn sincosf(__x: f32, p_sin: [*c]f32, p_cos: [*c]f32) void;
pub const struct__complex = extern struct {
x: f64,
y: f64,
};
pub extern fn _cabs(_ComplexA: struct__complex) f64;
pub extern fn _hypot(_X: f64, _Y: f64) f64;
pub extern fn _j0(_X: f64) f64;
pub extern fn _j1(_X: f64) f64;
pub extern fn _jn(_X: c_int, _Y: f64) f64;
pub extern fn _y0(_X: f64) f64;
pub extern fn _y1(_X: f64) f64;
pub extern fn _yn(_X: c_int, _Y: f64) f64;
pub extern fn _matherr([*c]struct__exception) c_int;
pub extern fn _chgsign(_X: f64) f64;
pub extern fn _copysign(_Number: f64, _Sign: f64) f64;
pub extern fn _logb(f64) f64;
pub extern fn _nextafter(f64, f64) f64;
pub extern fn _scalb(f64, c_long) f64;
pub extern fn _finite(f64) c_int;
pub extern fn _fpclass(f64) c_int;
pub extern fn _isnan(f64) c_int;
pub extern fn j0(f64) f64;
pub extern fn j1(f64) f64;
pub extern fn jn(c_int, f64) f64;
pub extern fn y0(f64) f64;
pub extern fn y1(f64) f64;
pub extern fn yn(c_int, f64) f64;
pub extern fn chgsign(f64) f64;
pub extern fn finite(f64) c_int;
pub extern fn fpclass(f64) c_int;
pub const float_t = f32;
pub const double_t = f64;
pub fn __fpclassifyl(arg_x: c_longdouble) callconv(.C) c_int {
var x = arg_x;
var hlp: __mingw_ldbl_type_t = undefined;
var e: c_uint = undefined;
hlp.x = x;
e = @bitCast(c_uint, hlp.lh.sign_exponent & @as(c_int, 32767));
if (!(e != 0)) {
var h: c_uint = hlp.lh.high;
if (!((hlp.lh.low | h) != 0)) return 16384 else if (!((h & @as(c_uint, 2147483648)) != 0)) return @as(c_int, 1024) | @as(c_int, 16384);
} else if (e == @bitCast(c_uint, @as(c_int, 32767))) return if (((hlp.lh.high & @bitCast(c_uint, @as(c_int, 2147483647))) | hlp.lh.low) == @bitCast(c_uint, @as(c_int, 0))) @as(c_int, 256) | @as(c_int, 1024) else @as(c_int, 256);
return 1024;
}
pub fn __fpclassifyf(arg_x: f32) callconv(.C) c_int {
var x = arg_x;
var hlp: __mingw_flt_type_t = undefined;
hlp.x = x;
hlp.val &= @bitCast(c_uint, @as(c_int, 2147483647));
if (hlp.val == @bitCast(c_uint, @as(c_int, 0))) return 16384;
if (hlp.val < @bitCast(c_uint, @as(c_int, 8388608))) return @as(c_int, 1024) | @as(c_int, 16384);
if (hlp.val >= @bitCast(c_uint, @as(c_int, 2139095040))) return if (hlp.val > @bitCast(c_uint, @as(c_int, 2139095040))) @as(c_int, 256) else @as(c_int, 256) | @as(c_int, 1024);
return 1024;
}
pub fn __fpclassify(arg_x: f64) callconv(.C) c_int {
var x = arg_x;
var hlp: __mingw_dbl_type_t = undefined;
var l: c_uint = undefined;
var h: c_uint = undefined;
hlp.x = x;
h = hlp.lh.high;
l = hlp.lh.low | (h & @bitCast(c_uint, @as(c_int, 1048575)));
h &= @bitCast(c_uint, @as(c_int, 2146435072));
if ((h | l) == @bitCast(c_uint, @as(c_int, 0))) return 16384;
if (!(h != 0)) return @as(c_int, 1024) | @as(c_int, 16384);
if (h == @bitCast(c_uint, @as(c_int, 2146435072))) return if (l != 0) @as(c_int, 256) else @as(c_int, 256) | @as(c_int, 1024);
return 1024;
}
pub fn __isnan(arg__x: f64) callconv(.C) c_int {
var _x = arg__x;
var hlp: __mingw_dbl_type_t = undefined;
var l: c_int = undefined;
var h: c_int = undefined;
hlp.x = _x;
l = @bitCast(c_int, hlp.lh.low);
h = @bitCast(c_int, hlp.lh.high & @bitCast(c_uint, @as(c_int, 2147483647)));
h |= @bitCast(c_int, @bitCast(c_uint, l | -l) >> @intCast(@import("std").math.Log2Int(c_uint), 31));
h = @as(c_int, 2146435072) - h;
return @bitCast(c_int, @bitCast(c_uint, h)) >> @intCast(@import("std").math.Log2Int(c_int), 31);
}
pub fn __isnanf(arg__x: f32) callconv(.C) c_int {
var _x = arg__x;
var hlp: __mingw_flt_type_t = undefined;
var i: c_int = undefined;
hlp.x = _x;
i = @bitCast(c_int, hlp.val & @bitCast(c_uint, @as(c_int, 2147483647)));
i = @as(c_int, 2139095040) - i;
return @bitCast(c_int, @bitCast(c_uint, i) >> @intCast(@import("std").math.Log2Int(c_uint), 31));
}
pub fn __isnanl(arg__x: c_longdouble) callconv(.C) c_int {
var _x = arg__x;
var ld: __mingw_ldbl_type_t = undefined;
var xx: c_int = undefined;
var signexp: c_int = undefined;
ld.x = _x;
signexp = (ld.lh.sign_exponent & @as(c_int, 32767)) << @intCast(@import("std").math.Log2Int(c_int), 1);
xx = @bitCast(c_int, ld.lh.low | (ld.lh.high & @as(c_uint, 2147483647)));
signexp |= @bitCast(c_int, @bitCast(c_uint, xx | -xx) >> @intCast(@import("std").math.Log2Int(c_uint), 31));
signexp = @as(c_int, 65534) - signexp;
return @bitCast(c_int, @bitCast(c_uint, signexp)) >> @intCast(@import("std").math.Log2Int(c_int), 16);
}
pub fn __signbit(arg_x: f64) callconv(.C) c_int {
var x = arg_x;
var hlp: __mingw_dbl_type_t = undefined;
hlp.x = x;
return @boolToInt((hlp.lh.high & @as(c_uint, 2147483648)) != @bitCast(c_uint, @as(c_int, 0)));
}
pub fn __signbitf(arg_x: f32) callconv(.C) c_int {
var x = arg_x;
var hlp: __mingw_flt_type_t = undefined;
hlp.x = x;
return @boolToInt((hlp.val & @as(c_uint, 2147483648)) != @bitCast(c_uint, @as(c_int, 0)));
}
pub fn __signbitl(arg_x: c_longdouble) callconv(.C) c_int {
var x = arg_x;
var ld: __mingw_ldbl_type_t = undefined;
ld.x = x;
return @boolToInt((ld.lh.sign_exponent & @as(c_int, 32768)) != @as(c_int, 0));
}
pub extern fn sinf(_X: f32) f32;
pub extern fn sinl(c_longdouble) c_longdouble;
pub extern fn cosf(_X: f32) f32;
pub extern fn cosl(c_longdouble) c_longdouble;
pub extern fn tanf(_X: f32) f32;
pub extern fn tanl(c_longdouble) c_longdouble;
pub extern fn asinf(_X: f32) f32;
pub extern fn asinl(c_longdouble) c_longdouble;
pub extern fn acosf(f32) f32;
pub extern fn acosl(c_longdouble) c_longdouble;
pub extern fn atanf(f32) f32;
pub extern fn atanl(c_longdouble) c_longdouble;
pub extern fn atan2f(f32, f32) f32;
pub extern fn atan2l(c_longdouble, c_longdouble) c_longdouble;
pub fn sinhf(arg__X: f32) callconv(.C) f32 {
var _X = arg__X;
return @floatCast(f32, sinh(@floatCast(f64, _X)));
}
pub extern fn sinhl(c_longdouble) c_longdouble;
pub fn coshf(arg__X: f32) callconv(.C) f32 {
var _X = arg__X;
return @floatCast(f32, cosh(@floatCast(f64, _X)));
}
pub extern fn coshl(c_longdouble) c_longdouble;
pub fn tanhf(arg__X: f32) callconv(.C) f32 {
var _X = arg__X;
return @floatCast(f32, tanh(@floatCast(f64, _X)));
}
pub extern fn tanhl(c_longdouble) c_longdouble;
pub extern fn acosh(f64) f64;
pub extern fn acoshf(f32) f32;
pub extern fn acoshl(c_longdouble) c_longdouble;
pub extern fn asinh(f64) f64;
pub extern fn asinhf(f32) f32;
pub extern fn asinhl(c_longdouble) c_longdouble;
pub extern fn atanh(f64) f64;
pub extern fn atanhf(f32) f32;
pub extern fn atanhl(c_longdouble) c_longdouble;
pub fn expf(arg__X: f32) callconv(.C) f32 {
var _X = arg__X;
return @floatCast(f32, exp(@floatCast(f64, _X)));
}
pub extern fn expl(c_longdouble) c_longdouble;
pub extern fn exp2(f64) f64;
pub extern fn exp2f(f32) f32;
pub extern fn exp2l(c_longdouble) c_longdouble;
pub extern fn expm1(f64) f64;
pub extern fn expm1f(f32) f32;
pub extern fn expm1l(c_longdouble) c_longdouble;
pub fn frexpf(arg__X: f32, arg__Y: [*c]c_int) callconv(.C) f32 {
var _X = arg__X;
var _Y = arg__Y;
return @floatCast(f32, frexp(@floatCast(f64, _X), _Y));
}
pub extern fn frexpl(c_longdouble, [*c]c_int) c_longdouble;
pub extern fn ilogb(f64) c_int;
pub extern fn ilogbf(f32) c_int;
pub extern fn ilogbl(c_longdouble) c_int;
pub fn ldexpf(arg_x: f32, arg_expn: c_int) callconv(.C) f32 {
var x = arg_x;
var expn = arg_expn;
return @floatCast(f32, ldexp(@floatCast(f64, x), expn));
}
pub extern fn ldexpl(c_longdouble, c_int) c_longdouble;
pub extern fn logf(f32) f32;
pub extern fn logl(c_longdouble) c_longdouble;
pub extern fn log10f(f32) f32;
pub extern fn log10l(c_longdouble) c_longdouble;
pub extern fn log1p(f64) f64;
pub extern fn log1pf(f32) f32;
pub extern fn log1pl(c_longdouble) c_longdouble;
pub extern fn log2(f64) f64;
pub extern fn log2f(f32) f32;
pub extern fn log2l(c_longdouble) c_longdouble;
pub extern fn logb(f64) f64;
pub extern fn logbf(f32) f32;
pub extern fn logbl(c_longdouble) c_longdouble;
pub extern fn modff(f32, [*c]f32) f32;
pub extern fn modfl(c_longdouble, [*c]c_longdouble) c_longdouble;
pub extern fn scalbn(f64, c_int) f64;
pub extern fn scalbnf(f32, c_int) f32;
pub extern fn scalbnl(c_longdouble, c_int) c_longdouble;
pub extern fn scalbln(f64, c_long) f64;
pub extern fn scalblnf(f32, c_long) f32;
pub extern fn scalblnl(c_longdouble, c_long) c_longdouble;
pub extern fn cbrt(f64) f64;
pub extern fn cbrtf(f32) f32;
pub extern fn cbrtl(c_longdouble) c_longdouble;
pub extern fn hypot(f64, f64) f64;
pub fn hypotf(arg_x: f32, arg_y: f32) callconv(.C) f32 {
var x = arg_x;
var y = arg_y;
return @floatCast(f32, hypot(@floatCast(f64, x), @floatCast(f64, y)));
}
pub extern fn hypotl(c_longdouble, c_longdouble) c_longdouble;
pub fn powf(arg__X: f32, arg__Y: f32) callconv(.C) f32 {
var _X = arg__X;
var _Y = arg__Y;
return @floatCast(f32, pow(@floatCast(f64, _X), @floatCast(f64, _Y)));
}
pub extern fn powl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn sqrtf(f32) f32;
pub extern fn sqrtl(c_longdouble) c_longdouble;
pub extern fn erf(f64) f64;
pub extern fn erff(f32) f32;
pub extern fn erfl(c_longdouble) c_longdouble;
pub extern fn erfc(f64) f64;
pub extern fn erfcf(f32) f32;
pub extern fn erfcl(c_longdouble) c_longdouble;
pub extern fn lgamma(f64) f64;
pub extern fn lgammaf(f32) f32;
pub extern fn lgammal(c_longdouble) c_longdouble;
pub extern var signgam: c_int;
pub extern fn tgamma(f64) f64;
pub extern fn tgammaf(f32) f32;
pub extern fn tgammal(c_longdouble) c_longdouble;
pub extern fn ceilf(f32) f32;
pub extern fn ceill(c_longdouble) c_longdouble;
pub extern fn floorf(f32) f32;
pub extern fn floorl(c_longdouble) c_longdouble;
pub extern fn nearbyint(f64) f64;
pub extern fn nearbyintf(f32) f32;
pub extern fn nearbyintl(c_longdouble) c_longdouble;
pub extern fn rint(f64) f64;
pub extern fn rintf(f32) f32;
pub extern fn rintl(c_longdouble) c_longdouble;
pub extern fn lrint(f64) c_long;
pub extern fn lrintf(f32) c_long;
pub extern fn lrintl(c_longdouble) c_long;
pub extern fn llrint(f64) c_longlong;
pub extern fn llrintf(f32) c_longlong;
pub extern fn llrintl(c_longdouble) c_longlong;
pub extern fn round(f64) f64;
pub extern fn roundf(f32) f32;
pub extern fn roundl(c_longdouble) c_longdouble;
pub extern fn lround(f64) c_long;
pub extern fn lroundf(f32) c_long;
pub extern fn lroundl(c_longdouble) c_long;
pub extern fn llround(f64) c_longlong;
pub extern fn llroundf(f32) c_longlong;
pub extern fn llroundl(c_longdouble) c_longlong;
pub extern fn trunc(f64) f64;
pub extern fn truncf(f32) f32;
pub extern fn truncl(c_longdouble) c_longdouble;
pub extern fn fmodf(f32, f32) f32;
pub extern fn fmodl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn remainder(f64, f64) f64;
pub extern fn remainderf(f32, f32) f32;
pub extern fn remainderl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn remquo(f64, f64, [*c]c_int) f64;
pub extern fn remquof(f32, f32, [*c]c_int) f32;
pub extern fn remquol(c_longdouble, c_longdouble, [*c]c_int) c_longdouble;
pub fn copysign(arg_x: f64, arg_y: f64) callconv(.C) f64 {
var x = arg_x;
var y = arg_y;
var hx: __mingw_dbl_type_t = undefined;
var hy: __mingw_dbl_type_t = undefined;
hx.x = x;
hy.x = y;
hx.lh.high = (hx.lh.high & @bitCast(c_uint, @as(c_int, 2147483647))) | (hy.lh.high & @as(c_uint, 2147483648));
return hx.x;
}
pub fn copysignf(arg_x: f32, arg_y: f32) callconv(.C) f32 {
var x = arg_x;
var y = arg_y;
var hx: __mingw_flt_type_t = undefined;
var hy: __mingw_flt_type_t = undefined;
hx.x = x;
hy.x = y;
hx.val = (hx.val & @bitCast(c_uint, @as(c_int, 2147483647))) | (hy.val & @as(c_uint, 2147483648));
return hx.x;
}
pub extern fn copysignl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn nan(tagp: [*c]const u8) f64;
pub extern fn nanf(tagp: [*c]const u8) f32;
pub extern fn nanl(tagp: [*c]const u8) c_longdouble;
pub extern fn nextafter(f64, f64) f64;
pub extern fn nextafterf(f32, f32) f32;
pub extern fn nextafterl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn nexttoward(f64, c_longdouble) f64;
pub extern fn nexttowardf(f32, c_longdouble) f32;
pub extern fn nexttowardl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn fdim(x: f64, y: f64) f64;
pub extern fn fdimf(x: f32, y: f32) f32;
pub extern fn fdiml(x: c_longdouble, y: c_longdouble) c_longdouble;
pub extern fn fmax(f64, f64) f64;
pub extern fn fmaxf(f32, f32) f32;
pub extern fn fmaxl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn fmin(f64, f64) f64;
pub extern fn fminf(f32, f32) f32;
pub extern fn fminl(c_longdouble, c_longdouble) c_longdouble;
pub extern fn fma(f64, f64, f64) f64;
pub extern fn fmaf(f32, f32, f32) f32;
pub extern fn fmal(c_longdouble, c_longdouble, c_longdouble) c_longdouble;
pub extern fn _copysignf(_Number: f32, _Sign: f32) f32;
pub extern fn _chgsignf(_X: f32) f32;
pub extern fn _logbf(_X: f32) f32;
pub extern fn _nextafterf(_X: f32, _Y: f32) f32;
pub extern fn _finitef(_X: f32) c_int;
pub extern fn _isnanf(_X: f32) c_int;
pub extern fn _fpclassf(_X: f32) c_int;
pub extern fn _chgsignl(c_longdouble) c_longdouble;
const struct_unnamed_4 = extern struct {
X: f32,
Y: f32,
};
const struct_unnamed_5 = extern struct {
U: f32,
V: f32,
};
const struct_unnamed_6 = extern struct {
Left: f32,
Right: f32,
};
const struct_unnamed_7 = extern struct {
Width: f32,
Height: f32,
};
pub const union_hmm_vec2 = extern union {
unnamed_0: struct_unnamed_4,
unnamed_1: struct_unnamed_5,
unnamed_2: struct_unnamed_6,
unnamed_3: struct_unnamed_7,
Elements: [2]f32,
};
pub const hmm_vec2 = union_hmm_vec2;
const struct_unnamed_8 = extern struct {
X: f32,
Y: f32,
Z: f32,
};
const struct_unnamed_9 = extern struct {
U: f32,
V: f32,
W: f32,
};
const struct_unnamed_10 = extern struct {
R: f32,
G: f32,
B: f32,
};
const struct_unnamed_11 = extern struct {
XY: hmm_vec2,
Ignored0_: f32,
};
const struct_unnamed_12 = extern struct {
Ignored1_: f32,
YZ: hmm_vec2,
};
const struct_unnamed_13 = extern struct {
UV: hmm_vec2,
Ignored2_: f32,
};
const struct_unnamed_14 = extern struct {
Ignored3_: f32,
VW: hmm_vec2,
};
pub const union_hmm_vec3 = extern union {
unnamed_0: struct_unnamed_8,
unnamed_1: struct_unnamed_9,
unnamed_2: struct_unnamed_10,
unnamed_3: struct_unnamed_11,
unnamed_4: struct_unnamed_12,
unnamed_5: struct_unnamed_13,
unnamed_6: struct_unnamed_14,
Elements: [3]f32,
};
pub const hmm_vec3 = union_hmm_vec3;
const struct_unnamed_17 = extern struct {
X: f32,
Y: f32,
Z: f32,
};
const union_unnamed_16 = extern union {
XYZ: hmm_vec3,
unnamed_0: struct_unnamed_17,
};
const struct_unnamed_15 = extern struct {
unnamed_0: union_unnamed_16,
W: f32,
};
const struct_unnamed_20 = extern struct {
R: f32,
G: f32,
B: f32,
};
const union_unnamed_19 = extern union {
RGB: hmm_vec3,
unnamed_0: struct_unnamed_20,
};
const struct_unnamed_18 = extern struct {
unnamed_0: union_unnamed_19,
A: f32,
};
const struct_unnamed_21 = extern struct {
XY: hmm_vec2,
Ignored0_: f32,
Ignored1_: f32,
};
const struct_unnamed_22 = extern struct {
Ignored2_: f32,
YZ: hmm_vec2,
Ignored3_: f32,
};
const struct_unnamed_23 = extern struct {
Ignored4_: f32,
Ignored5_: f32,
ZW: hmm_vec2,
};
pub const union_hmm_vec4 = extern union {
unnamed_0: struct_unnamed_15,
unnamed_1: struct_unnamed_18,
unnamed_2: struct_unnamed_21,
unnamed_3: struct_unnamed_22,
unnamed_4: struct_unnamed_23,
Elements: [4]f32,
InternalElementsSSE: __m128,
};
pub const hmm_vec4 = union_hmm_vec4;
pub const union_hmm_mat4 = extern union {
Elements: [4][4]f32,
Columns: [4]__m128,
Rows: [4]__m128,
};
pub const hmm_mat4 = union_hmm_mat4;
const struct_unnamed_26 = extern struct {
X: f32,
Y: f32,
Z: f32,
};
const union_unnamed_25 = extern union {
XYZ: hmm_vec3,
unnamed_0: struct_unnamed_26,
};
const struct_unnamed_24 = extern struct {
unnamed_0: union_unnamed_25,
W: f32,
};
pub const union_hmm_quaternion = extern union {
unnamed_0: struct_unnamed_24,
Elements: [4]f32,
InternalElementsSSE: __m128,
};
pub const hmm_quaternion = union_hmm_quaternion;
pub const hmm_bool = c_int;
pub const hmm_v2 = hmm_vec2;
pub const hmm_v3 = hmm_vec3;
pub const hmm_v4 = hmm_vec4;
pub const hmm_m4 = hmm_mat4;
pub fn HMM_SinF(arg_Radians: f32) callconv(.C) f32 {
var Radians = arg_Radians;
var Result: f32 = sinf(Radians);
return Result;
}
pub fn HMM_CosF(arg_Radians: f32) callconv(.C) f32 {
var Radians = arg_Radians;
var Result: f32 = cosf(Radians);
return Result;
}
pub fn HMM_TanF(arg_Radians: f32) callconv(.C) f32 {
var Radians = arg_Radians;
var Result: f32 = tanf(Radians);
return Result;
}
pub fn HMM_ACosF(arg_Radians: f32) callconv(.C) f32 {
var Radians = arg_Radians;
var Result: f32 = acosf(Radians);
return Result;
}
pub fn HMM_ATanF(arg_Radians: f32) callconv(.C) f32 {
var Radians = arg_Radians;
var Result: f32 = atanf(Radians);
return Result;
}
pub fn HMM_ATan2F(arg_Left: f32, arg_Right: f32) callconv(.C) f32 {
var Left = arg_Left;
var Right = arg_Right;
var Result: f32 = atan2f(Left, Right);
return Result;
}
pub fn HMM_ExpF(arg_Float: f32) callconv(.C) f32 {
var Float = arg_Float;
var Result: f32 = expf(Float);
return Result;
}
pub fn HMM_LogF(arg_Float: f32) callconv(.C) f32 {
var Float = arg_Float;
var Result: f32 = logf(Float);
return Result;
}
pub fn HMM_SquareRootF(arg_Float: f32) callconv(.C) f32 {
var Float = arg_Float;
var Result: f32 = undefined;
var In: __m128 = _mm_set_ss(Float);
var Out: __m128 = _mm_sqrt_ss(In);
Result = _mm_cvtss_f32(Out);
return Result;
}
pub fn HMM_RSquareRootF(arg_Float: f32) callconv(.C) f32 {
var Float = arg_Float;
var Result: f32 = undefined;
var In: __m128 = _mm_set_ss(Float);
var Out: __m128 = _mm_rsqrt_ss(In);
Result = _mm_cvtss_f32(Out);
return Result;
}
pub extern fn HMM_Power(Base: f32, Exponent: c_int) f32;
pub fn HMM_PowerF(arg_Base: f32, arg_Exponent: f32) callconv(.C) f32 {
var Base = arg_Base;
var Exponent = arg_Exponent;
var Result: f32 = expf(Exponent * logf(Base));
return Result;
}
pub fn HMM_ToRadians(arg_Degrees: f32) callconv(.C) f32 {
var Degrees = arg_Degrees;
var Result: f32 = Degrees * (3.1415927410125732 / 180.0);
return Result;
}
pub fn HMM_Lerp(arg_A: f32, arg_Time: f32, arg_B: f32) callconv(.C) f32 {
var A = arg_A;
var Time = arg_Time;
var B = arg_B;
var Result: f32 = ((1.0 - Time) * A) + (Time * B);
return Result;
}
pub fn HMM_Clamp(arg_Min: f32, arg_Value: f32, arg_Max: f32) callconv(.C) f32 {
var Min = arg_Min;
var Value = arg_Value;
var Max = arg_Max;
var Result: f32 = Value;
if (Result < Min) {
Result = Min;
}
if (Result > Max) {
Result = Max;
}
return Result;
}
pub fn HMM_Vec2(arg_X: f32, arg_Y: f32) callconv(.C) hmm_vec2 {
var X = arg_X;
var Y = arg_Y;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = X;
Result.unnamed_0.Y = Y;
return Result;
}
pub fn HMM_Vec2i(arg_X: c_int, arg_Y: c_int) callconv(.C) hmm_vec2 {
var X = arg_X;
var Y = arg_Y;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = @intToFloat(f32, X);
Result.unnamed_0.Y = @intToFloat(f32, Y);
return Result;
}
pub fn HMM_Vec3(arg_X: f32, arg_Y: f32, arg_Z: f32) callconv(.C) hmm_vec3 {
var X = arg_X;
var Y = arg_Y;
var Z = arg_Z;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = X;
Result.unnamed_0.Y = Y;
Result.unnamed_0.Z = Z;
return Result;
}
pub fn HMM_Vec3i(arg_X: c_int, arg_Y: c_int, arg_Z: c_int) callconv(.C) hmm_vec3 {
var X = arg_X;
var Y = arg_Y;
var Z = arg_Z;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = @intToFloat(f32, X);
Result.unnamed_0.Y = @intToFloat(f32, Y);
Result.unnamed_0.Z = @intToFloat(f32, Z);
return Result;
}
pub fn HMM_Vec4(arg_X: f32, arg_Y: f32, arg_Z: f32, arg_W: f32) callconv(.C) hmm_vec4 {
var X = arg_X;
var Y = arg_Y;
var Z = arg_Z;
var W = arg_W;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_setr_ps(X, Y, Z, W);
return Result;
}
pub fn HMM_Vec4i(arg_X: c_int, arg_Y: c_int, arg_Z: c_int, arg_W: c_int) callconv(.C) hmm_vec4 {
var X = arg_X;
var Y = arg_Y;
var Z = arg_Z;
var W = arg_W;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_setr_ps(@intToFloat(f32, X), @intToFloat(f32, Y), @intToFloat(f32, Z), @intToFloat(f32, W));
return Result;
}
pub fn HMM_Vec4v(arg_Vector: hmm_vec3, arg_W: f32) callconv(.C) hmm_vec4 {
var Vector = arg_Vector;
var W = arg_W;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_setr_ps(Vector.unnamed_0.X, Vector.unnamed_0.Y, Vector.unnamed_0.Z, W);
return Result;
}
pub fn HMM_AddVec2(arg_Left: hmm_vec2, arg_Right: hmm_vec2) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X + Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y + Right.unnamed_0.Y;
return Result;
}
pub fn HMM_AddVec3(arg_Left: hmm_vec3, arg_Right: hmm_vec3) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X + Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y + Right.unnamed_0.Y;
Result.unnamed_0.Z = Left.unnamed_0.Z + Right.unnamed_0.Z;
return Result;
}
pub fn HMM_AddVec4(arg_Left: hmm_vec4, arg_Right: hmm_vec4) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_add_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
}
pub fn HMM_SubtractVec2(arg_Left: hmm_vec2, arg_Right: hmm_vec2) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X - Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y - Right.unnamed_0.Y;
return Result;
}
pub fn HMM_SubtractVec3(arg_Left: hmm_vec3, arg_Right: hmm_vec3) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X - Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y - Right.unnamed_0.Y;
Result.unnamed_0.Z = Left.unnamed_0.Z - Right.unnamed_0.Z;
return Result;
}
pub fn HMM_SubtractVec4(arg_Left: hmm_vec4, arg_Right: hmm_vec4) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_sub_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
}
pub fn HMM_MultiplyVec2(arg_Left: hmm_vec2, arg_Right: hmm_vec2) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X * Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y * Right.unnamed_0.Y;
return Result;
}
pub fn HMM_MultiplyVec2f(arg_Left: hmm_vec2, arg_Right: f32) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X * Right;
Result.unnamed_0.Y = Left.unnamed_0.Y * Right;
return Result;
}
pub fn HMM_MultiplyVec3(arg_Left: hmm_vec3, arg_Right: hmm_vec3) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X * Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y * Right.unnamed_0.Y;
Result.unnamed_0.Z = Left.unnamed_0.Z * Right.unnamed_0.Z;
return Result;
}
pub fn HMM_MultiplyVec3f(arg_Left: hmm_vec3, arg_Right: f32) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X * Right;
Result.unnamed_0.Y = Left.unnamed_0.Y * Right;
Result.unnamed_0.Z = Left.unnamed_0.Z * Right;
return Result;
}
pub fn HMM_MultiplyVec4(arg_Left: hmm_vec4, arg_Right: hmm_vec4) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_mul_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
}
pub fn HMM_MultiplyVec4f(arg_Left: hmm_vec4, arg_Right: f32) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
var Scalar: __m128 = _mm_set1_ps(Right);
Result.InternalElementsSSE = _mm_mul_ps(Left.InternalElementsSSE, Scalar);
return Result;
}
pub fn HMM_DivideVec2(arg_Left: hmm_vec2, arg_Right: hmm_vec2) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X / Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y / Right.unnamed_0.Y;
return Result;
}
pub fn HMM_DivideVec2f(arg_Left: hmm_vec2, arg_Right: f32) callconv(.C) hmm_vec2 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec2 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X / Right;
Result.unnamed_0.Y = Left.unnamed_0.Y / Right;
return Result;
}
pub fn HMM_DivideVec3(arg_Left: hmm_vec3, arg_Right: hmm_vec3) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X / Right.unnamed_0.X;
Result.unnamed_0.Y = Left.unnamed_0.Y / Right.unnamed_0.Y;
Result.unnamed_0.Z = Left.unnamed_0.Z / Right.unnamed_0.Z;
return Result;
}
pub fn HMM_DivideVec3f(arg_Left: hmm_vec3, arg_Right: f32) callconv(.C) hmm_vec3 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = Left.unnamed_0.X / Right;
Result.unnamed_0.Y = Left.unnamed_0.Y / Right;
Result.unnamed_0.Z = Left.unnamed_0.Z / Right;
return Result;
}
pub fn HMM_DivideVec4(arg_Left: hmm_vec4, arg_Right: hmm_vec4) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
Result.InternalElementsSSE = _mm_div_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
}
pub fn HMM_DivideVec4f(arg_Left: hmm_vec4, arg_Right: f32) callconv(.C) hmm_vec4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_vec4 = undefined;
var Scalar: __m128 = _mm_set1_ps(Right);
Result.InternalElementsSSE = _mm_div_ps(Left.InternalElementsSSE, Scalar);
return Result;
}
pub fn HMM_EqualsVec2(arg_Left: hmm_vec2, arg_Right: hmm_vec2) callconv(.C) hmm_bool {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_bool = @boolToInt((Left.unnamed_0.X == Right.unnamed_0.X) and (Left.unnamed_0.Y == Right.unnamed_0.Y));
return Result;
}
pub fn HMM_EqualsVec3(arg_Left: hmm_vec3, arg_Right: hmm_vec3) callconv(.C) hmm_bool {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_bool = @boolToInt(((Left.unnamed_0.X == Right.unnamed_0.X) and (Left.unnamed_0.Y == Right.unnamed_0.Y)) and (Left.unnamed_0.Z == Right.unnamed_0.Z));
return Result;
}
pub fn HMM_EqualsVec4(arg_Left: hmm_vec4, arg_Right: hmm_vec4) callconv(.C) hmm_bool {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_bool = @boolToInt((((Left.unnamed_0.unnamed_0.unnamed_0.X == Right.unnamed_0.unnamed_0.unnamed_0.X) and (Left.unnamed_0.unnamed_0.unnamed_0.Y == Right.unnamed_0.unnamed_0.unnamed_0.Y)) and (Left.unnamed_0.unnamed_0.unnamed_0.Z == Right.unnamed_0.unnamed_0.unnamed_0.Z)) and (Left.unnamed_0.W == Right.unnamed_0.W));
return Result;
}
pub fn HMM_DotVec2(arg_VecOne: hmm_vec2, arg_VecTwo: hmm_vec2) callconv(.C) f32 {
var VecOne = arg_VecOne;
var VecTwo = arg_VecTwo;
var Result: f32 = (VecOne.unnamed_0.X * VecTwo.unnamed_0.X) + (VecOne.unnamed_0.Y * VecTwo.unnamed_0.Y);
return Result;
}
pub fn HMM_DotVec3(arg_VecOne: hmm_vec3, arg_VecTwo: hmm_vec3) callconv(.C) f32 {
var VecOne = arg_VecOne;
var VecTwo = arg_VecTwo;
var Result: f32 = ((VecOne.unnamed_0.X * VecTwo.unnamed_0.X) + (VecOne.unnamed_0.Y * VecTwo.unnamed_0.Y)) + (VecOne.unnamed_0.Z * VecTwo.unnamed_0.Z);
return Result;
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2604:11: warning: TODO implement function '__builtin_ia32_shufps' in std.c.builtins
// (no file):78:1: warning: unable to translate function, demoted to extern
pub extern fn HMM_DotVec4(arg_VecOne: hmm_vec4, arg_VecTwo: hmm_vec4) callconv(.C) f32;
pub fn HMM_Cross(arg_VecOne: hmm_vec3, arg_VecTwo: hmm_vec3) callconv(.C) hmm_vec3 {
var VecOne = arg_VecOne;
var VecTwo = arg_VecTwo;
var Result: hmm_vec3 = undefined;
Result.unnamed_0.X = (VecOne.unnamed_0.Y * VecTwo.unnamed_0.Z) - (VecOne.unnamed_0.Z * VecTwo.unnamed_0.Y);
Result.unnamed_0.Y = (VecOne.unnamed_0.Z * VecTwo.unnamed_0.X) - (VecOne.unnamed_0.X * VecTwo.unnamed_0.Z);
Result.unnamed_0.Z = (VecOne.unnamed_0.X * VecTwo.unnamed_0.Y) - (VecOne.unnamed_0.Y * VecTwo.unnamed_0.X);
return Result;
}
pub fn HMM_LengthSquaredVec2(arg_A: hmm_vec2) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_DotVec2(A, A);
return Result;
}
pub fn HMM_LengthSquaredVec3(arg_A: hmm_vec3) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_DotVec3(A, A);
return Result;
}
pub fn HMM_LengthSquaredVec4(arg_A: hmm_vec4) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_DotVec4(A, A);
return Result;
}
pub fn HMM_LengthVec2(arg_A: hmm_vec2) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_SquareRootF(HMM_LengthSquaredVec2(A));
return Result;
}
pub fn HMM_LengthVec3(arg_A: hmm_vec3) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_SquareRootF(HMM_LengthSquaredVec3(A));
return Result;
}
pub fn HMM_LengthVec4(arg_A: hmm_vec4) callconv(.C) f32 {
var A = arg_A;
var Result: f32 = HMM_SquareRootF(HMM_LengthSquaredVec4(A));
return Result;
}
pub fn HMM_NormalizeVec2(arg_A: hmm_vec2) callconv(.C) hmm_vec2 {
var A = arg_A;
var Result: hmm_vec2 = hmm_vec2{
.unnamed_0 = struct_unnamed_4{
.X = @intToFloat(f32, @as(c_int, 0)),
.Y = 0,
},
};
var VectorLength: f32 = HMM_LengthVec2(A);
if (VectorLength != 0.0) {
Result.unnamed_0.X = A.unnamed_0.X * (1.0 / VectorLength);
Result.unnamed_0.Y = A.unnamed_0.Y * (1.0 / VectorLength);
}
return Result;
}
pub fn HMM_NormalizeVec3(arg_A: hmm_vec3) callconv(.C) hmm_vec3 {
var A = arg_A;
var Result: hmm_vec3 = hmm_vec3{
.unnamed_0 = struct_unnamed_8{
.X = @intToFloat(f32, @as(c_int, 0)),
.Y = 0,
.Z = 0,
},
};
var VectorLength: f32 = HMM_LengthVec3(A);
if (VectorLength != 0.0) {
Result.unnamed_0.X = A.unnamed_0.X * (1.0 / VectorLength);
Result.unnamed_0.Y = A.unnamed_0.Y * (1.0 / VectorLength);
Result.unnamed_0.Z = A.unnamed_0.Z * (1.0 / VectorLength);
}
return Result;
}
pub fn HMM_NormalizeVec4(arg_A: hmm_vec4) callconv(.C) hmm_vec4 {
var A = arg_A;
var Result: hmm_vec4 = hmm_vec4{
.unnamed_0 = struct_unnamed_15{
.unnamed_0 = union_unnamed_16{
.XYZ = hmm_vec3{
.unnamed_0 = struct_unnamed_8{
.X = @intToFloat(f32, @as(c_int, 0)),
.Y = 0,
.Z = 0,
},
},
},
.W = 0,
},
};
var VectorLength: f32 = HMM_LengthVec4(A);
if (VectorLength != 0.0) {
var Multiplier: f32 = 1.0 / VectorLength;
var SSEMultiplier: __m128 = _mm_set1_ps(Multiplier);
Result.InternalElementsSSE = _mm_mul_ps(A.InternalElementsSSE, SSEMultiplier);
}
return Result;
}
pub fn HMM_FastNormalizeVec2(arg_A: hmm_vec2) callconv(.C) hmm_vec2 {
var A = arg_A;
return HMM_MultiplyVec2f(A, HMM_RSquareRootF(HMM_DotVec2(A, A)));
}
pub fn HMM_FastNormalizeVec3(arg_A: hmm_vec3) callconv(.C) hmm_vec3 {
var A = arg_A;
return HMM_MultiplyVec3f(A, HMM_RSquareRootF(HMM_DotVec3(A, A)));
}
pub fn HMM_FastNormalizeVec4(arg_A: hmm_vec4) callconv(.C) hmm_vec4 {
var A = arg_A;
return HMM_MultiplyVec4f(A, HMM_RSquareRootF(HMM_DotVec4(A, A)));
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2604:11: warning: TODO implement function '__builtin_ia32_shufps' in std.c.builtins
// (no file):113:1: warning: unable to translate function, demoted to extern
pub extern fn HMM_LinearCombineSSE(arg_Left: __m128, arg_Right: hmm_mat4) callconv(.C) __m128;
pub export fn HMM_Mat4() hmm_mat4 {
var Result: hmm_mat4 = hmm_mat4{
.Elements = [1][4]f32{
[1]f32{
0,
} ++ [1]f32{0} ** 3,
} ++ [1][4]f32{@import("std").mem.zeroes([4]f32)} ** 3,
};
return Result;
}
pub fn HMM_Mat4d(arg_Diagonal: f32) callconv(.C) hmm_mat4 {
var Diagonal = arg_Diagonal;
var Result: hmm_mat4 = hmm_mat4{
.Elements = [1][4]f32{
[1]f32{
0,
} ++ [1]f32{0} ** 3,
} ++ [1][4]f32{@import("std").mem.zeroes([4]f32)} ** 3,
};
Result.Elements[@intCast(c_uint, @as(c_int, 0))][@intCast(c_uint, @as(c_int, 0))] = Diagonal;
Result.Elements[@intCast(c_uint, @as(c_int, 1))][@intCast(c_uint, @as(c_int, 1))] = Diagonal;
Result.Elements[@intCast(c_uint, @as(c_int, 2))][@intCast(c_uint, @as(c_int, 2))] = Diagonal;
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 3))] = Diagonal;
return Result;
}
pub fn HMM_Transpose(arg_Matrix: hmm_mat4) callconv(.C) hmm_mat4 {
var Matrix = arg_Matrix;
var Result: hmm_mat4 = Matrix;
{
var tmp3: __m128 = undefined;
var tmp2: __m128 = undefined;
var tmp1: __m128 = undefined;
var tmp0: __m128 = undefined;
tmp0 = _mm_unpacklo_ps(Result.Columns[@intCast(c_uint, @as(c_int, 0))], Result.Columns[@intCast(c_uint, @as(c_int, 1))]);
tmp2 = _mm_unpacklo_ps(Result.Columns[@intCast(c_uint, @as(c_int, 2))], Result.Columns[@intCast(c_uint, @as(c_int, 3))]);
tmp1 = _mm_unpackhi_ps(Result.Columns[@intCast(c_uint, @as(c_int, 0))], Result.Columns[@intCast(c_uint, @as(c_int, 1))]);
tmp3 = _mm_unpackhi_ps(Result.Columns[@intCast(c_uint, @as(c_int, 2))], Result.Columns[@intCast(c_uint, @as(c_int, 3))]);
Result.Columns[@intCast(c_uint, @as(c_int, 0))] = _mm_movelh_ps(tmp0, tmp2);
Result.Columns[@intCast(c_uint, @as(c_int, 1))] = _mm_movehl_ps(tmp2, tmp0);
Result.Columns[@intCast(c_uint, @as(c_int, 2))] = _mm_movelh_ps(tmp1, tmp3);
Result.Columns[@intCast(c_uint, @as(c_int, 3))] = _mm_movehl_ps(tmp3, tmp1);
}
return Result;
}
pub fn HMM_AddMat4(arg_Left: hmm_mat4, arg_Right: hmm_mat4) callconv(.C) hmm_mat4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_mat4 = undefined;
Result.Columns[@intCast(c_uint, @as(c_int, 0))] = _mm_add_ps(Left.Columns[@intCast(c_uint, @as(c_int, 0))], Right.Columns[@intCast(c_uint, @as(c_int, 0))]);
Result.Columns[@intCast(c_uint, @as(c_int, 1))] = _mm_add_ps(Left.Columns[@intCast(c_uint, @as(c_int, 1))], Right.Columns[@intCast(c_uint, @as(c_int, 1))]);
Result.Columns[@intCast(c_uint, @as(c_int, 2))] = _mm_add_ps(Left.Columns[@intCast(c_uint, @as(c_int, 2))], Right.Columns[@intCast(c_uint, @as(c_int, 2))]);
Result.Columns[@intCast(c_uint, @as(c_int, 3))] = _mm_add_ps(Left.Columns[@intCast(c_uint, @as(c_int, 3))], Right.Columns[@intCast(c_uint, @as(c_int, 3))]);
return Result;
}
pub fn HMM_SubtractMat4(arg_Left: hmm_mat4, arg_Right: hmm_mat4) callconv(.C) hmm_mat4 {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_mat4 = undefined;
Result.Columns[@intCast(c_uint, @as(c_int, 0))] = _mm_sub_ps(Left.Columns[@intCast(c_uint, @as(c_int, 0))], Right.Columns[@intCast(c_uint, @as(c_int, 0))]);
Result.Columns[@intCast(c_uint, @as(c_int, 1))] = _mm_sub_ps(Left.Columns[@intCast(c_uint, @as(c_int, 1))], Right.Columns[@intCast(c_uint, @as(c_int, 1))]);
Result.Columns[@intCast(c_uint, @as(c_int, 2))] = _mm_sub_ps(Left.Columns[@intCast(c_uint, @as(c_int, 2))], Right.Columns[@intCast(c_uint, @as(c_int, 2))]);
Result.Columns[@intCast(c_uint, @as(c_int, 3))] = _mm_sub_ps(Left.Columns[@intCast(c_uint, @as(c_int, 3))], Right.Columns[@intCast(c_uint, @as(c_int, 3))]);
return Result;
}
pub extern fn HMM_MultiplyMat4(Left: hmm_mat4, Right: hmm_mat4) hmm_mat4;
pub fn HMM_MultiplyMat4f(arg_Matrix: hmm_mat4, arg_Scalar: f32) callconv(.C) hmm_mat4 {
var Matrix = arg_Matrix;
var Scalar = arg_Scalar;
var Result: hmm_mat4 = undefined;
var SSEScalar: __m128 = _mm_set1_ps(Scalar);
Result.Columns[@intCast(c_uint, @as(c_int, 0))] = _mm_mul_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 0))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 1))] = _mm_mul_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 1))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 2))] = _mm_mul_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 2))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 3))] = _mm_mul_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 3))], SSEScalar);
return Result;
}
pub extern fn HMM_MultiplyMat4ByVec4(Matrix: hmm_mat4, Vector: hmm_vec4) hmm_vec4;
pub fn HMM_DivideMat4f(arg_Matrix: hmm_mat4, arg_Scalar: f32) callconv(.C) hmm_mat4 {
var Matrix = arg_Matrix;
var Scalar = arg_Scalar;
var Result: hmm_mat4 = undefined;
var SSEScalar: __m128 = _mm_set1_ps(Scalar);
Result.Columns[@intCast(c_uint, @as(c_int, 0))] = _mm_div_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 0))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 1))] = _mm_div_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 1))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 2))] = _mm_div_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 2))], SSEScalar);
Result.Columns[@intCast(c_uint, @as(c_int, 3))] = _mm_div_ps(Matrix.Columns[@intCast(c_uint, @as(c_int, 3))], SSEScalar);
return Result;
}
pub fn HMM_Orthographic(arg_Left: f32, arg_Right: f32, arg_Bottom: f32, arg_Top: f32, arg_Near: f32, arg_Far: f32) callconv(.C) hmm_mat4 {
var Left = arg_Left;
var Right = arg_Right;
var Bottom = arg_Bottom;
var Top = arg_Top;
var Near = arg_Near;
var Far = arg_Far;
var Result: hmm_mat4 = HMM_Mat4();
Result.Elements[@intCast(c_uint, @as(c_int, 0))][@intCast(c_uint, @as(c_int, 0))] = 2.0 / (Right - Left);
Result.Elements[@intCast(c_uint, @as(c_int, 1))][@intCast(c_uint, @as(c_int, 1))] = 2.0 / (Top - Bottom);
Result.Elements[@intCast(c_uint, @as(c_int, 2))][@intCast(c_uint, @as(c_int, 2))] = 2.0 / (Near - Far);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 3))] = 1.0;
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 0))] = (Left + Right) / (Left - Right);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 1))] = (Bottom + Top) / (Bottom - Top);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 2))] = (Far + Near) / (Near - Far);
return Result;
}
pub fn HMM_Perspective(arg_FOV: f32, arg_AspectRatio: f32, arg_Near: f32, arg_Far: f32) callconv(.C) hmm_mat4 {
var FOV = arg_FOV;
var AspectRatio = arg_AspectRatio;
var Near = arg_Near;
var Far = arg_Far;
var Result: hmm_mat4 = HMM_Mat4();
var Cotangent: f32 = 1.0 / HMM_TanF(FOV * (3.1415927410125732 / 360.0));
Result.Elements[@intCast(c_uint, @as(c_int, 0))][@intCast(c_uint, @as(c_int, 0))] = Cotangent / AspectRatio;
Result.Elements[@intCast(c_uint, @as(c_int, 1))][@intCast(c_uint, @as(c_int, 1))] = Cotangent;
Result.Elements[@intCast(c_uint, @as(c_int, 2))][@intCast(c_uint, @as(c_int, 3))] = -1.0;
Result.Elements[@intCast(c_uint, @as(c_int, 2))][@intCast(c_uint, @as(c_int, 2))] = (Near + Far) / (Near - Far);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 2))] = ((2.0 * Near) * Far) / (Near - Far);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 3))] = 0.0;
return Result;
}
pub fn HMM_Translate(arg_Translation: hmm_vec3) callconv(.C) hmm_mat4 {
var Translation = arg_Translation;
var Result: hmm_mat4 = HMM_Mat4d(1.0);
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 0))] = Translation.unnamed_0.X;
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 1))] = Translation.unnamed_0.Y;
Result.Elements[@intCast(c_uint, @as(c_int, 3))][@intCast(c_uint, @as(c_int, 2))] = Translation.unnamed_0.Z;
return Result;
}
pub extern fn HMM_Rotate(Angle: f32, Axis: hmm_vec3) hmm_mat4;
pub fn HMM_Scale(arg_Scale: hmm_vec3) callconv(.C) hmm_mat4 {
var Scale = arg_Scale;
var Result: hmm_mat4 = HMM_Mat4d(1.0);
Result.Elements[@intCast(c_uint, @as(c_int, 0))][@intCast(c_uint, @as(c_int, 0))] = Scale.unnamed_0.X;
Result.Elements[@intCast(c_uint, @as(c_int, 1))][@intCast(c_uint, @as(c_int, 1))] = Scale.unnamed_0.Y;
Result.Elements[@intCast(c_uint, @as(c_int, 2))][@intCast(c_uint, @as(c_int, 2))] = Scale.unnamed_0.Z;
return Result;
}
pub extern fn HMM_LookAt(Eye: hmm_vec3, Center: hmm_vec3, Up: hmm_vec3) hmm_mat4;
pub fn HMM_Quaternion(arg_X: f32, arg_Y: f32, arg_Z: f32, arg_W: f32) callconv(.C) hmm_quaternion {
var X = arg_X;
var Y = arg_Y;
var Z = arg_Z;
var W = arg_W;
var Result: hmm_quaternion = undefined;
Result.InternalElementsSSE = _mm_setr_ps(X, Y, Z, W);
return Result;
}
pub fn HMM_QuaternionV4(arg_Vector: hmm_vec4) callconv(.C) hmm_quaternion {
var Vector = arg_Vector;
var Result: hmm_quaternion = undefined;
Result.InternalElementsSSE = Vector.InternalElementsSSE;
return Result;
}
pub fn HMM_AddQuaternion(arg_Left: hmm_quaternion, arg_Right: hmm_quaternion) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_quaternion = undefined;
Result.InternalElementsSSE = _mm_add_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
}
pub fn HMM_SubtractQuaternion(arg_Left: hmm_quaternion, arg_Right: hmm_quaternion) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Right = arg_Right;
var Result: hmm_quaternion = undefined;
Result.InternalElementsSSE = _mm_sub_ps(Left.InternalElementsSSE, Right.InternalElementsSSE);
return Result;
} // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2604:11: warning: TODO implement function '__builtin_ia32_shufps' in std.c.builtins
// (no file):137:1: warning: unable to translate function, demoted to extern
pub extern fn HMM_MultiplyQuaternion(arg_Left: hmm_quaternion, arg_Right: hmm_quaternion) callconv(.C) hmm_quaternion;
pub fn HMM_MultiplyQuaternionF(arg_Left: hmm_quaternion, arg_Multiplicative: f32) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Multiplicative = arg_Multiplicative;
var Result: hmm_quaternion = undefined;
var Scalar: __m128 = _mm_set1_ps(Multiplicative);
Result.InternalElementsSSE = _mm_mul_ps(Left.InternalElementsSSE, Scalar);
return Result;
}
pub fn HMM_DivideQuaternionF(arg_Left: hmm_quaternion, arg_Dividend: f32) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Dividend = arg_Dividend;
var Result: hmm_quaternion = undefined;
var Scalar: __m128 = _mm_set1_ps(Dividend);
Result.InternalElementsSSE = _mm_div_ps(Left.InternalElementsSSE, Scalar);
return Result;
}
pub extern fn HMM_InverseQuaternion(Left: hmm_quaternion) hmm_quaternion; // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2604:11: warning: TODO implement function '__builtin_ia32_shufps' in std.c.builtins
// (no file):141:1: warning: unable to translate function, demoted to extern
pub extern fn HMM_DotQuaternion(arg_Left: hmm_quaternion, arg_Right: hmm_quaternion) callconv(.C) f32;
pub fn HMM_NormalizeQuaternion(arg_Left: hmm_quaternion) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Result: hmm_quaternion = undefined;
var Length: f32 = HMM_SquareRootF(HMM_DotQuaternion(Left, Left));
Result = HMM_DivideQuaternionF(Left, Length);
return Result;
}
pub fn HMM_NLerp(arg_Left: hmm_quaternion, arg_Time: f32, arg_Right: hmm_quaternion) callconv(.C) hmm_quaternion {
var Left = arg_Left;
var Time = arg_Time;
var Right = arg_Right;
var Result: hmm_quaternion = undefined;
var ScalarLeft: __m128 = _mm_set1_ps(1.0 - Time);
var ScalarRight: __m128 = _mm_set1_ps(Time);
var SSEResultOne: __m128 = _mm_mul_ps(Left.InternalElementsSSE, ScalarLeft);
var SSEResultTwo: __m128 = _mm_mul_ps(Right.InternalElementsSSE, ScalarRight);
Result.InternalElementsSSE = _mm_add_ps(SSEResultOne, SSEResultTwo);
Result = HMM_NormalizeQuaternion(Result);
return Result;
}
pub extern fn HMM_Slerp(Left: hmm_quaternion, Time: f32, Right: hmm_quaternion) hmm_quaternion;
pub extern fn HMM_QuaternionToMat4(Left: hmm_quaternion) hmm_mat4;
pub extern fn HMM_Mat4ToQuaternion(Left: hmm_mat4) hmm_quaternion;
pub extern fn HMM_QuaternionFromAxisAngle(Axis: hmm_vec3, AngleOfRotation: f32) hmm_quaternion;
pub const __INTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):61:9
pub const __UINTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):65:9
pub const __PTRDIFF_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):72:9
pub const __INTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):76:9
pub const __SIZE_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):80:9
pub const __UINTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):95:9
pub const __INT64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):159:9
pub const __UINT64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):187:9
pub const __INT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):225:9
pub const __UINT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):229:9
pub const __INT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):265:9
pub const __UINT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // (no file):269:9
pub const COVERAGE = @compileError("unable to translate C expr: unexpected token .Eof"); // .\handmade_math\HandmadeMath.h:107:9
pub const ASSERT_COVERED = @compileError("unable to translate C expr: unexpected token .Eof"); // .\handmade_math\HandmadeMath.h:111:9
pub const __STRINGIFY = @compileError("unable to translate C expr: unexpected token .Hash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:10:9
pub const __MINGW64_VERSION_STR = @compileError("unable to translate C expr: unexpected token .StringLiteral"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:26:9
pub const __MINGW_IMP_SYMBOL = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:119:11
pub const __MINGW_IMP_LSYMBOL = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:120:11
pub const __MINGW_LSYMBOL = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:122:11
pub const __MINGW_POISON_NAME = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:203:11
pub const __MSABI_LONG = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:209:13
pub const __MINGW_ATTRIB_DEPRECATED_STR = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:247:11
pub const __mingw_ovr = @compileError("unable to translate C expr: unexpected token .Keyword_static"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_mac.h:289:11
pub const __MINGW_CRT_NAME_CONCAT2 = @compileError("unable to translate C expr: unexpected token .Colon"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_secapi.h:41:9
pub const __CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY_0_3_ = @compileError("unable to translate C expr: unexpected token .Identifier"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any/_mingw_secapi.h:69:9
pub const __MINGW_IMPORT = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:51:12
pub const __CRT_INLINE = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:90:11
pub const __MINGW_INTRIN_INLINE = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:97:9
pub const __MINGW_PRAGMA_PARAM = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:215:9
pub const __MINGW_BROKEN_INTERFACE = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:218:9
pub const __int64 = @compileError("unable to translate C expr: unexpected token .Keyword_long"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:242:9
pub const __forceinline = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:267:9
pub const _crt_va_start = @compileError("TODO implement function '__builtin_va_start' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\vadefs.h:48:9
pub const _crt_va_arg = @compileError("TODO implement function '__builtin_va_arg' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\vadefs.h:49:9
pub const _crt_va_end = @compileError("TODO implement function '__builtin_va_end' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\vadefs.h:50:9
pub const _crt_va_copy = @compileError("TODO implement function '__builtin_va_copy' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\vadefs.h:51:9
pub const __CRT_STRINGIZE = @compileError("unable to translate C expr: unexpected token .Hash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:286:9
pub const __CRT_WIDE = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:291:9
pub const _CRT_INSECURE_DEPRECATE_MEMORY = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:353:9
pub const _CRT_INSECURE_DEPRECATE_GLOBALS = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:357:9
pub const _CRT_OBSOLETE = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:365:9
pub const _UNION_NAME = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:476:9
pub const _STRUCT_NAME = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:477:9
pub const __CRT_UUID_DECL = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\_mingw.h:564:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_0 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:267:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:268:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_2 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:269:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_3 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:270:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_4 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:271:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_1 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:272:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_2 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:273:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_3 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:274:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_2_0 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:275:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1_ARGLIST = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:276:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_2_ARGLIST = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:277:9
pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_SPLITPATH = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:278:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_0 = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:282:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_1 = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:284:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_2 = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:286:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_3 = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:288:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_4 = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:290:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_0_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:427:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_1_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:428:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_2_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:429:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_3_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:430:9
pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_4_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:431:9
pub const __crt_typefix = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\corecrt.h:491:9
pub const _STATIC_ASSERT = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\malloc.h:27:9
pub const _alloca = @compileError("TODO implement function '__builtin_alloca' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\malloc.h:93:9
pub const alloca = @compileError("TODO implement function '__builtin_alloca' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\malloc.h:159:9
pub const _mm_prefetch = @compileError("TODO implement function '__builtin_prefetch' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2103:9
pub const _mm_extract_pi16 = @compileError("TODO implement function '__builtin_ia32_vec_ext_v4hi' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2183:9
pub const _mm_insert_pi16 = @compileError("TODO implement function '__builtin_ia32_vec_set_v4hi' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2214:9
pub const _mm_shuffle_pi16 = @compileError("TODO implement function '__builtin_ia32_pshufw' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2361:9
pub const _mm_shuffle_ps = @compileError("TODO implement function '__builtin_ia32_shufps' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2603:9
pub const _MM_TRANSPOSE4_PS = @compileError("unable to translate C expr: unexpected token .Keyword_do"); // C:\Users\ross\Desktop\zig\lib\include\xmmintrin.h:2970:9
pub const _mm_slli_si128 = @compileError("TODO implement function '__builtin_ia32_pslldqi128_byteshift' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2820:9
pub const _mm_bslli_si128 = @compileError("TODO implement function '__builtin_ia32_pslldqi128_byteshift' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:2823:9
pub const _mm_srli_si128 = @compileError("TODO implement function '__builtin_ia32_psrldqi128_byteshift' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3037:9
pub const _mm_bsrli_si128 = @compileError("TODO implement function '__builtin_ia32_psrldqi128_byteshift' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:3040:9
pub const _mm_extract_epi16 = @compileError("TODO implement function '__builtin_ia32_vec_ext_v8hi' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4358:9
pub const _mm_insert_epi16 = @compileError("TODO implement function '__builtin_ia32_vec_set_v8hi' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4382:9
pub const _mm_shuffle_epi32 = @compileError("TODO implement function '__builtin_ia32_pshufd' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4432:9
pub const _mm_shufflelo_epi16 = @compileError("TODO implement function '__builtin_ia32_pshuflw' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4462:9
pub const _mm_shufflehi_epi16 = @compileError("TODO implement function '__builtin_ia32_pshufhw' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4492:9
pub const _mm_shuffle_pd = @compileError("TODO implement function '__builtin_ia32_shufpd' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\include\emmintrin.h:4846:9
pub const HMM_INLINE = @compileError("unable to translate C expr: unexpected token .Keyword_static"); // .\handmade_math\HandmadeMath.h:167:9
pub const HMM_DEF = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // .\handmade_math\HandmadeMath.h:172:9
pub const __mingw_types_compatible_p = @compileError("TODO implement function '__builtin_types_compatible_p' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:97:9
pub const __mingw_choose_expr = @compileError("TODO implement function '__builtin_choose_expr' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:105:9
pub const HUGE_VAL = @compileError("TODO implement function '__builtin_huge_val' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:156:9
pub const HUGE_VALF = @compileError("TODO implement function '__builtin_huge_valf' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:349:9
pub const HUGE_VALL = @compileError("TODO implement function '__builtin_huge_vall' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:350:9
pub const INFINITY = @compileError("TODO implement function '__builtin_inff' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:351:9
pub const NAN = @compileError("TODO implement function '__builtin_nanf' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:352:9
pub const fpclassify = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:492:9
pub const isnan = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:586:9
pub const signbit = @compileError("unable to translate C expr: expected ',' or ')'"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:646:9
pub const isgreater = @compileError("TODO implement function '__builtin_isgreater' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1144:9
pub const isgreaterequal = @compileError("TODO implement function '__builtin_isgreaterequal' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1145:9
pub const isless = @compileError("TODO implement function '__builtin_isless' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1146:9
pub const islessequal = @compileError("TODO implement function '__builtin_islessequal' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1147:9
pub const islessgreater = @compileError("TODO implement function '__builtin_islessgreater' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1148:9
pub const isunordered = @compileError("TODO implement function '__builtin_isunordered' in std.c.builtins"); // C:\Users\ross\Desktop\zig\lib\libc\include\any-windows-any\math.h:1149:9
pub const HMM_PREFIX = @compileError("unable to translate C expr: unexpected token .HashHash"); // .\handmade_math\HandmadeMath.h:227:9
pub const __llvm__ = @as(c_int, 1);
pub const __clang__ = @as(c_int, 1);
pub const __clang_major__ = @as(c_int, 12);
pub const __clang_minor__ = @as(c_int, 0);
pub const __clang_patchlevel__ = @as(c_int, 1);
pub const __clang_version__ = "12.0.1 (https://github.com/ziglang/zig-bootstrap 8cc2870e09320a390cafe4e23624e8ed40bd363c)";
pub const __GNUC__ = @as(c_int, 4);
pub const __GNUC_MINOR__ = @as(c_int, 2);
pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1);
pub const __GXX_ABI_VERSION = @as(c_int, 1002);
pub const __ATOMIC_RELAXED = @as(c_int, 0);
pub const __ATOMIC_CONSUME = @as(c_int, 1);
pub const __ATOMIC_ACQUIRE = @as(c_int, 2);
pub const __ATOMIC_RELEASE = @as(c_int, 3);
pub const __ATOMIC_ACQ_REL = @as(c_int, 4);
pub const __ATOMIC_SEQ_CST = @as(c_int, 5);
pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0);
pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1);
pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2);
pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3);
pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4);
pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1);
pub const __VERSION__ = "Clang 12.0.1 (https://github.com/ziglang/zig-bootstrap 8cc2870e09320a390cafe4e23624e8ed40bd363c)";
pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0);
pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1);
pub const __SEH__ = @as(c_int, 1);
pub const __OPTIMIZE__ = @as(c_int, 1);
pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234);
pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321);
pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412);
pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__;
pub const __LITTLE_ENDIAN__ = @as(c_int, 1);
pub const __CHAR_BIT__ = @as(c_int, 8);
pub const __SCHAR_MAX__ = @as(c_int, 127);
pub const __SHRT_MAX__ = @as(c_int, 32767);
pub const __INT_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const __LONG_MAX__ = @as(c_long, 2147483647);
pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __WCHAR_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 65535, .decimal);
pub const __WINT_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 65535, .decimal);
pub const __INTMAX_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __SIZE_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __UINTMAX_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __PTRDIFF_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __INTPTR_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __UINTPTR_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __SIZEOF_DOUBLE__ = @as(c_int, 8);
pub const __SIZEOF_FLOAT__ = @as(c_int, 4);
pub const __SIZEOF_INT__ = @as(c_int, 4);
pub const __SIZEOF_LONG__ = @as(c_int, 4);
pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16);
pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8);
pub const __SIZEOF_POINTER__ = @as(c_int, 8);
pub const __SIZEOF_SHORT__ = @as(c_int, 2);
pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8);
pub const __SIZEOF_SIZE_T__ = @as(c_int, 8);
pub const __SIZEOF_WCHAR_T__ = @as(c_int, 2);
pub const __SIZEOF_WINT_T__ = @as(c_int, 2);
pub const __SIZEOF_INT128__ = @as(c_int, 16);
pub const __INTMAX_FMTd__ = "lld";
pub const __INTMAX_FMTi__ = "lli";
pub const __INTMAX_C_SUFFIX__ = LL;
pub const __UINTMAX_FMTo__ = "llo";
pub const __UINTMAX_FMTu__ = "llu";
pub const __UINTMAX_FMTx__ = "llx";
pub const __UINTMAX_FMTX__ = "llX";
pub const __UINTMAX_C_SUFFIX__ = ULL;
pub const __INTMAX_WIDTH__ = @as(c_int, 64);
pub const __PTRDIFF_FMTd__ = "lld";
pub const __PTRDIFF_FMTi__ = "lli";
pub const __PTRDIFF_WIDTH__ = @as(c_int, 64);
pub const __INTPTR_FMTd__ = "lld";
pub const __INTPTR_FMTi__ = "lli";
pub const __INTPTR_WIDTH__ = @as(c_int, 64);
pub const __SIZE_FMTo__ = "llo";
pub const __SIZE_FMTu__ = "llu";
pub const __SIZE_FMTx__ = "llx";
pub const __SIZE_FMTX__ = "llX";
pub const __SIZE_WIDTH__ = @as(c_int, 64);
pub const __WCHAR_TYPE__ = c_ushort;
pub const __WCHAR_WIDTH__ = @as(c_int, 16);
pub const __WINT_TYPE__ = c_ushort;
pub const __WINT_WIDTH__ = @as(c_int, 16);
pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32);
pub const __SIG_ATOMIC_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const __CHAR16_TYPE__ = c_ushort;
pub const __CHAR32_TYPE__ = c_uint;
pub const __UINTMAX_WIDTH__ = @as(c_int, 64);
pub const __UINTPTR_FMTo__ = "llo";
pub const __UINTPTR_FMTu__ = "llu";
pub const __UINTPTR_FMTx__ = "llx";
pub const __UINTPTR_FMTX__ = "llX";
pub const __UINTPTR_WIDTH__ = @as(c_int, 64);
pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45);
pub const __FLT_HAS_DENORM__ = @as(c_int, 1);
pub const __FLT_DIG__ = @as(c_int, 6);
pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9);
pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7);
pub const __FLT_HAS_INFINITY__ = @as(c_int, 1);
pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1);
pub const __FLT_MANT_DIG__ = @as(c_int, 24);
pub const __FLT_MAX_10_EXP__ = @as(c_int, 38);
pub const __FLT_MAX_EXP__ = @as(c_int, 128);
pub const __FLT_MAX__ = @as(f32, 3.40282347e+38);
pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37);
pub const __FLT_MIN_EXP__ = -@as(c_int, 125);
pub const __FLT_MIN__ = @as(f32, 1.17549435e-38);
pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324;
pub const __DBL_HAS_DENORM__ = @as(c_int, 1);
pub const __DBL_DIG__ = @as(c_int, 15);
pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17);
pub const __DBL_EPSILON__ = 2.2204460492503131e-16;
pub const __DBL_HAS_INFINITY__ = @as(c_int, 1);
pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1);
pub const __DBL_MANT_DIG__ = @as(c_int, 53);
pub const __DBL_MAX_10_EXP__ = @as(c_int, 308);
pub const __DBL_MAX_EXP__ = @as(c_int, 1024);
pub const __DBL_MAX__ = 1.7976931348623157e+308;
pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307);
pub const __DBL_MIN_EXP__ = -@as(c_int, 1021);
pub const __DBL_MIN__ = 2.2250738585072014e-308;
pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951);
pub const __LDBL_HAS_DENORM__ = @as(c_int, 1);
pub const __LDBL_DIG__ = @as(c_int, 18);
pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21);
pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19);
pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1);
pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1);
pub const __LDBL_MANT_DIG__ = @as(c_int, 64);
pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932);
pub const __LDBL_MAX_EXP__ = @as(c_int, 16384);
pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932);
pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931);
pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381);
pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932);
pub const __POINTER_WIDTH__ = @as(c_int, 64);
pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16);
pub const __WCHAR_UNSIGNED__ = @as(c_int, 1);
pub const __WINT_UNSIGNED__ = @as(c_int, 1);
pub const __INT8_TYPE__ = i8;
pub const __INT8_FMTd__ = "hhd";
pub const __INT8_FMTi__ = "hhi";
pub const __INT16_TYPE__ = c_short;
pub const __INT16_FMTd__ = "hd";
pub const __INT16_FMTi__ = "hi";
pub const __INT32_TYPE__ = c_int;
pub const __INT32_FMTd__ = "d";
pub const __INT32_FMTi__ = "i";
pub const __INT64_FMTd__ = "lld";
pub const __INT64_FMTi__ = "lli";
pub const __INT64_C_SUFFIX__ = LL;
pub const __UINT8_TYPE__ = u8;
pub const __UINT8_FMTo__ = "hho";
pub const __UINT8_FMTu__ = "hhu";
pub const __UINT8_FMTx__ = "hhx";
pub const __UINT8_FMTX__ = "hhX";
pub const __UINT8_MAX__ = @as(c_int, 255);
pub const __INT8_MAX__ = @as(c_int, 127);
pub const __UINT16_TYPE__ = c_ushort;
pub const __UINT16_FMTo__ = "ho";
pub const __UINT16_FMTu__ = "hu";
pub const __UINT16_FMTx__ = "hx";
pub const __UINT16_FMTX__ = "hX";
pub const __UINT16_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 65535, .decimal);
pub const __INT16_MAX__ = @as(c_int, 32767);
pub const __UINT32_TYPE__ = c_uint;
pub const __UINT32_FMTo__ = "o";
pub const __UINT32_FMTu__ = "u";
pub const __UINT32_FMTx__ = "x";
pub const __UINT32_FMTX__ = "X";
pub const __UINT32_C_SUFFIX__ = U;
pub const __UINT32_MAX__ = @import("std").meta.promoteIntLiteral(c_uint, 4294967295, .decimal);
pub const __INT32_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const __UINT64_FMTo__ = "llo";
pub const __UINT64_FMTu__ = "llu";
pub const __UINT64_FMTx__ = "llx";
pub const __UINT64_FMTX__ = "llX";
pub const __UINT64_C_SUFFIX__ = ULL;
pub const __UINT64_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __INT64_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __INT_LEAST8_TYPE__ = i8;
pub const __INT_LEAST8_MAX__ = @as(c_int, 127);
pub const __INT_LEAST8_FMTd__ = "hhd";
pub const __INT_LEAST8_FMTi__ = "hhi";
pub const __UINT_LEAST8_TYPE__ = u8;
pub const __UINT_LEAST8_MAX__ = @as(c_int, 255);
pub const __UINT_LEAST8_FMTo__ = "hho";
pub const __UINT_LEAST8_FMTu__ = "hhu";
pub const __UINT_LEAST8_FMTx__ = "hhx";
pub const __UINT_LEAST8_FMTX__ = "hhX";
pub const __INT_LEAST16_TYPE__ = c_short;
pub const __INT_LEAST16_MAX__ = @as(c_int, 32767);
pub const __INT_LEAST16_FMTd__ = "hd";
pub const __INT_LEAST16_FMTi__ = "hi";
pub const __UINT_LEAST16_TYPE__ = c_ushort;
pub const __UINT_LEAST16_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 65535, .decimal);
pub const __UINT_LEAST16_FMTo__ = "ho";
pub const __UINT_LEAST16_FMTu__ = "hu";
pub const __UINT_LEAST16_FMTx__ = "hx";
pub const __UINT_LEAST16_FMTX__ = "hX";
pub const __INT_LEAST32_TYPE__ = c_int;
pub const __INT_LEAST32_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const __INT_LEAST32_FMTd__ = "d";
pub const __INT_LEAST32_FMTi__ = "i";
pub const __UINT_LEAST32_TYPE__ = c_uint;
pub const __UINT_LEAST32_MAX__ = @import("std").meta.promoteIntLiteral(c_uint, 4294967295, .decimal);
pub const __UINT_LEAST32_FMTo__ = "o";
pub const __UINT_LEAST32_FMTu__ = "u";
pub const __UINT_LEAST32_FMTx__ = "x";
pub const __UINT_LEAST32_FMTX__ = "X";
pub const __INT_LEAST64_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __INT_LEAST64_FMTd__ = "lld";
pub const __INT_LEAST64_FMTi__ = "lli";
pub const __UINT_LEAST64_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __UINT_LEAST64_FMTo__ = "llo";
pub const __UINT_LEAST64_FMTu__ = "llu";
pub const __UINT_LEAST64_FMTx__ = "llx";
pub const __UINT_LEAST64_FMTX__ = "llX";
pub const __INT_FAST8_TYPE__ = i8;
pub const __INT_FAST8_MAX__ = @as(c_int, 127);
pub const __INT_FAST8_FMTd__ = "hhd";
pub const __INT_FAST8_FMTi__ = "hhi";
pub const __UINT_FAST8_TYPE__ = u8;
pub const __UINT_FAST8_MAX__ = @as(c_int, 255);
pub const __UINT_FAST8_FMTo__ = "hho";
pub const __UINT_FAST8_FMTu__ = "hhu";
pub const __UINT_FAST8_FMTx__ = "hhx";
pub const __UINT_FAST8_FMTX__ = "hhX";
pub const __INT_FAST16_TYPE__ = c_short;
pub const __INT_FAST16_MAX__ = @as(c_int, 32767);
pub const __INT_FAST16_FMTd__ = "hd";
pub const __INT_FAST16_FMTi__ = "hi";
pub const __UINT_FAST16_TYPE__ = c_ushort;
pub const __UINT_FAST16_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 65535, .decimal);
pub const __UINT_FAST16_FMTo__ = "ho";
pub const __UINT_FAST16_FMTu__ = "hu";
pub const __UINT_FAST16_FMTx__ = "hx";
pub const __UINT_FAST16_FMTX__ = "hX";
pub const __INT_FAST32_TYPE__ = c_int;
pub const __INT_FAST32_MAX__ = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const __INT_FAST32_FMTd__ = "d";
pub const __INT_FAST32_FMTi__ = "i";
pub const __UINT_FAST32_TYPE__ = c_uint;
pub const __UINT_FAST32_MAX__ = @import("std").meta.promoteIntLiteral(c_uint, 4294967295, .decimal);
pub const __UINT_FAST32_FMTo__ = "o";
pub const __UINT_FAST32_FMTu__ = "u";
pub const __UINT_FAST32_FMTx__ = "x";
pub const __UINT_FAST32_FMTX__ = "X";
pub const __INT_FAST64_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __INT_FAST64_FMTd__ = "lld";
pub const __INT_FAST64_FMTi__ = "lli";
pub const __UINT_FAST64_MAX__ = @as(c_ulonglong, 18446744073709551615);
pub const __UINT_FAST64_FMTo__ = "llo";
pub const __UINT_FAST64_FMTu__ = "llu";
pub const __UINT_FAST64_FMTx__ = "llx";
pub const __UINT_FAST64_FMTX__ = "llX";
pub const __FINITE_MATH_ONLY__ = @as(c_int, 0);
pub const __GNUC_STDC_INLINE__ = @as(c_int, 1);
pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1);
pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2);
pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2);
pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2);
pub const __PIC__ = @as(c_int, 2);
pub const __pic__ = @as(c_int, 2);
pub const __FLT_EVAL_METHOD__ = @as(c_int, 0);
pub const __FLT_RADIX__ = @as(c_int, 2);
pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__;
pub const __SSP_STRONG__ = @as(c_int, 2);
pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1);
pub const __code_model_small__ = @as(c_int, 1);
pub const __amd64__ = @as(c_int, 1);
pub const __amd64 = @as(c_int, 1);
pub const __x86_64 = @as(c_int, 1);
pub const __x86_64__ = @as(c_int, 1);
pub const __SEG_GS = @as(c_int, 1);
pub const __SEG_FS = @as(c_int, 1);
pub const __seg_gs = __attribute__(address_space(@as(c_int, 256)));
pub const __seg_fs = __attribute__(address_space(@as(c_int, 257)));
pub const __corei7 = @as(c_int, 1);
pub const __corei7__ = @as(c_int, 1);
pub const __tune_corei7__ = @as(c_int, 1);
pub const __NO_MATH_INLINES = @as(c_int, 1);
pub const __AES__ = @as(c_int, 1);
pub const __PCLMUL__ = @as(c_int, 1);
pub const __LAHF_SAHF__ = @as(c_int, 1);
pub const __LZCNT__ = @as(c_int, 1);
pub const __RDRND__ = @as(c_int, 1);
pub const __FSGSBASE__ = @as(c_int, 1);
pub const __BMI__ = @as(c_int, 1);
pub const __BMI2__ = @as(c_int, 1);
pub const __POPCNT__ = @as(c_int, 1);
pub const __RTM__ = @as(c_int, 1);
pub const __PRFCHW__ = @as(c_int, 1);
pub const __RDSEED__ = @as(c_int, 1);
pub const __ADX__ = @as(c_int, 1);
pub const __MOVBE__ = @as(c_int, 1);
pub const __FMA__ = @as(c_int, 1);
pub const __F16C__ = @as(c_int, 1);
pub const __FXSR__ = @as(c_int, 1);
pub const __XSAVE__ = @as(c_int, 1);
pub const __XSAVEOPT__ = @as(c_int, 1);
pub const __XSAVEC__ = @as(c_int, 1);
pub const __XSAVES__ = @as(c_int, 1);
pub const __CLFLUSHOPT__ = @as(c_int, 1);
pub const __INVPCID__ = @as(c_int, 1);
pub const __AVX2__ = @as(c_int, 1);
pub const __AVX__ = @as(c_int, 1);
pub const __SSE4_2__ = @as(c_int, 1);
pub const __SSE4_1__ = @as(c_int, 1);
pub const __SSSE3__ = @as(c_int, 1);
pub const __SSE3__ = @as(c_int, 1);
pub const __SSE2__ = @as(c_int, 1);
pub const __SSE2_MATH__ = @as(c_int, 1);
pub const __SSE__ = @as(c_int, 1);
pub const __SSE_MATH__ = @as(c_int, 1);
pub const __MMX__ = @as(c_int, 1);
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1);
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1);
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1);
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1);
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1);
pub const __SIZEOF_FLOAT128__ = @as(c_int, 16);
pub const _WIN32 = @as(c_int, 1);
pub const _WIN64 = @as(c_int, 1);
pub const WIN32 = @as(c_int, 1);
pub const __WIN32 = @as(c_int, 1);
pub const __WIN32__ = @as(c_int, 1);
pub const WINNT = @as(c_int, 1);
pub const __WINNT = @as(c_int, 1);
pub const __WINNT__ = @as(c_int, 1);
pub const WIN64 = @as(c_int, 1);
pub const __WIN64 = @as(c_int, 1);
pub const __WIN64__ = @as(c_int, 1);
pub const __MINGW64__ = @as(c_int, 1);
pub const __MSVCRT__ = @as(c_int, 1);
pub const __MINGW32__ = @as(c_int, 1);
pub inline fn __declspec(a: anytype) @TypeOf(__attribute__(a)) {
return __attribute__(a);
}
pub const _cdecl = __attribute__(__cdecl__);
pub const __cdecl = __attribute__(__cdecl__);
pub const _stdcall = __attribute__(__stdcall__);
pub const __stdcall = __attribute__(__stdcall__);
pub const _fastcall = __attribute__(__fastcall__);
pub const __fastcall = __attribute__(__fastcall__);
pub const _thiscall = __attribute__(__thiscall__);
pub const __thiscall = __attribute__(__thiscall__);
pub const _pascal = __attribute__(__pascal__);
pub const __pascal = __attribute__(__pascal__);
pub const __STDC__ = @as(c_int, 1);
pub const __STDC_HOSTED__ = @as(c_int, 1);
pub const __STDC_VERSION__ = @as(c_long, 201710);
pub const __STDC_UTF_16__ = @as(c_int, 1);
pub const __STDC_UTF_32__ = @as(c_int, 1);
pub const _DEBUG = @as(c_int, 1);
pub const HANDMADE_MATH__USE_SSE = @as(c_int, 1);
pub const __DEFAULT_FN_ATTRS = __attribute__(blk: {
_ = __always_inline__;
_ = __nodebug__;
_ = __target__("mmx");
break :blk __min_vector_width__(@as(c_int, 64));
});
pub const _m_empty = _mm_empty;
pub const _m_from_int = _mm_cvtsi32_si64;
pub const _m_from_int64 = _mm_cvtsi64_m64;
pub const _m_to_int = _mm_cvtsi64_si32;
pub const _m_to_int64 = _mm_cvtm64_si64;
pub const _m_packsswb = _mm_packs_pi16;
pub const _m_packssdw = _mm_packs_pi32;
pub const _m_packuswb = _mm_packs_pu16;
pub const _m_punpckhbw = _mm_unpackhi_pi8;
pub const _m_punpckhwd = _mm_unpackhi_pi16;
pub const _m_punpckhdq = _mm_unpackhi_pi32;
pub const _m_punpcklbw = _mm_unpacklo_pi8;
pub const _m_punpcklwd = _mm_unpacklo_pi16;
pub const _m_punpckldq = _mm_unpacklo_pi32;
pub const _m_paddb = _mm_add_pi8;
pub const _m_paddw = _mm_add_pi16;
pub const _m_paddd = _mm_add_pi32;
pub const _m_paddsb = _mm_adds_pi8;
pub const _m_paddsw = _mm_adds_pi16;
pub const _m_paddusb = _mm_adds_pu8;
pub const _m_paddusw = _mm_adds_pu16;
pub const _m_psubb = _mm_sub_pi8;
pub const _m_psubw = _mm_sub_pi16;
pub const _m_psubd = _mm_sub_pi32;
pub const _m_psubsb = _mm_subs_pi8;
pub const _m_psubsw = _mm_subs_pi16;
pub const _m_psubusb = _mm_subs_pu8;
pub const _m_psubusw = _mm_subs_pu16;
pub const _m_pmaddwd = _mm_madd_pi16;
pub const _m_pmulhw = _mm_mulhi_pi16;
pub const _m_pmullw = _mm_mullo_pi16;
pub const _m_psllw = _mm_sll_pi16;
pub const _m_psllwi = _mm_slli_pi16;
pub const _m_pslld = _mm_sll_pi32;
pub const _m_pslldi = _mm_slli_pi32;
pub const _m_psllq = _mm_sll_si64;
pub const _m_psllqi = _mm_slli_si64;
pub const _m_psraw = _mm_sra_pi16;
pub const _m_psrawi = _mm_srai_pi16;
pub const _m_psrad = _mm_sra_pi32;
pub const _m_psradi = _mm_srai_pi32;
pub const _m_psrlw = _mm_srl_pi16;
pub const _m_psrlwi = _mm_srli_pi16;
pub const _m_psrld = _mm_srl_pi32;
pub const _m_psrldi = _mm_srli_pi32;
pub const _m_psrlq = _mm_srl_si64;
pub const _m_psrlqi = _mm_srli_si64;
pub const _m_pand = _mm_and_si64;
pub const _m_pandn = _mm_andnot_si64;
pub const _m_por = _mm_or_si64;
pub const _m_pxor = _mm_xor_si64;
pub const _m_pcmpeqb = _mm_cmpeq_pi8;
pub const _m_pcmpeqw = _mm_cmpeq_pi16;
pub const _m_pcmpeqd = _mm_cmpeq_pi32;
pub const _m_pcmpgtb = _mm_cmpgt_pi8;
pub const _m_pcmpgtw = _mm_cmpgt_pi16;
pub const _m_pcmpgtd = _mm_cmpgt_pi32;
pub inline fn __MINGW64_STRINGIFY(x: anytype) @TypeOf(__STRINGIFY(x)) {
return __STRINGIFY(x);
}
pub const __MINGW64_VERSION_MAJOR = @as(c_int, 9);
pub const __MINGW64_VERSION_MINOR = @as(c_int, 0);
pub const __MINGW64_VERSION_BUGFIX = @as(c_int, 0);
pub const __MINGW64_VERSION_RC = @as(c_int, 0);
pub const __MINGW64_VERSION_STATE = "alpha";
pub const __MINGW32_MAJOR_VERSION = @as(c_int, 3);
pub const __MINGW32_MINOR_VERSION = @as(c_int, 11);
pub const _M_AMD64 = @as(c_int, 100);
pub const _M_X64 = @as(c_int, 100);
pub const _ = @as(c_int, 1);
pub const __MINGW_USE_UNDERSCORE_PREFIX = @as(c_int, 0);
pub inline fn __MINGW_USYMBOL(sym: anytype) @TypeOf(sym) {
return sym;
}
pub inline fn __MINGW_ASM_CALL(func: anytype) @TypeOf(__asm__(__MINGW64_STRINGIFY(__MINGW_USYMBOL(func)))) {
return __asm__(__MINGW64_STRINGIFY(__MINGW_USYMBOL(func)));
}
pub inline fn __MINGW_ASM_CRT_CALL(func: anytype) @TypeOf(__asm__(__STRINGIFY(func))) {
return __asm__(__STRINGIFY(func));
}
pub const __MINGW_EXTENSION = __extension__;
pub const __C89_NAMELESS = __MINGW_EXTENSION;
pub const __GNU_EXTENSION = __MINGW_EXTENSION;
pub const __MINGW_HAVE_ANSI_C99_PRINTF = @as(c_int, 1);
pub const __MINGW_HAVE_WIDE_C99_PRINTF = @as(c_int, 1);
pub const __MINGW_HAVE_ANSI_C99_SCANF = @as(c_int, 1);
pub const __MINGW_HAVE_WIDE_C99_SCANF = @as(c_int, 1);
pub const __MINGW_GCC_VERSION = ((__GNUC__ * @as(c_int, 10000)) + (__GNUC_MINOR__ * @as(c_int, 100))) + __GNUC_PATCHLEVEL__;
pub inline fn __MINGW_GNUC_PREREQ(major: anytype, minor: anytype) @TypeOf((__GNUC__ > major) or ((__GNUC__ == major) and (__GNUC_MINOR__ >= minor))) {
return (__GNUC__ > major) or ((__GNUC__ == major) and (__GNUC_MINOR__ >= minor));
}
pub inline fn __MINGW_MSC_PREREQ(major: anytype, minor: anytype) @TypeOf(@as(c_int, 0)) {
return @as(c_int, 0);
}
pub const __MINGW_SEC_WARN_STR = "This function or variable may be unsafe, use _CRT_SECURE_NO_WARNINGS to disable deprecation";
pub const __MINGW_MSVC2005_DEPREC_STR = "This POSIX function is deprecated beginning in Visual C++ 2005, use _CRT_NONSTDC_NO_DEPRECATE to disable deprecation";
pub const __MINGW_ATTRIB_DEPRECATED_MSVC2005 = __MINGW_ATTRIB_DEPRECATED_STR(__MINGW_MSVC2005_DEPREC_STR);
pub const __MINGW_ATTRIB_DEPRECATED_SEC_WARN = __MINGW_ATTRIB_DEPRECATED_STR(__MINGW_SEC_WARN_STR);
pub inline fn __MINGW_MS_PRINTF(__format: anytype, __args: anytype) @TypeOf(__attribute__(__format__(ms_printf, __format, __args))) {
return __attribute__(__format__(ms_printf, __format, __args));
}
pub inline fn __MINGW_MS_SCANF(__format: anytype, __args: anytype) @TypeOf(__attribute__(__format__(ms_scanf, __format, __args))) {
return __attribute__(__format__(ms_scanf, __format, __args));
}
pub inline fn __MINGW_GNU_PRINTF(__format: anytype, __args: anytype) @TypeOf(__attribute__(__format__(gnu_printf, __format, __args))) {
return __attribute__(__format__(gnu_printf, __format, __args));
}
pub inline fn __MINGW_GNU_SCANF(__format: anytype, __args: anytype) @TypeOf(__attribute__(__format__(gnu_scanf, __format, __args))) {
return __attribute__(__format__(gnu_scanf, __format, __args));
}
pub const __mingw_static_ovr = __mingw_ovr;
pub const __MINGW_FORTIFY_LEVEL = @as(c_int, 0);
pub const __mingw_bos_ovr = __mingw_ovr;
pub const __MINGW_FORTIFY_VA_ARG = @as(c_int, 0);
pub const _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES = @as(c_int, 0);
pub const _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES_MEMORY = @as(c_int, 0);
pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES = @as(c_int, 0);
pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT = @as(c_int, 0);
pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY = @as(c_int, 0);
pub const __LONG32 = c_long;
pub const __USE_CRTIMP = @as(c_int, 1);
pub const _CRTIMP = __attribute__(__dllimport__);
pub const USE___UUIDOF = @as(c_int, 0);
pub const _inline = __inline;
pub inline fn __UNUSED_PARAM(x: anytype) @TypeOf(x ++ __attribute__(__unused__)) {
return x ++ __attribute__(__unused__);
}
pub const __restrict_arr = __restrict;
pub const __MINGW_ATTRIB_NORETURN = __attribute__(__noreturn__);
pub const __MINGW_ATTRIB_CONST = __attribute__(__const__);
pub const __MINGW_ATTRIB_MALLOC = __attribute__(__malloc__);
pub const __MINGW_ATTRIB_PURE = __attribute__(__pure__);
pub inline fn __MINGW_ATTRIB_NONNULL(arg: anytype) @TypeOf(__attribute__(__nonnull__(arg))) {
return __attribute__(__nonnull__(arg));
}
pub const __MINGW_ATTRIB_UNUSED = __attribute__(__unused__);
pub const __MINGW_ATTRIB_USED = __attribute__(__used__);
pub const __MINGW_ATTRIB_DEPRECATED = __attribute__(__deprecated__);
pub inline fn __MINGW_ATTRIB_DEPRECATED_MSG(x: anytype) @TypeOf(__attribute__(__deprecated__(x))) {
return __attribute__(__deprecated__(x));
}
pub const __MINGW_NOTHROW = __attribute__(__nothrow__);
pub const __MSVCRT_VERSION__ = @as(c_int, 0x700);
pub const _WIN32_WINNT = @as(c_int, 0x0603);
pub const __int8 = u8;
pub const __int16 = c_short;
pub const __int32 = c_int;
pub const MINGW_HAS_SECURE_API = @as(c_int, 1);
pub const __STDC_SECURE_LIB__ = @as(c_long, 200411);
pub const __GOT_SECURE_LIB__ = __STDC_SECURE_LIB__;
pub const MINGW_HAS_DDK_H = @as(c_int, 1);
pub const _CRT_PACKING = @as(c_int, 8);
pub inline fn _ADDRESSOF(v: anytype) @TypeOf(&v) {
return &v;
}
pub inline fn _CRT_STRINGIZE(_Value: anytype) @TypeOf(__CRT_STRINGIZE(_Value)) {
return __CRT_STRINGIZE(_Value);
}
pub inline fn _CRT_WIDE(_String: anytype) @TypeOf(__CRT_WIDE(_String)) {
return __CRT_WIDE(_String);
}
pub const _CRTIMP_NOIA64 = _CRTIMP;
pub const _CRTIMP2 = _CRTIMP;
pub const _CRTIMP_ALTERNATIVE = _CRTIMP;
pub const _MRTIMP2 = _CRTIMP;
pub const _MCRTIMP = _CRTIMP;
pub const _CRTIMP_PURE = _CRTIMP;
pub const _SECURECRT_FILL_BUFFER_PATTERN = @as(c_int, 0xFD);
pub inline fn _CRT_DEPRECATE_TEXT(_Text: anytype) @TypeOf(__declspec(deprecated)) {
return __declspec(deprecated);
}
pub const UNALIGNED = __unaligned;
pub inline fn _CRT_ALIGN(x: anytype) @TypeOf(__attribute__(__aligned__(x))) {
return __attribute__(__aligned__(x));
}
pub const __CRTDECL = __cdecl;
pub const _ARGMAX = @as(c_int, 100);
pub const _TRUNCATE = usize - @as(c_int, 1);
pub inline fn _CRT_UNUSED(x: anytype) c_void {
return @import("std").meta.cast(c_void, x);
}
pub const __USE_MINGW_ANSI_STDIO = @as(c_int, 1);
pub const _CRT_glob = _dowildcard;
pub const _ANONYMOUS_UNION = __MINGW_EXTENSION;
pub const _ANONYMOUS_STRUCT = __MINGW_EXTENSION;
pub const __MINGW_DEBUGBREAK_IMPL = !(__has_builtin(__debugbreak) != 0);
pub const _CRT_SECURE_CPP_NOTHROW = throw();
pub const PATH_MAX = @as(c_int, 260);
pub const CHAR_BIT = @as(c_int, 8);
pub const SCHAR_MIN = -@as(c_int, 128);
pub const SCHAR_MAX = @as(c_int, 127);
pub const UCHAR_MAX = @as(c_int, 0xff);
pub const CHAR_MIN = SCHAR_MIN;
pub const CHAR_MAX = SCHAR_MAX;
pub const MB_LEN_MAX = @as(c_int, 5);
pub const SHRT_MIN = -@import("std").meta.promoteIntLiteral(c_int, 32768, .decimal);
pub const SHRT_MAX = @as(c_int, 32767);
pub const USHRT_MAX = @as(c_uint, 0xffff);
pub const INT_MIN = -@import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal) - @as(c_int, 1);
pub const INT_MAX = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const UINT_MAX = @import("std").meta.promoteIntLiteral(c_uint, 0xffffffff, .hexadecimal);
pub const LONG_MIN = -@as(c_long, 2147483647) - @as(c_int, 1);
pub const LONG_MAX = @as(c_long, 2147483647);
pub const ULONG_MAX = @as(c_ulong, 0xffffffff);
pub const LLONG_MAX = @as(c_longlong, 9223372036854775807);
pub const LLONG_MIN = -@as(c_longlong, 9223372036854775807) - @as(c_int, 1);
pub const ULLONG_MAX = @as(c_ulonglong, 0xffffffffffffffff);
pub const _I8_MIN = -@as(c_int, 127) - @as(c_int, 1);
pub const _I8_MAX = @as(c_int, 127);
pub const _UI8_MAX = @as(c_uint, 0xff);
pub const _I16_MIN = -@as(c_int, 32767) - @as(c_int, 1);
pub const _I16_MAX = @as(c_int, 32767);
pub const _UI16_MAX = @as(c_uint, 0xffff);
pub const _I32_MIN = -@import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal) - @as(c_int, 1);
pub const _I32_MAX = @import("std").meta.promoteIntLiteral(c_int, 2147483647, .decimal);
pub const _UI32_MAX = @import("std").meta.promoteIntLiteral(c_uint, 0xffffffff, .hexadecimal);
pub const LONG_LONG_MAX = @as(c_longlong, 9223372036854775807);
pub const LONG_LONG_MIN = -LONG_LONG_MAX - @as(c_int, 1);
pub const ULONG_LONG_MAX = (@as(c_ulonglong, 2) * LONG_LONG_MAX) + @as(c_ulonglong, 1);
pub const _I64_MIN = -@as(c_longlong, 9223372036854775807) - @as(c_int, 1);
pub const _I64_MAX = @as(c_longlong, 9223372036854775807);
pub const _UI64_MAX = @as(c_ulonglong, 0xffffffffffffffff);
pub const SIZE_MAX = _UI64_MAX;
pub const SSIZE_MAX = _I64_MAX;
pub const __USE_MINGW_STRTOX = @as(c_int, 1);
pub const _SECIMP = __declspec(dllimport);
pub const NULL = @import("std").meta.cast(?*c_void, @as(c_int, 0));
pub const EXIT_SUCCESS = @as(c_int, 0);
pub const EXIT_FAILURE = @as(c_int, 1);
pub const onexit_t = _onexit_t;
pub inline fn _PTR_LD(x: anytype) [*c]u8 {
return @import("std").meta.cast([*c]u8, &x.*.ld);
}
pub const RAND_MAX = @as(c_int, 0x7fff);
pub const MB_CUR_MAX = ___mb_cur_max_func();
pub const __mb_cur_max = ___mb_cur_max_func();
pub inline fn __max(a: anytype, b: anytype) @TypeOf(if (a > b) a else b) {
return if (a > b) a else b;
}
pub inline fn __min(a: anytype, b: anytype) @TypeOf(if (a < b) a else b) {
return if (a < b) a else b;
}
pub const _MAX_PATH = @as(c_int, 260);
pub const _MAX_DRIVE = @as(c_int, 3);
pub const _MAX_DIR = @as(c_int, 256);
pub const _MAX_FNAME = @as(c_int, 256);
pub const _MAX_EXT = @as(c_int, 256);
pub const _OUT_TO_DEFAULT = @as(c_int, 0);
pub const _OUT_TO_STDERR = @as(c_int, 1);
pub const _OUT_TO_MSGBOX = @as(c_int, 2);
pub const _REPORT_ERRMODE = @as(c_int, 3);
pub const _WRITE_ABORT_MSG = @as(c_int, 0x1);
pub const _CALL_REPORTFAULT = @as(c_int, 0x2);
pub const _MAX_ENV = @as(c_int, 32767);
pub const errno = _errno().*;
pub const _doserrno = __doserrno().*;
pub const _fmode = __p__fmode().*;
pub const __argc = __MINGW_IMP_SYMBOL(__argc).*;
pub const __argv = __p___argv().*;
pub const __wargv = __MINGW_IMP_SYMBOL(__wargv).*;
pub const _environ = __MINGW_IMP_SYMBOL(_environ).*;
pub const _wenviron = __MINGW_IMP_SYMBOL(_wenviron).*;
pub const _pgmptr = __MINGW_IMP_SYMBOL(_pgmptr).*;
pub const _wpgmptr = __MINGW_IMP_SYMBOL(_wpgmptr).*;
pub const _osplatform = __MINGW_IMP_SYMBOL(_osplatform).*;
pub const _osver = __MINGW_IMP_SYMBOL(_osver).*;
pub const _winver = __MINGW_IMP_SYMBOL(_winver).*;
pub const _winmajor = __MINGW_IMP_SYMBOL(_winmajor).*;
pub const _winminor = __MINGW_IMP_SYMBOL(_winminor).*;
pub inline fn _countof(_Array: anytype) @TypeOf(@import("std").meta.sizeof(_Array) / @import("std").meta.sizeof(_Array[@as(c_int, 0)])) {
return @import("std").meta.sizeof(_Array) / @import("std").meta.sizeof(_Array[@as(c_int, 0)]);
}
pub const _CVTBUFSIZE = @as(c_int, 309) + @as(c_int, 40);
pub const sys_errlist = _sys_errlist;
pub const sys_nerr = _sys_nerr;
pub const environ = _environ;
pub const _HEAP_MAXREQ = @import("std").meta.promoteIntLiteral(c_int, 0xFFFFFFFFFFFFFFE0, .hexadecimal);
pub const _HEAPEMPTY = -@as(c_int, 1);
pub const _HEAPOK = -@as(c_int, 2);
pub const _HEAPBADBEGIN = -@as(c_int, 3);
pub const _HEAPBADNODE = -@as(c_int, 4);
pub const _HEAPEND = -@as(c_int, 5);
pub const _HEAPBADPTR = -@as(c_int, 6);
pub const _FREEENTRY = @as(c_int, 0);
pub const _USEDENTRY = @as(c_int, 1);
pub const _MAX_WAIT_MALLOC_CRT = @import("std").meta.promoteIntLiteral(c_int, 60000, .decimal);
pub const _ALLOCA_S_THRESHOLD = @as(c_int, 1024);
pub const _ALLOCA_S_STACK_MARKER = @import("std").meta.promoteIntLiteral(c_int, 0xCCCC, .hexadecimal);
pub const _ALLOCA_S_HEAP_MARKER = @import("std").meta.promoteIntLiteral(c_int, 0xDDDD, .hexadecimal);
pub const _ALLOCA_S_MARKER_SIZE = @as(c_int, 16);
pub inline fn _malloca(size: anytype) @TypeOf(if ((size + _ALLOCA_S_MARKER_SIZE) <= _ALLOCA_S_THRESHOLD) _MarkAllocaS(_alloca(size + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_STACK_MARKER) else _MarkAllocaS(malloc(size + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_HEAP_MARKER)) {
return if ((size + _ALLOCA_S_MARKER_SIZE) <= _ALLOCA_S_THRESHOLD) _MarkAllocaS(_alloca(size + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_STACK_MARKER) else _MarkAllocaS(malloc(size + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_HEAP_MARKER);
}
pub const __DEFAULT_FN_ATTRS_MMX = __attribute__(blk: {
_ = __always_inline__;
_ = __nodebug__;
_ = __target__("mmx,sse");
break :blk __min_vector_width__(@as(c_int, 64));
});
pub inline fn _mm_load_ps1(p: anytype) @TypeOf(_mm_load1_ps(p)) {
return _mm_load1_ps(p);
}
pub const _MM_HINT_ET0 = @as(c_int, 7);
pub const _MM_HINT_ET1 = @as(c_int, 6);
pub const _MM_HINT_T0 = @as(c_int, 3);
pub const _MM_HINT_T1 = @as(c_int, 2);
pub const _MM_HINT_T2 = @as(c_int, 1);
pub const _MM_HINT_NTA = @as(c_int, 0);
pub const _MM_ALIGN16 = __attribute__(aligned(@as(c_int, 16)));
pub inline fn _MM_SHUFFLE(z: anytype, y: anytype, x: anytype, w: anytype) @TypeOf((((z << @as(c_int, 6)) | (y << @as(c_int, 4))) | (x << @as(c_int, 2))) | w) {
return (((z << @as(c_int, 6)) | (y << @as(c_int, 4))) | (x << @as(c_int, 2))) | w;
}
pub const _MM_EXCEPT_INVALID = @as(c_uint, 0x0001);
pub const _MM_EXCEPT_DENORM = @as(c_uint, 0x0002);
pub const _MM_EXCEPT_DIV_ZERO = @as(c_uint, 0x0004);
pub const _MM_EXCEPT_OVERFLOW = @as(c_uint, 0x0008);
pub const _MM_EXCEPT_UNDERFLOW = @as(c_uint, 0x0010);
pub const _MM_EXCEPT_INEXACT = @as(c_uint, 0x0020);
pub const _MM_EXCEPT_MASK = @as(c_uint, 0x003f);
pub const _MM_MASK_INVALID = @as(c_uint, 0x0080);
pub const _MM_MASK_DENORM = @as(c_uint, 0x0100);
pub const _MM_MASK_DIV_ZERO = @as(c_uint, 0x0200);
pub const _MM_MASK_OVERFLOW = @as(c_uint, 0x0400);
pub const _MM_MASK_UNDERFLOW = @as(c_uint, 0x0800);
pub const _MM_MASK_INEXACT = @as(c_uint, 0x1000);
pub const _MM_MASK_MASK = @as(c_uint, 0x1f80);
pub const _MM_ROUND_NEAREST = @as(c_uint, 0x0000);
pub const _MM_ROUND_DOWN = @as(c_uint, 0x2000);
pub const _MM_ROUND_UP = @as(c_uint, 0x4000);
pub const _MM_ROUND_TOWARD_ZERO = @as(c_uint, 0x6000);
pub const _MM_ROUND_MASK = @as(c_uint, 0x6000);
pub const _MM_FLUSH_ZERO_MASK = @as(c_uint, 0x8000);
pub const _MM_FLUSH_ZERO_ON = @as(c_uint, 0x8000);
pub const _MM_FLUSH_ZERO_OFF = @as(c_uint, 0x0000);
pub inline fn _MM_GET_EXCEPTION_MASK() @TypeOf(_mm_getcsr() & _MM_MASK_MASK) {
return _mm_getcsr() & _MM_MASK_MASK;
}
pub inline fn _MM_GET_EXCEPTION_STATE() @TypeOf(_mm_getcsr() & _MM_EXCEPT_MASK) {
return _mm_getcsr() & _MM_EXCEPT_MASK;
}
pub inline fn _MM_GET_FLUSH_ZERO_MODE() @TypeOf(_mm_getcsr() & _MM_FLUSH_ZERO_MASK) {
return _mm_getcsr() & _MM_FLUSH_ZERO_MASK;
}
pub inline fn _MM_GET_ROUNDING_MODE() @TypeOf(_mm_getcsr() & _MM_ROUND_MASK) {
return _mm_getcsr() & _MM_ROUND_MASK;
}
pub inline fn _MM_SET_EXCEPTION_MASK(x: anytype) @TypeOf(_mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | x)) {
return _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | x);
}
pub inline fn _MM_SET_EXCEPTION_STATE(x: anytype) @TypeOf(_mm_setcsr((_mm_getcsr() & ~_MM_EXCEPT_MASK) | x)) {
return _mm_setcsr((_mm_getcsr() & ~_MM_EXCEPT_MASK) | x);
}
pub inline fn _MM_SET_FLUSH_ZERO_MODE(x: anytype) @TypeOf(_mm_setcsr((_mm_getcsr() & ~_MM_FLUSH_ZERO_MASK) | x)) {
return _mm_setcsr((_mm_getcsr() & ~_MM_FLUSH_ZERO_MASK) | x);
}
pub inline fn _MM_SET_ROUNDING_MODE(x: anytype) @TypeOf(_mm_setcsr((_mm_getcsr() & ~_MM_ROUND_MASK) | x)) {
return _mm_setcsr((_mm_getcsr() & ~_MM_ROUND_MASK) | x);
}
pub const _m_pextrw = _mm_extract_pi16;
pub const _m_pinsrw = _mm_insert_pi16;
pub const _m_pmaxsw = _mm_max_pi16;
pub const _m_pmaxub = _mm_max_pu8;
pub const _m_pminsw = _mm_min_pi16;
pub const _m_pminub = _mm_min_pu8;
pub const _m_pmovmskb = _mm_movemask_pi8;
pub const _m_pmulhuw = _mm_mulhi_pu16;
pub const _m_pshufw = _mm_shuffle_pi16;
pub const _m_maskmovq = _mm_maskmove_si64;
pub const _m_pavgb = _mm_avg_pu8;
pub const _m_pavgw = _mm_avg_pu16;
pub const _m_psadbw = _mm_sad_pu8;
pub const _m_ = _mm_;
pub inline fn _mm_load_pd1(dp: anytype) @TypeOf(_mm_load1_pd(dp)) {
return _mm_load1_pd(dp);
}
pub inline fn _MM_SHUFFLE2(x: anytype, y: anytype) @TypeOf((x << @as(c_int, 1)) | y) {
return (x << @as(c_int, 1)) | y;
}
pub const _MM_DENORMALS_ZERO_ON = @as(c_uint, 0x0040);
pub const _MM_DENORMALS_ZERO_OFF = @as(c_uint, 0x0000);
pub const _MM_DENORMALS_ZERO_MASK = @as(c_uint, 0x0040);
pub inline fn _MM_GET_DENORMALS_ZERO_MODE() @TypeOf(_mm_getcsr() & _MM_DENORMALS_ZERO_MASK) {
return _mm_getcsr() & _MM_DENORMALS_ZERO_MASK;
}
pub inline fn _MM_SET_DENORMALS_ZERO_MODE(x: anytype) @TypeOf(_mm_setcsr((_mm_getcsr() & ~_MM_DENORMALS_ZERO_MASK) | x)) {
return _mm_setcsr((_mm_getcsr() & ~_MM_DENORMALS_ZERO_MASK) | x);
}
pub inline fn HMM_DEPRECATED(msg: anytype) @TypeOf(__attribute__(deprecated(msg))) {
return __attribute__(deprecated(msg));
}
pub const _DOMAIN = @as(c_int, 1);
pub const _SING = @as(c_int, 2);
pub const _OVERFLOW = @as(c_int, 3);
pub const _UNDERFLOW = @as(c_int, 4);
pub const _TLOSS = @as(c_int, 5);
pub const _PLOSS = @as(c_int, 6);
pub const DOMAIN = _DOMAIN;
pub const SING = _SING;
pub const OVERFLOW = _OVERFLOW;
pub const UNDERFLOW = _UNDERFLOW;
pub const TLOSS = _TLOSS;
pub const PLOSS = _PLOSS;
pub const M_E = 2.7182818284590452354;
pub const M_LOG2E = 1.4426950408889634074;
pub const M_LOG10E = 0.43429448190325182765;
pub const M_LN2 = 0.69314718055994530942;
pub const M_LN10 = 2.30258509299404568402;
pub const M_PI = 3.14159265358979323846;
pub const M_PI_2 = 1.57079632679489661923;
pub const M_PI_4 = 0.78539816339744830962;
pub const M_1_PI = 0.31830988618379067154;
pub const M_2_PI = 0.63661977236758134308;
pub const M_2_SQRTPI = 1.12837916709551257390;
pub const M_SQRT2 = 1.41421356237309504880;
pub const M_SQRT1_2 = 0.70710678118654752440;
pub const __MINGW_FPCLASS_DEFINED = @as(c_int, 1);
pub const _FPCLASS_SNAN = @as(c_int, 0x0001);
pub const _FPCLASS_QNAN = @as(c_int, 0x0002);
pub const _FPCLASS_NINF = @as(c_int, 0x0004);
pub const _FPCLASS_NN = @as(c_int, 0x0008);
pub const _FPCLASS_ND = @as(c_int, 0x0010);
pub const _FPCLASS_NZ = @as(c_int, 0x0020);
pub const _FPCLASS_PZ = @as(c_int, 0x0040);
pub const _FPCLASS_PD = @as(c_int, 0x0080);
pub const _FPCLASS_PN = @as(c_int, 0x0100);
pub const _FPCLASS_PINF = @as(c_int, 0x0200);
pub const _HUGE = __MINGW_IMP_SYMBOL(_HUGE).*;
pub const EDOM = @as(c_int, 33);
pub const ERANGE = @as(c_int, 34);
pub const FP_SNAN = _FPCLASS_SNAN;
pub const FP_QNAN = _FPCLASS_QNAN;
pub const FP_NINF = _FPCLASS_NINF;
pub const FP_PINF = _FPCLASS_PINF;
pub const FP_NDENORM = _FPCLASS_ND;
pub const FP_PDENORM = _FPCLASS_PD;
pub const FP_NZERO = _FPCLASS_NZ;
pub const FP_PZERO = _FPCLASS_PZ;
pub const FP_NNORM = _FPCLASS_NN;
pub const FP_PNORM = _FPCLASS_PN;
pub const FP_NAN = @as(c_int, 0x0100);
pub const FP_NORMAL = @as(c_int, 0x0400);
pub const FP_INFINITE = FP_NAN | FP_NORMAL;
pub const FP_ZERO = @as(c_int, 0x4000);
pub const FP_SUBNORMAL = FP_NORMAL | FP_ZERO;
pub inline fn __dfp_expansion(__call: anytype, __fin: anytype, x: anytype) @TypeOf(__fin) {
return __fin;
}
pub inline fn isfinite(x: anytype) @TypeOf((fpclassify(x) & FP_NAN) == @as(c_int, 0)) {
return (fpclassify(x) & FP_NAN) == @as(c_int, 0);
}
pub inline fn isinf(x: anytype) @TypeOf(fpclassify(x) == FP_INFINITE) {
return fpclassify(x) == FP_INFINITE;
}
pub inline fn isnormal(x: anytype) @TypeOf(fpclassify(x) == FP_NORMAL) {
return fpclassify(x) == FP_NORMAL;
}
pub const FP_ILOGB0 = @import("std").meta.cast(c_int, @import("std").meta.promoteIntLiteral(c_int, 0x80000000, .hexadecimal));
pub const FP_ILOGBNAN = @import("std").meta.cast(c_int, @import("std").meta.promoteIntLiteral(c_int, 0x7fffffff, .hexadecimal));
pub inline fn _nan() @TypeOf(nan("")) {
return nan("");
}
pub inline fn _nanf() @TypeOf(nanf("")) {
return nanf("");
}
pub inline fn _nanl() @TypeOf(nanl("")) {
return nanl("");
}
pub const _copysignl = copysignl;
pub const _hypotl = hypotl;
pub const matherr = _matherr;
pub const HUGE = _HUGE;
pub const HMM_SINF = sinf;
pub const HMM_COSF = cosf;
pub const HMM_TANF = tanf;
pub const HMM_SQRTF = sqrtf;
pub const HMM_EXPF = expf;
pub const HMM_LOGF = logf;
pub const HMM_ACOSF = acosf;
pub const HMM_ATANF = atanf;
pub const HMM_ATAN2F = atan2f;
pub const HMM_PI32 = @as(f32, 3.14159265359);
pub const HMM_PI = 3.14159265358979323846;
pub inline fn HMM_MIN(a: anytype, b: anytype) @TypeOf(if (a > b) b else a) {
return if (a > b) b else a;
}
pub inline fn HMM_MAX(a: anytype, b: anytype) @TypeOf(if (a < b) b else a) {
return if (a < b) b else a;
}
pub inline fn HMM_ABS(a: anytype) @TypeOf(if (a > @as(c_int, 0)) a else -a) {
return if (a > @as(c_int, 0)) a else -a;
}
pub inline fn HMM_MOD(a: anytype, m: anytype) @TypeOf(if ((a % m) >= @as(c_int, 0)) a % m else (a % m) + m) {
return if ((a % m) >= @as(c_int, 0)) a % m else (a % m) + m;
}
pub inline fn HMM_SQUARE(x: anytype) @TypeOf(x * x) {
return x * x;
}
pub const tagLC_ID = struct_tagLC_ID;
pub const lconv = struct_lconv;
pub const __lc_time_data = struct___lc_time_data;
pub const threadlocaleinfostruct = struct_threadlocaleinfostruct;
pub const threadmbcinfostruct = struct_threadmbcinfostruct;
pub const localeinfo_struct = struct_localeinfo_struct;
pub const _div_t = struct__div_t;
pub const _ldiv_t = struct__ldiv_t;
pub const _heapinfo = struct__heapinfo;
pub const _exception = struct__exception;
pub const _complex = struct__complex;
|
hmm.zig
|
const std = @import("../../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
/// Returns the arc-tangent of z.
pub fn atan(z: var) @typeOf(z) {
const T = @typeOf(z.re);
return switch (T) {
f32 => atan32(z),
f64 => atan64(z),
else => @compileError("atan not implemented for " ++ @typeName(z)),
};
}
fn redupif32(x: f32) f32 {
const DP1 = 3.140625;
const DP2 = 9.67502593994140625e-4;
const DP3 = 1.509957990978376432e-7;
var t = x / math.pi;
if (t >= 0.0) {
t += 0.5;
} else {
t -= 0.5;
}
const u = @intToFloat(f32, @floatToInt(i32, t));
return ((x - u * DP1) - u * DP2) - t * DP3;
}
fn atan32(z: Complex(f32)) Complex(f32) {
const maxnum = 1.0e38;
const x = z.re;
const y = z.im;
if ((x == 0.0) and (y > 1.0)) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
const x2 = x * x;
var a = 1.0 - x2 - (y * y);
if (a == 0.0) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
var t = 0.5 * math.atan2(f32, 2.0 * x, a);
var w = redupif32(t);
t = y - 1.0;
a = x2 + t * t;
if (a == 0.0) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
t = y + 1.0;
a = (x2 + (t * t)) / a;
return Complex(f32).new(w, 0.25 * math.ln(a));
}
fn redupif64(x: f64) f64 {
const DP1 = 3.14159265160560607910;
const DP2 = 1.98418714791870343106e-9;
const DP3 = 1.14423774522196636802e-17;
var t = x / math.pi;
if (t >= 0.0) {
t += 0.5;
} else {
t -= 0.5;
}
const u = @intToFloat(f64, @floatToInt(i64, t));
return ((x - u * DP1) - u * DP2) - t * DP3;
}
fn atan64(z: Complex(f64)) Complex(f64) {
const maxnum = 1.0e308;
const x = z.re;
const y = z.im;
if ((x == 0.0) and (y > 1.0)) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
const x2 = x * x;
var a = 1.0 - x2 - (y * y);
if (a == 0.0) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
var t = 0.5 * math.atan2(f64, 2.0 * x, a);
var w = redupif64(t);
t = y - 1.0;
a = x2 + t * t;
if (a == 0.0) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
t = y + 1.0;
a = (x2 + (t * t)) / a;
return Complex(f64).new(w, 0.25 * math.ln(a));
}
const epsilon = 0.0001;
test "complex.catan32" {
const a = Complex(f32).new(5, 3);
const c = atan(a);
testing.expect(math.approxEq(f32, c.re, 1.423679, epsilon));
testing.expect(math.approxEq(f32, c.im, 0.086569, epsilon));
}
test "complex.catan64" {
if (builtin.os == .linux and builtin.arch == .arm and builtin.abi == .musleabihf) {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
const a = Complex(f64).new(5, 3);
const c = atan(a);
testing.expect(math.approxEq(f64, c.re, 1.423679, epsilon));
testing.expect(math.approxEq(f64, c.im, 0.086569, epsilon));
}
|
lib/std/math/complex/atan.zig
|
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
test "params" {
try expect(testParamsAdd(22, 11) == 33);
}
fn testParamsAdd(a: i32, b: i32) i32 {
return a + b;
}
test "local variables" {
testLocVars(2);
}
fn testLocVars(b: i32) void {
const a: i32 = 1;
if (a + b != 3) unreachable;
}
test "mutable local variables" {
var zero: i32 = 0;
try expect(zero == 0);
var i = @as(i32, 0);
while (i != 3) {
i += 1;
}
try expect(i == 3);
}
test "separate block scopes" {
{
const no_conflict: i32 = 5;
try expect(no_conflict == 5);
}
const c = x: {
const no_conflict = @as(i32, 10);
break :x no_conflict;
};
try expect(c == 10);
}
fn @"weird function name"() i32 {
return 1234;
}
test "weird function name" {
try expect(@"weird function name"() == 1234);
}
test "assign inline fn to const variable" {
const a = inlineFn;
a();
}
inline fn inlineFn() void {}
fn outer(y: u32) fn (u32) u32 {
const Y = @TypeOf(y);
const st = struct {
fn get(z: u32) u32 {
return z + @sizeOf(Y);
}
};
return st.get;
}
test "return inner function which references comptime variable of outer function" {
var func = outer(10);
try expect(func(3) == 7);
}
test "discard the result of a function that returns a struct" {
const S = struct {
fn entry() void {
_ = func();
}
fn func() Foo {
return undefined;
}
const Foo = struct {
a: u64,
b: u64,
};
};
S.entry();
comptime S.entry();
}
test "inline function call that calls optional function pointer, return pointer at callsite interacts correctly with callsite return type" {
const S = struct {
field: u32,
fn doTheTest() !void {
bar2 = actualFn;
const result = try foo();
try expect(result.field == 1234);
}
const Foo = struct { field: u32 };
fn foo() !Foo {
var res: Foo = undefined;
res.field = bar();
return res;
}
inline fn bar() u32 {
return bar2.?();
}
var bar2: ?fn () u32 = null;
fn actualFn() u32 {
return 1234;
}
};
try S.doTheTest();
}
test "implicit cast function unreachable return" {
wantsFnWithVoid(fnWithUnreachable);
}
fn wantsFnWithVoid(f: fn () void) void {
_ = f;
}
fn fnWithUnreachable() noreturn {
unreachable;
}
test "extern struct with stdcallcc fn pointer" {
const S = extern struct {
ptr: fn () callconv(if (builtin.target.cpu.arch == .i386) .Stdcall else .C) i32,
fn foo() callconv(if (builtin.target.cpu.arch == .i386) .Stdcall else .C) i32 {
return 1234;
}
};
var s: S = undefined;
s.ptr = S.foo;
try expect(s.ptr() == 1234);
}
const nComplexCallconv = 100;
fn fComplexCallconvRet(x: u32) callconv(blk: {
const s: struct { n: u32 } = .{ .n = nComplexCallconv };
break :blk switch (s.n) {
0 => .C,
1 => .Inline,
else => .Unspecified,
};
}) struct { x: u32 } {
return .{ .x = x * x };
}
test "function with complex callconv and return type expressions" {
try expect(fComplexCallconvRet(3).x == 9);
}
|
test/behavior/fn.zig
|
const std = @import("std");
const builtin = @import("builtin");
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
const stdin = std.io.getStdIn();
const Options = @import("Options.zig");
const Choices = @import("Choices.zig");
const Tty = @import("Tty.zig");
const TtyInterface = @import("TtyInterface.zig");
pub fn main() anyerror!u8 {
// Use a GeneralPurposeAllocator in Debug builds and an arena allocator in Release builds
var backing_allocator = comptime switch (builtin.mode) {
.Debug => std.heap.GeneralPurposeAllocator(.{}){},
else => std.heap.ArenaAllocator.init(std.heap.page_allocator),
};
defer _ = backing_allocator.deinit();
var allocator = backing_allocator.allocator();
var options = try Options.new();
var choices = try Choices.init(allocator, options);
defer choices.deinit();
var file = if (options.input_file) |f|
std.fs.cwd().openFile(f, .{}) catch |err| switch (err) {
error.FileNotFound => {
try stderr.print("Input file {s} not found\n", .{f});
return 1;
},
error.PathAlreadyExists => unreachable,
else => return err,
}
else
stdin;
defer if (options.input_file) |_| file.close();
if (options.benchmark > 0) {
if (options.filter) |filter| {
try choices.read(file, options.input_delimiter);
var i: usize = 0;
while (i < options.benchmark) : (i += 1) {
try choices.search(filter);
}
} else {
std.debug.print("Must specify -e/--show-matches with --benchmark\n", .{});
return 1;
}
} else if (options.filter) |filter| {
try choices.read(file, options.input_delimiter);
try choices.search(filter);
for (choices.results.?.items) |result| {
if (options.show_scores) {
stdout.print("{}\t", .{result.score}) catch unreachable;
}
stdout.print("{s}\n", .{result.str}) catch unreachable;
}
} else {
if (stdin.isTty()) {
try choices.read(file, options.input_delimiter);
}
var tty = try Tty.init(options.tty_filename);
if (!stdin.isTty()) {
try choices.read(file, options.input_delimiter);
}
if (options.num_lines > choices.numChoices()) {
options.num_lines = choices.numChoices();
}
const num_lines_adjustment: usize = if (options.show_info) 2 else 1;
if (options.num_lines + num_lines_adjustment > tty.max_height) {
options.num_lines = tty.max_height - num_lines_adjustment;
}
var tty_interface = try TtyInterface.init(allocator, &tty, &choices, options);
defer tty_interface.deinit();
if (tty_interface.run()) |rc| {
return rc;
} else |err| return err;
}
return 0;
}
|
src/main.zig
|
const Self = @This();
const build_options = @import("build_options");
const std = @import("std");
const mem = std.mem;
const wlr = @import("wlroots");
const wl = @import("wayland").server.wl;
const c = @import("c.zig");
const util = @import("util.zig");
const Config = @import("Config.zig");
const Control = @import("Control.zig");
const DecorationManager = @import("DecorationManager.zig");
const InputManager = @import("InputManager.zig");
const LayerSurface = @import("LayerSurface.zig");
const LayoutManager = @import("LayoutManager.zig");
const Output = @import("Output.zig");
const Root = @import("Root.zig");
const StatusManager = @import("StatusManager.zig");
const View = @import("View.zig");
const ViewStack = @import("view_stack.zig").ViewStack;
const XwaylandUnmanaged = @import("XwaylandUnmanaged.zig");
const log = std.log.scoped(.server);
wl_server: *wl.Server,
sigint_source: *wl.EventSource,
sigterm_source: *wl.EventSource,
backend: *wlr.Backend,
noop_backend: *wlr.Backend,
xdg_shell: *wlr.XdgShell,
new_xdg_surface: wl.Listener(*wlr.XdgSurface),
layer_shell: *wlr.LayerShellV1,
new_layer_surface: wl.Listener(*wlr.LayerSurfaceV1),
xwayland: if (build_options.xwayland) *wlr.Xwayland else void,
new_xwayland_surface: if (build_options.xwayland) wl.Listener(*wlr.XwaylandSurface) else void,
foreign_toplevel_manager: *wlr.ForeignToplevelManagerV1,
xdg_activation: *wlr.XdgActivationV1,
decoration_manager: DecorationManager,
input_manager: InputManager,
root: Root,
config: Config,
control: Control,
status_manager: StatusManager,
layout_manager: LayoutManager,
pub fn init(self: *Self) !void {
self.wl_server = try wl.Server.create();
errdefer self.wl_server.destroy();
const loop = self.wl_server.getEventLoop();
self.sigint_source = try loop.addSignal(*wl.Server, std.os.SIGINT, terminate, self.wl_server);
errdefer self.sigint_source.remove();
self.sigterm_source = try loop.addSignal(*wl.Server, std.os.SIGTERM, terminate, self.wl_server);
errdefer self.sigterm_source.remove();
// This frees itself when the wl.Server is destroyed
self.backend = try wlr.Backend.autocreate(self.wl_server);
// This backend is used to create a noop output for use when no actual
// outputs are available. This frees itself when the wl.Server is destroyed.
self.noop_backend = try wlr.Backend.createNoop(self.wl_server);
// This will never be null for the non-custom backends in wlroots
const renderer = self.backend.getRenderer().?;
try renderer.initServer(self.wl_server);
const compositor = try wlr.Compositor.create(self.wl_server, renderer);
// Set up xdg shell
self.xdg_shell = try wlr.XdgShell.create(self.wl_server);
self.new_xdg_surface.setNotify(handleNewXdgSurface);
self.xdg_shell.events.new_surface.add(&self.new_xdg_surface);
// Set up layer shell
self.layer_shell = try wlr.LayerShellV1.create(self.wl_server);
self.new_layer_surface.setNotify(handleNewLayerSurface);
self.layer_shell.events.new_surface.add(&self.new_layer_surface);
// Set up xwayland if built with support
if (build_options.xwayland) {
self.xwayland = try wlr.Xwayland.create(self.wl_server, compositor, false);
self.new_xwayland_surface.setNotify(handleNewXwaylandSurface);
self.xwayland.events.new_surface.add(&self.new_xwayland_surface);
}
self.foreign_toplevel_manager = try wlr.ForeignToplevelManagerV1.create(self.wl_server);
self.xdg_activation = try wlr.XdgActivationV1.create(self.wl_server);
_ = try wlr.PrimarySelectionDeviceManagerV1.create(self.wl_server);
self.config = try Config.init();
try self.decoration_manager.init();
try self.root.init();
// Must be called after root is initialized
try self.input_manager.init();
try self.control.init();
try self.status_manager.init();
try self.layout_manager.init();
// These all free themselves when the wl_server is destroyed
_ = try wlr.DataDeviceManager.create(self.wl_server);
_ = try wlr.DataControlManagerV1.create(self.wl_server);
_ = try wlr.ExportDmabufManagerV1.create(self.wl_server);
_ = try wlr.GammaControlManagerV1.create(self.wl_server);
_ = try wlr.ScreencopyManagerV1.create(self.wl_server);
_ = try wlr.Viewporter.create(self.wl_server);
}
/// Free allocated memory and clean up. Note: order is important here
pub fn deinit(self: *Self) void {
self.sigint_source.remove();
self.sigterm_source.remove();
if (build_options.xwayland) self.xwayland.destroy();
self.wl_server.destroyClients();
self.backend.destroy();
self.root.deinit();
self.input_manager.deinit();
self.wl_server.destroy();
self.config.deinit();
}
/// Create the socket, start the backend, and setup the environment
pub fn start(self: Self) !void {
var buf: [11]u8 = undefined;
const socket = try self.wl_server.addSocketAuto(&buf);
try self.backend.start();
// TODO: don't use libc's setenv
if (c.setenv("WAYLAND_DISPLAY", socket, 1) < 0) return error.SetenvError;
if (build_options.xwayland) {
if (c.setenv("DISPLAY", self.xwayland.display_name, 1) < 0) return error.SetenvError;
}
}
/// Handle SIGINT and SIGTERM by gracefully stopping the server
fn terminate(signal: c_int, wl_server: *wl.Server) callconv(.C) c_int {
wl_server.terminate();
return 0;
}
fn handleNewXdgSurface(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void {
const self = @fieldParentPtr(Self, "new_xdg_surface", listener);
if (xdg_surface.role == .popup) {
log.debug("new xdg_popup", .{});
return;
}
log.debug("new xdg_toplevel", .{});
// The View will add itself to the output's view stack on map
const output = self.input_manager.defaultSeat().focused_output;
const node = util.gpa.create(ViewStack(View).Node) catch {
xdg_surface.resource.postNoMemory();
return;
};
node.view.init(output, getNewViewTags(output), xdg_surface);
}
/// This event is raised when the layer_shell recieves a new surface from a client.
fn handleNewLayerSurface(listener: *wl.Listener(*wlr.LayerSurfaceV1), wlr_layer_surface: *wlr.LayerSurfaceV1) void {
const self = @fieldParentPtr(Self, "new_layer_surface", listener);
log.debug(
"new layer surface: namespace {s}, layer {s}, anchor {b:0>4}, size {},{}, margin {},{},{},{}, exclusive_zone {}",
.{
wlr_layer_surface.namespace,
@tagName(wlr_layer_surface.client_pending.layer),
@bitCast(u32, wlr_layer_surface.client_pending.anchor),
wlr_layer_surface.client_pending.desired_width,
wlr_layer_surface.client_pending.desired_height,
wlr_layer_surface.client_pending.margin.top,
wlr_layer_surface.client_pending.margin.right,
wlr_layer_surface.client_pending.margin.bottom,
wlr_layer_surface.client_pending.margin.left,
wlr_layer_surface.client_pending.exclusive_zone,
},
);
// If the new layer surface does not have an output assigned to it, use the
// first output or close the surface if none are available.
if (wlr_layer_surface.output == null) {
const output = self.input_manager.defaultSeat().focused_output;
if (output == &self.root.noop_output) {
log.err("no output available for layer surface '{s}'", .{wlr_layer_surface.namespace});
wlr_layer_surface.close();
return;
}
log.debug("new layer surface had null output, assigning it to output '{s}'", .{
mem.sliceTo(&output.wlr_output.name, 0),
});
wlr_layer_surface.output = output.wlr_output;
}
// The layer surface will add itself to the proper list of the output on map
const output = @intToPtr(*Output, wlr_layer_surface.output.?.data);
const node = util.gpa.create(std.TailQueue(LayerSurface).Node) catch {
wlr_layer_surface.resource.postNoMemory();
return;
};
node.data.init(output, wlr_layer_surface);
}
fn handleNewXwaylandSurface(listener: *wl.Listener(*wlr.XwaylandSurface), wlr_xwayland_surface: *wlr.XwaylandSurface) void {
const self = @fieldParentPtr(Self, "new_xwayland_surface", listener);
if (wlr_xwayland_surface.override_redirect) {
log.debug("new unmanaged xwayland surface", .{});
// The unmanged surface will add itself to the list of unmanaged views
// in Root when it is mapped.
const node = util.gpa.create(std.TailQueue(XwaylandUnmanaged).Node) catch return;
node.data.init(wlr_xwayland_surface);
return;
}
log.debug(
"new xwayland surface: title '{s}', class '{s}'",
.{ wlr_xwayland_surface.title, wlr_xwayland_surface.class },
);
// The View will add itself to the output's view stack on map
const output = self.input_manager.defaultSeat().focused_output;
const node = util.gpa.create(ViewStack(View).Node) catch return;
node.view.init(output, getNewViewTags(output), wlr_xwayland_surface);
}
fn getNewViewTags(output: *Output) u32 {
const tags = output.current.tags & output.spawn_tagmask;
return if (tags != 0) tags else output.current.tags;
}
|
source/river-0.1.0/river/Server.zig
|
const std = @import("std");
const fmt = std.fmt;
const mem = std.mem;
const assert = std.debug.assert;
const io_uring_cqe = std.os.linux.io_uring_cqe;
/// Callback encapsulates a context and a function pointer that will be called when
/// the server loop will process the CQEs.
/// Pointers to this structure is what get passed as user data in a SQE and what we later get back in a CQE.
///
/// There are two kinds of callbacks currently:
/// * operations associated with a client
/// * operations not associated with a client
pub fn Callback(comptime ServerType: type, comptime ClientContext: type) type {
return struct {
const Self = @This();
server: ServerType,
client_context: ?ClientContext = null,
call: fn (ServerType, ?ClientContext, io_uring_cqe) anyerror!void,
next: ?*Self = null,
/// Pool is a pool of callback objects that facilitates lifecycle management of a callback.
/// The implementation is a free list of pre-allocated objects.
///
/// For each SQEs a callback must be obtained via get().
/// When the server loop is processing CQEs it will use the callback and then release it with put().
pub const Pool = struct {
allocator: mem.Allocator,
nb: usize,
free_list: ?*Self,
pub fn init(allocator: mem.Allocator, server: ServerType, nb: usize) !Pool {
var res = Pool{
.allocator = allocator,
.nb = nb,
.free_list = null,
};
// Preallocate as many callbacks as ring entries.
var i: usize = 0;
while (i < nb) : (i += 1) {
const callback = try allocator.create(Self);
callback.* = .{
.server = server,
.client_context = undefined,
.call = undefined,
.next = res.free_list,
};
res.free_list = callback;
}
return res;
}
pub fn deinit(self: *Pool) void {
// All callbacks must be put back in the pool before deinit is called
assert(self.count() == self.nb);
var ret = self.free_list;
while (ret) |item| {
ret = item.next;
self.allocator.destroy(item);
}
}
/// Returns the number of callback in the pool.
pub fn count(self: *Pool) usize {
var n: usize = 0;
var ret = self.free_list;
while (ret) |item| {
n += 1;
ret = item.next;
}
return n;
}
/// Returns a ready to use callback or an error if none are available.
/// `cb` must be a function with either one of the following signatures:
/// * fn(ServerType, io_uring_cqe)
/// * fn(ServerType, ClientContext, io_uring_cqe)
///
/// If `cb` takes a ClientContext `args` must be a tuple with at least the first element being a ClientContext.
pub fn get(self: *Pool, comptime cb: anytype, args: anytype) !*Self {
const ret = self.free_list orelse return error.OutOfCallback;
self.free_list = ret.next;
// Provide a wrapper based on the callback function.
const func_args = std.meta.fields(std.meta.ArgsTuple(@TypeOf(cb)));
switch (func_args.len) {
3 => {
comptime {
expectFuncArgType(func_args, 0, ServerType);
expectFuncArgType(func_args, 1, ClientContext);
expectFuncArgType(func_args, 2, io_uring_cqe);
}
ret.client_context = args[0];
ret.call = struct {
fn wrapper(server: ServerType, client_context: ?ClientContext, cqe: io_uring_cqe) anyerror!void {
return cb(server, client_context.?, cqe);
}
}.wrapper;
},
2 => {
comptime {
expectFuncArgType(func_args, 0, ServerType);
expectFuncArgType(func_args, 1, io_uring_cqe);
}
ret.client_context = null;
ret.call = struct {
fn wrapper(server: ServerType, client_context: ?ClientContext, cqe: io_uring_cqe) anyerror!void {
_ = client_context;
return cb(server, cqe);
}
}.wrapper;
},
else => @compileError("invalid callback function " ++ @typeName(@TypeOf(cb))),
}
ret.next = null;
return ret;
}
/// Reset the callback and puts it back into the pool.
pub fn put(self: *Pool, callback: *Self) void {
callback.client_context = null;
callback.next = self.free_list;
self.free_list = callback;
}
};
};
}
/// Checks that the argument at `idx` has the type `exp`.
fn expectFuncArgType(comptime args: []const std.builtin.TypeInfo.StructField, comptime idx: usize, comptime exp: type) void {
if (args[idx].field_type != exp) {
var msg = fmt.comptimePrint("expected func arg {d} to be of type {s}, got {s}", .{
idx,
@typeName(exp),
@typeName(args[idx].field_type),
});
@compileError(msg);
}
}
|
src/callback.zig
|
const std = @import("std");
const leb = std.leb;
pub const Opcode = enum(u8) {
@"unreachable" = 0x0,
nop = 0x01,
block = 0x02,
loop = 0x03,
@"if" = 0x04,
@"else" = 0x05,
end = 0x0b,
br = 0x0c,
br_if = 0x0d,
br_table = 0x0e,
@"return" = 0x0f,
call = 0x10,
call_indirect = 0x11,
drop = 0x1a,
select = 0x1b,
@"local.get" = 0x20,
@"local.set" = 0x21,
@"local.tee" = 0x22,
@"global.get" = 0x23,
@"global.set" = 0x24,
@"i32.load" = 0x28,
@"i64.load" = 0x29,
@"f32.load" = 0x2a,
@"f64.load" = 0x2b,
@"i32.load8_s" = 0x2c,
@"i32.load8_u" = 0x2d,
@"i32.load16_s" = 0x2e,
@"i32.load16_u" = 0x2f,
@"i64.load8_s" = 0x30,
@"i64.load8_u" = 0x31,
@"i64.load16_s" = 0x32,
@"i64.load16_u" = 0x33,
@"i64.load32_s" = 0x34,
@"i64.load32_u" = 0x35,
@"i32.store" = 0x36,
@"i64.store" = 0x37,
@"f32.store" = 0x38,
@"f64.store" = 0x39,
@"i32.store8" = 0x3a,
@"i32.store16" = 0x3b,
@"i64.store8" = 0x3c,
@"i64.store16" = 0x3d,
@"i64.store32" = 0x3e,
@"memory.size" = 0x3f,
@"memory.grow" = 0x40,
@"i32.const" = 0x41,
@"i64.const" = 0x42,
@"f32.const" = 0x43,
@"f64.const" = 0x44,
@"i32.eqz" = 0x45,
@"i32.eq" = 0x46,
@"i32.ne" = 0x47,
@"i32.lt_s" = 0x48,
@"i32.lt_u" = 0x49,
@"i32.gt_s" = 0x4a,
@"i32.gt_u" = 0x4b,
@"i32.le_s" = 0x4c,
@"i32.le_u" = 0x4d,
@"i32.ge_s" = 0x4e,
@"i32.ge_u" = 0x4f,
@"i64.eqz" = 0x50,
@"i64.eq" = 0x51,
@"i64.ne" = 0x52,
@"i64.lt_s" = 0x53,
@"i64.lt_u" = 0x54,
@"i64.gt_s" = 0x55,
@"i64.gt_u" = 0x56,
@"i64.le_s" = 0x57,
@"i64.le_u" = 0x58,
@"i64.ge_s" = 0x59,
@"i64.ge_u" = 0x5a,
@"f32.eq" = 0x5b,
@"f32.ne" = 0x5c,
@"f32.lt" = 0x5d,
@"f32.gt" = 0x5e,
@"f32.le" = 0x5f,
@"f32.ge" = 0x60,
@"f64.eq" = 0x61,
@"f64.ne" = 0x62,
@"f64.lt" = 0x63,
@"f64.gt" = 0x64,
@"f64.le" = 0x65,
@"f64.ge" = 0x66,
@"i32.clz" = 0x67,
@"i32.ctz" = 0x68,
@"i32.popcnt" = 0x69,
@"i32.add" = 0x6a,
@"i32.sub" = 0x6b,
@"i32.mul" = 0x6c,
@"i32.div_s" = 0x6d,
@"i32.div_u" = 0x6e,
@"i32.rem_s" = 0x6f,
@"i32.rem_u" = 0x70,
@"i32.and" = 0x71,
@"i32.or" = 0x72,
@"i32.xor" = 0x73,
@"i32.shl" = 0x74,
@"i32.shr_s" = 0x75,
@"i32.shr_u" = 0x76,
@"i32.rotl" = 0x77,
@"i32.rotr" = 0x78,
@"i64.clz" = 0x79,
@"i64.ctz" = 0x7a,
@"i64.popcnt" = 0x7b,
@"i64.add" = 0x7c,
@"i64.sub" = 0x7d,
@"i64.mul" = 0x7e,
@"i64.div_s" = 0x7f,
@"i64.div_u" = 0x80,
@"i64.rem_s" = 0x81,
@"i64.rem_u" = 0x82,
@"i64.and" = 0x83,
@"i64.or" = 0x84,
@"i64.xor" = 0x85,
@"i64.shl" = 0x86,
@"i64.shr_s" = 0x87,
@"i64.shr_u" = 0x88,
@"i64.rotl" = 0x89,
@"i64.rotr" = 0x8a,
@"f32.abs" = 0x8b,
@"f32.neg" = 0x8c,
@"f32.ceil" = 0x8d,
@"f32.floor" = 0x8e,
@"f32.trunc" = 0x8f,
@"f32.nearest" = 0x90,
@"f32.sqrt" = 0x91,
@"f32.add" = 0x92,
@"f32.sub" = 0x93,
@"f32.mul" = 0x94,
@"f32.div" = 0x95,
@"f32.min" = 0x96,
@"f32.max" = 0x97,
@"f32.copysign" = 0x98,
@"f64.abs" = 0x99,
@"f64.neg" = 0x9a,
@"f64.ceil" = 0x9b,
@"f64.floor" = 0x9c,
@"f64.trunc" = 0x9d,
@"f64.nearest" = 0x9e,
@"f64.sqrt" = 0x9f,
@"f64.add" = 0xa0,
@"f64.sub" = 0xa1,
@"f64.mul" = 0xa2,
@"f64.div" = 0xa3,
@"f64.min" = 0xa4,
@"f64.max" = 0xa5,
@"f64.copysign" = 0xa6,
@"i32.wrap_i64" = 0xa7,
@"i32.trunc_f32_s" = 0xa8,
@"i32.trunc_f32_u" = 0xa9,
@"i32.trunc_f64_s" = 0xaa,
@"i32.trunc_f64_u" = 0xab,
@"i64.extend_i32_s" = 0xac,
@"i64.extend_i32_u" = 0xad,
@"i64.trunc_f32_s" = 0xae,
@"i64.trunc_f32_u" = 0xaf,
@"i64.trunc_f64_s" = 0xb0,
@"i64.trunc_f64_u" = 0xb1,
@"f32.convert_i32_s" = 0xb2,
@"f32.convert_i32_u" = 0xb3,
@"f32.convert_i64_s" = 0xb4,
@"f32.convert_i64_u" = 0xb5,
@"f32.demote_f64" = 0xb6,
@"f64.convert_i32_s" = 0xb7,
@"f64.convert_i32_u" = 0xb8,
@"f64.convert_i64_s" = 0xb9,
@"f64.convert_i64_u" = 0xba,
@"f64.promote_f32" = 0xbb,
@"i32.reinterpret_f32" = 0xbc,
@"i64.reinterpret_f64" = 0xbd,
@"f32.reinterpret_i32" = 0xbe,
@"f64.reinterpret_i64" = 0xbf,
@"i32.extend8_s" = 0xc0,
@"i32.extend16_s" = 0xc1,
@"i64.extend8_s" = 0xc2,
@"i64.extend16_s" = 0xc3,
@"i64.extend32_s" = 0xc4,
trunc_sat = 0xfc,
};
const OpcodeMeta = struct {
instruction: Opcode,
offset: usize, // offset from start of function
};
pub const OpcodeIterator = struct {
function: []const u8,
code: []const u8,
pub fn init(function: []const u8) OpcodeIterator {
return OpcodeIterator{
.code = function,
.function = function,
};
}
pub fn next(self: *OpcodeIterator) !?OpcodeMeta {
if (self.code.len == 0) return null;
// 1. Get the instruction we're going to return and increment code
const instr = @intToEnum(Opcode, self.code[0]);
const offset = @ptrToInt(self.code.ptr) - @ptrToInt(self.function.ptr);
self.code = self.code[1..];
// 2. Find the start of the next instruction
switch (instr) {
.@"i32.const" => _ = try readILEB128Mem(i32, &self.code),
.@"i64.const" => _ = try readILEB128Mem(i64, &self.code),
.@"global.get",
.@"global.set",
.@"local.get",
.@"local.set",
.@"local.tee",
.@"if",
.call,
.br,
.br_if,
.block,
.loop,
=> _ = try readULEB128Mem(u32, &self.code),
.@"memory.size", .@"memory.grow" => {
const reserved = try readByte(&self.code);
if (reserved != 0) return error.MalformedMemoryReserved;
},
.br_table => {
const label_count = try readULEB128Mem(u32, &self.code);
var j: usize = 0;
while (j < label_count + 1) : (j += 1) {
_ = try readULEB128Mem(u32, &self.code);
}
},
.call_indirect => {
_ = try readULEB128Mem(u32, &self.code);
const reserved = try readByte(&self.code);
if (reserved != 0) return error.MalformedCallIndirectReserved;
},
.@"i32.load",
.@"i64.load",
.@"f32.load",
.@"f64.load",
.@"i32.load8_s",
.@"i32.load8_u",
.@"i32.load16_s",
.@"i32.load16_u",
.@"i64.load8_s",
.@"i64.load8_u",
.@"i64.load16_s",
.@"i64.load16_u",
.@"i64.load32_s",
.@"i64.load32_u",
.@"i32.store",
.@"i64.store",
.@"f32.store",
.@"f64.store",
.@"i32.store8",
.@"i32.store16",
.@"i64.store8",
.@"i64.store16",
.@"i64.store32",
=> {
_ = try readULEB128Mem(u32, &self.code);
_ = try readULEB128Mem(u32, &self.code);
},
.@"f32.const" => self.code = self.code[4..],
.@"f64.const" => self.code = self.code[8..],
.trunc_sat => self.code = self.code[1..],
else => {},
}
return OpcodeMeta{
.instruction = instr,
.offset = offset,
};
}
};
pub fn findFunctionEnd(code: []const u8) !OpcodeMeta {
var it = OpcodeIterator.init(code);
var i: usize = 1;
while (try it.next()) |meta| {
if (meta.offset == 0 and meta.instruction == .end) return meta;
if (meta.offset == 0) continue;
switch (meta.instruction) {
.block, .loop, .@"if" => i += 1,
.end => i -= 1,
else => {},
}
if (i == 0) return meta;
}
return error.CouldntFindEnd;
}
pub fn findExprEnd(code: []const u8) !OpcodeMeta {
var it = OpcodeIterator.init(code);
var i: usize = 1;
while (try it.next()) |meta| {
switch (meta.instruction) {
.end => i -= 1,
else => {},
}
if (i == 0) return meta;
}
return error.CouldntFindExprEnd;
}
pub fn readULEB128Mem(comptime T: type, ptr: *[]const u8) !T {
var buf = std.io.fixedBufferStream(ptr.*);
const value = try leb.readULEB128(T, buf.reader());
ptr.*.ptr += buf.pos;
ptr.*.len -= buf.pos;
return value;
}
pub fn readILEB128Mem(comptime T: type, ptr: *[]const u8) !T {
var buf = std.io.fixedBufferStream(ptr.*);
const value = try leb.readILEB128(T, buf.reader());
// The following is a bit of a kludge that should really
// be fixed in either the std lib readILEB128 or using a
// a fresh implementation. The issue is that the wasm spec
// expects the "unused" bits in a negative ILEB128 to all be
// one and the same bits in a positive ILEB128 to be zero.
switch (T) {
i32 => if (buf.pos == 5 and value < 0 and buf.buffer[4] & 0x70 != 0x70) return error.Overflow,
i64 => if (buf.pos == 10 and value < 0 and buf.buffer[9] & 0x7e != 0x7e) return error.Overflow,
else => @compileError("readILEB128Mem expects i32 or i64"),
}
ptr.*.ptr += buf.pos;
ptr.*.len -= buf.pos;
return value;
}
pub fn readU32(ptr: *[]const u8) !u32 {
var buf = std.io.fixedBufferStream(ptr.*);
const rd = buf.reader();
const value = try rd.readIntLittle(u32);
ptr.*.ptr += buf.pos;
ptr.*.len -= buf.pos;
return value;
}
pub fn readU64(ptr: *[]const u8) !u64 {
var buf = std.io.fixedBufferStream(ptr.*);
const rd = buf.reader();
const value = try rd.readIntLittle(u64);
ptr.*.ptr += buf.pos;
ptr.*.len -= buf.pos;
return value;
}
pub fn readByte(ptr: *[]const u8) !u8 {
var buf = std.io.fixedBufferStream(ptr.*);
const rd = buf.reader();
const value = try rd.readByte();
ptr.*.ptr += buf.pos;
ptr.*.len -= buf.pos;
return value;
}
|
src/opcode.zig
|
const VTE = @import("vte");
const c = VTE.c;
const gtk = VTE.gtk;
const vte = VTE.vte;
const std = @import("std");
const config = @import("config.zig");
const keys = @import("keys.zig");
const menus = @import("menus.zig");
const prefs = @import("prefs.zig");
const version = @import("version.zig").version;
const Keys = keys.Keys;
const Menu = menus.Menu;
const Nav = menus.Nav;
const allocator = std.heap.page_allocator;
const fmt = std.fmt;
const fs = std.fs;
const hashmap = std.AutoHashMap;
const mem = std.mem;
const os = std.os;
const stderr = std.io.getStdErr().writer();
const stdout = std.io.getStdOut().writer();
var conf: config.Config = undefined;
var gui: Gui = undefined;
var options: Opts = undefined;
var tabs: hashmap(u64, Tab) = undefined;
var terms: hashmap(u64, *c.VteTerminal) = undefined;
pub var css_provider: *c.GtkCssProvider = undefined;
pub const Opts = struct {
command: [:0]const u8,
title: [:0]const u8,
directory: [:0]const u8,
hostname: [:0]const u8,
config_dir: []const u8,
};
pub const Tab = struct {
box: gtk.Box,
tab_label: gtk.Label,
close_button: gtk.Button,
const Self = @This();
fn init(command: [:0]const u8) Self {
var tab = Self{
.box = gtk.Box.new(.horizontal, 0),
.tab_label = gtk.Label.new("Zterm"),
.close_button = gtk.Button.new_from_icon_name("window-close", .menu),
};
const term = Callbacks.newTerm(command);
const lbox = gtk.Box.new(.horizontal, 10);
tab.close_button.set_relief(.none);
const close_button_widget = tab.close_button.as_widget();
close_button_widget.set_has_tooltip(true);
close_button_widget.set_tooltip_text("Close tab");
lbox.pack_start(tab.tab_label.as_widget(), false, true, 1);
lbox.pack_start(close_button_widget, false, true, 1);
lbox.as_widget().show_all();
tab.box.set_homogeneous(true);
tab.box.pack_start(term.as_widget(), true, true, 1);
tab.box.as_widget().show_all();
gui.notebook.append_page(tab.box.as_widget(), lbox.as_widget());
gui.notebook.set_tab_label(tab.box.as_widget(), lbox.as_widget());
gui.notebook.set_tab_reorderable(tab.box.as_widget(), true);
tab.close_button.connect_clicked(@ptrCast(c.GCallback, Callbacks.closeTabByButton), @ptrCast(c.gpointer, tab.box.ptr));
return tab;
}
fn currentTerm(self: Self) ?vte.Terminal {
if (self.box.as_container().get_children(allocator)) |kids| {
defer kids.deinit();
for (kids.items) |child| {
if (child.has_focus()) {
return vte.Terminal.from_widget(child);
}
}
return null;
} else return null;
}
fn termTitle(self: Self, alloc: mem.Allocator) ?[:0]const u8 {
if (self.currentTerm()) |term| {
return if (term.get_window_title(alloc)) |s| s else null;
} else return null;
}
fn nextPane(self: Self) void {
if (self.box.as_container().get_children(allocator)) |kids| {
defer kids.deinit();
if (kids.items.len > 0) {
var next: usize = 0;
for (kids.items) |child, index| {
if (child.has_focus()) {
if (index < kids.items.len - 1) {
next = index + 1;
} else next = 0;
}
}
kids.items[next].grab_focus();
}
}
}
fn prevPane(self: Self) void {
if (self.box.as_container().get_children(allocator)) |kids| {
defer kids.deinit();
if (kids.items.len > 0) {
var prev: usize = 0;
for (kids.items) |child, index| {
if (child.has_focus()) {
if (index > 0) {
prev = index - 1;
} else prev = kids.items.len - 1;
}
}
kids.items[prev].grab_focus();
}
}
}
fn rotate(self: Self) void {
const orientable = self.box.as_orientable();
const orientation = orientable.get_orientation();
switch (orientation) {
.horizontal => orientable.set_orientation(.vertical),
.vertical => orientable.set_orientation(.horizontal),
}
}
fn split(self: Self) void {
const term = Callbacks.newTerm(options.command);
term.as_widget().show();
self.box.pack_start(term.as_widget(), true, true, 1);
}
fn selectPage(self: Self) void {
if (self.box.as_container().get_children(allocator)) |kids| {
defer kids.deinit();
kids.items[0].grab_focus();
}
}
};
const Gui = struct {
window: gtk.Window,
notebook: gtk.Notebook,
menu: Menu,
nav: Nav,
const Self = @This();
fn init(builder: gtk.Builder) Self {
const glade_str = @embedFile("gui.glade");
if (c.gtk_builder_add_from_string(builder.ptr, glade_str, glade_str.len, @intToPtr([*c][*c]c._GError, 0)) == 0) {
stderr.print("builder file fail\n", .{}) catch unreachable;
std.process.exit(1);
}
return Self{
.window = builder.get_widget("window").?.to_window().?,
.notebook = builder.get_widget("notebook").?.to_notebook().?,
.menu = Menu.init(builder),
.nav = Nav.init(builder),
};
}
fn currentTab(self: Self) ?Tab {
const num = self.notebook.get_current_page();
if (self.notebook.get_nth_page(num)) |box| {
return if (tabs.get(@ptrToInt(box.ptr))) |t| t else unreachable;
} else return null;
}
fn currentTerm(self: Gui) ?vte.Terminal {
if (self.currentTab()) |tab| {
return if (tab.currentTerm()) |t| t else null;
} else return null;
}
fn nthTab(self: Self, num: c_int) void {
self.notebook.set_current_page(num);
}
fn prevTab(self: Self) void {
const page = self.notebook.get_current_page();
if (page > 0) {
self.notebook.prev_page();
} else {
const pages = self.notebook.get_n_pages();
self.notebook.set_current_page(pages - 1);
}
}
fn nextTab(self: Self) void {
const pages = self.notebook.get_n_pages();
const page = self.notebook.get_current_page();
if (page < pages - 1) {
self.notebook.next_page();
} else {
self.notebook.set_current_page(0);
}
}
fn setTitle(self: Self) void {
const style = conf.dynamic_title_style;
const title = switch (style) {
.replaces_title => fmt.allocPrintZ(allocator, "{s} on {s}", .{ options.directory, options.hostname }),
.before_title => fmt.allocPrintZ(allocator, "{s} on {s} ~ {s}-{s}", .{ options.directory, options.hostname, conf.initial_title, version }),
.after_title => fmt.allocPrintZ(allocator, "{s}-{s} ~ {s} on {s}", .{ conf.initial_title, version, options.directory, options.hostname }),
.not_displayed => fmt.allocPrintZ(allocator, "{s}-{s}", .{conf.initial_title, version}),
} catch return;
defer allocator.free(title);
self.window.set_title(title);
}
fn setOpacity(self: Self) void {
const bg = conf.background;
switch (bg) {
.transparent => |percent| {
const opacity = percent / 100.0;
self.window.as_widget().set_opacity(opacity);
},
.solid_color, .image, .gradient => {
self.window.as_widget().set_opacity(1.0);
},
}
conf.setBg();
}
fn applySettings(self: Self) void {
var iter = terms.valueIterator();
while (iter.next()) |term| {
conf.set(term.*);
}
self.setTitle();
self.setOpacity();
}
fn pageRemoved(self: Self) void {
const pages = self.notebook.get_n_pages();
if (pages == 0) {
c.gtk_main_quit();
} else {
Callbacks.selectPage();
}
}
fn connectSignals(self: Self) void {
self.menu.new_tab.connect_activate(@ptrCast(c.GCallback, Callbacks.newTab), null);
self.menu.split_view.connect_activate(@ptrCast(c.GCallback, Callbacks.splitTab), null);
self.menu.rotate_view.connect_activate(@ptrCast(c.GCallback, Callbacks.rotateView), null);
self.notebook.connect_page_removed(@ptrCast(c.GCallback, Callbacks.pageRemoved), null);
self.notebook.connect_select_page(@ptrCast(c.GCallback, Callbacks.selectPage), null);
self.menu.preferences.connect_activate(@ptrCast(c.GCallback, Callbacks.runPrefs), null);
self.menu.close_tab.connect_activate(@ptrCast(c.GCallback, Callbacks.closeCurrentTab), null);
self.menu.quit.connect_activate(@ptrCast(c.GCallback, c.gtk_main_quit), null);
self.window.as_widget().connect("delete-event", @ptrCast(c.GCallback, c.gtk_main_quit), null);
}
fn connectAccels(self: Self) void {
// Check to see if our keyfile exists, and if it doesn't then create it
// from the defaults
const bindings: Keys = if (keys.getKeyFile(allocator)) |file| kblk: {
defer allocator.free(file);
if (fs.cwd().openFile(file, .{ .read=true, .write=false })) |f| {
defer f.close();
break :kblk if (Keys.fromFile(f)) |k| k else Keys.default();
} else |_| {
const k = Keys.default();
Keys.save(k);
break :kblk k;
}
} else Keys.default();
const accel_group = c.gtk_accel_group_new();
self.menu.setAccels(accel_group, bindings);
self.nav.setAccels(accel_group, bindings);
c.gtk_window_add_accel_group(@ptrCast(*c.GtkWindow, self.window.ptr), accel_group);
}
};
pub fn activate(application: *c.GtkApplication, opts: c.gpointer) void {
// Cast the gpointer to a normal pointer and dereference it, giving us
// our "opts" struct initialized earlier.
options = @ptrCast(*Opts, @alignCast(8, opts)).*;
tabs = hashmap(u64, Tab).init(allocator);
defer tabs.deinit();
terms = hashmap(u64, *c.VteTerminal).init(allocator);
defer terms.deinit();
conf = if (config.Config.fromFile(options.config_dir)) |cfg| cfg else config.Config.default();
//conf = config.Config.default();
const builder = gtk.Builder.new();
c.gtk_builder_set_application(builder.ptr, application);
gui = Gui.init(builder);
// In order to support transparency, we have to make the entire window
// transparent, but we want to prevent the titlebar going transparent as well.
// These three settings are a hack which achieves this.
const screen = gui.window.as_widget().get_screen();
const visual = c.gdk_screen_get_rgba_visual(screen);
if (visual) |v| gui.window.as_widget().set_visual(v);
css_provider = c.gtk_css_provider_new();
c.gtk_style_context_add_provider_for_screen(
screen,
@ptrCast(*c.GtkStyleProvider, css_provider),
c.GTK_STYLE_PROVIDER_PRIORITY_USER);
gui.window.set_title(options.title);
const tab = Tab.init(options.command);
tabs.putNoClobber(@ptrToInt(tab.box.ptr), tab) catch |e| {
stderr.print("{}\n", .{e}) catch unreachable;
};
// We have to get the terminal in order to grab focus, use an
// iterator and return the first (and only) entry's value field
const kids = c.gtk_container_get_children(@ptrCast(*c.GtkContainer, tab.box.ptr));
const term = c.g_list_nth_data(kids, 0);
const term_ptr = @ptrCast(*c.GtkWidget, @alignCast(8, term));
gui.window.as_widget().show_all();
c.gtk_widget_grab_focus(term_ptr);
gui.connectSignals();
gui.connectAccels();
gui.applySettings();
c.gtk_main();
}
const Callbacks = struct {
fn newTab() void {
const tab = Tab.init(options.command);
tabs.putNoClobber(@ptrToInt(tab.box.ptr), tab) catch |e| {
stderr.print("{}\n", .{e}) catch unreachable;
};
}
fn newTerm(command: [:0]const u8) vte.Terminal {
const term = vte.Terminal.new();
term.set_clear_background(false);
terms.put(@ptrToInt(term.ptr), term.ptr) catch {};
term.spawn_async(.default, options.directory, command, null, .default, null, -1, null);
conf.set(term.ptr);
_ = gtk.signal_connect(
term.ptr,
"child-exited",
@ptrCast(c.GCallback, Callbacks.closeTermCallback),
null,
);
return term;
}
fn splitTab() void {
if (gui.currentTab()) |t| t.split();
}
fn rotateView() void {
if (gui.currentTab()) |t| t.rotate();
}
fn pageRemoved() void {
gui.pageRemoved();
}
fn selectPage() void {
if (gui.currentTab()) |t| t.selectPage();
}
fn closeCurrentTab() void {
const num = gui.notebook.get_current_page();
const box = gui.notebook.get_nth_page(num);
if (box) |b| {
const key = @ptrToInt(b.ptr);
Callbacks.closeTabByRef(key);
}
}
fn closeTabByButton(_: *c.GtkButton, box: c.gpointer) void {
const box_widget = @ptrCast(*c.GtkWidget, @alignCast(8, box));
const key = @ptrToInt(box_widget);
Callbacks.closeTabByRef(key);
}
fn closeTabByRef(key: u64) void {
if (tabs.get(key)) |tab| {
const num = gui.notebook.page_num(tab.box.as_widget());
if (num) |n| {
// if num < 0 tab is already closed
if (n >= 0) {
gui.notebook.remove_page(n);
_ = tabs.remove(key);
}
}
}
}
fn closeTermCallback(term: *c.VteTerminal) void {
const box = c.gtk_widget_get_parent(@ptrCast(*c.GtkWidget, term));
const key = @ptrToInt(box);
const termkey = @ptrToInt(@ptrCast(*c.GtkWidget, term));
_ = terms.remove(termkey);
c.gtk_container_remove(@ptrCast(*c.GtkContainer, box), @ptrCast(*c.GtkWidget, term));
c.gtk_widget_destroy(@ptrCast(*c.GtkWidget, term));
if (tabs.get(key)) |_| {
const kids = c.gtk_container_get_children(@ptrCast(*c.GtkContainer, box));
const len = c.g_list_length(kids);
if (len == 0) {
Callbacks.closeTabByRef(key);
} else {
const first = c.g_list_nth_data(kids, 0);
const first_ptr = @ptrCast(*c.GtkWidget, @alignCast(8, first));
c.gtk_widget_grab_focus(first_ptr);
}
}
}
pub fn runPrefs() void {
if (prefs.run(conf)) |newconf| {
conf = newconf;
gui.applySettings();
if (config.getConfigDir(allocator)) |d| {
conf.save(d);
}
} else conf.setBg();
}
};
// C style closures below
pub const Closures = struct {
pub fn newTab() callconv(.C) void {
Callbacks.newTab();
}
pub fn splitView() callconv(.C) void {
Callbacks.splitTab();
}
pub fn rotateView() callconv(.C) void {
Callbacks.rotateView();
}
pub fn quit() callconv(.C) void {
c.gtk_main_quit();
}
pub fn tab1() callconv(.C) void {
gui.nthTab(0);
}
pub fn tab2() callconv(.C) void {
gui.nthTab(1);
}
pub fn tab3() callconv(.C) void {
gui.nthTab(2);
}
pub fn tab4() callconv(.C) void {
gui.nthTab(3);
}
pub fn tab5() callconv(.C) void {
gui.nthTab(4);
}
pub fn tab6() callconv(.C) void {
gui.nthTab(5);
}
pub fn tab7() callconv(.C) void {
gui.nthTab(6);
}
pub fn tab8() callconv(.C) void {
gui.nthTab(7);
}
pub fn tab9() callconv(.C) void {
gui.nthTab(8);
}
pub fn prevTab() callconv(.C) void {
gui.prevTab();
}
pub fn nextTab() callconv(.C) void {
gui.nextTab();
}
pub fn nextPane() callconv(.C) void {
if (gui.currentTab()) |t| t.nextPane();
}
pub fn prevPane() callconv(.C) void {
if (gui.currentTab()) |t| t.prevPane();
}
pub fn copy() callconv(.C) void {
if (gui.currentTab()) |tab| {
if (tab.currentTerm()) |term| {
term.copy_primary();
}
}
}
pub fn paste() callconv(.C) void {
if (gui.currentTab()) |tab| {
if (tab.currentTerm()) |term| {
term.paste_primary();
}
}
}
};
|
src/gui.zig
|
const std = @import("std");
const olin = @import("./olin/olin.zig");
pub const os = olin;
pub const panic = os.panic;
const log = @import("./olin/log.zig");
const stdout = @import("./olin/resource.zig").Resource.stdout;
// Dark -> Light color map
const colorMap = " ,:!=+%#$";
// Hardcoded terminal size
const fbWidth = 80;
const fbHeight = 19;
// Framebuffer
var fb: [fbWidth * fbHeight]f32 = undefined;
const Vec2 = struct {
x: f32,
y: f32,
};
const Tri = struct {
v0: Vec2,
v1: Vec2,
v2: Vec2,
c0: f32,
c1: f32,
c2: f32,
};
// Clockwise winding
fn edgeFunction(a: Vec2, b: Vec2, c: Vec2) f32 {
return (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);
}
// Basic unoptimized barycentric rasterizer
fn renderTri(t: Tri) void {
const area = edgeFunction(t.v0, t.v1, t.v2);
var y: usize = 0;
while (y < fbHeight) {
var x: usize = 0;
while (x < fbWidth) {
const p = Vec2{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) };
const w0 = edgeFunction(t.v1, t.v2, p);
const w1 = edgeFunction(t.v2, t.v0, p);
const w2 = edgeFunction(t.v0, t.v1, p);
if (w0 >= 0 and w1 >= 0 and w2 >= 0) {
const c0 = t.c0 * (w0 / area);
const c1 = t.c1 * (w1 / area);
const c2 = t.c2 * (w2 / area);
fb[(fbHeight - y - 1) * fbWidth + x] = c0 + c1 + c2;
}
x = x + 1;
}
y = y + 1;
}
}
fn clearFramebuffer() !void {
for (fb) |*x, i| {
x.* = 0;
}
}
pub fn main() anyerror!void {
std.os.exit(do());
}
fn do() u8 {
const tri = Tri{
.v0 = Vec2{
.x = 75,
.y = 18,
},
.c0 = 1,
.v1 = Vec2{
.x = 60,
.y = 2,
},
.c1 = 0.8,
.v2 = Vec2{
.x = 4,
.y = 14,
},
.c2 = 0.2,
};
renderTri(tri);
var fbChars: [fbWidth * fbHeight * 10]u8 = undefined;
var fbNum: usize = 0;
var buf: [8]u8 = undefined;
var bright = true;
// Reset and then set to color 15
const init = "\x1B[0m\x1B[1;37m";
// Reset
const reset = "\x1B[0m";
// Bold off (dark text)
const makeDark = "\x1B[21m";
// Bold on (light text)
const makeBright = "\x1B[1m";
for (init) |b, i| fbChars[fbNum + i] = b;
fbNum = fbNum + init.len;
for (fb) |*x, pixi| {
const colzz = std.math.floor(x.* * @intToFloat(f32, colorMap.len * 2));
const colus = @floatToInt(usize, colzz);
const colClamped = std.math.min(std.math.max(0, colus), (colorMap.len * 2) - 1);
if (colClamped < colorMap.len) {
if (bright) {
for (makeDark) |b, i| fbChars[fbNum + i] = b;
fbNum = fbNum + makeDark.len;
bright = false;
}
} else {
if (!bright) {
for (makeBright) |b, i| fbChars[fbNum + i] = b;
fbNum = fbNum + makeBright.len;
bright = true;
}
}
fbChars[fbNum] = colorMap[colClamped >> 1];
fbNum = fbNum + 1;
if (pixi % fbWidth == 0) {
fbChars[fbNum] = '\n';
fbNum = fbNum + 1;
}
}
fbChars[fbNum] = '\n';
fbNum = fbNum + 1;
for (reset) |b, i| fbChars[fbNum + i] = b;
fbNum = fbNum + reset.len;
if(stdout()) |fout| {
if (fout.write(fbChars[0..])) |n| {
olin.runtime.exit(0);
} else |err| {
log.err(@errorName(err));
olin.runtime.exit(1);
}
} else |err| {
log.err(@errorName(err));
olin.runtime.exit(1);
}
olin.runtime.exit(0);
}
|
zig/src/triangle.zig
|
const std = @import("std");
const stdx = @import("stdx");
const uv = @import("uv");
const builtin = @import("builtin");
const log = stdx.log.scoped(.uv_poller);
const mac_sys = @import("mac_sys.zig");
const runtime = @import("runtime.zig");
/// A dedicated thread is used to poll libuv's backend fd.
pub const UvPoller = struct {
const Self = @This();
uv_loop: *uv.uv_loop_t,
inner: switch (builtin.os.tag) {
.linux => UvPollerLinux,
.macos => UvPollerMac,
.windows => UvPollerWindows,
else => unreachable,
},
// Must refer to the same address in memory.
notify: *std.Thread.ResetEvent,
close_flag: std.atomic.Atomic(bool),
// Used to make sure there is only one thread polling at any moment.
// Used for GetQueuedCompletionStatus (pre windows 10).
// Used for macos select poller. libuv uses kevent which can deadlock with select.
poll_ready: std.atomic.Atomic(bool),
// Once polling returns this will be set true.
// This thread will then block on poll_ready to continue.
// This provides a cheap method for the main thread to do a realtime check of the polled status.
// Once true, the main thread will process events, set polled to false and set poll_ready to true.
// If main thread is only concerned with evented io, it would wait on notify.
polled: bool,
pub fn init(uv_loop: *uv.uv_loop_t, notify: *std.Thread.ResetEvent) Self {
var new = Self{
.uv_loop = uv_loop,
.inner = undefined,
.notify = notify,
.close_flag = std.atomic.Atomic(bool).init(false),
.poll_ready = std.atomic.Atomic(bool).init(true),
.polled = false,
};
new.inner.init(uv_loop);
return new;
}
pub fn setPollReady(self: *Self) void {
if (builtin.os.tag == .windows or builtin.os.tag == .macos) {
self.poll_ready.store(true, .Release);
}
}
/// Only exposed for testing purposes.
pub fn poll(self: *Self) void {
self.inner.poll(self.uv_loop);
self.polled = true;
}
pub fn run(self: *Self) void {
// pthread on macos only allows setting the name on the current thread.
switch (builtin.os.tag) {
.macos, .ios, .watchos, .tvos => if (builtin.link_libc) {
_ = std.c.pthread_setname_np("UV Poller");
},
else => {},
}
while (true) {
if (self.close_flag.load(.Acquire)) {
break;
}
if (builtin.os.tag == .windows or builtin.os.tag == .macos) {
while (!self.poll_ready.load(.Acquire)) {}
}
// log.debug("uv poller wait", .{});
self.inner.poll(self.uv_loop);
// log.debug("uv poller wait end, alive: {}", .{uv.uv_loop_alive(self.uv_loop) == 1});
self.polled = true;
if (builtin.os.tag == .windows or builtin.os.tag == .macos) {
self.poll_ready.store(false, .Release);
}
// Notify that there is new uv work to process.
self.notify.set();
}
// Reuse flag to indicate the thread is done.
self.close_flag.store(false, .Release);
}
};
const UvPollerLinux = struct {
const Self = @This();
epfd: i32,
fn init(self: *Self, uv_loop: *uv.uv_loop_t) void {
const backend_fd = uv.uv_backend_fd(uv_loop);
var evt: std.os.linux.epoll_event = undefined;
evt.events = std.os.linux.EPOLL.IN;
evt.data.fd = backend_fd;
const epfd = std.os.epoll_create1(std.os.linux.EPOLL.CLOEXEC) catch unreachable;
std.os.epoll_ctl(epfd, std.os.linux.EPOLL.CTL_ADD, backend_fd, &evt) catch unreachable;
self.* = .{
.epfd = epfd,
};
}
fn poll(self: Self, uv_loop: *uv.uv_loop_t) void {
const timeout = uv.uv_backend_timeout(uv_loop);
var evts: [1]std.os.linux.epoll_event = undefined;
_ = std.os.epoll_wait(self.epfd, &evts, timeout);
}
};
const UvPollerMac = struct {
const Self = @This();
fn init(self: *Self, uv_loop: *uv.uv_loop_t) void {
_ = self;
_ = uv_loop;
}
fn poll(self: Self, uv_loop: *uv.uv_loop_t) void {
_ = self;
var tv: mac_sys.timeval = undefined;
const timeout = uv.uv_backend_timeout(uv_loop);
if (timeout != -1) {
tv.tv_sec = @divTrunc(timeout, 1000);
tv.tv_usec = @rem(timeout, 1000) * 1000;
}
var readset: mac_sys.fd_set = undefined;
const fd = uv.uv_backend_fd(uv_loop);
mac_sys.sys_FD_ZERO(&readset);
mac_sys.sys_FD_SET(fd, &readset);
var r: c_int = undefined;
while (true) {
r = mac_sys.select(fd + 1, &readset, null, null, if (timeout == -1) null else &tv);
if (r != -1 or std.os.errno(r) != .INTR) {
break;
}
}
}
};
/// Since UvPoller runs on a separate thread,
/// and libuv also uses GetQueuedCompletionStatus(Ex),
/// the iocp is assumed to allow 2 concurrent threads.
/// Otherwise, the first thread to call GetQueuedCompletionStatus will bind to iocp
/// preventing the other thread from receiving anything.
const UvPollerWindows = struct {
const Self = @This();
fn init(self: *Self, uv_loop: *uv.uv_loop_t) void {
_ = self;
_ = uv_loop;
}
fn poll(self: Self, uv_loop: *uv.uv_loop_t) void {
_ = self;
var bytes: u32 = undefined;
var key: usize = undefined;
var overlapped: ?*std.os.windows.OVERLAPPED = null;
// Wait forever if -1 is returned.
const timeout = uv.uv_backend_timeout(uv_loop);
// log.debug("windows poll wait {} {}", .{timeout, uv_loop.iocp.?});
if (timeout == -1) {
GetQueuedCompletionStatus(uv_loop.iocp.?, &bytes, &key, &overlapped, std.os.windows.INFINITE);
} else {
GetQueuedCompletionStatus(uv_loop.iocp.?, &bytes, &key, &overlapped, @intCast(u32, timeout));
}
// Repost so libuv can pick it up during uv_run.
if (overlapped != null) {
std.os.windows.PostQueuedCompletionStatus(uv_loop.iocp.?, bytes, key, overlapped) catch |err| {
log.debug("PostQueuedCompletionStatus error: {}", .{err});
};
}
}
};
/// For debugging. Poll immediately to see if there are problems with the windows queue.
pub export fn cosmic_check_win_queue() void {
if (builtin.os.tag != .windows) {
return;
}
// log.debug("check win queue", .{});
var bytes: u32 = undefined;
var key: usize = undefined;
var overlapped: ?*std.os.windows.OVERLAPPED = null;
GetQueuedCompletionStatus(runtime.global.uv_loop.iocp.?, &bytes, &key, &overlapped, 0);
if (overlapped != null) {
// Repost so we don't lose any queue items.
std.os.windows.PostQueuedCompletionStatus(runtime.global.uv_loop.iocp.?, bytes, key, overlapped) catch |err| {
log.debug("PostQueuedCompletionStatus error: {}", .{err});
};
}
}
/// Duped from std.os.windows.GetQueuedCompletionStatus in case we need to make changes.
fn GetQueuedCompletionStatus(
completion_port: std.os.windows.HANDLE,
bytes_transferred_count: *std.os.windows.DWORD,
lpCompletionKey: *usize,
lpOverlapped: *?*std.os.windows.OVERLAPPED,
dwMilliseconds: std.os.windows.DWORD,
) void {
if (std.os.windows.kernel32.GetQueuedCompletionStatus(
completion_port,
bytes_transferred_count,
lpCompletionKey,
lpOverlapped,
dwMilliseconds,
) == std.os.windows.FALSE) {
switch (std.os.windows.kernel32.GetLastError()) {
.ABANDONED_WAIT_0 => {
// Nop, iocp handle was closed.
},
.OPERATION_ABORTED => {
// Nop, event was cancelled.
log.debug("OPERATION ABORTED", .{});
unreachable;
},
.IMEOUT => {
// Nop, timeout reached.
},
//.HANDLE_EOF => return GetQueuedCompletionStatusResult.EOF,
else => |err| {
log.debug("GetQueuedCompletionStatus error: {}", .{err});
unreachable;
},
}
}
}
|
runtime/uv_poller.zig
|
const std = @import("std");
const math = std.math;
const stdx = @import("stdx");
const t = stdx.testing;
const Vec2 = stdx.math.Vec2;
const vec2 = Vec2.init;
const graphics = @import("../../graphics.zig");
const QuadBez = graphics.curve.QuadBez;
const SubQuadBez = graphics.curve.SubQuadBez;
const CubicBez = graphics.curve.CubicBez;
const Color = graphics.Color;
const Mesh = @import("mesh.zig").Mesh;
const TexShaderVertex = @import("mesh.zig").TexShaderVertex;
const Graphics = @import("graphics.zig").Graphics;
const log = std.log.scoped(.stroke);
/// Given quadratic bezier curve, generate triangles along the inner and outer offset paths.
pub fn strokeQuadBez(mesh: *Mesh, buf: *std.ArrayList(Vec2), q_bez: QuadBez, half_width: f32, color: Color) void {
q_bez.flatten(0.5, buf);
strokePath(mesh, buf.items, half_width, color);
}
/// Given cubic bezier curve, generate triangles along the inner and outer offset paths.
pub fn strokeCubicBez(mesh: *Mesh, buf: *std.ArrayList(Vec2), qbez_buf: *std.ArrayList(SubQuadBez), c_bez: CubicBez, half_width: f32, color: Color) void {
c_bez.flatten(0.5, buf, qbez_buf);
strokePath(mesh, buf.items, half_width, color);
}
fn strokePath(mesh: *Mesh, pts: []const Vec2, half_width: f32, color: Color) void {
var vert: TexShaderVertex = undefined;
vert.setUV(0, 0);
vert.setColor(color);
var last_uvec = Vec2.initTo(pts[0], pts[1]).normalize();
var i: u32 = 0;
while (i < pts.len - 1) : (i += 1) {
const uvec = Vec2.initTo(pts[i], pts[i+1]).normalize();
const right_off_nvec = computeOffsetNormal(last_uvec, uvec).mul(half_width);
const right_pt = pts[i].add(right_off_nvec);
const left_pt = pts[i].add(right_off_nvec.neg());
const pt = pts[i];
const start_idx = mesh.getNextIndexId();
vert.setXY(left_pt.x, left_pt.y);
_ = mesh.addVertex(&vert);
vert.setXY(pt.x, pt.y);
_ = mesh.addVertex(&vert);
vert.setXY(right_pt.x, right_pt.y);
_ = mesh.addVertex(&vert);
// Left side quad.
mesh.addQuad(start_idx, start_idx + 1, start_idx + 4, start_idx + 3);
// Right side quad.
mesh.addQuad(start_idx+1, start_idx + 2, start_idx + 5, start_idx + 4);
last_uvec = uvec;
}
{
const uvec = last_uvec;
const right_off_nvec = computeOffsetNormal(last_uvec, uvec).mul(half_width);
const right_pt = pts[i].add(right_off_nvec);
const left_pt = pts[i].add(right_off_nvec.neg());
const pt = pts[i];
vert.setXY(left_pt.x, left_pt.y);
_ = mesh.addVertex(&vert);
vert.setXY(pt.x, pt.y);
_ = mesh.addVertex(&vert);
vert.setXY(right_pt.x, right_pt.y);
_ = mesh.addVertex(&vert);
}
}
/// Compute a normal vector at point P where --v1--> P --v2-->
/// The resulting vector is not normalized, rather the length is such that extruding the shape
/// would yield parallel segments exactly 1 unit away from v1 and v2. (useful for generating strokes and vertex-aa).
/// The normal points towards the positive side of v1.
/// v1 and v2 are expected to be normalized.
pub fn computeOffsetNormal(v1: Vec2, v2: Vec2) Vec2 {
const epsilon = 1e-4;
const v12 = v1.add(v2);
if (v12.squareLength() < epsilon) {
return vec2(0, 0);
}
const tangent = v12.normalize();
const n = vec2(-tangent.y, tangent.x);
const n1 = vec2(-v1.y, v1.x);
const inv_len = n.dot(n1);
if (@fabs(inv_len) < epsilon) {
return n1;
}
return n.div(inv_len);
}
test "computeOffsetNormal" {
try t.eq(computeOffsetNormal(vec2(1, 0), vec2(-1, 0)), vec2(0, 0));
try t.eq(computeOffsetNormal(vec2(1, 0), vec2(0, 1)), vec2(-1, 1));
try t.eq(computeOffsetNormal(vec2(1, 0), vec2(0, -1)), vec2(1, 1));
try t.eq(computeOffsetNormal(vec2(1, 0), vec2(1, 0)), vec2(0, 1));
try t.eq(computeOffsetNormal(vec2(1, 0), vec2(1, 0)), vec2(0, 1));
}
|
graphics/src/backend/gpu/stroke.zig
|
const std = @import("std");
const zig = std.zig.Ast;
const mem = std.mem;
const meta = std.meta;
const Allocator = std.mem.Allocator;
const Token = @import("./Token.zig");
pub const Op = @import("./token/op.zig").Op;
pub const Kwd = @import("./token/kw.zig").Kwd;
pub const Symbol = @import("./token/sym.zig");
pub const Tag = Symbol.Tag;
pub const Val = Symbol.Val;
const Parser = @import("./Parser.zig");
pub const Ast = @This();
root: *Node = Node.init(Token.start(), 0),
input: []const u8 = "",
arena: std.heap.ArenaAllocator.State,
allocator: std.mem.Allocator,
pub fn print(self: *Ast, order: Node.Order) void {
std.debug.print("\x1b[32;1mAST:\n\x1b[0m", .{});
self.root.traverse(order, Token.print);
}
pub const Node = struct {
token: Token = Token.start(),
depth: usize = 0,
lhs: ?*Node = null,
rhs: ?*Node = null,
pub const Leaf = enum {
lhs, rhs,
};
pub const Order = enum { pre, in, post };
pub fn init(tok: Token, depth: usize) Node {
return Node { .token = tok, .depth = depth };
}
pub fn initExpr(token: Token, lhs: Token, rhs: Token, depth: usize) Node {
return Node {
.token = token,
.lhs = &Node.init(lhs, depth + 1),
.rhs = &Node.init(rhs, depth + 1),
.depth = depth
};
}
pub fn add(self: *Node, leaf: Leaf, tk: Token) *Node {
var node = Node.init(tk, self.depth + 1);
switch (leaf) {
.lhs => self.*.lhs = &node,
.rhs => self.*.rhs = &node,
}
return &node;
}
pub fn addExpr(self: *Node, leaf: Leaf, tk: Token, lhs: Token, rhs: Token) *Node {
var op_node = Node.initExpr(tk, lhs, rhs, self.depth + 1);
switch (leaf) {
.lhs => self.*.lhs = &op_node,
.rhs => self.*.rhs = &op_node,
}
return &op_node;
}
pub fn traverse(self: *Node, ord: Order, f: fn(Token) void) void {
switch (ord) {
Order.in => {
if(self.lhs) |l| l.traverse(ord, f);
f(self.token);
if (self.rhs) |r| r.traverse(ord, f);
},
Order.post => {
f(self.token);
if(self.lhs) |l| l.traverse(ord, f);
if (self.rhs) |r| r.traverse(ord, f);
},
Order.pre => {
if(self.lhs) |l| l.traverse(ord, f);
if (self.rhs) |r| r.traverse(ord, f);
f(self.token);
},
}
}
pub fn print(self: *Node) void {
std.debug.print("\x1b[35;1mNode: \x1b[0m", .{});
self.token.print();
}
};
pub const Queue = struct {
start: *QNode,
end: ?*QNode = null,
pub fn init(node: *Node) Queue {
return Queue{ .start = QNode.fromNode(node), .end = null};
}
pub const QNode = struct {
curr: *Node,
next: ?*Node = null,
pub fn fromNode(node: *Node) QNode {
return Queue.QNode { .curr = node, .next = null};
}
};
};
pub fn init(a: Allocator, arena: std.heap.ArenaAllocator.State, root: *Node, input: []const u8) Ast {
return Ast{
.root = root,
.input = input,
.arena = arena,
.allocator = a,
};
}
test "manual construction" {
var al = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(al);
var ast = Ast.init(al, arena.state, &Node.init(Token.start(), 0), "(T and T) or (T and F)");
var orn = ast.root.add(.lhs, Token.op(8, Token.Op.@"or"));
_ = orn.addExpr(.lhs, Token.op(4, Op.@"and"), Token.val(2,Val{.bool = true}), Token.val(6, Val{.bool = true}));
_ = orn.addExpr(.rhs, Token.op(16, Op.@"and"), Token.val(12, Val{.bool = true}), Token.val(18, Val{.bool = false}));
ast.print(Node.Order.in);
}
|
lib/idla/src/Ast.zig
|
const opt = @import("opt.zig");
const warn = std.debug.warn;
const std = @import("std");
const stdout = &std.io.getStdOut().writer();
const BUFSIZ: u16 = 4096;
pub fn cat(file: std.fs.File) !void {
// print file from start pos
var in_stream = std.fs.File.reader(file);
print_stream(&in_stream) catch |err| {
try stdout.print("Error: cannot print file: {}\n", .{err});
return;
};
}
// TODO add this to a library (used in tail also)
// Prints stream from current pointer to end of file in BUFSIZ
// chunks.
pub fn print_stream(stream: *std.fs.File.Reader) anyerror!void {
var buffer: [BUFSIZ]u8 = undefined;
var size = try stream.readAll(&buffer);
// loop until EOF hit
while (size > 0) : (size = (try stream.readAll(&buffer))) {
try stdout.print("{s}", .{buffer[0..size]});
}
}
const CatFlags = enum {
Help,
Version,
};
var flags = [_]opt.Flag(CatFlags){
.{
.name = CatFlags.Help,
.long = "help",
},
.{
.name = CatFlags.Version,
.long = "version",
},
};
pub fn main(args: [][]u8) anyerror!u8 {
var it = opt.FlagIterator(CatFlags).init(flags[0..], args);
while (it.next_flag() catch {
return 1;
}) |flag| {
switch (flag.name) {
CatFlags.Help => {
warn("cat FILE_NAME ..\n", .{});
return 1;
},
CatFlags.Version => {
warn("(version info here)\n", .{});
return 1;
},
}
}
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..], std.fs.File.OpenFlags{ .read = true, .write = false }) catch |err| {
try stdout.print("Error: cannot open file {s}\n", .{file_name});
return 1;
};
// run command
cat(file) catch |err| {
try stdout.print("Error: {}\n", .{err});
return 1;
};
file.close();
}
} else {
try stdout.print("cat FILE_NAME ..\n", .{});
return 1;
}
return 0;
}
|
src/cat.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day04.txt");
// const data = @embedFile("../data/day04-tst.txt");
pub fn main() !void {
var tokens = tokenize(u8, data, "\r\n");
var played_nums = tokens.next();
var bingos = try buildBingoArray(&tokens);
var to_be_removed = List(usize).init(gpa);
var numbers = tokenize(u8, played_nums.?, ",");
while (numbers.next()) |num| {
const n = try parseInt(u32, num, 10);
for (bingos.items) |_, i| {
var bingo = &bingos.items[i];
if (bingo.play(n)) {
if (bingos.items.len == 1) { // This for part 2. Just ignore the if for part 1.
var sum: u32 = 0;
var num_it = bingo.numbers.iterator();
while (num_it.next()) |entry| {
if (!bingo.marked[entry.value_ptr.*]) {
sum += entry.key_ptr.*;
}
}
print("{}\n", .{sum * n});
return;
} else {
try to_be_removed.append(i);
}
}
}
if (to_be_removed.items.len != 0) {
var k = @intCast(i32, to_be_removed.items.len - 1);
while (k >= 0) : (k -= 1) {
_ = bingos.orderedRemove(to_be_removed.items[@intCast(usize, k)]);
}
}
to_be_removed.clearRetainingCapacity();
// for (bingos.items) |bingo| {
// bingo.print();
// print("\n", .{});
// }
// print("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n", .{});
// std.time.sleep(1000000000);
}
}
fn buildBingoArray(lines: *std.mem.TokenIterator(u8)) !List(Bingo) {
var bingos = List(Bingo).init(gpa);
while (true) {
var i: u32 = 0;
var bingo = try Bingo.init();
while (i < 5) : (i += 1) {
var line = lines.next();
if (line == null) {
// avoid leaking, that would be aweful !
bingo.deinit();
return bingos;
}
var nums = tokenize(u8, line.?, " ");
var j: u32 = 0;
while (nums.next()) |num| : (j += 1) {
const n = try parseInt(u32, num, 10);
try bingo.numbers.put(n, i * 5 + j);
}
}
try bingos.append(bingo);
}
unreachable();
}
const Bingo = struct {
numbers: Map(u32, u32), // value - index
marked: [25]bool,
fn init() !Bingo {
var bingo: Bingo = undefined;
bingo.numbers = Map(u32, u32).init(gpa);
try bingo.numbers.ensureTotalCapacity(25);
for (bingo.marked) |_, i| {
bingo.marked[i] = false;
}
return bingo;
}
fn deinit(self: *Bingo) void {
self.numbers.deinit();
}
fn play(self: *Bingo, value: u32) bool {
var index = self.numbers.get(value);
if (index == null) {
return false;
}
self.marked[index.?] = true;
var i: u32 = 0;
while (i < 5) : (i += 1) {
var all_marked = true;
var j: u32 = 0;
while (j < 5 and all_marked) : (j += 1) {
all_marked = all_marked and self.marked[i * 5 + j];
}
if (all_marked) {
return true;
}
}
i = 0;
while (i < 5) : (i += 1) {
var all_marked = true;
var j: u32 = 0;
while (j < 5 and all_marked) : (j += 1) {
all_marked = all_marked and self.marked[j * 5 + i];
}
if (all_marked) {
return true;
}
}
return false;
}
fn print(self: *const Bingo) void {
var i: u32 = 0;
while (i < 5) : (i += 1) {
var j: u32 = 0;
while (j < 5) : (j += 1) {
var c: u8 = if (self.marked[i * 5 + j]) 'x' else '_';
std.debug.print("{c} ", .{c});
}
std.debug.print("\n", .{});
}
}
};
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const print = std.debug.print;
const assert = std.debug.assert;
const parseInt = std.fmt.parseInt;
|
src/day04.zig
|
const std = @import("std");
const nvg = @import("nanovg");
const gui = @import("../gui.zig");
const Rect = @import("../geometry.zig").Rect;
pub fn Spinner(comptime T: type) type {
comptime if (T != i32 and T != f32) @compileError("Spinner needs to be i32 or f32");
const StepMode = enum(u1) {
linear,
exponential,
};
return struct {
widget: gui.Widget,
allocator: *std.mem.Allocator,
text_box: *gui.TextBox,
up_button: *gui.Button,
down_button: *gui.Button,
value: T = 0,
min_value: T = 0,
max_value: T = 100,
step_value: T = 1,
step_mode: StepMode = .linear,
baseTextBoxBlurFn: fn (*gui.Widget, *gui.FocusEvent) void,
onChangedFn: ?fn (*Self) void = null,
const Self = @This();
pub fn init(allocator: *std.mem.Allocator, rect: Rect(f32)) !*Self {
var self = try allocator.create(Self);
self.* = Self{
.widget = gui.Widget.init(allocator, rect),
.text_box = try gui.TextBox.init(allocator, Rect(f32).make(0, 0, 0, 0)),
.baseTextBoxBlurFn = undefined,
.up_button = try gui.Button.init(allocator, Rect(f32).make(0, 0, 0, 0), ""),
.down_button = try gui.Button.init(allocator, Rect(f32).make(0, 0, 0, 0), ""),
.allocator = allocator,
};
self.up_button.widget.focus_policy = gui.FocusPolicy.none();
self.down_button.widget.focus_policy = gui.FocusPolicy.none();
self.baseTextBoxBlurFn = self.text_box.widget.onBlurFn;
self.widget.onResizeFn = onResize;
self.widget.onKeyDownFn = onKeyDown;
self.widget.onKeyUpFn = onKeyUp;
try self.widget.addChild(&self.up_button.widget);
try self.widget.addChild(&self.down_button.widget);
try self.widget.addChild(&self.text_box.widget);
self.text_box.onChangedFn = struct {
fn changed(text_box: *gui.TextBox) void {
const error_color = nvg.rgbf(1, 0.82, 0.8);
if (text_box.widget.parent) |parent| {
const spinner = @fieldParentPtr(Spinner(T), "widget", parent);
if (text_box.text.items.len > 0) {
const text = text_box.text.items;
if (switch (T) {
i32 => std.fmt.parseInt(i32, text, 10),
f32 => std.fmt.parseFloat(f32, text),
else => unreachable,
}) |value| {
const old_value = spinner.value;
const in_range = value >= spinner.min_value and value <= spinner.max_value;
spinner.value = std.math.clamp(value, spinner.min_value, spinner.max_value);
if (spinner.value != old_value) spinner.notifyChanged();
text_box.background_color = if (in_range) gui.theme_colors.light else error_color;
} else |_| { // error
text_box.background_color = error_color;
}
}
}
}
}.changed;
self.text_box.widget.onBlurFn = struct {
fn blur(widget: *gui.Widget, event: *gui.FocusEvent) void {
if (widget.parent) |parent| {
const spinner = @fieldParentPtr(Spinner(T), "widget", parent);
spinner.up_button.pressed = false;
spinner.down_button.pressed = false;
spinner.baseTextBoxBlurFn(widget, event);
spinner.updateTextBox();
spinner.text_box.background_color = gui.theme_colors.light;
}
}
}.blur;
self.up_button.iconFn = gui.drawSmallArrowUp;
self.up_button.onClickFn = struct {
fn click(button: *gui.Button) void {
if (button.widget.parent) |parent| {
const spinner = @fieldParentPtr(Spinner(T), "widget", parent);
spinner.increment();
spinner.updateTextBox(); // ignore focus
}
}
}.click;
self.up_button.auto_repeat_interval = 150;
self.down_button.iconFn = gui.drawSmallArrowDown;
self.down_button.onClickFn = struct {
fn click(button: *gui.Button) void {
if (button.widget.parent) |parent| {
const spinner = @fieldParentPtr(Spinner(T), "widget", parent);
spinner.decrement();
spinner.updateTextBox(); // ignore focus
}
}
}.click;
self.down_button.auto_repeat_interval = 150;
self.updateTextBox();
self.updateLayout();
return self;
}
pub fn deinit(self: *Self) void {
self.text_box.deinit();
self.up_button.deinit();
self.down_button.deinit();
self.widget.deinit();
self.allocator.destroy(self);
}
fn onResize(widget: *gui.Widget, event: *gui.ResizeEvent) void {
_ = event;
const self = @fieldParentPtr(Self, "widget", widget);
self.updateLayout();
}
fn onKeyDown(widget: *gui.Widget, event: *gui.KeyEvent) void {
const self = @fieldParentPtr(Self, "widget", widget);
switch (event.key) {
.Up => {
self.up_button.pressed = true;
self.increment();
self.updateTextBox(); // ignore focus
},
.Down => {
self.down_button.pressed = true;
self.decrement();
self.updateTextBox(); // ignore focus
},
else => event.event.ignore(),
}
}
fn onKeyUp(widget: *gui.Widget, event: *gui.KeyEvent) void {
const self = @fieldParentPtr(Self, "widget", widget);
switch (event.key) {
.Up => self.up_button.pressed = false,
.Down => self.down_button.pressed = false,
else => event.event.ignore(),
}
}
fn updateLayout(self: *Self) void {
const button_width = 16;
const rect = self.widget.relative_rect;
self.up_button.widget.relative_rect.x = rect.w - button_width;
self.down_button.widget.relative_rect.x = rect.w - button_width;
self.down_button.widget.relative_rect.y = 0.5 * rect.h - 0.5;
self.text_box.widget.setSize(rect.w + 1 - button_width, rect.h);
self.up_button.widget.setSize(button_width, 0.5 * rect.h + 0.5);
self.up_button.icon_x = std.math.floor((self.up_button.widget.relative_rect.w - 6) / 2);
self.up_button.icon_y = std.math.floor((self.up_button.widget.relative_rect.h - 6) / 2);
self.down_button.widget.setSize(button_width, 0.5 * rect.h + 0.5);
self.down_button.icon_x = std.math.floor((self.down_button.widget.relative_rect.w - 6) / 2);
self.down_button.icon_y = std.math.floor((self.down_button.widget.relative_rect.h - 6) / 2);
}
pub fn setFocus(self: *Self, focus: bool, source: gui.FocusSource) void {
self.text_box.widget.setFocus(focus, source);
}
fn increment(self: *Self) void {
const new_value = switch (self.step_mode) {
.linear => self.value + self.step_value,
.exponential => self.value * (1 + self.step_value),
};
self.setValue(new_value);
}
pub fn decrement(self: *Self) void {
const new_value = switch (self.step_mode) {
.linear => self.value - self.step_value,
.exponential => if (T == i32) @divFloor(self.value, (1 + self.step_value)) else self.value / (1 + self.step_value),
};
self.setValue(new_value);
}
pub fn setValue(self: *Self, value: T) void {
const old_value = self.value;
self.value = std.math.clamp(value, self.min_value, self.max_value);
if (self.value != old_value) {
self.updateTextBox();
self.notifyChanged();
}
}
fn updateTextBox(self: *Self) void {
var buf: [50]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
switch (T) {
i32 => std.fmt.formatInt(self.value, 10, .lower, .{}, fbs.writer()) catch unreachable,
f32 => std.fmt.formatFloatDecimal(self.value, .{ .precision = 2 }, fbs.writer()) catch unreachable,
else => unreachable,
}
if (std.mem.indexOfScalar(u8, buf[0..fbs.pos], '.')) |dec| { // trim zeroes
while (buf[fbs.pos - 1] == '0') fbs.pos -= 1;
if (fbs.pos - 1 == dec) fbs.pos -= 1;
}
self.text_box.setText(buf[0..fbs.pos]) catch {}; // TODO
}
fn notifyChanged(self: *Self) void {
if (self.onChangedFn) |onChangedFn| onChangedFn(self);
}
};
}
|
src/gui/widgets/Spinner.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const windows = std.os.windows;
const Buffer = @import("../buffer.zig").Buffer;
const AudioMode = @import("../index.zig").AudioMode;
const winnm = @import("winnm.zig");
const Header = struct {
const Self = @This();
pub const Error = error {
InvalidLength,
};
buffer: Buffer(u8),
wavehdr: winnm.WaveHdr,
pub fn new(player: Player, buf_size: usize) !Self {
var result: Self = undefined;
result.buffer = try Buffer(u8).initSize(player.allocator, buf_size);
result.wavehdr = winnm.WaveHdr {
.lpData = result.buffer.ptr(),
.dwBufferLength = @intCast(windows.DWORD, buf_size),
.dwBytesRecorded = undefined,
.dwUser = undefined,
.dwFlags = 0,
.dwLoops = undefined,
.lpNext = undefined,
.reserved = undefined,
};
try winnm.waveOutPrepareHeader(
player.handle, &result.wavehdr,
@sizeOf(winnm.WaveHdr)
).toError();
return result;
}
pub fn write(self: *Self, player: *const Player, data: []const u8) !void {
if (data.len != self.buffer.len()) {
return error.InvalidLength;
}
try self.buffer.replaceContents(data);
try winnm.waveOutWrite(
player.handle, &self.wavehdr,
@intCast(windows.UINT, self.buffer.len())
).toError();
}
pub fn destroy(self: *Self, player: Player) !void {
try winnm.waveOutUnprepareHeader(
player.handle, &self.wavehdr,
@sizeOf(winnm.WaveHdr)
).toError();
self.buffer.deinit();
}
};
pub const Player = struct {
const Self = @This();
const BUF_COUNT = 2;
pub const Error = Header.Error || Allocator.Error || winnm.MMError;
allocator: *Allocator,
handle: windows.HANDLE,
headers: [BUF_COUNT]Header,
tmp: Buffer(u8),
buf_size: usize,
pub fn new(allocator: *Allocator, sample_rate: usize, mode: AudioMode, buf_size: usize) Error!Self {
var result: Self = undefined;
var handle: windows.HANDLE = undefined;
const bps = switch (mode) {
AudioMode.Mono => |bps| bps,
AudioMode.Stereo => |bps| bps,
};
const block_align = bps * mode.channelCount();
const format = winnm.WaveFormatEx {
.wFormatTag = winnm.WAVE_FORMAT_PCM,
.nChannels = @intCast(windows.WORD, mode.channelCount()),
.nSamplesPerSec = @intCast(windows.DWORD, sample_rate),
.nAvgBytesPerSec = @intCast(windows.DWORD, sample_rate * block_align),
.nBlockAlign = @intCast(windows.WORD, block_align),
.wBitsPerSample = @intCast(windows.WORD, bps * 8),
.cbSize = 0,
};
try winnm.waveOutOpen(
&handle, winnm.WAVE_MAPPER, &format,
0, 0, winnm.CALLBACK_NULL
).toError();
result = Self {
.handle = handle,
.headers = []Header {undefined} ** BUF_COUNT,
.buf_size = buf_size,
.allocator = allocator,
.tmp = try Buffer(u8).initSize(allocator, buf_size)
};
for (result.headers) |*header| {
header.* = try Header.new(result, buf_size);
}
return result;
}
pub fn write(self: *Self, data: []const u8) Error!usize {
const n = std.math.min(data.len, std.math.max(0, self.buf_size - self.tmp.len()));
try self.tmp.append(data[0..n]);
if (self.tmp.len() < self.buf_size) {
return n;
}
var header = for (self.headers) |header| {
if (header.wavehdr.dwFlags & winnm.WHDR_INQUEUE == 0) {
break header;
}
} else return n;
try header.write(self, self.tmp.toSlice());
try self.tmp.resize(0);
return n;
}
pub fn close(self: *Self) Error!void {
for (self.headers) |*header| {
try header.destroy(self.handle);
}
try winnm.waveOutClose(self.handle).toError();
self.tmp.deinit();
}
};
|
src/windows/index.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const fixedBufferStream = std.io.fixedBufferStream;
const ChemicalQuantity = struct {
chem: []const u8,
quant: usize,
const Self = @This();
pub fn mult(self: Self, x: usize) Self {
return Self{
.chem = self.chem,
.quant = self.quant * x,
};
}
pub fn print(self: Self) void {
std.debug.warn("{} {}", .{ self.quant, self.chem });
}
};
const one_fuel = ChemicalQuantity{ .chem = "FUEL", .quant = 1 };
const Reaction = struct {
alloc: *Allocator,
text: []const u8,
inputs: []ChemicalQuantity,
output: ChemicalQuantity,
const Self = @This();
pub fn fromStr(alloc: *Allocator, str: []const u8) !?Self {
return try ReactionParser.init(alloc, str).parseReaction();
}
pub fn deinit(self: *Self) void {
// std.debug.warn("{}\n", .{ self.output.chem });
self.alloc.free(self.text);
self.alloc.free(self.inputs);
}
pub fn print(self: Self) void {
for (self.inputs) |x| {
x.print();
std.debug.warn(", ", .{});
}
std.debug.warn(" => ", .{});
self.output.print();
std.debug.warn("\n", .{});
}
};
const ReactionParser = struct {
alloc: *Allocator,
str: []const u8,
pos: usize,
const Self = @This();
pub fn init(alloc: *Allocator, str: []const u8) Self {
return Self{
.alloc = alloc,
.str = str,
.pos = 0,
};
}
pub fn parseReaction(self: *Self) !?Reaction {
var inputs = ArrayList(ChemicalQuantity).init(self.alloc);
try inputs.append(self.parseChemicalQuantity() orelse return null);
self.skipWs();
while ((self.peek() orelse return null) == ',') {
_ = self.pop(); // consume the comma
self.skipWs();
// std.debug.warn("appending", .{});
try inputs.append(self.parseChemicalQuantity() orelse return null);
self.skipWs();
}
self.skipWs();
if (!self.acceptChar('=')) return null;
if (!self.acceptChar('>')) return null;
self.skipWs();
const output = self.parseChemicalQuantity() orelse return null;
return Reaction{
.alloc = self.alloc,
.text = self.str,
.inputs = inputs.toOwnedSlice(),
.output = output,
};
}
fn parseChemicalQuantity(self: *Self) ?ChemicalQuantity {
const quant = self.parseUsize() orelse return null;
self.skipWs();
const name = self.parseAlpha() orelse return null;
self.skipWs();
return ChemicalQuantity{
.quant = quant,
.chem = name,
};
}
fn parseUsize(self: *Self) ?usize {
var result: usize = 0;
while (self.peek()) |c| {
if (c < '0' or '9' < c) break;
result = result * 10 + (self.pop().? - '0');
}
return result;
}
fn parseAlpha(self: *Self) ?[]const u8 {
const old_pos = self.pos;
while (self.peek()) |c| {
if (c < 'A' or 'Z' < c) break;
_ = self.pop();
}
return self.str[old_pos..self.pos];
}
fn peek(self: Self) ?u8 {
if (self.pos < self.str.len) {
return self.str[self.pos];
} else {
return null;
}
}
fn pop(self: *Self) ?u8 {
defer if (self.pos < self.str.len) {
self.pos += 1;
};
return self.peek();
}
fn skipWs(self: *Self) void {
while ((self.peek() orelse return) == ' ') _ = self.pop();
}
fn acceptChar(self: *Self, char: u8) bool {
if (self.peek()) |c| {
if (c == char) _ = self.pop();
return c == char;
} else {
return false;
}
}
};
test "parse reaction" {
const allocator = std.testing.allocator;
const str = try std.mem.dupe(allocator, u8, "10 ORE => 20 ABC");
const expected = Reaction{
.alloc = allocator,
.text = str,
.inputs = &[_]ChemicalQuantity{
ChemicalQuantity{ .chem = str[3..6], .quant = 10 },
},
.output = ChemicalQuantity{ .chem = str[13..16], .quant = 20 },
};
var actual = (try Reaction.fromStr(allocator, str)).?;
defer actual.deinit();
expectEqual(expected.output, actual.output);
expectEqualSlices(ChemicalQuantity, expected.inputs, actual.inputs);
}
fn reactionsFromStream(alloc: *Allocator, stream: anytype) ![]Reaction {
var result = ArrayList(Reaction).init(alloc);
while (stream.readUntilDelimiterAlloc(alloc, '\n', 1024)) |line| {
// std.debug.warn("parsing: {}\n", .{ line });
if (try Reaction.fromStr(alloc, line)) |r| {
try result.append(r);
} else {
std.debug.warn("Could not parse: {}\n", .{line});
}
} else |e| switch (e) {
error.EndOfStream => {},
else => return e,
}
return result.toOwnedSlice();
}
test "parse example reactions" {
const allocator = std.testing.allocator;
var stream = fixedBufferStream(
\\9 ORE => 2 A
\\8 ORE => 3 B
\\7 ORE => 5 C
\\3 A, 4 B => 1 AB
\\5 B, 7 C => 1 BC
\\4 C, 1 A => 1 CA
\\2 AB, 3 BC, 4 CA => 1 FUEL
\\
).reader();
const reactions = try reactionsFromStream(allocator, stream);
defer allocator.free(reactions);
defer for (reactions) |*x| x.deinit();
for (reactions) |x| {
x.print();
}
}
const UniQueue = struct {
internal: ArrayList(ChemicalQuantity),
const Self = @This();
pub fn init(alloc: *Allocator) Self {
return Self{
.internal = ArrayList(ChemicalQuantity).init(alloc),
};
}
pub fn deinit(self: *Self) void {
self.internal.deinit();
}
pub fn onlyOre(self: Self) bool {
return self.internal.items.len == 1 and std.mem.eql(u8, "ORE", self.internal.items[0].chem);
}
pub fn pop(self: *Self) ChemicalQuantity {
return self.internal.orderedRemove(0);
}
pub fn push(self: *Self, c: ChemicalQuantity) !void {
for (self.internal.items) |*x| {
if (std.mem.eql(u8, x.chem, c.chem)) {
x.quant += c.quant;
return;
}
}
try self.internal.append(c);
}
};
fn requiredOre(alloc: *Allocator, reactions: []const Reaction) !usize {
var queue = UniQueue.init(alloc);
defer queue.deinit();
try queue.push(one_fuel);
while (!queue.onlyOre()) {
const c = queue.pop();
for (reactions) |r| {
if (std.mem.eql(u8, c.chem, r.output.chem)) {
const multiplier = c.quant / r.output.quant + (if (c.quant % r.output.quant > 0) @as(usize, 1) else 0);
for (r.inputs) |inp| {
try queue.push(inp.mult(multiplier));
}
break;
}
}
}
return queue.internal.items[0].quant;
}
test "requirements for example reactions" {
const allocator = std.testing.allocator;
var stream = fixedBufferStream(
\\9 ORE => 2 A
\\8 ORE => 3 B
\\7 ORE => 5 C
\\3 A, 4 B => 1 AB
\\5 B, 7 C => 1 BC
\\4 C, 1 A => 1 CA
\\2 AB, 3 BC, 4 CA => 1 FUEL
\\
).reader();
const reactions = try reactionsFromStream(allocator, stream);
defer allocator.free(reactions);
defer for (reactions) |*x| x.deinit();
expectEqual(@as(usize, 165), try requiredOre(allocator, reactions));
}
test "requirements for example 1" {
const allocator = std.testing.allocator;
var stream = fixedBufferStream(
\\157 ORE => 5 NZVS
\\165 ORE => 6 DCFZ
\\44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
\\12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ
\\179 ORE => 7 PSHF
\\177 ORE => 5 HKGWZ
\\7 DCFZ, 7 PSHF => 2 XJWVT
\\165 ORE => 2 GPVTF
\\3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT
\\
).reader();
const reactions = try reactionsFromStream(allocator, stream);
defer allocator.free(reactions);
defer for (reactions) |*x| x.deinit();
expectEqual(@as(usize, 13312), try requiredOre(allocator, reactions));
}
test "requirements for example 2" {
const allocator = std.testing.allocator;
var stream = fixedBufferStream(
\\2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG
\\17 NVRVD, 3 JNWZP => 8 VPVL
\\53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL
\\22 VJHF, 37 MNCFX => 5 FWMGM
\\139 ORE => 4 NVRVD
\\144 ORE => 7 JNWZP
\\5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC
\\5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV
\\145 ORE => 6 MNCFX
\\1 NVRVD => 8 CXFTF
\\1 VJHF, 6 MNCFX => 4 RFSQX
\\176 ORE => 6 VJHF
\\
).reader();
const reactions = try reactionsFromStream(allocator, stream);
defer allocator.free(reactions);
defer for (reactions) |*x| x.deinit();
for (reactions) |x| {
x.print();
}
// expectEqual(@as(usize, 180697), try requiredOre(allocator, reactions));
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const input_file = try std.fs.cwd().openFile("input14.txt", .{});
var input_stream = input_file.reader();
const reactions = try reactionsFromStream(allocator, input_stream);
defer allocator.free(reactions);
defer for (reactions) |*x| x.deinit();
std.debug.warn("required ore: {}\n", .{try requiredOre(allocator, reactions)});
}
|
zig/14.zig
|
const CTRL_SECURITY_ERROR_RESPONSE: u32 = 1 << 4;
const CTRL_AUTOINCREMENT: u32 = 1 << 8;
/// The device driver for the TrustZone Memory Protection Controller.
///
/// It is documented in the ARM CoreLink SIE-200 System IP for Embedded TRM
/// (DDI 0571G):
/// <https://developer.arm.com/products/architecture/m-profile/docs/ddi0571/g>
/// A software implementation can be found in QEMU's `tz-mpc.c`.
pub const TzMpc = struct {
base: usize,
const Self = @This();
/// Construct a `Pl011` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// Assign an address range to Non-Secure.
///
/// The range might be rounded to the block size the hardware is configured
/// with.
pub fn assignRangeToNonSecure(self: Self, start: u32, end: u32) void {
self.updateRange(start, end, Masks{ 0x00000000, 0xffffffff });
}
/// Assign an address range to Secure.
///
/// The range might be rounded to the block size the hardware is configured
/// with.
pub fn assignRangeToSecure(self: Self, start: u32, end: u32) void {
self.updateRange(start, end, Masks{ 0x00000000, 0x00000000 });
}
pub fn setEnableBusError(self: Self, value: bool) void {
if (value) {
self.regCtrl().* |= CTRL_SECURITY_ERROR_RESPONSE;
} else {
self.regCtrl().* &= ~CTRL_SECURITY_ERROR_RESPONSE;
}
}
fn regCtrl(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base);
}
fn regBlkMax(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x10);
}
fn regBlkCfg(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x14);
}
fn regBlkIdx(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x18);
}
fn regBlkLut(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x1c);
}
// TODO: Registers related to interrupt
fn blockSizeShift(self: Self) u5 {
return @truncate(u5, self.regBlkCfg().*) + 5;
}
fn updateLut(self: Self, masks: Masks) void {
const lut = self.regBlkLut();
lut.* = (lut.* & masks[0]) ^ masks[1];
}
fn updateRange(self: Self, startBytes: u32, endBytes: u32, masks: Masks) void {
// (Silently) round to the block size used by the hardware
const shift = self.blockSizeShift();
const start = startBytes >> shift;
const end = endBytes >> shift;
if (start >= end) {
return;
}
const start_group = start / 32;
const end_group = end / 32;
self.regCtrl().* &= ~CTRL_AUTOINCREMENT;
self.regBlkIdx().* = start_group;
if (start_group == end_group) {
const masks2 = filterMasks(masks, onesFrom(start % 32) ^ onesFrom(end % 32));
self.updateLut(masks2);
} else {
var group = start_group;
if ((start % 32) != 0) {
const cap_masks = filterMasks(masks, onesFrom(start % 32));
self.updateLut(cap_masks);
group += 1;
self.regBlkIdx().* = group;
}
while (group < end_group) {
self.updateLut(masks);
group += 1;
self.regBlkIdx().* = group;
}
if ((end % 32) != 0) {
const cap_masks = filterMasks(masks, ~onesFrom(end % 32));
self.updateLut(cap_masks);
}
}
}
};
/// AND and XOR masks.
const Masks = [2]u32;
fn filterMasks(masks: Masks, filter: u32) Masks {
return Masks{ masks[0] & ~filter, masks[1] & filter };
}
/// Returns `0b11111000...000` where the number of trailing zeros is specified
/// by `pos`. `pos` must be in `[0, 31]`.
fn onesFrom(pos: u32) u32 {
return u32(0xffffffff) << @intCast(u5, pos);
}
|
src/drivers/tz_mpc.zig
|
const std = @import("std");
const assert = std.debug.assert;
//===========================================================================//
/// Newly allocated memory will be memset to this value in debug mode, to help
/// users catch bugs where they use uninitialized memory.
pub const allocated_byte_memset: u8 = 0xaa;
/// Deallocated memory will (to some extent) be memset to this value in debug
/// mode, to help users catch use-after-free bugs.
pub const deallocated_byte_memset: u8 = 0xdd;
//===========================================================================//
/// Arbitrary magic number stored as the first field in a Superblock struct.
/// We use this to help detect errors where a program tries to free memory to
/// our allocator that was not allocated by it.
pub const superblock_magic_number: u32 = 0xb40cd14d;
/// The size of a Superblock struct. We'll typically be allocating these
/// directly from the OS, so it's best for this to be a multiple of the system
/// page size.
pub const superblock_size = std.os.page_size;
/// Bitwise-anding this mask with a pointer to a block will yield the pointer
/// to its containing superblock. This works because superblocks are always
/// aligned to `superblock_size`.
pub const superblock_ptr_mask = ~(usize(superblock_size) - 1);
/// The maximum block size for a superblock. Allocations larger than this are
/// delegated to the child allocator (which will typically be allocating
/// directly from the OS).
pub const max_block_size = @divExact(superblock_size, 16);
/// The smallest block size for a superblock. We need this to be at least the
/// size of a pointer to a block so that we can store a freelist within the
/// unallocated blocks in a superblock.
pub const min_block_size = @sizeOf(?[*]u8);
/// Superblocks within a heap are sorted into (emptyness_denominator + 2)
/// different buckets based on how full they are. Bucket #0 contains
/// totally-full superblocks; bucket #1 contains superblocks that are up to
/// 1/emptyness_denominator empty; bucket #2 contains superblocks that are
/// between 1/emptyness_denominator and 2/emptyness_denominator empty, and so
/// on; and the last bucket contains totally-empty superblocks.
pub const emptyness_denominator = 4;
pub const num_emptyness_buckets = emptyness_denominator + 2;
pub const totally_empty_bucket_index = num_emptyness_buckets - 1;
//===========================================================================//
/// Arbitrary magic number stored as the first field in a Hyperblock struct.
/// We use this to help detect errors where a program tries to free memory to
/// our allocator that was not allocated by it.
pub const hyperblock_magic_number: u32 = 0xda5b76a9;
/// The size of a Hyperblock struct. We'll typically be allocating these
/// directly from the OS, so it's best for this to be a multiple of the system
/// page size.
pub const hyperblock_size = 8 * std.os.page_size;
/// The number of equal-sized pieces that a hyperblock is divided into. The
/// first piece holds the hyperblock header, and the rest are used as
/// allocation chunks.
pub const chunk_denominator = 128;
/// The number of chunks in a hyperblock.
pub const hyperblock_num_chunks = chunk_denominator - 1;
/// The size of a hyperblock chunk.
pub const chunk_size = @divExact(hyperblock_size, chunk_denominator);
/// The maxinum number of hyperblock chunks that may comprise an allocated
/// span.
pub const allocated_span_max_num_chunks =
@divExact(std.os.page_size, chunk_size);
/// The maximum size (in bytes) of an allocated span in a hyperblock. Note
/// that we must leave room for a pointer to the containing hyperblock.
pub const allocated_span_max_size =
allocated_span_max_num_chunks * chunk_size - @sizeOf(*@OpaqueType());
//===========================================================================//
fn isPowerOfTwo(value: var) bool {
return value & (value - 1) == 0;
}
test "params" {
// Make sure the superblock size is a power of two (so that we can mask out
// block pointers to get a pointer to the containing superblock):
comptime assert(isPowerOfTwo(superblock_size));
// Block sizes must be powers of two, so check that the min and max block
// sizes are powers of two:
comptime assert(isPowerOfTwo(min_block_size));
comptime assert(isPowerOfTwo(max_block_size));
// We use chunk_size as an alignment for hyperblocks, so it must be a power
// of two:
comptime assert(isPowerOfTwo(chunk_size));
}
//===========================================================================//
|
src/ziegfried/params.zig
|
const Subsurface = @This();
const std = @import("std");
const assert = std.debug.assert;
const wlr = @import("wlroots");
const wl = @import("wayland").server.wl;
const server = &@import("main.zig").server;
const util = @import("util.zig");
const DragIcon = @import("DragIcon.zig");
const LayerSurface = @import("LayerSurface.zig");
const XdgToplevel = @import("XdgToplevel.zig");
pub const Parent = union(enum) {
xdg_toplevel: *XdgToplevel,
layer_surface: *LayerSurface,
drag_icon: *DragIcon,
pub fn damageWholeOutput(parent: Parent) void {
switch (parent) {
.xdg_toplevel => |xdg_toplevel| xdg_toplevel.view.output.damage.addWhole(),
.layer_surface => |layer_surface| layer_surface.output.damage.addWhole(),
.drag_icon => |drag_icon| {
var it = server.root.outputs.first;
while (it) |node| : (it = node.next) node.data.damage.addWhole();
},
}
}
};
/// The parent at the root of this surface tree
parent: Parent,
wlr_subsurface: *wlr.Subsurface,
// Always active
subsurface_destroy: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleDestroy),
map: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleMap),
unmap: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleUnmap),
new_subsurface: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleNewSubsurface),
// Only active while mapped
commit: wl.Listener(*wlr.Surface) = wl.Listener(*wlr.Surface).init(handleCommit),
pub fn create(wlr_subsurface: *wlr.Subsurface, parent: Parent) void {
const subsurface = util.gpa.create(Subsurface) catch {
std.log.crit("out of memory", .{});
wlr_subsurface.resource.getClient().postNoMemory();
return;
};
subsurface.* = .{ .wlr_subsurface = wlr_subsurface, .parent = parent };
assert(wlr_subsurface.data == 0);
wlr_subsurface.data = @ptrToInt(subsurface);
wlr_subsurface.events.destroy.add(&subsurface.subsurface_destroy);
wlr_subsurface.events.map.add(&subsurface.map);
wlr_subsurface.events.unmap.add(&subsurface.unmap);
wlr_subsurface.surface.events.new_subsurface.add(&subsurface.new_subsurface);
Subsurface.handleExisting(wlr_subsurface.surface, parent);
}
/// Create Subsurface structs to track subsurfaces already present on the
/// given surface when river becomes aware of the surface as we won't
/// recieve a new_subsurface event for them.
pub fn handleExisting(surface: *wlr.Surface, parent: Parent) void {
var below_it = surface.subsurfaces_below.iterator(.forward);
while (below_it.next()) |s| Subsurface.create(s, parent);
var above_it = surface.subsurfaces_above.iterator(.forward);
while (above_it.next()) |s| Subsurface.create(s, parent);
}
/// Destroy this Subsurface and all of its children
pub fn destroy(subsurface: *Subsurface) void {
subsurface.subsurface_destroy.link.remove();
subsurface.map.link.remove();
subsurface.unmap.link.remove();
subsurface.new_subsurface.link.remove();
if (subsurface.wlr_subsurface.mapped) subsurface.commit.link.remove();
Subsurface.destroySubsurfaces(subsurface.wlr_subsurface.surface);
subsurface.wlr_subsurface.data = 0;
util.gpa.destroy(subsurface);
}
pub fn destroySubsurfaces(surface: *wlr.Surface) void {
var below_it = surface.subsurfaces_below.iterator(.forward);
while (below_it.next()) |wlr_subsurface| {
if (@intToPtr(?*Subsurface, wlr_subsurface.data)) |s| s.destroy();
}
var above_it = surface.subsurfaces_above.iterator(.forward);
while (above_it.next()) |wlr_subsurface| {
if (@intToPtr(?*Subsurface, wlr_subsurface.data)) |s| s.destroy();
}
}
fn handleDestroy(listener: *wl.Listener(*wlr.Subsurface), wlr_subsurface: *wlr.Subsurface) void {
const subsurface = @fieldParentPtr(Subsurface, "subsurface_destroy", listener);
subsurface.destroy();
}
fn handleMap(listener: *wl.Listener(*wlr.Subsurface), wlr_subsurface: *wlr.Subsurface) void {
const subsurface = @fieldParentPtr(Subsurface, "map", listener);
wlr_subsurface.surface.events.commit.add(&subsurface.commit);
subsurface.parent.damageWholeOutput();
}
fn handleUnmap(listener: *wl.Listener(*wlr.Subsurface), wlr_subsurface: *wlr.Subsurface) void {
const subsurface = @fieldParentPtr(Subsurface, "unmap", listener);
subsurface.commit.link.remove();
subsurface.parent.damageWholeOutput();
}
fn handleCommit(listener: *wl.Listener(*wlr.Surface), surface: *wlr.Surface) void {
const subsurface = @fieldParentPtr(Subsurface, "commit", listener);
subsurface.parent.damageWholeOutput();
}
fn handleNewSubsurface(listener: *wl.Listener(*wlr.Subsurface), new_wlr_subsurface: *wlr.Subsurface) void {
const subsurface = @fieldParentPtr(Subsurface, "new_subsurface", listener);
Subsurface.create(new_wlr_subsurface, subsurface.parent);
}
|
source/river-0.1.0/river/Subsurface.zig
|
const std = @import("std");
const testing = std.testing;
const queen_attack = @import("queen_attack.zig");
const QueenError = queen_attack.QueenError;
test "queen with a valid position" {
const queen = try queen_attack.Queen.init(2, 2);
try testing.expectEqual(
@as(queen_attack.Queen, .{.x = 2, .y = 2}), queen);
}
test "queen must have positive row" {
const queen = queen_attack.Queen.init(-2, 2);
try testing.expectError(QueenError.InitializationFailure, queen);
}
test "queen must have row on board" {
const queen = queen_attack.Queen.init(8, 4);
try testing.expectError(QueenError.InitializationFailure, queen);
}
test "queen must have positive column" {
const queen = queen_attack.Queen.init(2, -2);
try testing.expectError(QueenError.InitializationFailure, queen);
}
test "queen must have column on board" {
const queen = queen_attack.Queen.init(4, 8);
try testing.expectError(QueenError.InitializationFailure, queen);
}
test "cannot attack" {
const white = try queen_attack.Queen.init(2, 4);
const black = try queen_attack.Queen.init(6, 6);
try testing.expect(!try white.canAttack(black));
}
test "can attack on same row" {
const white = try queen_attack.Queen.init(2, 4);
const black = try queen_attack.Queen.init(2, 6);
try testing.expect(try white.canAttack(black));
}
test "can attack on same column" {
const white = try queen_attack.Queen.init(4, 5);
const black = try queen_attack.Queen.init(2, 5);
try testing.expect(try white.canAttack(black));
}
test "can attack on first diagonal" {
const white = try queen_attack.Queen.init(2, 2);
const black = try queen_attack.Queen.init(0, 4);
try testing.expect(try white.canAttack(black));
}
test "can attack on second diagonal" {
const white = try queen_attack.Queen.init(2, 2);
const black = try queen_attack.Queen.init(3, 1);
try testing.expect(try white.canAttack(black));
}
test "can attack on third diagonal" {
const white = try queen_attack.Queen.init(2, 2);
const black = try queen_attack.Queen.init(1, 1);
try testing.expect(try white.canAttack(black));
}
test "can attack on fourth diagonal" {
const white = try queen_attack.Queen.init(1, 7);
const black = try queen_attack.Queen.init(0, 6);
try testing.expect(try white.canAttack(black));
}
|
exercises/practice/queen-attack/test_queen_attack.zig
|
const std = @import("std");
const log = @import("log.zig");
const api = @import("api.zig");
const ModSpec = struct {
name: []const u8,
version: std.SemanticVersion,
};
pub const Mod = struct {
pub const THudComponent = struct {
_cbk: fn (slot: u8, fmt: [*:0]const u8, buf: [*]u8, size: usize) callconv(.C) usize,
pub fn call(self: THudComponent, mod: []const u8, slot: u8, fmt: [*:0]const u8, buf: [*]u8, size: usize) usize {
return api.callExternal(mod, self._cbk, .{ slot, fmt, buf, size });
}
};
pub const EventHandler = struct {
_cbk: fn (data: ?*anyopaque) callconv(.C) void,
pub fn call(self: EventHandler, mod: []const u8, data: ?*anyopaque) void {
api.callExternal(mod, self._cbk, .{data});
}
};
arena: std.heap.ArenaAllocator.State,
lib: std.DynLib,
spec: ModSpec,
deps: []ModSpec,
thud_components: std.StringHashMap(THudComponent),
event_handlers: std.StringHashMap([]EventHandler),
};
var mods: std.StringHashMap(Mod) = undefined;
var allocator: std.mem.Allocator = undefined;
pub fn getMod(name: []const u8) ?Mod {
return mods.get(name);
}
pub const Iterator = struct {
it: std.StringHashMap(Mod).Iterator,
const Elem = std.meta.Tuple(&.{ []const u8, Mod });
pub fn next(self: *Iterator) ?Elem {
if (self.it.next()) |ent| {
return Elem{ ent.key_ptr.*, ent.value_ptr.* };
} else {
return null;
}
}
};
pub fn iterator() Iterator {
return .{ .it = mods.iterator() };
}
pub fn init(allocator1: std.mem.Allocator) !void {
allocator = allocator1;
var mod_list = std.ArrayList(Mod).init(allocator);
defer mod_list.deinit();
var dir = std.fs.cwd().openDir("mods", .{ .iterate = true }) catch |err| switch (err) {
error.FileNotFound, error.NotDir => {
log.info("mods directory not found; not loading any mods\n", .{});
return;
},
else => |e| return e,
};
defer dir.close();
var dir_it = dir.iterate();
while (try dir_it.next()) |ent| {
if (ent.kind != .File) continue;
const path = try std.fs.path.join(allocator, &.{ "mods", ent.name });
defer allocator.free(path);
const mod_info = loadMod(path) catch |err| {
switch (err) {
error.MissingModInfo => log.err("Missing MOD_INFO in {s}\n", .{ent.name}),
error.BadModName => log.err("Bad name in {s}\n", .{ent.name}),
error.BadModVersion => log.err("Bad version in {s}\n", .{ent.name}),
error.BadModDeps => log.err("Bad dependencies in {s}\n", .{ent.name}),
error.BadTHudComponents => log.err("Bad tHUD components in {s}\n", .{ent.name}),
error.BadEventHandlers => log.err("Bad event handlers in {s}\n", .{ent.name}),
else => |e| return e,
}
continue;
};
try mod_list.append(mod_info);
}
mods = std.StringHashMap(Mod).init(allocator);
errdefer mods.deinit();
try validateMods(mod_list.items);
}
pub fn deinit() void {
var it = mods.iterator();
while (it.next()) |kv| {
kv.value_ptr.arena.promote(allocator).deinit();
}
mods.deinit();
}
const ModInfoRaw = extern struct {
const THudComponent = extern struct {
name: ?[*:0]const u8,
cbk: ?fn (slot: u8, fmt: [*:0]const u8, buf: [*]u8, size: usize) callconv(.C) usize,
};
const EventHandler = extern struct {
name: ?[*:0]const u8,
cbk: ?fn (data: ?*anyopaque) callconv(.C) void,
};
name: ?[*:0]const u8,
version: ?[*:0]const u8,
deps: ?[*:null]?[*:0]const u8,
thud_components: ?[*:.{ .name = null, .cbk = null }]THudComponent,
event_handlers: ?[*:.{ .name = null, .cbk = null }]EventHandler,
};
fn loadMod(path: []const u8) !Mod {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
var lib = try std.DynLib.open(path);
errdefer lib.close();
// std.mem.span wants deps to be aligned correctly, so we alignCast
// this, returning an error if the alignment is incorrect
const info_raw = std.math.alignCast(
@alignOf(ModInfoRaw),
lib.lookup(*align(1) ModInfoRaw, "MOD_INFO") orelse return error.MissingModInfo,
) catch return error.MissingModInfo;
const spec = ModSpec{
.name = std.mem.span(info_raw.name) orelse return error.BadModName,
.version = std.SemanticVersion.parse(
std.mem.span(info_raw.version) orelse return error.BadModVersion,
) catch return error.BadModVersion,
};
if (spec.name.len == 0) return error.BadModName;
// Validate mod name
for (spec.name) |c| {
if (c >= 'a' and c <= 'z') continue;
if (c == '-') continue;
return error.BadModName;
}
var dep_list = std.ArrayList(ModSpec).init(arena.allocator());
for (std.mem.span(info_raw.deps) orelse return error.BadModDeps) |dep_str| {
try dep_list.append(try parseDep(std.mem.span(dep_str orelse unreachable)));
}
var thud_components = std.StringHashMap(Mod.THudComponent).init(arena.allocator());
if (info_raw.thud_components) |raw| {
var i: usize = 0;
while (raw[i].name != null or raw[i].cbk != null) : (i += 1) {
if (raw[i].name == null) return error.BadTHudComponents;
if (raw[i].cbk == null) return error.BadTHudComponents;
const name = std.mem.span(raw[i].name) orelse unreachable;
const res = try thud_components.getOrPut(name);
if (res.found_existing) {
return error.BadTHudComponents;
} else {
res.value_ptr.* = .{
._cbk = raw[i].cbk.?,
};
}
}
} else {
return error.BadTHudComponents;
}
// This is temporary so we allocate it on the normal allocator
var event_handlers_al = std.StringHashMap(std.ArrayList(Mod.EventHandler)).init(allocator);
defer {
var it = event_handlers_al.iterator();
while (it.next()) |kv| {
kv.value_ptr.deinit();
}
event_handlers_al.deinit();
}
if (info_raw.event_handlers) |raw| {
var i: usize = 0;
while (raw[i].name != null or raw[i].cbk != null) : (i += 1) {
if (raw[i].name == null) return error.BadEventHandlers;
if (raw[i].cbk == null) return error.BadEventHandlers;
const name = std.mem.span(raw[i].name) orelse unreachable;
const res = try event_handlers_al.getOrPut(name);
if (!res.found_existing) {
// These are also temporary so we allocate them on the
// normal allocator too
res.value_ptr.* = std.ArrayList(Mod.EventHandler).init(allocator);
}
try res.value_ptr.append(.{ ._cbk = raw[i].cbk.? });
}
}
// Move them into a more efficient representation where each slice
// is actually the right length
var event_handlers = std.StringHashMap([]Mod.EventHandler).init(arena.allocator());
{
var it = event_handlers_al.iterator();
while (it.next()) |kv| {
const ptr = try arena.allocator().alloc(Mod.EventHandler, kv.value_ptr.items.len);
std.mem.copy(Mod.EventHandler, ptr, kv.value_ptr.items);
kv.value_ptr.clearAndFree();
try event_handlers.put(kv.key_ptr.*, ptr);
}
}
return Mod{
.arena = arena.state,
.lib = lib,
.spec = spec,
.deps = dep_list.toOwnedSlice(),
.thud_components = thud_components,
.event_handlers = event_handlers,
};
}
fn parseDep(str: []const u8) !ModSpec {
const idx = std.mem.lastIndexOfScalar(u8, str, '@') orelse return error.BadModDeps;
return ModSpec{
.name = str[0..idx],
.version = try std.SemanticVersion.parse(str[idx + 1 ..]),
};
}
fn validateMods(mod_list: []Mod) !void {
var err = false;
for (mod_list) |mod| {
const res = try mods.getOrPut(mod.spec.name);
if (res.found_existing) {
log.err("Cannot load mod {s}; already loaded\n", .{
mod.spec.name,
});
err = true;
continue;
} else {
res.value_ptr.* = mod;
}
}
if (err) {
log.err("Error loading mods: duplicate mods\n", .{});
return error.VersionConflicts;
}
for (mod_list) |mod| {
for (mod.deps) |dep| {
if (mods.get(dep.name)) |dep_loaded| {
if (!compatibleWith(dep.version, dep_loaded.spec.version)) {
log.err("Incompatible version of dependency {s} for mod {s}\n", .{
dep.name,
mod.spec.name,
});
err = true;
}
break;
} else {
log.err("Missing dependency {s} for mod {s}\n", .{
dep.name,
mod.spec.name,
});
err = true;
}
}
}
if (err) {
log.err("Error loading mods: missing dependencies\n", .{});
return error.MissingDependencies;
}
log.info("{} mods loaded:\n", .{mods.count()});
for (mod_list) |mod| {
log.info(" {s}\n", .{mod.spec.name});
}
}
fn compatibleWith(version: std.SemanticVersion, desired: std.SemanticVersion) bool {
if (version.major != desired.major) return false;
if (version.major == 0) {
// Major version 0 does not guarantee backwards compatability
// for *any* change. Only allow the exact same version
return std.SemanticVersion.order(version, desired) == .eq;
}
// We need minor and patch (and pre) to be at *least* the desired version, so
// just order the versions, and check version is not below desired
return std.SemanticVersion.order(version, desired) != .lt;
}
|
src/mods.zig
|
pub const c = @import("c.zig");
pub const World = c.CbtWorldHandle;
pub const Shape = c.CbtShapeHandle;
pub const Body = c.CbtBodyHandle;
pub const Vector3 = c.CbtVector3;
pub const RayCastResult = c.CbtRayCastResult;
pub const Constraint = c.CbtConstraintHandle;
pub const worldCreate = c.cbtWorldCreate;
pub const worldDestroy = c.cbtWorldDestroy;
pub const worldSetGravity = c.cbtWorldSetGravity;
pub const worldGetGravity = c.cbtWorldGetGravity;
pub const worldStepSimulation = c.cbtWorldStepSimulation;
pub const worldAddBody = c.cbtWorldAddBody;
pub const worldAddConstraint = c.cbtWorldAddConstraint;
pub const worldRemoveBody = c.cbtWorldRemoveBody;
pub const worldRemoveConstraint = c.cbtWorldRemoveConstraint;
pub const worldGetNumBodies = c.cbtWorldGetNumBodies;
pub const worldGetNumConstraints = c.cbtWorldGetNumConstraints;
pub const worldGetBody = c.cbtWorldGetBody;
pub const worldGetConstraint = c.cbtWorldGetConstraint;
pub const rayTestClosest = c.cbtRayTestClosest;
pub const worldDebugSetCallbacks = c.cbtWorldDebugSetCallbacks;
pub const worldDebugDraw = c.cbtWorldDebugDraw;
pub const worldDebugDrawLine1 = c.cbtWorldDebugDrawLine1;
pub const worldDebugDrawLine2 = c.cbtWorldDebugDrawLine2;
pub const worldDebugDrawSphere = c.cbtWorldDebugDrawSphere;
pub const shapeAllocate = c.cbtShapeAllocate;
pub const shapeDeallocate = c.cbtShapeDeallocate;
pub const shapeDestroy = c.cbtShapeDestroy;
pub const shapeIsCreated = c.cbtShapeIsCreated;
pub const shapeGetType = c.cbtShapeGetType;
pub const shapeSetMargin = c.cbtShapeSetMargin;
pub const shapeGetMargin = c.cbtShapeGetMargin;
pub const shapeBoxCreate = c.cbtShapeBoxCreate;
pub const shapeBoxGetHalfExtentsWithoutMargin = c.cbtShapeBoxGetHalfExtentsWithoutMargin;
pub const shapeBoxGetHalfExtentsWithMargin = c.cbtShapeBoxGetHalfExtentsWithMargin;
pub const shapeSphereCreate = c.cbtShapeSphereCreate;
pub const shapeSphereSetUnscaledRadius = c.cbtShapeSphereSetUnscaledRadius;
pub const shapeSphereGetRadius = c.cbtShapeSphereGetRadius;
pub const shapeCapsuleCreate = c.cbtShapeCapsuleCreate;
pub const shapeCapsuleGetUpAxis = c.cbtShapeCapsuleGetUpAxis;
pub const shapeCapsuleGetHalfHeight = c.cbtShapeCapsuleGetHalfHeight;
pub const shapeCapsuleGetRadius = c.cbtShapeCapsuleGetRadius;
pub const shapeCylinderCreate = c.cbtShapeCylinderCreate;
pub const shapeCylinderGetHalfExtentsWithoutMargin = c.cbtShapeCylinderGetHalfExtentsWithoutMargin;
pub const shapeCylinderGetHalfExtentsWithMargin = c.cbtShapeCylinderGetHalfExtentsWithMargin;
pub const shapeCylinderGetUpAxis = c.cbtShapeCylinderGetUpAxis;
pub const shapeConeCreate = c.cbtShapeConeCreate;
pub const shapeConeGetRadius = c.cbtShapeConeGetRadius;
pub const shapeConeGetHeight = c.cbtShapeConeGetHeight;
pub const shapeConeGetUpAxis = c.cbtShapeConeGetUpAxis;
pub const shapeCompoundCreate = c.cbtShapeCompoundCreate;
pub const shapeCompoundAddChild = c.cbtShapeCompoundAddChild;
pub const shapeCompoundRemoveChild = c.cbtShapeCompoundRemoveChild;
pub const shapeCompoundRemoveChildByIndex = c.cbtShapeCompoundRemoveChildByIndex;
pub const shapeCompoundGetNumChilds = c.cbtShapeCompoundGetNumChilds;
pub const shapeCompoundGetChild = c.cbtShapeCompoundGetChild;
pub const shapeCompoundGetChildTransform = c.cbtShapeCompoundGetChildTransform;
pub const shapeTriMeshCreateBegin = c.cbtShapeTriMeshCreateBegin;
pub const shapeTriMeshCreateEnd = c.cbtShapeTriMeshCreateEnd;
pub const shapeTriMeshDestroy = c.cbtShapeTriMeshDestroy;
pub const shapeTriMeshAddIndexVertexArray = c.cbtShapeTriMeshAddIndexVertexArray;
pub const shapeIsPolyhedral = c.cbtShapeIsPolyhedral;
pub const shapeIsConvex2d = c.cbtShapeIsConvex2d;
pub const shapeIsConvex = c.cbtShapeIsConvex;
pub const shapeIsNonMoving = c.cbtShapeIsNonMoving;
pub const shapeIsConcave = c.cbtShapeIsConcave;
pub const shapeIsCompound = c.cbtShapeIsCompound;
pub const shapeCalculateLocalInertia = c.cbtShapeCalculateLocalInertia;
pub const shapeSetUserPointer = c.cbtShapeSetUserPointer;
pub const shapeGetUserPointer = c.cbtShapeGetUserPointer;
pub const shapeSetUserIndex = c.cbtShapeSetUserIndex;
pub const shapeGetUserIndex = c.cbtShapeGetUserIndex;
pub const bodyAllocate = c.cbtBodyAllocate;
pub const bodyAllocateBatch = c.cbtBodyAllocateBatch;
pub const bodyDeallocate = c.cbtBodyDeallocate;
pub const bodyDeallocateBatch = c.cbtBodyDeallocateBatch;
pub const bodyCreate = c.cbtBodyCreate;
pub const bodyDestroy = c.cbtBodyDestroy;
pub const bodyIsCreated = c.cbtBodyIsCreated;
pub const bodySetShape = c.cbtBodySetShape;
pub const bodyGetShape = c.cbtBodyGetShape;
pub const bodySetRestitution = c.cbtBodySetRestitution;
pub const bodySetFriction = c.cbtBodySetFriction;
pub const bodySetRollingFriction = c.cbtBodySetRollingFriction;
pub const bodySetSpinningFriction = c.cbtBodySetSpinningFriction;
pub const bodySetAnisotropicFriction = c.cbtBodySetAnisotropicFriction;
pub const bodySetContactStiffnessAndDamping = c.cbtBodySetContactStiffnessAndDamping;
pub const bodySetMassProps = c.cbtBodySetMassProps;
pub const bodySetDamping = c.cbtBodySetDamping;
pub const bodySetLinearVelocity = c.cbtBodySetLinearVelocity;
pub const bodySetAngularVelocity = c.cbtBodySetAngularVelocity;
pub const bodySetLinearFactor = c.cbtBodySetLinearFactor;
pub const bodySetAngularFactor = c.cbtBodySetAngularFactor;
pub const bodySetGravity = c.cbtBodySetGravity;
pub const bodyGetGravity = c.cbtBodyGetGravity;
pub const bodyGetNumConstraints = c.cbtBodyGetNumConstraints;
pub const bodyGetConstraint = c.cbtBodyGetConstraint;
pub const bodyApplyCentralForce = c.cbtBodyApplyCentralForce;
pub const bodyApplyCentralImpulse = c.cbtBodyApplyCentralImpulse;
pub const bodyApplyForce = c.cbtBodyApplyForce;
pub const bodyApplyImpulse = c.cbtBodyApplyImpulse;
pub const bodyApplyTorque = c.cbtBodyApplyTorque;
pub const bodyApplyTorqueImpulse = c.cbtBodyApplyTorqueImpulse;
pub const bodyGetRestitution = c.cbtBodyGetRestitution;
pub const bodyGetFriction = c.cbtBodyGetFriction;
pub const bodyGetRollingFriction = c.cbtBodyGetRollingFriction;
pub const bodyGetSpinningFriction = c.cbtBodyGetSpinningFriction;
pub const bodyGetAnisotropicFriction = c.cbtBodyGetAnisotropicFriction;
pub const bodyGetContactStiffness = c.cbtBodyGetContactStiffness;
pub const bodyGetContactDamping = c.cbtBodyGetContactDamping;
pub const bodyGetMass = c.cbtBodyGetMass;
pub const bodyGetLinearDamping = c.cbtBodyGetLinearDamping;
pub const bodyGetAngularDamping = c.cbtBodyGetAngularDamping;
pub const bodyGetLinearVelocity = c.cbtBodyGetLinearVelocity;
pub const bodyGetAngularVelocity = c.cbtBodyGetAngularVelocity;
pub const bodyGetTotalForce = c.cbtBodyGetTotalForce;
pub const bodyGetTotalTorque = c.cbtBodyGetTotalTorque;
pub const bodyIsStatic = c.cbtBodyIsStatic;
pub const bodyIsKinematic = c.cbtBodyIsKinematic;
pub const bodyIsStaticOrKinematic = c.cbtBodyIsStaticOrKinematic;
pub const bodyGetDeactivationTime = c.cbtBodyGetDeactivationTime;
pub const bodySetDeactivationTime = c.cbtBodySetDeactivationTime;
pub const bodyGetActivationState = c.cbtBodyGetActivationState;
pub const bodySetActivationState = c.cbtBodySetActivationState;
pub const bodyForceActivationState = c.cbtBodyForceActivationState;
pub const bodyIsActive = c.cbtBodyIsActive;
pub const bodyIsInWorld = c.cbtBodyIsInWorld;
pub const bodySetUserPointer = c.cbtBodySetUserPointer;
pub const bodyGetUserPointer = c.cbtBodyGetUserPointer;
pub const bodySetUserIndex = c.cbtBodySetUserIndex;
pub const bodyGetUserIndex = c.cbtBodyGetUserIndex;
pub const bodySetCenterOfMassTransform = c.cbtBodySetCenterOfMassTransform;
pub const bodyGetCenterOfMassTransform = c.cbtBodyGetCenterOfMassTransform;
pub const bodyGetCenterOfMassPosition = c.cbtBodyGetCenterOfMassPosition;
pub const bodyGetInvCenterOfMassTransform = c.cbtBodyGetInvCenterOfMassTransform;
pub const bodyGetGraphicsWorldTransform = c.cbtBodyGetGraphicsWorldTransform;
pub const conGetFixedBody = c.cbtConGetFixedBody;
pub const conAllocate = c.cbtConAllocate;
pub const conDeallocate = c.cbtConDeallocate;
pub const conDestroy = c.cbtConDestroy;
pub const conIsCreated = c.cbtConIsCreated;
pub const conGetType = c.cbtConGetType;
pub const conSetParam = c.cbtConSetParam;
pub const conGetParam = c.cbtConGetParam;
pub const conSetEnabled = c.cbtConSetEnabled;
pub const conIsEnabled = c.cbtConIsEnabled;
pub const conGetBodyA = c.cbtConGetBodyA;
pub const conGetBodyB = c.cbtConGetBodyB;
pub const conSetBreakingImpulseThreshold = c.cbtConSetBreakingImpulseThreshold;
pub const conGetBreakingImpulseThreshold = c.cbtConGetBreakingImpulseThreshold;
pub const conSetDebugDrawSize = c.cbtConSetDebugDrawSize;
pub const conGetDebugDrawSize = c.cbtConGetDebugDrawSize;
pub const conPoint2PointCreate1 = c.cbtConPoint2PointCreate1;
pub const conPoint2PointCreate2 = c.cbtConPoint2PointCreate2;
pub const conPoint2PointSetPivotA = c.cbtConPoint2PointSetPivotA;
pub const conPoint2PointSetPivotB = c.cbtConPoint2PointSetPivotB;
pub const conPoint2PointSetTau = c.cbtConPoint2PointSetTau;
pub const conPoint2PointSetDamping = c.cbtConPoint2PointSetDamping;
pub const conPoint2PointSetImpulseClamp = c.cbtConPoint2PointSetImpulseClamp;
pub const conPoint2PointGetPivotA = c.cbtConPoint2PointGetPivotA;
pub const conPoint2PointGetPivotB = c.cbtConPoint2PointGetPivotB;
pub const conHingeCreate1 = c.cbtConHingeCreate1;
pub const conHingeCreate2 = c.cbtConHingeCreate2;
pub const conHingeCreate3 = c.cbtConHingeCreate3;
pub const conHingeSetAngularOnly = c.cbtConHingeSetAngularOnly;
pub const conHingeEnableAngularMotor = c.cbtConHingeEnableAngularMotor;
pub const conHingeSetLimit = c.cbtConHingeSetLimit;
pub const conGearCreate = c.cbtConGearCreate;
pub const conGearSetAxisA = c.cbtConGearSetAxisA;
pub const conGearSetAxisB = c.cbtConGearSetAxisB;
pub const conGearSetRatio = c.cbtConGearSetRatio;
pub const conGearGetAxisA = c.cbtConGearGetAxisA;
pub const conGearGetAxisB = c.cbtConGearGetAxisB;
pub const conGearGetRatio = c.cbtConGearGetRatio;
pub const conSliderCreate1 = c.cbtConSliderCreate1;
pub const conSliderCreate2 = c.cbtConSliderCreate2;
pub const conSliderSetLinearLowerLimit = c.cbtConSliderSetLinearLowerLimit;
pub const conSliderSetLinearUpperLimit = c.cbtConSliderSetLinearUpperLimit;
pub const conSliderGetLinearLowerLimit = c.cbtConSliderGetLinearLowerLimit;
pub const conSliderGetLinearUpperLimit = c.cbtConSliderGetLinearUpperLimit;
pub const conSliderSetAngularLowerLimit = c.cbtConSliderSetAngularLowerLimit;
pub const conSliderSetAngularUpperLimit = c.cbtConSliderSetAngularUpperLimit;
pub const conSliderGetAngularLowerLimit = c.cbtConSliderGetAngularLowerLimit;
pub const conSliderGetAngularUpperLimit = c.cbtConSliderGetAngularUpperLimit;
pub const conSliderEnableLinearMotor = c.cbtConSliderEnableLinearMotor;
pub const conSliderEnableAngularMotor = c.cbtConSliderEnableAngularMotor;
pub const conSliderIsLinearMotorEnabled = c.cbtConSliderIsLinearMotorEnabled;
pub const conSliderIsAngularMotorEnabled = c.cbtConSliderIsAngularMotorEnabled;
pub const conSliderGetAngularMotor = c.cbtConSliderGetAngularMotor;
pub const conSliderGetLinearPosition = c.cbtConSliderGetLinearPosition;
pub const conSliderGetAngularPosition = c.cbtConSliderGetAngularPosition;
pub const conD6Spring2Create1 = c.cbtConD6Spring2Create1;
pub const conD6Spring2Create2 = c.cbtConD6Spring2Create2;
pub const conD6Spring2SetLinearLowerLimit = c.cbtConD6Spring2SetLinearLowerLimit;
pub const conD6Spring2SetLinearUpperLimit = c.cbtConD6Spring2SetLinearUpperLimit;
pub const conD6Spring2GetLinearLowerLimit = c.cbtConD6Spring2GetLinearLowerLimit;
pub const conD6Spring2GetLinearUpperLimit = c.cbtConD6Spring2GetLinearUpperLimit;
pub const conD6Spring2SetAngularLowerLimit = c.cbtConD6Spring2SetAngularLowerLimit;
pub const conD6Spring2SetAngularUpperLimit = c.cbtConD6Spring2SetAngularUpperLimit;
pub const conD6Spring2GetAngularLowerLimit = c.cbtConD6Spring2GetAngularLowerLimit;
pub const conD6Spring2GetAngularUpperLimit = c.cbtConD6Spring2GetAngularUpperLimit;
pub const conConeTwistCreate1 = c.cbtConConeTwistCreate1;
pub const conConeTwistCreate2 = c.cbtConConeTwistCreate2;
pub const conConeTwistSetLimit = c.cbtConConeTwistSetLimit;
// 4x3 tranform matrix manipulation
const zp = @import("../../zplay.zig");
const Mat4 = zp.deps.alg.Mat4;
pub const Transform = [4]Vector3;
pub fn convertMat4ToTransform(m: Mat4) Transform {
return [4][3]f32{
[3]f32{ m.data[0][0], m.data[0][1], m.data[0][2] },
[3]f32{ m.data[1][0], m.data[1][1], m.data[1][2] },
[3]f32{ m.data[2][0], m.data[2][1], m.data[2][2] },
[3]f32{ m.data[3][0], m.data[3][1], m.data[3][2] },
};
}
pub fn convertTransformToMat4(a: Transform) Mat4 {
return Mat4{
.data = .{
.{ a[0][0], a[0][1], a[0][2], 0 },
.{ a[1][0], a[1][1], a[1][2], 0 },
.{ a[2][0], a[2][1], a[2][2], 0 },
.{ a[3][0], a[3][1], a[3][2], 1 },
},
};
}
|
src/deps/bullet/bullet.zig
|
const std = @import("std");
const assert = std.debug.assert;
pub const Bool32 = i32;
pub const CString = [*:0]const u8;
pub const MutCString = [*:0]u8;
pub const FileType = enum(c_int) {
invalid,
gltf,
glb,
};
pub const Result = enum(c_int) {
success,
data_too_short,
unknown_format,
invalid_json,
invalid_gltf,
invalid_options,
file_not_found,
io_error,
out_of_memory,
legacy_gltf,
};
pub const MemoryOptions = extern struct {
alloc: ?fn (user: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque = null,
free: ?fn (user: ?*anyopaque, ptr: ?*anyopaque) callconv(.C) void = null,
user_data: ?*anyopaque = null,
};
pub const FileOptions = extern struct {
read: ?fn (
*const MemoryOptions,
*const FileOptions,
CString,
*usize,
*?*anyopaque,
) callconv(.C) Result = null,
release: ?fn (*const MemoryOptions, *const FileOptions, ?*anyopaque) callconv(.C) void = null,
user_data: ?*anyopaque = null,
};
pub const Options = extern struct {
file_type: FileType = .invalid,
json_token_count: usize = 0,
memory: MemoryOptions = .{},
file: FileOptions = .{},
};
pub const BufferViewType = enum(c_int) {
invalid,
indices,
vertices,
};
pub const AttributeType = enum(c_int) {
invalid,
position,
normal,
tangent,
texcoord,
color,
joints,
weights,
};
pub const ComponentType = enum(c_int) {
invalid,
r_8,
r_8u,
r_16,
r_16u,
r_32u,
r_32f,
};
pub const Type = enum(c_int) {
invalid,
scalar,
vec2,
vec3,
vec4,
mat2,
mat3,
mat4,
pub fn numComponents(dtype: Type) usize {
return switch (dtype) {
.vec2 => 2,
.vec3 => 3,
.vec4 => 4,
.mat2 => 4,
.mat3 => 9,
.mat4 => 16,
else => 1,
};
}
};
pub const PrimitiveType = enum(c_int) {
points,
lines,
line_loop,
line_strip,
triangles,
triangle_strip,
triangle_fan,
};
pub const AlphaMode = enum(c_int) {
@"opaque",
mask,
blend,
};
pub const AnimationPathType = enum(c_int) {
invalid,
translation,
rotation,
scale,
weights,
};
pub const InterpolationType = enum(c_int) {
linear,
step,
cubic_spline,
};
pub const CameraType = enum(c_int) {
invalid,
perspective,
orthographic,
};
pub const LightType = enum(c_int) {
invalid,
directional,
point,
spot,
};
pub const DataFreeMethod = enum(c_int) {
none,
file_release,
memory_free,
};
pub const MeshoptCompressionMode = enum(c_int) {
invalid,
attributes,
triangles,
indices,
};
pub const MeshoptCompressionFilter = enum(c_int) {
none,
octahedral,
quaternion,
exponential,
};
pub const Extras = extern struct {
start_offset: usize,
end_offset: usize,
};
pub const Extension = extern struct {
name: ?MutCString,
data: ?MutCString,
};
pub const Buffer = extern struct {
name: ?MutCString,
size: usize,
uri: ?MutCString,
data: ?*anyopaque, // loaded by loadBuffers()
data_free_method: DataFreeMethod,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const MeshoptCompression = extern struct {
buffer: *Buffer,
offset: usize,
size: usize,
stride: usize,
count: usize,
mode: MeshoptCompressionMode,
filter: MeshoptCompressionFilter,
};
pub const BufferView = extern struct {
name: ?MutCString,
buffer: *Buffer,
offset: usize,
size: usize,
stride: usize, // 0 == automatically determined by accessor
view_type: BufferViewType,
data: ?*anyopaque, // overrides buffer.data if present, filled by extensions
has_meshopt_compression: Bool32,
meshopt_compression: MeshoptCompression,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const AccessorSparse = extern struct {
count: usize,
indices_buffer_view: *BufferView,
indices_byte_offset: usize,
indices_component_type: ComponentType,
values_buffer_view: *BufferView,
values_byte_offset: usize,
extras: Extras,
indices_extras: Extras,
values_extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
indices_extensions_count: usize,
indices_extensions: ?[*]Extension,
values_extensions_count: usize,
values_extensions: ?[*]Extension,
};
pub const Accessor = extern struct {
name: ?MutCString,
component_type: ComponentType,
normalized: Bool32,
type: Type,
offset: usize,
count: usize,
stride: usize,
buffer_view: ?*BufferView,
has_min: Bool32,
min: [16]f32,
has_max: Bool32,
max: [16]f32,
is_sparse: Bool32,
sparse: AccessorSparse,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
pub fn unpackFloatsCount(accessor: Accessor) usize {
return cgltf_accessor_unpack_floats(&accessor, null, 0);
}
pub fn unpackFloats(accessor: Accessor, out: []f32) []f32 {
const count = cgltf_accessor_unpack_floats(&accessor, out.ptr, out.len);
return out[0..count];
}
pub fn readFloat(accessor: Accessor, index: usize, out: []f32) bool {
assert(out.len == accessor.type.numComponents());
const result = cgltf_accessor_read_float(&accessor, index, out.ptr, out.len);
return result != 0;
}
pub fn readUint(accessor: Accessor, index: usize, out: []u32) bool {
assert(out.len == accessor.type.numComponents());
const result = cgltf_accessor_read_uint(&accessor, index, out.ptr, out.len);
return result != 0;
}
pub fn readIndex(accessor: Accessor, index: usize) usize {
return cgltf_accessor_read_index(&accessor, index);
}
};
pub const Attribute = extern struct {
name: ?MutCString,
type: AttributeType,
index: i32,
data: *Accessor,
};
pub const Image = extern struct {
name: ?MutCString,
uri: ?MutCString,
buffer_view: ?*BufferView,
mime_type: ?MutCString,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Sampler = extern struct {
uri: ?MutCString,
mag_filter: i32,
min_filter: i32,
wrap_s: i32,
wrap_t: i32,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Texture = extern struct {
name: ?MutCString,
image: ?*Image,
sampler: ?*Sampler,
has_basisu: Bool32,
basisu_image: ?*Image,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const TextureTransform = extern struct {
offset: [2]f32,
rotation: f32,
scale: [2]f32,
has_texcoord: Bool32,
texcoord: i32,
};
pub const TextureView = extern struct {
texture: ?*Texture,
texcoord: i32,
scale: f32,
has_transform: Bool32,
transform: TextureTransform,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const PbrMetallicRoughness = extern struct {
base_color_texture: TextureView,
metallic_roughness_texture: TextureView,
base_color_factor: [4]f32,
metallic_factor: f32,
roughness_factor: f32,
extras: Extras,
};
pub const PbrSpecularGlossiness = extern struct {
diffuse_texture: TextureView,
specular_glossiness_texture: TextureView,
diffuse_factor: [4]f32,
specular_factor: [3]f32,
glossiness_factor: f32,
};
pub const Clearcoat = extern struct {
clearcoat_texture: TextureView,
clearcoat_roughness_texture: TextureView,
clearcoat_normal_texture: TextureView,
clearcoat_factor: f32,
clearcoat_roughness_factor: f32,
};
pub const Transmission = extern struct {
transmission_texture: TextureView,
transmission_factor: f32,
};
pub const Ior = extern struct {
ior: f32,
};
pub const Specular = extern struct {
specular_texture: TextureView,
specular_color_texture: TextureView,
specular_color_factor: [3]f32,
specular_factor: f32,
};
pub const Volume = extern struct {
thickness_texture: TextureView,
thickness_factor: f32,
attentuation_color: [3]f32,
attentuation_distance: f32,
};
pub const Sheen = extern struct {
sheen_color_texture: TextureView,
sheen_color_factor: [3]f32,
sheen_roughness_texture: TextureView,
sheen_roughness_factor: f32,
};
pub const EmissiveStrength = extern struct {
emissive_strength: f32,
};
pub const Iridescence = extern struct {
iridescence_factor: f32,
iridescence_texture: TextureView,
iridescence_ior: f32,
iridescence_thickness_min: f32,
iridescence_thickness_max: f32,
iridescence_thickness_texture: TextureView,
};
pub const Material = extern struct {
name: ?MutCString,
has_pbr_metallic_roughness: Bool32,
has_pbr_specular_glossiness: Bool32,
has_clearcoat: Bool32,
has_transmission: Bool32,
has_volume: Bool32,
has_ior: Bool32,
has_specular: Bool32,
has_sheen: Bool32,
has_emissive_strength: Bool32,
has_iridescence: Bool32,
pbr_metallic_roughness: PbrMetallicRoughness,
pbr_specular_glossiness: PbrSpecularGlossiness,
clearcoat: Clearcoat,
ior: Ior,
specular: Specular,
sheen: Sheen,
transmission: Transmission,
volume: Volume,
emissive_strength: EmissiveStrength,
iridescence: Iridescence,
normal_texture: TextureView,
occlusion_texture: TextureView,
emissive_texture: TextureView,
emissive_factor: [3]f32,
alpha_mode: AlphaMode,
alpha_cutoff: f32,
double_sided: Bool32,
unlit: Bool32,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const MaterialMapping = extern struct {
variant: usize,
material: ?*Material,
extras: Extras,
};
pub const MorphTarget = extern struct {
attributes: ?[*]Attribute,
attributes_count: usize,
};
pub const DracoMeshCompression = extern struct {
buffer_view: ?*BufferView,
attributes: ?[*]Attribute,
attributes_count: usize,
};
pub const MeshGpuInstancing = extern struct {
buffer_view: ?*BufferView,
attributes: ?[*]Attribute,
attributes_count: usize,
};
pub const Primitive = extern struct {
type: PrimitiveType,
indices: ?*Accessor,
material: ?*Material,
attributes: [*]Attribute, // required
attributes_count: usize,
targets: ?[*]MorphTarget,
targets_count: usize,
extras: Extras,
has_draco_mesh_compression: Bool32,
draco_mesh_compression: DracoMeshCompression,
mappings: ?[*]MaterialMapping,
mappings_count: usize,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Mesh = extern struct {
name: ?MutCString,
primitives: [*]Primitive, // required
primitives_count: usize,
weights: ?[*]f32,
weights_count: usize,
target_names: ?[*]MutCString,
target_names_count: usize,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Skin = extern struct {
name: ?MutCString,
joints: [*]*Node, // required
joints_count: usize,
skeleton: ?*Node,
inverse_bind_matrices: ?*Accessor,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const CameraPerspective = extern struct {
has_aspect_ratio: Bool32,
aspect_ratio: f32,
yfov: f32,
has_zfar: Bool32,
zfar: f32,
znear: f32,
extras: Extras,
};
pub const CameraOrthographic = extern struct {
xmag: f32,
ymag: f32,
zfar: f32,
znear: f32,
extras: Extras,
};
pub const Camera = extern struct {
name: ?MutCString,
type: CameraType,
data: extern union {
perspective: CameraPerspective,
orthographic: CameraOrthographic,
},
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Light = extern struct {
name: ?MutCString,
color: [3]f32,
intensity: f32,
type: LightType,
range: f32,
spot_inner_cone_angle: f32,
spot_outer_cone_angle: f32,
extras: Extras,
};
pub const Node = extern struct {
name: ?MutCString,
parent: ?*Node,
children: ?[*]*Node,
children_count: usize,
skin: ?*Skin,
mesh: ?*Mesh,
camera: ?*Camera,
light: ?*Light,
weights: [*]f32,
weights_count: usize,
has_translation: Bool32,
has_rotation: Bool32,
has_scale: Bool32,
has_matrix: Bool32,
translation: [3]f32,
rotation: [4]f32,
scale: [3]f32,
matrix: [16]f32,
extras: Extras,
has_mesh_gpu_instancing: Bool32,
mesh_gpu_instancing: MeshGpuInstancing,
extensions_count: usize,
extensions: ?[*]Extension,
pub fn transformLocal(node: Node) [16]f32 {
var transform: [16]f32 = undefined;
cgltf_node_transform_local(&node, &transform);
return transform;
}
pub fn transformWorld(node: Node) [16]f32 {
var transform: [16]f32 = undefined;
cgltf_node_transform_world(&node, &transform);
return transform;
}
};
pub const Scene = extern struct {
name: ?MutCString,
nodes: ?[*]*Node,
nodes_count: usize,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const AnimationSampler = extern struct {
input: *Accessor, // required
output: *Accessor, // required
interpolation: InterpolationType,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const AnimationChannel = extern struct {
sampler: *AnimationSampler, // required
target_node: ?*Node,
target_path: AnimationPathType,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Animation = extern struct {
name: ?MutCString,
samplers: [*]AnimationSampler, // required
samplers_count: usize,
channels: [*]AnimationChannel, // required
channels_count: usize,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const MaterialVariant = extern struct {
name: ?MutCString,
extras: Extras,
};
pub const Asset = extern struct {
copyright: ?MutCString,
generator: ?MutCString,
version: ?MutCString,
min_version: ?MutCString,
extras: Extras,
extensions_count: usize,
extensions: ?[*]Extension,
};
pub const Data = extern struct {
file_type: FileType,
file_data: ?*anyopaque,
asset: Asset,
meshes: ?[*]Mesh,
meshes_count: usize,
materials: ?[*]Material,
materials_count: usize,
accessors: ?[*]Accessor,
accessors_count: usize,
buffer_views: ?[*]BufferView,
buffer_views_count: usize,
buffers: ?[*]Buffer,
buffers_count: usize,
images: ?[*]Image,
images_count: usize,
textures: ?[*]Texture,
textures_count: usize,
samplers: ?[*]Sampler,
samplers_count: usize,
skins: ?[*]Skin,
skins_count: usize,
cameras: ?[*]Camera,
cameras_count: usize,
lights: ?[*]Light,
lights_count: usize,
nodes: ?[*]Node,
nodes_count: usize,
scenes: ?[*]Scene,
scenes_count: usize,
scene: ?*Scene,
animations: ?[*]Animation,
animations_count: usize,
variants: ?[*]MaterialVariant,
variants_count: usize,
extras: Extras,
data_extensions_count: usize,
data_extensions: ?[*]Extension,
extensions_used: ?[*]MutCString,
extensions_used_count: usize,
extensions_required: ?[*]MutCString,
extensions_required_count: usize,
json: ?CString,
json_size: usize,
bin: ?*const anyopaque,
bin_size: usize,
memory: MemoryOptions,
file: FileOptions,
};
pub const Error = error{
DataTooShort,
UnknownFormat,
InvalidJson,
InvalidGltf,
InvalidOptions,
FileNotFound,
IoError,
OutOfMemory,
LegacyGltf,
};
pub fn parse(options: Options, data: []const u8) Error!*Data {
var out_data: ?*Data = null;
const result = cgltf_parse(&options, data.ptr, data.len, &out_data);
return try resultToError(result, out_data);
}
pub fn parseFile(options: Options, path: [*:0]const u8) Error!*Data {
var out_data: ?*Data = null;
const result = cgltf_parse_file(&options, path, &out_data);
return try resultToError(result, out_data);
}
pub fn loadBuffers(options: Options, data: *Data, gltf_path: [*:0]const u8) Error!void {
const result = cgltf_load_buffers(&options, data, gltf_path);
_ = try resultToError(result, data);
}
pub fn free(data: *Data) void {
cgltf_free(data);
}
pub fn validate(data: *Data) Result {
return cgltf_validate(data);
}
extern fn cgltf_parse(
options: ?*const Options,
data: ?*const anyopaque,
size: usize,
out_data: ?*?*Data,
) Result;
extern fn cgltf_parse_file(
options: ?*const Options,
path: ?[*:0]const u8,
out_data: ?*?*Data,
) Result;
extern fn cgltf_load_buffers(
options: ?*const Options,
data: ?*Data,
gltf_path: ?[*:0]const u8,
) Result;
extern fn cgltf_load_buffer_base64(
options: ?*const Options,
size: usize,
base64: ?[*:0]const u8,
out_data: ?*?*Data,
) Result;
extern fn cgltf_decode_string(string: ?MutCString) usize;
extern fn cgltf_decode_uri(string: ?MutCString) usize;
extern fn cgltf_free(data: ?*Data) void;
extern fn cgltf_validate(data: ?*Data) Result;
extern fn cgltf_node_transform_local(node: ?*const Node, out_matrix: ?*[16]f32) void;
extern fn cgltf_node_transform_world(node: ?*const Node, out_matrix: ?*[16]f32) void;
extern fn cgltf_accessor_read_float(
accessor: ?*const Accessor,
index: usize,
out: ?[*]f32,
element_size: usize,
) Bool32;
extern fn cgltf_accessor_read_uint(
accessor: ?*const Accessor,
index: usize,
out: ?[*]u32,
element_size: usize,
) Bool32;
extern fn cgltf_accessor_read_index(
accessor: ?*const Accessor,
index: usize,
) usize;
extern fn cgltf_accessor_unpack_floats(
accessor: ?*const Accessor,
out: ?[*]f32,
float_count: usize,
) usize;
extern fn cgltf_copy_extras_json(
data: ?*const Data,
extras: ?*const Extras,
dest: ?[*]u8,
dest_size: ?*usize,
) Result;
fn resultToError(result: Result, data: ?*Data) Error!*Data {
if (result == .success)
return data.?;
return switch (result) {
.data_too_short => error.DataTooShort,
.unknown_format => error.UnknownFormat,
.invalid_json => error.InvalidJson,
.invalid_gltf => error.InvalidGltf,
.invalid_options => error.InvalidOptions,
.file_not_found => error.FileNotFound,
.io_error => error.IoError,
.out_of_memory => error.OutOfMemory,
.legacy_gltf => error.LegacyGltf,
else => unreachable,
};
}
|
modules/graphics/vendored/zmesh/src/zcgltf.zig
|
const aoc = @import("../aoc.zig");
const std = @import("std");
const Part1 = struct {
vowels: u8 = 0,
last: u8 = 0,
has_double: bool = false,
dead: bool = false,
fn feed(self: *Part1, c: u8) void {
if (self.dead) {
return;
}
switch (c) {
'a', 'e', 'i', 'o', 'u' => self.vowels += 1,
'b' => if (self.last == 'a') {self.dead = true; return;},
'd' => if (self.last == 'c') {self.dead = true; return;},
'q' => if (self.last == 'p') {self.dead = true; return;},
'y' => if (self.last == 'x') {self.dead = true; return;},
else => {},
}
if (c == self.last) {
self.has_double = true;
}
self.last = c;
}
fn eval(self: *Part1) u16 {
return if (!self.dead and self.vowels >= 3 and self.has_double) 1 else 0;
}
};
const Part2 = struct {
const LetterPairs = std.AutoHashMap([2]u8, usize);
last0: u8 = 0,
last1: u8 = 0,
saw_pair: bool = false,
saw_repeat: bool = false,
pairs: LetterPairs,
fn init(allocator: std.mem.Allocator) Part2 {
return Part2 { .pairs = LetterPairs.init(allocator) };
}
fn deinit(self: *Part2) void {
self.pairs.deinit();
}
fn feed(self: *Part2, c: u8, idx: usize) !void {
if (c == self.last0) {
self.saw_repeat = true;
}
if (!self.saw_pair) {
const pair = [2]u8{ self.last1, c };
if (self.pairs.get(pair)) |inserted_idx| {
if (idx - inserted_idx > 1) {
self.saw_pair = true;
}
}
else {
_ = try self.pairs.put(pair, idx);
}
}
self.last0 = self.last1;
self.last1 = c;
}
fn eval(self: *Part2) u16 {
return if (self.saw_pair and self.saw_repeat) 1 else 0;
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var nice1: u16 = 0;
var nice2: u16 = 0;
while (problem.line()) |line| {
var part1 = Part1 {};
var part2 = Part2.init(problem.allocator);
defer part2.deinit();
for (line) |c, idx| {
part1.feed(c);
try part2.feed(c, idx);
}
nice1 += part1.eval();
nice2 += part2.eval();
}
return problem.solution(nice1, nice2);
}
|
src/main/zig/2015/day05.zig
|
const std = @import("std");
const math = std.math;
// Struct Declarations
pub const Color = struct {
r: f32 = 0.0,
g: f32 = 0.0,
b: f32 = 0.0,
a: f32 = 0.0,
pub inline fn c(r: f32, g: f32, b: f32, a: f32) Color {
return Color{ .r = r, .g = g, .b = b, .a = a };
}
};
pub const Vec2 = struct {
x: f32 = 0.0,
y: f32 = 0.0,
pub inline fn c(x: f32, y: f32) Vec2 {
return Vec2{ .x = x, .y = y };
}
};
pub const Vec3 = struct {
x: f32 = 0.0,
y: f32 = 0.0,
z: f32 = 0.0,
pub inline fn c(x: f32, y: f32, z: f32) Vec3 {
return Vec3{ .x = x, .y = y, .z = z };
}
pub inline fn neg(v: *Vec3) Vec3 {
return Vec3{ .x = -v.x, .y = -v.y, .z = -v.z };
}
};
pub const Vec4 = struct {
x: f32 = 0.0,
y: f32 = 0.0,
z: f32 = 0.0,
w: f32 = 0.0,
pub inline fn c(x: f32, y: f32, z: f32, w: f32) Vec3 {
return Vec3{ .x = x, .y = y, .z = z, .w = w };
}
};
pub const Plane = struct {
n: Vec3 = .{},
d: f32 = .{},
pub inline fn c(nx: f32, ny: f32, nz: f32, d: f32) Plane {
return Plane{
.n = Vec3_normalize(Vec3.c(nx, ny, nz)),
.d = d,
};
}
};
pub const Vertex = struct {
pos: Vec3 = .{},
uv: Vec2 = .{},
w: f32 = 1.0,
pub inline fn c(pos: Vec3, uv: Vec2) Vertex {
return Vertex{
.pos = pos,
.uv = uv,
};
}
};
pub const Transform = struct {
position: Vec3 = .{},
rotation: Vec3 = .{}, // TODO(Samuel): Change to rotor
scale: Vec3 = .{
.x = 1,
.y = 1,
.z = 1,
},
};
pub fn lerp(a: f32, b: f32, t: f32) f32 {
const result = (1 - t) * a + t * b;
return result;
}
pub fn Color_lerp(ca: Color, cb: Color, t: f32) Color {
const result = Color{
.r = lerp(ca.r, cb.r, t),
.g = lerp(ca.g, cb.g, t),
.b = lerp(ca.b, cb.b, t),
.a = lerp(ca.a, cb.a, t),
};
return result;
}
pub fn Vec3_add(va: Vec3, vb: Vec3) Vec3 {
const result = Vec3{
.x = va.x + vb.x,
.y = va.y + vb.y,
.z = va.z + vb.z,
};
return result;
}
pub fn Vec3_sub(va: Vec3, vb: Vec3) Vec3 {
const result = Vec3{
.x = va.x - vb.x,
.y = va.y - vb.y,
.z = va.z - vb.z,
};
return result;
}
pub fn Vec3_mul(va: Vec3, vb: Vec3) Vec3 {
const result = Vec3{
.x = va.x * vb.x,
.y = va.y * vb.y,
.z = va.z * vb.z,
};
return result;
}
pub fn Vec3_div(va: Vec3, vb: Vec3) Vec3 {
const result = Vec3{
.x = va.x / vb.x,
.y = va.y / vb.y,
.z = va.z / vb.z,
};
return result;
}
pub fn Vec3_add_F(v: Vec3, f: f32) Vec3 {
const result = Vec3{
.x = v.x + f,
.y = v.y + f,
.z = v.z + f,
};
return result;
}
pub fn Vec3_sub_F(v: Vec3, f: f32) Vec3 {
const result = Vec3{
.x = v.x - f,
.y = v.y - f,
.z = v.z - f,
};
return result;
}
pub fn Vec3_mul_F(v: Vec3, f: f32) Vec3 {
const result = Vec3{
.x = v.x * f,
.y = v.y * f,
.z = v.z * f,
};
return result;
}
pub fn Vec3_div_F(v: Vec3, f: f32) Vec3 {
const result = Vec3{
.x = v.x / f,
.y = v.y / f,
.z = v.z / f,
};
return result;
}
pub fn Vec3_dot(va: Vec3, vb: Vec3) f32 {
const result = va.x * vb.x + va.y * vb.y + va.z * vb.z;
return result;
}
pub fn Vec3_cross(va: Vec3, vb: Vec3) Vec3 {
var result = Vec3{};
result.x = va.y * vb.z - va.z * vb.y;
result.y = va.z * vb.x - va.x * vb.z;
result.z = va.x * vb.y - va.y * vb.x;
return result;
}
pub fn Vec3_len(v: Vec3) f32 {
const result = math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
return result;
}
pub fn Vec3_normalize(v: Vec3) Vec3 {
const l = Vec3_len(v);
const result = if (l > 0.001) Vec3_div_F(v, Vec3_len(v)) else Vec3{};
return result;
}
pub fn lineIntersectPlane(l_origin: Vec3, l_dir: Vec3, plane: Plane) ?Vec3 {
var result: ?Vec3 = null;
const denom = Vec3_dot(plane.n, l_dir);
const epslon = 0.001;
if (denom > epslon or denom < -epslon) {
const t = (-plane.d - Vec3_dot(plane.n, l_origin)) / denom;
const hit_pos = Vec3_add(l_origin, Vec3_mul_F(l_dir, t));
result = hit_pos;
}
return result;
}
pub fn lineIntersectPlaneT(l_origin: Vec3, l_end: Vec3, plane: Plane, t: *f32) Vec3 {
const ad = Vec3_dot(l_origin, plane.n);
const bd = Vec3_dot(l_end, plane.n);
t.* = (-plane.d - ad) / (bd - ad);
const line_start_to_end = Vec3_sub(l_end, l_origin);
const line_to_intersect = Vec3_mul_F(line_start_to_end, t.*);
return Vec3_add(l_origin, line_to_intersect);
}
pub const Bivec3 = struct {
xy: f32,
xz: f32,
yz: f32,
};
pub inline fn edgeFunction(xa: f32, ya: f32, xb: f32, yb: f32, xc: f32, yc: f32) f32 {
return (xc - xa) * (yb - ya) - (yc - ya) * (xb - xa);
}
pub inline fn edgeFunctionI(xa: i32, ya: i32, xb: i32, yb: i32, xc: i32, yc: i32) i32 {
const result = (xc -% xa) *% (yb -% ya) -% (yc -% ya) *% (xb -% xa);
return result;
}
pub fn interpolateVertexAttr(va: Vertex, vb: Vertex, vc: Vertex, pos: Vec3) Vertex {
var result = Vertex{
.pos = pos,
};
const area = edgeFunction(va.pos.x, va.pos.y, vb.pos.x, vb.pos.y, vc.pos.x, vc.pos.y);
var w0 = edgeFunction(vb.pos.x, vb.pos.y, vc.pos.x, vc.pos.y, pos.x, pos.y) / area;
var w1 = edgeFunction(vc.pos.x, vc.pos.y, va.pos.x, va.pos.y, pos.x, pos.y) / area;
var w2 = 1.0 - w0 - w1;
if (false) {
w0 /= va.w;
w1 /= va.w;
w2 /= va.w;
const w_sum = w0 + w1 + w2;
w0 /= w_sum;
w1 /= w_sum;
w2 /= w_sum;
}
result.color.r = w0 * va.color.r + w1 * vb.color.r + w2 * vc.color.r;
result.color.g = w0 * va.color.g + w1 * vb.color.g + w2 * vc.color.g;
result.color.b = w0 * va.color.b + w1 * vb.color.b + w2 * vc.color.b;
result.color.a = w0 * va.color.a + w1 * vb.color.a + w2 * vc.color.a;
return result;
}
pub fn baricentricCoordinates(a: anytype, b: anytype, c: anytype, p: anytype) Vec3 {
if (@TypeOf(a) != Vec3 and @TypeOf(a) != Vec2) @compileError("");
if (@TypeOf(b) != Vec3 and @TypeOf(b) != Vec2) @compileError("");
if (@TypeOf(c) != Vec3 and @TypeOf(c) != Vec2) @compileError("");
if (@TypeOf(p) != Vec3 and @TypeOf(p) != Vec2) @compileError("");
const area = edgeFunction(a.x, a.y, b.x, b.y, c.x, c.y);
var w0 = edgeFunction(b.x, b.y, c.x, c.y, p.x, p.y) / area;
var w1 = edgeFunction(c.x, c.y, a.x, a.y, p.x, p.y) / area;
var w2 = 1.0 - w0 - w1;
return Vec3.c(w0, w1, w2);
}
pub fn rotateVectorOnY(v: Vec3, angle: f32) Vec3 {
const result = Vec3{
.x = v.x * @cos(angle) + v.z * @sin(angle),
.y = v.y,
.z = -v.x * @sin(angle) + v.z * @cos(angle),
};
return result;
}
pub fn rotateVectorOnX(v: Vec3, angle: f32) Vec3 {
const result = Vec3{
.x = v.x,
.y = v.y * @cos(angle) + v.z * @sin(angle),
.z = -v.y * @sin(angle) + v.z * @cos(angle),
};
return result;
}
pub fn rotateVectorOnZ(v: Vec3, angle: f32) Vec3 {
const result = Vec3{
.x = v.x * @cos(angle) + v.y * @sin(angle),
.y = -v.x * @sin(angle) + v.y * @cos(angle),
.z = v.z,
};
return result;
}
pub fn perspectiveMatrix(near: f32, far: f32, fov: f32, height_to_width_ratio: f32) [4][4]f32 {
const S: f32 = 1 / (std.math.tan(fov * 3.1415926535 / 90.0));
var matrix = [4][4]f32{
.{ -S * height_to_width_ratio, 0, 0, 0 },
.{ 0, -S, 0, 0 },
.{ 0, 0, -(far / (far - near)), -(far * near / (far - near)) },
.{ 0, 0, -1, 0 },
};
return matrix;
}
pub fn eulerAnglesToDirVector(v: Vec3) Vec3 {
var result = Vec3{
.x = -@sin(v.y),
.y = -@sin(v.x) * @cos(v.y),
.z = @cos(v.x) * @cos(v.y),
};
return result;
}
pub fn sphericalToCartesian(r: f32, z: f32, a: f32) Vec3 {
const result = Vec3{
.x = r * @sin(z) * @cos(a),
.y = r * @sin(z) * @sin(a),
.z = r * @cos(z),
};
return result;
}
|
src/vector_math.zig
|
//--------------------------------------------------------------------------------
// Section: Types (1)
//--------------------------------------------------------------------------------
const IID_IGraphicsCaptureItemInterop_Value = Guid.initString("3628e81b-3cac-4c60-b7f4-23ce0e0c3356");
pub const IID_IGraphicsCaptureItemInterop = &IID_IGraphicsCaptureItemInterop_Value;
pub const IGraphicsCaptureItemInterop = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateForWindow: fn(
self: *const IGraphicsCaptureItemInterop,
window: ?HWND,
riid: ?*const Guid,
result: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateForMonitor: fn(
self: *const IGraphicsCaptureItemInterop,
monitor: ?HMONITOR,
riid: ?*const Guid,
result: ?*?*anyopaque,
) 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 IGraphicsCaptureItemInterop_CreateForWindow(self: *const T, window: ?HWND, riid: ?*const Guid, result: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IGraphicsCaptureItemInterop.VTable, self.vtable).CreateForWindow(@ptrCast(*const IGraphicsCaptureItemInterop, self), window, riid, result);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGraphicsCaptureItemInterop_CreateForMonitor(self: *const T, monitor: ?HMONITOR, riid: ?*const Guid, result: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IGraphicsCaptureItemInterop.VTable, self.vtable).CreateForMonitor(@ptrCast(*const IGraphicsCaptureItemInterop, self), monitor, riid, result);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const Guid = @import("../../../zig.zig").Guid;
const HMONITOR = @import("../../../graphics/gdi.zig").HMONITOR;
const HRESULT = @import("../../../foundation.zig").HRESULT;
const HWND = @import("../../../foundation.zig").HWND;
const IUnknown = @import("../../../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/system/win_rt/graphics/capture.zig
|
const std = @import("std");
pub const Value = union(enum) {
String: []const u8,
Integer: usize,
List: []Value,
Dictionary: []std.StringArrayHashMap(Value).Entry,
};
fn peek(r: anytype) ?u8 {
const c = r.context;
if (c.pos == c.buffer.len) {
return null;
}
return c.buffer[c.pos];
}
const max_number_length = 25;
/// Accepts a {std.io.FixedBufferStream} and a {std.mem.Allocator} to parse a Bencode stream.
/// @see https://en.wikipedia.org/wiki/Bencode
pub fn parse(r: anytype, alloc: *std.mem.Allocator) anyerror!Value {
const pc = peek(r) orelse return error.EndOfStream;
if (pc >= '0' and pc <= '9') return Value{ .String = try parseString(r, alloc), };
const t = try r.readByte();
if (t == 'i') return Value{ .Integer = try parseInteger(r, alloc), };
if (t == 'l') return Value{ .List = try parseList(r, alloc), };
if (t == 'd') return Value{ .Dictionary = try parseDict(r, alloc), };
return error.BencodeBadDelimiter;
}
fn parseString(r: anytype, alloc: *std.mem.Allocator) ![]const u8 {
const str = try r.readUntilDelimiterAlloc(alloc, ':', max_number_length);
const len = try std.fmt.parseInt(usize, str, 10);
var buf = try alloc.alloc(u8, len);
const l = try r.read(buf);
return buf[0..l];
}
fn parseInteger(r: anytype, alloc: *std.mem.Allocator) !usize {
const str = try r.readUntilDelimiterAlloc(alloc, 'e', max_number_length);
const x = try std.fmt.parseInt(usize, str, 10);
return x;
}
fn parseList(r: anytype, alloc: *std.mem.Allocator) ![]Value {
var list = std.ArrayList(Value).init(alloc);
while (true) {
if (peek(r)) |c| {
if (c == 'e') {
_ = try r.readByte();
return list.toOwnedSlice();
}
const v = try parse(r, alloc);
try list.append(v);
}
else {
break;
}
}
return error.EndOfStream;
}
fn parseDict(r: anytype, alloc: *std.mem.Allocator) ![]std.StringArrayHashMap(Value).Entry {
var map = std.StringArrayHashMap(Value).init(alloc);
while (true) {
if (peek(r)) |c| {
if (c == 'e') {
_ = try r.readByte();
return map.items();
}
const k = try parseString(r, alloc);
const v = try parse(r, alloc);
try map.put(k, v);
}
else {
break;
}
}
return error.EndOfStream;
}
|
src/lib.zig
|
const std = @import("std");
//--------------------------------------------------------------------------------------------------
const Vec2 = struct {
x: u16,
y: u16,
pub fn init(x: u16, y: u16) Vec2 {
return Vec2{ .x = x, .y = y };
}
};
//--------------------------------------------------------------------------------------------------
pub fn print(points: []Vec2) void {
var x: u32 = std.math.maxInt(u32);
var y: u32 = std.math.maxInt(u32);
const row_len: u32 = 40; // TODO: could find the max x value
for (points) |point| {
// Avoid printing the duplicates
if (point.x == x and point.y == y) {
continue;
}
// Fill in empty cells between points
if (x == std.math.maxInt(u32)) {
x = 0;
y = 0;
}
const y_diff = point.y - y;
if (y_diff != 0) {
// Complete remainder of row
var i: usize = 0;
while (i < (row_len - x)) : (i += 1) {
std.debug.print(".", .{});
}
std.debug.print("\n", .{});
// Draw complete rows
i = 1; // +1 because we 'completed' the remainer of one row elsewhere
while (i < y_diff) : (i += 1) {
var j: usize = 0;
while (j < row_len) : (j += 1) {
std.debug.print(".", .{});
}
std.debug.print("\n", .{});
}
// Pad last row until x
i = 0;
while (i < point.x) : (i += 1) {
std.debug.print(".", .{});
}
//
} else {
// Pad row
const x_diff = point.x - x;
var i: usize = 1; // +1 because we want to leave space for the point itself
while (i < x_diff) : (i += 1) {
std.debug.print(".", .{});
}
}
// Ready to draw the new point
x = point.x;
y = point.y;
std.debug.print("#", .{});
}
std.debug.print("\n", .{});
}
//--------------------------------------------------------------------------------------------------
pub fn count_unique(points: []Vec2) u32 {
var count: u32 = 0;
var i: usize = 0;
while (i < points.len) : (i += 1) {
var j: usize = i + 1;
const unique: bool = while (j < points.len) : (j += 1) {
if (points[i].x == points[j].x and points[i].y == points[j].y) {
break false;
}
} else true;
if (unique) {
count += 1;
}
}
return count;
}
//--------------------------------------------------------------------------------------------------
pub fn sort_pred(comptime T: type) fn (void, T, T) bool {
const impl = struct {
fn inner(context: void, a: T, b: T) bool {
_ = context;
if (a.y == b.y) {
return a.x < b.x;
} else {
return a.y < b.y;
}
}
};
return impl.inner;
}
//--------------------------------------------------------------------------------------------------
pub fn main() anyerror!void {
const file = std.fs.cwd().openFile("data/day13_input.txt", .{}) catch |err| label: {
std.debug.print("unable to open file: {e}\n", .{err});
const stderr = std.io.getStdErr();
break :label stderr;
};
defer file.close();
var points: [877]Vec2 = undefined;
var point_count: usize = 0;
var folds: [12]Vec2 = undefined;
var fold_count: usize = 0;
{
var reader = std.io.bufferedReader(file.reader());
var istream = reader.reader();
var buf: [16]u8 = undefined;
while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
if (line.len == 0) {
continue;
}
const fold_prefix = "fold along ";
const flen = fold_prefix.len;
if (line.len > flen and std.mem.eql(u8, line[0..flen], fold_prefix)) {
var x: u16 = 0;
var y: u16 = 0;
if (std.mem.eql(u8, line[flen .. flen + 1], "x")) {
x = std.fmt.parseInt(u16, line[flen + 2 ..], 10) catch unreachable;
} else {
y = std.fmt.parseInt(u16, line[flen + 2 ..], 10) catch unreachable;
}
folds[fold_count] = Vec2.init(x, y);
fold_count += 1;
} else {
var it = std.mem.tokenize(u8, line, ",");
const x = std.fmt.parseInt(u16, it.next().?, 10) catch unreachable;
const y = std.fmt.parseInt(u16, it.next().?, 10) catch unreachable;
points[point_count] = Vec2.init(x, y);
point_count += 1;
}
}
}
// Perform folds
for (folds) |fold| {
for (points) |*point| {
if (fold.x != 0) {
if (point.x > fold.x) {
point.x = fold.x - (point.x - fold.x);
}
} else {
if (point.y > fold.y) {
point.y = fold.y - (point.y - fold.y);
}
}
}
const unique = count_unique(points[0..point_count]);
std.log.info("Unique: {d}", .{unique});
}
std.sort.sort(Vec2, points[0..point_count], {}, comptime sort_pred(Vec2));
print(points[0..point_count]);
//std.log.info("points: {d}", .{points});
}
//--------------------------------------------------------------------------------------------------
|
src/day13.zig
|
const std = @import("std");
const warn = std.debug.warn;
const c = @cImport({
@cInclude("GL/gl3w.h");
@cInclude("GLFW/glfw3.h");
});
usingnamespace @import("shader");
pub fn main() !u8 {
if (c.glfwInit() == 0) {
warn("failed to initialize c.glfw\n", .{});
return 255;
}
c.glfwWindowHint(c.GLFW_SAMPLES, 4);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 3);
c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
var _window: ?*c.GLFWwindow = undefined;
_window = c.glfwCreateWindow(1024, 768, "Tutorial 01", null, null).?;
if (_window == null) {
warn("failed to open a window", .{});
c.glfwTerminate();
return 255;
}
var window = _window.?;
c.glfwMakeContextCurrent(window);
// c.glewExperimental = 1;
// if (c.glewInit() != c.GLEW_OK) {
if (c.gl3wInit() != 0) {
warn("failed to initialize gl3w\n", .{});
return 255;
}
if (c.gl3wIsSupported(3, 3) == 0) {
warn("OpenGL 3.3 not supported\n", .{});
return 255;
}
c.glfwSetInputMode(window, c.GLFW_STICKY_KEYS, c.GL_TRUE);
c.glClearColor(0.0, 0.0, 0.4, 0.0);
var vertexArrayId: c.GLuint = undefined;
c.glGenVertexArrays(1, &vertexArrayId);
c.glBindVertexArray(vertexArrayId);
var programId = try loadShaders("src/SimpleVertexShader.vertexshader", "src/SimpleFragmentShader.fragmentshader");
const vertexBufferData = [_]c.GLfloat{
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
0.0, 1.0, 0.0,
};
var vertexBuffer: c.GLuint = undefined;
c.glGenBuffers(1, &vertexBuffer);
c.glBindBuffer(c.GL_ARRAY_BUFFER, vertexBuffer);
c.glBufferData(c.GL_ARRAY_BUFFER, @sizeOf(@TypeOf(vertexBufferData)), &vertexBufferData, c.GL_STATIC_DRAW);
var do_quit = false;
while (!do_quit) {
c.glClear(c.GL_COLOR_BUFFER_BIT);
c.glUseProgram(programId);
c.glEnableVertexAttribArray(0);
c.glBindBuffer(c.GL_ARRAY_BUFFER, vertexBuffer);
c.glVertexAttribPointer(0, // attribute 0. No particular reason for 0, but must match the layout in the shader
3, // size
c.GL_FLOAT, // type
c.GL_FALSE, // normalized?
0, // stride
null // array buffer offset
);
c.glDrawArrays(c.GL_TRIANGLES, 0, 3);
c.glDisableVertexAttribArray(0);
c.glfwSwapBuffers(window);
c.glfwPollEvents();
do_quit = c.glfwGetKey(window, c.GLFW_KEY_ESCAPE) == c.GLFW_PRESS and
c.glfwWindowShouldClose(window) == 0;
}
return 0;
}
|
02/src/main.zig
|
const std = @import("std");
const fmod = @import("fmod.zig");
const testing = std.testing;
fn test_fmodq(a: f128, b: f128, exp: f128) !void {
const res = fmod.fmodq(a, b);
try testing.expect(exp == res);
}
fn test_fmodq_nans() !void {
try testing.expect(std.math.isNan(fmod.fmodq(1.0, std.math.nan(f128))));
try testing.expect(std.math.isNan(fmod.fmodq(1.0, -std.math.nan(f128))));
try testing.expect(std.math.isNan(fmod.fmodq(std.math.nan(f128), 1.0)));
try testing.expect(std.math.isNan(fmod.fmodq(-std.math.nan(f128), 1.0)));
}
fn test_fmodq_infs() !void {
try testing.expect(fmod.fmodq(1.0, std.math.inf(f128)) == 1.0);
try testing.expect(fmod.fmodq(1.0, -std.math.inf(f128)) == 1.0);
try testing.expect(std.math.isNan(fmod.fmodq(std.math.inf(f128), 1.0)));
try testing.expect(std.math.isNan(fmod.fmodq(-std.math.inf(f128), 1.0)));
}
test "fmodq" {
try test_fmodq(6.8, 4.0, 2.8);
try test_fmodq(6.8, -4.0, 2.8);
try test_fmodq(-6.8, 4.0, -2.8);
try test_fmodq(-6.8, -4.0, -2.8);
try test_fmodq(3.0, 2.0, 1.0);
try test_fmodq(-5.0, 3.0, -2.0);
try test_fmodq(3.0, 2.0, 1.0);
try test_fmodq(1.0, 2.0, 1.0);
try test_fmodq(0.0, 1.0, 0.0);
try test_fmodq(-0.0, 1.0, -0.0);
try test_fmodq(7046119.0, 5558362.0, 1487757.0);
try test_fmodq(9010357.0, 1957236.0, 1181413.0);
try test_fmodq(5192296858534827628530496329220095, 10.0, 5.0);
try test_fmodq(5192296858534827628530496329220095, 922337203681230954775807, 220474884073715748246157);
// Denormals
const a1: f128 = 0xedcb34a235253948765432134674p-16494;
const b1: f128 = 0x5d2e38791cfbc0737402da5a9518p-16494;
const exp1: f128 = 0x336ec3affb2db8618e4e7d5e1c44p-16494;
try test_fmodq(a1, b1, exp1);
const a2: f128 = 0x0.7654_3210_fdec_ba98_7654_3210_fdecp-16382;
const b2: f128 = 0x0.0012_fdac_bdef_1234_fdec_3222_1111p-16382;
const exp2: f128 = 0x0.0001_aecd_9d66_4a6e_67b7_d7d0_a901p-16382;
try test_fmodq(a2, b2, exp2);
try test_fmodq_nans();
try test_fmodq_infs();
}
|
lib/compiler_rt/fmodq_test.zig
|
const Zld = @This();
const std = @import("std");
const assert = std.debug.assert;
const leb = std.leb;
const mem = std.mem;
const meta = std.meta;
const fs = std.fs;
const macho = std.macho;
const math = std.math;
const log = std.log.scoped(.zld);
const aarch64 = @import("../../codegen/aarch64.zig");
const reloc = @import("reloc.zig");
const Allocator = mem.Allocator;
const Archive = @import("Archive.zig");
const CodeSignature = @import("CodeSignature.zig");
const Dylib = @import("Dylib.zig");
const Object = @import("Object.zig");
const Symbol = @import("Symbol.zig");
const Trie = @import("Trie.zig");
usingnamespace @import("commands.zig");
usingnamespace @import("bind.zig");
allocator: *Allocator,
arch: ?std.Target.Cpu.Arch = null,
page_size: ?u16 = null,
file: ?fs.File = null,
out_path: ?[]const u8 = null,
// TODO these args will become obselete once Zld is coalesced with incremental
// linker.
stack_size: u64 = 0,
objects: std.ArrayListUnmanaged(*Object) = .{},
archives: std.ArrayListUnmanaged(*Archive) = .{},
dylibs: std.ArrayListUnmanaged(*Dylib) = .{},
load_commands: std.ArrayListUnmanaged(LoadCommand) = .{},
pagezero_segment_cmd_index: ?u16 = null,
text_segment_cmd_index: ?u16 = null,
data_const_segment_cmd_index: ?u16 = null,
data_segment_cmd_index: ?u16 = null,
linkedit_segment_cmd_index: ?u16 = null,
dyld_info_cmd_index: ?u16 = null,
symtab_cmd_index: ?u16 = null,
dysymtab_cmd_index: ?u16 = null,
dylinker_cmd_index: ?u16 = null,
libsystem_cmd_index: ?u16 = null,
data_in_code_cmd_index: ?u16 = null,
function_starts_cmd_index: ?u16 = null,
main_cmd_index: ?u16 = null,
version_min_cmd_index: ?u16 = null,
source_version_cmd_index: ?u16 = null,
uuid_cmd_index: ?u16 = null,
code_signature_cmd_index: ?u16 = null,
// __TEXT segment sections
text_section_index: ?u16 = null,
stubs_section_index: ?u16 = null,
stub_helper_section_index: ?u16 = null,
text_const_section_index: ?u16 = null,
cstring_section_index: ?u16 = null,
ustring_section_index: ?u16 = null,
// __DATA_CONST segment sections
got_section_index: ?u16 = null,
mod_init_func_section_index: ?u16 = null,
mod_term_func_section_index: ?u16 = null,
data_const_section_index: ?u16 = null,
// __DATA segment sections
tlv_section_index: ?u16 = null,
tlv_data_section_index: ?u16 = null,
tlv_bss_section_index: ?u16 = null,
la_symbol_ptr_section_index: ?u16 = null,
data_section_index: ?u16 = null,
bss_section_index: ?u16 = null,
common_section_index: ?u16 = null,
globals: std.StringArrayHashMapUnmanaged(*Symbol) = .{},
imports: std.StringArrayHashMapUnmanaged(*Symbol) = .{},
unresolved: std.StringArrayHashMapUnmanaged(*Symbol) = .{},
strtab: std.ArrayListUnmanaged(u8) = .{},
strtab_dir: std.StringHashMapUnmanaged(u32) = .{},
threadlocal_offsets: std.ArrayListUnmanaged(TlvOffset) = .{}, // TODO merge with Symbol abstraction
local_rebases: std.ArrayListUnmanaged(Pointer) = .{},
stubs: std.ArrayListUnmanaged(*Symbol) = .{},
got_entries: std.ArrayListUnmanaged(*Symbol) = .{},
stub_helper_stubs_start_off: ?u64 = null,
mappings: std.AutoHashMapUnmanaged(MappingKey, SectionMapping) = .{},
unhandled_sections: std.AutoHashMapUnmanaged(MappingKey, u0) = .{},
const TlvOffset = struct {
source_addr: u64,
offset: u64,
fn cmp(context: void, a: TlvOffset, b: TlvOffset) bool {
return a.source_addr < b.source_addr;
}
};
const MappingKey = struct {
object_id: u16,
source_sect_id: u16,
};
pub const SectionMapping = struct {
source_sect_id: u16,
target_seg_id: u16,
target_sect_id: u16,
offset: u32,
};
/// Default path to dyld
const DEFAULT_DYLD_PATH: [*:0]const u8 = "/usr/lib/dyld";
const LIB_SYSTEM_NAME: [*:0]const u8 = "System";
/// TODO this should be inferred from included libSystem.tbd or similar.
const LIB_SYSTEM_PATH: [*:0]const u8 = "/usr/lib/libSystem.B.dylib";
pub fn init(allocator: *Allocator) Zld {
return .{ .allocator = allocator };
}
pub fn deinit(self: *Zld) void {
self.threadlocal_offsets.deinit(self.allocator);
self.local_rebases.deinit(self.allocator);
self.stubs.deinit(self.allocator);
self.got_entries.deinit(self.allocator);
for (self.load_commands.items) |*lc| {
lc.deinit(self.allocator);
}
self.load_commands.deinit(self.allocator);
for (self.objects.items) |object| {
object.deinit();
self.allocator.destroy(object);
}
self.objects.deinit(self.allocator);
for (self.archives.items) |archive| {
archive.deinit();
self.allocator.destroy(archive);
}
self.archives.deinit(self.allocator);
for (self.dylibs.items) |dylib| {
dylib.deinit();
self.allocator.destroy(dylib);
}
self.dylibs.deinit(self.allocator);
self.mappings.deinit(self.allocator);
self.unhandled_sections.deinit(self.allocator);
self.globals.deinit(self.allocator);
self.imports.deinit(self.allocator);
self.unresolved.deinit(self.allocator);
self.strtab.deinit(self.allocator);
{
var it = self.strtab_dir.iterator();
while (it.next()) |entry| {
self.allocator.free(entry.key);
}
}
self.strtab_dir.deinit(self.allocator);
}
pub fn closeFiles(self: Zld) void {
for (self.objects.items) |object| {
object.closeFile();
}
for (self.archives.items) |archive| {
archive.closeFile();
}
if (self.file) |f| f.close();
}
const LinkArgs = struct {
shared_libs: []const []const u8,
rpaths: []const []const u8,
};
pub fn link(self: *Zld, files: []const []const u8, out_path: []const u8, args: LinkArgs) !void {
if (files.len == 0) return error.NoInputFiles;
if (out_path.len == 0) return error.EmptyOutputPath;
if (self.arch == null) {
// Try inferring the arch from the object files.
self.arch = blk: {
const file = try fs.cwd().openFile(files[0], .{});
defer file.close();
var reader = file.reader();
const header = try reader.readStruct(macho.mach_header_64);
const arch: std.Target.Cpu.Arch = switch (header.cputype) {
macho.CPU_TYPE_X86_64 => .x86_64,
macho.CPU_TYPE_ARM64 => .aarch64,
else => |value| {
log.err("unsupported cpu architecture 0x{x}", .{value});
return error.UnsupportedCpuArchitecture;
},
};
break :blk arch;
};
}
self.page_size = switch (self.arch.?) {
.aarch64 => 0x4000,
.x86_64 => 0x1000,
else => unreachable,
};
self.out_path = out_path;
self.file = try fs.cwd().createFile(out_path, .{
.truncate = true,
.read = true,
.mode = if (std.Target.current.os.tag == .windows) 0 else 0o777,
});
try self.populateMetadata();
try self.addRpaths(args.rpaths);
try self.parseInputFiles(files);
try self.parseDylibs(args.shared_libs);
try self.resolveSymbols();
try self.resolveStubsAndGotEntries();
try self.updateMetadata();
try self.sortSections();
try self.allocateTextSegment();
try self.allocateDataConstSegment();
try self.allocateDataSegment();
self.allocateLinkeditSegment();
try self.allocateSymbols();
try self.flush();
}
fn parseInputFiles(self: *Zld, files: []const []const u8) !void {
const Input = struct {
kind: enum {
object,
archive,
dylib,
},
file: fs.File,
name: []const u8,
};
var classified = std.ArrayList(Input).init(self.allocator);
defer classified.deinit();
// First, classify input files: object, archive or dylib.
for (files) |file_name| {
const file = try fs.cwd().openFile(file_name, .{});
const full_path = full_path: {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const path = try std.fs.realpath(file_name, &buffer);
break :full_path try self.allocator.dupe(u8, path);
};
try_object: {
const header = try file.reader().readStruct(macho.mach_header_64);
if (header.filetype != macho.MH_OBJECT) {
try file.seekTo(0);
break :try_object;
}
try file.seekTo(0);
try classified.append(.{
.kind = .object,
.file = file,
.name = full_path,
});
continue;
}
try_archive: {
const magic = try file.reader().readBytesNoEof(Archive.SARMAG);
if (!mem.eql(u8, &magic, Archive.ARMAG)) {
try file.seekTo(0);
break :try_archive;
}
try file.seekTo(0);
try classified.append(.{
.kind = .archive,
.file = file,
.name = full_path,
});
continue;
}
try_dylib: {
const header = try file.reader().readStruct(macho.mach_header_64);
if (header.filetype != macho.MH_DYLIB) {
try file.seekTo(0);
break :try_dylib;
}
try file.seekTo(0);
try classified.append(.{
.kind = .dylib,
.file = file,
.name = full_path,
});
continue;
}
log.debug("unexpected input file of unknown type '{s}'", .{file_name});
}
// Based on our classification, proceed with parsing.
for (classified.items) |input| {
switch (input.kind) {
.object => {
const object = try self.allocator.create(Object);
errdefer self.allocator.destroy(object);
object.* = Object.init(self.allocator);
object.arch = self.arch.?;
object.name = input.name;
object.file = input.file;
try object.parse();
try self.objects.append(self.allocator, object);
},
.archive => {
const archive = try self.allocator.create(Archive);
errdefer self.allocator.destroy(archive);
archive.* = Archive.init(self.allocator);
archive.arch = self.arch.?;
archive.name = input.name;
archive.file = input.file;
try archive.parse();
try self.archives.append(self.allocator, archive);
},
.dylib => {
const dylib = try self.allocator.create(Dylib);
errdefer self.allocator.destroy(dylib);
dylib.* = Dylib.init(self.allocator);
dylib.arch = self.arch.?;
dylib.name = input.name;
dylib.file = input.file;
const ordinal = @intCast(u16, self.dylibs.items.len);
dylib.ordinal = ordinal + 2; // TODO +2 since 1 is reserved for libSystem
// TODO Defer parsing of the dylibs until they are actually needed
try dylib.parse();
try self.dylibs.append(self.allocator, dylib);
// Add LC_LOAD_DYLIB command
const dylib_id = dylib.id orelse unreachable;
var dylib_cmd = try createLoadDylibCommand(
self.allocator,
dylib_id.name,
dylib_id.timestamp,
dylib_id.current_version,
dylib_id.compatibility_version,
);
errdefer dylib_cmd.deinit(self.allocator);
try self.load_commands.append(self.allocator, .{ .Dylib = dylib_cmd });
},
}
}
}
fn parseDylibs(self: *Zld, shared_libs: []const []const u8) !void {
for (shared_libs) |lib| {
const dylib = try self.allocator.create(Dylib);
errdefer self.allocator.destroy(dylib);
dylib.* = Dylib.init(self.allocator);
dylib.arch = self.arch.?;
dylib.name = try self.allocator.dupe(u8, lib);
dylib.file = try fs.cwd().openFile(lib, .{});
const ordinal = @intCast(u16, self.dylibs.items.len);
dylib.ordinal = ordinal + 2; // TODO +2 since 1 is reserved for libSystem
// TODO Defer parsing of the dylibs until they are actually needed
try dylib.parse();
try self.dylibs.append(self.allocator, dylib);
// Add LC_LOAD_DYLIB command
const dylib_id = dylib.id orelse unreachable;
var dylib_cmd = try createLoadDylibCommand(
self.allocator,
dylib_id.name,
dylib_id.timestamp,
dylib_id.current_version,
dylib_id.compatibility_version,
);
errdefer dylib_cmd.deinit(self.allocator);
try self.load_commands.append(self.allocator, .{ .Dylib = dylib_cmd });
}
}
fn mapAndUpdateSections(
self: *Zld,
object_id: u16,
source_sect_id: u16,
target_seg_id: u16,
target_sect_id: u16,
) !void {
const object = self.objects.items[object_id];
const source_seg = object.load_commands.items[object.segment_cmd_index.?].Segment;
const source_sect = source_seg.sections.items[source_sect_id];
const target_seg = &self.load_commands.items[target_seg_id].Segment;
const target_sect = &target_seg.sections.items[target_sect_id];
const alignment = try math.powi(u32, 2, target_sect.@"align");
const offset = mem.alignForwardGeneric(u64, target_sect.size, alignment);
const size = mem.alignForwardGeneric(u64, source_sect.size, alignment);
const key = MappingKey{
.object_id = object_id,
.source_sect_id = source_sect_id,
};
try self.mappings.putNoClobber(self.allocator, key, .{
.source_sect_id = source_sect_id,
.target_seg_id = target_seg_id,
.target_sect_id = target_sect_id,
.offset = @intCast(u32, offset),
});
log.debug("{s}: {s},{s} mapped to {s},{s} from 0x{x} to 0x{x}", .{
object.name,
parseName(&source_sect.segname),
parseName(&source_sect.sectname),
parseName(&target_sect.segname),
parseName(&target_sect.sectname),
offset,
offset + size,
});
target_sect.size = offset + size;
}
fn updateMetadata(self: *Zld) !void {
for (self.objects.items) |object, id| {
const object_id = @intCast(u16, id);
const object_seg = object.load_commands.items[object.segment_cmd_index.?].Segment;
const text_seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const data_const_seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const data_seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
// Create missing metadata
for (object_seg.sections.items) |source_sect, sect_id| {
if (sect_id == object.text_section_index.?) continue;
const segname = parseName(&source_sect.segname);
const sectname = parseName(&source_sect.sectname);
const flags = source_sect.flags;
switch (flags) {
macho.S_REGULAR, macho.S_4BYTE_LITERALS, macho.S_8BYTE_LITERALS, macho.S_16BYTE_LITERALS => {
if (mem.eql(u8, segname, "__TEXT")) {
if (mem.eql(u8, sectname, "__ustring")) {
if (self.ustring_section_index != null) continue;
self.ustring_section_index = @intCast(u16, text_seg.sections.items.len);
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__ustring"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
} else {
if (self.text_const_section_index != null) continue;
self.text_const_section_index = @intCast(u16, text_seg.sections.items.len);
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__const"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
} else if (mem.eql(u8, segname, "__DATA")) {
if (!mem.eql(u8, sectname, "__const")) continue;
if (self.data_const_section_index != null) continue;
self.data_const_section_index = @intCast(u16, data_const_seg.sections.items.len);
try data_const_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__const"),
.segname = makeStaticString("__DATA_CONST"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
},
macho.S_CSTRING_LITERALS => {
if (!mem.eql(u8, segname, "__TEXT")) continue;
if (self.cstring_section_index != null) continue;
self.cstring_section_index = @intCast(u16, text_seg.sections.items.len);
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__cstring"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_CSTRING_LITERALS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
macho.S_MOD_INIT_FUNC_POINTERS => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (self.mod_init_func_section_index != null) continue;
self.mod_init_func_section_index = @intCast(u16, data_const_seg.sections.items.len);
try data_const_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__mod_init_func"),
.segname = makeStaticString("__DATA_CONST"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_MOD_INIT_FUNC_POINTERS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
macho.S_MOD_TERM_FUNC_POINTERS => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (self.mod_term_func_section_index != null) continue;
self.mod_term_func_section_index = @intCast(u16, data_const_seg.sections.items.len);
try data_const_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__mod_term_func"),
.segname = makeStaticString("__DATA_CONST"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_MOD_TERM_FUNC_POINTERS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
macho.S_ZEROFILL => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (mem.eql(u8, sectname, "__common")) {
if (self.common_section_index != null) continue;
self.common_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__common"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_ZEROFILL,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
} else {
if (self.bss_section_index != null) continue;
self.bss_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__bss"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_ZEROFILL,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
},
macho.S_THREAD_LOCAL_VARIABLES => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (self.tlv_section_index != null) continue;
self.tlv_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__thread_vars"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_THREAD_LOCAL_VARIABLES,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
macho.S_THREAD_LOCAL_REGULAR => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (self.tlv_data_section_index != null) continue;
self.tlv_data_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__thread_data"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_THREAD_LOCAL_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
macho.S_THREAD_LOCAL_ZEROFILL => {
if (!mem.eql(u8, segname, "__DATA")) continue;
if (self.tlv_bss_section_index != null) continue;
self.tlv_bss_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__thread_bss"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 0,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_THREAD_LOCAL_ZEROFILL,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
},
else => {
log.debug("unhandled section type 0x{x} for '{s}/{s}'", .{ flags, segname, sectname });
},
}
}
// Find ideal section alignment.
for (object_seg.sections.items) |source_sect| {
if (self.getMatchingSection(source_sect)) |res| {
const target_seg = &self.load_commands.items[res.seg].Segment;
const target_sect = &target_seg.sections.items[res.sect];
target_sect.@"align" = math.max(target_sect.@"align", source_sect.@"align");
}
}
// Update section mappings
for (object_seg.sections.items) |source_sect, sect_id| {
const source_sect_id = @intCast(u16, sect_id);
if (self.getMatchingSection(source_sect)) |res| {
try self.mapAndUpdateSections(object_id, source_sect_id, res.seg, res.sect);
continue;
}
const segname = parseName(&source_sect.segname);
const sectname = parseName(&source_sect.sectname);
log.debug("section '{s}/{s}' will be unmapped", .{ segname, sectname });
try self.unhandled_sections.putNoClobber(self.allocator, .{
.object_id = object_id,
.source_sect_id = source_sect_id,
}, 0);
}
}
tlv_align: {
const has_tlv =
self.tlv_section_index != null or
self.tlv_data_section_index != null or
self.tlv_bss_section_index != null;
if (!has_tlv) break :tlv_align;
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
if (self.tlv_section_index) |index| {
const sect = &seg.sections.items[index];
sect.@"align" = 3; // __thread_vars is always 8byte aligned
}
// Apparently __tlv_data and __tlv_bss need to have matching alignment, so fix it up.
// <rdar://problem/24221680> All __thread_data and __thread_bss sections must have same alignment
// https://github.com/apple-opensource/ld64/blob/e28c028b20af187a16a7161d89e91868a450cadc/src/ld/ld.cpp#L1172
const data_align: u32 = data: {
if (self.tlv_data_section_index) |index| {
const sect = &seg.sections.items[index];
break :data sect.@"align";
}
break :tlv_align;
};
const bss_align: u32 = bss: {
if (self.tlv_bss_section_index) |index| {
const sect = &seg.sections.items[index];
break :bss sect.@"align";
}
break :tlv_align;
};
const max_align = math.max(data_align, bss_align);
if (self.tlv_data_section_index) |index| {
const sect = &seg.sections.items[index];
sect.@"align" = max_align;
}
if (self.tlv_bss_section_index) |index| {
const sect = &seg.sections.items[index];
sect.@"align" = max_align;
}
}
}
const MatchingSection = struct {
seg: u16,
sect: u16,
};
fn getMatchingSection(self: *Zld, section: macho.section_64) ?MatchingSection {
const segname = parseName(§ion.segname);
const sectname = parseName(§ion.sectname);
const res: ?MatchingSection = blk: {
switch (section.flags) {
macho.S_4BYTE_LITERALS, macho.S_8BYTE_LITERALS, macho.S_16BYTE_LITERALS => {
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_const_section_index.?,
};
},
macho.S_CSTRING_LITERALS => {
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.cstring_section_index.?,
};
},
macho.S_MOD_INIT_FUNC_POINTERS => {
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.mod_init_func_section_index.?,
};
},
macho.S_MOD_TERM_FUNC_POINTERS => {
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.mod_term_func_section_index.?,
};
},
macho.S_ZEROFILL => {
if (mem.eql(u8, sectname, "__common")) {
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.common_section_index.?,
};
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.bss_section_index.?,
};
},
macho.S_THREAD_LOCAL_VARIABLES => {
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_section_index.?,
};
},
macho.S_THREAD_LOCAL_REGULAR => {
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_data_section_index.?,
};
},
macho.S_THREAD_LOCAL_ZEROFILL => {
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_bss_section_index.?,
};
},
macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS => {
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_section_index.?,
};
},
macho.S_REGULAR => {
if (mem.eql(u8, segname, "__TEXT")) {
if (mem.eql(u8, sectname, "__ustring")) {
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.ustring_section_index.?,
};
} else {
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_const_section_index.?,
};
}
} else if (mem.eql(u8, segname, "__DATA")) {
if (mem.eql(u8, sectname, "__data")) {
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.data_section_index.?,
};
} else if (mem.eql(u8, sectname, "__const")) {
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.data_const_section_index.?,
};
}
}
break :blk null;
},
else => {
break :blk null;
},
}
};
return res;
}
fn sortSections(self: *Zld) !void {
var text_index_mapping = std.AutoHashMap(u16, u16).init(self.allocator);
defer text_index_mapping.deinit();
var data_const_index_mapping = std.AutoHashMap(u16, u16).init(self.allocator);
defer data_const_index_mapping.deinit();
var data_index_mapping = std.AutoHashMap(u16, u16).init(self.allocator);
defer data_index_mapping.deinit();
{
// __TEXT segment
const seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
var sections = seg.sections.toOwnedSlice(self.allocator);
defer self.allocator.free(sections);
try seg.sections.ensureCapacity(self.allocator, sections.len);
const indices = &[_]*?u16{
&self.text_section_index,
&self.stubs_section_index,
&self.stub_helper_section_index,
&self.text_const_section_index,
&self.cstring_section_index,
&self.ustring_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try text_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
{
// __DATA_CONST segment
const seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
var sections = seg.sections.toOwnedSlice(self.allocator);
defer self.allocator.free(sections);
try seg.sections.ensureCapacity(self.allocator, sections.len);
const indices = &[_]*?u16{
&self.got_section_index,
&self.mod_init_func_section_index,
&self.mod_term_func_section_index,
&self.data_const_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try data_const_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
{
// __DATA segment
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
var sections = seg.sections.toOwnedSlice(self.allocator);
defer self.allocator.free(sections);
try seg.sections.ensureCapacity(self.allocator, sections.len);
// __DATA segment
const indices = &[_]*?u16{
&self.la_symbol_ptr_section_index,
&self.data_section_index,
&self.tlv_section_index,
&self.tlv_data_section_index,
&self.tlv_bss_section_index,
&self.bss_section_index,
&self.common_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try data_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
var it = self.mappings.iterator();
while (it.next()) |entry| {
const mapping = &entry.value;
if (self.text_segment_cmd_index.? == mapping.target_seg_id) {
const new_index = text_index_mapping.get(mapping.target_sect_id) orelse unreachable;
mapping.target_sect_id = new_index;
} else if (self.data_const_segment_cmd_index.? == mapping.target_seg_id) {
const new_index = data_const_index_mapping.get(mapping.target_sect_id) orelse unreachable;
mapping.target_sect_id = new_index;
} else if (self.data_segment_cmd_index.? == mapping.target_seg_id) {
const new_index = data_index_mapping.get(mapping.target_sect_id) orelse unreachable;
mapping.target_sect_id = new_index;
} else unreachable;
}
}
fn allocateTextSegment(self: *Zld) !void {
const seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const nstubs = @intCast(u32, self.stubs.items.len);
const base_vmaddr = self.load_commands.items[self.pagezero_segment_cmd_index.?].Segment.inner.vmsize;
seg.inner.fileoff = 0;
seg.inner.vmaddr = base_vmaddr;
// Set stubs and stub_helper sizes
const stubs = &seg.sections.items[self.stubs_section_index.?];
const stub_helper = &seg.sections.items[self.stub_helper_section_index.?];
stubs.size += nstubs * stubs.reserved2;
const stub_size: u4 = switch (self.arch.?) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
stub_helper.size += nstubs * stub_size;
var sizeofcmds: u64 = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
try self.allocateSegment(self.text_segment_cmd_index.?, @sizeOf(macho.mach_header_64) + sizeofcmds);
// Shift all sections to the back to minimize jump size between __TEXT and __DATA segments.
var min_alignment: u32 = 0;
for (seg.sections.items) |sect| {
const alignment = try math.powi(u32, 2, sect.@"align");
min_alignment = math.max(min_alignment, alignment);
}
assert(min_alignment > 0);
const last_sect_idx = seg.sections.items.len - 1;
const last_sect = seg.sections.items[last_sect_idx];
const shift: u32 = blk: {
const diff = seg.inner.filesize - last_sect.offset - last_sect.size;
const factor = @divTrunc(diff, min_alignment);
break :blk @intCast(u32, factor * min_alignment);
};
if (shift > 0) {
for (seg.sections.items) |*sect| {
sect.offset += shift;
sect.addr += shift;
}
}
}
fn allocateDataConstSegment(self: *Zld) !void {
const seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const nentries = @intCast(u32, self.got_entries.items.len);
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
seg.inner.fileoff = text_seg.inner.fileoff + text_seg.inner.filesize;
seg.inner.vmaddr = text_seg.inner.vmaddr + text_seg.inner.vmsize;
// Set got size
const got = &seg.sections.items[self.got_section_index.?];
got.size += nentries * @sizeOf(u64);
try self.allocateSegment(self.data_const_segment_cmd_index.?, 0);
}
fn allocateDataSegment(self: *Zld) !void {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const nstubs = @intCast(u32, self.stubs.items.len);
const data_const_seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
seg.inner.fileoff = data_const_seg.inner.fileoff + data_const_seg.inner.filesize;
seg.inner.vmaddr = data_const_seg.inner.vmaddr + data_const_seg.inner.vmsize;
// Set la_symbol_ptr and data size
const la_symbol_ptr = &seg.sections.items[self.la_symbol_ptr_section_index.?];
const data = &seg.sections.items[self.data_section_index.?];
la_symbol_ptr.size += nstubs * @sizeOf(u64);
data.size += @sizeOf(u64); // We need at least 8bytes for address of dyld_stub_binder
try self.allocateSegment(self.data_segment_cmd_index.?, 0);
}
fn allocateLinkeditSegment(self: *Zld) void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const data_seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
seg.inner.fileoff = data_seg.inner.fileoff + data_seg.inner.filesize;
seg.inner.vmaddr = data_seg.inner.vmaddr + data_seg.inner.vmsize;
}
fn allocateSegment(self: *Zld, index: u16, offset: u64) !void {
const base_vmaddr = self.load_commands.items[self.pagezero_segment_cmd_index.?].Segment.inner.vmsize;
const seg = &self.load_commands.items[index].Segment;
// Allocate the sections according to their alignment at the beginning of the segment.
var start: u64 = offset;
for (seg.sections.items) |*sect| {
const alignment = try math.powi(u32, 2, sect.@"align");
const start_aligned = mem.alignForwardGeneric(u64, start, alignment);
const end_aligned = mem.alignForwardGeneric(u64, start_aligned + sect.size, alignment);
sect.offset = @intCast(u32, seg.inner.fileoff + start_aligned);
sect.addr = seg.inner.vmaddr + start_aligned;
start = end_aligned;
}
const seg_size_aligned = mem.alignForwardGeneric(u64, start, self.page_size.?);
seg.inner.filesize = seg_size_aligned;
seg.inner.vmsize = seg_size_aligned;
}
fn allocateSymbols(self: *Zld) !void {
for (self.objects.items) |object, object_id| {
for (object.symbols.items) |sym| {
const reg = sym.cast(Symbol.Regular) orelse continue;
// TODO I am more and more convinced we should store the mapping as part of the Object struct.
const target_mapping = self.mappings.get(.{
.object_id = @intCast(u16, object_id),
.source_sect_id = reg.section,
}) orelse {
if (self.unhandled_sections.get(.{
.object_id = @intCast(u16, object_id),
.source_sect_id = reg.section,
}) != null) continue;
log.err("section not mapped for symbol '{s}'", .{sym.name});
return error.SectionNotMappedForSymbol;
};
const source_seg = object.load_commands.items[object.segment_cmd_index.?].Segment;
const source_sect = source_seg.sections.items[reg.section];
const target_seg = self.load_commands.items[target_mapping.target_seg_id].Segment;
const target_sect = target_seg.sections.items[target_mapping.target_sect_id];
const target_addr = target_sect.addr + target_mapping.offset;
const address = reg.address - source_sect.addr + target_addr;
log.debug("resolving symbol '{s}' at 0x{x}", .{ sym.name, address });
// TODO there might be a more generic way of doing this.
var section: u8 = 0;
for (self.load_commands.items) |cmd, cmd_id| {
if (cmd != .Segment) break;
if (cmd_id == target_mapping.target_seg_id) {
section += @intCast(u8, target_mapping.target_sect_id) + 1;
break;
}
section += @intCast(u8, cmd.Segment.sections.items.len);
}
reg.address = address;
reg.section = section;
}
}
}
fn writeStubHelperCommon(self: *Zld) !void {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = &text_segment.sections.items[self.stub_helper_section_index.?];
const data_const_segment = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const got = &data_const_segment.sections.items[self.got_section_index.?];
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const data = &data_segment.sections.items[self.data_section_index.?];
const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?];
self.stub_helper_stubs_start_off = blk: {
switch (self.arch.?) {
.x86_64 => {
const code_size = 15;
var code: [code_size]u8 = undefined;
// lea %r11, [rip + disp]
code[0] = 0x4c;
code[1] = 0x8d;
code[2] = 0x1d;
{
const target_addr = data.addr + data.size - @sizeOf(u64);
const displacement = try math.cast(u32, target_addr - stub_helper.addr - 7);
mem.writeIntLittle(u32, code[3..7], displacement);
}
// push %r11
code[7] = 0x41;
code[8] = 0x53;
// jmp [rip + disp]
code[9] = 0xff;
code[10] = 0x25;
{
const dyld_stub_binder = self.imports.get("dyld_stub_binder").?;
const addr = (got.addr + dyld_stub_binder.got_index.? * @sizeOf(u64));
const displacement = try math.cast(u32, addr - stub_helper.addr - code_size);
mem.writeIntLittle(u32, code[11..], displacement);
}
try self.file.?.pwriteAll(&code, stub_helper.offset);
break :blk stub_helper.offset + code_size;
},
.aarch64 => {
var code: [6 * @sizeOf(u32)]u8 = undefined;
data_blk_outer: {
const this_addr = stub_helper.addr;
const target_addr = data.addr + data.size - @sizeOf(u64);
data_blk: {
const displacement = math.cast(i21, target_addr - this_addr) catch |_| break :data_blk;
// adr x17, disp
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.adr(.x17, displacement).toU32());
// nop
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.nop().toU32());
break :data_blk_outer;
}
data_blk: {
const new_this_addr = this_addr + @sizeOf(u32);
const displacement = math.cast(i21, target_addr - new_this_addr) catch |_| break :data_blk;
// nop
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.nop().toU32());
// adr x17, disp
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.adr(.x17, displacement).toU32());
break :data_blk_outer;
}
// Jump is too big, replace adr with adrp and add.
const this_page = @intCast(i32, this_addr >> 12);
const target_page = @intCast(i32, target_addr >> 12);
const pages = @intCast(i21, target_page - this_page);
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.adrp(.x17, pages).toU32());
const narrowed = @truncate(u12, target_addr);
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.add(.x17, .x17, narrowed, false).toU32());
}
// stp x16, x17, [sp, #-16]!
code[8] = 0xf0;
code[9] = 0x47;
code[10] = 0xbf;
code[11] = 0xa9;
binder_blk_outer: {
const dyld_stub_binder = self.imports.get("dyld_stub_binder").?;
const this_addr = stub_helper.addr + 3 * @sizeOf(u32);
const target_addr = (got.addr + dyld_stub_binder.got_index.? * @sizeOf(u64));
binder_blk: {
const displacement = math.divExact(u64, target_addr - this_addr, 4) catch |_| break :binder_blk;
const literal = math.cast(u18, displacement) catch |_| break :binder_blk;
// ldr x16, label
mem.writeIntLittle(u32, code[12..16], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
// nop
mem.writeIntLittle(u32, code[16..20], aarch64.Instruction.nop().toU32());
break :binder_blk_outer;
}
binder_blk: {
const new_this_addr = this_addr + @sizeOf(u32);
const displacement = math.divExact(u64, target_addr - new_this_addr, 4) catch |_| break :binder_blk;
const literal = math.cast(u18, displacement) catch |_| break :binder_blk;
// Pad with nop to please division.
// nop
mem.writeIntLittle(u32, code[12..16], aarch64.Instruction.nop().toU32());
// ldr x16, label
mem.writeIntLittle(u32, code[16..20], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
break :binder_blk_outer;
}
// Use adrp followed by ldr(immediate).
const this_page = @intCast(i32, this_addr >> 12);
const target_page = @intCast(i32, target_addr >> 12);
const pages = @intCast(i21, target_page - this_page);
mem.writeIntLittle(u32, code[12..16], aarch64.Instruction.adrp(.x16, pages).toU32());
const narrowed = @truncate(u12, target_addr);
const offset = try math.divExact(u12, narrowed, 8);
mem.writeIntLittle(u32, code[16..20], aarch64.Instruction.ldr(.x16, .{
.register = .{
.rn = .x16,
.offset = aarch64.Instruction.LoadStoreOffset.imm(offset),
},
}).toU32());
}
// br x16
code[20] = 0x00;
code[21] = 0x02;
code[22] = 0x1f;
code[23] = 0xd6;
try self.file.?.pwriteAll(&code, stub_helper.offset);
break :blk stub_helper.offset + 6 * @sizeOf(u32);
},
else => unreachable,
}
};
for (self.stubs.items) |sym| {
// TODO weak bound pointers
const index = sym.stubs_index orelse unreachable;
try self.writeLazySymbolPointer(index);
try self.writeStub(index);
try self.writeStubInStubHelper(index);
}
}
fn writeLazySymbolPointer(self: *Zld, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = text_segment.sections.items[self.stub_helper_section_index.?];
const data_segment = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const stub_size: u4 = switch (self.arch.?) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const stub_off = self.stub_helper_stubs_start_off.? + index * stub_size;
const end = stub_helper.addr + stub_off - stub_helper.offset;
var buf: [@sizeOf(u64)]u8 = undefined;
mem.writeIntLittle(u64, &buf, end);
const off = la_symbol_ptr.offset + index * @sizeOf(u64);
log.debug("writing lazy symbol pointer entry 0x{x} at 0x{x}", .{ end, off });
try self.file.?.pwriteAll(&buf, off);
}
fn writeStub(self: *Zld, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stubs = text_segment.sections.items[self.stubs_section_index.?];
const data_segment = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const stub_off = stubs.offset + index * stubs.reserved2;
const stub_addr = stubs.addr + index * stubs.reserved2;
const la_ptr_addr = la_symbol_ptr.addr + index * @sizeOf(u64);
log.debug("writing stub at 0x{x}", .{stub_off});
var code = try self.allocator.alloc(u8, stubs.reserved2);
defer self.allocator.free(code);
switch (self.arch.?) {
.x86_64 => {
assert(la_ptr_addr >= stub_addr + stubs.reserved2);
const displacement = try math.cast(u32, la_ptr_addr - stub_addr - stubs.reserved2);
// jmp
code[0] = 0xff;
code[1] = 0x25;
mem.writeIntLittle(u32, code[2..][0..4], displacement);
},
.aarch64 => {
assert(la_ptr_addr >= stub_addr);
outer: {
const this_addr = stub_addr;
const target_addr = la_ptr_addr;
inner: {
const displacement = math.divExact(u64, target_addr - this_addr, 4) catch |_| break :inner;
const literal = math.cast(u18, displacement) catch |_| break :inner;
// ldr x16, literal
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
// nop
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.nop().toU32());
break :outer;
}
inner: {
const new_this_addr = this_addr + @sizeOf(u32);
const displacement = math.divExact(u64, target_addr - new_this_addr, 4) catch |_| break :inner;
const literal = math.cast(u18, displacement) catch |_| break :inner;
// nop
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.nop().toU32());
// ldr x16, literal
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
break :outer;
}
// Use adrp followed by ldr(immediate).
const this_page = @intCast(i32, this_addr >> 12);
const target_page = @intCast(i32, target_addr >> 12);
const pages = @intCast(i21, target_page - this_page);
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.adrp(.x16, pages).toU32());
const narrowed = @truncate(u12, target_addr);
const offset = try math.divExact(u12, narrowed, 8);
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.ldr(.x16, .{
.register = .{
.rn = .x16,
.offset = aarch64.Instruction.LoadStoreOffset.imm(offset),
},
}).toU32());
}
// br x16
mem.writeIntLittle(u32, code[8..12], aarch64.Instruction.br(.x16).toU32());
},
else => unreachable,
}
try self.file.?.pwriteAll(code, stub_off);
}
fn writeStubInStubHelper(self: *Zld, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = text_segment.sections.items[self.stub_helper_section_index.?];
const stub_size: u4 = switch (self.arch.?) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const stub_off = self.stub_helper_stubs_start_off.? + index * stub_size;
var code = try self.allocator.alloc(u8, stub_size);
defer self.allocator.free(code);
switch (self.arch.?) {
.x86_64 => {
const displacement = try math.cast(
i32,
@intCast(i64, stub_helper.offset) - @intCast(i64, stub_off) - stub_size,
);
// pushq
code[0] = 0x68;
mem.writeIntLittle(u32, code[1..][0..4], 0x0); // Just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
// jmpq
code[5] = 0xe9;
mem.writeIntLittle(u32, code[6..][0..4], @bitCast(u32, displacement));
},
.aarch64 => {
const displacement = try math.cast(i28, @intCast(i64, stub_helper.offset) - @intCast(i64, stub_off) - 4);
const literal = @divExact(stub_size - @sizeOf(u32), 4);
// ldr w16, literal
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.ldr(.w16, .{
.literal = literal,
}).toU32());
// b disp
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.b(displacement).toU32());
mem.writeIntLittle(u32, code[8..12], 0x0); // Just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
},
else => unreachable,
}
try self.file.?.pwriteAll(code, stub_off);
}
fn resolveSymbolsInObject(self: *Zld, object: *Object) !void {
log.debug("resolving symbols in '{s}'", .{object.name});
for (object.symbols.items) |sym| {
if (sym.cast(Symbol.Regular)) |reg| {
if (reg.linkage == .translation_unit) continue; // Symbol local to TU.
if (self.unresolved.swapRemove(sym.name)) |entry| {
// Create link to the global.
entry.value.alias = sym;
}
const entry = self.globals.getEntry(sym.name) orelse {
// Put new global symbol into the symbol table.
try self.globals.putNoClobber(self.allocator, sym.name, sym);
continue;
};
const g_sym = entry.value;
const g_reg = g_sym.cast(Symbol.Regular) orelse unreachable;
switch (g_reg.linkage) {
.translation_unit => unreachable,
.linkage_unit => {
if (reg.linkage == .linkage_unit) {
// Create link to the first encountered linkage_unit symbol.
sym.alias = g_sym;
continue;
}
},
.global => {
if (reg.linkage == .global) {
log.debug("symbol '{s}' defined multiple times", .{reg.base.name});
return error.MultipleSymbolDefinitions;
}
sym.alias = g_sym;
continue;
},
}
g_sym.alias = sym;
entry.value = sym;
} else if (sym.cast(Symbol.Unresolved)) |und| {
if (self.globals.get(sym.name)) |g_sym| {
sym.alias = g_sym;
continue;
}
if (self.unresolved.get(sym.name)) |u_sym| {
sym.alias = u_sym;
continue;
}
try self.unresolved.putNoClobber(self.allocator, sym.name, sym);
} else unreachable;
}
}
fn resolveSymbols(self: *Zld) !void {
// First pass, resolve symbols in provided objects.
for (self.objects.items) |object| {
try self.resolveSymbolsInObject(object);
}
// Second pass, resolve symbols in static libraries.
var next_sym: usize = 0;
while (true) {
if (next_sym == self.unresolved.count()) break;
const entry = self.unresolved.items()[next_sym];
const sym = entry.value;
var reset: bool = false;
for (self.archives.items) |archive| {
// Check if the entry exists in a static archive.
const offsets = archive.toc.get(sym.name) orelse {
// No hit.
continue;
};
assert(offsets.items.len > 0);
const object = try archive.parseObject(offsets.items[0]);
try self.objects.append(self.allocator, object);
try self.resolveSymbolsInObject(object);
reset = true;
break;
}
if (reset) {
next_sym = 0;
} else {
next_sym += 1;
}
}
// Third pass, resolve symbols in dynamic libraries.
// TODO Implement libSystem as a hard-coded library, or ship with
// a libSystem.B.tbd definition file?
var unresolved = std.ArrayList(*Symbol).init(self.allocator);
defer unresolved.deinit();
try unresolved.ensureCapacity(self.unresolved.count());
for (self.unresolved.items()) |entry| {
unresolved.appendAssumeCapacity(entry.value);
}
self.unresolved.clearAndFree(self.allocator);
var has_undefined = false;
while (unresolved.popOrNull()) |undef| {
var found = false;
for (self.dylibs.items) |dylib| {
const proxy = dylib.symbols.get(undef.name) orelse continue;
try self.imports.putNoClobber(self.allocator, proxy.name, proxy);
undef.alias = proxy;
found = true;
}
if (!found) {
// TODO we currently hardcode all unresolved symbols to libSystem
const proxy = try self.allocator.create(Symbol.Proxy);
errdefer self.allocator.destroy(proxy);
proxy.* = .{
.base = .{
.@"type" = .proxy,
.name = try self.allocator.dupe(u8, undef.name),
},
.dylib = null, // TODO null means libSystem
};
try self.imports.putNoClobber(self.allocator, proxy.base.name, &proxy.base);
undef.alias = &proxy.base;
// log.err("undefined reference to symbol '{s}'", .{undef.name});
// log.err(" | referenced in {s}", .{
// undef.cast(Symbol.Unresolved).?.file.name.?,
// });
// has_undefined = true;
}
}
if (has_undefined) return error.UndefinedSymbolReference;
// Finally put dyld_stub_binder as an Import
const dyld_stub_binder = try self.allocator.create(Symbol.Proxy);
errdefer self.allocator.destroy(dyld_stub_binder);
dyld_stub_binder.* = .{
.base = .{
.@"type" = .proxy,
.name = try self.allocator.dupe(u8, "dyld_stub_binder"),
},
.dylib = null, // TODO null means libSystem
};
try self.imports.putNoClobber(
self.allocator,
dyld_stub_binder.base.name,
&dyld_stub_binder.base,
);
}
fn resolveStubsAndGotEntries(self: *Zld) !void {
for (self.objects.items) |object| {
log.debug("resolving stubs and got entries from {s}", .{object.name});
for (object.sections.items) |sect| {
const relocs = sect.relocs orelse continue;
for (relocs) |rel| {
switch (rel.@"type") {
.unsigned => continue,
.got_page, .got_page_off, .got_load, .got => {
const sym = rel.target.symbol.getTopmostAlias();
if (sym.got_index != null) continue;
const index = @intCast(u32, self.got_entries.items.len);
sym.got_index = index;
try self.got_entries.append(self.allocator, sym);
log.debug(" | found GOT entry {s}: {*}", .{ sym.name, sym });
},
else => {
if (rel.target != .symbol) continue;
const sym = rel.target.symbol.getTopmostAlias();
assert(sym.@"type" != .unresolved);
if (sym.stubs_index != null) continue;
if (sym.@"type" != .proxy) continue;
// if (sym.cast(Symbol.Regular)) |reg| {
// if (!reg.weak_ref) continue;
// }
const index = @intCast(u32, self.stubs.items.len);
sym.stubs_index = index;
try self.stubs.append(self.allocator, sym);
log.debug(" | found stub {s}: {*}", .{ sym.name, sym });
},
}
}
}
}
// Finally, put dyld_stub_binder as the final GOT entry
const sym = self.imports.get("dyld_stub_binder") orelse unreachable;
const index = @intCast(u32, self.got_entries.items.len);
sym.got_index = index;
try self.got_entries.append(self.allocator, sym);
log.debug(" | found GOT entry {s}: {*}", .{ sym.name, sym });
}
fn resolveRelocsAndWriteSections(self: *Zld) !void {
for (self.objects.items) |object, object_id| {
log.debug("relocating object {s}", .{object.name});
for (object.sections.items) |sect, source_sect_id| {
if (sect.inner.flags == macho.S_MOD_INIT_FUNC_POINTERS or
sect.inner.flags == macho.S_MOD_TERM_FUNC_POINTERS) continue;
const segname = parseName(§.inner.segname);
const sectname = parseName(§.inner.sectname);
log.debug("relocating section '{s},{s}'", .{ segname, sectname });
// Get mapping
const target_mapping = self.mappings.get(.{
.object_id = @intCast(u16, object_id),
.source_sect_id = @intCast(u16, source_sect_id),
}) orelse {
log.debug("no mapping for {s},{s}; skipping", .{ segname, sectname });
continue;
};
const target_seg = self.load_commands.items[target_mapping.target_seg_id].Segment;
const target_sect = target_seg.sections.items[target_mapping.target_sect_id];
const target_sect_addr = target_sect.addr + target_mapping.offset;
const target_sect_off = target_sect.offset + target_mapping.offset;
if (sect.relocs) |relocs| {
for (relocs) |rel| {
const source_addr = target_sect_addr + rel.offset;
var args: reloc.Relocation.ResolveArgs = .{
.source_addr = source_addr,
.target_addr = undefined,
};
switch (rel.@"type") {
.unsigned => {
args.target_addr = try self.relocTargetAddr(@intCast(u16, object_id), rel.target);
const unsigned = rel.cast(reloc.Unsigned) orelse unreachable;
if (unsigned.subtractor) |subtractor| {
args.subtractor = try self.relocTargetAddr(@intCast(u16, object_id), subtractor);
}
if (rel.target == .section) {
const source_sect = object.sections.items[rel.target.section];
args.source_source_sect_addr = sect.inner.addr;
args.source_target_sect_addr = source_sect.inner.addr;
}
rebases: {
var hit: bool = false;
if (target_mapping.target_seg_id == self.data_segment_cmd_index.?) {
if (self.data_section_index) |index| {
if (index == target_mapping.target_sect_id) hit = true;
}
}
if (target_mapping.target_seg_id == self.data_const_segment_cmd_index.?) {
if (self.data_const_section_index) |index| {
if (index == target_mapping.target_sect_id) hit = true;
}
}
if (!hit) break :rebases;
try self.local_rebases.append(self.allocator, .{
.offset = source_addr - target_seg.inner.vmaddr,
.segment_id = target_mapping.target_seg_id,
});
}
// TLV is handled via a separate offset mechanism.
// Calculate the offset to the initializer.
if (target_sect.flags == macho.S_THREAD_LOCAL_VARIABLES) tlv: {
// TODO we don't want to save offset to tlv_bootstrap
if (mem.eql(u8, rel.target.symbol.name, "__tlv_bootstrap")) break :tlv;
const base_addr = blk: {
if (self.tlv_data_section_index) |index| {
const tlv_data = target_seg.sections.items[index];
break :blk tlv_data.addr;
} else {
const tlv_bss = target_seg.sections.items[self.tlv_bss_section_index.?];
break :blk tlv_bss.addr;
}
};
// Since we require TLV data to always preceed TLV bss section, we calculate
// offsets wrt to the former if it is defined; otherwise, wrt to the latter.
try self.threadlocal_offsets.append(self.allocator, .{
.source_addr = args.source_addr,
.offset = args.target_addr - base_addr,
});
}
},
.got_page, .got_page_off, .got_load, .got => {
const dc_seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const got = dc_seg.sections.items[self.got_section_index.?];
const final = rel.target.symbol.getTopmostAlias();
args.target_addr = got.addr + final.got_index.? * @sizeOf(u64);
},
else => |tt| {
if (tt == .signed and rel.target == .section) {
const source_sect = object.sections.items[rel.target.section];
args.source_source_sect_addr = sect.inner.addr;
args.source_target_sect_addr = source_sect.inner.addr;
}
args.target_addr = try self.relocTargetAddr(@intCast(u16, object_id), rel.target);
},
}
try rel.resolve(args);
}
}
log.debug("writing contents of '{s},{s}' section from '{s}' from 0x{x} to 0x{x}", .{
segname,
sectname,
object.name,
target_sect_off,
target_sect_off + sect.code.len,
});
if (target_sect.flags == macho.S_ZEROFILL or
target_sect.flags == macho.S_THREAD_LOCAL_ZEROFILL or
target_sect.flags == macho.S_THREAD_LOCAL_VARIABLES)
{
log.debug("zeroing out '{s},{s}' from 0x{x} to 0x{x}", .{
parseName(&target_sect.segname),
parseName(&target_sect.sectname),
target_sect_off,
target_sect_off + sect.code.len,
});
// Zero-out the space
var zeroes = try self.allocator.alloc(u8, sect.code.len);
defer self.allocator.free(zeroes);
mem.set(u8, zeroes, 0);
try self.file.?.pwriteAll(zeroes, target_sect_off);
} else {
try self.file.?.pwriteAll(sect.code, target_sect_off);
}
}
}
}
fn relocTargetAddr(self: *Zld, object_id: u16, target: reloc.Relocation.Target) !u64 {
const target_addr = blk: {
switch (target) {
.symbol => |sym| {
const final = sym.getTopmostAlias();
if (final.cast(Symbol.Regular)) |reg| {
log.debug(" | regular '{s}'", .{sym.name});
break :blk reg.address;
} else if (final.cast(Symbol.Proxy)) |proxy| {
if (mem.eql(u8, sym.name, "__tlv_bootstrap")) {
log.debug(" | symbol '__tlv_bootstrap'", .{});
const segment = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const tlv = segment.sections.items[self.tlv_section_index.?];
break :blk tlv.addr;
}
log.debug(" | symbol stub '{s}'", .{sym.name});
const segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stubs = segment.sections.items[self.stubs_section_index.?];
break :blk stubs.addr + proxy.base.stubs_index.? * stubs.reserved2;
} else {
log.err("failed to resolve symbol '{s}' as a relocation target", .{sym.name});
return error.FailedToResolveRelocationTarget;
}
},
.section => |sect_id| {
const target_mapping = self.mappings.get(.{
.object_id = object_id,
.source_sect_id = sect_id,
}) orelse unreachable;
const target_seg = self.load_commands.items[target_mapping.target_seg_id].Segment;
const target_sect = target_seg.sections.items[target_mapping.target_sect_id];
break :blk target_sect.addr + target_mapping.offset;
},
}
};
return target_addr;
}
fn populateMetadata(self: *Zld) !void {
if (self.pagezero_segment_cmd_index == null) {
self.pagezero_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__PAGEZERO"),
.vmaddr = 0,
.vmsize = 0x100000000, // size always set to 4GB
.fileoff = 0,
.filesize = 0,
.maxprot = 0,
.initprot = 0,
.nsects = 0,
.flags = 0,
}),
});
}
if (self.text_segment_cmd_index == null) {
self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__TEXT"),
.vmaddr = 0x100000000, // always starts at 4GB
.vmsize = 0,
.fileoff = 0,
.filesize = 0,
.maxprot = macho.VM_PROT_READ | macho.VM_PROT_EXECUTE,
.initprot = macho.VM_PROT_READ | macho.VM_PROT_EXECUTE,
.nsects = 0,
.flags = 0,
}),
});
}
if (self.text_section_index == null) {
const text_seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.text_section_index = @intCast(u16, text_seg.sections.items.len);
const alignment: u2 = switch (self.arch.?) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__text"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
if (self.stubs_section_index == null) {
const text_seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.stubs_section_index = @intCast(u16, text_seg.sections.items.len);
const alignment: u2 = switch (self.arch.?) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const stub_size: u4 = switch (self.arch.?) {
.x86_64 => 6,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable, // unhandled architecture type
};
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__stubs"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_SYMBOL_STUBS | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
.reserved1 = 0,
.reserved2 = stub_size,
.reserved3 = 0,
});
}
if (self.stub_helper_section_index == null) {
const text_seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.stub_helper_section_index = @intCast(u16, text_seg.sections.items.len);
const alignment: u2 = switch (self.arch.?) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const stub_helper_size: u6 = switch (self.arch.?) {
.x86_64 => 15,
.aarch64 => 6 * @sizeOf(u32),
else => unreachable,
};
try text_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__stub_helper"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = stub_helper_size,
.offset = 0,
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
if (self.data_const_segment_cmd_index == null) {
self.data_const_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__DATA_CONST"),
.vmaddr = 0,
.vmsize = 0,
.fileoff = 0,
.filesize = 0,
.maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE,
.initprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE,
.nsects = 0,
.flags = 0,
}),
});
}
if (self.got_section_index == null) {
const data_const_seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
self.got_section_index = @intCast(u16, data_const_seg.sections.items.len);
try data_const_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__got"),
.segname = makeStaticString("__DATA_CONST"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = macho.S_NON_LAZY_SYMBOL_POINTERS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
if (self.data_segment_cmd_index == null) {
self.data_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__DATA"),
.vmaddr = 0,
.vmsize = 0,
.fileoff = 0,
.filesize = 0,
.maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE,
.initprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE,
.nsects = 0,
.flags = 0,
}),
});
}
if (self.la_symbol_ptr_section_index == null) {
const data_seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
self.la_symbol_ptr_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__la_symbol_ptr"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = macho.S_LAZY_SYMBOL_POINTERS,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
if (self.data_section_index == null) {
const data_seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
self.data_section_index = @intCast(u16, data_seg.sections.items.len);
try data_seg.addSection(self.allocator, .{
.sectname = makeStaticString("__data"),
.segname = makeStaticString("__DATA"),
.addr = 0,
.size = 0,
.offset = 0,
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
}
if (self.linkedit_segment_cmd_index == null) {
self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__LINKEDIT"),
.vmaddr = 0,
.vmsize = 0,
.fileoff = 0,
.filesize = 0,
.maxprot = macho.VM_PROT_READ,
.initprot = macho.VM_PROT_READ,
.nsects = 0,
.flags = 0,
}),
});
}
if (self.dyld_info_cmd_index == null) {
self.dyld_info_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.DyldInfoOnly = .{
.cmd = macho.LC_DYLD_INFO_ONLY,
.cmdsize = @sizeOf(macho.dyld_info_command),
.rebase_off = 0,
.rebase_size = 0,
.bind_off = 0,
.bind_size = 0,
.weak_bind_off = 0,
.weak_bind_size = 0,
.lazy_bind_off = 0,
.lazy_bind_size = 0,
.export_off = 0,
.export_size = 0,
},
});
}
if (self.symtab_cmd_index == null) {
self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Symtab = .{
.cmd = macho.LC_SYMTAB,
.cmdsize = @sizeOf(macho.symtab_command),
.symoff = 0,
.nsyms = 0,
.stroff = 0,
.strsize = 0,
},
});
try self.strtab.append(self.allocator, 0);
}
if (self.dysymtab_cmd_index == null) {
self.dysymtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Dysymtab = .{
.cmd = macho.LC_DYSYMTAB,
.cmdsize = @sizeOf(macho.dysymtab_command),
.ilocalsym = 0,
.nlocalsym = 0,
.iextdefsym = 0,
.nextdefsym = 0,
.iundefsym = 0,
.nundefsym = 0,
.tocoff = 0,
.ntoc = 0,
.modtaboff = 0,
.nmodtab = 0,
.extrefsymoff = 0,
.nextrefsyms = 0,
.indirectsymoff = 0,
.nindirectsyms = 0,
.extreloff = 0,
.nextrel = 0,
.locreloff = 0,
.nlocrel = 0,
},
});
}
if (self.dylinker_cmd_index == null) {
self.dylinker_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.dylinker_command) + mem.lenZ(DEFAULT_DYLD_PATH),
@sizeOf(u64),
));
var dylinker_cmd = emptyGenericCommandWithData(macho.dylinker_command{
.cmd = macho.LC_LOAD_DYLINKER,
.cmdsize = cmdsize,
.name = @sizeOf(macho.dylinker_command),
});
dylinker_cmd.data = try self.allocator.alloc(u8, cmdsize - dylinker_cmd.inner.name);
mem.set(u8, dylinker_cmd.data, 0);
mem.copy(u8, dylinker_cmd.data, mem.spanZ(DEFAULT_DYLD_PATH));
try self.load_commands.append(self.allocator, .{ .Dylinker = dylinker_cmd });
}
if (self.libsystem_cmd_index == null) {
self.libsystem_cmd_index = @intCast(u16, self.load_commands.items.len);
var dylib_cmd = try createLoadDylibCommand(self.allocator, mem.spanZ(LIB_SYSTEM_PATH), 2, 0, 0);
errdefer dylib_cmd.deinit(self.allocator);
try self.load_commands.append(self.allocator, .{ .Dylib = dylib_cmd });
}
if (self.main_cmd_index == null) {
self.main_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.Main = .{
.cmd = macho.LC_MAIN,
.cmdsize = @sizeOf(macho.entry_point_command),
.entryoff = 0x0,
.stacksize = 0,
},
});
}
if (self.source_version_cmd_index == null) {
self.source_version_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.SourceVersion = .{
.cmd = macho.LC_SOURCE_VERSION,
.cmdsize = @sizeOf(macho.source_version_command),
.version = 0x0,
},
});
}
if (self.uuid_cmd_index == null) {
self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len);
var uuid_cmd: macho.uuid_command = .{
.cmd = macho.LC_UUID,
.cmdsize = @sizeOf(macho.uuid_command),
.uuid = undefined,
};
std.crypto.random.bytes(&uuid_cmd.uuid);
try self.load_commands.append(self.allocator, .{ .Uuid = uuid_cmd });
}
if (self.code_signature_cmd_index == null and self.arch.? == .aarch64) {
self.code_signature_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.LinkeditData = .{
.cmd = macho.LC_CODE_SIGNATURE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
}
if (self.data_in_code_cmd_index == null and self.arch.? == .x86_64) {
self.data_in_code_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.allocator, .{
.LinkeditData = .{
.cmd = macho.LC_DATA_IN_CODE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
}
}
fn addRpaths(self: *Zld, rpaths: []const []const u8) !void {
for (rpaths) |rpath| {
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.rpath_command) + rpath.len,
@sizeOf(u64),
));
var rpath_cmd = emptyGenericCommandWithData(macho.rpath_command{
.cmd = macho.LC_RPATH,
.cmdsize = cmdsize,
.path = @sizeOf(macho.rpath_command),
});
rpath_cmd.data = try self.allocator.alloc(u8, cmdsize - rpath_cmd.inner.path);
mem.set(u8, rpath_cmd.data, 0);
mem.copy(u8, rpath_cmd.data, rpath);
try self.load_commands.append(self.allocator, .{ .Rpath = rpath_cmd });
}
}
fn flush(self: *Zld) !void {
try self.writeStubHelperCommon();
try self.resolveRelocsAndWriteSections();
if (self.common_section_index) |index| {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = &seg.sections.items[index];
sect.offset = 0;
}
if (self.bss_section_index) |index| {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = &seg.sections.items[index];
sect.offset = 0;
}
if (self.tlv_bss_section_index) |index| {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = &seg.sections.items[index];
sect.offset = 0;
}
if (self.tlv_section_index) |index| {
const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = &seg.sections.items[index];
var buffer = try self.allocator.alloc(u8, sect.size);
defer self.allocator.free(buffer);
_ = try self.file.?.preadAll(buffer, sect.offset);
var stream = std.io.fixedBufferStream(buffer);
var writer = stream.writer();
std.sort.sort(TlvOffset, self.threadlocal_offsets.items, {}, TlvOffset.cmp);
const seek_amt = 2 * @sizeOf(u64);
for (self.threadlocal_offsets.items) |tlv| {
try writer.context.seekBy(seek_amt);
try writer.writeIntLittle(u64, tlv.offset);
}
try self.file.?.pwriteAll(buffer, sect.offset);
}
if (self.mod_init_func_section_index) |index| {
const seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const sect = &seg.sections.items[index];
var initializers = std.ArrayList(u64).init(self.allocator);
defer initializers.deinit();
for (self.objects.items) |object| {
for (object.initializers.items) |initializer| {
const address = initializer.cast(Symbol.Regular).?.address;
try initializers.append(address);
}
}
_ = try self.file.?.pwriteAll(mem.sliceAsBytes(initializers.items), sect.offset);
sect.size = @intCast(u32, initializers.items.len * @sizeOf(u64));
}
try self.writeGotEntries();
try self.setEntryPoint();
try self.writeRebaseInfoTable();
try self.writeBindInfoTable();
try self.writeLazyBindInfoTable();
try self.writeExportInfo();
if (self.arch.? == .x86_64) {
try self.writeDataInCode();
}
{
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
symtab.symoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
}
try self.writeDebugInfo();
try self.writeSymbolTable();
try self.writeStringTable();
{
// Seal __LINKEDIT size
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size.?);
}
if (self.arch.? == .aarch64) {
try self.writeCodeSignaturePadding();
}
try self.writeLoadCommands();
try self.writeHeader();
if (self.arch.? == .aarch64) {
try self.writeCodeSignature();
}
if (comptime std.Target.current.isDarwin() and std.Target.current.cpu.arch == .aarch64) {
try fs.cwd().copyFile(self.out_path.?, fs.cwd(), self.out_path.?, .{});
}
}
fn writeGotEntries(self: *Zld) !void {
const seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const sect = seg.sections.items[self.got_section_index.?];
var buffer = try self.allocator.alloc(u8, self.got_entries.items.len * @sizeOf(u64));
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
var writer = stream.writer();
for (self.got_entries.items) |sym| {
const address: u64 = if (sym.cast(Symbol.Regular)) |reg| reg.address else 0;
try writer.writeIntLittle(u64, address);
}
log.debug("writing GOT pointers at 0x{x} to 0x{x}", .{ sect.offset, sect.offset + buffer.len });
try self.file.?.pwriteAll(buffer, sect.offset);
}
fn setEntryPoint(self: *Zld) !void {
// TODO we should respect the -entry flag passed in by the user to set a custom
// entrypoint. For now, assume default of `_main`.
const seg = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text = seg.sections.items[self.text_section_index.?];
const sym = self.globals.get("_main") orelse return error.MissingMainEntrypoint;
const entry_sym = sym.cast(Symbol.Regular) orelse unreachable;
const ec = &self.load_commands.items[self.main_cmd_index.?].Main;
ec.entryoff = @intCast(u32, entry_sym.address - seg.inner.vmaddr);
ec.stacksize = self.stack_size;
}
fn writeRebaseInfoTable(self: *Zld) !void {
var pointers = std.ArrayList(Pointer).init(self.allocator);
defer pointers.deinit();
try pointers.ensureCapacity(self.local_rebases.items.len);
pointers.appendSliceAssumeCapacity(self.local_rebases.items);
if (self.got_section_index) |idx| {
const seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_const_segment_cmd_index.?);
for (self.got_entries.items) |sym| {
if (sym.@"type" == .proxy) continue;
try pointers.append(.{
.offset = base_offset + sym.got_index.? * @sizeOf(u64),
.segment_id = segment_id,
});
}
}
if (self.mod_init_func_section_index) |idx| {
const seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_const_segment_cmd_index.?);
var index: u64 = 0;
for (self.objects.items) |object| {
for (object.initializers.items) |_| {
try pointers.append(.{
.offset = base_offset + index * @sizeOf(u64),
.segment_id = segment_id,
});
index += 1;
}
}
}
if (self.la_symbol_ptr_section_index) |idx| {
const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_segment_cmd_index.?);
try pointers.ensureCapacity(pointers.items.len + self.stubs.items.len);
for (self.stubs.items) |sym| {
pointers.appendAssumeCapacity(.{
.offset = base_offset + sym.stubs_index.? * @sizeOf(u64),
.segment_id = segment_id,
});
}
}
std.sort.sort(Pointer, pointers.items, {}, pointerCmp);
const size = try rebaseInfoSize(pointers.items);
var buffer = try self.allocator.alloc(u8, @intCast(usize, size));
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeRebaseInfo(pointers.items, stream.writer());
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
dyld_info.rebase_off = @intCast(u32, seg.inner.fileoff);
dyld_info.rebase_size = @intCast(u32, mem.alignForwardGeneric(u64, buffer.len, @sizeOf(u64)));
seg.inner.filesize += dyld_info.rebase_size;
log.debug("writing rebase info from 0x{x} to 0x{x}", .{ dyld_info.rebase_off, dyld_info.rebase_off + dyld_info.rebase_size });
try self.file.?.pwriteAll(buffer, dyld_info.rebase_off);
}
fn writeBindInfoTable(self: *Zld) !void {
var pointers = std.ArrayList(Pointer).init(self.allocator);
defer pointers.deinit();
if (self.got_section_index) |idx| {
const seg = self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_const_segment_cmd_index.?);
for (self.got_entries.items) |sym| {
if (sym.cast(Symbol.Proxy)) |proxy| {
const dylib_ordinal = ordinal: {
const dylib = proxy.dylib orelse break :ordinal 1; // TODO embedded libSystem
break :ordinal dylib.ordinal.?;
};
try pointers.append(.{
.offset = base_offset + proxy.base.got_index.? * @sizeOf(u64),
.segment_id = segment_id,
.dylib_ordinal = dylib_ordinal,
.name = proxy.base.name,
});
}
}
}
if (self.tlv_section_index) |idx| {
const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_segment_cmd_index.?);
const sym = self.imports.get("__tlv_bootstrap") orelse unreachable;
const proxy = sym.cast(Symbol.Proxy) orelse unreachable;
const dylib_ordinal = ordinal: {
const dylib = proxy.dylib orelse break :ordinal 1; // TODO embedded libSystem
break :ordinal dylib.ordinal.?;
};
try pointers.append(.{
.offset = base_offset,
.segment_id = segment_id,
.dylib_ordinal = dylib_ordinal,
.name = proxy.base.name,
});
}
const size = try bindInfoSize(pointers.items);
var buffer = try self.allocator.alloc(u8, @intCast(usize, size));
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeBindInfo(pointers.items, stream.writer());
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
dyld_info.bind_off = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dyld_info.bind_size = @intCast(u32, mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64)));
seg.inner.filesize += dyld_info.bind_size;
log.debug("writing binding info from 0x{x} to 0x{x}", .{ dyld_info.bind_off, dyld_info.bind_off + dyld_info.bind_size });
try self.file.?.pwriteAll(buffer, dyld_info.bind_off);
}
fn writeLazyBindInfoTable(self: *Zld) !void {
var pointers = std.ArrayList(Pointer).init(self.allocator);
defer pointers.deinit();
if (self.la_symbol_ptr_section_index) |idx| {
const seg = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const sect = seg.sections.items[idx];
const base_offset = sect.addr - seg.inner.vmaddr;
const segment_id = @intCast(u16, self.data_segment_cmd_index.?);
try pointers.ensureCapacity(self.stubs.items.len);
for (self.stubs.items) |sym| {
const proxy = sym.cast(Symbol.Proxy) orelse unreachable;
const dylib_ordinal = ordinal: {
const dylib = proxy.dylib orelse break :ordinal 1; // TODO embedded libSystem
break :ordinal dylib.ordinal.?;
};
pointers.appendAssumeCapacity(.{
.offset = base_offset + sym.stubs_index.? * @sizeOf(u64),
.segment_id = segment_id,
.dylib_ordinal = dylib_ordinal,
.name = sym.name,
});
}
}
const size = try lazyBindInfoSize(pointers.items);
var buffer = try self.allocator.alloc(u8, @intCast(usize, size));
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeLazyBindInfo(pointers.items, stream.writer());
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
dyld_info.lazy_bind_off = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dyld_info.lazy_bind_size = @intCast(u32, mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64)));
seg.inner.filesize += dyld_info.lazy_bind_size;
log.debug("writing lazy binding info from 0x{x} to 0x{x}", .{ dyld_info.lazy_bind_off, dyld_info.lazy_bind_off + dyld_info.lazy_bind_size });
try self.file.?.pwriteAll(buffer, dyld_info.lazy_bind_off);
try self.populateLazyBindOffsetsInStubHelper(buffer);
}
fn populateLazyBindOffsetsInStubHelper(self: *Zld, buffer: []const u8) !void {
var stream = std.io.fixedBufferStream(buffer);
var reader = stream.reader();
var offsets = std.ArrayList(u32).init(self.allocator);
try offsets.append(0);
defer offsets.deinit();
var valid_block = false;
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK;
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_DO_BIND => {
valid_block = true;
},
macho.BIND_OPCODE_DONE => {
if (valid_block) {
const offset = try stream.getPos();
try offsets.append(@intCast(u32, offset));
}
valid_block = false;
},
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var next = try reader.readByte();
while (next != @as(u8, 0)) {
next = try reader.readByte();
}
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
_ = try leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
_ = try leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
_ = try leb.readILEB128(i64, reader);
},
else => {},
}
}
assert(self.stubs.items.len <= offsets.items.len);
const stub_size: u4 = switch (self.arch.?) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const off: u4 = switch (self.arch.?) {
.x86_64 => 1,
.aarch64 => 2 * @sizeOf(u32),
else => unreachable,
};
var buf: [@sizeOf(u32)]u8 = undefined;
for (self.stubs.items) |sym| {
const index = sym.stubs_index orelse unreachable;
const placeholder_off = self.stub_helper_stubs_start_off.? + index * stub_size + off;
mem.writeIntLittle(u32, &buf, offsets.items[index]);
try self.file.?.pwriteAll(&buf, placeholder_off);
}
}
fn writeExportInfo(self: *Zld) !void {
var trie = Trie.init(self.allocator);
defer trie.deinit();
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
// TODO export items for dylibs
const sym = self.globals.get("_main") orelse return error.MissingMainEntrypoint;
const reg = sym.cast(Symbol.Regular) orelse unreachable;
assert(reg.address >= text_segment.inner.vmaddr);
try trie.put(.{
.name = sym.name,
.vmaddr_offset = reg.address - text_segment.inner.vmaddr,
.export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR,
});
try trie.finalize();
var buffer = try self.allocator.alloc(u8, @intCast(usize, trie.size));
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
const nwritten = try trie.write(stream.writer());
assert(nwritten == trie.size);
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
dyld_info.export_off = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dyld_info.export_size = @intCast(u32, mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64)));
seg.inner.filesize += dyld_info.export_size;
log.debug("writing export info from 0x{x} to 0x{x}", .{ dyld_info.export_off, dyld_info.export_off + dyld_info.export_size });
try self.file.?.pwriteAll(buffer, dyld_info.export_off);
}
fn writeDebugInfo(self: *Zld) !void {
var stabs = std.ArrayList(macho.nlist_64).init(self.allocator);
defer stabs.deinit();
for (self.objects.items) |object| {
const tu_path = object.tu_path orelse continue;
const tu_mtime = object.tu_mtime orelse continue;
const dirname = std.fs.path.dirname(tu_path) orelse "./";
// Current dir
try stabs.append(.{
.n_strx = try self.makeString(tu_path[0 .. dirname.len + 1]),
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
// Artifact name
try stabs.append(.{
.n_strx = try self.makeString(tu_path[dirname.len + 1 ..]),
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
// Path to object file with debug info
try stabs.append(.{
.n_strx = try self.makeString(object.name.?),
.n_type = macho.N_OSO,
.n_sect = 0,
.n_desc = 1,
.n_value = 0, //tu_mtime, TODO figure out why precalculated mtime value doesn't work
});
for (object.symbols.items) |sym| {
if (sym.@"type" != .regular) continue;
const reg = sym.cast(Symbol.Regular) orelse unreachable;
if (reg.isTemp() or reg.stab == null) continue;
const stab = reg.stab orelse unreachable;
switch (stab.kind) {
.function => {
try stabs.append(.{
.n_strx = 0,
.n_type = macho.N_BNSYM,
.n_sect = reg.section,
.n_desc = 0,
.n_value = reg.address,
});
try stabs.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_FUN,
.n_sect = reg.section,
.n_desc = 0,
.n_value = reg.address,
});
try stabs.append(.{
.n_strx = 0,
.n_type = macho.N_FUN,
.n_sect = 0,
.n_desc = 0,
.n_value = stab.size,
});
try stabs.append(.{
.n_strx = 0,
.n_type = macho.N_ENSYM,
.n_sect = reg.section,
.n_desc = 0,
.n_value = stab.size,
});
},
.global => {
try stabs.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_GSYM,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
},
.static => {
try stabs.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_STSYM,
.n_sect = reg.section,
.n_desc = 0,
.n_value = reg.address,
});
},
}
}
// Close the source file!
try stabs.append(.{
.n_strx = 0,
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
}
if (stabs.items.len == 0) return;
// Write stabs into the symbol table
const linkedit = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
symtab.nsyms = @intCast(u32, stabs.items.len);
const stabs_off = symtab.symoff;
const stabs_size = symtab.nsyms * @sizeOf(macho.nlist_64);
log.debug("writing symbol stabs from 0x{x} to 0x{x}", .{ stabs_off, stabs_size + stabs_off });
try self.file.?.pwriteAll(mem.sliceAsBytes(stabs.items), stabs_off);
linkedit.inner.filesize += stabs_size;
// Update dynamic symbol table.
const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
dysymtab.nlocalsym = symtab.nsyms;
}
fn writeSymbolTable(self: *Zld) !void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
var locals = std.ArrayList(macho.nlist_64).init(self.allocator);
defer locals.deinit();
var exports = std.ArrayList(macho.nlist_64).init(self.allocator);
defer exports.deinit();
for (self.objects.items) |object| {
for (object.symbols.items) |sym| {
const final = sym.getTopmostAlias();
if (final.@"type" != .regular) continue;
const reg = final.cast(Symbol.Regular) orelse unreachable;
if (reg.isTemp()) continue;
switch (reg.linkage) {
.translation_unit => {
try locals.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_SECT,
.n_sect = reg.section,
.n_desc = 0,
.n_value = reg.address,
});
},
else => {
try exports.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_SECT | macho.N_EXT,
.n_sect = reg.section,
.n_desc = 0,
.n_value = reg.address,
});
},
}
}
}
var undefs = std.ArrayList(macho.nlist_64).init(self.allocator);
defer undefs.deinit();
for (self.imports.items()) |entry| {
const sym = entry.value;
const ordinal = ordinal: {
const dylib = sym.cast(Symbol.Proxy).?.dylib orelse break :ordinal 1; // TODO handle libSystem
break :ordinal dylib.ordinal.?;
};
try undefs.append(.{
.n_strx = try self.makeString(sym.name),
.n_type = macho.N_UNDF | macho.N_EXT,
.n_sect = 0,
.n_desc = (ordinal * macho.N_SYMBOL_RESOLVER) | macho.REFERENCE_FLAG_UNDEFINED_NON_LAZY,
.n_value = 0,
});
}
const nlocals = locals.items.len;
const nexports = exports.items.len;
const nundefs = undefs.items.len;
const locals_off = symtab.symoff + symtab.nsyms * @sizeOf(macho.nlist_64);
const locals_size = nlocals * @sizeOf(macho.nlist_64);
log.debug("writing local symbols from 0x{x} to 0x{x}", .{ locals_off, locals_size + locals_off });
try self.file.?.pwriteAll(mem.sliceAsBytes(locals.items), locals_off);
const exports_off = locals_off + locals_size;
const exports_size = nexports * @sizeOf(macho.nlist_64);
log.debug("writing exported symbols from 0x{x} to 0x{x}", .{ exports_off, exports_size + exports_off });
try self.file.?.pwriteAll(mem.sliceAsBytes(exports.items), exports_off);
const undefs_off = exports_off + exports_size;
const undefs_size = nundefs * @sizeOf(macho.nlist_64);
log.debug("writing undefined symbols from 0x{x} to 0x{x}", .{ undefs_off, undefs_size + undefs_off });
try self.file.?.pwriteAll(mem.sliceAsBytes(undefs.items), undefs_off);
symtab.nsyms += @intCast(u32, nlocals + nexports + nundefs);
seg.inner.filesize += locals_size + exports_size + undefs_size;
// Update dynamic symbol table.
const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
dysymtab.nlocalsym += @intCast(u32, nlocals);
dysymtab.iextdefsym = dysymtab.nlocalsym;
dysymtab.nextdefsym = @intCast(u32, nexports);
dysymtab.iundefsym = dysymtab.nlocalsym + dysymtab.nextdefsym;
dysymtab.nundefsym = @intCast(u32, nundefs);
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stubs = &text_segment.sections.items[self.stubs_section_index.?];
const data_const_segment = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const got = &data_const_segment.sections.items[self.got_section_index.?];
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = &data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const nstubs = @intCast(u32, self.stubs.items.len);
const ngot_entries = @intCast(u32, self.got_entries.items.len);
dysymtab.indirectsymoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dysymtab.nindirectsyms = nstubs * 2 + ngot_entries;
const needed_size = dysymtab.nindirectsyms * @sizeOf(u32);
seg.inner.filesize += needed_size;
log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{
dysymtab.indirectsymoff,
dysymtab.indirectsymoff + needed_size,
});
var buf = try self.allocator.alloc(u8, needed_size);
defer self.allocator.free(buf);
var stream = std.io.fixedBufferStream(buf);
var writer = stream.writer();
stubs.reserved1 = 0;
for (self.stubs.items) |sym| {
const id = self.imports.getIndex(sym.name) orelse unreachable;
try writer.writeIntLittle(u32, dysymtab.iundefsym + @intCast(u32, id));
}
got.reserved1 = nstubs;
for (self.got_entries.items) |sym| {
if (sym.@"type" == .proxy) {
const id = self.imports.getIndex(sym.name) orelse unreachable;
try writer.writeIntLittle(u32, dysymtab.iundefsym + @intCast(u32, id));
} else {
try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL);
}
}
la_symbol_ptr.reserved1 = got.reserved1 + ngot_entries;
for (self.stubs.items) |sym| {
const id = self.imports.getIndex(sym.name) orelse unreachable;
try writer.writeIntLittle(u32, dysymtab.iundefsym + @intCast(u32, id));
}
try self.file.?.pwriteAll(buf, dysymtab.indirectsymoff);
}
fn writeStringTable(self: *Zld) !void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
symtab.stroff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
symtab.strsize = @intCast(u32, mem.alignForwardGeneric(u64, self.strtab.items.len, @alignOf(u64)));
seg.inner.filesize += symtab.strsize;
log.debug("writing string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize });
try self.file.?.pwriteAll(self.strtab.items, symtab.stroff);
if (symtab.strsize > self.strtab.items.len and self.arch.? == .x86_64) {
// This is the last section, so we need to pad it out.
try self.file.?.pwriteAll(&[_]u8{0}, seg.inner.fileoff + seg.inner.filesize - 1);
}
}
fn writeDataInCode(self: *Zld) !void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dice_cmd = &self.load_commands.items[self.data_in_code_cmd_index.?].LinkeditData;
const fileoff = seg.inner.fileoff + seg.inner.filesize;
var buf = std.ArrayList(u8).init(self.allocator);
defer buf.deinit();
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_sect = text_seg.sections.items[self.text_section_index.?];
for (self.objects.items) |object, object_id| {
const source_seg = object.load_commands.items[object.segment_cmd_index.?].Segment;
const source_sect = source_seg.sections.items[object.text_section_index.?];
const target_mapping = self.mappings.get(.{
.object_id = @intCast(u16, object_id),
.source_sect_id = object.text_section_index.?,
}) orelse continue;
try buf.ensureCapacity(
buf.items.len + object.data_in_code_entries.items.len * @sizeOf(macho.data_in_code_entry),
);
for (object.data_in_code_entries.items) |dice| {
const new_dice: macho.data_in_code_entry = .{
.offset = text_sect.offset + target_mapping.offset + dice.offset,
.length = dice.length,
.kind = dice.kind,
};
buf.appendSliceAssumeCapacity(mem.asBytes(&new_dice));
}
}
const datasize = @intCast(u32, buf.items.len);
dice_cmd.dataoff = @intCast(u32, fileoff);
dice_cmd.datasize = datasize;
seg.inner.filesize += datasize;
log.debug("writing data-in-code from 0x{x} to 0x{x}", .{ fileoff, fileoff + datasize });
try self.file.?.pwriteAll(buf.items, fileoff);
}
fn writeCodeSignaturePadding(self: *Zld) !void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const code_sig_cmd = &self.load_commands.items[self.code_signature_cmd_index.?].LinkeditData;
const fileoff = seg.inner.fileoff + seg.inner.filesize;
const needed_size = CodeSignature.calcCodeSignaturePaddingSize(
self.out_path.?,
fileoff,
self.page_size.?,
);
code_sig_cmd.dataoff = @intCast(u32, fileoff);
code_sig_cmd.datasize = needed_size;
// Advance size of __LINKEDIT segment
seg.inner.filesize += needed_size;
seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size.?);
log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ fileoff, fileoff + needed_size });
// Pad out the space. We need to do this to calculate valid hashes for everything in the file
// except for code signature data.
try self.file.?.pwriteAll(&[_]u8{0}, fileoff + needed_size - 1);
}
fn writeCodeSignature(self: *Zld) !void {
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const code_sig_cmd = self.load_commands.items[self.code_signature_cmd_index.?].LinkeditData;
var code_sig = CodeSignature.init(self.allocator, self.page_size.?);
defer code_sig.deinit();
try code_sig.calcAdhocSignature(
self.file.?,
self.out_path.?,
text_seg.inner,
code_sig_cmd,
.Exe,
);
var buffer = try self.allocator.alloc(u8, code_sig.size());
defer self.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try code_sig.write(stream.writer());
log.debug("writing code signature from 0x{x} to 0x{x}", .{ code_sig_cmd.dataoff, code_sig_cmd.dataoff + buffer.len });
try self.file.?.pwriteAll(buffer, code_sig_cmd.dataoff);
}
fn writeLoadCommands(self: *Zld) !void {
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
var buffer = try self.allocator.alloc(u8, sizeofcmds);
defer self.allocator.free(buffer);
var writer = std.io.fixedBufferStream(buffer).writer();
for (self.load_commands.items) |lc| {
try lc.write(writer);
}
const off = @sizeOf(macho.mach_header_64);
log.debug("writing {} load commands from 0x{x} to 0x{x}", .{ self.load_commands.items.len, off, off + sizeofcmds });
try self.file.?.pwriteAll(buffer, off);
}
fn writeHeader(self: *Zld) !void {
var header: macho.mach_header_64 = undefined;
header.magic = macho.MH_MAGIC_64;
const CpuInfo = struct {
cpu_type: macho.cpu_type_t,
cpu_subtype: macho.cpu_subtype_t,
};
const cpu_info: CpuInfo = switch (self.arch.?) {
.aarch64 => .{
.cpu_type = macho.CPU_TYPE_ARM64,
.cpu_subtype = macho.CPU_SUBTYPE_ARM_ALL,
},
.x86_64 => .{
.cpu_type = macho.CPU_TYPE_X86_64,
.cpu_subtype = macho.CPU_SUBTYPE_X86_64_ALL,
},
else => return error.UnsupportedCpuArchitecture,
};
header.cputype = cpu_info.cpu_type;
header.cpusubtype = cpu_info.cpu_subtype;
header.filetype = macho.MH_EXECUTE;
header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL;
header.reserved = 0;
if (self.tlv_section_index) |_|
header.flags |= macho.MH_HAS_TLV_DESCRIPTORS;
header.ncmds = @intCast(u32, self.load_commands.items.len);
header.sizeofcmds = 0;
for (self.load_commands.items) |cmd| {
header.sizeofcmds += cmd.cmdsize();
}
log.debug("writing Mach-O header {}", .{header});
try self.file.?.pwriteAll(mem.asBytes(&header), 0);
}
pub fn makeStaticString(bytes: []const u8) [16]u8 {
var buf = [_]u8{0} ** 16;
assert(bytes.len <= buf.len);
mem.copy(u8, &buf, bytes);
return buf;
}
fn makeString(self: *Zld, bytes: []const u8) !u32 {
if (self.strtab_dir.get(bytes)) |offset| {
log.debug("reusing '{s}' from string table at offset 0x{x}", .{ bytes, offset });
return offset;
}
try self.strtab.ensureCapacity(self.allocator, self.strtab.items.len + bytes.len + 1);
const offset = @intCast(u32, self.strtab.items.len);
log.debug("writing new string '{s}' into string table at offset 0x{x}", .{ bytes, offset });
self.strtab.appendSliceAssumeCapacity(bytes);
self.strtab.appendAssumeCapacity(0);
try self.strtab_dir.putNoClobber(self.allocator, try self.allocator.dupe(u8, bytes), offset);
return offset;
}
fn getString(self: *const Zld, str_off: u32) []const u8 {
assert(str_off < self.strtab.items.len);
return mem.spanZ(@ptrCast([*:0]const u8, self.strtab.items.ptr + str_off));
}
pub fn parseName(name: *const [16]u8) []const u8 {
const len = mem.indexOfScalar(u8, name, @as(u8, 0)) orelse name.len;
return name[0..len];
}
fn printSymbols(self: *Zld) void {
log.debug("globals", .{});
for (self.globals.items()) |entry| {
const sym = entry.value.cast(Symbol.Regular) orelse unreachable;
log.debug(" | {s} @ {*}", .{ sym.base.name, entry.value });
log.debug(" => alias of {*}", .{sym.base.alias});
log.debug(" => linkage {s}", .{sym.linkage});
log.debug(" => defined in {s}", .{sym.file.name.?});
}
for (self.objects.items) |object| {
log.debug("locals in {s}", .{object.name.?});
for (object.symbols.items) |sym| {
log.debug(" | {s} @ {*}", .{ sym.name, sym });
log.debug(" => alias of {*}", .{sym.alias});
if (sym.cast(Symbol.Regular)) |reg| {
log.debug(" => linkage {s}", .{reg.linkage});
} else {
log.debug(" => unresolved", .{});
}
}
}
log.debug("proxies", .{});
for (self.imports.items()) |entry| {
const sym = entry.value.cast(Symbol.Proxy) orelse unreachable;
log.debug(" | {s} @ {*}", .{ sym.base.name, entry.value });
log.debug(" => alias of {*}", .{sym.base.alias});
log.debug(" => defined in libSystem.B.dylib", .{});
}
}
|
src/link/MachO/Zld.zig
|
const builtin = @import("builtin");
const testing = @import("std").testing;
const udivmod = @import("udivmod.zig").udivmod;
pub fn __divmoddi4(a: i64, b: i64, rem: *i64) callconv(.C) i64 {
@setRuntimeSafety(builtin.is_test);
const d = __divdi3(a, b);
rem.* = a -% (d *% b);
return d;
}
pub fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?*u64) callconv(.C) u64 {
@setRuntimeSafety(builtin.is_test);
return udivmod(u64, a, b, maybe_rem);
}
test "test_udivmoddi4" {
_ = @import("udivmoddi4_test.zig");
}
pub fn __divdi3(a: i64, b: i64) callconv(.C) i64 {
@setRuntimeSafety(builtin.is_test);
// Set aside the sign of the quotient.
const sign = @bitCast(u64, (a ^ b) >> 63);
// Take absolute value of a and b via abs(x) = (x^(x >> 63)) - (x >> 63).
const abs_a = (a ^ (a >> 63)) -% (a >> 63);
const abs_b = (b ^ (b >> 63)) -% (b >> 63);
// Unsigned division
const res = __udivmoddi4(@bitCast(u64, abs_a), @bitCast(u64, abs_b), null);
// Apply sign of quotient to result and return.
return @bitCast(i64, (res ^ sign) -% sign);
}
test "test_divdi3" {
const cases = [_][3]i64{
[_]i64{ 0, 1, 0 },
[_]i64{ 0, -1, 0 },
[_]i64{ 2, 1, 2 },
[_]i64{ 2, -1, -2 },
[_]i64{ -2, 1, -2 },
[_]i64{ -2, -1, 2 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, @bitCast(i64, @as(u64, 0x8000000000000000)) },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, @bitCast(i64, @as(u64, 0x8000000000000000)) },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0x4000000000000000 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, @bitCast(i64, @as(u64, 0xC000000000000000)) },
};
for (cases) |case| {
test_one_divdi3(case[0], case[1], case[2]);
}
}
fn test_one_divdi3(a: i64, b: i64, expected_q: i64) void {
const q: i64 = __divdi3(a, b);
testing.expect(q == expected_q);
}
pub fn __moddi3(a: i64, b: i64) callconv(.C) i64 {
@setRuntimeSafety(builtin.is_test);
// Take absolute value of a and b via abs(x) = (x^(x >> 63)) - (x >> 63).
const abs_a = (a ^ (a >> 63)) -% (a >> 63);
const abs_b = (b ^ (b >> 63)) -% (b >> 63);
// Unsigned division
var r: u64 = undefined;
_ = __udivmoddi4(@bitCast(u64, abs_a), @bitCast(u64, abs_b), &r);
// Apply the sign of the dividend and return.
return (@bitCast(i64, r) ^ (a >> 63)) -% (a >> 63);
}
test "test_moddi3" {
const cases = [_][3]i64{
[_]i64{ 0, 1, 0 },
[_]i64{ 0, -1, 0 },
[_]i64{ 5, 3, 2 },
[_]i64{ 5, -3, 2 },
[_]i64{ -5, 3, -2 },
[_]i64{ -5, -3, -2 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, 0 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, 0 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, 0 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 3, -2 },
[_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -3, -2 },
};
for (cases) |case| {
test_one_moddi3(case[0], case[1], case[2]);
}
}
fn test_one_moddi3(a: i64, b: i64, expected_r: i64) void {
const r: i64 = __moddi3(a, b);
testing.expect(r == expected_r);
}
pub fn __udivdi3(a: u64, b: u64) callconv(.C) u64 {
@setRuntimeSafety(builtin.is_test);
return __udivmoddi4(a, b, null);
}
pub fn __umoddi3(a: u64, b: u64) callconv(.C) u64 {
@setRuntimeSafety(builtin.is_test);
var r: u64 = undefined;
_ = __udivmoddi4(a, b, &r);
return r;
}
test "test_umoddi3" {
test_one_umoddi3(0, 1, 0);
test_one_umoddi3(2, 1, 0);
test_one_umoddi3(0x8000000000000000, 1, 0x0);
test_one_umoddi3(0x8000000000000000, 2, 0x0);
test_one_umoddi3(0xFFFFFFFFFFFFFFFF, 2, 0x1);
}
fn test_one_umoddi3(a: u64, b: u64, expected_r: u64) void {
const r = __umoddi3(a, b);
testing.expect(r == expected_r);
}
pub fn __divmodsi4(a: i32, b: i32, rem: *i32) callconv(.C) i32 {
@setRuntimeSafety(builtin.is_test);
const d = __divsi3(a, b);
rem.* = a -% (d * b);
return d;
}
test "test_divmodsi4" {
const cases = [_][4]i32{
[_]i32{ 0, 1, 0, 0 },
[_]i32{ 0, -1, 0, 0 },
[_]i32{ 2, 1, 2, 0 },
[_]i32{ 2, -1, -2, 0 },
[_]i32{ -2, 1, -2, 0 },
[_]i32{ -2, -1, 2, 0 },
[_]i32{ 7, 5, 1, 2 },
[_]i32{ -7, 5, -1, -2 },
[_]i32{ 19, 5, 3, 4 },
[_]i32{ 19, -5, -3, 4 },
[_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 8, @bitCast(i32, @as(u32, 0xf0000000)), 0 },
[_]i32{ @bitCast(i32, @as(u32, 0x80000007)), 8, @bitCast(i32, @as(u32, 0xf0000001)), -1 },
};
for (cases) |case| {
test_one_divmodsi4(case[0], case[1], case[2], case[3]);
}
}
fn test_one_divmodsi4(a: i32, b: i32, expected_q: i32, expected_r: i32) void {
var r: i32 = undefined;
const q: i32 = __divmodsi4(a, b, &r);
testing.expect(q == expected_q and r == expected_r);
}
pub fn __udivmodsi4(a: u32, b: u32, rem: *u32) callconv(.C) u32 {
@setRuntimeSafety(builtin.is_test);
const d = __udivsi3(a, b);
rem.* = @bitCast(u32, @bitCast(i32, a) -% (@bitCast(i32, d) * @bitCast(i32, b)));
return d;
}
pub fn __divsi3(n: i32, d: i32) callconv(.C) i32 {
@setRuntimeSafety(builtin.is_test);
// Set aside the sign of the quotient.
const sign = @bitCast(u32, (n ^ d) >> 31);
// Take absolute value of a and b via abs(x) = (x^(x >> 31)) - (x >> 31).
const abs_n = (n ^ (n >> 31)) -% (n >> 31);
const abs_d = (d ^ (d >> 31)) -% (d >> 31);
// abs(a) / abs(b)
const res = @bitCast(u32, abs_n) / @bitCast(u32, abs_d);
// Apply sign of quotient to result and return.
return @bitCast(i32, (res ^ sign) -% sign);
}
test "test_divsi3" {
const cases = [_][3]i32{
[_]i32{ 0, 1, 0 },
[_]i32{ 0, -1, 0 },
[_]i32{ 2, 1, 2 },
[_]i32{ 2, -1, -2 },
[_]i32{ -2, 1, -2 },
[_]i32{ -2, -1, 2 },
[_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 1, @bitCast(i32, @as(u32, 0x80000000)) },
[_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -1, @bitCast(i32, @as(u32, 0x80000000)) },
[_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -2, 0x40000000 },
[_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 2, @bitCast(i32, @as(u32, 0xC0000000)) },
};
for (cases) |case| {
test_one_divsi3(case[0], case[1], case[2]);
}
}
fn test_one_divsi3(a: i32, b: i32, expected_q: i32) void {
const q: i32 = __divsi3(a, b);
testing.expect(q == expected_q);
}
pub fn __udivsi3(n: u32, d: u32) callconv(.C) u32 {
@setRuntimeSafety(builtin.is_test);
const n_uword_bits: c_uint = u32.bit_count;
// special cases
if (d == 0) return 0; // ?!
if (n == 0) return 0;
var sr = @bitCast(c_uint, @as(c_int, @clz(u32, d)) - @as(c_int, @clz(u32, n)));
// 0 <= sr <= n_uword_bits - 1 or sr large
if (sr > n_uword_bits - 1) {
// d > r
return 0;
}
if (sr == n_uword_bits - 1) {
// d == 1
return n;
}
sr += 1;
// 1 <= sr <= n_uword_bits - 1
// Not a special case
var q: u32 = n << @intCast(u5, n_uword_bits - sr);
var r: u32 = n >> @intCast(u5, sr);
var carry: u32 = 0;
while (sr > 0) : (sr -= 1) {
// r:q = ((r:q) << 1) | carry
r = (r << 1) | (q >> @intCast(u5, n_uword_bits - 1));
q = (q << 1) | carry;
// carry = 0;
// if (r.all >= d.all)
// {
// r.all -= d.all;
// carry = 1;
// }
const s = @intCast(i32, d -% r -% 1) >> @intCast(u5, n_uword_bits - 1);
carry = @intCast(u32, s & 1);
r -= d & @bitCast(u32, s);
}
q = (q << 1) | carry;
return q;
}
test "test_udivsi3" {
const cases = [_][3]u32{
[_]u32{ 0x00000000, 0x00000001, 0x00000000 },
[_]u32{ 0x00000000, 0x00000002, 0x00000000 },
[_]u32{ 0x00000000, 0x00000003, 0x00000000 },
[_]u32{ 0x00000000, 0x00000010, 0x00000000 },
[_]u32{ 0x00000000, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000000, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000000, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000000, 0x80000000, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x00000001, 0x00000001, 0x00000001 },
[_]u32{ 0x00000001, 0x00000002, 0x00000000 },
[_]u32{ 0x00000001, 0x00000003, 0x00000000 },
[_]u32{ 0x00000001, 0x00000010, 0x00000000 },
[_]u32{ 0x00000001, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000001, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000001, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000001, 0x80000000, 0x00000000 },
[_]u32{ 0x00000001, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000001, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000001, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x00000002, 0x00000001, 0x00000002 },
[_]u32{ 0x00000002, 0x00000002, 0x00000001 },
[_]u32{ 0x00000002, 0x00000003, 0x00000000 },
[_]u32{ 0x00000002, 0x00000010, 0x00000000 },
[_]u32{ 0x00000002, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000002, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000002, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000002, 0x80000000, 0x00000000 },
[_]u32{ 0x00000002, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000002, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000002, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x00000003, 0x00000001, 0x00000003 },
[_]u32{ 0x00000003, 0x00000002, 0x00000001 },
[_]u32{ 0x00000003, 0x00000003, 0x00000001 },
[_]u32{ 0x00000003, 0x00000010, 0x00000000 },
[_]u32{ 0x00000003, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000003, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000003, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000003, 0x80000000, 0x00000000 },
[_]u32{ 0x00000003, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000003, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000003, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x00000010, 0x00000001, 0x00000010 },
[_]u32{ 0x00000010, 0x00000002, 0x00000008 },
[_]u32{ 0x00000010, 0x00000003, 0x00000005 },
[_]u32{ 0x00000010, 0x00000010, 0x00000001 },
[_]u32{ 0x00000010, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000010, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000010, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000010, 0x80000000, 0x00000000 },
[_]u32{ 0x00000010, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000010, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000010, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x078644FA, 0x00000001, 0x078644FA },
[_]u32{ 0x078644FA, 0x00000002, 0x03C3227D },
[_]u32{ 0x078644FA, 0x00000003, 0x028216FE },
[_]u32{ 0x078644FA, 0x00000010, 0x0078644F },
[_]u32{ 0x078644FA, 0x078644FA, 0x00000001 },
[_]u32{ 0x078644FA, 0x0747AE14, 0x00000001 },
[_]u32{ 0x078644FA, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x078644FA, 0x80000000, 0x00000000 },
[_]u32{ 0x078644FA, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x078644FA, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x078644FA, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x0747AE14, 0x00000001, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0x00000002, 0x03A3D70A },
[_]u32{ 0x0747AE14, 0x00000003, 0x026D3A06 },
[_]u32{ 0x0747AE14, 0x00000010, 0x00747AE1 },
[_]u32{ 0x0747AE14, 0x078644FA, 0x00000000 },
[_]u32{ 0x0747AE14, 0x0747AE14, 0x00000001 },
[_]u32{ 0x0747AE14, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x0747AE14, 0x80000000, 0x00000000 },
[_]u32{ 0x0747AE14, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x0747AE14, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x0747AE14, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0x00000001, 0x7FFFFFFF },
[_]u32{ 0x7FFFFFFF, 0x00000002, 0x3FFFFFFF },
[_]u32{ 0x7FFFFFFF, 0x00000003, 0x2AAAAAAA },
[_]u32{ 0x7FFFFFFF, 0x00000010, 0x07FFFFFF },
[_]u32{ 0x7FFFFFFF, 0x078644FA, 0x00000011 },
[_]u32{ 0x7FFFFFFF, 0x0747AE14, 0x00000011 },
[_]u32{ 0x7FFFFFFF, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0x7FFFFFFF, 0x80000000, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x80000000, 0x00000001, 0x80000000 },
[_]u32{ 0x80000000, 0x00000002, 0x40000000 },
[_]u32{ 0x80000000, 0x00000003, 0x2AAAAAAA },
[_]u32{ 0x80000000, 0x00000010, 0x08000000 },
[_]u32{ 0x80000000, 0x078644FA, 0x00000011 },
[_]u32{ 0x80000000, 0x0747AE14, 0x00000011 },
[_]u32{ 0x80000000, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0x80000000, 0x80000000, 0x00000001 },
[_]u32{ 0x80000000, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x80000000, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x80000000, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0xFFFFFFFD, 0x00000001, 0xFFFFFFFD },
[_]u32{ 0xFFFFFFFD, 0x00000002, 0x7FFFFFFE },
[_]u32{ 0xFFFFFFFD, 0x00000003, 0x55555554 },
[_]u32{ 0xFFFFFFFD, 0x00000010, 0x0FFFFFFF },
[_]u32{ 0xFFFFFFFD, 0x078644FA, 0x00000022 },
[_]u32{ 0xFFFFFFFD, 0x0747AE14, 0x00000023 },
[_]u32{ 0xFFFFFFFD, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0xFFFFFFFD, 0x80000000, 0x00000001 },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFD, 0x00000001 },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0xFFFFFFFE, 0x00000001, 0xFFFFFFFE },
[_]u32{ 0xFFFFFFFE, 0x00000002, 0x7FFFFFFF },
[_]u32{ 0xFFFFFFFE, 0x00000003, 0x55555554 },
[_]u32{ 0xFFFFFFFE, 0x00000010, 0x0FFFFFFF },
[_]u32{ 0xFFFFFFFE, 0x078644FA, 0x00000022 },
[_]u32{ 0xFFFFFFFE, 0x0747AE14, 0x00000023 },
[_]u32{ 0xFFFFFFFE, 0x7FFFFFFF, 0x00000002 },
[_]u32{ 0xFFFFFFFE, 0x80000000, 0x00000001 },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFD, 0x00000001 },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFE, 0x00000001 },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF },
[_]u32{ 0xFFFFFFFF, 0x00000002, 0x7FFFFFFF },
[_]u32{ 0xFFFFFFFF, 0x00000003, 0x55555555 },
[_]u32{ 0xFFFFFFFF, 0x00000010, 0x0FFFFFFF },
[_]u32{ 0xFFFFFFFF, 0x078644FA, 0x00000022 },
[_]u32{ 0xFFFFFFFF, 0x0747AE14, 0x00000023 },
[_]u32{ 0xFFFFFFFF, 0x7FFFFFFF, 0x00000002 },
[_]u32{ 0xFFFFFFFF, 0x80000000, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFD, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFE, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001 },
};
for (cases) |case| {
test_one_udivsi3(case[0], case[1], case[2]);
}
}
fn test_one_udivsi3(a: u32, b: u32, expected_q: u32) void {
const q: u32 = __udivsi3(a, b);
testing.expect(q == expected_q);
}
pub fn __modsi3(n: i32, d: i32) callconv(.C) i32 {
@setRuntimeSafety(builtin.is_test);
return n -% __divsi3(n, d) *% d;
}
test "test_modsi3" {
const cases = [_][3]i32{
[_]i32{ 0, 1, 0 },
[_]i32{ 0, -1, 0 },
[_]i32{ 5, 3, 2 },
[_]i32{ 5, -3, 2 },
[_]i32{ -5, 3, -2 },
[_]i32{ -5, -3, -2 },
[_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 1, 0x0 },
[_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 2, 0x0 },
[_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), -2, 0x0 },
[_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 3, -2 },
[_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), -3, -2 },
};
for (cases) |case| {
test_one_modsi3(case[0], case[1], case[2]);
}
}
fn test_one_modsi3(a: i32, b: i32, expected_r: i32) void {
const r: i32 = __modsi3(a, b);
testing.expect(r == expected_r);
}
pub fn __umodsi3(n: u32, d: u32) callconv(.C) u32 {
@setRuntimeSafety(builtin.is_test);
return n -% __udivsi3(n, d) *% d;
}
test "test_umodsi3" {
const cases = [_][3]u32{
[_]u32{ 0x00000000, 0x00000001, 0x00000000 },
[_]u32{ 0x00000000, 0x00000002, 0x00000000 },
[_]u32{ 0x00000000, 0x00000003, 0x00000000 },
[_]u32{ 0x00000000, 0x00000010, 0x00000000 },
[_]u32{ 0x00000000, 0x078644FA, 0x00000000 },
[_]u32{ 0x00000000, 0x0747AE14, 0x00000000 },
[_]u32{ 0x00000000, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x00000000, 0x80000000, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0x00000000, 0xFFFFFFFF, 0x00000000 },
[_]u32{ 0x00000001, 0x00000001, 0x00000000 },
[_]u32{ 0x00000001, 0x00000002, 0x00000001 },
[_]u32{ 0x00000001, 0x00000003, 0x00000001 },
[_]u32{ 0x00000001, 0x00000010, 0x00000001 },
[_]u32{ 0x00000001, 0x078644FA, 0x00000001 },
[_]u32{ 0x00000001, 0x0747AE14, 0x00000001 },
[_]u32{ 0x00000001, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0x00000001, 0x80000000, 0x00000001 },
[_]u32{ 0x00000001, 0xFFFFFFFD, 0x00000001 },
[_]u32{ 0x00000001, 0xFFFFFFFE, 0x00000001 },
[_]u32{ 0x00000001, 0xFFFFFFFF, 0x00000001 },
[_]u32{ 0x00000002, 0x00000001, 0x00000000 },
[_]u32{ 0x00000002, 0x00000002, 0x00000000 },
[_]u32{ 0x00000002, 0x00000003, 0x00000002 },
[_]u32{ 0x00000002, 0x00000010, 0x00000002 },
[_]u32{ 0x00000002, 0x078644FA, 0x00000002 },
[_]u32{ 0x00000002, 0x0747AE14, 0x00000002 },
[_]u32{ 0x00000002, 0x7FFFFFFF, 0x00000002 },
[_]u32{ 0x00000002, 0x80000000, 0x00000002 },
[_]u32{ 0x00000002, 0xFFFFFFFD, 0x00000002 },
[_]u32{ 0x00000002, 0xFFFFFFFE, 0x00000002 },
[_]u32{ 0x00000002, 0xFFFFFFFF, 0x00000002 },
[_]u32{ 0x00000003, 0x00000001, 0x00000000 },
[_]u32{ 0x00000003, 0x00000002, 0x00000001 },
[_]u32{ 0x00000003, 0x00000003, 0x00000000 },
[_]u32{ 0x00000003, 0x00000010, 0x00000003 },
[_]u32{ 0x00000003, 0x078644FA, 0x00000003 },
[_]u32{ 0x00000003, 0x0747AE14, 0x00000003 },
[_]u32{ 0x00000003, 0x7FFFFFFF, 0x00000003 },
[_]u32{ 0x00000003, 0x80000000, 0x00000003 },
[_]u32{ 0x00000003, 0xFFFFFFFD, 0x00000003 },
[_]u32{ 0x00000003, 0xFFFFFFFE, 0x00000003 },
[_]u32{ 0x00000003, 0xFFFFFFFF, 0x00000003 },
[_]u32{ 0x00000010, 0x00000001, 0x00000000 },
[_]u32{ 0x00000010, 0x00000002, 0x00000000 },
[_]u32{ 0x00000010, 0x00000003, 0x00000001 },
[_]u32{ 0x00000010, 0x00000010, 0x00000000 },
[_]u32{ 0x00000010, 0x078644FA, 0x00000010 },
[_]u32{ 0x00000010, 0x0747AE14, 0x00000010 },
[_]u32{ 0x00000010, 0x7FFFFFFF, 0x00000010 },
[_]u32{ 0x00000010, 0x80000000, 0x00000010 },
[_]u32{ 0x00000010, 0xFFFFFFFD, 0x00000010 },
[_]u32{ 0x00000010, 0xFFFFFFFE, 0x00000010 },
[_]u32{ 0x00000010, 0xFFFFFFFF, 0x00000010 },
[_]u32{ 0x078644FA, 0x00000001, 0x00000000 },
[_]u32{ 0x078644FA, 0x00000002, 0x00000000 },
[_]u32{ 0x078644FA, 0x00000003, 0x00000000 },
[_]u32{ 0x078644FA, 0x00000010, 0x0000000A },
[_]u32{ 0x078644FA, 0x078644FA, 0x00000000 },
[_]u32{ 0x078644FA, 0x0747AE14, 0x003E96E6 },
[_]u32{ 0x078644FA, 0x7FFFFFFF, 0x078644FA },
[_]u32{ 0x078644FA, 0x80000000, 0x078644FA },
[_]u32{ 0x078644FA, 0xFFFFFFFD, 0x078644FA },
[_]u32{ 0x078644FA, 0xFFFFFFFE, 0x078644FA },
[_]u32{ 0x078644FA, 0xFFFFFFFF, 0x078644FA },
[_]u32{ 0x0747AE14, 0x00000001, 0x00000000 },
[_]u32{ 0x0747AE14, 0x00000002, 0x00000000 },
[_]u32{ 0x0747AE14, 0x00000003, 0x00000002 },
[_]u32{ 0x0747AE14, 0x00000010, 0x00000004 },
[_]u32{ 0x0747AE14, 0x078644FA, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0x0747AE14, 0x00000000 },
[_]u32{ 0x0747AE14, 0x7FFFFFFF, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0x80000000, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0xFFFFFFFD, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0xFFFFFFFE, 0x0747AE14 },
[_]u32{ 0x0747AE14, 0xFFFFFFFF, 0x0747AE14 },
[_]u32{ 0x7FFFFFFF, 0x00000001, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0x00000002, 0x00000001 },
[_]u32{ 0x7FFFFFFF, 0x00000003, 0x00000001 },
[_]u32{ 0x7FFFFFFF, 0x00000010, 0x0000000F },
[_]u32{ 0x7FFFFFFF, 0x078644FA, 0x00156B65 },
[_]u32{ 0x7FFFFFFF, 0x0747AE14, 0x043D70AB },
[_]u32{ 0x7FFFFFFF, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFD, 0x7FFFFFFF },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFE, 0x7FFFFFFF },
[_]u32{ 0x7FFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF },
[_]u32{ 0x80000000, 0x00000001, 0x00000000 },
[_]u32{ 0x80000000, 0x00000002, 0x00000000 },
[_]u32{ 0x80000000, 0x00000003, 0x00000002 },
[_]u32{ 0x80000000, 0x00000010, 0x00000000 },
[_]u32{ 0x80000000, 0x078644FA, 0x00156B66 },
[_]u32{ 0x80000000, 0x0747AE14, 0x043D70AC },
[_]u32{ 0x80000000, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0x80000000, 0x80000000, 0x00000000 },
[_]u32{ 0x80000000, 0xFFFFFFFD, 0x80000000 },
[_]u32{ 0x80000000, 0xFFFFFFFE, 0x80000000 },
[_]u32{ 0x80000000, 0xFFFFFFFF, 0x80000000 },
[_]u32{ 0xFFFFFFFD, 0x00000001, 0x00000000 },
[_]u32{ 0xFFFFFFFD, 0x00000002, 0x00000001 },
[_]u32{ 0xFFFFFFFD, 0x00000003, 0x00000001 },
[_]u32{ 0xFFFFFFFD, 0x00000010, 0x0000000D },
[_]u32{ 0xFFFFFFFD, 0x078644FA, 0x002AD6C9 },
[_]u32{ 0xFFFFFFFD, 0x0747AE14, 0x01333341 },
[_]u32{ 0xFFFFFFFD, 0x7FFFFFFF, 0x7FFFFFFE },
[_]u32{ 0xFFFFFFFD, 0x80000000, 0x7FFFFFFD },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFD, 0x00000000 },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFE, 0xFFFFFFFD },
[_]u32{ 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFD },
[_]u32{ 0xFFFFFFFE, 0x00000001, 0x00000000 },
[_]u32{ 0xFFFFFFFE, 0x00000002, 0x00000000 },
[_]u32{ 0xFFFFFFFE, 0x00000003, 0x00000002 },
[_]u32{ 0xFFFFFFFE, 0x00000010, 0x0000000E },
[_]u32{ 0xFFFFFFFE, 0x078644FA, 0x002AD6CA },
[_]u32{ 0xFFFFFFFE, 0x0747AE14, 0x01333342 },
[_]u32{ 0xFFFFFFFE, 0x7FFFFFFF, 0x00000000 },
[_]u32{ 0xFFFFFFFE, 0x80000000, 0x7FFFFFFE },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFD, 0x00000001 },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFE, 0x00000000 },
[_]u32{ 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFE },
[_]u32{ 0xFFFFFFFF, 0x00000001, 0x00000000 },
[_]u32{ 0xFFFFFFFF, 0x00000002, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0x00000003, 0x00000000 },
[_]u32{ 0xFFFFFFFF, 0x00000010, 0x0000000F },
[_]u32{ 0xFFFFFFFF, 0x078644FA, 0x002AD6CB },
[_]u32{ 0xFFFFFFFF, 0x0747AE14, 0x01333343 },
[_]u32{ 0xFFFFFFFF, 0x7FFFFFFF, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFD, 0x00000002 },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFE, 0x00000001 },
[_]u32{ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000 },
};
for (cases) |case| {
test_one_umodsi3(case[0], case[1], case[2]);
}
}
fn test_one_umodsi3(a: u32, b: u32, expected_r: u32) void {
const r: u32 = __umodsi3(a, b);
testing.expect(r == expected_r);
}
|
lib/std/special/compiler_rt/int.zig
|
const std = @import("std");
const builtin = std.builtin;
const Log2Int = std.math.Log2Int;
fn Dwords(comptime T: type, comptime signed_half: bool) type {
return extern union {
pub const HalfTU = std.meta.IntType(false, @divExact(T.bit_count, 2));
pub const HalfTS = std.meta.IntType(true, @divExact(T.bit_count, 2));
pub const HalfT = if (signed_half) HalfTS else HalfTU;
all: T,
s: if (builtin.endian == .Little)
struct { low: HalfT, high: HalfT }
else
struct { high: HalfT, low: HalfT },
};
}
// Arithmetic shift left
// Precondition: 0 <= b < bits_in_dword
pub fn ashlXi3(comptime T: type, a: T, b: i32) T {
const dwords = Dwords(T, false);
const S = Log2Int(dwords.HalfT);
const input = dwords{ .all = a };
var output: dwords = undefined;
if (b >= dwords.HalfT.bit_count) {
output.s.low = 0;
output.s.high = input.s.low << @intCast(S, b - dwords.HalfT.bit_count);
} else if (b == 0) {
return a;
} else {
output.s.low = input.s.low << @intCast(S, b);
output.s.high = input.s.high << @intCast(S, b);
output.s.high |= input.s.low >> @intCast(S, dwords.HalfT.bit_count - b);
}
return output.all;
}
// Arithmetic shift right
// Precondition: 0 <= b < T.bit_count
pub fn ashrXi3(comptime T: type, a: T, b: i32) T {
const dwords = Dwords(T, true);
const S = Log2Int(dwords.HalfT);
const input = dwords{ .all = a };
var output: dwords = undefined;
if (b >= dwords.HalfT.bit_count) {
output.s.high = input.s.high >> (dwords.HalfT.bit_count - 1);
output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count);
} else if (b == 0) {
return a;
} else {
output.s.high = input.s.high >> @intCast(S, b);
output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b);
// Avoid sign-extension here
output.s.low |= @bitCast(
dwords.HalfT,
@bitCast(dwords.HalfTU, input.s.low) >> @intCast(S, b),
);
}
return output.all;
}
// Logical shift right
// Precondition: 0 <= b < T.bit_count
pub fn lshrXi3(comptime T: type, a: T, b: i32) T {
const dwords = Dwords(T, false);
const S = Log2Int(dwords.HalfT);
const input = dwords{ .all = a };
var output: dwords = undefined;
if (b >= dwords.HalfT.bit_count) {
output.s.high = 0;
output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count);
} else if (b == 0) {
return a;
} else {
output.s.high = input.s.high >> @intCast(S, b);
output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b);
output.s.low |= input.s.low >> @intCast(S, b);
}
return output.all;
}
pub fn __ashldi3(a: i64, b: i32) callconv(.C) i64 {
return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i64, a, b });
}
pub fn __ashlti3(a: i128, b: i32) callconv(.C) i128 {
return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i128, a, b });
}
pub fn __ashrdi3(a: i64, b: i32) callconv(.C) i64 {
return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i64, a, b });
}
pub fn __ashrti3(a: i128, b: i32) callconv(.C) i128 {
return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i128, a, b });
}
pub fn __lshrdi3(a: i64, b: i32) callconv(.C) i64 {
return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i64, a, b });
}
pub fn __lshrti3(a: i128, b: i32) callconv(.C) i128 {
return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i128, a, b });
}
pub fn __aeabi_llsl(a: i64, b: i32) callconv(.AAPCS) i64 {
return __ashldi3(a, b);
}
pub fn __aeabi_lasr(a: i64, b: i32) callconv(.AAPCS) i64 {
return __ashrdi3(a, b);
}
pub fn __aeabi_llsr(a: i64, b: i32) callconv(.AAPCS) i64 {
return __lshrdi3(a, b);
}
test "" {
_ = @import("ashrdi3_test.zig");
_ = @import("ashrti3_test.zig");
_ = @import("ashldi3_test.zig");
_ = @import("ashlti3_test.zig");
_ = @import("lshrdi3_test.zig");
_ = @import("lshrti3_test.zig");
}
|
lib/std/special/compiler_rt/shift.zig
|
const std = @import("../../../std.zig");
const linux = std.os.linux;
const socklen_t = linux.socklen_t;
const iovec = linux.iovec;
const iovec_const = linux.iovec_const;
const uid_t = linux.uid_t;
const gid_t = linux.gid_t;
pub const SYS_Linux = 4000;
pub const SYS_syscall = (SYS_Linux + 0);
pub const SYS_exit = (SYS_Linux + 1);
pub const SYS_fork = (SYS_Linux + 2);
pub const SYS_read = (SYS_Linux + 3);
pub const SYS_write = (SYS_Linux + 4);
pub const SYS_open = (SYS_Linux + 5);
pub const SYS_close = (SYS_Linux + 6);
pub const SYS_waitpid = (SYS_Linux + 7);
pub const SYS_creat = (SYS_Linux + 8);
pub const SYS_link = (SYS_Linux + 9);
pub const SYS_unlink = (SYS_Linux + 10);
pub const SYS_execve = (SYS_Linux + 11);
pub const SYS_chdir = (SYS_Linux + 12);
pub const SYS_time = (SYS_Linux + 13);
pub const SYS_mknod = (SYS_Linux + 14);
pub const SYS_chmod = (SYS_Linux + 15);
pub const SYS_lchown = (SYS_Linux + 16);
pub const SYS_break = (SYS_Linux + 17);
pub const SYS_unused18 = (SYS_Linux + 18);
pub const SYS_lseek = (SYS_Linux + 19);
pub const SYS_getpid = (SYS_Linux + 20);
pub const SYS_mount = (SYS_Linux + 21);
pub const SYS_umount = (SYS_Linux + 22);
pub const SYS_setuid = (SYS_Linux + 23);
pub const SYS_getuid = (SYS_Linux + 24);
pub const SYS_stime = (SYS_Linux + 25);
pub const SYS_ptrace = (SYS_Linux + 26);
pub const SYS_alarm = (SYS_Linux + 27);
pub const SYS_unused28 = (SYS_Linux + 28);
pub const SYS_pause = (SYS_Linux + 29);
pub const SYS_utime = (SYS_Linux + 30);
pub const SYS_stty = (SYS_Linux + 31);
pub const SYS_gtty = (SYS_Linux + 32);
pub const SYS_access = (SYS_Linux + 33);
pub const SYS_nice = (SYS_Linux + 34);
pub const SYS_ftime = (SYS_Linux + 35);
pub const SYS_sync = (SYS_Linux + 36);
pub const SYS_kill = (SYS_Linux + 37);
pub const SYS_rename = (SYS_Linux + 38);
pub const SYS_mkdir = (SYS_Linux + 39);
pub const SYS_rmdir = (SYS_Linux + 40);
pub const SYS_dup = (SYS_Linux + 41);
pub const SYS_pipe = (SYS_Linux + 42);
pub const SYS_times = (SYS_Linux + 43);
pub const SYS_prof = (SYS_Linux + 44);
pub const SYS_brk = (SYS_Linux + 45);
pub const SYS_setgid = (SYS_Linux + 46);
pub const SYS_getgid = (SYS_Linux + 47);
pub const SYS_signal = (SYS_Linux + 48);
pub const SYS_geteuid = (SYS_Linux + 49);
pub const SYS_getegid = (SYS_Linux + 50);
pub const SYS_acct = (SYS_Linux + 51);
pub const SYS_umount2 = (SYS_Linux + 52);
pub const SYS_lock = (SYS_Linux + 53);
pub const SYS_ioctl = (SYS_Linux + 54);
pub const SYS_fcntl = (SYS_Linux + 55);
pub const SYS_mpx = (SYS_Linux + 56);
pub const SYS_setpgid = (SYS_Linux + 57);
pub const SYS_ulimit = (SYS_Linux + 58);
pub const SYS_unused59 = (SYS_Linux + 59);
pub const SYS_umask = (SYS_Linux + 60);
pub const SYS_chroot = (SYS_Linux + 61);
pub const SYS_ustat = (SYS_Linux + 62);
pub const SYS_dup2 = (SYS_Linux + 63);
pub const SYS_getppid = (SYS_Linux + 64);
pub const SYS_getpgrp = (SYS_Linux + 65);
pub const SYS_setsid = (SYS_Linux + 66);
pub const SYS_sigaction = (SYS_Linux + 67);
pub const SYS_sgetmask = (SYS_Linux + 68);
pub const SYS_ssetmask = (SYS_Linux + 69);
pub const SYS_setreuid = (SYS_Linux + 70);
pub const SYS_setregid = (SYS_Linux + 71);
pub const SYS_sigsuspend = (SYS_Linux + 72);
pub const SYS_sigpending = (SYS_Linux + 73);
pub const SYS_sethostname = (SYS_Linux + 74);
pub const SYS_setrlimit = (SYS_Linux + 75);
pub const SYS_getrlimit = (SYS_Linux + 76);
pub const SYS_getrusage = (SYS_Linux + 77);
pub const SYS_gettimeofday = (SYS_Linux + 78);
pub const SYS_settimeofday = (SYS_Linux + 79);
pub const SYS_getgroups = (SYS_Linux + 80);
pub const SYS_setgroups = (SYS_Linux + 81);
pub const SYS_reserved82 = (SYS_Linux + 82);
pub const SYS_symlink = (SYS_Linux + 83);
pub const SYS_unused84 = (SYS_Linux + 84);
pub const SYS_readlink = (SYS_Linux + 85);
pub const SYS_uselib = (SYS_Linux + 86);
pub const SYS_swapon = (SYS_Linux + 87);
pub const SYS_reboot = (SYS_Linux + 88);
pub const SYS_readdir = (SYS_Linux + 89);
pub const SYS_mmap = (SYS_Linux + 90);
pub const SYS_munmap = (SYS_Linux + 91);
pub const SYS_truncate = (SYS_Linux + 92);
pub const SYS_ftruncate = (SYS_Linux + 93);
pub const SYS_fchmod = (SYS_Linux + 94);
pub const SYS_fchown = (SYS_Linux + 95);
pub const SYS_getpriority = (SYS_Linux + 96);
pub const SYS_setpriority = (SYS_Linux + 97);
pub const SYS_profil = (SYS_Linux + 98);
pub const SYS_statfs = (SYS_Linux + 99);
pub const SYS_fstatfs = (SYS_Linux + 100);
pub const SYS_ioperm = (SYS_Linux + 101);
pub const SYS_socketcall = (SYS_Linux + 102);
pub const SYS_syslog = (SYS_Linux + 103);
pub const SYS_setitimer = (SYS_Linux + 104);
pub const SYS_getitimer = (SYS_Linux + 105);
pub const SYS_stat = (SYS_Linux + 106);
pub const SYS_lstat = (SYS_Linux + 107);
pub const SYS_fstat = (SYS_Linux + 108);
pub const SYS_unused109 = (SYS_Linux + 109);
pub const SYS_iopl = (SYS_Linux + 110);
pub const SYS_vhangup = (SYS_Linux + 111);
pub const SYS_idle = (SYS_Linux + 112);
pub const SYS_vm86 = (SYS_Linux + 113);
pub const SYS_wait4 = (SYS_Linux + 114);
pub const SYS_swapoff = (SYS_Linux + 115);
pub const SYS_sysinfo = (SYS_Linux + 116);
pub const SYS_ipc = (SYS_Linux + 117);
pub const SYS_fsync = (SYS_Linux + 118);
pub const SYS_sigreturn = (SYS_Linux + 119);
pub const SYS_clone = (SYS_Linux + 120);
pub const SYS_setdomainname = (SYS_Linux + 121);
pub const SYS_uname = (SYS_Linux + 122);
pub const SYS_modify_ldt = (SYS_Linux + 123);
pub const SYS_adjtimex = (SYS_Linux + 124);
pub const SYS_mprotect = (SYS_Linux + 125);
pub const SYS_sigprocmask = (SYS_Linux + 126);
pub const SYS_create_module = (SYS_Linux + 127);
pub const SYS_init_module = (SYS_Linux + 128);
pub const SYS_delete_module = (SYS_Linux + 129);
pub const SYS_get_kernel_syms = (SYS_Linux + 130);
pub const SYS_quotactl = (SYS_Linux + 131);
pub const SYS_getpgid = (SYS_Linux + 132);
pub const SYS_fchdir = (SYS_Linux + 133);
pub const SYS_bdflush = (SYS_Linux + 134);
pub const SYS_sysfs = (SYS_Linux + 135);
pub const SYS_personality = (SYS_Linux + 136);
pub const SYS_afs_syscall = (SYS_Linux + 137);
pub const SYS_setfsuid = (SYS_Linux + 138);
pub const SYS_setfsgid = (SYS_Linux + 139);
pub const SYS__llseek = (SYS_Linux + 140);
pub const SYS_getdents = (SYS_Linux + 141);
pub const SYS__newselect = (SYS_Linux + 142);
pub const SYS_flock = (SYS_Linux + 143);
pub const SYS_msync = (SYS_Linux + 144);
pub const SYS_readv = (SYS_Linux + 145);
pub const SYS_writev = (SYS_Linux + 146);
pub const SYS_cacheflush = (SYS_Linux + 147);
pub const SYS_cachectl = (SYS_Linux + 148);
pub const SYS_sysmips = (SYS_Linux + 149);
pub const SYS_unused150 = (SYS_Linux + 150);
pub const SYS_getsid = (SYS_Linux + 151);
pub const SYS_fdatasync = (SYS_Linux + 152);
pub const SYS__sysctl = (SYS_Linux + 153);
pub const SYS_mlock = (SYS_Linux + 154);
pub const SYS_munlock = (SYS_Linux + 155);
pub const SYS_mlockall = (SYS_Linux + 156);
pub const SYS_munlockall = (SYS_Linux + 157);
pub const SYS_sched_setparam = (SYS_Linux + 158);
pub const SYS_sched_getparam = (SYS_Linux + 159);
pub const SYS_sched_setscheduler = (SYS_Linux + 160);
pub const SYS_sched_getscheduler = (SYS_Linux + 161);
pub const SYS_sched_yield = (SYS_Linux + 162);
pub const SYS_sched_get_priority_max = (SYS_Linux + 163);
pub const SYS_sched_get_priority_min = (SYS_Linux + 164);
pub const SYS_sched_rr_get_interval = (SYS_Linux + 165);
pub const SYS_nanosleep = (SYS_Linux + 166);
pub const SYS_mremap = (SYS_Linux + 167);
pub const SYS_accept = (SYS_Linux + 168);
pub const SYS_bind = (SYS_Linux + 169);
pub const SYS_connect = (SYS_Linux + 170);
pub const SYS_getpeername = (SYS_Linux + 171);
pub const SYS_getsockname = (SYS_Linux + 172);
pub const SYS_getsockopt = (SYS_Linux + 173);
pub const SYS_listen = (SYS_Linux + 174);
pub const SYS_recv = (SYS_Linux + 175);
pub const SYS_recvfrom = (SYS_Linux + 176);
pub const SYS_recvmsg = (SYS_Linux + 177);
pub const SYS_send = (SYS_Linux + 178);
pub const SYS_sendmsg = (SYS_Linux + 179);
pub const SYS_sendto = (SYS_Linux + 180);
pub const SYS_setsockopt = (SYS_Linux + 181);
pub const SYS_shutdown = (SYS_Linux + 182);
pub const SYS_socket = (SYS_Linux + 183);
pub const SYS_socketpair = (SYS_Linux + 184);
pub const SYS_setresuid = (SYS_Linux + 185);
pub const SYS_getresuid = (SYS_Linux + 186);
pub const SYS_query_module = (SYS_Linux + 187);
pub const SYS_poll = (SYS_Linux + 188);
pub const SYS_nfsservctl = (SYS_Linux + 189);
pub const SYS_setresgid = (SYS_Linux + 190);
pub const SYS_getresgid = (SYS_Linux + 191);
pub const SYS_prctl = (SYS_Linux + 192);
pub const SYS_rt_sigreturn = (SYS_Linux + 193);
pub const SYS_rt_sigaction = (SYS_Linux + 194);
pub const SYS_rt_sigprocmask = (SYS_Linux + 195);
pub const SYS_rt_sigpending = (SYS_Linux + 196);
pub const SYS_rt_sigtimedwait = (SYS_Linux + 197);
pub const SYS_rt_sigqueueinfo = (SYS_Linux + 198);
pub const SYS_rt_sigsuspend = (SYS_Linux + 199);
pub const SYS_pread64 = (SYS_Linux + 200);
pub const SYS_pwrite64 = (SYS_Linux + 201);
pub const SYS_chown = (SYS_Linux + 202);
pub const SYS_getcwd = (SYS_Linux + 203);
pub const SYS_capget = (SYS_Linux + 204);
pub const SYS_capset = (SYS_Linux + 205);
pub const SYS_sigaltstack = (SYS_Linux + 206);
pub const SYS_sendfile = (SYS_Linux + 207);
pub const SYS_getpmsg = (SYS_Linux + 208);
pub const SYS_putpmsg = (SYS_Linux + 209);
pub const SYS_mmap2 = (SYS_Linux + 210);
pub const SYS_truncate64 = (SYS_Linux + 211);
pub const SYS_ftruncate64 = (SYS_Linux + 212);
pub const SYS_stat64 = (SYS_Linux + 213);
pub const SYS_lstat64 = (SYS_Linux + 214);
pub const SYS_fstat64 = (SYS_Linux + 215);
pub const SYS_pivot_root = (SYS_Linux + 216);
pub const SYS_mincore = (SYS_Linux + 217);
pub const SYS_madvise = (SYS_Linux + 218);
pub const SYS_getdents64 = (SYS_Linux + 219);
pub const SYS_fcntl64 = (SYS_Linux + 220);
pub const SYS_reserved221 = (SYS_Linux + 221);
pub const SYS_gettid = (SYS_Linux + 222);
pub const SYS_readahead = (SYS_Linux + 223);
pub const SYS_setxattr = (SYS_Linux + 224);
pub const SYS_lsetxattr = (SYS_Linux + 225);
pub const SYS_fsetxattr = (SYS_Linux + 226);
pub const SYS_getxattr = (SYS_Linux + 227);
pub const SYS_lgetxattr = (SYS_Linux + 228);
pub const SYS_fgetxattr = (SYS_Linux + 229);
pub const SYS_listxattr = (SYS_Linux + 230);
pub const SYS_llistxattr = (SYS_Linux + 231);
pub const SYS_flistxattr = (SYS_Linux + 232);
pub const SYS_removexattr = (SYS_Linux + 233);
pub const SYS_lremovexattr = (SYS_Linux + 234);
pub const SYS_fremovexattr = (SYS_Linux + 235);
pub const SYS_tkill = (SYS_Linux + 236);
pub const SYS_sendfile64 = (SYS_Linux + 237);
pub const SYS_futex = (SYS_Linux + 238);
pub const SYS_sched_setaffinity = (SYS_Linux + 239);
pub const SYS_sched_getaffinity = (SYS_Linux + 240);
pub const SYS_io_setup = (SYS_Linux + 241);
pub const SYS_io_destroy = (SYS_Linux + 242);
pub const SYS_io_getevents = (SYS_Linux + 243);
pub const SYS_io_submit = (SYS_Linux + 244);
pub const SYS_io_cancel = (SYS_Linux + 245);
pub const SYS_exit_group = (SYS_Linux + 246);
pub const SYS_lookup_dcookie = (SYS_Linux + 247);
pub const SYS_epoll_create = (SYS_Linux + 248);
pub const SYS_epoll_ctl = (SYS_Linux + 249);
pub const SYS_epoll_wait = (SYS_Linux + 250);
pub const SYS_remap_file_pages = (SYS_Linux + 251);
pub const SYS_set_tid_address = (SYS_Linux + 252);
pub const SYS_restart_syscall = (SYS_Linux + 253);
pub const SYS_fadvise64 = (SYS_Linux + 254);
pub const SYS_statfs64 = (SYS_Linux + 255);
pub const SYS_fstatfs64 = (SYS_Linux + 256);
pub const SYS_timer_create = (SYS_Linux + 257);
pub const SYS_timer_settime = (SYS_Linux + 258);
pub const SYS_timer_gettime = (SYS_Linux + 259);
pub const SYS_timer_getoverrun = (SYS_Linux + 260);
pub const SYS_timer_delete = (SYS_Linux + 261);
pub const SYS_clock_settime = (SYS_Linux + 262);
pub const SYS_clock_gettime = (SYS_Linux + 263);
pub const SYS_clock_getres = (SYS_Linux + 264);
pub const SYS_clock_nanosleep = (SYS_Linux + 265);
pub const SYS_tgkill = (SYS_Linux + 266);
pub const SYS_utimes = (SYS_Linux + 267);
pub const SYS_mbind = (SYS_Linux + 268);
pub const SYS_get_mempolicy = (SYS_Linux + 269);
pub const SYS_set_mempolicy = (SYS_Linux + 270);
pub const SYS_mq_open = (SYS_Linux + 271);
pub const SYS_mq_unlink = (SYS_Linux + 272);
pub const SYS_mq_timedsend = (SYS_Linux + 273);
pub const SYS_mq_timedreceive = (SYS_Linux + 274);
pub const SYS_mq_notify = (SYS_Linux + 275);
pub const SYS_mq_getsetattr = (SYS_Linux + 276);
pub const SYS_vserver = (SYS_Linux + 277);
pub const SYS_waitid = (SYS_Linux + 278);
pub const SYS_add_key = (SYS_Linux + 280);
pub const SYS_request_key = (SYS_Linux + 281);
pub const SYS_keyctl = (SYS_Linux + 282);
pub const SYS_set_thread_area = (SYS_Linux + 283);
pub const SYS_inotify_init = (SYS_Linux + 284);
pub const SYS_inotify_add_watch = (SYS_Linux + 285);
pub const SYS_inotify_rm_watch = (SYS_Linux + 286);
pub const SYS_migrate_pages = (SYS_Linux + 287);
pub const SYS_openat = (SYS_Linux + 288);
pub const SYS_mkdirat = (SYS_Linux + 289);
pub const SYS_mknodat = (SYS_Linux + 290);
pub const SYS_fchownat = (SYS_Linux + 291);
pub const SYS_futimesat = (SYS_Linux + 292);
pub const SYS_fstatat64 = (SYS_Linux + 293);
pub const SYS_unlinkat = (SYS_Linux + 294);
pub const SYS_renameat = (SYS_Linux + 295);
pub const SYS_linkat = (SYS_Linux + 296);
pub const SYS_symlinkat = (SYS_Linux + 297);
pub const SYS_readlinkat = (SYS_Linux + 298);
pub const SYS_fchmodat = (SYS_Linux + 299);
pub const SYS_faccessat = (SYS_Linux + 300);
pub const SYS_pselect6 = (SYS_Linux + 301);
pub const SYS_ppoll = (SYS_Linux + 302);
pub const SYS_unshare = (SYS_Linux + 303);
pub const SYS_splice = (SYS_Linux + 304);
pub const SYS_sync_file_range = (SYS_Linux + 305);
pub const SYS_tee = (SYS_Linux + 306);
pub const SYS_vmsplice = (SYS_Linux + 307);
pub const SYS_move_pages = (SYS_Linux + 308);
pub const SYS_set_robust_list = (SYS_Linux + 309);
pub const SYS_get_robust_list = (SYS_Linux + 310);
pub const SYS_kexec_load = (SYS_Linux + 311);
pub const SYS_getcpu = (SYS_Linux + 312);
pub const SYS_epoll_pwait = (SYS_Linux + 313);
pub const SYS_ioprio_set = (SYS_Linux + 314);
pub const SYS_ioprio_get = (SYS_Linux + 315);
pub const SYS_utimensat = (SYS_Linux + 316);
pub const SYS_signalfd = (SYS_Linux + 317);
pub const SYS_timerfd = (SYS_Linux + 318);
pub const SYS_eventfd = (SYS_Linux + 319);
pub const SYS_fallocate = (SYS_Linux + 320);
pub const SYS_timerfd_create = (SYS_Linux + 321);
pub const SYS_timerfd_gettime = (SYS_Linux + 322);
pub const SYS_timerfd_settime = (SYS_Linux + 323);
pub const SYS_signalfd4 = (SYS_Linux + 324);
pub const SYS_eventfd2 = (SYS_Linux + 325);
pub const SYS_epoll_create1 = (SYS_Linux + 326);
pub const SYS_dup3 = (SYS_Linux + 327);
pub const SYS_pipe2 = (SYS_Linux + 328);
pub const SYS_inotify_init1 = (SYS_Linux + 329);
pub const SYS_preadv = (SYS_Linux + 330);
pub const SYS_pwritev = (SYS_Linux + 331);
pub const SYS_rt_tgsigqueueinfo = (SYS_Linux + 332);
pub const SYS_perf_event_open = (SYS_Linux + 333);
pub const SYS_accept4 = (SYS_Linux + 334);
pub const SYS_recvmmsg = (SYS_Linux + 335);
pub const SYS_fanotify_init = (SYS_Linux + 336);
pub const SYS_fanotify_mark = (SYS_Linux + 337);
pub const SYS_prlimit64 = (SYS_Linux + 338);
pub const SYS_name_to_handle_at = (SYS_Linux + 339);
pub const SYS_open_by_handle_at = (SYS_Linux + 340);
pub const SYS_clock_adjtime = (SYS_Linux + 341);
pub const SYS_syncfs = (SYS_Linux + 342);
pub const SYS_sendmmsg = (SYS_Linux + 343);
pub const SYS_setns = (SYS_Linux + 344);
pub const SYS_process_vm_readv = (SYS_Linux + 345);
pub const SYS_process_vm_writev = (SYS_Linux + 346);
pub const SYS_kcmp = (SYS_Linux + 347);
pub const SYS_finit_module = (SYS_Linux + 348);
pub const SYS_sched_setattr = (SYS_Linux + 349);
pub const SYS_sched_getattr = (SYS_Linux + 350);
pub const SYS_renameat2 = (SYS_Linux + 351);
pub const SYS_seccomp = (SYS_Linux + 352);
pub const SYS_getrandom = (SYS_Linux + 353);
pub const SYS_memfd_create = (SYS_Linux + 354);
pub const SYS_bpf = (SYS_Linux + 355);
pub const SYS_execveat = (SYS_Linux + 356);
pub const SYS_userfaultfd = (SYS_Linux + 357);
pub const SYS_membarrier = (SYS_Linux + 358);
pub const SYS_mlock2 = (SYS_Linux + 359);
pub const SYS_copy_file_range = (SYS_Linux + 360);
pub const SYS_preadv2 = (SYS_Linux + 361);
pub const SYS_pwritev2 = (SYS_Linux + 362);
pub const SYS_pkey_mprotect = (SYS_Linux + 363);
pub const SYS_pkey_alloc = (SYS_Linux + 364);
pub const SYS_pkey_free = (SYS_Linux + 365);
pub const SYS_statx = (SYS_Linux + 366);
pub const SYS_rseq = (SYS_Linux + 367);
pub const SYS_io_pgetevents = (SYS_Linux + 368);
pub const SYS_openat2 = (SYS_Linux + 437);
pub const SYS_pidfd_getfd = (SYS_Linux + 438);
pub const O_CREAT = 0o0400;
pub const O_EXCL = 0o02000;
pub const O_NOCTTY = 0o04000;
pub const O_TRUNC = 0o01000;
pub const O_APPEND = 0o0010;
pub const O_NONBLOCK = 0o0200;
pub const O_DSYNC = 0o0020;
pub const O_SYNC = 0o040020;
pub const O_RSYNC = 0o040020;
pub const O_DIRECTORY = 0o0200000;
pub const O_NOFOLLOW = 0o0400000;
pub const O_CLOEXEC = 0o02000000;
pub const O_ASYNC = 0o010000;
pub const O_DIRECT = 0o0100000;
pub const O_LARGEFILE = 0o020000;
pub const O_NOATIME = 0o01000000;
pub const O_PATH = 0o010000000;
pub const O_TMPFILE = 0o020200000;
pub const O_NDELAY = O_NONBLOCK;
pub const F_DUPFD = 0;
pub const F_GETFD = 1;
pub const F_SETFD = 2;
pub const F_GETFL = 3;
pub const F_SETFL = 4;
pub const F_SETOWN = 24;
pub const F_GETOWN = 23;
pub const F_SETSIG = 10;
pub const F_GETSIG = 11;
pub const F_GETLK = 33;
pub const F_SETLK = 34;
pub const F_SETLKW = 35;
pub const F_SETOWN_EX = 15;
pub const F_GETOWN_EX = 16;
pub const F_GETOWNER_UIDS = 17;
pub const MMAP2_UNIT = 4096;
pub const MAP_NORESERVE = 0x0400;
pub const MAP_GROWSDOWN = 0x1000;
pub const MAP_DENYWRITE = 0x2000;
pub const MAP_EXECUTABLE = 0x4000;
pub const MAP_LOCKED = 0x8000;
pub const MAP_32BIT = 0x40;
pub const SO_DEBUG = 1;
pub const SO_REUSEADDR = 0x0004;
pub const SO_KEEPALIVE = 0x0008;
pub const SO_DONTROUTE = 0x0010;
pub const SO_BROADCAST = 0x0020;
pub const SO_LINGER = 0x0080;
pub const SO_OOBINLINE = 0x0100;
pub const SO_REUSEPORT = 0x0200;
pub const SO_SNDBUF = 0x1001;
pub const SO_RCVBUF = 0x1002;
pub const SO_SNDLOWAT = 0x1003;
pub const SO_RCVLOWAT = 0x1004;
pub const SO_RCVTIMEO = 0x1006;
pub const SO_SNDTIMEO = 0x1005;
pub const SO_ERROR = 0x1007;
pub const SO_TYPE = 0x1008;
pub const SO_ACCEPTCONN = 0x1009;
pub const SO_PROTOCOL = 0x1028;
pub const SO_DOMAIN = 0x1029;
pub const SO_NO_CHECK = 11;
pub const SO_PRIORITY = 12;
pub const SO_BSDCOMPAT = 14;
pub const SO_PASSCRED = 17;
pub const SO_PEERCRED = 18;
pub const SO_PEERSEC = 30;
pub const SO_SNDBUFFORCE = 31;
pub const SO_RCVBUFFORCE = 33;
pub const VDSO_CGT_SYM = "__kernel_clock_gettime";
pub const VDSO_CGT_VER = "LINUX_2.6.39";
pub const blksize_t = i32;
pub const nlink_t = u32;
pub const time_t = isize;
pub const mode_t = u32;
pub const off_t = i64;
pub const ino_t = u64;
pub const dev_t = usize;
pub const blkcnt_t = i64;
pub const Stat = extern struct {
dev: u32,
__pad0: [3]u32,
ino: ino_t,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
__pad1: [3]u32,
size: off_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
blksize: blksize_t,
__pad3: [1]u32,
blocks: blkcnt_t,
__pad4: [14]usize,
pub fn atime(self: Stat) timespec {
return self.atim;
}
pub fn mtime(self: Stat) timespec {
return self.mtim;
}
pub fn ctime(self: Stat) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const Elf_Symndx = u32;
|
lib/std/os/bits/linux/mipsel.zig
|