code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const common = @import("common.zig");
const FloatStream = @import("FloatStream.zig");
const isEightDigits = common.isEightDigits;
const Number = common.Number;
/// Parse 8 digits, loaded as bytes in little-endian order.
///
/// This uses the trick where every digit is in [0x030, 0x39],
/// and therefore can be parsed in 3 multiplications, much
/// faster than the normal 8.
///
/// This is based off the algorithm described in "Fast numeric string to
/// int", available here: <https://johnnylee-sde.github.io/Fast-numeric-string-to-int/>.
fn parse8Digits(v_: u64) u64 {
var v = v_;
const mask = 0x0000_00ff_0000_00ff;
const mul1 = 0x000f_4240_0000_0064;
const mul2 = 0x0000_2710_0000_0001;
v -= 0x3030_3030_3030_3030;
v = (v * 10) + (v >> 8); // will not overflow, fits in 63 bits
const v1 = (v & mask) *% mul1;
const v2 = ((v >> 16) & mask) *% mul2;
return @as(u64, @truncate(u32, (v1 +% v2) >> 32));
}
/// Parse digits until a non-digit character is found.
fn tryParseDigits(comptime T: type, stream: *FloatStream, x: *T, comptime base: u8) void {
// Try to parse 8 digits at a time, using an optimized algorithm.
// This only supports decimal digits.
if (base == 10) {
while (stream.hasLen(8)) {
const v = stream.readU64Unchecked();
if (!isEightDigits(v)) {
break;
}
x.* = x.* *% 1_0000_0000 +% parse8Digits(v);
stream.advance(8);
}
}
while (stream.scanDigit(base)) |digit| {
x.* *%= base;
x.* +%= digit;
}
}
fn min_n_digit_int(comptime T: type, digit_count: usize) T {
var n: T = 1;
var i: usize = 1;
while (i < digit_count) : (i += 1) n *= 10;
return n;
}
/// Parse up to N digits
fn tryParseNDigits(comptime T: type, stream: *FloatStream, x: *T, comptime base: u8, comptime n: usize) void {
while (x.* < min_n_digit_int(T, n)) {
if (stream.scanDigit(base)) |digit| {
x.* *%= base;
x.* +%= digit;
} else {
break;
}
}
}
/// Parse the scientific notation component of a float.
fn parseScientific(stream: *FloatStream) ?i64 {
var exponent: i64 = 0;
var negative = false;
if (stream.first()) |c| {
negative = c == '-';
if (c == '-' or c == '+') {
stream.advance(1);
}
}
if (stream.firstIsDigit(10)) {
while (stream.scanDigit(10)) |digit| {
// no overflows here, saturate well before overflow
if (exponent < 0x1000_0000) {
exponent = 10 * exponent + digit;
}
}
return if (negative) -exponent else exponent;
}
return null;
}
const ParseInfo = struct {
// 10 or 16
base: u8,
// 10^19 fits in u64, 16^16 fits in u64
max_mantissa_digits: usize,
// e.g. e or p (E and P also checked)
exp_char_lower: u8,
};
fn parsePartialNumberBase(comptime T: type, stream: *FloatStream, negative: bool, n: *usize, comptime info: ParseInfo) ?Number(T) {
const MantissaT = common.mantissaType(T);
// parse initial digits before dot
var mantissa: MantissaT = 0;
tryParseDigits(MantissaT, stream, &mantissa, info.base);
var int_end = stream.offsetTrue();
var n_digits = @intCast(isize, stream.offsetTrue());
// handle dot with the following digits
var exponent: i64 = 0;
if (stream.firstIs('.')) {
stream.advance(1);
const marker = stream.offsetTrue();
tryParseDigits(MantissaT, stream, &mantissa, info.base);
const n_after_dot = stream.offsetTrue() - marker;
exponent = -@intCast(i64, n_after_dot);
n_digits += @intCast(isize, n_after_dot);
}
// adjust required shift to offset mantissa for base-16 (2^4)
if (info.base == 16) {
exponent *= 4;
}
if (n_digits == 0) {
return null;
}
// handle scientific format
var exp_number: i64 = 0;
if (stream.firstIsLower(info.exp_char_lower)) {
stream.advance(1);
exp_number = parseScientific(stream) orelse return null;
exponent += exp_number;
}
const len = stream.offset; // length must be complete parsed length
n.* = len;
if (stream.underscore_count > 0 and !validUnderscores(stream.slice, info.base)) {
return null;
}
// common case with not many digits
if (n_digits <= info.max_mantissa_digits) {
return Number(T){
.exponent = exponent,
.mantissa = mantissa,
.negative = negative,
.many_digits = false,
.hex = info.base == 16,
};
}
n_digits -= info.max_mantissa_digits;
var many_digits = false;
stream.reset(); // re-parse from beginning
while (stream.firstIs3('0', '.', '_')) {
// '0' = '.' + 2
const next = stream.firstUnchecked();
if (next != '_') {
n_digits -= @intCast(isize, next -| ('0' - 1));
} else {
stream.underscore_count += 1;
}
stream.advance(1);
}
if (n_digits > 0) {
// at this point we have more than max_mantissa_digits significant digits, let's try again
many_digits = true;
mantissa = 0;
stream.reset();
tryParseNDigits(MantissaT, stream, &mantissa, info.base, info.max_mantissa_digits);
exponent = blk: {
if (mantissa >= min_n_digit_int(MantissaT, info.max_mantissa_digits)) {
// big int
break :blk @intCast(i64, int_end) - @intCast(i64, stream.offsetTrue());
} else {
// the next byte must be present and be '.'
// We know this is true because we had more than 19
// digits previously, so we overflowed a 64-bit integer,
// but parsing only the integral digits produced less
// than 19 digits. That means we must have a decimal
// point, and at least 1 fractional digit.
stream.advance(1);
var marker = stream.offsetTrue();
tryParseNDigits(MantissaT, stream, &mantissa, info.base, info.max_mantissa_digits);
break :blk @intCast(i64, marker) - @intCast(i64, stream.offsetTrue());
}
};
// add back the explicit part
exponent += exp_number;
}
return Number(T){
.exponent = exponent,
.mantissa = mantissa,
.negative = negative,
.many_digits = many_digits,
.hex = info.base == 16,
};
}
/// Parse a partial, non-special floating point number.
///
/// This creates a representation of the float as the
/// significant digits and the decimal exponent.
fn parsePartialNumber(comptime T: type, s: []const u8, negative: bool, n: *usize) ?Number(T) {
std.debug.assert(s.len != 0);
var stream = FloatStream.init(s);
const MantissaT = common.mantissaType(T);
if (stream.hasLen(2) and stream.atUnchecked(0) == '0' and std.ascii.toLower(stream.atUnchecked(1)) == 'x') {
stream.advance(2);
return parsePartialNumberBase(T, &stream, negative, n, .{
.base = 16,
.max_mantissa_digits = if (MantissaT == u64) 16 else 32,
.exp_char_lower = 'p',
});
} else {
return parsePartialNumberBase(T, &stream, negative, n, .{
.base = 10,
.max_mantissa_digits = if (MantissaT == u64) 19 else 38,
.exp_char_lower = 'e',
});
}
}
pub fn parseNumber(comptime T: type, s: []const u8, negative: bool) ?Number(T) {
var consumed: usize = 0;
if (parsePartialNumber(T, s, negative, &consumed)) |number| {
// must consume entire float (no trailing data)
if (s.len == consumed) {
return number;
}
}
return null;
}
fn parsePartialInfOrNan(comptime T: type, s: []const u8, negative: bool, n: *usize) ?T {
// inf/infinity; infxxx should only consume inf.
if (std.ascii.startsWithIgnoreCase(s, "inf")) {
n.* = 3;
if (std.ascii.startsWithIgnoreCase(s[3..], "inity")) {
n.* = 8;
}
return if (!negative) std.math.inf(T) else -std.math.inf(T);
}
if (std.ascii.startsWithIgnoreCase(s, "nan")) {
n.* = 3;
return std.math.nan(T);
}
return null;
}
pub fn parseInfOrNan(comptime T: type, s: []const u8, negative: bool) ?T {
var consumed: usize = 0;
if (parsePartialInfOrNan(T, s, negative, &consumed)) |special| {
if (s.len == consumed) {
return special;
}
}
return null;
}
pub fn validUnderscores(s: []const u8, comptime base: u8) bool {
var i: usize = 0;
while (i < s.len) : (i += 1) {
if (s[i] == '_') {
// underscore at start of end
if (i == 0 or i + 1 == s.len) {
return false;
}
// consecutive underscores
if (!common.isDigit(s[i - 1], base) or !common.isDigit(s[i + 1], base)) {
return false;
}
// next is guaranteed a digit, skip an extra
i += 1;
}
}
return true;
} | lib/std/fmt/parse_float/parse.zig |
const std = @import("std");
const ast = std.zig.ast;
const render = std.zig.render;
const io = std.io;
const mem = std.mem;
const os = std.os;
const cli = @import("flags");
const Command = cli.Command;
const Context = cli.Context;
const Flag = cli.Flag;
/// taken from https://github.com/Hejsil/zig-clap
const max_src_size = 2 * 1024 * 1024 * 1024; // 2 GiB
pub const command = Command{
.name = "fmt",
.flags = [_]Flag{
Flag{
.name = "f",
.desc = "filename to be formated",
.kind = .String,
},
Flag{
.name = "stdin",
.desc = "reads text to format from stdin",
.kind = .Bool,
},
},
.action = formatCmd,
.sub_commands = null,
};
pub fn format(allocator: *mem.Allocator, source_code: []const u8, stdout: var) !void {
var tree = std.zig.parse(allocator, source_code) catch |err| {
std.debug.warn("error parsing stdin: {}\n", err);
os.exit(1);
};
defer tree.deinit();
if (tree.errors.count() > 0) {
var stderr = try std.debug.getStderrStream();
var error_it = tree.errors.iterator(0);
while (error_it.next()) |parse_error| {
try renderError(
allocator,
"<stdin>",
tree,
parse_error,
stderr,
);
}
os.exit(1);
}
_ = try render(allocator, stdout, tree);
}
fn renderError(
a: *mem.Allocator,
file_path: []const u8,
tree: *ast.Tree,
parse_error: *const ast.Error,
stream: var,
) !void {
const loc = parse_error.loc();
const loc_token = parse_error.loc();
var text_buf = try std.Buffer.initSize(a, 0);
defer text_buf.deinit();
var out_stream = &std.io.BufferOutStream.init(&text_buf).stream;
try parse_error.render(&tree.tokens, out_stream);
const first_token = tree.tokens.at(loc);
const start_loc = tree.tokenLocationPtr(0, first_token);
try stream.print(
"{}:{}:{}: error: {}\n",
file_path,
start_loc.line + 1,
start_loc.column + 1,
text_buf.toSlice(),
);
}
fn formatCmd(
ctx: *const Context,
) anyerror!void {
const source_code = try ctx.stdin.?.readAllAlloc(ctx.allocator, max_src_size);
defer ctx.allocator.free(source_code);
if (ctx.boolean("stdin")) {
return format(ctx.allocator, source_code, ctx.stdout.?);
}
} | src/cmd/fmt.zig |
pub const Keysym = extern enum(u32) {
NoSymbol = 0x000000,
VoidSymbol = 0xffffff,
BackSpace = 0xff08,
Tab = 0xff09,
Linefeed = 0xff0a,
Clear = 0xff0b,
Return = 0xff0d,
Pause = 0xff13,
Scroll_Lock = 0xff14,
Sys_Req = 0xff15,
Escape = 0xff1b,
Delete = 0xffff,
Multi_key = 0xff20,
Codeinput = 0xff37,
SingleCandidate = 0xff3c,
MultipleCandidate = 0xff3d,
PreviousCandidate = 0xff3e,
Kanji = 0xff21,
Muhenkan = 0xff22,
Henkan_Mode = 0xff23,
Henkan = 0xff23,
Romaji = 0xff24,
Hiragana = 0xff25,
Katakana = 0xff26,
Hiragana_Katakana = 0xff27,
Zenkaku = 0xff28,
Hankaku = 0xff29,
Zenkaku_Hankaku = 0xff2a,
Touroku = 0xff2b,
Massyo = 0xff2c,
Kana_Lock = 0xff2d,
Kana_Shift = 0xff2e,
Eisu_Shift = 0xff2f,
Eisu_toggle = 0xff30,
Kanji_Bangou = 0xff37,
Zen_Koho = 0xff3d,
Mae_Koho = 0xff3e,
Home = 0xff50,
Left = 0xff51,
Up = 0xff52,
Right = 0xff53,
Down = 0xff54,
Prior = 0xff55,
Page_Up = 0xff55,
Next = 0xff56,
Page_Down = 0xff56,
End = 0xff57,
Begin = 0xff58,
Select = 0xff60,
Print = 0xff61,
Execute = 0xff62,
Insert = 0xff63,
Undo = 0xff65,
Redo = 0xff66,
Menu = 0xff67,
Find = 0xff68,
Cancel = 0xff69,
Help = 0xff6a,
Break = 0xff6b,
Mode_switch = 0xff7e,
script_switch = 0xff7e,
Num_Lock = 0xff7f,
KP_Space = 0xff80,
KP_Tab = 0xff89,
KP_Enter = 0xff8d,
KP_F1 = 0xff91,
KP_F2 = 0xff92,
KP_F3 = 0xff93,
KP_F4 = 0xff94,
KP_Home = 0xff95,
KP_Left = 0xff96,
KP_Up = 0xff97,
KP_Right = 0xff98,
KP_Down = 0xff99,
KP_Prior = 0xff9a,
KP_Page_Up = 0xff9a,
KP_Next = 0xff9b,
KP_Page_Down = 0xff9b,
KP_End = 0xff9c,
KP_Begin = 0xff9d,
KP_Insert = 0xff9e,
KP_Delete = 0xff9f,
KP_Equal = 0xffbd,
KP_Multiply = 0xffaa,
KP_Add = 0xffab,
KP_Separator = 0xffac,
KP_Subtract = 0xffad,
KP_Decimal = 0xffae,
KP_Divide = 0xffaf,
KP_0 = 0xffb0,
KP_1 = 0xffb1,
KP_2 = 0xffb2,
KP_3 = 0xffb3,
KP_4 = 0xffb4,
KP_5 = 0xffb5,
KP_6 = 0xffb6,
KP_7 = 0xffb7,
KP_8 = 0xffb8,
KP_9 = 0xffb9,
F1 = 0xffbe,
F2 = 0xffbf,
F3 = 0xffc0,
F4 = 0xffc1,
F5 = 0xffc2,
F6 = 0xffc3,
F7 = 0xffc4,
F8 = 0xffc5,
F9 = 0xffc6,
F10 = 0xffc7,
F11 = 0xffc8,
L1 = 0xffc8,
F12 = 0xffc9,
L2 = 0xffc9,
F13 = 0xffca,
L3 = 0xffca,
F14 = 0xffcb,
L4 = 0xffcb,
F15 = 0xffcc,
L5 = 0xffcc,
F16 = 0xffcd,
L6 = 0xffcd,
F17 = 0xffce,
L7 = 0xffce,
F18 = 0xffcf,
L8 = 0xffcf,
F19 = 0xffd0,
L9 = 0xffd0,
F20 = 0xffd1,
L10 = 0xffd1,
F21 = 0xffd2,
R1 = 0xffd2,
F22 = 0xffd3,
R2 = 0xffd3,
F23 = 0xffd4,
R3 = 0xffd4,
F24 = 0xffd5,
R4 = 0xffd5,
F25 = 0xffd6,
R5 = 0xffd6,
F26 = 0xffd7,
R6 = 0xffd7,
F27 = 0xffd8,
R7 = 0xffd8,
F28 = 0xffd9,
R8 = 0xffd9,
F29 = 0xffda,
R9 = 0xffda,
F30 = 0xffdb,
R10 = 0xffdb,
F31 = 0xffdc,
R11 = 0xffdc,
F32 = 0xffdd,
R12 = 0xffdd,
F33 = 0xffde,
R13 = 0xffde,
F34 = 0xffdf,
R14 = 0xffdf,
F35 = 0xffe0,
R15 = 0xffe0,
Shift_L = 0xffe1,
Shift_R = 0xffe2,
Control_L = 0xffe3,
Control_R = 0xffe4,
Caps_Lock = 0xffe5,
Shift_Lock = 0xffe6,
Meta_L = 0xffe7,
Meta_R = 0xffe8,
Alt_L = 0xffe9,
Alt_R = 0xffea,
Super_L = 0xffeb,
Super_R = 0xffec,
Hyper_L = 0xffed,
Hyper_R = 0xffee,
ISO_Lock = 0xfe01,
ISO_Level2_Latch = 0xfe02,
ISO_Level3_Shift = 0xfe03,
ISO_Level3_Latch = 0xfe04,
ISO_Level3_Lock = 0xfe05,
ISO_Level5_Shift = 0xfe11,
ISO_Level5_Latch = 0xfe12,
ISO_Level5_Lock = 0xfe13,
ISO_Group_Shift = 0xff7e,
ISO_Group_Latch = 0xfe06,
ISO_Group_Lock = 0xfe07,
ISO_Next_Group = 0xfe08,
ISO_Next_Group_Lock = 0xfe09,
ISO_Prev_Group = 0xfe0a,
ISO_Prev_Group_Lock = 0xfe0b,
ISO_First_Group = 0xfe0c,
ISO_First_Group_Lock = 0xfe0d,
ISO_Last_Group = 0xfe0e,
ISO_Last_Group_Lock = 0xfe0f,
ISO_Left_Tab = 0xfe20,
ISO_Move_Line_Up = 0xfe21,
ISO_Move_Line_Down = 0xfe22,
ISO_Partial_Line_Up = 0xfe23,
ISO_Partial_Line_Down = 0xfe24,
ISO_Partial_Space_Left = 0xfe25,
ISO_Partial_Space_Right = 0xfe26,
ISO_Set_Margin_Left = 0xfe27,
ISO_Set_Margin_Right = 0xfe28,
ISO_Release_Margin_Left = 0xfe29,
ISO_Release_Margin_Right = 0xfe2a,
ISO_Release_Both_Margins = 0xfe2b,
ISO_Fast_Cursor_Left = 0xfe2c,
ISO_Fast_Cursor_Right = 0xfe2d,
ISO_Fast_Cursor_Up = 0xfe2e,
ISO_Fast_Cursor_Down = 0xfe2f,
ISO_Continuous_Underline = 0xfe30,
ISO_Discontinuous_Underline = 0xfe31,
ISO_Emphasize = 0xfe32,
ISO_Center_Object = 0xfe33,
ISO_Enter = 0xfe34,
dead_grave = 0xfe50,
dead_acute = 0xfe51,
dead_circumflex = 0xfe52,
dead_tilde = 0xfe53,
dead_perispomeni = 0xfe53,
dead_macron = 0xfe54,
dead_breve = 0xfe55,
dead_abovedot = 0xfe56,
dead_diaeresis = 0xfe57,
dead_abovering = 0xfe58,
dead_doubleacute = 0xfe59,
dead_caron = 0xfe5a,
dead_cedilla = 0xfe5b,
dead_ogonek = 0xfe5c,
dead_iota = 0xfe5d,
dead_voiced_sound = 0xfe5e,
dead_semivoiced_sound = 0xfe5f,
dead_belowdot = 0xfe60,
dead_hook = 0xfe61,
dead_horn = 0xfe62,
dead_stroke = 0xfe63,
dead_abovecomma = 0xfe64,
dead_psili = 0xfe64,
dead_abovereversedcomma = 0xfe65,
dead_dasia = 0xfe65,
dead_doublegrave = 0xfe66,
dead_belowring = 0xfe67,
dead_belowmacron = 0xfe68,
dead_belowcircumflex = 0xfe69,
dead_belowtilde = 0xfe6a,
dead_belowbreve = 0xfe6b,
dead_belowdiaeresis = 0xfe6c,
dead_invertedbreve = 0xfe6d,
dead_belowcomma = 0xfe6e,
dead_currency = 0xfe6f,
dead_lowline = 0xfe90,
dead_aboveverticalline = 0xfe91,
dead_belowverticalline = 0xfe92,
dead_longsolidusoverlay = 0xfe93,
dead_a = 0xfe80,
dead_A = 0xfe81,
dead_e = 0xfe82,
dead_E = 0xfe83,
dead_i = 0xfe84,
dead_I = 0xfe85,
dead_o = 0xfe86,
dead_O = 0xfe87,
dead_u = 0xfe88,
dead_U = 0xfe89,
dead_small_schwa = 0xfe8a,
dead_capital_schwa = 0xfe8b,
dead_greek = 0xfe8c,
First_Virtual_Screen = 0xfed0,
Prev_Virtual_Screen = 0xfed1,
Next_Virtual_Screen = 0xfed2,
Last_Virtual_Screen = 0xfed4,
Terminate_Server = 0xfed5,
AccessX_Enable = 0xfe70,
AccessX_Feedback_Enable = 0xfe71,
RepeatKeys_Enable = 0xfe72,
SlowKeys_Enable = 0xfe73,
BounceKeys_Enable = 0xfe74,
StickyKeys_Enable = 0xfe75,
MouseKeys_Enable = 0xfe76,
MouseKeys_Accel_Enable = 0xfe77,
Overlay1_Enable = 0xfe78,
Overlay2_Enable = 0xfe79,
AudibleBell_Enable = 0xfe7a,
Pointer_Left = 0xfee0,
Pointer_Right = 0xfee1,
Pointer_Up = 0xfee2,
Pointer_Down = 0xfee3,
Pointer_UpLeft = 0xfee4,
Pointer_UpRight = 0xfee5,
Pointer_DownLeft = 0xfee6,
Pointer_DownRight = 0xfee7,
Pointer_Button_Dflt = 0xfee8,
Pointer_Button1 = 0xfee9,
Pointer_Button2 = 0xfeea,
Pointer_Button3 = 0xfeeb,
Pointer_Button4 = 0xfeec,
Pointer_Button5 = 0xfeed,
Pointer_DblClick_Dflt = 0xfeee,
Pointer_DblClick1 = 0xfeef,
Pointer_DblClick2 = 0xfef0,
Pointer_DblClick3 = 0xfef1,
Pointer_DblClick4 = 0xfef2,
Pointer_DblClick5 = 0xfef3,
Pointer_Drag_Dflt = 0xfef4,
Pointer_Drag1 = 0xfef5,
Pointer_Drag2 = 0xfef6,
Pointer_Drag3 = 0xfef7,
Pointer_Drag4 = 0xfef8,
Pointer_Drag5 = 0xfefd,
Pointer_EnableKeys = 0xfef9,
Pointer_Accelerate = 0xfefa,
Pointer_DfltBtnNext = 0xfefb,
Pointer_DfltBtnPrev = 0xfefc,
ch = 0xfea0,
Ch = 0xfea1,
CH = 0xfea2,
c_h = 0xfea3,
C_h = 0xfea4,
C_H = 0xfea5,
@"3270_Duplicate" = 0xfd01,
@"3270_FieldMark" = 0xfd02,
@"3270_Right2" = 0xfd03,
@"3270_Left2" = 0xfd04,
@"3270_BackTab" = 0xfd05,
@"3270_EraseEOF" = 0xfd06,
@"3270_EraseInput" = 0xfd07,
@"3270_Reset" = 0xfd08,
@"3270_Quit" = 0xfd09,
@"3270_PA1" = 0xfd0a,
@"3270_PA2" = 0xfd0b,
@"3270_PA3" = 0xfd0c,
@"3270_Test" = 0xfd0d,
@"3270_Attn" = 0xfd0e,
@"3270_CursorBlink" = 0xfd0f,
@"3270_AltCursor" = 0xfd10,
@"3270_KeyClick" = 0xfd11,
@"3270_Jump" = 0xfd12,
@"3270_Ident" = 0xfd13,
@"3270_Rule" = 0xfd14,
@"3270_Copy" = 0xfd15,
@"3270_Play" = 0xfd16,
@"3270_Setup" = 0xfd17,
@"3270_Record" = 0xfd18,
@"3270_ChangeScreen" = 0xfd19,
@"3270_DeleteWord" = 0xfd1a,
@"3270_ExSelect" = 0xfd1b,
@"3270_CursorSelect" = 0xfd1c,
@"3270_PrintScreen" = 0xfd1d,
@"3270_Enter" = 0xfd1e,
space = 0x0020,
exclam = 0x0021,
quotedbl = 0x0022,
numbersign = 0x0023,
dollar = 0x0024,
percent = 0x0025,
ampersand = 0x0026,
apostrophe = 0x0027,
quoteright = 0x0027,
parenleft = 0x0028,
parenright = 0x0029,
asterisk = 0x002a,
plus = 0x002b,
comma = 0x002c,
minus = 0x002d,
period = 0x002e,
slash = 0x002f,
@"0" = 0x0030,
@"1" = 0x0031,
@"2" = 0x0032,
@"3" = 0x0033,
@"4" = 0x0034,
@"5" = 0x0035,
@"6" = 0x0036,
@"7" = 0x0037,
@"8" = 0x0038,
@"9" = 0x0039,
colon = 0x003a,
semicolon = 0x003b,
less = 0x003c,
equal = 0x003d,
greater = 0x003e,
question = 0x003f,
at = 0x0040,
A = 0x0041,
B = 0x0042,
C = 0x0043,
D = 0x0044,
E = 0x0045,
F = 0x0046,
G = 0x0047,
H = 0x0048,
I = 0x0049,
J = 0x004a,
K = 0x004b,
L = 0x004c,
M = 0x004d,
N = 0x004e,
O = 0x004f,
P = 0x0050,
Q = 0x0051,
R = 0x0052,
S = 0x0053,
T = 0x0054,
U = 0x0055,
V = 0x0056,
W = 0x0057,
X = 0x0058,
Y = 0x0059,
Z = 0x005a,
bracketleft = 0x005b,
backslash = 0x005c,
bracketright = 0x005d,
asciicircum = 0x005e,
underscore = 0x005f,
grave = 0x0060,
quoteleft = 0x0060,
a = 0x0061,
b = 0x0062,
c = 0x0063,
d = 0x0064,
e = 0x0065,
f = 0x0066,
g = 0x0067,
h = 0x0068,
i = 0x0069,
j = 0x006a,
k = 0x006b,
l = 0x006c,
m = 0x006d,
n = 0x006e,
o = 0x006f,
p = 0x0070,
q = 0x0071,
r = 0x0072,
s = 0x0073,
t = 0x0074,
u = 0x0075,
v = 0x0076,
w = 0x0077,
x = 0x0078,
y = 0x0079,
z = 0x007a,
braceleft = 0x007b,
bar = 0x007c,
braceright = 0x007d,
asciitilde = 0x007e,
nobreakspace = 0x00a0,
exclamdown = 0x00a1,
cent = 0x00a2,
sterling = 0x00a3,
currency = 0x00a4,
yen = 0x00a5,
brokenbar = 0x00a6,
section = 0x00a7,
diaeresis = 0x00a8,
copyright = 0x00a9,
ordfeminine = 0x00aa,
guillemotleft = 0x00ab,
notsign = 0x00ac,
hyphen = 0x00ad,
registered = 0x00ae,
macron = 0x00af,
degree = 0x00b0,
plusminus = 0x00b1,
twosuperior = 0x00b2,
threesuperior = 0x00b3,
acute = 0x00b4,
mu = 0x00b5,
paragraph = 0x00b6,
periodcentered = 0x00b7,
cedilla = 0x00b8,
onesuperior = 0x00b9,
masculine = 0x00ba,
guillemotright = 0x00bb,
onequarter = 0x00bc,
onehalf = 0x00bd,
threequarters = 0x00be,
questiondown = 0x00bf,
Agrave = 0x00c0,
Aacute = 0x00c1,
Acircumflex = 0x00c2,
Atilde = 0x00c3,
Adiaeresis = 0x00c4,
Aring = 0x00c5,
AE = 0x00c6,
Ccedilla = 0x00c7,
Egrave = 0x00c8,
Eacute = 0x00c9,
Ecircumflex = 0x00ca,
Ediaeresis = 0x00cb,
Igrave = 0x00cc,
Iacute = 0x00cd,
Icircumflex = 0x00ce,
Idiaeresis = 0x00cf,
ETH = 0x00d0,
Eth = 0x00d0,
Ntilde = 0x00d1,
Ograve = 0x00d2,
Oacute = 0x00d3,
Ocircumflex = 0x00d4,
Otilde = 0x00d5,
Odiaeresis = 0x00d6,
multiply = 0x00d7,
Oslash = 0x00d8,
Ooblique = 0x00d8,
Ugrave = 0x00d9,
Uacute = 0x00da,
Ucircumflex = 0x00db,
Udiaeresis = 0x00dc,
Yacute = 0x00dd,
THORN = 0x00de,
Thorn = 0x00de,
ssharp = 0x00df,
agrave = 0x00e0,
aacute = 0x00e1,
acircumflex = 0x00e2,
atilde = 0x00e3,
adiaeresis = 0x00e4,
aring = 0x00e5,
ae = 0x00e6,
ccedilla = 0x00e7,
egrave = 0x00e8,
eacute = 0x00e9,
ecircumflex = 0x00ea,
ediaeresis = 0x00eb,
igrave = 0x00ec,
iacute = 0x00ed,
icircumflex = 0x00ee,
idiaeresis = 0x00ef,
eth = 0x00f0,
ntilde = 0x00f1,
ograve = 0x00f2,
oacute = 0x00f3,
ocircumflex = 0x00f4,
otilde = 0x00f5,
odiaeresis = 0x00f6,
division = 0x00f7,
oslash = 0x00f8,
ooblique = 0x00f8,
ugrave = 0x00f9,
uacute = 0x00fa,
ucircumflex = 0x00fb,
udiaeresis = 0x00fc,
yacute = 0x00fd,
thorn = 0x00fe,
ydiaeresis = 0x00ff,
Aogonek = 0x01a1,
breve = 0x01a2,
Lstroke = 0x01a3,
Lcaron = 0x01a5,
Sacute = 0x01a6,
Scaron = 0x01a9,
Scedilla = 0x01aa,
Tcaron = 0x01ab,
Zacute = 0x01ac,
Zcaron = 0x01ae,
Zabovedot = 0x01af,
aogonek = 0x01b1,
ogonek = 0x01b2,
lstroke = 0x01b3,
lcaron = 0x01b5,
sacute = 0x01b6,
caron = 0x01b7,
scaron = 0x01b9,
scedilla = 0x01ba,
tcaron = 0x01bb,
zacute = 0x01bc,
doubleacute = 0x01bd,
zcaron = 0x01be,
zabovedot = 0x01bf,
Racute = 0x01c0,
Abreve = 0x01c3,
Lacute = 0x01c5,
Cacute = 0x01c6,
Ccaron = 0x01c8,
Eogonek = 0x01ca,
Ecaron = 0x01cc,
Dcaron = 0x01cf,
Dstroke = 0x01d0,
Nacute = 0x01d1,
Ncaron = 0x01d2,
Odoubleacute = 0x01d5,
Rcaron = 0x01d8,
Uring = 0x01d9,
Udoubleacute = 0x01db,
Tcedilla = 0x01de,
racute = 0x01e0,
abreve = 0x01e3,
lacute = 0x01e5,
cacute = 0x01e6,
ccaron = 0x01e8,
eogonek = 0x01ea,
ecaron = 0x01ec,
dcaron = 0x01ef,
dstroke = 0x01f0,
nacute = 0x01f1,
ncaron = 0x01f2,
odoubleacute = 0x01f5,
rcaron = 0x01f8,
uring = 0x01f9,
udoubleacute = 0x01fb,
tcedilla = 0x01fe,
abovedot = 0x01ff,
Hstroke = 0x02a1,
Hcircumflex = 0x02a6,
Iabovedot = 0x02a9,
Gbreve = 0x02ab,
Jcircumflex = 0x02ac,
hstroke = 0x02b1,
hcircumflex = 0x02b6,
idotless = 0x02b9,
gbreve = 0x02bb,
jcircumflex = 0x02bc,
Cabovedot = 0x02c5,
Ccircumflex = 0x02c6,
Gabovedot = 0x02d5,
Gcircumflex = 0x02d8,
Ubreve = 0x02dd,
Scircumflex = 0x02de,
cabovedot = 0x02e5,
ccircumflex = 0x02e6,
gabovedot = 0x02f5,
gcircumflex = 0x02f8,
ubreve = 0x02fd,
scircumflex = 0x02fe,
kra = 0x03a2,
kappa = 0x03a2,
Rcedilla = 0x03a3,
Itilde = 0x03a5,
Lcedilla = 0x03a6,
Emacron = 0x03aa,
Gcedilla = 0x03ab,
Tslash = 0x03ac,
rcedilla = 0x03b3,
itilde = 0x03b5,
lcedilla = 0x03b6,
emacron = 0x03ba,
gcedilla = 0x03bb,
tslash = 0x03bc,
ENG = 0x03bd,
eng = 0x03bf,
Amacron = 0x03c0,
Iogonek = 0x03c7,
Eabovedot = 0x03cc,
Imacron = 0x03cf,
Ncedilla = 0x03d1,
Omacron = 0x03d2,
Kcedilla = 0x03d3,
Uogonek = 0x03d9,
Utilde = 0x03dd,
Umacron = 0x03de,
amacron = 0x03e0,
iogonek = 0x03e7,
eabovedot = 0x03ec,
imacron = 0x03ef,
ncedilla = 0x03f1,
omacron = 0x03f2,
kcedilla = 0x03f3,
uogonek = 0x03f9,
utilde = 0x03fd,
umacron = 0x03fe,
Wcircumflex = 0x1000174,
wcircumflex = 0x1000175,
Ycircumflex = 0x1000176,
ycircumflex = 0x1000177,
Babovedot = 0x1001e02,
babovedot = 0x1001e03,
Dabovedot = 0x1001e0a,
dabovedot = 0x1001e0b,
Fabovedot = 0x1001e1e,
fabovedot = 0x1001e1f,
Mabovedot = 0x1001e40,
mabovedot = 0x1001e41,
Pabovedot = 0x1001e56,
pabovedot = 0x1001e57,
Sabovedot = 0x1001e60,
sabovedot = 0x1001e61,
Tabovedot = 0x1001e6a,
tabovedot = 0x1001e6b,
Wgrave = 0x1001e80,
wgrave = 0x1001e81,
Wacute = 0x1001e82,
wacute = 0x1001e83,
Wdiaeresis = 0x1001e84,
wdiaeresis = 0x1001e85,
Ygrave = 0x1001ef2,
ygrave = 0x1001ef3,
OE = 0x13bc,
oe = 0x13bd,
Ydiaeresis = 0x13be,
overline = 0x047e,
kana_fullstop = 0x04a1,
kana_openingbracket = 0x04a2,
kana_closingbracket = 0x04a3,
kana_comma = 0x04a4,
kana_conjunctive = 0x04a5,
kana_middledot = 0x04a5,
kana_WO = 0x04a6,
kana_a = 0x04a7,
kana_i = 0x04a8,
kana_u = 0x04a9,
kana_e = 0x04aa,
kana_o = 0x04ab,
kana_ya = 0x04ac,
kana_yu = 0x04ad,
kana_yo = 0x04ae,
kana_tsu = 0x04af,
kana_tu = 0x04af,
prolongedsound = 0x04b0,
kana_A = 0x04b1,
kana_I = 0x04b2,
kana_U = 0x04b3,
kana_E = 0x04b4,
kana_O = 0x04b5,
kana_KA = 0x04b6,
kana_KI = 0x04b7,
kana_KU = 0x04b8,
kana_KE = 0x04b9,
kana_KO = 0x04ba,
kana_SA = 0x04bb,
kana_SHI = 0x04bc,
kana_SU = 0x04bd,
kana_SE = 0x04be,
kana_SO = 0x04bf,
kana_TA = 0x04c0,
kana_CHI = 0x04c1,
kana_TI = 0x04c1,
kana_TSU = 0x04c2,
kana_TU = 0x04c2,
kana_TE = 0x04c3,
kana_TO = 0x04c4,
kana_NA = 0x04c5,
kana_NI = 0x04c6,
kana_NU = 0x04c7,
kana_NE = 0x04c8,
kana_NO = 0x04c9,
kana_HA = 0x04ca,
kana_HI = 0x04cb,
kana_FU = 0x04cc,
kana_HU = 0x04cc,
kana_HE = 0x04cd,
kana_HO = 0x04ce,
kana_MA = 0x04cf,
kana_MI = 0x04d0,
kana_MU = 0x04d1,
kana_ME = 0x04d2,
kana_MO = 0x04d3,
kana_YA = 0x04d4,
kana_YU = 0x04d5,
kana_YO = 0x04d6,
kana_RA = 0x04d7,
kana_RI = 0x04d8,
kana_RU = 0x04d9,
kana_RE = 0x04da,
kana_RO = 0x04db,
kana_WA = 0x04dc,
kana_N = 0x04dd,
voicedsound = 0x04de,
semivoicedsound = 0x04df,
kana_switch = 0xff7e,
Farsi_0 = 0x10006f0,
Farsi_1 = 0x10006f1,
Farsi_2 = 0x10006f2,
Farsi_3 = 0x10006f3,
Farsi_4 = 0x10006f4,
Farsi_5 = 0x10006f5,
Farsi_6 = 0x10006f6,
Farsi_7 = 0x10006f7,
Farsi_8 = 0x10006f8,
Farsi_9 = 0x10006f9,
Arabic_percent = 0x100066a,
Arabic_superscript_alef = 0x1000670,
Arabic_tteh = 0x1000679,
Arabic_peh = 0x100067e,
Arabic_tcheh = 0x1000686,
Arabic_ddal = 0x1000688,
Arabic_rreh = 0x1000691,
Arabic_comma = 0x05ac,
Arabic_fullstop = 0x10006d4,
Arabic_0 = 0x1000660,
Arabic_1 = 0x1000661,
Arabic_2 = 0x1000662,
Arabic_3 = 0x1000663,
Arabic_4 = 0x1000664,
Arabic_5 = 0x1000665,
Arabic_6 = 0x1000666,
Arabic_7 = 0x1000667,
Arabic_8 = 0x1000668,
Arabic_9 = 0x1000669,
Arabic_semicolon = 0x05bb,
Arabic_question_mark = 0x05bf,
Arabic_hamza = 0x05c1,
Arabic_maddaonalef = 0x05c2,
Arabic_hamzaonalef = 0x05c3,
Arabic_hamzaonwaw = 0x05c4,
Arabic_hamzaunderalef = 0x05c5,
Arabic_hamzaonyeh = 0x05c6,
Arabic_alef = 0x05c7,
Arabic_beh = 0x05c8,
Arabic_tehmarbuta = 0x05c9,
Arabic_teh = 0x05ca,
Arabic_theh = 0x05cb,
Arabic_jeem = 0x05cc,
Arabic_hah = 0x05cd,
Arabic_khah = 0x05ce,
Arabic_dal = 0x05cf,
Arabic_thal = 0x05d0,
Arabic_ra = 0x05d1,
Arabic_zain = 0x05d2,
Arabic_seen = 0x05d3,
Arabic_sheen = 0x05d4,
Arabic_sad = 0x05d5,
Arabic_dad = 0x05d6,
Arabic_tah = 0x05d7,
Arabic_zah = 0x05d8,
Arabic_ain = 0x05d9,
Arabic_ghain = 0x05da,
Arabic_tatweel = 0x05e0,
Arabic_feh = 0x05e1,
Arabic_qaf = 0x05e2,
Arabic_kaf = 0x05e3,
Arabic_lam = 0x05e4,
Arabic_meem = 0x05e5,
Arabic_noon = 0x05e6,
Arabic_ha = 0x05e7,
Arabic_heh = 0x05e7,
Arabic_waw = 0x05e8,
Arabic_alefmaksura = 0x05e9,
Arabic_yeh = 0x05ea,
Arabic_fathatan = 0x05eb,
Arabic_dammatan = 0x05ec,
Arabic_kasratan = 0x05ed,
Arabic_fatha = 0x05ee,
Arabic_damma = 0x05ef,
Arabic_kasra = 0x05f0,
Arabic_shadda = 0x05f1,
Arabic_sukun = 0x05f2,
Arabic_madda_above = 0x1000653,
Arabic_hamza_above = 0x1000654,
Arabic_hamza_below = 0x1000655,
Arabic_jeh = 0x1000698,
Arabic_veh = 0x10006a4,
Arabic_keheh = 0x10006a9,
Arabic_gaf = 0x10006af,
Arabic_noon_ghunna = 0x10006ba,
Arabic_heh_doachashmee = 0x10006be,
Farsi_yeh = 0x10006cc,
Arabic_farsi_yeh = 0x10006cc,
Arabic_yeh_baree = 0x10006d2,
Arabic_heh_goal = 0x10006c1,
Arabic_switch = 0xff7e,
Cyrillic_GHE_bar = 0x1000492,
Cyrillic_ghe_bar = 0x1000493,
Cyrillic_ZHE_descender = 0x1000496,
Cyrillic_zhe_descender = 0x1000497,
Cyrillic_KA_descender = 0x100049a,
Cyrillic_ka_descender = 0x100049b,
Cyrillic_KA_vertstroke = 0x100049c,
Cyrillic_ka_vertstroke = 0x100049d,
Cyrillic_EN_descender = 0x10004a2,
Cyrillic_en_descender = 0x10004a3,
Cyrillic_U_straight = 0x10004ae,
Cyrillic_u_straight = 0x10004af,
Cyrillic_U_straight_bar = 0x10004b0,
Cyrillic_u_straight_bar = 0x10004b1,
Cyrillic_HA_descender = 0x10004b2,
Cyrillic_ha_descender = 0x10004b3,
Cyrillic_CHE_descender = 0x10004b6,
Cyrillic_che_descender = 0x10004b7,
Cyrillic_CHE_vertstroke = 0x10004b8,
Cyrillic_che_vertstroke = 0x10004b9,
Cyrillic_SHHA = 0x10004ba,
Cyrillic_shha = 0x10004bb,
Cyrillic_SCHWA = 0x10004d8,
Cyrillic_schwa = 0x10004d9,
Cyrillic_I_macron = 0x10004e2,
Cyrillic_i_macron = 0x10004e3,
Cyrillic_O_bar = 0x10004e8,
Cyrillic_o_bar = 0x10004e9,
Cyrillic_U_macron = 0x10004ee,
Cyrillic_u_macron = 0x10004ef,
Serbian_dje = 0x06a1,
Macedonia_gje = 0x06a2,
Cyrillic_io = 0x06a3,
Ukrainian_ie = 0x06a4,
Ukranian_je = 0x06a4,
Macedonia_dse = 0x06a5,
Ukrainian_i = 0x06a6,
Ukranian_i = 0x06a6,
Ukrainian_yi = 0x06a7,
Ukranian_yi = 0x06a7,
Cyrillic_je = 0x06a8,
Serbian_je = 0x06a8,
Cyrillic_lje = 0x06a9,
Serbian_lje = 0x06a9,
Cyrillic_nje = 0x06aa,
Serbian_nje = 0x06aa,
Serbian_tshe = 0x06ab,
Macedonia_kje = 0x06ac,
Ukrainian_ghe_with_upturn = 0x06ad,
Byelorussian_shortu = 0x06ae,
Cyrillic_dzhe = 0x06af,
Serbian_dze = 0x06af,
numerosign = 0x06b0,
Serbian_DJE = 0x06b1,
Macedonia_GJE = 0x06b2,
Cyrillic_IO = 0x06b3,
Ukrainian_IE = 0x06b4,
Ukranian_JE = 0x06b4,
Macedonia_DSE = 0x06b5,
Ukrainian_I = 0x06b6,
Ukranian_I = 0x06b6,
Ukrainian_YI = 0x06b7,
Ukranian_YI = 0x06b7,
Cyrillic_JE = 0x06b8,
Serbian_JE = 0x06b8,
Cyrillic_LJE = 0x06b9,
Serbian_LJE = 0x06b9,
Cyrillic_NJE = 0x06ba,
Serbian_NJE = 0x06ba,
Serbian_TSHE = 0x06bb,
Macedonia_KJE = 0x06bc,
Ukrainian_GHE_WITH_UPTURN = 0x06bd,
Byelorussian_SHORTU = 0x06be,
Cyrillic_DZHE = 0x06bf,
Serbian_DZE = 0x06bf,
Cyrillic_yu = 0x06c0,
Cyrillic_a = 0x06c1,
Cyrillic_be = 0x06c2,
Cyrillic_tse = 0x06c3,
Cyrillic_de = 0x06c4,
Cyrillic_ie = 0x06c5,
Cyrillic_ef = 0x06c6,
Cyrillic_ghe = 0x06c7,
Cyrillic_ha = 0x06c8,
Cyrillic_i = 0x06c9,
Cyrillic_shorti = 0x06ca,
Cyrillic_ka = 0x06cb,
Cyrillic_el = 0x06cc,
Cyrillic_em = 0x06cd,
Cyrillic_en = 0x06ce,
Cyrillic_o = 0x06cf,
Cyrillic_pe = 0x06d0,
Cyrillic_ya = 0x06d1,
Cyrillic_er = 0x06d2,
Cyrillic_es = 0x06d3,
Cyrillic_te = 0x06d4,
Cyrillic_u = 0x06d5,
Cyrillic_zhe = 0x06d6,
Cyrillic_ve = 0x06d7,
Cyrillic_softsign = 0x06d8,
Cyrillic_yeru = 0x06d9,
Cyrillic_ze = 0x06da,
Cyrillic_sha = 0x06db,
Cyrillic_e = 0x06dc,
Cyrillic_shcha = 0x06dd,
Cyrillic_che = 0x06de,
Cyrillic_hardsign = 0x06df,
Cyrillic_YU = 0x06e0,
Cyrillic_A = 0x06e1,
Cyrillic_BE = 0x06e2,
Cyrillic_TSE = 0x06e3,
Cyrillic_DE = 0x06e4,
Cyrillic_IE = 0x06e5,
Cyrillic_EF = 0x06e6,
Cyrillic_GHE = 0x06e7,
Cyrillic_HA = 0x06e8,
Cyrillic_I = 0x06e9,
Cyrillic_SHORTI = 0x06ea,
Cyrillic_KA = 0x06eb,
Cyrillic_EL = 0x06ec,
Cyrillic_EM = 0x06ed,
Cyrillic_EN = 0x06ee,
Cyrillic_O = 0x06ef,
Cyrillic_PE = 0x06f0,
Cyrillic_YA = 0x06f1,
Cyrillic_ER = 0x06f2,
Cyrillic_ES = 0x06f3,
Cyrillic_TE = 0x06f4,
Cyrillic_U = 0x06f5,
Cyrillic_ZHE = 0x06f6,
Cyrillic_VE = 0x06f7,
Cyrillic_SOFTSIGN = 0x06f8,
Cyrillic_YERU = 0x06f9,
Cyrillic_ZE = 0x06fa,
Cyrillic_SHA = 0x06fb,
Cyrillic_E = 0x06fc,
Cyrillic_SHCHA = 0x06fd,
Cyrillic_CHE = 0x06fe,
Cyrillic_HARDSIGN = 0x06ff,
Greek_ALPHAaccent = 0x07a1,
Greek_EPSILONaccent = 0x07a2,
Greek_ETAaccent = 0x07a3,
Greek_IOTAaccent = 0x07a4,
Greek_IOTAdieresis = 0x07a5,
Greek_IOTAdiaeresis = 0x07a5,
Greek_OMICRONaccent = 0x07a7,
Greek_UPSILONaccent = 0x07a8,
Greek_UPSILONdieresis = 0x07a9,
Greek_OMEGAaccent = 0x07ab,
Greek_accentdieresis = 0x07ae,
Greek_horizbar = 0x07af,
Greek_alphaaccent = 0x07b1,
Greek_epsilonaccent = 0x07b2,
Greek_etaaccent = 0x07b3,
Greek_iotaaccent = 0x07b4,
Greek_iotadieresis = 0x07b5,
Greek_iotaaccentdieresis = 0x07b6,
Greek_omicronaccent = 0x07b7,
Greek_upsilonaccent = 0x07b8,
Greek_upsilondieresis = 0x07b9,
Greek_upsilonaccentdieresis = 0x07ba,
Greek_omegaaccent = 0x07bb,
Greek_ALPHA = 0x07c1,
Greek_BETA = 0x07c2,
Greek_GAMMA = 0x07c3,
Greek_DELTA = 0x07c4,
Greek_EPSILON = 0x07c5,
Greek_ZETA = 0x07c6,
Greek_ETA = 0x07c7,
Greek_THETA = 0x07c8,
Greek_IOTA = 0x07c9,
Greek_KAPPA = 0x07ca,
Greek_LAMDA = 0x07cb,
Greek_LAMBDA = 0x07cb,
Greek_MU = 0x07cc,
Greek_NU = 0x07cd,
Greek_XI = 0x07ce,
Greek_OMICRON = 0x07cf,
Greek_PI = 0x07d0,
Greek_RHO = 0x07d1,
Greek_SIGMA = 0x07d2,
Greek_TAU = 0x07d4,
Greek_UPSILON = 0x07d5,
Greek_PHI = 0x07d6,
Greek_CHI = 0x07d7,
Greek_PSI = 0x07d8,
Greek_OMEGA = 0x07d9,
Greek_alpha = 0x07e1,
Greek_beta = 0x07e2,
Greek_gamma = 0x07e3,
Greek_delta = 0x07e4,
Greek_epsilon = 0x07e5,
Greek_zeta = 0x07e6,
Greek_eta = 0x07e7,
Greek_theta = 0x07e8,
Greek_iota = 0x07e9,
Greek_kappa = 0x07ea,
Greek_lamda = 0x07eb,
Greek_lambda = 0x07eb,
Greek_mu = 0x07ec,
Greek_nu = 0x07ed,
Greek_xi = 0x07ee,
Greek_omicron = 0x07ef,
Greek_pi = 0x07f0,
Greek_rho = 0x07f1,
Greek_sigma = 0x07f2,
Greek_finalsmallsigma = 0x07f3,
Greek_tau = 0x07f4,
Greek_upsilon = 0x07f5,
Greek_phi = 0x07f6,
Greek_chi = 0x07f7,
Greek_psi = 0x07f8,
Greek_omega = 0x07f9,
Greek_switch = 0xff7e,
leftradical = 0x08a1,
topleftradical = 0x08a2,
horizconnector = 0x08a3,
topintegral = 0x08a4,
botintegral = 0x08a5,
vertconnector = 0x08a6,
topleftsqbracket = 0x08a7,
botleftsqbracket = 0x08a8,
toprightsqbracket = 0x08a9,
botrightsqbracket = 0x08aa,
topleftparens = 0x08ab,
botleftparens = 0x08ac,
toprightparens = 0x08ad,
botrightparens = 0x08ae,
leftmiddlecurlybrace = 0x08af,
rightmiddlecurlybrace = 0x08b0,
topleftsummation = 0x08b1,
botleftsummation = 0x08b2,
topvertsummationconnector = 0x08b3,
botvertsummationconnector = 0x08b4,
toprightsummation = 0x08b5,
botrightsummation = 0x08b6,
rightmiddlesummation = 0x08b7,
lessthanequal = 0x08bc,
notequal = 0x08bd,
greaterthanequal = 0x08be,
integral = 0x08bf,
therefore = 0x08c0,
variation = 0x08c1,
infinity = 0x08c2,
nabla = 0x08c5,
approximate = 0x08c8,
similarequal = 0x08c9,
ifonlyif = 0x08cd,
implies = 0x08ce,
identical = 0x08cf,
radical = 0x08d6,
includedin = 0x08da,
includes = 0x08db,
intersection = 0x08dc,
@"union" = 0x08dd,
logicaland = 0x08de,
logicalor = 0x08df,
partialderivative = 0x08ef,
function = 0x08f6,
leftarrow = 0x08fb,
uparrow = 0x08fc,
rightarrow = 0x08fd,
downarrow = 0x08fe,
blank = 0x09df,
soliddiamond = 0x09e0,
checkerboard = 0x09e1,
ht = 0x09e2,
ff = 0x09e3,
cr = 0x09e4,
lf = 0x09e5,
nl = 0x09e8,
vt = 0x09e9,
lowrightcorner = 0x09ea,
uprightcorner = 0x09eb,
upleftcorner = 0x09ec,
lowleftcorner = 0x09ed,
crossinglines = 0x09ee,
horizlinescan1 = 0x09ef,
horizlinescan3 = 0x09f0,
horizlinescan5 = 0x09f1,
horizlinescan7 = 0x09f2,
horizlinescan9 = 0x09f3,
leftt = 0x09f4,
rightt = 0x09f5,
bott = 0x09f6,
topt = 0x09f7,
vertbar = 0x09f8,
emspace = 0x0aa1,
enspace = 0x0aa2,
em3space = 0x0aa3,
em4space = 0x0aa4,
digitspace = 0x0aa5,
punctspace = 0x0aa6,
thinspace = 0x0aa7,
hairspace = 0x0aa8,
emdash = 0x0aa9,
endash = 0x0aaa,
signifblank = 0x0aac,
ellipsis = 0x0aae,
doubbaselinedot = 0x0aaf,
onethird = 0x0ab0,
twothirds = 0x0ab1,
onefifth = 0x0ab2,
twofifths = 0x0ab3,
threefifths = 0x0ab4,
fourfifths = 0x0ab5,
onesixth = 0x0ab6,
fivesixths = 0x0ab7,
careof = 0x0ab8,
figdash = 0x0abb,
leftanglebracket = 0x0abc,
decimalpoint = 0x0abd,
rightanglebracket = 0x0abe,
marker = 0x0abf,
oneeighth = 0x0ac3,
threeeighths = 0x0ac4,
fiveeighths = 0x0ac5,
seveneighths = 0x0ac6,
trademark = 0x0ac9,
signaturemark = 0x0aca,
trademarkincircle = 0x0acb,
leftopentriangle = 0x0acc,
rightopentriangle = 0x0acd,
emopencircle = 0x0ace,
emopenrectangle = 0x0acf,
leftsinglequotemark = 0x0ad0,
rightsinglequotemark = 0x0ad1,
leftdoublequotemark = 0x0ad2,
rightdoublequotemark = 0x0ad3,
prescription = 0x0ad4,
permille = 0x0ad5,
minutes = 0x0ad6,
seconds = 0x0ad7,
latincross = 0x0ad9,
hexagram = 0x0ada,
filledrectbullet = 0x0adb,
filledlefttribullet = 0x0adc,
filledrighttribullet = 0x0add,
emfilledcircle = 0x0ade,
emfilledrect = 0x0adf,
enopencircbullet = 0x0ae0,
enopensquarebullet = 0x0ae1,
openrectbullet = 0x0ae2,
opentribulletup = 0x0ae3,
opentribulletdown = 0x0ae4,
openstar = 0x0ae5,
enfilledcircbullet = 0x0ae6,
enfilledsqbullet = 0x0ae7,
filledtribulletup = 0x0ae8,
filledtribulletdown = 0x0ae9,
leftpointer = 0x0aea,
rightpointer = 0x0aeb,
club = 0x0aec,
diamond = 0x0aed,
heart = 0x0aee,
maltesecross = 0x0af0,
dagger = 0x0af1,
doubledagger = 0x0af2,
checkmark = 0x0af3,
ballotcross = 0x0af4,
musicalsharp = 0x0af5,
musicalflat = 0x0af6,
malesymbol = 0x0af7,
femalesymbol = 0x0af8,
telephone = 0x0af9,
telephonerecorder = 0x0afa,
phonographcopyright = 0x0afb,
caret = 0x0afc,
singlelowquotemark = 0x0afd,
doublelowquotemark = 0x0afe,
cursor = 0x0aff,
leftcaret = 0x0ba3,
rightcaret = 0x0ba6,
downcaret = 0x0ba8,
upcaret = 0x0ba9,
overbar = 0x0bc0,
downtack = 0x0bc2,
upshoe = 0x0bc3,
downstile = 0x0bc4,
underbar = 0x0bc6,
jot = 0x0bca,
quad = 0x0bcc,
uptack = 0x0bce,
circle = 0x0bcf,
upstile = 0x0bd3,
downshoe = 0x0bd6,
rightshoe = 0x0bd8,
leftshoe = 0x0bda,
lefttack = 0x0bdc,
righttack = 0x0bfc,
hebrew_doublelowline = 0x0cdf,
hebrew_aleph = 0x0ce0,
hebrew_bet = 0x0ce1,
hebrew_beth = 0x0ce1,
hebrew_gimel = 0x0ce2,
hebrew_gimmel = 0x0ce2,
hebrew_dalet = 0x0ce3,
hebrew_daleth = 0x0ce3,
hebrew_he = 0x0ce4,
hebrew_waw = 0x0ce5,
hebrew_zain = 0x0ce6,
hebrew_zayin = 0x0ce6,
hebrew_chet = 0x0ce7,
hebrew_het = 0x0ce7,
hebrew_tet = 0x0ce8,
hebrew_teth = 0x0ce8,
hebrew_yod = 0x0ce9,
hebrew_finalkaph = 0x0cea,
hebrew_kaph = 0x0ceb,
hebrew_lamed = 0x0cec,
hebrew_finalmem = 0x0ced,
hebrew_mem = 0x0cee,
hebrew_finalnun = 0x0cef,
hebrew_nun = 0x0cf0,
hebrew_samech = 0x0cf1,
hebrew_samekh = 0x0cf1,
hebrew_ayin = 0x0cf2,
hebrew_finalpe = 0x0cf3,
hebrew_pe = 0x0cf4,
hebrew_finalzade = 0x0cf5,
hebrew_finalzadi = 0x0cf5,
hebrew_zade = 0x0cf6,
hebrew_zadi = 0x0cf6,
hebrew_qoph = 0x0cf7,
hebrew_kuf = 0x0cf7,
hebrew_resh = 0x0cf8,
hebrew_shin = 0x0cf9,
hebrew_taw = 0x0cfa,
hebrew_taf = 0x0cfa,
Hebrew_switch = 0xff7e,
Thai_kokai = 0x0da1,
Thai_khokhai = 0x0da2,
Thai_khokhuat = 0x0da3,
Thai_khokhwai = 0x0da4,
Thai_khokhon = 0x0da5,
Thai_khorakhang = 0x0da6,
Thai_ngongu = 0x0da7,
Thai_chochan = 0x0da8,
Thai_choching = 0x0da9,
Thai_chochang = 0x0daa,
Thai_soso = 0x0dab,
Thai_chochoe = 0x0dac,
Thai_yoying = 0x0dad,
Thai_dochada = 0x0dae,
Thai_topatak = 0x0daf,
Thai_thothan = 0x0db0,
Thai_thonangmontho = 0x0db1,
Thai_thophuthao = 0x0db2,
Thai_nonen = 0x0db3,
Thai_dodek = 0x0db4,
Thai_totao = 0x0db5,
Thai_thothung = 0x0db6,
Thai_thothahan = 0x0db7,
Thai_thothong = 0x0db8,
Thai_nonu = 0x0db9,
Thai_bobaimai = 0x0dba,
Thai_popla = 0x0dbb,
Thai_phophung = 0x0dbc,
Thai_fofa = 0x0dbd,
Thai_phophan = 0x0dbe,
Thai_fofan = 0x0dbf,
Thai_phosamphao = 0x0dc0,
Thai_moma = 0x0dc1,
Thai_yoyak = 0x0dc2,
Thai_rorua = 0x0dc3,
Thai_ru = 0x0dc4,
Thai_loling = 0x0dc5,
Thai_lu = 0x0dc6,
Thai_wowaen = 0x0dc7,
Thai_sosala = 0x0dc8,
Thai_sorusi = 0x0dc9,
Thai_sosua = 0x0dca,
Thai_hohip = 0x0dcb,
Thai_lochula = 0x0dcc,
Thai_oang = 0x0dcd,
Thai_honokhuk = 0x0dce,
Thai_paiyannoi = 0x0dcf,
Thai_saraa = 0x0dd0,
Thai_maihanakat = 0x0dd1,
Thai_saraaa = 0x0dd2,
Thai_saraam = 0x0dd3,
Thai_sarai = 0x0dd4,
Thai_saraii = 0x0dd5,
Thai_saraue = 0x0dd6,
Thai_sarauee = 0x0dd7,
Thai_sarau = 0x0dd8,
Thai_sarauu = 0x0dd9,
Thai_phinthu = 0x0dda,
Thai_maihanakat_maitho = 0x0dde,
Thai_baht = 0x0ddf,
Thai_sarae = 0x0de0,
Thai_saraae = 0x0de1,
Thai_sarao = 0x0de2,
Thai_saraaimaimuan = 0x0de3,
Thai_saraaimaimalai = 0x0de4,
Thai_lakkhangyao = 0x0de5,
Thai_maiyamok = 0x0de6,
Thai_maitaikhu = 0x0de7,
Thai_maiek = 0x0de8,
Thai_maitho = 0x0de9,
Thai_maitri = 0x0dea,
Thai_maichattawa = 0x0deb,
Thai_thanthakhat = 0x0dec,
Thai_nikhahit = 0x0ded,
Thai_leksun = 0x0df0,
Thai_leknung = 0x0df1,
Thai_leksong = 0x0df2,
Thai_leksam = 0x0df3,
Thai_leksi = 0x0df4,
Thai_lekha = 0x0df5,
Thai_lekhok = 0x0df6,
Thai_lekchet = 0x0df7,
Thai_lekpaet = 0x0df8,
Thai_lekkao = 0x0df9,
Hangul = 0xff31,
Hangul_Start = 0xff32,
Hangul_End = 0xff33,
Hangul_Hanja = 0xff34,
Hangul_Jamo = 0xff35,
Hangul_Romaja = 0xff36,
Hangul_Codeinput = 0xff37,
Hangul_Jeonja = 0xff38,
Hangul_Banja = 0xff39,
Hangul_PreHanja = 0xff3a,
Hangul_PostHanja = 0xff3b,
Hangul_SingleCandidate = 0xff3c,
Hangul_MultipleCandidate = 0xff3d,
Hangul_PreviousCandidate = 0xff3e,
Hangul_Special = 0xff3f,
Hangul_switch = 0xff7e,
Hangul_Kiyeog = 0x0ea1,
Hangul_SsangKiyeog = 0x0ea2,
Hangul_KiyeogSios = 0x0ea3,
Hangul_Nieun = 0x0ea4,
Hangul_NieunJieuj = 0x0ea5,
Hangul_NieunHieuh = 0x0ea6,
Hangul_Dikeud = 0x0ea7,
Hangul_SsangDikeud = 0x0ea8,
Hangul_Rieul = 0x0ea9,
Hangul_RieulKiyeog = 0x0eaa,
Hangul_RieulMieum = 0x0eab,
Hangul_RieulPieub = 0x0eac,
Hangul_RieulSios = 0x0ead,
Hangul_RieulTieut = 0x0eae,
Hangul_RieulPhieuf = 0x0eaf,
Hangul_RieulHieuh = 0x0eb0,
Hangul_Mieum = 0x0eb1,
Hangul_Pieub = 0x0eb2,
Hangul_SsangPieub = 0x0eb3,
Hangul_PieubSios = 0x0eb4,
Hangul_Sios = 0x0eb5,
Hangul_SsangSios = 0x0eb6,
Hangul_Ieung = 0x0eb7,
Hangul_Jieuj = 0x0eb8,
Hangul_SsangJieuj = 0x0eb9,
Hangul_Cieuc = 0x0eba,
Hangul_Khieuq = 0x0ebb,
Hangul_Tieut = 0x0ebc,
Hangul_Phieuf = 0x0ebd,
Hangul_Hieuh = 0x0ebe,
Hangul_A = 0x0ebf,
Hangul_AE = 0x0ec0,
Hangul_YA = 0x0ec1,
Hangul_YAE = 0x0ec2,
Hangul_EO = 0x0ec3,
Hangul_E = 0x0ec4,
Hangul_YEO = 0x0ec5,
Hangul_YE = 0x0ec6,
Hangul_O = 0x0ec7,
Hangul_WA = 0x0ec8,
Hangul_WAE = 0x0ec9,
Hangul_OE = 0x0eca,
Hangul_YO = 0x0ecb,
Hangul_U = 0x0ecc,
Hangul_WEO = 0x0ecd,
Hangul_WE = 0x0ece,
Hangul_WI = 0x0ecf,
Hangul_YU = 0x0ed0,
Hangul_EU = 0x0ed1,
Hangul_YI = 0x0ed2,
Hangul_I = 0x0ed3,
Hangul_J_Kiyeog = 0x0ed4,
Hangul_J_SsangKiyeog = 0x0ed5,
Hangul_J_KiyeogSios = 0x0ed6,
Hangul_J_Nieun = 0x0ed7,
Hangul_J_NieunJieuj = 0x0ed8,
Hangul_J_NieunHieuh = 0x0ed9,
Hangul_J_Dikeud = 0x0eda,
Hangul_J_Rieul = 0x0edb,
Hangul_J_RieulKiyeog = 0x0edc,
Hangul_J_RieulMieum = 0x0edd,
Hangul_J_RieulPieub = 0x0ede,
Hangul_J_RieulSios = 0x0edf,
Hangul_J_RieulTieut = 0x0ee0,
Hangul_J_RieulPhieuf = 0x0ee1,
Hangul_J_RieulHieuh = 0x0ee2,
Hangul_J_Mieum = 0x0ee3,
Hangul_J_Pieub = 0x0ee4,
Hangul_J_PieubSios = 0x0ee5,
Hangul_J_Sios = 0x0ee6,
Hangul_J_SsangSios = 0x0ee7,
Hangul_J_Ieung = 0x0ee8,
Hangul_J_Jieuj = 0x0ee9,
Hangul_J_Cieuc = 0x0eea,
Hangul_J_Khieuq = 0x0eeb,
Hangul_J_Tieut = 0x0eec,
Hangul_J_Phieuf = 0x0eed,
Hangul_J_Hieuh = 0x0eee,
Hangul_RieulYeorinHieuh = 0x0eef,
Hangul_SunkyeongeumMieum = 0x0ef0,
Hangul_SunkyeongeumPieub = 0x0ef1,
Hangul_PanSios = 0x0ef2,
Hangul_KkogjiDalrinIeung = 0x0ef3,
Hangul_SunkyeongeumPhieuf = 0x0ef4,
Hangul_YeorinHieuh = 0x0ef5,
Hangul_AraeA = 0x0ef6,
Hangul_AraeAE = 0x0ef7,
Hangul_J_PanSios = 0x0ef8,
Hangul_J_KkogjiDalrinIeung = 0x0ef9,
Hangul_J_YeorinHieuh = 0x0efa,
Korean_Won = 0x0eff,
Armenian_ligature_ew = 0x1000587,
Armenian_full_stop = 0x1000589,
Armenian_verjaket = 0x1000589,
Armenian_separation_mark = 0x100055d,
Armenian_but = 0x100055d,
Armenian_hyphen = 0x100058a,
Armenian_yentamna = 0x100058a,
Armenian_exclam = 0x100055c,
Armenian_amanak = 0x100055c,
Armenian_accent = 0x100055b,
Armenian_shesht = 0x100055b,
Armenian_question = 0x100055e,
Armenian_paruyk = 0x100055e,
Armenian_AYB = 0x1000531,
Armenian_ayb = 0x1000561,
Armenian_BEN = 0x1000532,
Armenian_ben = 0x1000562,
Armenian_GIM = 0x1000533,
Armenian_gim = 0x1000563,
Armenian_DA = 0x1000534,
Armenian_da = 0x1000564,
Armenian_YECH = 0x1000535,
Armenian_yech = 0x1000565,
Armenian_ZA = 0x1000536,
Armenian_za = 0x1000566,
Armenian_E = 0x1000537,
Armenian_e = 0x1000567,
Armenian_AT = 0x1000538,
Armenian_at = 0x1000568,
Armenian_TO = 0x1000539,
Armenian_to = 0x1000569,
Armenian_ZHE = 0x100053a,
Armenian_zhe = 0x100056a,
Armenian_INI = 0x100053b,
Armenian_ini = 0x100056b,
Armenian_LYUN = 0x100053c,
Armenian_lyun = 0x100056c,
Armenian_KHE = 0x100053d,
Armenian_khe = 0x100056d,
Armenian_TSA = 0x100053e,
Armenian_tsa = 0x100056e,
Armenian_KEN = 0x100053f,
Armenian_ken = 0x100056f,
Armenian_HO = 0x1000540,
Armenian_ho = 0x1000570,
Armenian_DZA = 0x1000541,
Armenian_dza = 0x1000571,
Armenian_GHAT = 0x1000542,
Armenian_ghat = 0x1000572,
Armenian_TCHE = 0x1000543,
Armenian_tche = 0x1000573,
Armenian_MEN = 0x1000544,
Armenian_men = 0x1000574,
Armenian_HI = 0x1000545,
Armenian_hi = 0x1000575,
Armenian_NU = 0x1000546,
Armenian_nu = 0x1000576,
Armenian_SHA = 0x1000547,
Armenian_sha = 0x1000577,
Armenian_VO = 0x1000548,
Armenian_vo = 0x1000578,
Armenian_CHA = 0x1000549,
Armenian_cha = 0x1000579,
Armenian_PE = 0x100054a,
Armenian_pe = 0x100057a,
Armenian_JE = 0x100054b,
Armenian_je = 0x100057b,
Armenian_RA = 0x100054c,
Armenian_ra = 0x100057c,
Armenian_SE = 0x100054d,
Armenian_se = 0x100057d,
Armenian_VEV = 0x100054e,
Armenian_vev = 0x100057e,
Armenian_TYUN = 0x100054f,
Armenian_tyun = 0x100057f,
Armenian_RE = 0x1000550,
Armenian_re = 0x1000580,
Armenian_TSO = 0x1000551,
Armenian_tso = 0x1000581,
Armenian_VYUN = 0x1000552,
Armenian_vyun = 0x1000582,
Armenian_PYUR = 0x1000553,
Armenian_pyur = 0x1000583,
Armenian_KE = 0x1000554,
Armenian_ke = 0x1000584,
Armenian_O = 0x1000555,
Armenian_o = 0x1000585,
Armenian_FE = 0x1000556,
Armenian_fe = 0x1000586,
Armenian_apostrophe = 0x100055a,
Georgian_an = 0x10010d0,
Georgian_ban = 0x10010d1,
Georgian_gan = 0x10010d2,
Georgian_don = 0x10010d3,
Georgian_en = 0x10010d4,
Georgian_vin = 0x10010d5,
Georgian_zen = 0x10010d6,
Georgian_tan = 0x10010d7,
Georgian_in = 0x10010d8,
Georgian_kan = 0x10010d9,
Georgian_las = 0x10010da,
Georgian_man = 0x10010db,
Georgian_nar = 0x10010dc,
Georgian_on = 0x10010dd,
Georgian_par = 0x10010de,
Georgian_zhar = 0x10010df,
Georgian_rae = 0x10010e0,
Georgian_san = 0x10010e1,
Georgian_tar = 0x10010e2,
Georgian_un = 0x10010e3,
Georgian_phar = 0x10010e4,
Georgian_khar = 0x10010e5,
Georgian_ghan = 0x10010e6,
Georgian_qar = 0x10010e7,
Georgian_shin = 0x10010e8,
Georgian_chin = 0x10010e9,
Georgian_can = 0x10010ea,
Georgian_jil = 0x10010eb,
Georgian_cil = 0x10010ec,
Georgian_char = 0x10010ed,
Georgian_xan = 0x10010ee,
Georgian_jhan = 0x10010ef,
Georgian_hae = 0x10010f0,
Georgian_he = 0x10010f1,
Georgian_hie = 0x10010f2,
Georgian_we = 0x10010f3,
Georgian_har = 0x10010f4,
Georgian_hoe = 0x10010f5,
Georgian_fi = 0x10010f6,
Xabovedot = 0x1001e8a,
Ibreve = 0x100012c,
Zstroke = 0x10001b5,
Gcaron = 0x10001e6,
Ocaron = 0x10001d1,
Obarred = 0x100019f,
xabovedot = 0x1001e8b,
ibreve = 0x100012d,
zstroke = 0x10001b6,
gcaron = 0x10001e7,
ocaron = 0x10001d2,
obarred = 0x1000275,
SCHWA = 0x100018f,
schwa = 0x1000259,
EZH = 0x10001b7,
ezh = 0x1000292,
Lbelowdot = 0x1001e36,
lbelowdot = 0x1001e37,
Abelowdot = 0x1001ea0,
abelowdot = 0x1001ea1,
Ahook = 0x1001ea2,
ahook = 0x1001ea3,
Acircumflexacute = 0x1001ea4,
acircumflexacute = 0x1001ea5,
Acircumflexgrave = 0x1001ea6,
acircumflexgrave = 0x1001ea7,
Acircumflexhook = 0x1001ea8,
acircumflexhook = 0x1001ea9,
Acircumflextilde = 0x1001eaa,
acircumflextilde = 0x1001eab,
Acircumflexbelowdot = 0x1001eac,
acircumflexbelowdot = 0x1001ead,
Abreveacute = 0x1001eae,
abreveacute = 0x1001eaf,
Abrevegrave = 0x1001eb0,
abrevegrave = 0x1001eb1,
Abrevehook = 0x1001eb2,
abrevehook = 0x1001eb3,
Abrevetilde = 0x1001eb4,
abrevetilde = 0x1001eb5,
Abrevebelowdot = 0x1001eb6,
abrevebelowdot = 0x1001eb7,
Ebelowdot = 0x1001eb8,
ebelowdot = 0x1001eb9,
Ehook = 0x1001eba,
ehook = 0x1001ebb,
Etilde = 0x1001ebc,
etilde = 0x1001ebd,
Ecircumflexacute = 0x1001ebe,
ecircumflexacute = 0x1001ebf,
Ecircumflexgrave = 0x1001ec0,
ecircumflexgrave = 0x1001ec1,
Ecircumflexhook = 0x1001ec2,
ecircumflexhook = 0x1001ec3,
Ecircumflextilde = 0x1001ec4,
ecircumflextilde = 0x1001ec5,
Ecircumflexbelowdot = 0x1001ec6,
ecircumflexbelowdot = 0x1001ec7,
Ihook = 0x1001ec8,
ihook = 0x1001ec9,
Ibelowdot = 0x1001eca,
ibelowdot = 0x1001ecb,
Obelowdot = 0x1001ecc,
obelowdot = 0x1001ecd,
Ohook = 0x1001ece,
ohook = 0x1001ecf,
Ocircumflexacute = 0x1001ed0,
ocircumflexacute = 0x1001ed1,
Ocircumflexgrave = 0x1001ed2,
ocircumflexgrave = 0x1001ed3,
Ocircumflexhook = 0x1001ed4,
ocircumflexhook = 0x1001ed5,
Ocircumflextilde = 0x1001ed6,
ocircumflextilde = 0x1001ed7,
Ocircumflexbelowdot = 0x1001ed8,
ocircumflexbelowdot = 0x1001ed9,
Ohornacute = 0x1001eda,
ohornacute = 0x1001edb,
Ohorngrave = 0x1001edc,
ohorngrave = 0x1001edd,
Ohornhook = 0x1001ede,
ohornhook = 0x1001edf,
Ohorntilde = 0x1001ee0,
ohorntilde = 0x1001ee1,
Ohornbelowdot = 0x1001ee2,
ohornbelowdot = 0x1001ee3,
Ubelowdot = 0x1001ee4,
ubelowdot = 0x1001ee5,
Uhook = 0x1001ee6,
uhook = 0x1001ee7,
Uhornacute = 0x1001ee8,
uhornacute = 0x1001ee9,
Uhorngrave = 0x1001eea,
uhorngrave = 0x1001eeb,
Uhornhook = 0x1001eec,
uhornhook = 0x1001eed,
Uhorntilde = 0x1001eee,
uhorntilde = 0x1001eef,
Uhornbelowdot = 0x1001ef0,
uhornbelowdot = 0x1001ef1,
Ybelowdot = 0x1001ef4,
ybelowdot = 0x1001ef5,
Yhook = 0x1001ef6,
yhook = 0x1001ef7,
Ytilde = 0x1001ef8,
ytilde = 0x1001ef9,
Ohorn = 0x10001a0,
ohorn = 0x10001a1,
Uhorn = 0x10001af,
uhorn = 0x10001b0,
EcuSign = 0x10020a0,
ColonSign = 0x10020a1,
CruzeiroSign = 0x10020a2,
FFrancSign = 0x10020a3,
LiraSign = 0x10020a4,
MillSign = 0x10020a5,
NairaSign = 0x10020a6,
PesetaSign = 0x10020a7,
RupeeSign = 0x10020a8,
WonSign = 0x10020a9,
NewSheqelSign = 0x10020aa,
DongSign = 0x10020ab,
EuroSign = 0x20ac,
zerosuperior = 0x1002070,
foursuperior = 0x1002074,
fivesuperior = 0x1002075,
sixsuperior = 0x1002076,
sevensuperior = 0x1002077,
eightsuperior = 0x1002078,
ninesuperior = 0x1002079,
zerosubscript = 0x1002080,
onesubscript = 0x1002081,
twosubscript = 0x1002082,
threesubscript = 0x1002083,
foursubscript = 0x1002084,
fivesubscript = 0x1002085,
sixsubscript = 0x1002086,
sevensubscript = 0x1002087,
eightsubscript = 0x1002088,
ninesubscript = 0x1002089,
partdifferential = 0x1002202,
emptyset = 0x1002205,
elementof = 0x1002208,
notelementof = 0x1002209,
containsas = 0x100220B,
squareroot = 0x100221A,
cuberoot = 0x100221B,
fourthroot = 0x100221C,
dintegral = 0x100222C,
tintegral = 0x100222D,
because = 0x1002235,
approxeq = 0x1002248,
notapproxeq = 0x1002247,
notidentical = 0x1002262,
stricteq = 0x1002263,
braille_dot_1 = 0xfff1,
braille_dot_2 = 0xfff2,
braille_dot_3 = 0xfff3,
braille_dot_4 = 0xfff4,
braille_dot_5 = 0xfff5,
braille_dot_6 = 0xfff6,
braille_dot_7 = 0xfff7,
braille_dot_8 = 0xfff8,
braille_dot_9 = 0xfff9,
braille_dot_10 = 0xfffa,
braille_blank = 0x1002800,
braille_dots_1 = 0x1002801,
braille_dots_2 = 0x1002802,
braille_dots_12 = 0x1002803,
braille_dots_3 = 0x1002804,
braille_dots_13 = 0x1002805,
braille_dots_23 = 0x1002806,
braille_dots_123 = 0x1002807,
braille_dots_4 = 0x1002808,
braille_dots_14 = 0x1002809,
braille_dots_24 = 0x100280a,
braille_dots_124 = 0x100280b,
braille_dots_34 = 0x100280c,
braille_dots_134 = 0x100280d,
braille_dots_234 = 0x100280e,
braille_dots_1234 = 0x100280f,
braille_dots_5 = 0x1002810,
braille_dots_15 = 0x1002811,
braille_dots_25 = 0x1002812,
braille_dots_125 = 0x1002813,
braille_dots_35 = 0x1002814,
braille_dots_135 = 0x1002815,
braille_dots_235 = 0x1002816,
braille_dots_1235 = 0x1002817,
braille_dots_45 = 0x1002818,
braille_dots_145 = 0x1002819,
braille_dots_245 = 0x100281a,
braille_dots_1245 = 0x100281b,
braille_dots_345 = 0x100281c,
braille_dots_1345 = 0x100281d,
braille_dots_2345 = 0x100281e,
braille_dots_12345 = 0x100281f,
braille_dots_6 = 0x1002820,
braille_dots_16 = 0x1002821,
braille_dots_26 = 0x1002822,
braille_dots_126 = 0x1002823,
braille_dots_36 = 0x1002824,
braille_dots_136 = 0x1002825,
braille_dots_236 = 0x1002826,
braille_dots_1236 = 0x1002827,
braille_dots_46 = 0x1002828,
braille_dots_146 = 0x1002829,
braille_dots_246 = 0x100282a,
braille_dots_1246 = 0x100282b,
braille_dots_346 = 0x100282c,
braille_dots_1346 = 0x100282d,
braille_dots_2346 = 0x100282e,
braille_dots_12346 = 0x100282f,
braille_dots_56 = 0x1002830,
braille_dots_156 = 0x1002831,
braille_dots_256 = 0x1002832,
braille_dots_1256 = 0x1002833,
braille_dots_356 = 0x1002834,
braille_dots_1356 = 0x1002835,
braille_dots_2356 = 0x1002836,
braille_dots_12356 = 0x1002837,
braille_dots_456 = 0x1002838,
braille_dots_1456 = 0x1002839,
braille_dots_2456 = 0x100283a,
braille_dots_12456 = 0x100283b,
braille_dots_3456 = 0x100283c,
braille_dots_13456 = 0x100283d,
braille_dots_23456 = 0x100283e,
braille_dots_123456 = 0x100283f,
braille_dots_7 = 0x1002840,
braille_dots_17 = 0x1002841,
braille_dots_27 = 0x1002842,
braille_dots_127 = 0x1002843,
braille_dots_37 = 0x1002844,
braille_dots_137 = 0x1002845,
braille_dots_237 = 0x1002846,
braille_dots_1237 = 0x1002847,
braille_dots_47 = 0x1002848,
braille_dots_147 = 0x1002849,
braille_dots_247 = 0x100284a,
braille_dots_1247 = 0x100284b,
braille_dots_347 = 0x100284c,
braille_dots_1347 = 0x100284d,
braille_dots_2347 = 0x100284e,
braille_dots_12347 = 0x100284f,
braille_dots_57 = 0x1002850,
braille_dots_157 = 0x1002851,
braille_dots_257 = 0x1002852,
braille_dots_1257 = 0x1002853,
braille_dots_357 = 0x1002854,
braille_dots_1357 = 0x1002855,
braille_dots_2357 = 0x1002856,
braille_dots_12357 = 0x1002857,
braille_dots_457 = 0x1002858,
braille_dots_1457 = 0x1002859,
braille_dots_2457 = 0x100285a,
braille_dots_12457 = 0x100285b,
braille_dots_3457 = 0x100285c,
braille_dots_13457 = 0x100285d,
braille_dots_23457 = 0x100285e,
braille_dots_123457 = 0x100285f,
braille_dots_67 = 0x1002860,
braille_dots_167 = 0x1002861,
braille_dots_267 = 0x1002862,
braille_dots_1267 = 0x1002863,
braille_dots_367 = 0x1002864,
braille_dots_1367 = 0x1002865,
braille_dots_2367 = 0x1002866,
braille_dots_12367 = 0x1002867,
braille_dots_467 = 0x1002868,
braille_dots_1467 = 0x1002869,
braille_dots_2467 = 0x100286a,
braille_dots_12467 = 0x100286b,
braille_dots_3467 = 0x100286c,
braille_dots_13467 = 0x100286d,
braille_dots_23467 = 0x100286e,
braille_dots_123467 = 0x100286f,
braille_dots_567 = 0x1002870,
braille_dots_1567 = 0x1002871,
braille_dots_2567 = 0x1002872,
braille_dots_12567 = 0x1002873,
braille_dots_3567 = 0x1002874,
braille_dots_13567 = 0x1002875,
braille_dots_23567 = 0x1002876,
braille_dots_123567 = 0x1002877,
braille_dots_4567 = 0x1002878,
braille_dots_14567 = 0x1002879,
braille_dots_24567 = 0x100287a,
braille_dots_124567 = 0x100287b,
braille_dots_34567 = 0x100287c,
braille_dots_134567 = 0x100287d,
braille_dots_234567 = 0x100287e,
braille_dots_1234567 = 0x100287f,
braille_dots_8 = 0x1002880,
braille_dots_18 = 0x1002881,
braille_dots_28 = 0x1002882,
braille_dots_128 = 0x1002883,
braille_dots_38 = 0x1002884,
braille_dots_138 = 0x1002885,
braille_dots_238 = 0x1002886,
braille_dots_1238 = 0x1002887,
braille_dots_48 = 0x1002888,
braille_dots_148 = 0x1002889,
braille_dots_248 = 0x100288a,
braille_dots_1248 = 0x100288b,
braille_dots_348 = 0x100288c,
braille_dots_1348 = 0x100288d,
braille_dots_2348 = 0x100288e,
braille_dots_12348 = 0x100288f,
braille_dots_58 = 0x1002890,
braille_dots_158 = 0x1002891,
braille_dots_258 = 0x1002892,
braille_dots_1258 = 0x1002893,
braille_dots_358 = 0x1002894,
braille_dots_1358 = 0x1002895,
braille_dots_2358 = 0x1002896,
braille_dots_12358 = 0x1002897,
braille_dots_458 = 0x1002898,
braille_dots_1458 = 0x1002899,
braille_dots_2458 = 0x100289a,
braille_dots_12458 = 0x100289b,
braille_dots_3458 = 0x100289c,
braille_dots_13458 = 0x100289d,
braille_dots_23458 = 0x100289e,
braille_dots_123458 = 0x100289f,
braille_dots_68 = 0x10028a0,
braille_dots_168 = 0x10028a1,
braille_dots_268 = 0x10028a2,
braille_dots_1268 = 0x10028a3,
braille_dots_368 = 0x10028a4,
braille_dots_1368 = 0x10028a5,
braille_dots_2368 = 0x10028a6,
braille_dots_12368 = 0x10028a7,
braille_dots_468 = 0x10028a8,
braille_dots_1468 = 0x10028a9,
braille_dots_2468 = 0x10028aa,
braille_dots_12468 = 0x10028ab,
braille_dots_3468 = 0x10028ac,
braille_dots_13468 = 0x10028ad,
braille_dots_23468 = 0x10028ae,
braille_dots_123468 = 0x10028af,
braille_dots_568 = 0x10028b0,
braille_dots_1568 = 0x10028b1,
braille_dots_2568 = 0x10028b2,
braille_dots_12568 = 0x10028b3,
braille_dots_3568 = 0x10028b4,
braille_dots_13568 = 0x10028b5,
braille_dots_23568 = 0x10028b6,
braille_dots_123568 = 0x10028b7,
braille_dots_4568 = 0x10028b8,
braille_dots_14568 = 0x10028b9,
braille_dots_24568 = 0x10028ba,
braille_dots_124568 = 0x10028bb,
braille_dots_34568 = 0x10028bc,
braille_dots_134568 = 0x10028bd,
braille_dots_234568 = 0x10028be,
braille_dots_1234568 = 0x10028bf,
braille_dots_78 = 0x10028c0,
braille_dots_178 = 0x10028c1,
braille_dots_278 = 0x10028c2,
braille_dots_1278 = 0x10028c3,
braille_dots_378 = 0x10028c4,
braille_dots_1378 = 0x10028c5,
braille_dots_2378 = 0x10028c6,
braille_dots_12378 = 0x10028c7,
braille_dots_478 = 0x10028c8,
braille_dots_1478 = 0x10028c9,
braille_dots_2478 = 0x10028ca,
braille_dots_12478 = 0x10028cb,
braille_dots_3478 = 0x10028cc,
braille_dots_13478 = 0x10028cd,
braille_dots_23478 = 0x10028ce,
braille_dots_123478 = 0x10028cf,
braille_dots_578 = 0x10028d0,
braille_dots_1578 = 0x10028d1,
braille_dots_2578 = 0x10028d2,
braille_dots_12578 = 0x10028d3,
braille_dots_3578 = 0x10028d4,
braille_dots_13578 = 0x10028d5,
braille_dots_23578 = 0x10028d6,
braille_dots_123578 = 0x10028d7,
braille_dots_4578 = 0x10028d8,
braille_dots_14578 = 0x10028d9,
braille_dots_24578 = 0x10028da,
braille_dots_124578 = 0x10028db,
braille_dots_34578 = 0x10028dc,
braille_dots_134578 = 0x10028dd,
braille_dots_234578 = 0x10028de,
braille_dots_1234578 = 0x10028df,
braille_dots_678 = 0x10028e0,
braille_dots_1678 = 0x10028e1,
braille_dots_2678 = 0x10028e2,
braille_dots_12678 = 0x10028e3,
braille_dots_3678 = 0x10028e4,
braille_dots_13678 = 0x10028e5,
braille_dots_23678 = 0x10028e6,
braille_dots_123678 = 0x10028e7,
braille_dots_4678 = 0x10028e8,
braille_dots_14678 = 0x10028e9,
braille_dots_24678 = 0x10028ea,
braille_dots_124678 = 0x10028eb,
braille_dots_34678 = 0x10028ec,
braille_dots_134678 = 0x10028ed,
braille_dots_234678 = 0x10028ee,
braille_dots_1234678 = 0x10028ef,
braille_dots_5678 = 0x10028f0,
braille_dots_15678 = 0x10028f1,
braille_dots_25678 = 0x10028f2,
braille_dots_125678 = 0x10028f3,
braille_dots_35678 = 0x10028f4,
braille_dots_135678 = 0x10028f5,
braille_dots_235678 = 0x10028f6,
braille_dots_1235678 = 0x10028f7,
braille_dots_45678 = 0x10028f8,
braille_dots_145678 = 0x10028f9,
braille_dots_245678 = 0x10028fa,
braille_dots_1245678 = 0x10028fb,
braille_dots_345678 = 0x10028fc,
braille_dots_1345678 = 0x10028fd,
braille_dots_2345678 = 0x10028fe,
braille_dots_12345678 = 0x10028ff,
Sinh_ng = 0x1000d82,
Sinh_h2 = 0x1000d83,
Sinh_a = 0x1000d85,
Sinh_aa = 0x1000d86,
Sinh_ae = 0x1000d87,
Sinh_aee = 0x1000d88,
Sinh_i = 0x1000d89,
Sinh_ii = 0x1000d8a,
Sinh_u = 0x1000d8b,
Sinh_uu = 0x1000d8c,
Sinh_ri = 0x1000d8d,
Sinh_rii = 0x1000d8e,
Sinh_lu = 0x1000d8f,
Sinh_luu = 0x1000d90,
Sinh_e = 0x1000d91,
Sinh_ee = 0x1000d92,
Sinh_ai = 0x1000d93,
Sinh_o = 0x1000d94,
Sinh_oo = 0x1000d95,
Sinh_au = 0x1000d96,
Sinh_ka = 0x1000d9a,
Sinh_kha = 0x1000d9b,
Sinh_ga = 0x1000d9c,
Sinh_gha = 0x1000d9d,
Sinh_ng2 = 0x1000d9e,
Sinh_nga = 0x1000d9f,
Sinh_ca = 0x1000da0,
Sinh_cha = 0x1000da1,
Sinh_ja = 0x1000da2,
Sinh_jha = 0x1000da3,
Sinh_nya = 0x1000da4,
Sinh_jnya = 0x1000da5,
Sinh_nja = 0x1000da6,
Sinh_tta = 0x1000da7,
Sinh_ttha = 0x1000da8,
Sinh_dda = 0x1000da9,
Sinh_ddha = 0x1000daa,
Sinh_nna = 0x1000dab,
Sinh_ndda = 0x1000dac,
Sinh_tha = 0x1000dad,
Sinh_thha = 0x1000dae,
Sinh_dha = 0x1000daf,
Sinh_dhha = 0x1000db0,
Sinh_na = 0x1000db1,
Sinh_ndha = 0x1000db3,
Sinh_pa = 0x1000db4,
Sinh_pha = 0x1000db5,
Sinh_ba = 0x1000db6,
Sinh_bha = 0x1000db7,
Sinh_ma = 0x1000db8,
Sinh_mba = 0x1000db9,
Sinh_ya = 0x1000dba,
Sinh_ra = 0x1000dbb,
Sinh_la = 0x1000dbd,
Sinh_va = 0x1000dc0,
Sinh_sha = 0x1000dc1,
Sinh_ssha = 0x1000dc2,
Sinh_sa = 0x1000dc3,
Sinh_ha = 0x1000dc4,
Sinh_lla = 0x1000dc5,
Sinh_fa = 0x1000dc6,
Sinh_al = 0x1000dca,
Sinh_aa2 = 0x1000dcf,
Sinh_ae2 = 0x1000dd0,
Sinh_aee2 = 0x1000dd1,
Sinh_i2 = 0x1000dd2,
Sinh_ii2 = 0x1000dd3,
Sinh_u2 = 0x1000dd4,
Sinh_uu2 = 0x1000dd6,
Sinh_ru2 = 0x1000dd8,
Sinh_e2 = 0x1000dd9,
Sinh_ee2 = 0x1000dda,
Sinh_ai2 = 0x1000ddb,
Sinh_o2 = 0x1000ddc,
Sinh_oo2 = 0x1000ddd,
Sinh_au2 = 0x1000dde,
Sinh_lu2 = 0x1000ddf,
Sinh_ruu2 = 0x1000df2,
Sinh_luu2 = 0x1000df3,
Sinh_kunddaliya = 0x1000df4,
XF86ModeLock = 0x1008FF01,
XF86MonBrightnessUp = 0x1008FF02,
XF86MonBrightnessDown = 0x1008FF03,
XF86KbdLightOnOff = 0x1008FF04,
XF86KbdBrightnessUp = 0x1008FF05,
XF86KbdBrightnessDown = 0x1008FF06,
XF86MonBrightnessCycle = 0x1008FF07,
XF86Standby = 0x1008FF10,
XF86AudioLowerVolume = 0x1008FF11,
XF86AudioMute = 0x1008FF12,
XF86AudioRaiseVolume = 0x1008FF13,
XF86AudioPlay = 0x1008FF14,
XF86AudioStop = 0x1008FF15,
XF86AudioPrev = 0x1008FF16,
XF86AudioNext = 0x1008FF17,
XF86HomePage = 0x1008FF18,
XF86Mail = 0x1008FF19,
XF86Start = 0x1008FF1A,
XF86Search = 0x1008FF1B,
XF86AudioRecord = 0x1008FF1C,
XF86Calculator = 0x1008FF1D,
XF86Memo = 0x1008FF1E,
XF86ToDoList = 0x1008FF1F,
XF86Calendar = 0x1008FF20,
XF86PowerDown = 0x1008FF21,
XF86ContrastAdjust = 0x1008FF22,
XF86RockerUp = 0x1008FF23,
XF86RockerDown = 0x1008FF24,
XF86RockerEnter = 0x1008FF25,
XF86Back = 0x1008FF26,
XF86Forward = 0x1008FF27,
XF86Stop = 0x1008FF28,
XF86Refresh = 0x1008FF29,
XF86PowerOff = 0x1008FF2A,
XF86WakeUp = 0x1008FF2B,
XF86Eject = 0x1008FF2C,
XF86ScreenSaver = 0x1008FF2D,
XF86WWW = 0x1008FF2E,
XF86Sleep = 0x1008FF2F,
XF86Favorites = 0x1008FF30,
XF86AudioPause = 0x1008FF31,
XF86AudioMedia = 0x1008FF32,
XF86MyComputer = 0x1008FF33,
XF86VendorHome = 0x1008FF34,
XF86LightBulb = 0x1008FF35,
XF86Shop = 0x1008FF36,
XF86History = 0x1008FF37,
XF86OpenURL = 0x1008FF38,
XF86AddFavorite = 0x1008FF39,
XF86HotLinks = 0x1008FF3A,
XF86BrightnessAdjust = 0x1008FF3B,
XF86Finance = 0x1008FF3C,
XF86Community = 0x1008FF3D,
XF86AudioRewind = 0x1008FF3E,
XF86BackForward = 0x1008FF3F,
XF86Launch0 = 0x1008FF40,
XF86Launch1 = 0x1008FF41,
XF86Launch2 = 0x1008FF42,
XF86Launch3 = 0x1008FF43,
XF86Launch4 = 0x1008FF44,
XF86Launch5 = 0x1008FF45,
XF86Launch6 = 0x1008FF46,
XF86Launch7 = 0x1008FF47,
XF86Launch8 = 0x1008FF48,
XF86Launch9 = 0x1008FF49,
XF86LaunchA = 0x1008FF4A,
XF86LaunchB = 0x1008FF4B,
XF86LaunchC = 0x1008FF4C,
XF86LaunchD = 0x1008FF4D,
XF86LaunchE = 0x1008FF4E,
XF86LaunchF = 0x1008FF4F,
XF86ApplicationLeft = 0x1008FF50,
XF86ApplicationRight = 0x1008FF51,
XF86Book = 0x1008FF52,
XF86CD = 0x1008FF53,
XF86Calculater = 0x1008FF54,
XF86Clear = 0x1008FF55,
XF86Close = 0x1008FF56,
XF86Copy = 0x1008FF57,
XF86Cut = 0x1008FF58,
XF86Display = 0x1008FF59,
XF86DOS = 0x1008FF5A,
XF86Documents = 0x1008FF5B,
XF86Excel = 0x1008FF5C,
XF86Explorer = 0x1008FF5D,
XF86Game = 0x1008FF5E,
XF86Go = 0x1008FF5F,
XF86iTouch = 0x1008FF60,
XF86LogOff = 0x1008FF61,
XF86Market = 0x1008FF62,
XF86Meeting = 0x1008FF63,
XF86MenuKB = 0x1008FF65,
XF86MenuPB = 0x1008FF66,
XF86MySites = 0x1008FF67,
XF86New = 0x1008FF68,
XF86News = 0x1008FF69,
XF86OfficeHome = 0x1008FF6A,
XF86Open = 0x1008FF6B,
XF86Option = 0x1008FF6C,
XF86Paste = 0x1008FF6D,
XF86Phone = 0x1008FF6E,
XF86Q = 0x1008FF70,
XF86Reply = 0x1008FF72,
XF86Reload = 0x1008FF73,
XF86RotateWindows = 0x1008FF74,
XF86RotationPB = 0x1008FF75,
XF86RotationKB = 0x1008FF76,
XF86Save = 0x1008FF77,
XF86ScrollUp = 0x1008FF78,
XF86ScrollDown = 0x1008FF79,
XF86ScrollClick = 0x1008FF7A,
XF86Send = 0x1008FF7B,
XF86Spell = 0x1008FF7C,
XF86SplitScreen = 0x1008FF7D,
XF86Support = 0x1008FF7E,
XF86TaskPane = 0x1008FF7F,
XF86Terminal = 0x1008FF80,
XF86Tools = 0x1008FF81,
XF86Travel = 0x1008FF82,
XF86UserPB = 0x1008FF84,
XF86User1KB = 0x1008FF85,
XF86User2KB = 0x1008FF86,
XF86Video = 0x1008FF87,
XF86WheelButton = 0x1008FF88,
XF86Word = 0x1008FF89,
XF86Xfer = 0x1008FF8A,
XF86ZoomIn = 0x1008FF8B,
XF86ZoomOut = 0x1008FF8C,
XF86Away = 0x1008FF8D,
XF86Messenger = 0x1008FF8E,
XF86WebCam = 0x1008FF8F,
XF86MailForward = 0x1008FF90,
XF86Pictures = 0x1008FF91,
XF86Music = 0x1008FF92,
XF86Battery = 0x1008FF93,
XF86Bluetooth = 0x1008FF94,
XF86WLAN = 0x1008FF95,
XF86UWB = 0x1008FF96,
XF86AudioForward = 0x1008FF97,
XF86AudioRepeat = 0x1008FF98,
XF86AudioRandomPlay = 0x1008FF99,
XF86Subtitle = 0x1008FF9A,
XF86AudioCycleTrack = 0x1008FF9B,
XF86CycleAngle = 0x1008FF9C,
XF86FrameBack = 0x1008FF9D,
XF86FrameForward = 0x1008FF9E,
XF86Time = 0x1008FF9F,
XF86Select = 0x1008FFA0,
XF86View = 0x1008FFA1,
XF86TopMenu = 0x1008FFA2,
XF86Red = 0x1008FFA3,
XF86Green = 0x1008FFA4,
XF86Yellow = 0x1008FFA5,
XF86Blue = 0x1008FFA6,
XF86Suspend = 0x1008FFA7,
XF86Hibernate = 0x1008FFA8,
XF86TouchpadToggle = 0x1008FFA9,
XF86TouchpadOn = 0x1008FFB0,
XF86TouchpadOff = 0x1008FFB1,
XF86AudioMicMute = 0x1008FFB2,
XF86Keyboard = 0x1008FFB3,
XF86WWAN = 0x1008FFB4,
XF86RFKill = 0x1008FFB5,
XF86AudioPreset = 0x1008FFB6,
XF86RotationLockToggle = 0x1008FFB7,
XF86FullScreen = 0x1008FFB8,
XF86Switch_VT_1 = 0x1008FE01,
XF86Switch_VT_2 = 0x1008FE02,
XF86Switch_VT_3 = 0x1008FE03,
XF86Switch_VT_4 = 0x1008FE04,
XF86Switch_VT_5 = 0x1008FE05,
XF86Switch_VT_6 = 0x1008FE06,
XF86Switch_VT_7 = 0x1008FE07,
XF86Switch_VT_8 = 0x1008FE08,
XF86Switch_VT_9 = 0x1008FE09,
XF86Switch_VT_10 = 0x1008FE0A,
XF86Switch_VT_11 = 0x1008FE0B,
XF86Switch_VT_12 = 0x1008FE0C,
XF86Ungrab = 0x1008FE20,
XF86ClearGrab = 0x1008FE21,
XF86Next_VMode = 0x1008FE22,
XF86Prev_VMode = 0x1008FE23,
XF86LogWindowTree = 0x1008FE24,
XF86LogGrabInfo = 0x1008FE25,
SunFA_Grave = 0x1005FF00,
SunFA_Circum = 0x1005FF01,
SunFA_Tilde = 0x1005FF02,
SunFA_Acute = 0x1005FF03,
SunFA_Diaeresis = 0x1005FF04,
SunFA_Cedilla = 0x1005FF05,
SunF36 = 0x1005FF10,
SunF37 = 0x1005FF11,
SunSys_Req = 0x1005FF60,
SunPrint_Screen = 0x0000FF61,
SunCompose = 0x0000FF20,
SunAltGraph = 0x0000FF7E,
SunPageUp = 0x0000FF55,
SunPageDown = 0x0000FF56,
SunUndo = 0x0000FF65,
SunAgain = 0x0000FF66,
SunFind = 0x0000FF68,
SunStop = 0x0000FF69,
SunProps = 0x1005FF70,
SunFront = 0x1005FF71,
SunCopy = 0x1005FF72,
SunOpen = 0x1005FF73,
SunPaste = 0x1005FF74,
SunCut = 0x1005FF75,
SunPowerSwitch = 0x1005FF76,
SunAudioLowerVolume = 0x1005FF77,
SunAudioMute = 0x1005FF78,
SunAudioRaiseVolume = 0x1005FF79,
SunVideoDegauss = 0x1005FF7A,
SunVideoLowerBrightness = 0x1005FF7B,
SunVideoRaiseBrightness = 0x1005FF7C,
SunPowerSwitchShift = 0x1005FF7D,
Dring_accent = 0x1000FEB0,
Dcircumflex_accent = 0x1000FE5E,
Dcedilla_accent = 0x1000FE2C,
Dacute_accent = 0x1000FE27,
Dgrave_accent = 0x1000FE60,
Dtilde = 0x1000FE7E,
Ddiaeresis = 0x1000FE22,
DRemove = 0x1000FF00,
hpClearLine = 0x1000FF6F,
hpInsertLine = 0x1000FF70,
hpDeleteLine = 0x1000FF71,
hpInsertChar = 0x1000FF72,
hpDeleteChar = 0x1000FF73,
hpBackTab = 0x1000FF74,
hpKP_BackTab = 0x1000FF75,
hpModelock1 = 0x1000FF48,
hpModelock2 = 0x1000FF49,
hpReset = 0x1000FF6C,
hpSystem = 0x1000FF6D,
hpUser = 0x1000FF6E,
hpmute_acute = 0x100000A8,
hpmute_grave = 0x100000A9,
hpmute_asciicircum = 0x100000AA,
hpmute_diaeresis = 0x100000AB,
hpmute_asciitilde = 0x100000AC,
hplira = 0x100000AF,
hpguilder = 0x100000BE,
hpYdiaeresis = 0x100000EE,
hpIO = 0x100000EE,
hplongminus = 0x100000F6,
hpblock = 0x100000FC,
osfCopy = 0x1004FF02,
osfCut = 0x1004FF03,
osfPaste = 0x1004FF04,
osfBackTab = 0x1004FF07,
osfBackSpace = 0x1004FF08,
osfClear = 0x1004FF0B,
osfEscape = 0x1004FF1B,
osfAddMode = 0x1004FF31,
osfPrimaryPaste = 0x1004FF32,
osfQuickPaste = 0x1004FF33,
osfPageLeft = 0x1004FF40,
osfPageUp = 0x1004FF41,
osfPageDown = 0x1004FF42,
osfPageRight = 0x1004FF43,
osfActivate = 0x1004FF44,
osfMenuBar = 0x1004FF45,
osfLeft = 0x1004FF51,
osfUp = 0x1004FF52,
osfRight = 0x1004FF53,
osfDown = 0x1004FF54,
osfEndLine = 0x1004FF57,
osfBeginLine = 0x1004FF58,
osfEndData = 0x1004FF59,
osfBeginData = 0x1004FF5A,
osfPrevMenu = 0x1004FF5B,
osfNextMenu = 0x1004FF5C,
osfPrevField = 0x1004FF5D,
osfNextField = 0x1004FF5E,
osfSelect = 0x1004FF60,
osfInsert = 0x1004FF63,
osfUndo = 0x1004FF65,
osfMenu = 0x1004FF67,
osfCancel = 0x1004FF69,
osfHelp = 0x1004FF6A,
osfSelectAll = 0x1004FF71,
osfDeselectAll = 0x1004FF72,
osfReselect = 0x1004FF73,
osfExtend = 0x1004FF74,
osfRestore = 0x1004FF78,
osfDelete = 0x1004FFFF,
Reset = 0x1000FF6C,
System = 0x1000FF6D,
User = 0x1000FF6E,
ClearLine = 0x1000FF6F,
InsertLine = 0x1000FF70,
DeleteLine = 0x1000FF71,
InsertChar = 0x1000FF72,
DeleteChar = 0x1000FF73,
BackTab = 0x1000FF74,
KP_BackTab = 0x1000FF75,
Ext16bit_L = 0x1000FF76,
Ext16bit_R = 0x1000FF77,
mute_acute = 0x100000a8,
mute_grave = 0x100000a9,
mute_asciicircum = 0x100000aa,
mute_diaeresis = 0x100000ab,
mute_asciitilde = 0x100000ac,
lira = 0x100000af,
guilder = 0x100000be,
IO = 0x100000ee,
longminus = 0x100000f6,
block = 0x100000fc,
_,
pub const Flags = extern enum {
no_flags = 0,
case_insensitive = 1 << 0,
};
extern fn xkb_keysym_get_name(keysym: Keysym, buffer: [*]u8, size: usize) c_int;
pub const getName = xkb_keysym_get_name;
extern fn xkb_keysym_from_name(name: [*:0]const u8, flags: Flags) Keysym;
pub const fromName = xkb_keysym_from_name;
extern fn xkb_keysym_to_utf8(keysym: Keysym, buffer: [*]u8, size: usize) c_int;
pub const toUTF8 = xkb_keysym_to_utf8;
extern fn xkb_keysym_to_utf32(keysym: Keysym) u32;
pub const toUTF32 = xkb_keysym_to_utf32;
extern fn xkb_utf32_to_keysym(ucs: u32) Keysym;
pub const fromUTF32 = xkb_utf32_to_keysym;
extern fn xkb_keysym_to_upper(ks: Keysym) Keysym;
pub const toUpper = xkb_keysym_to_upper;
extern fn xkb_keysym_to_lower(ks: Keysym) Keysym;
pub const toLower = xkb_keysym_to_lower;
}; | source/river-0.1.0/deps/zig-xkbcommon/src/xkbcommon_keysyms.zig |
const Self = @This();
const std = @import("std");
const wlr = @import("wlroots");
const wl = @import("wayland").server.wl;
const xkb = @import("xkbcommon");
const server = &@import("main.zig").server;
const util = @import("util.zig");
const Seat = @import("Seat.zig");
const log = std.log.scoped(.keyboard);
seat: *Seat,
input_device: *wlr.InputDevice,
key: wl.Listener(*wlr.Keyboard.event.Key) = wl.Listener(*wlr.Keyboard.event.Key).init(handleKey),
modifiers: wl.Listener(*wlr.Keyboard) = wl.Listener(*wlr.Keyboard).init(handleModifiers),
destroy: wl.Listener(*wlr.Keyboard) = wl.Listener(*wlr.Keyboard).init(handleDestroy),
pub fn init(self: *Self, seat: *Seat, input_device: *wlr.InputDevice) !void {
self.* = .{
.seat = seat,
.input_device = input_device,
};
// We need to prepare an XKB keymap and assign it to the keyboard. This
// assumes the defaults (e.g. layout = "us").
const rules = xkb.RuleNames{
.rules = null,
.model = null,
.layout = null,
.variant = null,
.options = null,
};
const context = xkb.Context.new(.no_flags) orelse return error.XkbContextFailed;
defer context.unref();
const keymap = xkb.Keymap.newFromNames(context, &rules, .no_flags) orelse return error.XkbKeymapFailed;
defer keymap.unref();
const wlr_keyboard = self.input_device.device.keyboard;
if (!wlr_keyboard.setKeymap(keymap)) return error.SetKeymapFailed;
wlr_keyboard.setRepeatInfo(server.config.repeat_rate, server.config.repeat_delay);
wlr_keyboard.events.key.add(&self.key);
wlr_keyboard.events.modifiers.add(&self.modifiers);
wlr_keyboard.events.destroy.add(&self.destroy);
}
pub fn deinit(self: *Self) void {
self.key.link.remove();
self.modifiers.link.remove();
self.destroy.link.remove();
}
fn handleKey(listener: *wl.Listener(*wlr.Keyboard.event.Key), event: *wlr.Keyboard.event.Key) void {
// This event is raised when a key is pressed or released.
const self = @fieldParentPtr(Self, "key", listener);
const wlr_keyboard = self.input_device.device.keyboard;
self.seat.handleActivity();
self.seat.clearRepeatingMapping();
// Translate libinput keycode -> xkbcommon
const keycode = event.keycode + 8;
// TODO: These modifiers aren't properly handled, see sway's code
const modifiers = wlr_keyboard.getModifiers();
const released = event.state == .released;
var handled = false;
// First check translated keysyms as xkb reports them
for (wlr_keyboard.xkb_state.?.keyGetSyms(keycode)) |sym| {
// Handle builtin mapping only when keys are pressed
if (!released and self.handleBuiltinMapping(sym)) {
handled = true;
break;
} else if (self.seat.handleMapping(sym, modifiers, released)) {
handled = true;
break;
}
}
// If not yet handled, check keysyms ignoring modifiers (e.g. 1 instead of !)
// Important for mappings like Mod+Shift+1
if (!handled) {
const layout_index = wlr_keyboard.xkb_state.?.keyGetLayout(keycode);
for (wlr_keyboard.keymap.?.keyGetSymsByLevel(keycode, layout_index, 0)) |sym| {
// Handle builtin mapping only when keys are pressed
if (!released and self.handleBuiltinMapping(sym)) {
handled = true;
break;
} else if (self.seat.handleMapping(sym, modifiers, released)) {
handled = true;
break;
}
}
}
if (!handled) {
// Otherwise, we pass it along to the client.
const wlr_seat = self.seat.wlr_seat;
wlr_seat.setKeyboard(self.input_device);
wlr_seat.keyboardNotifyKey(event.time_msec, event.keycode, event.state);
}
}
/// Simply pass modifiers along to the client
fn handleModifiers(listener: *wl.Listener(*wlr.Keyboard), wlr_keyboard: *wlr.Keyboard) void {
const self = @fieldParentPtr(Self, "modifiers", listener);
self.seat.wlr_seat.setKeyboard(self.input_device);
self.seat.wlr_seat.keyboardNotifyModifiers(&self.input_device.device.keyboard.modifiers);
}
fn handleDestroy(listener: *wl.Listener(*wlr.Keyboard), wlr_keyboard: *wlr.Keyboard) void {
const self = @fieldParentPtr(Self, "destroy", listener);
const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self);
self.seat.keyboards.remove(node);
self.deinit();
util.gpa.destroy(node);
}
/// Handle any builtin, harcoded compsitor mappings such as VT switching.
/// Returns true if the keysym was handled.
fn handleBuiltinMapping(self: Self, keysym: xkb.Keysym) bool {
switch (@enumToInt(keysym)) {
@enumToInt(xkb.Keysym.XF86Switch_VT_1)...@enumToInt(xkb.Keysym.XF86Switch_VT_12) => {
log.debug("switch VT keysym received", .{});
if (server.backend.isMulti()) {
if (server.backend.getSession()) |session| {
const vt = @enumToInt(keysym) - @enumToInt(xkb.Keysym.XF86Switch_VT_1) + 1;
const log_server = std.log.scoped(.server);
log_server.notice("switching to VT {}", .{vt});
session.changeVt(vt) catch log_server.err("changing VT failed", .{});
}
}
return true;
},
else => return false,
}
} | source/river-0.1.0/river/Keyboard.zig |
const x86_64 = @import("../index.zig");
const bitjuggle = @import("bitjuggle");
const std = @import("std");
/// Used to obtain random numbers using x86_64's RDRAND opcode
pub const RdRand = struct {
/// Creates a RdRand if RDRAND is supported, null otherwise
pub fn init() ?RdRand {
// RDRAND support indicated by CPUID page 01h, ecx bit 30
// https://en.wikipedia.org/wiki/RdRand#Overview
if (bitjuggle.isBitSet(x86_64.cpuid(0x1).ecx, 30)) {
return RdRand{};
}
return null;
}
/// Uniformly sampled u64.
/// May fail in rare circumstances or heavy load.
pub fn getU64(self: RdRand) ?u64 {
_ = self;
var carry: u8 = undefined;
const num: u64 = asm ("rdrand %[result]; setc %[carry]"
: [result] "=r" (-> u64),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
/// Uniformly sampled u32.
/// May fail in rare circumstances or heavy load.
pub fn getU32(self: RdRand) ?u32 {
_ = self;
var carry: u8 = undefined;
const num: u32 = asm ("rdrand %[result]; setc %[carry]"
: [result] "=r" (-> u32),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
/// Uniformly sampled u16.
/// May fail in rare circumstances or heavy load.
pub fn getU16(self: RdRand) ?u16 {
_ = self;
var carry: u8 = undefined;
const num: u16 = asm ("rdrand %[result]; setc %[carry]"
: [result] "=r" (-> u16),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Used to obtain seed numbers using x86_64's RDSEED opcode
pub const RdSeed = struct {
/// Creates RdSeed if RDSEED is supported
pub fn init() ?RdSeed {
// RDSEED support indicated by CPUID page 07h, ebx bit 18
if (bitjuggle.isBitSet(x86_64.cpuid(0x7).ebx, 18)) {
return RdSeed{};
}
return null;
}
/// Random u64 seed directly from entropy store.
/// May fail in rare circumstances or heavy load.
pub fn getU64(self: RdSeed) ?u64 {
_ = self;
var carry: u8 = undefined;
const num: u64 = asm ("rdseed %[result]; setc %[carry]"
: [result] "=r" (-> u64),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
/// Random u32 seed directly from entropy store.
/// May fail in rare circumstances or heavy load.
pub fn getU32(self: RdSeed) ?u32 {
_ = self;
var carry: u8 = undefined;
const num: u32 = asm ("rdseed %[result]; setc %[carry]"
: [result] "=r" (-> u32),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
/// Random u16 seed directly from entropy store.
/// May fail in rare circumstances or heavy load.
pub fn getU16(self: RdSeed) ?u16 {
_ = self;
var carry: u8 = undefined;
const num: u16 = asm ("rdseed %[result]; setc %[carry]"
: [result] "=r" (-> u16),
: [carry] "qm" (&carry),
: "cc"
);
return if (carry == 0) null else num;
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/instructions/random.zig |
const std = @import("std");
const log = std.log;
const math = std.math;
const assert = std.debug.assert;
const cuda = @import("cudaz");
const cu = cuda.cu;
const png = @import("png.zig");
const utils = @import("utils.zig");
const resources_dir = "resources/hw2_resources/";
const Rgb24 = png.Rgb24;
const Gray8 = png.Gray8;
pub fn main() anyerror!void {
log.info("***** HW2 ******", .{});
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = general_purpose_allocator.allocator();
try all_tests(alloc);
const args = try std.process.argsAlloc(alloc);
defer std.process.argsFree(alloc, args);
var stream = try cuda.Stream.init(0);
defer stream.deinit();
const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png");
defer img.deinit();
assert(img.px == .rgb24);
var max_show: usize = 10;
log.info("Loaded img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(img.px.rgb24[200 .. 200 + max_show]) });
var d_img = try cuda.allocAndCopy(Rgb24, img.px.rgb24);
defer cuda.free(d_img);
var d_red = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_red);
var d_green = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_green);
var d_blue = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_blue);
var d_red_blured = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_red_blured);
var d_green_blured = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_green_blured);
var d_blue_blured = try cuda.alloc(Gray8, img.width * img.height);
defer cuda.free(d_blue_blured);
const d_buffers = [_][2]@TypeOf(d_red){
.{ d_red, d_red_blured },
.{ d_green, d_green_blured },
.{ d_blue, d_blue_blured },
};
var d_out = try cuda.alloc(Rgb24, img.width * img.height);
defer cuda.free(d_out);
const separateChannels = try cuda.Function("separateChannels").init();
const gaussianBlur = try cuda.Function("gaussian_blur").init();
const recombineChannels = try cuda.Function("recombineChannels").init();
var d_filter = try cuda.allocAndCopy(f32, &blurFilter());
defer cuda.free(d_filter);
var grid2D = cuda.Grid.init2D(img.height, img.width, 32, 32);
try separateChannels.launch(
&stream,
grid2D,
.{
@ptrCast([*c]const cu.uchar3, d_img.ptr),
@intCast(c_int, img.height),
@intCast(c_int, img.width),
@ptrCast([*c]u8, d_red.ptr),
@ptrCast([*c]u8, d_green.ptr),
@ptrCast([*c]u8, d_blue.ptr),
},
);
var timer = cuda.GpuTimer.start(&stream);
for (d_buffers) |d_src_tgt| {
try gaussianBlur.launch(
&stream,
grid2D,
.{
@ptrCast([*c]const u8, d_src_tgt[0].ptr),
@ptrCast([*c]u8, d_src_tgt[1].ptr),
@intCast(c_uint, img.height),
@intCast(c_uint, img.width),
@ptrCast([*c]const f32, d_filter),
@intCast(c_int, blurKernelWidth),
},
);
}
timer.stop();
var h_red = try png.grayscale(alloc, img.width, img.height);
try cuda.memcpyDtoH(Gray8, h_red.px.gray8, d_red_blured);
try h_red.writeToFilePath(resources_dir ++ "output_red.png");
try recombineChannels.launch(
&stream,
grid2D,
.{
@ptrCast([*c]const u8, d_red_blured.ptr),
@ptrCast([*c]const u8, d_green_blured.ptr),
@ptrCast([*c]const u8, d_blue_blured.ptr),
@ptrCast([*c]cu.uchar3, d_out.ptr),
@intCast(c_int, img.height),
@intCast(c_int, img.width),
},
);
try cuda.memcpyDtoH(Rgb24, img.px.rgb24, d_out);
try img.writeToFilePath(resources_dir ++ "output.png");
try utils.validate_output(alloc, resources_dir, 2.0);
}
const blurKernelWidth = 9;
fn blurFilter() [blurKernelWidth * blurKernelWidth]f32 {
const blurKernelSigma = 2.0;
// create and fill the filter we will convolve with
var filter: [blurKernelWidth * blurKernelWidth]f32 = undefined;
var filterSum: f32 = 0.0; // for normalization
const halfWidth: i8 = @divTrunc(blurKernelWidth, 2);
var r: i8 = -halfWidth;
while (r <= halfWidth) : (r += 1) {
var c: i8 = -halfWidth;
while (c <= halfWidth) : (c += 1) {
const filterValue: f32 = math.exp(-@intToFloat(f32, c * c + r * r) /
(2.0 * blurKernelSigma * blurKernelSigma));
filter[@intCast(usize, (r + halfWidth) * blurKernelWidth + c + halfWidth)] = filterValue;
filterSum += filterValue;
}
}
const normalizationFactor = 1.0 / filterSum;
var result: f32 = 0.0;
for (filter) |*v| {
v.* *= normalizationFactor;
result += v.*;
}
return filter;
}
fn all_tests(alloc: std.mem.Allocator) !void {
var arena_alloc = std.heap.ArenaAllocator.init(alloc);
defer arena_alloc.deinit();
try test_gaussianBlur(arena_alloc.allocator());
}
fn test_gaussianBlur(alloc: std.mem.Allocator) !void {
// const blur_kernel_size = blurKernelWidth * blurKernelWidth;
var cols: c_uint = 50;
var rows: c_uint = 100;
var img: []u8 = try alloc.alloc(u8, @intCast(usize, rows * cols));
std.mem.set(u8, img, 100);
var out: []u8 = try alloc.alloc(u8, @intCast(usize, rows * cols));
std.mem.set(u8, out, 0);
cu.blockDim = cu.dim3{ .x = cols, .y = rows, .z = 1 };
cu.blockIdx = cu.dim3{ .x = 0, .y = 0, .z = 0 };
cu.threadIdx = cu.dim3{ .x = 10, .y = 10, .z = 0 };
cu.gaussian_blur(img.ptr, out.ptr, rows, cols, &blurFilter(), blurKernelWidth);
try std.testing.expectEqual(out[cols * 10 + 10], 100);
cu.threadIdx = cu.dim3{ .x = cols - 1, .y = 10, .z = 0 };
cu.gaussian_blur(img.ptr, out.ptr, rows, cols, &blurFilter(), blurKernelWidth);
try std.testing.expectEqual(out[cols * 11 - 1], 100);
try std.testing.expectEqual(out[cols * 11 - 1], 100);
}
fn recombine(
img: png.Image,
red: []const Gray8,
green: []const Gray8,
blue: []const Gray8,
) !void {
for (img.px) |_, i| {
img.px.rgb24[i] = Rgb24(red[i], green[i], blue[i]);
}
} | CS344/src/hw2.zig |
const std = @import("std");
const mem = std.mem;
const proto = @import("protocol.zig");
const Table = @import("table.zig").Table;
// TODO: Think about input sanitisation
pub const WireBuffer = struct {
// the current position in the buffer
mem: []u8 = undefined,
head: usize = 0, // current reading position
end: usize = 0,
const Self = @This();
pub fn init(slice: []u8) WireBuffer {
return WireBuffer{
.mem = slice,
.head = 0,
.end = 0,
};
}
pub fn printSpan(self: *Self) void {
for (self.mem[self.head..self.end]) |byte, i| {
std.debug.warn("{x:0>2}", .{byte});
if ((i + 1) % 8 == 0) std.debug.warn("\n", .{}) else std.debug.warn(" ", .{});
}
std.debug.warn("\n", .{});
}
// move head back to beginning of buffer
pub fn reset(self: *Self) void {
self.head = 0;
}
pub fn isFull(self: *Self) bool {
return self.end == self.mem.len; // Should this actually be self.mem.len
}
// shift moves data between head and end to the front of mem
pub fn shift(self: *Self) void {
const new_end = self.end - self.head;
mem.copy(u8, self.mem[0..new_end], self.mem[self.head..self.end]);
self.head = 0;
self.end = new_end;
}
// Returns a slice of everything between the start of mem and head
pub fn extent(self: *Self) []u8 {
return self.mem[0..self.head];
}
// This doesn't return an error because we should always use this after
// reading into self.remaining() which already bounds amount.
pub fn incrementEnd(self: *Self, amount: usize) void {
self.end += amount;
}
// Returns a slice of everthing between end and the end of mem
pub fn remaining(self: *Self) []u8 {
return self.mem[self.end..];
}
pub fn isMoreData(self: *Self) bool {
return self.head < self.mem.len;
}
pub fn readFrameHeader(self: *Self) !FrameHeader {
if (self.end - self.head < @sizeOf(FrameHeader)) return error.FrameHeaderReadFailure;
const frame_type = self.readU8();
const channel = self.readU16();
const size = self.readU32();
// std.debug.warn("frame_type: {}, channel: {}, size: {}\n", .{frame_type, channel, size});
return FrameHeader{
.@"type" = @intToEnum(FrameType, frame_type),
.channel = channel,
.size = size,
};
}
// Returns true if there is enough data read for
// a full frame
pub fn frameReady(self: *Self) bool {
const save_head = self.head;
defer self.head = save_head;
const frame_header = self.readFrameHeader() catch |err| {
switch (err) {
error.FrameHeaderReadFailure => return false,
}
};
return (self.end - save_head) >= (8 + frame_header.size);
}
pub fn readEOF(self: *Self) !void {
const byte = self.readU8();
if (byte != 0xCE) return error.ExpectedEOF;
}
fn writeEOF(self: *Self) void {
self.writeU8(0xCE);
}
pub fn writeFrameHeader(self: *Self, frame_type: FrameType, channel: u16, size: u32) void {
self.writeU8(@enumToInt(frame_type));
self.writeU16(channel);
self.writeU32(size); // This will be overwritten later
}
pub fn updateFrameLength(self: *Self) void {
self.writeEOF();
const head = self.head;
self.head = 3;
self.writeU32(@intCast(u32, head - 8)); // size is head - header length (7 bytes) - frame end (1 bytes)
self.head = head;
}
pub fn readMethodHeader(self: *Self) !MethodHeader {
const class = self.readU16();
const method = self.readU16();
return MethodHeader{
.class = class,
.method = method,
};
}
pub fn writeMethodHeader(self: *Self, class: u16, method: u16) void {
self.writeU16(class);
self.writeU16(method);
}
pub fn readHeader(self: *Self, frame_size: usize) !Header {
const class = self.readU16();
const weight = self.readU16();
const body_size = self.readU64();
const property_flags = self.readU16();
const properties = self.mem[self.head .. self.head + (frame_size - 14)];
self.head += (frame_size - 14);
try self.readEOF();
return Header{
.class = class,
.weight = weight,
.body_size = body_size,
.property_flags = property_flags,
.properties = properties,
};
}
pub fn writeHeader(self: *Self, channel: u16, size: u64, class: u16) void {
self.writeFrameHeader(.Header, channel, 0);
self.writeU16(class);
self.writeU16(0);
self.writeU64(size);
self.writeU16(0);
self.updateFrameLength();
}
pub fn readBody(self: *Self, frame_size: usize) ![]u8 {
const body = self.mem[self.head .. self.head + frame_size];
self.head += frame_size;
try self.readEOF();
return body;
}
pub fn writeBody(self: *Self, channel: u16, body: []const u8) void {
self.writeFrameHeader(.Body, channel, 0);
std.mem.copy(u8, self.mem[self.head..], body);
self.head += body.len;
self.updateFrameLength();
}
pub fn writeHeartbeat(self: *Self) void {
self.writeFrameHeader(.Heartbeat, 0, 0);
self.updateFrameLength();
}
pub fn readU8(self: *Self) u8 {
const r = @ptrCast(u8, self.mem[self.head]);
self.head += 1;
return r;
}
pub fn writeU8(self: *Self, byte: u8) void {
std.mem.writeInt(u8, &self.mem[self.head], byte, .Big);
self.head += 1;
}
pub fn readU16(self: *Self) u16 {
const r = std.mem.readInt(u16, @ptrCast(*const [@sizeOf(u16)]u8, &self.mem[self.head]), .Big);
self.head += @sizeOf(u16);
return r;
}
pub fn writeU16(self: *Self, short: u16) void {
std.mem.writeInt(u16, @ptrCast(*[@sizeOf(u16)]u8, &self.mem[self.head]), short, .Big);
self.head += 2;
}
pub fn readU32(self: *Self) u32 {
const r = std.mem.readInt(u32, @ptrCast(*const [@sizeOf(u32)]u8, &self.mem[self.head]), .Big);
self.head += @sizeOf(u32);
return r;
}
pub fn writeU32(self: *Self, number: u32) void {
std.mem.writeInt(u32, @ptrCast(*[@sizeOf(u32)]u8, &self.mem[self.head]), number, .Big);
self.head += @sizeOf(u32);
}
pub fn readU64(self: *Self) u64 {
const r = std.mem.readInt(u64, @ptrCast(*const [@sizeOf(u64)]u8, &self.mem[self.head]), .Big);
self.head += @sizeOf(u64);
return r;
}
pub fn writeU64(self: *Self, number: u64) void {
std.mem.writeInt(u64, @ptrCast(*[@sizeOf(u64)]u8, &self.mem[self.head]), number, .Big);
self.head += @sizeOf(u64);
}
pub fn readBool(self: *Self) bool {
const r = self.readU8();
if (r == 0) return false;
return true;
}
pub fn writeBool(self: *Self, boolean: bool) void {
self.writeU8(if (boolean) 1 else 0);
}
pub fn readShortString(self: *Self) []u8 {
const length = self.readU8();
const array = self.mem[self.head .. self.head + length];
self.head += length;
return array;
}
pub fn writeShortString(self: *Self, string: []const u8) void {
self.writeU8(@intCast(u8, string.len));
std.mem.copy(u8, self.mem[self.head..], string);
self.head += string.len;
}
pub fn readLongString(self: *Self) []u8 {
const length = self.readU32();
const array = self.mem[self.head .. self.head + length];
self.head += length;
return array;
}
pub fn writeLongString(self: *Self, string: []const u8) void {
self.writeU32(@intCast(u32, string.len));
std.mem.copy(u8, self.mem[self.head..], string);
self.head += string.len;
}
// 1. Save the current read head
// 2. Read the length (u32) of the table (the length of data after the u32 length)
// 3. Until we've reached the end of the table
// 3a. Read a table key
// 3b. Read the value type for the key
// 3c. Read that type
pub fn readTable(self: *Self) Table {
const table_start = self.head;
const length = self.readU32();
while (self.head - table_start < (length + @sizeOf(u32))) {
const key = self.readShortString();
const t = self.readU8();
switch (t) {
'F' => {
_ = self.readTable();
},
't' => {
const b = self.readBool();
},
's' => {
const s = self.readShortString();
},
'S' => {
const s = self.readLongString();
},
else => continue,
}
}
return Table{
.buf = WireBuffer.init(self.mem[table_start..self.head]),
};
}
// writeTable is making an assumption that we're using a separate
// buffer to write all the fields / values separately, then all
// we have to do is copy them
// TODO: thought: we might have this take *Table instead
// if we did, we could maybe make use of the len field
// in table to avoid provide a backing store for an empty
// table. We would simply chekc that length first, and
// if it's zeroe, manually write the 0 length, otherwise
// do the mem.copy
pub fn writeTable(self: *Self, table: ?*Table) void {
if (table) |t| {
const table_bytes = t.buf.extent();
std.mem.copy(u8, self.mem[self.head..], table_bytes);
self.head += table_bytes.len;
} else {
self.writeU32(0);
}
}
};
pub const FrameHeader = struct {
@"type": FrameType = .Method,
channel: u16 = 0,
size: u32 = 0,
};
const FrameType = enum(u8) {
Method = proto.FRAME_METHOD,
Header = proto.FRAME_HEADER,
Body = proto.FRAME_BODY,
Heartbeat = proto.FRAME_HEARTBEAT,
};
const MethodHeader = struct {
class: u16 = 0,
method: u16 = 0,
};
pub const Header = struct {
class: u16 = 0,
weight: u16 = 0,
body_size: u64 = 0,
property_flags: u16 = 0,
// TODO: I don't understand the properties field
properties: []u8 = undefined,
};
const testing = std.testing;
test "buffer is full" {
var memory: [16]u8 = [_]u8{0} ** 16;
var buf = WireBuffer.init(memory[0..]);
testing.expect(buf.isFull() == false);
buf.incrementEnd(16); // simluate writing 16 bytes into buffer
// The buffer should now be full
testing.expect(buf.isFull() == true);
testing.expect(buf.remaining().len == 0);
}
test "basic write / read" {
var rx_memory: [1024]u8 = [_]u8{0} ** 1024;
var tx_memory: [1024]u8 = [_]u8{0} ** 1024;
var table_memory: [1024]u8 = [_]u8{0} ** 1024;
var rx_buf = WireBuffer.init(rx_memory[0..]);
var tx_buf = WireBuffer.init(tx_memory[0..]);
// Write to tx_buf (imagine this is the server's buffer)
tx_buf.writeU8(22);
tx_buf.writeU16(23);
tx_buf.writeU32(24);
tx_buf.writeShortString("Hello");
tx_buf.writeLongString("World");
tx_buf.writeBool(true);
var tx_table = Table.init(table_memory[0..]);
tx_table.insertBool("flag1", true);
tx_table.insertBool("flag2", false);
tx_table.insertLongString("longstring", "zig is the best");
tx_buf.writeTable(&tx_table);
// Simulate transmission
mem.copy(u8, rx_buf.remaining(), tx_buf.extent());
rx_buf.incrementEnd(tx_buf.extent().len);
// Read from rx_buf (image this is the client's buffer)
testing.expect(rx_buf.readU8() == 22);
testing.expect(rx_buf.readU16() == 23);
testing.expect(rx_buf.readU32() == 24);
testing.expect(mem.eql(u8, rx_buf.readShortString(), "Hello"));
testing.expect(mem.eql(u8, rx_buf.readLongString(), "World"));
testing.expect(rx_buf.readBool() == true);
var rx_table = rx_buf.readTable();
testing.expect(rx_table.lookup(bool, "flag1").? == true);
testing.expect(rx_table.lookup(bool, "flag2").? == false);
testing.expect(mem.eql(u8, rx_table.lookup([]u8, "longstring").?, "zig is the best"));
} | src/wire.zig |
const std = @import("std.zig");
const builtin = std.builtin;
const io = std.io;
const os = std.os;
const math = std.math;
const mem = std.mem;
const debug = std.debug;
const File = std.fs.File;
pub const AT_NULL = 0;
pub const AT_IGNORE = 1;
pub const AT_EXECFD = 2;
pub const AT_PHDR = 3;
pub const AT_PHENT = 4;
pub const AT_PHNUM = 5;
pub const AT_PAGESZ = 6;
pub const AT_BASE = 7;
pub const AT_FLAGS = 8;
pub const AT_ENTRY = 9;
pub const AT_NOTELF = 10;
pub const AT_UID = 11;
pub const AT_EUID = 12;
pub const AT_GID = 13;
pub const AT_EGID = 14;
pub const AT_CLKTCK = 17;
pub const AT_PLATFORM = 15;
pub const AT_HWCAP = 16;
pub const AT_FPUCW = 18;
pub const AT_DCACHEBSIZE = 19;
pub const AT_ICACHEBSIZE = 20;
pub const AT_UCACHEBSIZE = 21;
pub const AT_IGNOREPPC = 22;
pub const AT_SECURE = 23;
pub const AT_BASE_PLATFORM = 24;
pub const AT_RANDOM = 25;
pub const AT_HWCAP2 = 26;
pub const AT_EXECFN = 31;
pub const AT_SYSINFO = 32;
pub const AT_SYSINFO_EHDR = 33;
pub const AT_L1I_CACHESHAPE = 34;
pub const AT_L1D_CACHESHAPE = 35;
pub const AT_L2_CACHESHAPE = 36;
pub const AT_L3_CACHESHAPE = 37;
pub const AT_L1I_CACHESIZE = 40;
pub const AT_L1I_CACHEGEOMETRY = 41;
pub const AT_L1D_CACHESIZE = 42;
pub const AT_L1D_CACHEGEOMETRY = 43;
pub const AT_L2_CACHESIZE = 44;
pub const AT_L2_CACHEGEOMETRY = 45;
pub const AT_L3_CACHESIZE = 46;
pub const AT_L3_CACHEGEOMETRY = 47;
pub const DT_NULL = 0;
pub const DT_NEEDED = 1;
pub const DT_PLTRELSZ = 2;
pub const DT_PLTGOT = 3;
pub const DT_HASH = 4;
pub const DT_STRTAB = 5;
pub const DT_SYMTAB = 6;
pub const DT_RELA = 7;
pub const DT_RELASZ = 8;
pub const DT_RELAENT = 9;
pub const DT_STRSZ = 10;
pub const DT_SYMENT = 11;
pub const DT_INIT = 12;
pub const DT_FINI = 13;
pub const DT_SONAME = 14;
pub const DT_RPATH = 15;
pub const DT_SYMBOLIC = 16;
pub const DT_REL = 17;
pub const DT_RELSZ = 18;
pub const DT_RELENT = 19;
pub const DT_PLTREL = 20;
pub const DT_DEBUG = 21;
pub const DT_TEXTREL = 22;
pub const DT_JMPREL = 23;
pub const DT_BIND_NOW = 24;
pub const DT_INIT_ARRAY = 25;
pub const DT_FINI_ARRAY = 26;
pub const DT_INIT_ARRAYSZ = 27;
pub const DT_FINI_ARRAYSZ = 28;
pub const DT_RUNPATH = 29;
pub const DT_FLAGS = 30;
pub const DT_ENCODING = 32;
pub const DT_PREINIT_ARRAY = 32;
pub const DT_PREINIT_ARRAYSZ = 33;
pub const DT_SYMTAB_SHNDX = 34;
pub const DT_NUM = 35;
pub const DT_LOOS = 0x6000000d;
pub const DT_HIOS = 0x6ffff000;
pub const DT_LOPROC = 0x70000000;
pub const DT_HIPROC = 0x7fffffff;
pub const DT_PROCNUM = DT_MIPS_NUM;
pub const DT_VALRNGLO = 0x6ffffd00;
pub const DT_GNU_PRELINKED = 0x6ffffdf5;
pub const DT_GNU_CONFLICTSZ = 0x6ffffdf6;
pub const DT_GNU_LIBLISTSZ = 0x6ffffdf7;
pub const DT_CHECKSUM = 0x6ffffdf8;
pub const DT_PLTPADSZ = 0x6ffffdf9;
pub const DT_MOVEENT = 0x6ffffdfa;
pub const DT_MOVESZ = 0x6ffffdfb;
pub const DT_FEATURE_1 = 0x6ffffdfc;
pub const DT_POSFLAG_1 = 0x6ffffdfd;
pub const DT_SYMINSZ = 0x6ffffdfe;
pub const DT_SYMINENT = 0x6ffffdff;
pub const DT_VALRNGHI = 0x6ffffdff;
pub const DT_VALNUM = 12;
pub const DT_ADDRRNGLO = 0x6ffffe00;
pub const DT_GNU_HASH = 0x6ffffef5;
pub const DT_TLSDESC_PLT = 0x6ffffef6;
pub const DT_TLSDESC_GOT = 0x6ffffef7;
pub const DT_GNU_CONFLICT = 0x6ffffef8;
pub const DT_GNU_LIBLIST = 0x6ffffef9;
pub const DT_CONFIG = 0x6ffffefa;
pub const DT_DEPAUDIT = 0x6ffffefb;
pub const DT_AUDIT = 0x6ffffefc;
pub const DT_PLTPAD = 0x6ffffefd;
pub const DT_MOVETAB = 0x6ffffefe;
pub const DT_SYMINFO = 0x6ffffeff;
pub const DT_ADDRRNGHI = 0x6ffffeff;
pub const DT_ADDRNUM = 11;
pub const DT_VERSYM = 0x6ffffff0;
pub const DT_RELACOUNT = 0x6ffffff9;
pub const DT_RELCOUNT = 0x6ffffffa;
pub const DT_FLAGS_1 = 0x6ffffffb;
pub const DT_VERDEF = 0x6ffffffc;
pub const DT_VERDEFNUM = 0x6ffffffd;
pub const DT_VERNEED = 0x6ffffffe;
pub const DT_VERNEEDNUM = 0x6fffffff;
pub const DT_VERSIONTAGNUM = 16;
pub const DT_AUXILIARY = 0x7ffffffd;
pub const DT_FILTER = 0x7fffffff;
pub const DT_EXTRANUM = 3;
pub const DT_SPARC_REGISTER = 0x70000001;
pub const DT_SPARC_NUM = 2;
pub const DT_MIPS_RLD_VERSION = 0x70000001;
pub const DT_MIPS_TIME_STAMP = 0x70000002;
pub const DT_MIPS_ICHECKSUM = 0x70000003;
pub const DT_MIPS_IVERSION = 0x70000004;
pub const DT_MIPS_FLAGS = 0x70000005;
pub const DT_MIPS_BASE_ADDRESS = 0x70000006;
pub const DT_MIPS_MSYM = 0x70000007;
pub const DT_MIPS_CONFLICT = 0x70000008;
pub const DT_MIPS_LIBLIST = 0x70000009;
pub const DT_MIPS_LOCAL_GOTNO = 0x7000000a;
pub const DT_MIPS_CONFLICTNO = 0x7000000b;
pub const DT_MIPS_LIBLISTNO = 0x70000010;
pub const DT_MIPS_SYMTABNO = 0x70000011;
pub const DT_MIPS_UNREFEXTNO = 0x70000012;
pub const DT_MIPS_GOTSYM = 0x70000013;
pub const DT_MIPS_HIPAGENO = 0x70000014;
pub const DT_MIPS_RLD_MAP = 0x70000016;
pub const DT_MIPS_DELTA_CLASS = 0x70000017;
pub const DT_MIPS_DELTA_CLASS_NO = 0x70000018;
pub const DT_MIPS_DELTA_INSTANCE = 0x70000019;
pub const DT_MIPS_DELTA_INSTANCE_NO = 0x7000001a;
pub const DT_MIPS_DELTA_RELOC = 0x7000001b;
pub const DT_MIPS_DELTA_RELOC_NO = 0x7000001c;
pub const DT_MIPS_DELTA_SYM = 0x7000001d;
pub const DT_MIPS_DELTA_SYM_NO = 0x7000001e;
pub const DT_MIPS_DELTA_CLASSSYM = 0x70000020;
pub const DT_MIPS_DELTA_CLASSSYM_NO = 0x70000021;
pub const DT_MIPS_CXX_FLAGS = 0x70000022;
pub const DT_MIPS_PIXIE_INIT = 0x70000023;
pub const DT_MIPS_SYMBOL_LIB = 0x70000024;
pub const DT_MIPS_LOCALPAGE_GOTIDX = 0x70000025;
pub const DT_MIPS_LOCAL_GOTIDX = 0x70000026;
pub const DT_MIPS_HIDDEN_GOTIDX = 0x70000027;
pub const DT_MIPS_PROTECTED_GOTIDX = 0x70000028;
pub const DT_MIPS_OPTIONS = 0x70000029;
pub const DT_MIPS_INTERFACE = 0x7000002a;
pub const DT_MIPS_DYNSTR_ALIGN = 0x7000002b;
pub const DT_MIPS_INTERFACE_SIZE = 0x7000002c;
pub const DT_MIPS_RLD_TEXT_RESOLVE_ADDR = 0x7000002d;
pub const DT_MIPS_PERF_SUFFIX = 0x7000002e;
pub const DT_MIPS_COMPACT_SIZE = 0x7000002f;
pub const DT_MIPS_GP_VALUE = 0x70000030;
pub const DT_MIPS_AUX_DYNAMIC = 0x70000031;
pub const DT_MIPS_PLTGOT = 0x70000032;
pub const DT_MIPS_RWPLT = 0x70000034;
pub const DT_MIPS_RLD_MAP_REL = 0x70000035;
pub const DT_MIPS_NUM = 0x36;
pub const DT_ALPHA_PLTRO = (DT_LOPROC + 0);
pub const DT_ALPHA_NUM = 1;
pub const DT_PPC_GOT = (DT_LOPROC + 0);
pub const DT_PPC_OPT = (DT_LOPROC + 1);
pub const DT_PPC_NUM = 2;
pub const DT_PPC64_GLINK = (DT_LOPROC + 0);
pub const DT_PPC64_OPD = (DT_LOPROC + 1);
pub const DT_PPC64_OPDSZ = (DT_LOPROC + 2);
pub const DT_PPC64_OPT = (DT_LOPROC + 3);
pub const DT_PPC64_NUM = 4;
pub const DT_IA_64_PLT_RESERVE = (DT_LOPROC + 0);
pub const DT_IA_64_NUM = 1;
pub const DT_NIOS2_GP = 0x70000002;
pub const PT_NULL = 0;
pub const PT_LOAD = 1;
pub const PT_DYNAMIC = 2;
pub const PT_INTERP = 3;
pub const PT_NOTE = 4;
pub const PT_SHLIB = 5;
pub const PT_PHDR = 6;
pub const PT_TLS = 7;
pub const PT_NUM = 8;
pub const PT_LOOS = 0x60000000;
pub const PT_GNU_EH_FRAME = 0x6474e550;
pub const PT_GNU_STACK = 0x6474e551;
pub const PT_GNU_RELRO = 0x6474e552;
pub const PT_LOSUNW = 0x6ffffffa;
pub const PT_SUNWBSS = 0x6ffffffa;
pub const PT_SUNWSTACK = 0x6ffffffb;
pub const PT_HISUNW = 0x6fffffff;
pub const PT_HIOS = 0x6fffffff;
pub const PT_LOPROC = 0x70000000;
pub const PT_HIPROC = 0x7fffffff;
pub const SHT_NULL = 0;
pub const SHT_PROGBITS = 1;
pub const SHT_SYMTAB = 2;
pub const SHT_STRTAB = 3;
pub const SHT_RELA = 4;
pub const SHT_HASH = 5;
pub const SHT_DYNAMIC = 6;
pub const SHT_NOTE = 7;
pub const SHT_NOBITS = 8;
pub const SHT_REL = 9;
pub const SHT_SHLIB = 10;
pub const SHT_DYNSYM = 11;
pub const SHT_INIT_ARRAY = 14;
pub const SHT_FINI_ARRAY = 15;
pub const SHT_PREINIT_ARRAY = 16;
pub const SHT_GROUP = 17;
pub const SHT_SYMTAB_SHNDX = 18;
pub const SHT_LOOS = 0x60000000;
pub const SHT_HIOS = 0x6fffffff;
pub const SHT_LOPROC = 0x70000000;
pub const SHT_HIPROC = 0x7fffffff;
pub const SHT_LOUSER = 0x80000000;
pub const SHT_HIUSER = 0xffffffff;
pub const STB_LOCAL = 0;
pub const STB_GLOBAL = 1;
pub const STB_WEAK = 2;
pub const STB_NUM = 3;
pub const STB_LOOS = 10;
pub const STB_GNU_UNIQUE = 10;
pub const STB_HIOS = 12;
pub const STB_LOPROC = 13;
pub const STB_HIPROC = 15;
pub const STB_MIPS_SPLIT_COMMON = 13;
pub const STT_NOTYPE = 0;
pub const STT_OBJECT = 1;
pub const STT_FUNC = 2;
pub const STT_SECTION = 3;
pub const STT_FILE = 4;
pub const STT_COMMON = 5;
pub const STT_TLS = 6;
pub const STT_NUM = 7;
pub const STT_LOOS = 10;
pub const STT_GNU_IFUNC = 10;
pub const STT_HIOS = 12;
pub const STT_LOPROC = 13;
pub const STT_HIPROC = 15;
pub const STT_SPARC_REGISTER = 13;
pub const STT_PARISC_MILLICODE = 13;
pub const STT_HP_OPAQUE = (STT_LOOS + 0x1);
pub const STT_HP_STUB = (STT_LOOS + 0x2);
pub const STT_ARM_TFUNC = STT_LOPROC;
pub const STT_ARM_16BIT = STT_HIPROC;
pub const VER_FLG_BASE = 0x1;
pub const VER_FLG_WEAK = 0x2;
/// File types
pub const ET = extern enum(u16) {
/// No file type
NONE = 0,
/// Relocatable file
REL = 1,
/// Executable file
EXEC = 2,
/// Shared object file
DYN = 3,
/// Core file
CORE = 4,
/// Beginning of processor-specific codes
pub const LOPROC = 0xff00;
/// Processor-specific
pub const HIPROC = 0xffff;
};
/// All integers are native endian.
const Header = struct {
endian: builtin.Endian,
is_64: bool,
entry: u64,
phoff: u64,
shoff: u64,
phentsize: u16,
phnum: u16,
shentsize: u16,
shnum: u16,
shstrndx: u16,
pub fn program_header_iterator(self: Header, file: File) ProgramHeaderIterator {
return .{
.elf_header = self,
.file = file,
};
}
pub fn section_header_iterator(self: Header, file: File) SectionHeaderIterator {
return .{
.elf_header = self,
.file = file,
};
}
};
pub fn readHeader(file: File) !Header {
var hdr_buf: [@sizeOf(Elf64_Ehdr)]u8 align(@alignOf(Elf64_Ehdr)) = undefined;
try preadNoEof(file, &hdr_buf, 0);
const hdr32 = @ptrCast(*Elf32_Ehdr, &hdr_buf);
const hdr64 = @ptrCast(*Elf64_Ehdr, &hdr_buf);
if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
if (hdr32.e_ident[EI_VERSION] != 1) return error.InvalidElfVersion;
const endian: std.builtin.Endian = switch (hdr32.e_ident[EI_DATA]) {
ELFDATA2LSB => .Little,
ELFDATA2MSB => .Big,
else => return error.InvalidElfEndian,
};
const need_bswap = endian != std.builtin.endian;
const is_64 = switch (hdr32.e_ident[EI_CLASS]) {
ELFCLASS32 => false,
ELFCLASS64 => true,
else => return error.InvalidElfClass,
};
return @as(Header, .{
.endian = endian,
.is_64 = is_64,
.entry = int(is_64, need_bswap, hdr32.e_entry, hdr64.e_entry),
.phoff = int(is_64, need_bswap, hdr32.e_phoff, hdr64.e_phoff),
.shoff = int(is_64, need_bswap, hdr32.e_shoff, hdr64.e_shoff),
.phentsize = int(is_64, need_bswap, hdr32.e_phentsize, hdr64.e_phentsize),
.phnum = int(is_64, need_bswap, hdr32.e_phnum, hdr64.e_phnum),
.shentsize = int(is_64, need_bswap, hdr32.e_shentsize, hdr64.e_shentsize),
.shnum = int(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum),
.shstrndx = int(is_64, need_bswap, hdr32.e_shstrndx, hdr64.e_shstrndx),
});
}
pub const ProgramHeaderIterator = struct {
elf_header: Header,
file: File,
index: usize = 0,
pub fn next(self: *ProgramHeaderIterator) !?Elf64_Phdr {
if (self.index >= self.elf_header.phnum) return null;
defer self.index += 1;
if (self.elf_header.is_64) {
var phdr: Elf64_Phdr = undefined;
const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index;
try preadNoEof(self.file, mem.asBytes(&phdr), offset);
// ELF endianness matches native endianness.
if (self.elf_header.endian == std.builtin.endian) return phdr;
// Convert fields to native endianness.
return Elf64_Phdr{
.p_type = @byteSwap(@TypeOf(phdr.p_type), phdr.p_type),
.p_offset = @byteSwap(@TypeOf(phdr.p_offset), phdr.p_offset),
.p_vaddr = @byteSwap(@TypeOf(phdr.p_vaddr), phdr.p_vaddr),
.p_paddr = @byteSwap(@TypeOf(phdr.p_paddr), phdr.p_paddr),
.p_filesz = @byteSwap(@TypeOf(phdr.p_filesz), phdr.p_filesz),
.p_memsz = @byteSwap(@TypeOf(phdr.p_memsz), phdr.p_memsz),
.p_flags = @byteSwap(@TypeOf(phdr.p_flags), phdr.p_flags),
.p_align = @byteSwap(@TypeOf(phdr.p_align), phdr.p_align),
};
}
var phdr: Elf32_Phdr = undefined;
const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index;
try preadNoEof(self.file, mem.asBytes(&phdr), offset);
// ELF endianness does NOT match native endianness.
if (self.elf_header.endian != std.builtin.endian) {
// Convert fields to native endianness.
phdr = .{
.p_type = @byteSwap(@TypeOf(phdr.p_type), phdr.p_type),
.p_offset = @byteSwap(@TypeOf(phdr.p_offset), phdr.p_offset),
.p_vaddr = @byteSwap(@TypeOf(phdr.p_vaddr), phdr.p_vaddr),
.p_paddr = @byteSwap(@TypeOf(phdr.p_paddr), phdr.p_paddr),
.p_filesz = @byteSwap(@TypeOf(phdr.p_filesz), phdr.p_filesz),
.p_memsz = @byteSwap(@TypeOf(phdr.p_memsz), phdr.p_memsz),
.p_flags = @byteSwap(@TypeOf(phdr.p_flags), phdr.p_flags),
.p_align = @byteSwap(@TypeOf(phdr.p_align), phdr.p_align),
};
}
// Convert 32-bit header to 64-bit.
return Elf64_Phdr{
.p_type = phdr.p_type,
.p_offset = phdr.p_offset,
.p_vaddr = phdr.p_vaddr,
.p_paddr = phdr.p_paddr,
.p_filesz = phdr.p_filesz,
.p_memsz = phdr.p_memsz,
.p_flags = phdr.p_flags,
.p_align = phdr.p_align,
};
}
};
pub const SectionHeaderIterator = struct {
elf_header: Header,
file: File,
index: usize = 0,
pub fn next(self: *SectionHeaderIterator) !?Elf64_Shdr {
if (self.index >= self.elf_header.shnum) return null;
defer self.index += 1;
if (self.elf_header.is_64) {
var shdr: Elf64_Shdr = undefined;
const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index;
try preadNoEof(self.file, mem.asBytes(&shdr), offset);
// ELF endianness matches native endianness.
if (self.elf_header.endian == std.builtin.endian) return shdr;
// Convert fields to native endianness.
return Elf64_Shdr{
.sh_name = @byteSwap(@TypeOf(shdr.sh_name), shdr.sh_name),
.sh_type = @byteSwap(@TypeOf(shdr.sh_type), shdr.sh_type),
.sh_flags = @byteSwap(@TypeOf(shdr.sh_flags), shdr.sh_flags),
.sh_addr = @byteSwap(@TypeOf(shdr.sh_addr), shdr.sh_addr),
.sh_offset = @byteSwap(@TypeOf(shdr.sh_offset), shdr.sh_offset),
.sh_size = @byteSwap(@TypeOf(shdr.sh_size), shdr.sh_size),
.sh_link = @byteSwap(@TypeOf(shdr.sh_link), shdr.sh_link),
.sh_info = @byteSwap(@TypeOf(shdr.sh_info), shdr.sh_info),
.sh_addralign = @byteSwap(@TypeOf(shdr.sh_addralign), shdr.sh_addralign),
.sh_entsize = @byteSwap(@TypeOf(shdr.sh_entsize), shdr.sh_entsize),
};
}
var shdr: Elf32_Shdr = undefined;
const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index;
try preadNoEof(self.file, mem.asBytes(&shdr), offset);
// ELF endianness does NOT match native endianness.
if (self.elf_header.endian != std.builtin.endian) {
// Convert fields to native endianness.
shdr = .{
.sh_name = @byteSwap(@TypeOf(shdr.sh_name), shdr.sh_name),
.sh_type = @byteSwap(@TypeOf(shdr.sh_type), shdr.sh_type),
.sh_flags = @byteSwap(@TypeOf(shdr.sh_flags), shdr.sh_flags),
.sh_addr = @byteSwap(@TypeOf(shdr.sh_addr), shdr.sh_addr),
.sh_offset = @byteSwap(@TypeOf(shdr.sh_offset), shdr.sh_offset),
.sh_size = @byteSwap(@TypeOf(shdr.sh_size), shdr.sh_size),
.sh_link = @byteSwap(@TypeOf(shdr.sh_link), shdr.sh_link),
.sh_info = @byteSwap(@TypeOf(shdr.sh_info), shdr.sh_info),
.sh_addralign = @byteSwap(@TypeOf(shdr.sh_addralign), shdr.sh_addralign),
.sh_entsize = @byteSwap(@TypeOf(shdr.sh_entsize), shdr.sh_entsize),
};
}
// Convert 32-bit header to 64-bit.
return Elf64_Shdr{
.sh_name = shdr.sh_name,
.sh_type = shdr.sh_type,
.sh_flags = shdr.sh_flags,
.sh_addr = shdr.sh_addr,
.sh_offset = shdr.sh_offset,
.sh_size = shdr.sh_size,
.sh_link = shdr.sh_link,
.sh_info = shdr.sh_info,
.sh_addralign = shdr.sh_addralign,
.sh_entsize = shdr.sh_entsize,
};
}
};
pub fn int(is_64: bool, need_bswap: bool, int_32: anytype, int_64: anytype) @TypeOf(int_64) {
if (is_64) {
if (need_bswap) {
return @byteSwap(@TypeOf(int_64), int_64);
} else {
return int_64;
}
} else {
return int32(need_bswap, int_32, @TypeOf(int_64));
}
}
pub fn int32(need_bswap: bool, int_32: anytype, comptime Int64: anytype) Int64 {
if (need_bswap) {
return @byteSwap(@TypeOf(int_32), int_32);
} else {
return int_32;
}
}
fn preadNoEof(file: std.fs.File, buf: []u8, offset: u64) !void {
var i: usize = 0;
while (i < buf.len) {
const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
error.SystemResources => return error.SystemResources,
error.IsDir => return error.UnableToReadElfFile,
error.OperationAborted => return error.UnableToReadElfFile,
error.BrokenPipe => return error.UnableToReadElfFile,
error.Unseekable => return error.UnableToReadElfFile,
error.ConnectionResetByPeer => return error.UnableToReadElfFile,
error.ConnectionTimedOut => return error.UnableToReadElfFile,
error.InputOutput => return error.FileSystem,
error.Unexpected => return error.Unexpected,
error.WouldBlock => return error.Unexpected,
error.NotOpenForReading => return error.Unexpected,
error.AccessDenied => return error.Unexpected,
};
if (len == 0) return error.UnexpectedEndOfFile;
i += len;
}
}
pub const EI_NIDENT = 16;
pub const EI_CLASS = 4;
pub const ELFCLASSNONE = 0;
pub const ELFCLASS32 = 1;
pub const ELFCLASS64 = 2;
pub const ELFCLASSNUM = 3;
pub const EI_DATA = 5;
pub const ELFDATANONE = 0;
pub const ELFDATA2LSB = 1;
pub const ELFDATA2MSB = 2;
pub const ELFDATANUM = 3;
pub const EI_VERSION = 6;
pub const Elf32_Half = u16;
pub const Elf64_Half = u16;
pub const Elf32_Word = u32;
pub const Elf32_Sword = i32;
pub const Elf64_Word = u32;
pub const Elf64_Sword = i32;
pub const Elf32_Xword = u64;
pub const Elf32_Sxword = i64;
pub const Elf64_Xword = u64;
pub const Elf64_Sxword = i64;
pub const Elf32_Addr = u32;
pub const Elf64_Addr = u64;
pub const Elf32_Off = u32;
pub const Elf64_Off = u64;
pub const Elf32_Section = u16;
pub const Elf64_Section = u16;
pub const Elf32_Versym = Elf32_Half;
pub const Elf64_Versym = Elf64_Half;
pub const Elf32_Ehdr = extern struct {
e_ident: [EI_NIDENT]u8,
e_type: ET,
e_machine: EM,
e_version: Elf32_Word,
e_entry: Elf32_Addr,
e_phoff: Elf32_Off,
e_shoff: Elf32_Off,
e_flags: Elf32_Word,
e_ehsize: Elf32_Half,
e_phentsize: Elf32_Half,
e_phnum: Elf32_Half,
e_shentsize: Elf32_Half,
e_shnum: Elf32_Half,
e_shstrndx: Elf32_Half,
};
pub const Elf64_Ehdr = extern struct {
e_ident: [EI_NIDENT]u8,
e_type: ET,
e_machine: EM,
e_version: Elf64_Word,
e_entry: Elf64_Addr,
e_phoff: Elf64_Off,
e_shoff: Elf64_Off,
e_flags: Elf64_Word,
e_ehsize: Elf64_Half,
e_phentsize: Elf64_Half,
e_phnum: Elf64_Half,
e_shentsize: Elf64_Half,
e_shnum: Elf64_Half,
e_shstrndx: Elf64_Half,
};
pub const Elf32_Phdr = extern struct {
p_type: Elf32_Word,
p_offset: Elf32_Off,
p_vaddr: Elf32_Addr,
p_paddr: Elf32_Addr,
p_filesz: Elf32_Word,
p_memsz: Elf32_Word,
p_flags: Elf32_Word,
p_align: Elf32_Word,
};
pub const Elf64_Phdr = extern struct {
p_type: Elf64_Word,
p_flags: Elf64_Word,
p_offset: Elf64_Off,
p_vaddr: Elf64_Addr,
p_paddr: Elf64_Addr,
p_filesz: Elf64_Xword,
p_memsz: Elf64_Xword,
p_align: Elf64_Xword,
};
pub const Elf32_Shdr = extern struct {
sh_name: Elf32_Word,
sh_type: Elf32_Word,
sh_flags: Elf32_Word,
sh_addr: Elf32_Addr,
sh_offset: Elf32_Off,
sh_size: Elf32_Word,
sh_link: Elf32_Word,
sh_info: Elf32_Word,
sh_addralign: Elf32_Word,
sh_entsize: Elf32_Word,
};
pub const Elf64_Shdr = extern struct {
sh_name: Elf64_Word,
sh_type: Elf64_Word,
sh_flags: Elf64_Xword,
sh_addr: Elf64_Addr,
sh_offset: Elf64_Off,
sh_size: Elf64_Xword,
sh_link: Elf64_Word,
sh_info: Elf64_Word,
sh_addralign: Elf64_Xword,
sh_entsize: Elf64_Xword,
};
pub const Elf32_Chdr = extern struct {
ch_type: Elf32_Word,
ch_size: Elf32_Word,
ch_addralign: Elf32_Word,
};
pub const Elf64_Chdr = extern struct {
ch_type: Elf64_Word,
ch_reserved: Elf64_Word,
ch_size: Elf64_Xword,
ch_addralign: Elf64_Xword,
};
pub const Elf32_Sym = extern struct {
st_name: Elf32_Word,
st_value: Elf32_Addr,
st_size: Elf32_Word,
st_info: u8,
st_other: u8,
st_shndx: Elf32_Section,
};
pub const Elf64_Sym = extern struct {
st_name: Elf64_Word,
st_info: u8,
st_other: u8,
st_shndx: Elf64_Section,
st_value: Elf64_Addr,
st_size: Elf64_Xword,
};
pub const Elf32_Syminfo = extern struct {
si_boundto: Elf32_Half,
si_flags: Elf32_Half,
};
pub const Elf64_Syminfo = extern struct {
si_boundto: Elf64_Half,
si_flags: Elf64_Half,
};
pub const Elf32_Rel = extern struct {
r_offset: Elf32_Addr,
r_info: Elf32_Word,
pub inline fn r_sym(self: @This()) u24 {
return @truncate(u24, self.r_info >> 8);
}
pub inline fn r_type(self: @This()) u8 {
return @truncate(u8, self.r_info & 0xff);
}
};
pub const Elf64_Rel = extern struct {
r_offset: Elf64_Addr,
r_info: Elf64_Xword,
pub inline fn r_sym(self: @This()) u32 {
return @truncate(u32, self.r_info >> 32);
}
pub inline fn r_type(self: @This()) u32 {
return @truncate(u32, self.r_info & 0xffffffff);
}
};
pub const Elf32_Rela = extern struct {
r_offset: Elf32_Addr,
r_info: Elf32_Word,
r_addend: Elf32_Sword,
pub inline fn r_sym(self: @This()) u24 {
return @truncate(u24, self.r_info >> 8);
}
pub inline fn r_type(self: @This()) u8 {
return @truncate(u8, self.r_info & 0xff);
}
};
pub const Elf64_Rela = extern struct {
r_offset: Elf64_Addr,
r_info: Elf64_Xword,
r_addend: Elf64_Sxword,
pub inline fn r_sym(self: @This()) u32 {
return @truncate(u32, self.r_info >> 32);
}
pub inline fn r_type(self: @This()) u32 {
return @truncate(u32, self.r_info & 0xffffffff);
}
};
pub const Elf32_Dyn = extern struct {
d_tag: Elf32_Sword,
d_val: Elf32_Addr,
};
pub const Elf64_Dyn = extern struct {
d_tag: Elf64_Sxword,
d_val: Elf64_Addr,
};
pub const Elf32_Verdef = extern struct {
vd_version: Elf32_Half,
vd_flags: Elf32_Half,
vd_ndx: Elf32_Half,
vd_cnt: Elf32_Half,
vd_hash: Elf32_Word,
vd_aux: Elf32_Word,
vd_next: Elf32_Word,
};
pub const Elf64_Verdef = extern struct {
vd_version: Elf64_Half,
vd_flags: Elf64_Half,
vd_ndx: Elf64_Half,
vd_cnt: Elf64_Half,
vd_hash: Elf64_Word,
vd_aux: Elf64_Word,
vd_next: Elf64_Word,
};
pub const Elf32_Verdaux = extern struct {
vda_name: Elf32_Word,
vda_next: Elf32_Word,
};
pub const Elf64_Verdaux = extern struct {
vda_name: Elf64_Word,
vda_next: Elf64_Word,
};
pub const Elf32_Verneed = extern struct {
vn_version: Elf32_Half,
vn_cnt: Elf32_Half,
vn_file: Elf32_Word,
vn_aux: Elf32_Word,
vn_next: Elf32_Word,
};
pub const Elf64_Verneed = extern struct {
vn_version: Elf64_Half,
vn_cnt: Elf64_Half,
vn_file: Elf64_Word,
vn_aux: Elf64_Word,
vn_next: Elf64_Word,
};
pub const Elf32_Vernaux = extern struct {
vna_hash: Elf32_Word,
vna_flags: Elf32_Half,
vna_other: Elf32_Half,
vna_name: Elf32_Word,
vna_next: Elf32_Word,
};
pub const Elf64_Vernaux = extern struct {
vna_hash: Elf64_Word,
vna_flags: Elf64_Half,
vna_other: Elf64_Half,
vna_name: Elf64_Word,
vna_next: Elf64_Word,
};
pub const Elf32_auxv_t = extern struct {
a_type: u32,
a_un: extern union {
a_val: u32,
},
};
pub const Elf64_auxv_t = extern struct {
a_type: u64,
a_un: extern union {
a_val: u64,
},
};
pub const Elf32_Nhdr = extern struct {
n_namesz: Elf32_Word,
n_descsz: Elf32_Word,
n_type: Elf32_Word,
};
pub const Elf64_Nhdr = extern struct {
n_namesz: Elf64_Word,
n_descsz: Elf64_Word,
n_type: Elf64_Word,
};
pub const Elf32_Move = extern struct {
m_value: Elf32_Xword,
m_info: Elf32_Word,
m_poffset: Elf32_Word,
m_repeat: Elf32_Half,
m_stride: Elf32_Half,
};
pub const Elf64_Move = extern struct {
m_value: Elf64_Xword,
m_info: Elf64_Xword,
m_poffset: Elf64_Xword,
m_repeat: Elf64_Half,
m_stride: Elf64_Half,
};
pub const Elf32_gptab = extern union {
gt_header: extern struct {
gt_current_g_value: Elf32_Word,
gt_unused: Elf32_Word,
},
gt_entry: extern struct {
gt_g_value: Elf32_Word,
gt_bytes: Elf32_Word,
},
};
pub const Elf32_RegInfo = extern struct {
ri_gprmask: Elf32_Word,
ri_cprmask: [4]Elf32_Word,
ri_gp_value: Elf32_Sword,
};
pub const Elf_Options = extern struct {
kind: u8,
size: u8,
@"section": Elf32_Section,
info: Elf32_Word,
};
pub const Elf_Options_Hw = extern struct {
hwp_flags1: Elf32_Word,
hwp_flags2: Elf32_Word,
};
pub const Elf32_Lib = extern struct {
l_name: Elf32_Word,
l_time_stamp: Elf32_Word,
l_checksum: Elf32_Word,
l_version: Elf32_Word,
l_flags: Elf32_Word,
};
pub const Elf64_Lib = extern struct {
l_name: Elf64_Word,
l_time_stamp: Elf64_Word,
l_checksum: Elf64_Word,
l_version: Elf64_Word,
l_flags: Elf64_Word,
};
pub const Elf32_Conflict = Elf32_Addr;
pub const Elf_MIPS_ABIFlags_v0 = extern struct {
version: Elf32_Half,
isa_level: u8,
isa_rev: u8,
gpr_size: u8,
cpr1_size: u8,
cpr2_size: u8,
fp_abi: u8,
isa_ext: Elf32_Word,
ases: Elf32_Word,
flags1: Elf32_Word,
flags2: Elf32_Word,
};
comptime {
debug.assert(@sizeOf(Elf32_Ehdr) == 52);
debug.assert(@sizeOf(Elf64_Ehdr) == 64);
debug.assert(@sizeOf(Elf32_Phdr) == 32);
debug.assert(@sizeOf(Elf64_Phdr) == 56);
debug.assert(@sizeOf(Elf32_Shdr) == 40);
debug.assert(@sizeOf(Elf64_Shdr) == 64);
}
pub const Auxv = switch (@sizeOf(usize)) {
4 => Elf32_auxv_t,
8 => Elf64_auxv_t,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Ehdr = switch (@sizeOf(usize)) {
4 => Elf32_Ehdr,
8 => Elf64_Ehdr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Phdr = switch (@sizeOf(usize)) {
4 => Elf32_Phdr,
8 => Elf64_Phdr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Dyn = switch (@sizeOf(usize)) {
4 => Elf32_Dyn,
8 => Elf64_Dyn,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Rel = switch (@sizeOf(usize)) {
4 => Elf32_Rel,
8 => Elf64_Rel,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Rela = switch (@sizeOf(usize)) {
4 => Elf32_Rela,
8 => Elf64_Rela,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Shdr = switch (@sizeOf(usize)) {
4 => Elf32_Shdr,
8 => Elf64_Shdr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Sym = switch (@sizeOf(usize)) {
4 => Elf32_Sym,
8 => Elf64_Sym,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Verdef = switch (@sizeOf(usize)) {
4 => Elf32_Verdef,
8 => Elf64_Verdef,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Verdaux = switch (@sizeOf(usize)) {
4 => Elf32_Verdaux,
8 => Elf64_Verdaux,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Addr = switch (@sizeOf(usize)) {
4 => Elf32_Addr,
8 => Elf64_Addr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Half = switch (@sizeOf(usize)) {
4 => Elf32_Half,
8 => Elf64_Half,
else => @compileError("expected pointer size of 32 or 64"),
};
/// Machine architectures
/// See current registered ELF machine architectures at:
/// http://www.uxsglobal.com/developers/gabi/latest/ch4.eheader.html
/// The underscore prefix is because many of these start with numbers.
pub const EM = extern enum(u16) {
/// No machine
_NONE = 0,
/// AT&T WE 32100
_M32 = 1,
/// SPARC
_SPARC = 2,
/// Intel 386
_386 = 3,
/// Motorola 68000
_68K = 4,
/// Motorola 88000
_88K = 5,
/// Intel MCU
_IAMCU = 6,
/// Intel 80860
_860 = 7,
/// MIPS R3000
_MIPS = 8,
/// IBM System/370
_S370 = 9,
/// MIPS RS3000 Little-endian
_MIPS_RS3_LE = 10,
/// SPU Mark II
_SPU_2 = 13,
/// Hewlett-Packard PA-RISC
_PARISC = 15,
/// Fujitsu VPP500
_VPP500 = 17,
/// Enhanced instruction set SPARC
_SPARC32PLUS = 18,
/// Intel 80960
_960 = 19,
/// PowerPC
_PPC = 20,
/// PowerPC64
_PPC64 = 21,
/// IBM System/390
_S390 = 22,
/// IBM SPU/SPC
_SPU = 23,
/// NEC V800
_V800 = 36,
/// Fujitsu FR20
_FR20 = 37,
/// TRW RH-32
_RH32 = 38,
/// Motorola RCE
_RCE = 39,
/// ARM
_ARM = 40,
/// DEC Alpha
_ALPHA = 41,
/// Hitachi SH
_SH = 42,
/// SPARC V9
_SPARCV9 = 43,
/// Siemens TriCore
_TRICORE = 44,
/// Argonaut RISC Core
_ARC = 45,
/// Hitachi H8/300
_H8_300 = 46,
/// Hitachi H8/300H
_H8_300H = 47,
/// Hitachi H8S
_H8S = 48,
/// Hitachi H8/500
_H8_500 = 49,
/// Intel IA-64 processor architecture
_IA_64 = 50,
/// Stanford MIPS-X
_MIPS_X = 51,
/// Motorola ColdFire
_COLDFIRE = 52,
/// Motorola M68HC12
_68HC12 = 53,
/// Fujitsu MMA Multimedia Accelerator
_MMA = 54,
/// Siemens PCP
_PCP = 55,
/// Sony nCPU embedded RISC processor
_NCPU = 56,
/// Denso NDR1 microprocessor
_NDR1 = 57,
/// Motorola Star*Core processor
_STARCORE = 58,
/// Toyota ME16 processor
_ME16 = 59,
/// STMicroelectronics ST100 processor
_ST100 = 60,
/// Advanced Logic Corp. TinyJ embedded processor family
_TINYJ = 61,
/// AMD x86-64 architecture
_X86_64 = 62,
/// Sony DSP Processor
_PDSP = 63,
/// Digital Equipment Corp. PDP-10
_PDP10 = 64,
/// Digital Equipment Corp. PDP-11
_PDP11 = 65,
/// Siemens FX66 microcontroller
_FX66 = 66,
/// STMicroelectronics ST9+ 8/16 bit microcontroller
_ST9PLUS = 67,
/// STMicroelectronics ST7 8-bit microcontroller
_ST7 = 68,
/// Motorola MC68HC16 Microcontroller
_68HC16 = 69,
/// Motorola MC68HC11 Microcontroller
_68HC11 = 70,
/// Motorola MC68HC08 Microcontroller
_68HC08 = 71,
/// Motorola MC68HC05 Microcontroller
_68HC05 = 72,
/// Silicon Graphics SVx
_SVX = 73,
/// STMicroelectronics ST19 8-bit microcontroller
_ST19 = 74,
/// Digital VAX
_VAX = 75,
/// Axis Communications 32-bit embedded processor
_CRIS = 76,
/// Infineon Technologies 32-bit embedded processor
_JAVELIN = 77,
/// Element 14 64-bit DSP Processor
_FIREPATH = 78,
/// LSI Logic 16-bit DSP Processor
_ZSP = 79,
/// Donald Knuth's educational 64-bit processor
_MMIX = 80,
/// Harvard University machine-independent object files
_HUANY = 81,
/// SiTera Prism
_PRISM = 82,
/// Atmel AVR 8-bit microcontroller
_AVR = 83,
/// Fujitsu FR30
_FR30 = 84,
/// Mitsubishi D10V
_D10V = 85,
/// Mitsubishi D30V
_D30V = 86,
/// NEC v850
_V850 = 87,
/// Mitsubishi M32R
_M32R = 88,
/// Matsushita MN10300
_MN10300 = 89,
/// Matsushita MN10200
_MN10200 = 90,
/// picoJava
_PJ = 91,
/// OpenRISC 32-bit embedded processor
_OPENRISC = 92,
/// ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5)
_ARC_COMPACT = 93,
/// Tensilica Xtensa Architecture
_XTENSA = 94,
/// Alphamosaic VideoCore processor
_VIDEOCORE = 95,
/// Thompson Multimedia General Purpose Processor
_TMM_GPP = 96,
/// National Semiconductor 32000 series
_NS32K = 97,
/// Tenor Network TPC processor
_TPC = 98,
/// Trebia SNP 1000 processor
_SNP1K = 99,
/// STMicroelectronics (www.st.com) ST200
_ST200 = 100,
/// Ubicom IP2xxx microcontroller family
_IP2K = 101,
/// MAX Processor
_MAX = 102,
/// National Semiconductor CompactRISC microprocessor
_CR = 103,
/// Fujitsu F2MC16
_F2MC16 = 104,
/// Texas Instruments embedded microcontroller msp430
_MSP430 = 105,
/// Analog Devices Blackfin (DSP) processor
_BLACKFIN = 106,
/// S1C33 Family of Seiko Epson processors
_SE_C33 = 107,
/// Sharp embedded microprocessor
_SEP = 108,
/// Arca RISC Microprocessor
_ARCA = 109,
/// Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University
_UNICORE = 110,
/// eXcess: 16/32/64-bit configurable embedded CPU
_EXCESS = 111,
/// Icera Semiconductor Inc. Deep Execution Processor
_DXP = 112,
/// Altera Nios II soft-core processor
_ALTERA_NIOS2 = 113,
/// National Semiconductor CompactRISC CRX
_CRX = 114,
/// Motorola XGATE embedded processor
_XGATE = 115,
/// Infineon C16x/XC16x processor
_C166 = 116,
/// Renesas M16C series microprocessors
_M16C = 117,
/// Microchip Technology dsPIC30F Digital Signal Controller
_DSPIC30F = 118,
/// Freescale Communication Engine RISC core
_CE = 119,
/// Renesas M32C series microprocessors
_M32C = 120,
/// Altium TSK3000 core
_TSK3000 = 131,
/// Freescale RS08 embedded processor
_RS08 = 132,
/// Analog Devices SHARC family of 32-bit DSP processors
_SHARC = 133,
/// Cyan Technology eCOG2 microprocessor
_ECOG2 = 134,
/// Sunplus S+core7 RISC processor
_SCORE7 = 135,
/// New Japan Radio (NJR) 24-bit DSP Processor
_DSP24 = 136,
/// Broadcom VideoCore III processor
_VIDEOCORE3 = 137,
/// RISC processor for Lattice FPGA architecture
_LATTICEMICO32 = 138,
/// Seiko Epson C17 family
_SE_C17 = 139,
/// The Texas Instruments TMS320C6000 DSP family
_TI_C6000 = 140,
/// The Texas Instruments TMS320C2000 DSP family
_TI_C2000 = 141,
/// The Texas Instruments TMS320C55x DSP family
_TI_C5500 = 142,
/// STMicroelectronics 64bit VLIW Data Signal Processor
_MMDSP_PLUS = 160,
/// Cypress M8C microprocessor
_CYPRESS_M8C = 161,
/// Renesas R32C series microprocessors
_R32C = 162,
/// NXP Semiconductors TriMedia architecture family
_TRIMEDIA = 163,
/// Qualcomm Hexagon processor
_HEXAGON = 164,
/// Intel 8051 and variants
_8051 = 165,
/// STMicroelectronics STxP7x family of configurable and extensible RISC processors
_STXP7X = 166,
/// Andes Technology compact code size embedded RISC processor family
_NDS32 = 167,
/// Cyan Technology eCOG1X family
_ECOG1X = 168,
/// Dallas Semiconductor MAXQ30 Core Micro-controllers
_MAXQ30 = 169,
/// New Japan Radio (NJR) 16-bit DSP Processor
_XIMO16 = 170,
/// M2000 Reconfigurable RISC Microprocessor
_MANIK = 171,
/// Cray Inc. NV2 vector architecture
_CRAYNV2 = 172,
/// Renesas RX family
_RX = 173,
/// Imagination Technologies META processor architecture
_METAG = 174,
/// MCST Elbrus general purpose hardware architecture
_MCST_ELBRUS = 175,
/// Cyan Technology eCOG16 family
_ECOG16 = 176,
/// National Semiconductor CompactRISC CR16 16-bit microprocessor
_CR16 = 177,
/// Freescale Extended Time Processing Unit
_ETPU = 178,
/// Infineon Technologies SLE9X core
_SLE9X = 179,
/// Intel L10M
_L10M = 180,
/// Intel K10M
_K10M = 181,
/// ARM AArch64
_AARCH64 = 183,
/// Atmel Corporation 32-bit microprocessor family
_AVR32 = 185,
/// STMicroeletronics STM8 8-bit microcontroller
_STM8 = 186,
/// Tilera TILE64 multicore architecture family
_TILE64 = 187,
/// Tilera TILEPro multicore architecture family
_TILEPRO = 188,
/// NVIDIA CUDA architecture
_CUDA = 190,
/// Tilera TILE-Gx multicore architecture family
_TILEGX = 191,
/// CloudShield architecture family
_CLOUDSHIELD = 192,
/// KIPO-KAIST Core-A 1st generation processor family
_COREA_1ST = 193,
/// KIPO-KAIST Core-A 2nd generation processor family
_COREA_2ND = 194,
/// Synopsys ARCompact V2
_ARC_COMPACT2 = 195,
/// Open8 8-bit RISC soft processor core
_OPEN8 = 196,
/// Renesas RL78 family
_RL78 = 197,
/// Broadcom VideoCore V processor
_VIDEOCORE5 = 198,
/// Renesas 78KOR family
_78KOR = 199,
/// Freescale 56800EX Digital Signal Controller (DSC)
_56800EX = 200,
/// Beyond BA1 CPU architecture
_BA1 = 201,
/// Beyond BA2 CPU architecture
_BA2 = 202,
/// XMOS xCORE processor family
_XCORE = 203,
/// Microchip 8-bit PIC(r) family
_MCHP_PIC = 204,
/// Reserved by Intel
_INTEL205 = 205,
/// Reserved by Intel
_INTEL206 = 206,
/// Reserved by Intel
_INTEL207 = 207,
/// Reserved by Intel
_INTEL208 = 208,
/// Reserved by Intel
_INTEL209 = 209,
/// KM211 KM32 32-bit processor
_KM32 = 210,
/// KM211 KMX32 32-bit processor
_KMX32 = 211,
/// KM211 KMX16 16-bit processor
_KMX16 = 212,
/// KM211 KMX8 8-bit processor
_KMX8 = 213,
/// KM211 KVARC processor
_KVARC = 214,
/// Paneve CDP architecture family
_CDP = 215,
/// Cognitive Smart Memory Processor
_COGE = 216,
/// iCelero CoolEngine
_COOL = 217,
/// Nanoradio Optimized RISC
_NORC = 218,
/// CSR Kalimba architecture family
_CSR_KALIMBA = 219,
/// AMD GPU architecture
_AMDGPU = 224,
/// RISC-V
_RISCV = 243,
/// Lanai 32-bit processor
_LANAI = 244,
/// Linux kernel bpf virtual machine
_BPF = 247,
};
/// Section data should be writable during execution.
pub const SHF_WRITE = 0x1;
/// Section occupies memory during program execution.
pub const SHF_ALLOC = 0x2;
/// Section contains executable machine instructions.
pub const SHF_EXECINSTR = 0x4;
/// The data in this section may be merged.
pub const SHF_MERGE = 0x10;
/// The data in this section is null-terminated strings.
pub const SHF_STRINGS = 0x20;
/// A field in this section holds a section header table index.
pub const SHF_INFO_LINK = 0x40;
/// Adds special ordering requirements for link editors.
pub const SHF_LINK_ORDER = 0x80;
/// This section requires special OS-specific processing to avoid incorrect
/// behavior.
pub const SHF_OS_NONCONFORMING = 0x100;
/// This section is a member of a section group.
pub const SHF_GROUP = 0x200;
/// This section holds Thread-Local Storage.
pub const SHF_TLS = 0x400;
/// Identifies a section containing compressed data.
pub const SHF_COMPRESSED = 0x800;
/// This section is excluded from the final executable or shared library.
pub const SHF_EXCLUDE = 0x80000000;
/// Start of target-specific flags.
pub const SHF_MASKOS = 0x0ff00000;
/// Bits indicating processor-specific flags.
pub const SHF_MASKPROC = 0xf0000000;
/// All sections with the "d" flag are grouped together by the linker to form
/// the data section and the dp register is set to the start of the section by
/// the boot code.
pub const XCORE_SHF_DP_SECTION = 0x10000000;
/// All sections with the "c" flag are grouped together by the linker to form
/// the constant pool and the cp register is set to the start of the constant
/// pool by the boot code.
pub const XCORE_SHF_CP_SECTION = 0x20000000;
/// If an object file section does not have this flag set, then it may not hold
/// more than 2GB and can be freely referred to in objects using smaller code
/// models. Otherwise, only objects using larger code models can refer to them.
/// For example, a medium code model object can refer to data in a section that
/// sets this flag besides being able to refer to data in a section that does
/// not set it; likewise, a small code model object can refer only to code in a
/// section that does not set this flag.
pub const SHF_X86_64_LARGE = 0x10000000;
/// All sections with the GPREL flag are grouped into a global data area
/// for faster accesses
pub const SHF_HEX_GPREL = 0x10000000;
/// Section contains text/data which may be replicated in other sections.
/// Linker must retain only one copy.
pub const SHF_MIPS_NODUPES = 0x01000000;
/// Linker must generate implicit hidden weak names.
pub const SHF_MIPS_NAMES = 0x02000000;
/// Section data local to process.
pub const SHF_MIPS_LOCAL = 0x04000000;
/// Do not strip this section.
pub const SHF_MIPS_NOSTRIP = 0x08000000;
/// Section must be part of global data area.
pub const SHF_MIPS_GPREL = 0x10000000;
/// This section should be merged.
pub const SHF_MIPS_MERGE = 0x20000000;
/// Address size to be inferred from section entry size.
pub const SHF_MIPS_ADDR = 0x40000000;
/// Section data is string data by default.
pub const SHF_MIPS_STRING = 0x80000000;
/// Make code section unreadable when in execute-only mode
pub const SHF_ARM_PURECODE = 0x2000000;
/// Execute
pub const PF_X = 1;
/// Write
pub const PF_W = 2;
/// Read
pub const PF_R = 4;
/// Bits for operating system-specific semantics.
pub const PF_MASKOS = 0x0ff00000;
/// Bits for processor-specific semantics.
pub const PF_MASKPROC = 0xf0000000; | lib/std/elf.zig |
const std = @import("./std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
/// Returns how many bytes the UTF-8 representation would require
/// for the given codepoint.
pub fn utf8CodepointSequenceLength(c: u21) !u3 {
if (c < 0x80) return @as(u3, 1);
if (c < 0x800) return @as(u3, 2);
if (c < 0x10000) return @as(u3, 3);
if (c < 0x110000) return @as(u3, 4);
return error.CodepointTooLarge;
}
/// Given the first byte of a UTF-8 codepoint,
/// returns a number 1-4 indicating the total length of the codepoint in bytes.
/// If this byte does not match the form of a UTF-8 start byte, returns Utf8InvalidStartByte.
pub fn utf8ByteSequenceLength(first_byte: u8) !u3 {
return switch (@clz(u8, ~first_byte)) {
0 => 1,
2 => 2,
3 => 3,
4 => 4,
else => error.Utf8InvalidStartByte,
};
}
/// Encodes the given codepoint into a UTF-8 byte sequence.
/// c: the codepoint.
/// out: the out buffer to write to. Must have a len >= utf8CodepointSequenceLength(c).
/// Errors: if c cannot be encoded in UTF-8.
/// Returns: the number of bytes written to out.
pub fn utf8Encode(c: u21, out: []u8) !u3 {
const length = try utf8CodepointSequenceLength(c);
assert(out.len >= length);
switch (length) {
// The pattern for each is the same
// - Increasing the initial shift by 6 each time
// - Each time after the first shorten the shifted
// value to a max of 0b111111 (63)
1 => out[0] = @intCast(u8, c), // Can just do 0 + codepoint for initial range
2 => {
out[0] = @intCast(u8, 0b11000000 | (c >> 6));
out[1] = @intCast(u8, 0b10000000 | (c & 0b111111));
},
3 => {
if (0xd800 <= c and c <= 0xdfff) return error.Utf8CannotEncodeSurrogateHalf;
out[0] = @intCast(u8, 0b11100000 | (c >> 12));
out[1] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111));
out[2] = @intCast(u8, 0b10000000 | (c & 0b111111));
},
4 => {
out[0] = @intCast(u8, 0b11110000 | (c >> 18));
out[1] = @intCast(u8, 0b10000000 | ((c >> 12) & 0b111111));
out[2] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111));
out[3] = @intCast(u8, 0b10000000 | (c & 0b111111));
},
else => unreachable,
}
return length;
}
const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error;
/// Decodes the UTF-8 codepoint encoded in the given slice of bytes.
/// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable.
/// If you already know the length at comptime, you can call one of
/// utf8Decode2,utf8Decode3,utf8Decode4 directly instead of this function.
pub fn utf8Decode(bytes: []const u8) Utf8DecodeError!u21 {
return switch (bytes.len) {
1 => @as(u21, bytes[0]),
2 => utf8Decode2(bytes),
3 => utf8Decode3(bytes),
4 => utf8Decode4(bytes),
else => unreachable,
};
}
const Utf8Decode2Error = error{
Utf8ExpectedContinuation,
Utf8OverlongEncoding,
};
pub fn utf8Decode2(bytes: []const u8) Utf8Decode2Error!u21 {
assert(bytes.len == 2);
assert(bytes[0] & 0b11100000 == 0b11000000);
var value: u21 = bytes[0] & 0b00011111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (value < 0x80) return error.Utf8OverlongEncoding;
return value;
}
const Utf8Decode3Error = error{
Utf8ExpectedContinuation,
Utf8OverlongEncoding,
Utf8EncodesSurrogateHalf,
};
pub fn utf8Decode3(bytes: []const u8) Utf8Decode3Error!u21 {
assert(bytes.len == 3);
assert(bytes[0] & 0b11110000 == 0b11100000);
var value: u21 = bytes[0] & 0b00001111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (bytes[2] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[2] & 0b00111111;
if (value < 0x800) return error.Utf8OverlongEncoding;
if (0xd800 <= value and value <= 0xdfff) return error.Utf8EncodesSurrogateHalf;
return value;
}
const Utf8Decode4Error = error{
Utf8ExpectedContinuation,
Utf8OverlongEncoding,
Utf8CodepointTooLarge,
};
pub fn utf8Decode4(bytes: []const u8) Utf8Decode4Error!u21 {
assert(bytes.len == 4);
assert(bytes[0] & 0b11111000 == 0b11110000);
var value: u21 = bytes[0] & 0b00000111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (bytes[2] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[2] & 0b00111111;
if (bytes[3] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[3] & 0b00111111;
if (value < 0x10000) return error.Utf8OverlongEncoding;
if (value > 0x10FFFF) return error.Utf8CodepointTooLarge;
return value;
}
pub fn utf8ValidateSlice(s: []const u8) bool {
var i: usize = 0;
while (i < s.len) {
if (utf8ByteSequenceLength(s[i])) |cp_len| {
if (i + cp_len > s.len) {
return false;
}
if (utf8Decode(s[i .. i + cp_len])) |_| {} else |_| {
return false;
}
i += cp_len;
} else |err| {
return false;
}
}
return true;
}
/// Utf8View iterates the code points of a utf-8 encoded string.
///
/// ```
/// var utf8 = (try std.unicode.Utf8View.init("hi there")).iterator();
/// while (utf8.nextCodepointSlice()) |codepoint| {
/// std.debug.warn("got codepoint {}\n", .{codepoint});
/// }
/// ```
pub const Utf8View = struct {
bytes: []const u8,
pub fn init(s: []const u8) !Utf8View {
if (!utf8ValidateSlice(s)) {
return error.InvalidUtf8;
}
return initUnchecked(s);
}
pub fn initUnchecked(s: []const u8) Utf8View {
return Utf8View{ .bytes = s };
}
/// TODO: https://github.com/ziglang/zig/issues/425
pub fn initComptime(comptime s: []const u8) Utf8View {
if (comptime init(s)) |r| {
return r;
} else |err| switch (err) {
error.InvalidUtf8 => {
@compileError("invalid utf8");
unreachable;
},
}
}
pub fn iterator(s: Utf8View) Utf8Iterator {
return Utf8Iterator{
.bytes = s.bytes,
.i = 0,
};
}
};
pub const Utf8Iterator = struct {
bytes: []const u8,
i: usize,
pub fn nextCodepointSlice(it: *Utf8Iterator) ?[]const u8 {
if (it.i >= it.bytes.len) {
return null;
}
const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable;
it.i += cp_len;
return it.bytes[it.i - cp_len .. it.i];
}
pub fn nextCodepoint(it: *Utf8Iterator) ?u21 {
const slice = it.nextCodepointSlice() orelse return null;
switch (slice.len) {
1 => return @as(u21, slice[0]),
2 => return utf8Decode2(slice) catch unreachable,
3 => return utf8Decode3(slice) catch unreachable,
4 => return utf8Decode4(slice) catch unreachable,
else => unreachable,
}
}
};
pub const Utf16LeIterator = struct {
bytes: []const u8,
i: usize,
pub fn init(s: []const u16) Utf16LeIterator {
return Utf16LeIterator{
.bytes = @sliceToBytes(s),
.i = 0,
};
}
pub fn nextCodepoint(it: *Utf16LeIterator) !?u21 {
assert(it.i <= it.bytes.len);
if (it.i == it.bytes.len) return null;
const c0: u21 = mem.readIntSliceLittle(u16, it.bytes[it.i .. it.i + 2]);
if (c0 & ~@as(u21, 0x03ff) == 0xd800) {
// surrogate pair
it.i += 2;
if (it.i >= it.bytes.len) return error.DanglingSurrogateHalf;
const c1: u21 = mem.readIntSliceLittle(u16, it.bytes[it.i .. it.i + 2]);
if (c1 & ~@as(u21, 0x03ff) != 0xdc00) return error.ExpectedSecondSurrogateHalf;
it.i += 2;
return 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff));
} else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) {
return error.UnexpectedSecondSurrogateHalf;
} else {
it.i += 2;
return c0;
}
}
};
test "utf8 encode" {
comptime testUtf8Encode() catch unreachable;
try testUtf8Encode();
}
fn testUtf8Encode() !void {
// A few taken from wikipedia a few taken elsewhere
var array: [4]u8 = undefined;
testing.expect((try utf8Encode(try utf8Decode("€"), array[0..])) == 3);
testing.expect(array[0] == 0b11100010);
testing.expect(array[1] == 0b10000010);
testing.expect(array[2] == 0b10101100);
testing.expect((try utf8Encode(try utf8Decode("$"), array[0..])) == 1);
testing.expect(array[0] == 0b00100100);
testing.expect((try utf8Encode(try utf8Decode("¢"), array[0..])) == 2);
testing.expect(array[0] == 0b11000010);
testing.expect(array[1] == 0b10100010);
testing.expect((try utf8Encode(try utf8Decode("𐍈"), array[0..])) == 4);
testing.expect(array[0] == 0b11110000);
testing.expect(array[1] == 0b10010000);
testing.expect(array[2] == 0b10001101);
testing.expect(array[3] == 0b10001000);
}
test "utf8 encode error" {
comptime testUtf8EncodeError();
testUtf8EncodeError();
}
fn testUtf8EncodeError() void {
var array: [4]u8 = undefined;
testErrorEncode(0xd800, array[0..], error.Utf8CannotEncodeSurrogateHalf);
testErrorEncode(0xdfff, array[0..], error.Utf8CannotEncodeSurrogateHalf);
testErrorEncode(0x110000, array[0..], error.CodepointTooLarge);
testErrorEncode(0x1fffff, array[0..], error.CodepointTooLarge);
}
fn testErrorEncode(codePoint: u21, array: []u8, expectedErr: anyerror) void {
testing.expectError(expectedErr, utf8Encode(codePoint, array));
}
test "utf8 iterator on ascii" {
comptime testUtf8IteratorOnAscii();
testUtf8IteratorOnAscii();
}
fn testUtf8IteratorOnAscii() void {
const s = Utf8View.initComptime("abc");
var it1 = s.iterator();
testing.expect(std.mem.eql(u8, "a", it1.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "b", it1.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "c", it1.nextCodepointSlice().?));
testing.expect(it1.nextCodepointSlice() == null);
var it2 = s.iterator();
testing.expect(it2.nextCodepoint().? == 'a');
testing.expect(it2.nextCodepoint().? == 'b');
testing.expect(it2.nextCodepoint().? == 'c');
testing.expect(it2.nextCodepoint() == null);
}
test "utf8 view bad" {
comptime testUtf8ViewBad();
testUtf8ViewBad();
}
fn testUtf8ViewBad() void {
// Compile-time error.
// const s3 = Utf8View.initComptime("\xfe\xf2");
testing.expectError(error.InvalidUtf8, Utf8View.init("hel\xadlo"));
}
test "utf8 view ok" {
comptime testUtf8ViewOk();
testUtf8ViewOk();
}
fn testUtf8ViewOk() void {
const s = Utf8View.initComptime("東京市");
var it1 = s.iterator();
testing.expect(std.mem.eql(u8, "東", it1.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "京", it1.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "市", it1.nextCodepointSlice().?));
testing.expect(it1.nextCodepointSlice() == null);
var it2 = s.iterator();
testing.expect(it2.nextCodepoint().? == 0x6771);
testing.expect(it2.nextCodepoint().? == 0x4eac);
testing.expect(it2.nextCodepoint().? == 0x5e02);
testing.expect(it2.nextCodepoint() == null);
}
test "bad utf8 slice" {
comptime testBadUtf8Slice();
testBadUtf8Slice();
}
fn testBadUtf8Slice() void {
testing.expect(utf8ValidateSlice("abc"));
testing.expect(!utf8ValidateSlice("abc\xc0"));
testing.expect(!utf8ValidateSlice("abc\xc0abc"));
testing.expect(utf8ValidateSlice("abc\xdf\xbf"));
}
test "valid utf8" {
comptime testValidUtf8();
testValidUtf8();
}
fn testValidUtf8() void {
testValid("\x00", 0x0);
testValid("\x20", 0x20);
testValid("\x7f", 0x7f);
testValid("\xc2\x80", 0x80);
testValid("\xdf\xbf", 0x7ff);
testValid("\xe0\xa0\x80", 0x800);
testValid("\xe1\x80\x80", 0x1000);
testValid("\xef\xbf\xbf", 0xffff);
testValid("\xf0\x90\x80\x80", 0x10000);
testValid("\xf1\x80\x80\x80", 0x40000);
testValid("\xf3\xbf\xbf\xbf", 0xfffff);
testValid("\xf4\x8f\xbf\xbf", 0x10ffff);
}
test "invalid utf8 continuation bytes" {
comptime testInvalidUtf8ContinuationBytes();
testInvalidUtf8ContinuationBytes();
}
fn testInvalidUtf8ContinuationBytes() void {
// unexpected continuation
testError("\x80", error.Utf8InvalidStartByte);
testError("\xbf", error.Utf8InvalidStartByte);
// too many leading 1's
testError("\xf8", error.Utf8InvalidStartByte);
testError("\xff", error.Utf8InvalidStartByte);
// expected continuation for 2 byte sequences
testError("\xc2", error.UnexpectedEof);
testError("\xc2\x00", error.Utf8ExpectedContinuation);
testError("\xc2\xc0", error.Utf8ExpectedContinuation);
// expected continuation for 3 byte sequences
testError("\xe0", error.UnexpectedEof);
testError("\xe0\x00", error.UnexpectedEof);
testError("\xe0\xc0", error.UnexpectedEof);
testError("\xe0\xa0", error.UnexpectedEof);
testError("\xe0\xa0\x00", error.Utf8ExpectedContinuation);
testError("\xe0\xa0\xc0", error.Utf8ExpectedContinuation);
// expected continuation for 4 byte sequences
testError("\xf0", error.UnexpectedEof);
testError("\xf0\x00", error.UnexpectedEof);
testError("\xf0\xc0", error.UnexpectedEof);
testError("\xf0\x90\x00", error.UnexpectedEof);
testError("\xf0\x90\xc0", error.UnexpectedEof);
testError("\xf0\x90\x80\x00", error.Utf8ExpectedContinuation);
testError("\xf0\x90\x80\xc0", error.Utf8ExpectedContinuation);
}
test "overlong utf8 codepoint" {
comptime testOverlongUtf8Codepoint();
testOverlongUtf8Codepoint();
}
fn testOverlongUtf8Codepoint() void {
testError("\xc0\x80", error.Utf8OverlongEncoding);
testError("\xc1\xbf", error.Utf8OverlongEncoding);
testError("\xe0\x80\x80", error.Utf8OverlongEncoding);
testError("\xe0\x9f\xbf", error.Utf8OverlongEncoding);
testError("\xf0\x80\x80\x80", error.Utf8OverlongEncoding);
testError("\xf0\x8f\xbf\xbf", error.Utf8OverlongEncoding);
}
test "misc invalid utf8" {
comptime testMiscInvalidUtf8();
testMiscInvalidUtf8();
}
fn testMiscInvalidUtf8() void {
// codepoint out of bounds
testError("\xf4\x90\x80\x80", error.Utf8CodepointTooLarge);
testError("\xf7\xbf\xbf\xbf", error.Utf8CodepointTooLarge);
// surrogate halves
testValid("\xed\x9f\xbf", 0xd7ff);
testError("\xed\xa0\x80", error.Utf8EncodesSurrogateHalf);
testError("\xed\xbf\xbf", error.Utf8EncodesSurrogateHalf);
testValid("\xee\x80\x80", 0xe000);
}
fn testError(bytes: []const u8, expected_err: anyerror) void {
testing.expectError(expected_err, testDecode(bytes));
}
fn testValid(bytes: []const u8, expected_codepoint: u21) void {
testing.expect((testDecode(bytes) catch unreachable) == expected_codepoint);
}
fn testDecode(bytes: []const u8) !u21 {
const length = try utf8ByteSequenceLength(bytes[0]);
if (bytes.len < length) return error.UnexpectedEof;
testing.expect(bytes.len == length);
return utf8Decode(bytes);
}
/// Caller must free returned memory.
pub fn utf16leToUtf8Alloc(allocator: *mem.Allocator, utf16le: []const u16) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
// optimistically guess that it will all be ascii.
try result.ensureCapacity(utf16le.len);
var out_index: usize = 0;
var it = Utf16LeIterator.init(utf16le);
while (try it.nextCodepoint()) |codepoint| {
const utf8_len = utf8CodepointSequenceLength(codepoint) catch unreachable;
try result.resize(result.len + utf8_len);
assert((utf8Encode(codepoint, result.items[out_index..]) catch unreachable) == utf8_len);
out_index += utf8_len;
}
return result.toOwnedSlice();
}
/// Asserts that the output buffer is big enough.
/// Returns end byte index into utf8.
pub fn utf16leToUtf8(utf8: []u8, utf16le: []const u16) !usize {
var end_index: usize = 0;
var it = Utf16LeIterator.init(utf16le);
while (try it.nextCodepoint()) |codepoint| {
end_index += try utf8Encode(codepoint, utf8[end_index..]);
}
return end_index;
}
test "utf16leToUtf8" {
var utf16le: [2]u16 = undefined;
const utf16le_as_bytes = @sliceToBytes(utf16le[0..]);
{
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 'A');
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 'a');
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "Aa"));
}
{
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0x80);
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xffff);
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "\xc2\x80" ++ "\xef\xbf\xbf"));
}
{
// the values just outside the surrogate half range
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xd7ff);
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xe000);
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "\xed\x9f\xbf" ++ "\xee\x80\x80"));
}
{
// smallest surrogate pair
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xd800);
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdc00);
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "\xf0\x90\x80\x80"));
}
{
// largest surrogate pair
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xdbff);
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdfff);
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "\xf4\x8f\xbf\xbf"));
}
{
mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xdbff);
mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdc00);
const utf8 = try utf16leToUtf8Alloc(std.debug.global_allocator, &utf16le);
testing.expect(mem.eql(u8, utf8, "\xf4\x8f\xb0\x80"));
}
}
pub fn utf8ToUtf16LeWithNull(allocator: *mem.Allocator, utf8: []const u8) ![:0]u16 {
var result = std.ArrayList(u16).init(allocator);
// optimistically guess that it will not require surrogate pairs
try result.ensureCapacity(utf8.len + 1);
const view = try Utf8View.init(utf8);
var it = view.iterator();
while (it.nextCodepoint()) |codepoint| {
if (codepoint < 0x10000) {
const short = @intCast(u16, codepoint);
try result.append(mem.nativeToLittle(u16, short));
} else {
const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
var out: [2]u16 = undefined;
out[0] = mem.nativeToLittle(u16, high);
out[1] = mem.nativeToLittle(u16, low);
try result.appendSlice(out[0..]);
}
}
try result.append(0);
return result.toOwnedSlice()[0..:0];
}
/// Returns index of next character. If exact fit, returned index equals output slice length.
/// Assumes there is enough space for the output.
pub fn utf8ToUtf16Le(utf16le: []u16, utf8: []const u8) !usize {
var dest_i: usize = 0;
var src_i: usize = 0;
while (src_i < utf8.len) {
const n = utf8ByteSequenceLength(utf8[src_i]) catch return error.InvalidUtf8;
const next_src_i = src_i + n;
const codepoint = utf8Decode(utf8[src_i..next_src_i]) catch return error.InvalidUtf8;
if (codepoint < 0x10000) {
const short = @intCast(u16, codepoint);
utf16le[dest_i] = mem.nativeToLittle(u16, short);
dest_i += 1;
} else {
const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
utf16le[dest_i] = mem.nativeToLittle(u16, high);
utf16le[dest_i + 1] = mem.nativeToLittle(u16, low);
dest_i += 2;
}
src_i = next_src_i;
}
return dest_i;
}
test "utf8ToUtf16Le" {
var utf16le: [2]u16 = [_]u16{0} ** 2;
{
const length = try utf8ToUtf16Le(utf16le[0..], "𐐷");
testing.expectEqual(@as(usize, 2), length);
testing.expectEqualSlices(u8, "\x01\xd8\x37\xdc", @sliceToBytes(utf16le[0..]));
}
{
const length = try utf8ToUtf16Le(utf16le[0..], "\u{10FFFF}");
testing.expectEqual(@as(usize, 2), length);
testing.expectEqualSlices(u8, "\xff\xdb\xff\xdf", @sliceToBytes(utf16le[0..]));
}
}
test "utf8ToUtf16LeWithNull" {
{
var bytes: [128]u8 = undefined;
const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;
const utf16 = try utf8ToUtf16LeWithNull(allocator, "𐐷");
testing.expectEqualSlices(u8, "\x01\xd8\x37\xdc\x00\x00", @sliceToBytes(utf16[0..]));
}
{
var bytes: [128]u8 = undefined;
const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;
const utf16 = try utf8ToUtf16LeWithNull(allocator, "\u{10FFFF}");
testing.expectEqualSlices(u8, "\xff\xdb\xff\xdf\x00\x00", @sliceToBytes(utf16[0..]));
}
} | lib/std/unicode.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const assert = std.debug.assert;
const log = std.log.scoped(.module);
const BigIntConst = std.math.big.int.Const;
const BigIntMutable = std.math.big.int.Mutable;
const Target = std.Target;
const ast = std.zig.ast;
const Module = @This();
const Compilation = @import("Compilation.zig");
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const TypedValue = @import("TypedValue.zig");
const Package = @import("Package.zig");
const link = @import("link.zig");
const ir = @import("ir.zig");
const zir = @import("zir.zig");
const trace = @import("tracy.zig").trace;
const AstGen = @import("AstGen.zig");
const Sema = @import("Sema.zig");
const target_util = @import("target.zig");
/// General-purpose allocator. Used for both temporary and long-term storage.
gpa: *Allocator,
comp: *Compilation,
/// Where our incremental compilation metadata serialization will go.
zig_cache_artifact_directory: Compilation.Directory,
/// Pointer to externally managed resource. `null` if there is no zig file being compiled.
root_pkg: *Package,
/// Module owns this resource.
root_scope: *Scope.File,
/// It's rare for a decl to be exported, so we save memory by having a sparse map of
/// Decl pointers to details about them being exported.
/// The Export memory is owned by the `export_owners` table; the slice itself is owned by this table.
/// The slice is guaranteed to not be empty.
decl_exports: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
/// We track which export is associated with the given symbol name for quick
/// detection of symbol collisions.
symbol_exports: std.StringArrayHashMapUnmanaged(*Export) = .{},
/// This models the Decls that perform exports, so that `decl_exports` can be updated when a Decl
/// is modified. Note that the key of this table is not the Decl being exported, but the Decl that
/// is performing the export of another Decl.
/// This table owns the Export memory.
export_owners: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
/// Maps fully qualified namespaced names to the Decl struct for them.
decl_table: std.ArrayHashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
/// We optimize memory usage for a compilation with no compile errors by storing the
/// error messages and mapping outside of `Decl`.
/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.
/// Note that a Decl can succeed but the Fn it represents can fail. In this case,
/// a Decl can have a failed_decls entry but have analysis status of success.
failed_decls: std.AutoArrayHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
/// When emit_h is non-null, each Decl gets one more compile error slot for
/// emit-h failing for that Decl. This table is also how we tell if a Decl has
/// failed emit-h or succeeded.
emit_h_failed_decls: std.AutoArrayHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
/// Keep track of one `@compileLog` callsite per owner Decl.
compile_log_decls: std.AutoArrayHashMapUnmanaged(*Decl, SrcLoc) = .{},
/// Using a map here for consistency with the other fields here.
/// The ErrorMsg memory is owned by the `Scope.File`, using Module's general purpose allocator.
failed_files: std.AutoArrayHashMapUnmanaged(*Scope.File, *ErrorMsg) = .{},
/// Using a map here for consistency with the other fields here.
/// The ErrorMsg memory is owned by the `Export`, using Module's general purpose allocator.
failed_exports: std.AutoArrayHashMapUnmanaged(*Export, *ErrorMsg) = .{},
next_anon_name_index: usize = 0,
/// Candidates for deletion. After a semantic analysis update completes, this list
/// contains Decls that need to be deleted if they end up having no references to them.
deletion_set: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
/// Error tags and their values, tag names are duped with mod.gpa.
/// Corresponds with `error_name_list`.
global_error_set: std.StringHashMapUnmanaged(ErrorInt) = .{},
/// ErrorInt -> []const u8 for fast lookups for @intToError at comptime
/// Corresponds with `global_error_set`.
error_name_list: ArrayListUnmanaged([]const u8) = .{},
/// Keys are fully qualified paths
import_table: std.StringArrayHashMapUnmanaged(*Scope.File) = .{},
/// Incrementing integer used to compare against the corresponding Decl
/// field to determine whether a Decl's status applies to an ongoing update, or a
/// previous analysis.
generation: u32 = 0,
/// When populated it means there was an error opening/reading the root source file.
failed_root_src_file: ?anyerror = null,
stage1_flags: packed struct {
have_winmain: bool = false,
have_wwinmain: bool = false,
have_winmain_crt_startup: bool = false,
have_wwinmain_crt_startup: bool = false,
have_dllmain_crt_startup: bool = false,
have_c_main: bool = false,
reserved: u2 = 0,
} = .{},
emit_h: ?Compilation.EmitLoc,
compile_log_text: ArrayListUnmanaged(u8) = .{},
pub const ErrorInt = u32;
pub const Export = struct {
options: std.builtin.ExportOptions,
src: LazySrcLoc,
/// Represents the position of the export, if any, in the output file.
link: link.File.Export,
/// The Decl that performs the export. Note that this is *not* the Decl being exported.
owner_decl: *Decl,
/// The Decl being exported. Note this is *not* the Decl performing the export.
exported_decl: *Decl,
status: enum {
in_progress,
failed,
/// Indicates that the failure was due to a temporary issue, such as an I/O error
/// when writing to the output file. Retrying the export may succeed.
failed_retryable,
complete,
},
};
/// When Module emit_h field is non-null, each Decl is allocated via this struct, so that
/// there can be EmitH state attached to each Decl.
pub const DeclPlusEmitH = struct {
decl: Decl,
emit_h: EmitH,
};
pub const Decl = struct {
/// This name is relative to the containing namespace of the decl. It uses
/// null-termination to save bytes, since there can be a lot of decls in a
/// compilation. The null byte is not allowed in symbol names, because
/// executable file formats use null-terminated strings for symbol names.
/// All Decls have names, even values that are not bound to a zig namespace.
/// This is necessary for mapping them to an address in the output file.
/// Memory owned by this decl, using Module's allocator.
name: [*:0]const u8,
/// The direct parent container of the Decl.
/// Reference to externally owned memory.
container: *Scope.Container,
/// An integer that can be checked against the corresponding incrementing
/// generation field of Module. This is used to determine whether `complete` status
/// represents pre- or post- re-analysis.
generation: u32,
/// The AST Node index or ZIR Inst index that contains this declaration.
/// Must be recomputed when the corresponding source file is modified.
src_node: ast.Node.Index,
/// The most recent value of the Decl after a successful semantic analysis.
typed_value: union(enum) {
never_succeeded: void,
most_recent: TypedValue.Managed,
},
/// Represents the "shallow" analysis status. For example, for decls that are functions,
/// the function type is analyzed with this set to `in_progress`, however, the semantic
/// analysis of the function body is performed with this value set to `success`. Functions
/// have their own analysis status field.
analysis: enum {
/// This Decl corresponds to an AST Node that has not been referenced yet, and therefore
/// because of Zig's lazy declaration analysis, it will remain unanalyzed until referenced.
unreferenced,
/// Semantic analysis for this Decl is running right now. This state detects dependency loops.
in_progress,
/// This Decl might be OK but it depends on another one which did not successfully complete
/// semantic analysis.
dependency_failure,
/// Semantic analysis failure.
/// There will be a corresponding ErrorMsg in Module.failed_decls.
sema_failure,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
/// This indicates the failure was something like running out of disk space,
/// and attempting semantic analysis again may succeed.
sema_failure_retryable,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
codegen_failure,
/// There will be a corresponding ErrorMsg in Module.failed_decls.
/// This indicates the failure was something like running out of disk space,
/// and attempting codegen again may succeed.
codegen_failure_retryable,
/// Everything is done. During an update, this Decl may be out of date, depending
/// on its dependencies. The `generation` field can be used to determine if this
/// completion status occurred before or after a given update.
complete,
/// A Module update is in progress, and this Decl has been flagged as being known
/// to require re-analysis.
outdated,
},
/// This flag is set when this Decl is added to `Module.deletion_set`, and cleared
/// when removed.
deletion_flag: bool,
/// Whether the corresponding AST decl has a `pub` keyword.
is_pub: bool,
/// Represents the position of the code in the output file.
/// This is populated regardless of semantic analysis and code generation.
link: link.File.LinkBlock,
/// Represents the function in the linked output file, if the `Decl` is a function.
/// This is stored here and not in `Fn` because `Decl` survives across updates but
/// `Fn` does not.
/// TODO Look into making `Fn` a longer lived structure and moving this field there
/// to save on memory usage.
fn_link: link.File.LinkFn,
contents_hash: std.zig.SrcHash,
/// The shallow set of other decls whose typed_value could possibly change if this Decl's
/// typed_value is modified.
dependants: DepsTable = .{},
/// The shallow set of other decls whose typed_value changing indicates that this Decl's
/// typed_value may need to be regenerated.
dependencies: DepsTable = .{},
/// The reason this is not `std.AutoArrayHashMapUnmanaged` is a workaround for
/// stage1 compiler giving me: `error: struct 'Module.Decl' depends on itself`
pub const DepsTable = std.ArrayHashMapUnmanaged(*Decl, void, std.array_hash_map.getAutoHashFn(*Decl), std.array_hash_map.getAutoEqlFn(*Decl), false);
pub fn destroy(decl: *Decl, module: *Module) void {
const gpa = module.gpa;
gpa.free(mem.spanZ(decl.name));
if (decl.typedValueManaged()) |tvm| {
if (tvm.typed_value.val.castTag(.function)) |payload| {
const func = payload.data;
func.deinit(gpa);
}
tvm.deinit(gpa);
}
decl.dependants.deinit(gpa);
decl.dependencies.deinit(gpa);
if (module.emit_h != null) {
const decl_plus_emit_h = @fieldParentPtr(DeclPlusEmitH, "decl", decl);
decl_plus_emit_h.emit_h.fwd_decl.deinit(gpa);
gpa.destroy(decl_plus_emit_h);
} else {
gpa.destroy(decl);
}
}
pub fn relativeToNodeIndex(decl: Decl, offset: i32) ast.Node.Index {
return @bitCast(ast.Node.Index, offset + @bitCast(i32, decl.src_node));
}
pub fn nodeIndexToRelative(decl: Decl, node_index: ast.Node.Index) i32 {
return @bitCast(i32, node_index) - @bitCast(i32, decl.src_node);
}
pub fn tokSrcLoc(decl: Decl, token_index: ast.TokenIndex) LazySrcLoc {
return .{ .token_offset = token_index - decl.srcToken() };
}
pub fn nodeSrcLoc(decl: Decl, node_index: ast.Node.Index) LazySrcLoc {
return .{ .node_offset = decl.nodeIndexToRelative(node_index) };
}
pub fn srcLoc(decl: *Decl) SrcLoc {
return .{
.container = .{ .decl = decl },
.lazy = .{ .node_offset = 0 },
};
}
pub fn srcToken(decl: Decl) u32 {
const tree = &decl.container.file_scope.tree;
return tree.firstToken(decl.src_node);
}
pub fn srcByteOffset(decl: Decl) u32 {
const tree = &decl.container.file_scope.tree;
return tree.tokens.items(.start)[decl.srcToken()];
}
pub fn fullyQualifiedNameHash(decl: Decl) Scope.NameHash {
return decl.container.fullyQualifiedNameHash(mem.spanZ(decl.name));
}
pub fn renderFullyQualifiedName(decl: Decl, writer: anytype) !void {
const unqualified_name = mem.spanZ(decl.name);
return decl.container.renderFullyQualifiedName(unqualified_name, writer);
}
pub fn getFullyQualifiedName(decl: Decl, gpa: *Allocator) ![]u8 {
var buffer = std.ArrayList(u8).init(gpa);
defer buffer.deinit();
try decl.renderFullyQualifiedName(buffer.writer());
return buffer.toOwnedSlice();
}
pub fn typedValue(decl: *Decl) error{AnalysisFail}!TypedValue {
const tvm = decl.typedValueManaged() orelse return error.AnalysisFail;
return tvm.typed_value;
}
pub fn value(decl: *Decl) error{AnalysisFail}!Value {
return (try decl.typedValue()).val;
}
pub fn dump(decl: *Decl) void {
const loc = std.zig.findLineColumn(decl.scope.source.bytes, decl.src);
std.debug.print("{s}:{d}:{d} name={s} status={s}", .{
decl.scope.sub_file_path,
loc.line + 1,
loc.column + 1,
mem.spanZ(decl.name),
@tagName(decl.analysis),
});
if (decl.typedValueManaged()) |tvm| {
std.debug.print(" ty={} val={}", .{ tvm.typed_value.ty, tvm.typed_value.val });
}
std.debug.print("\n", .{});
}
pub fn typedValueManaged(decl: *Decl) ?*TypedValue.Managed {
switch (decl.typed_value) {
.most_recent => |*x| return x,
.never_succeeded => return null,
}
}
pub fn getFileScope(decl: Decl) *Scope.File {
return decl.container.file_scope;
}
pub fn getEmitH(decl: *Decl, module: *Module) *EmitH {
assert(module.emit_h != null);
const decl_plus_emit_h = @fieldParentPtr(DeclPlusEmitH, "decl", decl);
return &decl_plus_emit_h.emit_h;
}
fn removeDependant(decl: *Decl, other: *Decl) void {
decl.dependants.removeAssertDiscard(other);
}
fn removeDependency(decl: *Decl, other: *Decl) void {
decl.dependencies.removeAssertDiscard(other);
}
};
/// This state is attached to every Decl when Module emit_h is non-null.
pub const EmitH = struct {
fwd_decl: ArrayListUnmanaged(u8) = .{},
};
/// Represents the data that an explicit error set syntax provides.
pub const ErrorSet = struct {
owner_decl: *Decl,
/// Offset from Decl node index, points to the error set AST node.
node_offset: i32,
names_len: u32,
/// The string bytes are stored in the owner Decl arena.
/// They are in the same order they appear in the AST.
names_ptr: [*]const []const u8,
pub fn srcLoc(self: ErrorSet) SrcLoc {
return .{
.container = .{ .decl = self.owner_decl },
.lazy = .{ .node_offset = self.node_offset },
};
}
};
/// Represents the data that a struct declaration provides.
pub const Struct = struct {
owner_decl: *Decl,
/// Set of field names in declaration order.
fields: std.StringArrayHashMapUnmanaged(Field),
/// Represents the declarations inside this struct.
container: Scope.Container,
/// Offset from `owner_decl`, points to the struct AST node.
node_offset: i32,
pub const Field = struct {
ty: Type,
abi_align: Value,
/// Uses `unreachable_value` to indicate no default.
default_val: Value,
};
pub fn getFullyQualifiedName(s: *Struct, gpa: *Allocator) ![]u8 {
return s.owner_decl.getFullyQualifiedName(gpa);
}
pub fn srcLoc(s: Struct) SrcLoc {
return .{
.container = .{ .decl = s.owner_decl },
.lazy = .{ .node_offset = s.node_offset },
};
}
};
/// Represents the data that an enum declaration provides, when the fields
/// are auto-numbered, and there are no declarations. The integer tag type
/// is inferred to be the smallest power of two unsigned int that fits
/// the number of fields.
pub const EnumSimple = struct {
owner_decl: *Decl,
/// Set of field names in declaration order.
fields: std.StringArrayHashMapUnmanaged(void),
/// Offset from `owner_decl`, points to the enum decl AST node.
node_offset: i32,
pub fn srcLoc(self: EnumSimple) SrcLoc {
return .{
.container = .{ .decl = self.owner_decl },
.lazy = .{ .node_offset = self.node_offset },
};
}
};
/// Represents the data that an enum declaration provides, when there is
/// at least one tag value explicitly specified, or at least one declaration.
pub const EnumFull = struct {
owner_decl: *Decl,
/// An integer type which is used for the numerical value of the enum.
/// Whether zig chooses this type or the user specifies it, it is stored here.
tag_ty: Type,
/// Set of field names in declaration order.
fields: std.StringArrayHashMapUnmanaged(void),
/// Maps integer tag value to field index.
/// Entries are in declaration order, same as `fields`.
/// If this hash map is empty, it means the enum tags are auto-numbered.
values: ValueMap,
/// Represents the declarations inside this struct.
container: Scope.Container,
/// Offset from `owner_decl`, points to the enum decl AST node.
node_offset: i32,
pub const ValueMap = std.ArrayHashMapUnmanaged(Value, void, Value.hash_u32, Value.eql, false);
pub fn srcLoc(self: EnumFull) SrcLoc {
return .{
.container = .{ .decl = self.owner_decl },
.lazy = .{ .node_offset = self.node_offset },
};
}
};
/// Some Fn struct memory is owned by the Decl's TypedValue.Managed arena allocator.
/// Extern functions do not have this data structure; they are represented by
/// the `Decl` only, with a `Value` tag of `extern_fn`.
pub const Fn = struct {
owner_decl: *Decl,
/// Contains un-analyzed ZIR instructions generated from Zig source AST.
/// Even after we finish analysis, the ZIR is kept in memory, so that
/// comptime and inline function calls can happen.
/// Parameter names are stored here so that they may be referenced for debug info,
/// without having source code bytes loaded into memory.
/// The number of parameters is determined by referring to the type.
/// The first N elements of `extra` are indexes into `string_bytes` to
/// a null-terminated string.
/// This memory is managed with gpa, must be freed when the function is freed.
zir: zir.Code,
/// undefined unless analysis state is `success`.
body: ir.Body,
state: Analysis,
pub const Analysis = enum {
queued,
/// This function intentionally only has ZIR generated because it is marked
/// inline, which means no runtime version of the function will be generated.
inline_only,
in_progress,
/// There will be a corresponding ErrorMsg in Module.failed_decls
sema_failure,
/// This Fn might be OK but it depends on another Decl which did not
/// successfully complete semantic analysis.
dependency_failure,
success,
};
/// For debugging purposes.
pub fn dump(func: *Fn, mod: Module) void {
ir.dumpFn(mod, func);
}
pub fn deinit(func: *Fn, gpa: *Allocator) void {
func.zir.deinit(gpa);
}
};
pub const Var = struct {
/// if is_extern == true this is undefined
init: Value,
owner_decl: *Decl,
is_extern: bool,
is_mutable: bool,
is_threadlocal: bool,
};
pub const Scope = struct {
tag: Tag,
pub const NameHash = [16]u8;
pub fn cast(base: *Scope, comptime T: type) ?*T {
if (base.tag != T.base_tag)
return null;
return @fieldParentPtr(T, "base", base);
}
/// Returns the arena Allocator associated with the Decl of the Scope.
pub fn arena(scope: *Scope) *Allocator {
switch (scope.tag) {
.block => return scope.cast(Block).?.sema.arena,
.gen_zir => return scope.cast(GenZir).?.astgen.arena,
.local_val => return scope.cast(LocalVal).?.gen_zir.astgen.arena,
.local_ptr => return scope.cast(LocalPtr).?.gen_zir.astgen.arena,
.file => unreachable,
.container => unreachable,
.decl_ref => unreachable,
}
}
pub fn ownerDecl(scope: *Scope) ?*Decl {
return switch (scope.tag) {
.block => scope.cast(Block).?.sema.owner_decl,
.gen_zir => scope.cast(GenZir).?.astgen.decl,
.local_val => scope.cast(LocalVal).?.gen_zir.astgen.decl,
.local_ptr => scope.cast(LocalPtr).?.gen_zir.astgen.decl,
.file => null,
.container => null,
.decl_ref => scope.cast(DeclRef).?.decl,
};
}
pub fn srcDecl(scope: *Scope) ?*Decl {
return switch (scope.tag) {
.block => scope.cast(Block).?.src_decl,
.gen_zir => scope.cast(GenZir).?.astgen.decl,
.local_val => scope.cast(LocalVal).?.gen_zir.astgen.decl,
.local_ptr => scope.cast(LocalPtr).?.gen_zir.astgen.decl,
.file => null,
.container => null,
.decl_ref => scope.cast(DeclRef).?.decl,
};
}
/// Asserts the scope has a parent which is a Container and returns it.
pub fn namespace(scope: *Scope) *Container {
switch (scope.tag) {
.block => return scope.cast(Block).?.sema.owner_decl.container,
.gen_zir => return scope.cast(GenZir).?.astgen.decl.container,
.local_val => return scope.cast(LocalVal).?.gen_zir.astgen.decl.container,
.local_ptr => return scope.cast(LocalPtr).?.gen_zir.astgen.decl.container,
.file => return &scope.cast(File).?.root_container,
.container => return scope.cast(Container).?,
.decl_ref => return scope.cast(DeclRef).?.decl.container,
}
}
/// Must generate unique bytes with no collisions with other decls.
/// The point of hashing here is only to limit the number of bytes of
/// the unique identifier to a fixed size (16 bytes).
pub fn fullyQualifiedNameHash(scope: *Scope, name: []const u8) NameHash {
switch (scope.tag) {
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.file => unreachable,
.container => return scope.cast(Container).?.fullyQualifiedNameHash(name),
.decl_ref => unreachable,
}
}
/// Asserts the scope is a child of a File and has an AST tree and returns the tree.
pub fn tree(scope: *Scope) *const ast.Tree {
switch (scope.tag) {
.file => return &scope.cast(File).?.tree,
.block => return &scope.cast(Block).?.src_decl.container.file_scope.tree,
.gen_zir => return scope.cast(GenZir).?.tree(),
.local_val => return &scope.cast(LocalVal).?.gen_zir.astgen.decl.container.file_scope.tree,
.local_ptr => return &scope.cast(LocalPtr).?.gen_zir.astgen.decl.container.file_scope.tree,
.container => return &scope.cast(Container).?.file_scope.tree,
.decl_ref => return &scope.cast(DeclRef).?.decl.container.file_scope.tree,
}
}
/// Asserts the scope is a child of a `GenZir` and returns it.
pub fn getGenZir(scope: *Scope) *GenZir {
return switch (scope.tag) {
.block => unreachable,
.gen_zir => scope.cast(GenZir).?,
.local_val => return scope.cast(LocalVal).?.gen_zir,
.local_ptr => return scope.cast(LocalPtr).?.gen_zir,
.file => unreachable,
.container => unreachable,
.decl_ref => unreachable,
};
}
/// Asserts the scope has a parent which is a Container or File and
/// returns the sub_file_path field.
pub fn subFilePath(base: *Scope) []const u8 {
switch (base.tag) {
.container => return @fieldParentPtr(Container, "base", base).file_scope.sub_file_path,
.file => return @fieldParentPtr(File, "base", base).sub_file_path,
.block => unreachable,
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.decl_ref => unreachable,
}
}
pub fn getSource(base: *Scope, module: *Module) ![:0]const u8 {
switch (base.tag) {
.container => return @fieldParentPtr(Container, "base", base).file_scope.getSource(module),
.file => return @fieldParentPtr(File, "base", base).getSource(module),
.gen_zir => unreachable,
.local_val => unreachable,
.local_ptr => unreachable,
.block => unreachable,
.decl_ref => unreachable,
}
}
/// When called from inside a Block Scope, chases the src_decl, not the owner_decl.
pub fn getFileScope(base: *Scope) *Scope.File {
var cur = base;
while (true) {
cur = switch (cur.tag) {
.container => return @fieldParentPtr(Container, "base", cur).file_scope,
.file => return @fieldParentPtr(File, "base", cur),
.gen_zir => @fieldParentPtr(GenZir, "base", cur).parent,
.local_val => @fieldParentPtr(LocalVal, "base", cur).parent,
.local_ptr => @fieldParentPtr(LocalPtr, "base", cur).parent,
.block => return @fieldParentPtr(Block, "base", cur).src_decl.container.file_scope,
.decl_ref => return @fieldParentPtr(DeclRef, "base", cur).decl.container.file_scope,
};
}
}
fn name_hash_hash(x: NameHash) u32 {
return @truncate(u32, @bitCast(u128, x));
}
fn name_hash_eql(a: NameHash, b: NameHash) bool {
return @bitCast(u128, a) == @bitCast(u128, b);
}
pub const Tag = enum {
/// .zig source code.
file,
/// struct, enum or union, every .file contains one of these.
container,
block,
gen_zir,
local_val,
local_ptr,
/// Used for simple error reporting. Only contains a reference to a
/// `Decl` for use with `srcDecl` and `ownerDecl`.
/// Has no parents or children.
decl_ref,
};
pub const Container = struct {
pub const base_tag: Tag = .container;
base: Scope = Scope{ .tag = base_tag },
file_scope: *Scope.File,
parent_name_hash: NameHash,
/// Direct children of the file.
decls: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
ty: Type,
pub fn deinit(cont: *Container, gpa: *Allocator) void {
cont.decls.deinit(gpa);
// TODO either Container of File should have an arena for sub_file_path and ty
gpa.destroy(cont.ty.castTag(.empty_struct).?);
gpa.free(cont.file_scope.sub_file_path);
cont.* = undefined;
}
pub fn removeDecl(cont: *Container, child: *Decl) void {
_ = cont.decls.swapRemove(child);
}
pub fn fullyQualifiedNameHash(cont: *Container, name: []const u8) NameHash {
return std.zig.hashName(cont.parent_name_hash, ".", name);
}
pub fn renderFullyQualifiedName(cont: Container, name: []const u8, writer: anytype) !void {
// TODO this should render e.g. "std.fs.Dir.OpenOptions"
return writer.writeAll(name);
}
};
pub const File = struct {
pub const base_tag: Tag = .file;
base: Scope = Scope{ .tag = base_tag },
status: enum {
never_loaded,
unloaded_success,
unloaded_parse_failure,
loaded_success,
},
/// Relative to the owning package's root_src_dir.
/// Reference to external memory, not owned by File.
sub_file_path: []const u8,
source: union(enum) {
unloaded: void,
bytes: [:0]const u8,
},
/// Whether this is populated or not depends on `status`.
tree: ast.Tree,
/// Package that this file is a part of, managed externally.
pkg: *Package,
root_container: Container,
pub fn unload(file: *File, gpa: *Allocator) void {
switch (file.status) {
.unloaded_parse_failure,
.never_loaded,
.unloaded_success,
=> {
file.status = .unloaded_success;
},
.loaded_success => {
file.tree.deinit(gpa);
file.status = .unloaded_success;
},
}
switch (file.source) {
.bytes => |bytes| {
gpa.free(bytes);
file.source = .{ .unloaded = {} };
},
.unloaded => {},
}
}
pub fn deinit(file: *File, gpa: *Allocator) void {
file.root_container.deinit(gpa);
file.unload(gpa);
file.* = undefined;
}
pub fn destroy(file: *File, gpa: *Allocator) void {
file.deinit(gpa);
gpa.destroy(file);
}
pub fn dumpSrc(file: *File, src: LazySrcLoc) void {
const loc = std.zig.findLineColumn(file.source.bytes, src);
std.debug.print("{s}:{d}:{d}\n", .{ file.sub_file_path, loc.line + 1, loc.column + 1 });
}
pub fn getSource(file: *File, module: *Module) ![:0]const u8 {
switch (file.source) {
.unloaded => {
const source = try file.pkg.root_src_directory.handle.readFileAllocOptions(
module.gpa,
file.sub_file_path,
std.math.maxInt(u32),
null,
1,
0,
);
file.source = .{ .bytes = source };
return source;
},
.bytes => |bytes| return bytes,
}
}
};
/// This is the context needed to semantically analyze ZIR instructions and
/// produce TZIR instructions.
/// This is a temporary structure stored on the stack; references to it are valid only
/// during semantic analysis of the block.
pub const Block = struct {
pub const base_tag: Tag = .block;
base: Scope = Scope{ .tag = base_tag },
parent: ?*Block,
/// Shared among all child blocks.
sema: *Sema,
/// This Decl is the Decl according to the Zig source code corresponding to this Block.
/// This can vary during inline or comptime function calls. See `Sema.owner_decl`
/// for the one that will be the same for all Block instances.
src_decl: *Decl,
instructions: ArrayListUnmanaged(*ir.Inst),
label: ?Label = null,
inlining: ?*Inlining,
is_comptime: bool,
/// This `Block` maps a block ZIR instruction to the corresponding
/// TZIR instruction for break instruction analysis.
pub const Label = struct {
zir_block: zir.Inst.Index,
merges: Merges,
};
/// This `Block` indicates that an inline function call is happening
/// and return instructions should be analyzed as a break instruction
/// to this TZIR block instruction.
/// It is shared among all the blocks in an inline or comptime called
/// function.
pub const Inlining = struct {
merges: Merges,
};
pub const Merges = struct {
block_inst: *ir.Inst.Block,
/// Separate array list from break_inst_list so that it can be passed directly
/// to resolvePeerTypes.
results: ArrayListUnmanaged(*ir.Inst),
/// Keeps track of the break instructions so that the operand can be replaced
/// if we need to add type coercion at the end of block analysis.
/// Same indexes, capacity, length as `results`.
br_list: ArrayListUnmanaged(*ir.Inst.Br),
};
/// For debugging purposes.
pub fn dump(block: *Block, mod: Module) void {
zir.dumpBlock(mod, block);
}
pub fn makeSubBlock(parent: *Block) Block {
return .{
.parent = parent,
.sema = parent.sema,
.src_decl = parent.src_decl,
.instructions = .{},
.label = null,
.inlining = parent.inlining,
.is_comptime = parent.is_comptime,
};
}
pub fn wantSafety(block: *const Block) bool {
// TODO take into account scope's safety overrides
return switch (block.sema.mod.optimizeMode()) {
.Debug => true,
.ReleaseSafe => true,
.ReleaseFast => false,
.ReleaseSmall => false,
};
}
pub fn getFileScope(block: *Block) *Scope.File {
return block.src_decl.container.file_scope;
}
pub fn addNoOp(
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
comptime tag: ir.Inst.Tag,
) !*ir.Inst {
const inst = try block.sema.arena.create(tag.Type());
inst.* = .{
.base = .{
.tag = tag,
.ty = ty,
.src = src,
},
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addUnOp(
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
tag: ir.Inst.Tag,
operand: *ir.Inst,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.UnOp);
inst.* = .{
.base = .{
.tag = tag,
.ty = ty,
.src = src,
},
.operand = operand,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addBinOp(
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
tag: ir.Inst.Tag,
lhs: *ir.Inst,
rhs: *ir.Inst,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.BinOp);
inst.* = .{
.base = .{
.tag = tag,
.ty = ty,
.src = src,
},
.lhs = lhs,
.rhs = rhs,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addBr(
scope_block: *Scope.Block,
src: LazySrcLoc,
target_block: *ir.Inst.Block,
operand: *ir.Inst,
) !*ir.Inst.Br {
const inst = try scope_block.sema.arena.create(ir.Inst.Br);
inst.* = .{
.base = .{
.tag = .br,
.ty = Type.initTag(.noreturn),
.src = src,
},
.operand = operand,
.block = target_block,
};
try scope_block.instructions.append(scope_block.sema.gpa, &inst.base);
return inst;
}
pub fn addCondBr(
block: *Scope.Block,
src: LazySrcLoc,
condition: *ir.Inst,
then_body: ir.Body,
else_body: ir.Body,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.CondBr);
inst.* = .{
.base = .{
.tag = .condbr,
.ty = Type.initTag(.noreturn),
.src = src,
},
.condition = condition,
.then_body = then_body,
.else_body = else_body,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addCall(
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
func: *ir.Inst,
args: []const *ir.Inst,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.Call);
inst.* = .{
.base = .{
.tag = .call,
.ty = ty,
.src = src,
},
.func = func,
.args = args,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addSwitchBr(
block: *Scope.Block,
src: LazySrcLoc,
operand: *ir.Inst,
cases: []ir.Inst.SwitchBr.Case,
else_body: ir.Body,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.SwitchBr);
inst.* = .{
.base = .{
.tag = .switchbr,
.ty = Type.initTag(.noreturn),
.src = src,
},
.target = operand,
.cases = cases,
.else_body = else_body,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addDbgStmt(block: *Scope.Block, src: LazySrcLoc, abs_byte_off: u32) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.DbgStmt);
inst.* = .{
.base = .{
.tag = .dbg_stmt,
.ty = Type.initTag(.void),
.src = src,
},
.byte_offset = abs_byte_off,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
pub fn addStructFieldPtr(
block: *Scope.Block,
src: LazySrcLoc,
ty: Type,
struct_ptr: *ir.Inst,
field_index: u32,
) !*ir.Inst {
const inst = try block.sema.arena.create(ir.Inst.StructFieldPtr);
inst.* = .{
.base = .{
.tag = .struct_field_ptr,
.ty = ty,
.src = src,
},
.struct_ptr = struct_ptr,
.field_index = field_index,
};
try block.instructions.append(block.sema.gpa, &inst.base);
return &inst.base;
}
};
/// This is a temporary structure; references to it are valid only
/// while constructing a `zir.Code`.
pub const GenZir = struct {
pub const base_tag: Tag = .gen_zir;
base: Scope = Scope{ .tag = base_tag },
force_comptime: bool,
/// Parents can be: `GenZir`, `File`
parent: *Scope,
/// All `GenZir` scopes for the same ZIR share this.
astgen: *AstGen,
/// Keeps track of the list of instructions in this scope only. Indexes
/// to instructions in `astgen`.
instructions: ArrayListUnmanaged(zir.Inst.Index) = .{},
label: ?Label = null,
break_block: zir.Inst.Index = 0,
continue_block: zir.Inst.Index = 0,
/// Only valid when setBreakResultLoc is called.
break_result_loc: AstGen.ResultLoc = undefined,
/// When a block has a pointer result location, here it is.
rl_ptr: zir.Inst.Ref = .none,
/// When a block has a type result location, here it is.
rl_ty_inst: zir.Inst.Ref = .none,
/// Keeps track of how many branches of a block did not actually
/// consume the result location. astgen uses this to figure out
/// whether to rely on break instructions or writing to the result
/// pointer for the result instruction.
rvalue_rl_count: usize = 0,
/// Keeps track of how many break instructions there are. When astgen is finished
/// with a block, it can check this against rvalue_rl_count to find out whether
/// the break instructions should be downgraded to break_void.
break_count: usize = 0,
/// Tracks `break :foo bar` instructions so they can possibly be elided later if
/// the labeled block ends up not needing a result location pointer.
labeled_breaks: ArrayListUnmanaged(zir.Inst.Index) = .{},
/// Tracks `store_to_block_ptr` instructions that correspond to break instructions
/// so they can possibly be elided later if the labeled block ends up not needing
/// a result location pointer.
labeled_store_to_block_ptr_list: ArrayListUnmanaged(zir.Inst.Index) = .{},
pub const Label = struct {
token: ast.TokenIndex,
block_inst: zir.Inst.Index,
used: bool = false,
};
/// Only valid to call on the top of the `GenZir` stack. Completes the
/// `AstGen` into a `zir.Code`. Leaves the `AstGen` in an
/// initialized, but empty, state.
pub fn finish(gz: *GenZir) !zir.Code {
const gpa = gz.astgen.mod.gpa;
try gz.setBlockBody(0);
return zir.Code{
.instructions = gz.astgen.instructions.toOwnedSlice(),
.string_bytes = gz.astgen.string_bytes.toOwnedSlice(gpa),
.extra = gz.astgen.extra.toOwnedSlice(gpa),
};
}
pub fn tokSrcLoc(gz: GenZir, token_index: ast.TokenIndex) LazySrcLoc {
return gz.astgen.decl.tokSrcLoc(token_index);
}
pub fn nodeSrcLoc(gz: GenZir, node_index: ast.Node.Index) LazySrcLoc {
return gz.astgen.decl.nodeSrcLoc(node_index);
}
pub fn tree(gz: *const GenZir) *const ast.Tree {
return &gz.astgen.decl.container.file_scope.tree;
}
pub fn setBreakResultLoc(gz: *GenZir, parent_rl: AstGen.ResultLoc) void {
// Depending on whether the result location is a pointer or value, different
// ZIR needs to be generated. In the former case we rely on storing to the
// pointer to communicate the result, and use breakvoid; in the latter case
// the block break instructions will have the result values.
// One more complication: when the result location is a pointer, we detect
// the scenario where the result location is not consumed. In this case
// we emit ZIR for the block break instructions to have the result values,
// and then rvalue() on that to pass the value to the result location.
switch (parent_rl) {
.ty => |ty_inst| {
gz.rl_ty_inst = ty_inst;
gz.break_result_loc = parent_rl;
},
.none_or_ref => {
gz.break_result_loc = .ref;
},
.discard, .none, .ptr, .ref => {
gz.break_result_loc = parent_rl;
},
.inferred_ptr => |ptr| {
gz.rl_ptr = ptr;
gz.break_result_loc = .{ .block_ptr = gz };
},
.block_ptr => |parent_block_scope| {
gz.rl_ty_inst = parent_block_scope.rl_ty_inst;
gz.rl_ptr = parent_block_scope.rl_ptr;
gz.break_result_loc = .{ .block_ptr = gz };
},
}
}
pub fn setBoolBrBody(gz: GenZir, inst: zir.Inst.Index) !void {
const gpa = gz.astgen.mod.gpa;
try gz.astgen.extra.ensureCapacity(gpa, gz.astgen.extra.items.len +
@typeInfo(zir.Inst.Block).Struct.fields.len + gz.instructions.items.len);
const zir_datas = gz.astgen.instructions.items(.data);
zir_datas[inst].bool_br.payload_index = gz.astgen.addExtraAssumeCapacity(
zir.Inst.Block{ .body_len = @intCast(u32, gz.instructions.items.len) },
);
gz.astgen.extra.appendSliceAssumeCapacity(gz.instructions.items);
}
pub fn setBlockBody(gz: GenZir, inst: zir.Inst.Index) !void {
const gpa = gz.astgen.mod.gpa;
try gz.astgen.extra.ensureCapacity(gpa, gz.astgen.extra.items.len +
@typeInfo(zir.Inst.Block).Struct.fields.len + gz.instructions.items.len);
const zir_datas = gz.astgen.instructions.items(.data);
zir_datas[inst].pl_node.payload_index = gz.astgen.addExtraAssumeCapacity(
zir.Inst.Block{ .body_len = @intCast(u32, gz.instructions.items.len) },
);
gz.astgen.extra.appendSliceAssumeCapacity(gz.instructions.items);
}
pub fn identAsString(gz: *GenZir, ident_token: ast.TokenIndex) !u32 {
const astgen = gz.astgen;
const gpa = astgen.mod.gpa;
const string_bytes = &astgen.string_bytes;
const str_index = @intCast(u32, string_bytes.items.len);
try astgen.mod.appendIdentStr(&gz.base, ident_token, string_bytes);
try string_bytes.append(gpa, 0);
return str_index;
}
pub fn addFnTypeCc(gz: *GenZir, tag: zir.Inst.Tag, args: struct {
src_node: ast.Node.Index,
param_types: []const zir.Inst.Ref,
ret_ty: zir.Inst.Ref,
cc: zir.Inst.Ref,
}) !zir.Inst.Ref {
assert(args.src_node != 0);
assert(args.ret_ty != .none);
assert(args.cc != .none);
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
try gz.astgen.extra.ensureCapacity(gpa, gz.astgen.extra.items.len +
@typeInfo(zir.Inst.FnTypeCc).Struct.fields.len + args.param_types.len);
const payload_index = gz.astgen.addExtraAssumeCapacity(zir.Inst.FnTypeCc{
.return_type = args.ret_ty,
.cc = args.cc,
.param_types_len = @intCast(u32, args.param_types.len),
});
gz.astgen.appendRefsAssumeCapacity(args.param_types);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(args.src_node),
.payload_index = payload_index,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return gz.astgen.indexToRef(new_index);
}
pub fn addFnType(gz: *GenZir, tag: zir.Inst.Tag, args: struct {
src_node: ast.Node.Index,
ret_ty: zir.Inst.Ref,
param_types: []const zir.Inst.Ref,
}) !zir.Inst.Ref {
assert(args.src_node != 0);
assert(args.ret_ty != .none);
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
try gz.astgen.extra.ensureCapacity(gpa, gz.astgen.extra.items.len +
@typeInfo(zir.Inst.FnType).Struct.fields.len + args.param_types.len);
const payload_index = gz.astgen.addExtraAssumeCapacity(zir.Inst.FnType{
.return_type = args.ret_ty,
.param_types_len = @intCast(u32, args.param_types.len),
});
gz.astgen.appendRefsAssumeCapacity(args.param_types);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(args.src_node),
.payload_index = payload_index,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return gz.astgen.indexToRef(new_index);
}
pub fn addCall(
gz: *GenZir,
tag: zir.Inst.Tag,
callee: zir.Inst.Ref,
args: []const zir.Inst.Ref,
/// Absolute node index. This function does the conversion to offset from Decl.
src_node: ast.Node.Index,
) !zir.Inst.Ref {
assert(callee != .none);
assert(src_node != 0);
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
try gz.astgen.extra.ensureCapacity(gpa, gz.astgen.extra.items.len +
@typeInfo(zir.Inst.Call).Struct.fields.len + args.len);
const payload_index = gz.astgen.addExtraAssumeCapacity(zir.Inst.Call{
.callee = callee,
.args_len = @intCast(u32, args.len),
});
gz.astgen.appendRefsAssumeCapacity(args);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(src_node),
.payload_index = payload_index,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return gz.astgen.indexToRef(new_index);
}
/// Note that this returns a `zir.Inst.Index` not a ref.
/// Leaves the `payload_index` field undefined.
pub fn addBoolBr(
gz: *GenZir,
tag: zir.Inst.Tag,
lhs: zir.Inst.Ref,
) !zir.Inst.Index {
assert(lhs != .none);
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = tag,
.data = .{ .bool_br = .{
.lhs = lhs,
.payload_index = undefined,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return new_index;
}
pub fn addInt(gz: *GenZir, integer: u64) !zir.Inst.Ref {
return gz.add(.{
.tag = .int,
.data = .{ .int = integer },
});
}
pub fn addFloat(gz: *GenZir, number: f32, src_node: ast.Node.Index) !zir.Inst.Ref {
return gz.add(.{
.tag = .float,
.data = .{ .float = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(src_node),
.number = number,
} },
});
}
pub fn addUnNode(
gz: *GenZir,
tag: zir.Inst.Tag,
operand: zir.Inst.Ref,
/// Absolute node index. This function does the conversion to offset from Decl.
src_node: ast.Node.Index,
) !zir.Inst.Ref {
assert(operand != .none);
return gz.add(.{
.tag = tag,
.data = .{ .un_node = .{
.operand = operand,
.src_node = gz.astgen.decl.nodeIndexToRelative(src_node),
} },
});
}
pub fn addPlNode(
gz: *GenZir,
tag: zir.Inst.Tag,
/// Absolute node index. This function does the conversion to offset from Decl.
src_node: ast.Node.Index,
extra: anytype,
) !zir.Inst.Ref {
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
const payload_index = try gz.astgen.addExtra(extra);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(src_node),
.payload_index = payload_index,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return gz.astgen.indexToRef(new_index);
}
pub fn addArrayTypeSentinel(
gz: *GenZir,
len: zir.Inst.Ref,
sentinel: zir.Inst.Ref,
elem_type: zir.Inst.Ref,
) !zir.Inst.Ref {
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
const payload_index = try gz.astgen.addExtra(zir.Inst.ArrayTypeSentinel{
.sentinel = sentinel,
.elem_type = elem_type,
});
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(.{
.tag = .array_type_sentinel,
.data = .{ .array_type_sentinel = .{
.len = len,
.payload_index = payload_index,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return gz.astgen.indexToRef(new_index);
}
pub fn addUnTok(
gz: *GenZir,
tag: zir.Inst.Tag,
operand: zir.Inst.Ref,
/// Absolute token index. This function does the conversion to Decl offset.
abs_tok_index: ast.TokenIndex,
) !zir.Inst.Ref {
assert(operand != .none);
return gz.add(.{
.tag = tag,
.data = .{ .un_tok = .{
.operand = operand,
.src_tok = abs_tok_index - gz.astgen.decl.srcToken(),
} },
});
}
pub fn addStrTok(
gz: *GenZir,
tag: zir.Inst.Tag,
str_index: u32,
/// Absolute token index. This function does the conversion to Decl offset.
abs_tok_index: ast.TokenIndex,
) !zir.Inst.Ref {
return gz.add(.{
.tag = tag,
.data = .{ .str_tok = .{
.start = str_index,
.src_tok = abs_tok_index - gz.astgen.decl.srcToken(),
} },
});
}
pub fn addBreak(
gz: *GenZir,
tag: zir.Inst.Tag,
break_block: zir.Inst.Index,
operand: zir.Inst.Ref,
) !zir.Inst.Index {
return gz.addAsIndex(.{
.tag = tag,
.data = .{ .@"break" = .{
.block_inst = break_block,
.operand = operand,
} },
});
}
pub fn addBin(
gz: *GenZir,
tag: zir.Inst.Tag,
lhs: zir.Inst.Ref,
rhs: zir.Inst.Ref,
) !zir.Inst.Ref {
assert(lhs != .none);
assert(rhs != .none);
return gz.add(.{
.tag = tag,
.data = .{ .bin = .{
.lhs = lhs,
.rhs = rhs,
} },
});
}
pub fn addDecl(
gz: *GenZir,
tag: zir.Inst.Tag,
decl_index: u32,
src_node: ast.Node.Index,
) !zir.Inst.Ref {
return gz.add(.{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(src_node),
.payload_index = decl_index,
} },
});
}
pub fn addNode(
gz: *GenZir,
tag: zir.Inst.Tag,
/// Absolute node index. This function does the conversion to offset from Decl.
src_node: ast.Node.Index,
) !zir.Inst.Ref {
return gz.add(.{
.tag = tag,
.data = .{ .node = gz.astgen.decl.nodeIndexToRelative(src_node) },
});
}
/// Asserts that `str` is 8 or fewer bytes.
pub fn addSmallStr(
gz: *GenZir,
tag: zir.Inst.Tag,
str: []const u8,
) !zir.Inst.Ref {
var buf: [9]u8 = undefined;
mem.copy(u8, &buf, str);
buf[str.len] = 0;
return gz.add(.{
.tag = tag,
.data = .{ .small_str = .{ .bytes = buf[0..8].* } },
});
}
/// Note that this returns a `zir.Inst.Index` not a ref.
/// Does *not* append the block instruction to the scope.
/// Leaves the `payload_index` field undefined.
pub fn addBlock(gz: *GenZir, tag: zir.Inst.Tag, node: ast.Node.Index) !zir.Inst.Index {
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
const gpa = gz.astgen.mod.gpa;
try gz.astgen.instructions.append(gpa, .{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(node),
.payload_index = undefined,
} },
});
return new_index;
}
/// Note that this returns a `zir.Inst.Index` not a ref.
/// Leaves the `payload_index` field undefined.
pub fn addCondBr(gz: *GenZir, tag: zir.Inst.Tag, node: ast.Node.Index) !zir.Inst.Index {
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
try gz.astgen.instructions.append(gpa, .{
.tag = tag,
.data = .{ .pl_node = .{
.src_node = gz.astgen.decl.nodeIndexToRelative(node),
.payload_index = undefined,
} },
});
gz.instructions.appendAssumeCapacity(new_index);
return new_index;
}
pub fn add(gz: *GenZir, inst: zir.Inst) !zir.Inst.Ref {
return gz.astgen.indexToRef(try gz.addAsIndex(inst));
}
pub fn addAsIndex(gz: *GenZir, inst: zir.Inst) !zir.Inst.Index {
const gpa = gz.astgen.mod.gpa;
try gz.instructions.ensureCapacity(gpa, gz.instructions.items.len + 1);
try gz.astgen.instructions.ensureCapacity(gpa, gz.astgen.instructions.len + 1);
const new_index = @intCast(zir.Inst.Index, gz.astgen.instructions.len);
gz.astgen.instructions.appendAssumeCapacity(inst);
gz.instructions.appendAssumeCapacity(new_index);
return new_index;
}
};
/// This is always a `const` local and importantly the `inst` is a value type, not a pointer.
/// This structure lives as long as the AST generation of the Block
/// node that contains the variable.
pub const LocalVal = struct {
pub const base_tag: Tag = .local_val;
base: Scope = Scope{ .tag = base_tag },
/// Parents can be: `LocalVal`, `LocalPtr`, `GenZir`.
parent: *Scope,
gen_zir: *GenZir,
name: []const u8,
inst: zir.Inst.Ref,
/// Source location of the corresponding variable declaration.
src: LazySrcLoc,
};
/// This could be a `const` or `var` local. It has a pointer instead of a value.
/// This structure lives as long as the AST generation of the Block
/// node that contains the variable.
pub const LocalPtr = struct {
pub const base_tag: Tag = .local_ptr;
base: Scope = Scope{ .tag = base_tag },
/// Parents can be: `LocalVal`, `LocalPtr`, `GenZir`.
parent: *Scope,
gen_zir: *GenZir,
name: []const u8,
ptr: zir.Inst.Ref,
/// Source location of the corresponding variable declaration.
src: LazySrcLoc,
};
pub const DeclRef = struct {
pub const base_tag: Tag = .decl_ref;
base: Scope = Scope{ .tag = base_tag },
decl: *Decl,
};
};
/// This struct holds data necessary to construct API-facing `AllErrors.Message`.
/// Its memory is managed with the general purpose allocator so that they
/// can be created and destroyed in response to incremental updates.
/// In some cases, the Scope.File could have been inferred from where the ErrorMsg
/// is stored. For example, if it is stored in Module.failed_decls, then the Scope.File
/// would be determined by the Decl Scope. However, the data structure contains the field
/// anyway so that `ErrorMsg` can be reused for error notes, which may be in a different
/// file than the parent error message. It also simplifies processing of error messages.
pub const ErrorMsg = struct {
src_loc: SrcLoc,
msg: []const u8,
notes: []ErrorMsg = &.{},
pub fn create(
gpa: *Allocator,
src_loc: SrcLoc,
comptime format: []const u8,
args: anytype,
) !*ErrorMsg {
const err_msg = try gpa.create(ErrorMsg);
errdefer gpa.destroy(err_msg);
err_msg.* = try init(gpa, src_loc, format, args);
return err_msg;
}
/// Assumes the ErrorMsg struct and msg were both allocated with `gpa`,
/// as well as all notes.
pub fn destroy(err_msg: *ErrorMsg, gpa: *Allocator) void {
err_msg.deinit(gpa);
gpa.destroy(err_msg);
}
pub fn init(
gpa: *Allocator,
src_loc: SrcLoc,
comptime format: []const u8,
args: anytype,
) !ErrorMsg {
return ErrorMsg{
.src_loc = src_loc,
.msg = try std.fmt.allocPrint(gpa, format, args),
};
}
pub fn deinit(err_msg: *ErrorMsg, gpa: *Allocator) void {
for (err_msg.notes) |*note| {
note.deinit(gpa);
}
gpa.free(err_msg.notes);
gpa.free(err_msg.msg);
err_msg.* = undefined;
}
};
/// Canonical reference to a position within a source file.
pub const SrcLoc = struct {
/// The active field is determined by tag of `lazy`.
container: union {
/// The containing `Decl` according to the source code.
decl: *Decl,
file_scope: *Scope.File,
},
/// Relative to `decl`.
lazy: LazySrcLoc,
pub fn fileScope(src_loc: SrcLoc) *Scope.File {
return switch (src_loc.lazy) {
.unneeded => unreachable,
.byte_abs,
.token_abs,
.node_abs,
=> src_loc.container.file_scope,
.byte_offset,
.token_offset,
.node_offset,
.node_offset_back2tok,
.node_offset_var_decl_ty,
.node_offset_for_cond,
.node_offset_builtin_call_arg0,
.node_offset_builtin_call_arg1,
.node_offset_array_access_index,
.node_offset_slice_sentinel,
.node_offset_call_func,
.node_offset_field_name,
.node_offset_deref_ptr,
.node_offset_asm_source,
.node_offset_asm_ret_ty,
.node_offset_if_cond,
.node_offset_bin_op,
.node_offset_bin_lhs,
.node_offset_bin_rhs,
.node_offset_switch_operand,
.node_offset_switch_special_prong,
.node_offset_switch_range,
.node_offset_fn_type_cc,
.node_offset_fn_type_ret_ty,
=> src_loc.container.decl.container.file_scope,
};
}
pub fn byteOffset(src_loc: SrcLoc) !u32 {
switch (src_loc.lazy) {
.unneeded => unreachable,
.byte_abs => |byte_index| return byte_index,
.token_abs => |tok_index| {
const tree = src_loc.container.file_scope.base.tree();
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_abs => |node| {
const tree = src_loc.container.file_scope.base.tree();
const token_starts = tree.tokens.items(.start);
const tok_index = tree.firstToken(node);
return token_starts[tok_index];
},
.byte_offset => |byte_off| {
const decl = src_loc.container.decl;
return decl.srcByteOffset() + byte_off;
},
.token_offset => |tok_off| {
const decl = src_loc.container.decl;
const tok_index = decl.srcToken() + tok_off;
const tree = decl.container.file_scope.base.tree();
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset, .node_offset_bin_op => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_back2tok => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const tok_index = tree.firstToken(node) - 2;
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_var_decl_ty => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_tags = tree.nodes.items(.tag);
const full = switch (node_tags[node]) {
.global_var_decl => tree.globalVarDecl(node),
.local_var_decl => tree.localVarDecl(node),
.simple_var_decl => tree.simpleVarDecl(node),
.aligned_var_decl => tree.alignedVarDecl(node),
else => unreachable,
};
const tok_index = if (full.ast.type_node != 0) blk: {
const main_tokens = tree.nodes.items(.main_token);
break :blk main_tokens[full.ast.type_node];
} else blk: {
break :blk full.ast.mut_token + 1; // the name token
};
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_builtin_call_arg0 => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const param = switch (node_tags[node]) {
.builtin_call_two, .builtin_call_two_comma => node_datas[node].lhs,
.builtin_call, .builtin_call_comma => tree.extra_data[node_datas[node].lhs],
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[param];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_builtin_call_arg1 => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const param = switch (node_tags[node]) {
.builtin_call_two, .builtin_call_two_comma => node_datas[node].rhs,
.builtin_call, .builtin_call_comma => tree.extra_data[node_datas[node].lhs + 1],
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[param];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_array_access_index => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[node_datas[node].rhs];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_slice_sentinel => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const full = switch (node_tags[node]) {
.slice_open => tree.sliceOpen(node),
.slice => tree.slice(node),
.slice_sentinel => tree.sliceSentinel(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.ast.sentinel];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_call_func => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
var params: [1]ast.Node.Index = undefined;
const full = switch (node_tags[node]) {
.call_one,
.call_one_comma,
.async_call_one,
.async_call_one_comma,
=> tree.callOne(¶ms, node),
.call,
.call_comma,
.async_call,
.async_call_comma,
=> tree.callFull(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.ast.fn_expr];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_field_name => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const tok_index = switch (node_tags[node]) {
.field_access => node_datas[node].rhs,
else => tree.firstToken(node) - 2,
};
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_deref_ptr => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const tok_index = node_datas[node].lhs;
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_asm_source => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const full = switch (node_tags[node]) {
.asm_simple => tree.asmSimple(node),
.@"asm" => tree.asmFull(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.ast.template];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_asm_ret_ty => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
const full = switch (node_tags[node]) {
.asm_simple => tree.asmSimple(node),
.@"asm" => tree.asmFull(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.outputs[0]];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_for_cond, .node_offset_if_cond => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_tags = tree.nodes.items(.tag);
const src_node = switch (node_tags[node]) {
.if_simple => tree.ifSimple(node).ast.cond_expr,
.@"if" => tree.ifFull(node).ast.cond_expr,
.while_simple => tree.whileSimple(node).ast.cond_expr,
.while_cont => tree.whileCont(node).ast.cond_expr,
.@"while" => tree.whileFull(node).ast.cond_expr,
.for_simple => tree.forSimple(node).ast.cond_expr,
.@"for" => tree.forFull(node).ast.cond_expr,
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[src_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_bin_lhs => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const src_node = node_datas[node].lhs;
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[src_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_bin_rhs => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const src_node = node_datas[node].rhs;
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[src_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_switch_operand => |node_off| {
const decl = src_loc.container.decl;
const node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const src_node = node_datas[node].lhs;
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[src_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_switch_special_prong => |node_off| {
const decl = src_loc.container.decl;
const switch_node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const extra = tree.extraData(node_datas[switch_node].rhs, ast.Node.SubRange);
const case_nodes = tree.extra_data[extra.start..extra.end];
for (case_nodes) |case_node| {
const case = switch (node_tags[case_node]) {
.switch_case_one => tree.switchCaseOne(case_node),
.switch_case => tree.switchCase(case_node),
else => unreachable,
};
const is_special = (case.ast.values.len == 0) or
(case.ast.values.len == 1 and
node_tags[case.ast.values[0]] == .identifier and
mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_"));
if (!is_special) continue;
const tok_index = main_tokens[case_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
} else unreachable;
},
.node_offset_switch_range => |node_off| {
const decl = src_loc.container.decl;
const switch_node = decl.relativeToNodeIndex(node_off);
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const extra = tree.extraData(node_datas[switch_node].rhs, ast.Node.SubRange);
const case_nodes = tree.extra_data[extra.start..extra.end];
for (case_nodes) |case_node| {
const case = switch (node_tags[case_node]) {
.switch_case_one => tree.switchCaseOne(case_node),
.switch_case => tree.switchCase(case_node),
else => unreachable,
};
const is_special = (case.ast.values.len == 0) or
(case.ast.values.len == 1 and
node_tags[case.ast.values[0]] == .identifier and
mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_"));
if (is_special) continue;
for (case.ast.values) |item_node| {
if (node_tags[item_node] == .switch_range) {
const tok_index = main_tokens[item_node];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
}
}
} else unreachable;
},
.node_offset_fn_type_cc => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
var params: [1]ast.Node.Index = undefined;
const full = switch (node_tags[node]) {
.fn_proto_simple => tree.fnProtoSimple(¶ms, node),
.fn_proto_multi => tree.fnProtoMulti(node),
.fn_proto_one => tree.fnProtoOne(¶ms, node),
.fn_proto => tree.fnProto(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.ast.callconv_expr];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
.node_offset_fn_type_ret_ty => |node_off| {
const decl = src_loc.container.decl;
const tree = decl.container.file_scope.base.tree();
const node_datas = tree.nodes.items(.data);
const node_tags = tree.nodes.items(.tag);
const node = decl.relativeToNodeIndex(node_off);
var params: [1]ast.Node.Index = undefined;
const full = switch (node_tags[node]) {
.fn_proto_simple => tree.fnProtoSimple(¶ms, node),
.fn_proto_multi => tree.fnProtoMulti(node),
.fn_proto_one => tree.fnProtoOne(¶ms, node),
.fn_proto => tree.fnProto(node),
else => unreachable,
};
const main_tokens = tree.nodes.items(.main_token);
const tok_index = main_tokens[full.ast.return_type];
const token_starts = tree.tokens.items(.start);
return token_starts[tok_index];
},
}
}
};
/// Resolving a source location into a byte offset may require doing work
/// that we would rather not do unless the error actually occurs.
/// Therefore we need a data structure that contains the information necessary
/// to lazily produce a `SrcLoc` as required.
/// Most of the offsets in this data structure are relative to the containing Decl.
/// This makes the source location resolve properly even when a Decl gets
/// shifted up or down in the file, as long as the Decl's contents itself
/// do not change.
pub const LazySrcLoc = union(enum) {
/// When this tag is set, the code that constructed this `LazySrcLoc` is asserting
/// that all code paths which would need to resolve the source location are
/// unreachable. If you are debugging this tag incorrectly being this value,
/// look into using reverse-continue with a memory watchpoint to see where the
/// value is being set to this tag.
unneeded,
/// The source location points to a byte offset within a source file,
/// offset from 0. The source file is determined contextually.
/// Inside a `SrcLoc`, the `file_scope` union field will be active.
byte_abs: u32,
/// The source location points to a token within a source file,
/// offset from 0. The source file is determined contextually.
/// Inside a `SrcLoc`, the `file_scope` union field will be active.
token_abs: u32,
/// The source location points to an AST node within a source file,
/// offset from 0. The source file is determined contextually.
/// Inside a `SrcLoc`, the `file_scope` union field will be active.
node_abs: u32,
/// The source location points to a byte offset within a source file,
/// offset from the byte offset of the Decl within the file.
/// The Decl is determined contextually.
byte_offset: u32,
/// This data is the offset into the token list from the Decl token.
/// The Decl is determined contextually.
token_offset: u32,
/// The source location points to an AST node, which is this value offset
/// from its containing Decl node AST index.
/// The Decl is determined contextually.
node_offset: i32,
/// The source location points to two tokens left of the first token of an AST node,
/// which is this value offset from its containing Decl node AST index.
/// The Decl is determined contextually.
node_offset_back2tok: i32,
/// The source location points to a variable declaration type expression,
/// found by taking this AST node index offset from the containing
/// Decl AST node, which points to a variable declaration AST node. Next, navigate
/// to the type expression.
/// The Decl is determined contextually.
node_offset_var_decl_ty: i32,
/// The source location points to a for loop condition expression,
/// found by taking this AST node index offset from the containing
/// Decl AST node, which points to a for loop AST node. Next, navigate
/// to the condition expression.
/// The Decl is determined contextually.
node_offset_for_cond: i32,
/// The source location points to the first parameter of a builtin
/// function call, found by taking this AST node index offset from the containing
/// Decl AST node, which points to a builtin call AST node. Next, navigate
/// to the first parameter.
/// The Decl is determined contextually.
node_offset_builtin_call_arg0: i32,
/// Same as `node_offset_builtin_call_arg0` except arg index 1.
node_offset_builtin_call_arg1: i32,
/// The source location points to the index expression of an array access
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to an array access AST node. Next, navigate
/// to the index expression.
/// The Decl is determined contextually.
node_offset_array_access_index: i32,
/// The source location points to the sentinel expression of a slice
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to a slice AST node. Next, navigate
/// to the sentinel expression.
/// The Decl is determined contextually.
node_offset_slice_sentinel: i32,
/// The source location points to the callee expression of a function
/// call expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to a function call AST node. Next, navigate
/// to the callee expression.
/// The Decl is determined contextually.
node_offset_call_func: i32,
/// The payload is offset from the containing Decl AST node.
/// The source location points to the field name of:
/// * a field access expression (`a.b`), or
/// * the operand ("b" node) of a field initialization expression (`.a = b`)
/// The Decl is determined contextually.
node_offset_field_name: i32,
/// The source location points to the pointer of a pointer deref expression,
/// found by taking this AST node index offset from the containing
/// Decl AST node, which points to a pointer deref AST node. Next, navigate
/// to the pointer expression.
/// The Decl is determined contextually.
node_offset_deref_ptr: i32,
/// The source location points to the assembly source code of an inline assembly
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to inline assembly AST node. Next, navigate
/// to the asm template source code.
/// The Decl is determined contextually.
node_offset_asm_source: i32,
/// The source location points to the return type of an inline assembly
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to inline assembly AST node. Next, navigate
/// to the return type expression.
/// The Decl is determined contextually.
node_offset_asm_ret_ty: i32,
/// The source location points to the condition expression of an if
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to an if expression AST node. Next, navigate
/// to the condition expression.
/// The Decl is determined contextually.
node_offset_if_cond: i32,
/// The source location points to a binary expression, such as `a + b`, found
/// by taking this AST node index offset from the containing Decl AST node.
/// The Decl is determined contextually.
node_offset_bin_op: i32,
/// The source location points to the LHS of a binary expression, found
/// by taking this AST node index offset from the containing Decl AST node,
/// which points to a binary expression AST node. Next, nagivate to the LHS.
/// The Decl is determined contextually.
node_offset_bin_lhs: i32,
/// The source location points to the RHS of a binary expression, found
/// by taking this AST node index offset from the containing Decl AST node,
/// which points to a binary expression AST node. Next, nagivate to the RHS.
/// The Decl is determined contextually.
node_offset_bin_rhs: i32,
/// The source location points to the operand of a switch expression, found
/// by taking this AST node index offset from the containing Decl AST node,
/// which points to a switch expression AST node. Next, nagivate to the operand.
/// The Decl is determined contextually.
node_offset_switch_operand: i32,
/// The source location points to the else/`_` prong of a switch expression, found
/// by taking this AST node index offset from the containing Decl AST node,
/// which points to a switch expression AST node. Next, nagivate to the else/`_` prong.
/// The Decl is determined contextually.
node_offset_switch_special_prong: i32,
/// The source location points to all the ranges of a switch expression, found
/// by taking this AST node index offset from the containing Decl AST node,
/// which points to a switch expression AST node. Next, nagivate to any of the
/// range nodes. The error applies to all of them.
/// The Decl is determined contextually.
node_offset_switch_range: i32,
/// The source location points to the calling convention of a function type
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to a function type AST node. Next, nagivate to
/// the calling convention node.
/// The Decl is determined contextually.
node_offset_fn_type_cc: i32,
/// The source location points to the return type of a function type
/// expression, found by taking this AST node index offset from the containing
/// Decl AST node, which points to a function type AST node. Next, nagivate to
/// the return type node.
/// The Decl is determined contextually.
node_offset_fn_type_ret_ty: i32,
/// Upgrade to a `SrcLoc` based on the `Decl` or file in the provided scope.
pub fn toSrcLoc(lazy: LazySrcLoc, scope: *Scope) SrcLoc {
return switch (lazy) {
.unneeded,
.byte_abs,
.token_abs,
.node_abs,
=> .{
.container = .{ .file_scope = scope.getFileScope() },
.lazy = lazy,
},
.byte_offset,
.token_offset,
.node_offset,
.node_offset_back2tok,
.node_offset_var_decl_ty,
.node_offset_for_cond,
.node_offset_builtin_call_arg0,
.node_offset_builtin_call_arg1,
.node_offset_array_access_index,
.node_offset_slice_sentinel,
.node_offset_call_func,
.node_offset_field_name,
.node_offset_deref_ptr,
.node_offset_asm_source,
.node_offset_asm_ret_ty,
.node_offset_if_cond,
.node_offset_bin_op,
.node_offset_bin_lhs,
.node_offset_bin_rhs,
.node_offset_switch_operand,
.node_offset_switch_special_prong,
.node_offset_switch_range,
.node_offset_fn_type_cc,
.node_offset_fn_type_ret_ty,
=> .{
.container = .{ .decl = scope.srcDecl().? },
.lazy = lazy,
},
};
}
/// Upgrade to a `SrcLoc` based on the `Decl` provided.
pub fn toSrcLocWithDecl(lazy: LazySrcLoc, decl: *Decl) SrcLoc {
return switch (lazy) {
.unneeded,
.byte_abs,
.token_abs,
.node_abs,
=> .{
.container = .{ .file_scope = decl.getFileScope() },
.lazy = lazy,
},
.byte_offset,
.token_offset,
.node_offset,
.node_offset_back2tok,
.node_offset_var_decl_ty,
.node_offset_for_cond,
.node_offset_builtin_call_arg0,
.node_offset_builtin_call_arg1,
.node_offset_array_access_index,
.node_offset_slice_sentinel,
.node_offset_call_func,
.node_offset_field_name,
.node_offset_deref_ptr,
.node_offset_asm_source,
.node_offset_asm_ret_ty,
.node_offset_if_cond,
.node_offset_bin_op,
.node_offset_bin_lhs,
.node_offset_bin_rhs,
.node_offset_switch_operand,
.node_offset_switch_special_prong,
.node_offset_switch_range,
.node_offset_fn_type_cc,
.node_offset_fn_type_ret_ty,
=> .{
.container = .{ .decl = decl },
.lazy = lazy,
},
};
}
};
pub const InnerError = error{ OutOfMemory, AnalysisFail };
pub fn deinit(mod: *Module) void {
const gpa = mod.gpa;
// The callsite of `Compilation.create` owns the `root_pkg`, however
// Module owns the builtin and std packages that it adds.
if (mod.root_pkg.table.remove("builtin")) |entry| {
gpa.free(entry.key);
entry.value.destroy(gpa);
}
if (mod.root_pkg.table.remove("std")) |entry| {
gpa.free(entry.key);
entry.value.destroy(gpa);
}
if (mod.root_pkg.table.remove("root")) |entry| {
gpa.free(entry.key);
}
mod.compile_log_text.deinit(gpa);
mod.zig_cache_artifact_directory.handle.close();
mod.deletion_set.deinit(gpa);
for (mod.decl_table.items()) |entry| {
entry.value.destroy(mod);
}
mod.decl_table.deinit(gpa);
for (mod.failed_decls.items()) |entry| {
entry.value.destroy(gpa);
}
mod.failed_decls.deinit(gpa);
for (mod.emit_h_failed_decls.items()) |entry| {
entry.value.destroy(gpa);
}
mod.emit_h_failed_decls.deinit(gpa);
for (mod.failed_files.items()) |entry| {
entry.value.destroy(gpa);
}
mod.failed_files.deinit(gpa);
for (mod.failed_exports.items()) |entry| {
entry.value.destroy(gpa);
}
mod.failed_exports.deinit(gpa);
mod.compile_log_decls.deinit(gpa);
for (mod.decl_exports.items()) |entry| {
const export_list = entry.value;
gpa.free(export_list);
}
mod.decl_exports.deinit(gpa);
for (mod.export_owners.items()) |entry| {
freeExportList(gpa, entry.value);
}
mod.export_owners.deinit(gpa);
mod.symbol_exports.deinit(gpa);
mod.root_scope.destroy(gpa);
var it = mod.global_error_set.iterator();
while (it.next()) |entry| {
gpa.free(entry.key);
}
mod.global_error_set.deinit(gpa);
mod.error_name_list.deinit(gpa);
for (mod.import_table.items()) |entry| {
entry.value.destroy(gpa);
}
mod.import_table.deinit(gpa);
}
fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
for (export_list) |exp| {
gpa.free(exp.options.name);
gpa.destroy(exp);
}
gpa.free(export_list);
}
pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void {
const tracy = trace(@src());
defer tracy.end();
const subsequent_analysis = switch (decl.analysis) {
.in_progress => unreachable,
.sema_failure,
.sema_failure_retryable,
.codegen_failure,
.dependency_failure,
.codegen_failure_retryable,
=> return error.AnalysisFail,
.complete => return,
.outdated => blk: {
log.debug("re-analyzing {s}", .{decl.name});
// The exports this Decl performs will be re-discovered, so we remove them here
// prior to re-analysis.
mod.deleteDeclExports(decl);
// Dependencies will be re-discovered, so we remove them here prior to re-analysis.
for (decl.dependencies.items()) |entry| {
const dep = entry.key;
dep.removeDependant(decl);
if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
// We don't perform a deletion here, because this Decl or another one
// may end up referencing it before the update is complete.
dep.deletion_flag = true;
try mod.deletion_set.put(mod.gpa, dep, {});
}
}
decl.dependencies.clearRetainingCapacity();
break :blk true;
},
.unreferenced => false,
};
const type_changed = mod.astgenAndSemaDecl(decl) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.AnalysisFail => return error.AnalysisFail,
else => {
decl.analysis = .sema_failure_retryable;
try mod.failed_decls.ensureCapacity(mod.gpa, mod.failed_decls.items().len + 1);
mod.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
mod.gpa,
decl.srcLoc(),
"unable to analyze: {s}",
.{@errorName(err)},
));
return error.AnalysisFail;
},
};
if (subsequent_analysis) {
// We may need to chase the dependants and re-analyze them.
// However, if the decl is a function, and the type is the same, we do not need to.
if (type_changed or decl.typed_value.most_recent.typed_value.val.tag() != .function) {
for (decl.dependants.items()) |entry| {
const dep = entry.key;
switch (dep.analysis) {
.unreferenced => unreachable,
.in_progress => unreachable,
.outdated => continue, // already queued for update
.dependency_failure,
.sema_failure,
.sema_failure_retryable,
.codegen_failure,
.codegen_failure_retryable,
.complete,
=> if (dep.generation != mod.generation) {
try mod.markOutdatedDecl(dep);
},
}
}
}
}
}
/// Returns `true` if the Decl type changed.
/// Returns `true` if this is the first time analyzing the Decl.
/// Returns `false` otherwise.
fn astgenAndSemaDecl(mod: *Module, decl: *Decl) !bool {
const tracy = trace(@src());
defer tracy.end();
const tree = try mod.getAstTree(decl.container.file_scope);
const node_tags = tree.nodes.items(.tag);
const node_datas = tree.nodes.items(.data);
const decl_node = decl.src_node;
switch (node_tags[decl_node]) {
.fn_decl => {
const fn_proto = node_datas[decl_node].lhs;
const body = node_datas[decl_node].rhs;
switch (node_tags[fn_proto]) {
.fn_proto_simple => {
var params: [1]ast.Node.Index = undefined;
return mod.astgenAndSemaFn(decl, tree.*, body, tree.fnProtoSimple(¶ms, fn_proto));
},
.fn_proto_multi => return mod.astgenAndSemaFn(decl, tree.*, body, tree.fnProtoMulti(fn_proto)),
.fn_proto_one => {
var params: [1]ast.Node.Index = undefined;
return mod.astgenAndSemaFn(decl, tree.*, body, tree.fnProtoOne(¶ms, fn_proto));
},
.fn_proto => return mod.astgenAndSemaFn(decl, tree.*, body, tree.fnProto(fn_proto)),
else => unreachable,
}
},
.fn_proto_simple => {
var params: [1]ast.Node.Index = undefined;
return mod.astgenAndSemaFn(decl, tree.*, 0, tree.fnProtoSimple(¶ms, decl_node));
},
.fn_proto_multi => return mod.astgenAndSemaFn(decl, tree.*, 0, tree.fnProtoMulti(decl_node)),
.fn_proto_one => {
var params: [1]ast.Node.Index = undefined;
return mod.astgenAndSemaFn(decl, tree.*, 0, tree.fnProtoOne(¶ms, decl_node));
},
.fn_proto => return mod.astgenAndSemaFn(decl, tree.*, 0, tree.fnProto(decl_node)),
.global_var_decl => return mod.astgenAndSemaVarDecl(decl, tree.*, tree.globalVarDecl(decl_node)),
.local_var_decl => return mod.astgenAndSemaVarDecl(decl, tree.*, tree.localVarDecl(decl_node)),
.simple_var_decl => return mod.astgenAndSemaVarDecl(decl, tree.*, tree.simpleVarDecl(decl_node)),
.aligned_var_decl => return mod.astgenAndSemaVarDecl(decl, tree.*, tree.alignedVarDecl(decl_node)),
.@"comptime" => {
decl.analysis = .in_progress;
// A comptime decl does not store any value so we can just deinit this arena after analysis is done.
var analysis_arena = std.heap.ArenaAllocator.init(mod.gpa);
defer analysis_arena.deinit();
var code: zir.Code = blk: {
var astgen = try AstGen.init(mod, decl, &analysis_arena.allocator);
defer astgen.deinit();
var gen_scope: Scope.GenZir = .{
.force_comptime = true,
.parent = &decl.container.base,
.astgen = &astgen,
};
defer gen_scope.instructions.deinit(mod.gpa);
const block_expr = node_datas[decl_node].lhs;
_ = try AstGen.comptimeExpr(&gen_scope, &gen_scope.base, .none, block_expr);
_ = try gen_scope.addBreak(.break_inline, 0, .void_value);
const code = try gen_scope.finish();
if (std.builtin.mode == .Debug and mod.comp.verbose_ir) {
code.dump(mod.gpa, "comptime_block", &gen_scope.base, 0) catch {};
}
break :blk code;
};
defer code.deinit(mod.gpa);
var sema: Sema = .{
.mod = mod,
.gpa = mod.gpa,
.arena = &analysis_arena.allocator,
.code = code,
.inst_map = try analysis_arena.allocator.alloc(*ir.Inst, code.instructions.len),
.owner_decl = decl,
.func = null,
.owner_func = null,
.param_inst_list = &.{},
};
var block_scope: Scope.Block = .{
.parent = null,
.sema = &sema,
.src_decl = decl,
.instructions = .{},
.inlining = null,
.is_comptime = true,
};
defer block_scope.instructions.deinit(mod.gpa);
_ = try sema.root(&block_scope);
decl.analysis = .complete;
decl.generation = mod.generation;
return true;
},
.@"usingnamespace" => @panic("TODO usingnamespace decl"),
else => unreachable,
}
}
fn astgenAndSemaFn(
mod: *Module,
decl: *Decl,
tree: ast.Tree,
body_node: ast.Node.Index,
fn_proto: ast.full.FnProto,
) !bool {
const tracy = trace(@src());
defer tracy.end();
decl.analysis = .in_progress;
const token_tags = tree.tokens.items(.tag);
// This arena allocator's memory is discarded at the end of this function. It is used
// to determine the type of the function, and hence the type of the decl, which is needed
// to complete the Decl analysis.
var fn_type_scope_arena = std.heap.ArenaAllocator.init(mod.gpa);
defer fn_type_scope_arena.deinit();
var fn_type_astgen = try AstGen.init(mod, decl, &fn_type_scope_arena.allocator);
defer fn_type_astgen.deinit();
var fn_type_scope: Scope.GenZir = .{
.force_comptime = true,
.parent = &decl.container.base,
.astgen = &fn_type_astgen,
};
defer fn_type_scope.instructions.deinit(mod.gpa);
decl.is_pub = fn_proto.visib_token != null;
// The AST params array does not contain anytype and ... parameters.
// We must iterate to count how many param types to allocate.
const param_count = blk: {
var count: usize = 0;
var it = fn_proto.iterate(tree);
while (it.next()) |param| {
if (param.anytype_ellipsis3) |some| if (token_tags[some] == .ellipsis3) break;
count += 1;
}
break :blk count;
};
const param_types = try fn_type_scope_arena.allocator.alloc(zir.Inst.Ref, param_count);
var is_var_args = false;
{
var param_type_i: usize = 0;
var it = fn_proto.iterate(tree);
while (it.next()) |param| : (param_type_i += 1) {
if (param.anytype_ellipsis3) |token| {
switch (token_tags[token]) {
.keyword_anytype => return mod.failTok(
&fn_type_scope.base,
token,
"TODO implement anytype parameter",
.{},
),
.ellipsis3 => {
is_var_args = true;
break;
},
else => unreachable,
}
}
const param_type_node = param.type_expr;
assert(param_type_node != 0);
param_types[param_type_i] =
try AstGen.expr(&fn_type_scope, &fn_type_scope.base, .{ .ty = .type_type }, param_type_node);
}
assert(param_type_i == param_count);
}
if (fn_proto.lib_name) |lib_name_token| blk: {
// TODO call std.zig.parseStringLiteral
const lib_name_str = mem.trim(u8, tree.tokenSlice(lib_name_token), "\"");
log.debug("extern fn symbol expected in lib '{s}'", .{lib_name_str});
const target = mod.comp.getTarget();
if (target_util.is_libc_lib_name(target, lib_name_str)) {
if (!mod.comp.bin_file.options.link_libc) {
return mod.failTok(
&fn_type_scope.base,
lib_name_token,
"dependency on libc must be explicitly specified in the build command",
.{},
);
}
break :blk;
}
if (target_util.is_libcpp_lib_name(target, lib_name_str)) {
if (!mod.comp.bin_file.options.link_libcpp) {
return mod.failTok(
&fn_type_scope.base,
lib_name_token,
"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.failTok(
&fn_type_scope.base,
lib_name_token,
"dependency on dynamic library '{s}' requires enabling Position Independent Code. Fixed by `-l{s}` or `-fPIC`.",
.{ lib_name_str, lib_name_str },
);
}
mod.comp.stage1AddLinkLib(lib_name_str) catch |err| {
return mod.failTok(
&fn_type_scope.base,
lib_name_token,
"unable to add link lib '{s}': {s}",
.{ lib_name_str, @errorName(err) },
);
};
}
if (fn_proto.ast.align_expr != 0) {
return mod.failNode(
&fn_type_scope.base,
fn_proto.ast.align_expr,
"TODO implement function align expression",
.{},
);
}
if (fn_proto.ast.section_expr != 0) {
return mod.failNode(
&fn_type_scope.base,
fn_proto.ast.section_expr,
"TODO implement function section expression",
.{},
);
}
const maybe_bang = tree.firstToken(fn_proto.ast.return_type) - 1;
if (token_tags[maybe_bang] == .bang) {
return mod.failTok(&fn_type_scope.base, maybe_bang, "TODO implement inferred error sets", .{});
}
const return_type_inst = try AstGen.expr(
&fn_type_scope,
&fn_type_scope.base,
.{ .ty = .type_type },
fn_proto.ast.return_type,
);
const is_extern = if (fn_proto.extern_export_token) |maybe_export_token|
token_tags[maybe_export_token] == .keyword_extern
else
false;
const cc: zir.Inst.Ref = if (fn_proto.ast.callconv_expr != 0)
// TODO instead of enum literal type, this needs to be the
// std.builtin.CallingConvention enum. We need to implement importing other files
// and enums in order to fix this.
try AstGen.comptimeExpr(
&fn_type_scope,
&fn_type_scope.base,
.{ .ty = .enum_literal_type },
fn_proto.ast.callconv_expr,
)
else if (is_extern) // note: https://github.com/ziglang/zig/issues/5269
try fn_type_scope.addSmallStr(.enum_literal_small, "C")
else
.none;
const fn_type_inst: zir.Inst.Ref = if (cc != .none) fn_type: {
const tag: zir.Inst.Tag = if (is_var_args) .fn_type_cc_var_args else .fn_type_cc;
break :fn_type try fn_type_scope.addFnTypeCc(tag, .{
.src_node = fn_proto.ast.proto_node,
.ret_ty = return_type_inst,
.param_types = param_types,
.cc = cc,
});
} else fn_type: {
const tag: zir.Inst.Tag = if (is_var_args) .fn_type_var_args else .fn_type;
break :fn_type try fn_type_scope.addFnType(tag, .{
.src_node = fn_proto.ast.proto_node,
.ret_ty = return_type_inst,
.param_types = param_types,
});
};
_ = try fn_type_scope.addBreak(.break_inline, 0, fn_type_inst);
// We need the memory for the Type to go into the arena for the Decl
var decl_arena = std.heap.ArenaAllocator.init(mod.gpa);
errdefer decl_arena.deinit();
const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
var fn_type_code = try fn_type_scope.finish();
defer fn_type_code.deinit(mod.gpa);
if (std.builtin.mode == .Debug and mod.comp.verbose_ir) {
fn_type_code.dump(mod.gpa, "fn_type", &fn_type_scope.base, 0) catch {};
}
var fn_type_sema: Sema = .{
.mod = mod,
.gpa = mod.gpa,
.arena = &decl_arena.allocator,
.code = fn_type_code,
.inst_map = try fn_type_scope_arena.allocator.alloc(*ir.Inst, fn_type_code.instructions.len),
.owner_decl = decl,
.func = null,
.owner_func = null,
.param_inst_list = &.{},
};
var block_scope: Scope.Block = .{
.parent = null,
.sema = &fn_type_sema,
.src_decl = decl,
.instructions = .{},
.inlining = null,
.is_comptime = true,
};
defer block_scope.instructions.deinit(mod.gpa);
const fn_type = try fn_type_sema.rootAsType(&block_scope);
if (body_node == 0) {
if (!is_extern) {
return mod.failNode(&block_scope.base, fn_proto.ast.fn_token, "non-extern function has no body", .{});
}
// Extern function.
var type_changed = true;
if (decl.typedValueManaged()) |tvm| {
type_changed = !tvm.typed_value.ty.eql(fn_type);
tvm.deinit(mod.gpa);
}
const fn_val = try Value.Tag.extern_fn.create(&decl_arena.allocator, decl);
decl_arena_state.* = decl_arena.state;
decl.typed_value = .{
.most_recent = .{
.typed_value = .{ .ty = fn_type, .val = fn_val },
.arena = decl_arena_state,
},
};
decl.analysis = .complete;
decl.generation = mod.generation;
try mod.comp.bin_file.allocateDeclIndexes(decl);
try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl });
if (type_changed and mod.emit_h != null) {
try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
}
return type_changed;
}
if (fn_type.fnIsVarArgs()) {
return mod.failNode(&block_scope.base, fn_proto.ast.fn_token, "non-extern function is variadic", .{});
}
const new_func = try decl_arena.allocator.create(Fn);
const fn_payload = try decl_arena.allocator.create(Value.Payload.Function);
const fn_zir: zir.Code = blk: {
// We put the ZIR inside the Decl arena.
var astgen = try AstGen.init(mod, decl, &decl_arena.allocator);
astgen.ref_start_index = @intCast(u32, zir.Inst.Ref.typed_value_map.len + param_count);
defer astgen.deinit();
var gen_scope: Scope.GenZir = .{
.force_comptime = false,
.parent = &decl.container.base,
.astgen = &astgen,
};
defer gen_scope.instructions.deinit(mod.gpa);
// Iterate over the parameters. We put the param names as the first N
// items inside `extra` so that debug info later can refer to the parameter names
// even while the respective source code is unloaded.
try astgen.extra.ensureCapacity(mod.gpa, param_count);
var params_scope = &gen_scope.base;
var i: usize = 0;
var it = fn_proto.iterate(tree);
while (it.next()) |param| : (i += 1) {
const name_token = param.name_token.?;
const param_name = try mod.identifierTokenString(&gen_scope.base, name_token);
const sub_scope = try decl_arena.allocator.create(Scope.LocalVal);
sub_scope.* = .{
.parent = params_scope,
.gen_zir = &gen_scope,
.name = param_name,
// Implicit const list first, then implicit arg list.
.inst = @intToEnum(zir.Inst.Ref, @intCast(u32, zir.Inst.Ref.typed_value_map.len + i)),
.src = decl.tokSrcLoc(name_token),
};
params_scope = &sub_scope.base;
// Additionally put the param name into `string_bytes` and reference it with
// `extra` so that we have access to the data in codegen, for debug info.
const str_index = @intCast(u32, astgen.string_bytes.items.len);
astgen.extra.appendAssumeCapacity(str_index);
const used_bytes = astgen.string_bytes.items.len;
try astgen.string_bytes.ensureCapacity(mod.gpa, used_bytes + param_name.len + 1);
astgen.string_bytes.appendSliceAssumeCapacity(param_name);
astgen.string_bytes.appendAssumeCapacity(0);
}
_ = try AstGen.expr(&gen_scope, params_scope, .none, body_node);
if (gen_scope.instructions.items.len == 0 or
!astgen.instructions.items(.tag)[gen_scope.instructions.items.len - 1]
.isNoReturn())
{
// astgen uses result location semantics to coerce return operands.
// Since we are adding the return instruction here, we must handle the coercion.
// We do this by using the `ret_coerce` instruction.
_ = try gen_scope.addUnTok(.ret_coerce, .void_value, tree.lastToken(body_node));
}
const code = try gen_scope.finish();
if (std.builtin.mode == .Debug and mod.comp.verbose_ir) {
code.dump(mod.gpa, "fn_body", &gen_scope.base, param_count) catch {};
}
break :blk code;
};
const is_inline = fn_type.fnCallingConvention() == .Inline;
const anal_state: Fn.Analysis = if (is_inline) .inline_only else .queued;
new_func.* = .{
.state = anal_state,
.zir = fn_zir,
.body = undefined,
.owner_decl = decl,
};
fn_payload.* = .{
.base = .{ .tag = .function },
.data = new_func,
};
var prev_type_has_bits = false;
var prev_is_inline = false;
var type_changed = true;
if (decl.typedValueManaged()) |tvm| {
prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits();
type_changed = !tvm.typed_value.ty.eql(fn_type);
if (tvm.typed_value.val.castTag(.function)) |payload| {
const prev_func = payload.data;
prev_is_inline = prev_func.state == .inline_only;
prev_func.deinit(mod.gpa);
}
tvm.deinit(mod.gpa);
}
decl_arena_state.* = decl_arena.state;
decl.typed_value = .{
.most_recent = .{
.typed_value = .{
.ty = fn_type,
.val = Value.initPayload(&fn_payload.base),
},
.arena = decl_arena_state,
},
};
decl.analysis = .complete;
decl.generation = mod.generation;
if (!is_inline and fn_type.hasCodeGenBits()) {
// We don't fully codegen the decl until later, but we do need to reserve a global
// offset table index for it. This allows us to codegen decls out of dependency order,
// increasing how many computations can be done in parallel.
try mod.comp.bin_file.allocateDeclIndexes(decl);
try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl });
if (type_changed and mod.emit_h != null) {
try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
}
} else if (!prev_is_inline and prev_type_has_bits) {
mod.comp.bin_file.freeDecl(decl);
}
if (fn_proto.extern_export_token) |maybe_export_token| {
if (token_tags[maybe_export_token] == .keyword_export) {
if (is_inline) {
return mod.failTok(
&block_scope.base,
maybe_export_token,
"export of inline function",
.{},
);
}
const export_src = decl.tokSrcLoc(maybe_export_token);
const name = tree.tokenSlice(fn_proto.name_token.?); // TODO identifierTokenString
// The scope needs to have the decl in it.
try mod.analyzeExport(&block_scope.base, export_src, name, decl);
}
}
return type_changed or is_inline != prev_is_inline;
}
fn astgenAndSemaVarDecl(
mod: *Module,
decl: *Decl,
tree: ast.Tree,
var_decl: ast.full.VarDecl,
) !bool {
const tracy = trace(@src());
defer tracy.end();
decl.analysis = .in_progress;
decl.is_pub = var_decl.visib_token != null;
const token_tags = tree.tokens.items(.tag);
// We need the memory for the Type to go into the arena for the Decl
var decl_arena = std.heap.ArenaAllocator.init(mod.gpa);
errdefer decl_arena.deinit();
const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
// Used for simple error reporting.
var decl_scope: Scope.DeclRef = .{ .decl = decl };
const is_extern = blk: {
const maybe_extern_token = var_decl.extern_export_token orelse break :blk false;
break :blk token_tags[maybe_extern_token] == .keyword_extern;
};
if (var_decl.lib_name) |lib_name| {
assert(is_extern);
return mod.failTok(&decl_scope.base, lib_name, "TODO implement function library name", .{});
}
const is_mutable = token_tags[var_decl.ast.mut_token] == .keyword_var;
const is_threadlocal = if (var_decl.threadlocal_token) |some| blk: {
if (!is_mutable) {
return mod.failTok(&decl_scope.base, some, "threadlocal variable cannot be constant", .{});
}
break :blk true;
} else false;
assert(var_decl.comptime_token == null);
if (var_decl.ast.align_node != 0) {
return mod.failNode(
&decl_scope.base,
var_decl.ast.align_node,
"TODO implement function align expression",
.{},
);
}
if (var_decl.ast.section_node != 0) {
return mod.failNode(
&decl_scope.base,
var_decl.ast.section_node,
"TODO implement function section expression",
.{},
);
}
const var_info: struct { ty: Type, val: ?Value } = if (var_decl.ast.init_node != 0) vi: {
if (is_extern) {
return mod.failNode(
&decl_scope.base,
var_decl.ast.init_node,
"extern variables have no initializers",
.{},
);
}
var gen_scope_arena = std.heap.ArenaAllocator.init(mod.gpa);
defer gen_scope_arena.deinit();
var astgen = try AstGen.init(mod, decl, &gen_scope_arena.allocator);
defer astgen.deinit();
var gen_scope: Scope.GenZir = .{
.force_comptime = true,
.parent = &decl.container.base,
.astgen = &astgen,
};
defer gen_scope.instructions.deinit(mod.gpa);
const init_result_loc: AstGen.ResultLoc = if (var_decl.ast.type_node != 0) .{
.ty = try AstGen.expr(&gen_scope, &gen_scope.base, .{ .ty = .type_type }, var_decl.ast.type_node),
} else .none;
const init_inst = try AstGen.comptimeExpr(
&gen_scope,
&gen_scope.base,
init_result_loc,
var_decl.ast.init_node,
);
_ = try gen_scope.addBreak(.break_inline, 0, init_inst);
var code = try gen_scope.finish();
defer code.deinit(mod.gpa);
if (std.builtin.mode == .Debug and mod.comp.verbose_ir) {
code.dump(mod.gpa, "var_init", &gen_scope.base, 0) catch {};
}
var sema: Sema = .{
.mod = mod,
.gpa = mod.gpa,
.arena = &gen_scope_arena.allocator,
.code = code,
.inst_map = try gen_scope_arena.allocator.alloc(*ir.Inst, code.instructions.len),
.owner_decl = decl,
.func = null,
.owner_func = null,
.param_inst_list = &.{},
};
var block_scope: Scope.Block = .{
.parent = null,
.sema = &sema,
.src_decl = decl,
.instructions = .{},
.inlining = null,
.is_comptime = true,
};
defer block_scope.instructions.deinit(mod.gpa);
const init_inst_zir_ref = try sema.rootAsRef(&block_scope);
// The result location guarantees the type coercion.
const analyzed_init_inst = try sema.resolveInst(init_inst_zir_ref);
// The is_comptime in the Scope.Block guarantees the result is comptime-known.
const val = analyzed_init_inst.value().?;
break :vi .{
.ty = try analyzed_init_inst.ty.copy(&decl_arena.allocator),
.val = try val.copy(&decl_arena.allocator),
};
} else if (!is_extern) {
return mod.failTok(
&decl_scope.base,
var_decl.ast.mut_token,
"variables must be initialized",
.{},
);
} else if (var_decl.ast.type_node != 0) vi: {
var type_scope_arena = std.heap.ArenaAllocator.init(mod.gpa);
defer type_scope_arena.deinit();
var astgen = try AstGen.init(mod, decl, &type_scope_arena.allocator);
defer astgen.deinit();
var type_scope: Scope.GenZir = .{
.force_comptime = true,
.parent = &decl.container.base,
.astgen = &astgen,
};
defer type_scope.instructions.deinit(mod.gpa);
const var_type = try AstGen.typeExpr(&type_scope, &type_scope.base, var_decl.ast.type_node);
_ = try type_scope.addBreak(.break_inline, 0, var_type);
var code = try type_scope.finish();
defer code.deinit(mod.gpa);
if (std.builtin.mode == .Debug and mod.comp.verbose_ir) {
code.dump(mod.gpa, "var_type", &type_scope.base, 0) catch {};
}
var sema: Sema = .{
.mod = mod,
.gpa = mod.gpa,
.arena = &type_scope_arena.allocator,
.code = code,
.inst_map = try type_scope_arena.allocator.alloc(*ir.Inst, code.instructions.len),
.owner_decl = decl,
.func = null,
.owner_func = null,
.param_inst_list = &.{},
};
var block_scope: Scope.Block = .{
.parent = null,
.sema = &sema,
.src_decl = decl,
.instructions = .{},
.inlining = null,
.is_comptime = true,
};
defer block_scope.instructions.deinit(mod.gpa);
const ty = try sema.rootAsType(&block_scope);
break :vi .{
.ty = try ty.copy(&decl_arena.allocator),
.val = null,
};
} else {
return mod.failTok(
&decl_scope.base,
var_decl.ast.mut_token,
"unable to infer variable type",
.{},
);
};
if (is_mutable and !var_info.ty.isValidVarType(is_extern)) {
return mod.failTok(
&decl_scope.base,
var_decl.ast.mut_token,
"variable of type '{}' must be const",
.{var_info.ty},
);
}
var type_changed = true;
if (decl.typedValueManaged()) |tvm| {
type_changed = !tvm.typed_value.ty.eql(var_info.ty);
tvm.deinit(mod.gpa);
}
const new_variable = try decl_arena.allocator.create(Var);
new_variable.* = .{
.owner_decl = decl,
.init = var_info.val orelse undefined,
.is_extern = is_extern,
.is_mutable = is_mutable,
.is_threadlocal = is_threadlocal,
};
const var_val = try Value.Tag.variable.create(&decl_arena.allocator, new_variable);
decl_arena_state.* = decl_arena.state;
decl.typed_value = .{
.most_recent = .{
.typed_value = .{
.ty = var_info.ty,
.val = var_val,
},
.arena = decl_arena_state,
},
};
decl.analysis = .complete;
decl.generation = mod.generation;
if (var_decl.extern_export_token) |maybe_export_token| {
if (token_tags[maybe_export_token] == .keyword_export) {
const export_src = decl.tokSrcLoc(maybe_export_token);
const name_token = var_decl.ast.mut_token + 1;
const name = tree.tokenSlice(name_token); // TODO identifierTokenString
// The scope needs to have the decl in it.
try mod.analyzeExport(&decl_scope.base, export_src, name, decl);
}
}
return type_changed;
}
/// Returns the depender's index of the dependee.
pub fn declareDeclDependency(mod: *Module, depender: *Decl, dependee: *Decl) !u32 {
try depender.dependencies.ensureCapacity(mod.gpa, depender.dependencies.count() + 1);
try dependee.dependants.ensureCapacity(mod.gpa, dependee.dependants.count() + 1);
if (dependee.deletion_flag) {
dependee.deletion_flag = false;
mod.deletion_set.removeAssertDiscard(dependee);
}
dependee.dependants.putAssumeCapacity(depender, {});
const gop = depender.dependencies.getOrPutAssumeCapacity(dependee);
return @intCast(u32, gop.index);
}
pub fn getAstTree(mod: *Module, root_scope: *Scope.File) !*const ast.Tree {
const tracy = trace(@src());
defer tracy.end();
switch (root_scope.status) {
.never_loaded, .unloaded_success => {
try mod.failed_files.ensureCapacity(mod.gpa, mod.failed_files.items().len + 1);
const source = try root_scope.getSource(mod);
var keep_tree = false;
root_scope.tree = try std.zig.parse(mod.gpa, source);
defer if (!keep_tree) root_scope.tree.deinit(mod.gpa);
const tree = &root_scope.tree;
if (tree.errors.len != 0) {
const parse_err = tree.errors[0];
var msg = std.ArrayList(u8).init(mod.gpa);
defer msg.deinit();
const token_starts = tree.tokens.items(.start);
try tree.renderError(parse_err, msg.writer());
const err_msg = try mod.gpa.create(ErrorMsg);
err_msg.* = .{
.src_loc = .{
.container = .{ .file_scope = root_scope },
.lazy = .{ .byte_abs = token_starts[parse_err.token] },
},
.msg = msg.toOwnedSlice(),
};
mod.failed_files.putAssumeCapacityNoClobber(root_scope, err_msg);
root_scope.status = .unloaded_parse_failure;
return error.AnalysisFail;
}
root_scope.status = .loaded_success;
keep_tree = true;
return tree;
},
.unloaded_parse_failure => return error.AnalysisFail,
.loaded_success => return &root_scope.tree,
}
}
pub fn analyzeContainer(mod: *Module, container_scope: *Scope.Container) !void {
const tracy = trace(@src());
defer tracy.end();
// We may be analyzing it for the first time, or this may be
// an incremental update. This code handles both cases.
const tree = try mod.getAstTree(container_scope.file_scope);
const node_tags = tree.nodes.items(.tag);
const node_datas = tree.nodes.items(.data);
const decls = tree.rootDecls();
try mod.comp.work_queue.ensureUnusedCapacity(decls.len);
try container_scope.decls.ensureCapacity(mod.gpa, decls.len);
// Keep track of the decls that we expect to see in this file so that
// we know which ones have been deleted.
var deleted_decls = std.AutoArrayHashMap(*Decl, void).init(mod.gpa);
defer deleted_decls.deinit();
try deleted_decls.ensureCapacity(container_scope.decls.items().len);
for (container_scope.decls.items()) |entry| {
deleted_decls.putAssumeCapacityNoClobber(entry.key, {});
}
// Keep track of decls that are invalidated from the update. Ultimately,
// the goal is to queue up `analyze_decl` tasks in the work queue for
// the outdated decls, but we cannot queue up the tasks until after
// we find out which ones have been deleted, otherwise there would be
// deleted Decl pointers in the work queue.
var outdated_decls = std.AutoArrayHashMap(*Decl, void).init(mod.gpa);
defer outdated_decls.deinit();
for (decls) |decl_node| switch (node_tags[decl_node]) {
.fn_decl => {
const fn_proto = node_datas[decl_node].lhs;
const body = node_datas[decl_node].rhs;
switch (node_tags[fn_proto]) {
.fn_proto_simple => {
var params: [1]ast.Node.Index = undefined;
try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
body,
tree.fnProtoSimple(¶ms, fn_proto),
);
},
.fn_proto_multi => try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
body,
tree.fnProtoMulti(fn_proto),
),
.fn_proto_one => {
var params: [1]ast.Node.Index = undefined;
try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
body,
tree.fnProtoOne(¶ms, fn_proto),
);
},
.fn_proto => try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
body,
tree.fnProto(fn_proto),
),
else => unreachable,
}
},
.fn_proto_simple => {
var params: [1]ast.Node.Index = undefined;
try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
0,
tree.fnProtoSimple(¶ms, decl_node),
);
},
.fn_proto_multi => try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
0,
tree.fnProtoMulti(decl_node),
),
.fn_proto_one => {
var params: [1]ast.Node.Index = undefined;
try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
0,
tree.fnProtoOne(¶ms, decl_node),
);
},
.fn_proto => try mod.semaContainerFn(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
0,
tree.fnProto(decl_node),
),
.global_var_decl => try mod.semaContainerVar(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
tree.globalVarDecl(decl_node),
),
.local_var_decl => try mod.semaContainerVar(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
tree.localVarDecl(decl_node),
),
.simple_var_decl => try mod.semaContainerVar(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
tree.simpleVarDecl(decl_node),
),
.aligned_var_decl => try mod.semaContainerVar(
container_scope,
&deleted_decls,
&outdated_decls,
decl_node,
tree.*,
tree.alignedVarDecl(decl_node),
),
.@"comptime" => {
const name_index = mod.getNextAnonNameIndex();
const name = try std.fmt.allocPrint(mod.gpa, "__comptime_{d}", .{name_index});
defer mod.gpa.free(name);
const name_hash = container_scope.fullyQualifiedNameHash(name);
const contents_hash = std.zig.hashSrc(tree.getNodeSource(decl_node));
const new_decl = try mod.createNewDecl(&container_scope.base, name, decl_node, name_hash, contents_hash);
container_scope.decls.putAssumeCapacity(new_decl, {});
mod.comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = new_decl });
},
// Container fields are handled in AstGen.
.container_field_init,
.container_field_align,
.container_field,
=> continue,
.test_decl => {
if (mod.comp.bin_file.options.is_test) {
log.err("TODO: analyze test decl", .{});
}
},
.@"usingnamespace" => {
log.err("TODO: analyze usingnamespace decl", .{});
},
else => unreachable,
};
// Handle explicitly deleted decls from the source code. This is one of two
// places that Decl deletions happen. The other is in `Compilation`, after
// `performAllTheWork`, where we iterate over `Module.deletion_set` and
// delete Decls which are no longer referenced.
// If a Decl is explicitly deleted from source, and also no longer referenced,
// it may be both in this `deleted_decls` set, as well as in the
// `Module.deletion_set`. To avoid deleting it twice, we remove it from the
// deletion set at this time.
for (deleted_decls.items()) |entry| {
const decl = entry.key;
log.debug("'{s}' deleted from source", .{decl.name});
if (decl.deletion_flag) {
log.debug("'{s}' redundantly in deletion set; removing", .{decl.name});
mod.deletion_set.removeAssertDiscard(decl);
}
try mod.deleteDecl(decl, &outdated_decls);
}
// Finally we can queue up re-analysis tasks after we have processed
// the deleted decls.
for (outdated_decls.items()) |entry| {
try mod.markOutdatedDecl(entry.key);
}
}
fn semaContainerFn(
mod: *Module,
container_scope: *Scope.Container,
deleted_decls: *std.AutoArrayHashMap(*Decl, void),
outdated_decls: *std.AutoArrayHashMap(*Decl, void),
decl_node: ast.Node.Index,
tree: ast.Tree,
body_node: ast.Node.Index,
fn_proto: ast.full.FnProto,
) !void {
const tracy = trace(@src());
defer tracy.end();
// We will create a Decl for it regardless of analysis status.
const name_token = fn_proto.name_token orelse {
// This problem will go away with #1717.
@panic("TODO missing function name");
};
const name = tree.tokenSlice(name_token); // TODO use identifierTokenString
const name_hash = container_scope.fullyQualifiedNameHash(name);
const contents_hash = std.zig.hashSrc(tree.getNodeSource(decl_node));
if (mod.decl_table.get(name_hash)) |decl| {
// Update the AST Node index of the decl, even if its contents are unchanged, it may
// have been re-ordered.
const prev_src_node = decl.src_node;
decl.src_node = decl_node;
if (deleted_decls.swapRemove(decl) == null) {
decl.analysis = .sema_failure;
const msg = try ErrorMsg.create(mod.gpa, .{
.container = .{ .file_scope = container_scope.file_scope },
.lazy = .{ .token_abs = name_token },
}, "redefinition of '{s}'", .{decl.name});
errdefer msg.destroy(mod.gpa);
const other_src_loc: SrcLoc = .{
.container = .{ .file_scope = decl.container.file_scope },
.lazy = .{ .node_abs = prev_src_node },
};
try mod.errNoteNonLazy(other_src_loc, msg, "previous definition here", .{});
try mod.failed_decls.putNoClobber(mod.gpa, decl, msg);
} else {
if (!srcHashEql(decl.contents_hash, contents_hash)) {
try outdated_decls.put(decl, {});
decl.contents_hash = contents_hash;
} else switch (mod.comp.bin_file.tag) {
.coff => {
// TODO Implement for COFF
},
.elf => if (decl.fn_link.elf.len != 0) {
// TODO Look into detecting when this would be unnecessary by storing enough state
// in `Decl` to notice that the line number did not change.
mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl });
},
.macho => if (decl.fn_link.macho.len != 0) {
// TODO Look into detecting when this would be unnecessary by storing enough state
// in `Decl` to notice that the line number did not change.
mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl });
},
.c, .wasm, .spirv => {},
}
}
} else {
const new_decl = try mod.createNewDecl(&container_scope.base, name, decl_node, name_hash, contents_hash);
container_scope.decls.putAssumeCapacity(new_decl, {});
if (fn_proto.extern_export_token) |maybe_export_token| {
const token_tags = tree.tokens.items(.tag);
if (token_tags[maybe_export_token] == .keyword_export) {
mod.comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = new_decl });
}
}
new_decl.is_pub = fn_proto.visib_token != null;
}
}
fn semaContainerVar(
mod: *Module,
container_scope: *Scope.Container,
deleted_decls: *std.AutoArrayHashMap(*Decl, void),
outdated_decls: *std.AutoArrayHashMap(*Decl, void),
decl_node: ast.Node.Index,
tree: ast.Tree,
var_decl: ast.full.VarDecl,
) !void {
const tracy = trace(@src());
defer tracy.end();
const name_token = var_decl.ast.mut_token + 1;
const name = tree.tokenSlice(name_token); // TODO identifierTokenString
const name_hash = container_scope.fullyQualifiedNameHash(name);
const contents_hash = std.zig.hashSrc(tree.getNodeSource(decl_node));
if (mod.decl_table.get(name_hash)) |decl| {
// Update the AST Node index of the decl, even if its contents are unchanged, it may
// have been re-ordered.
const prev_src_node = decl.src_node;
decl.src_node = decl_node;
if (deleted_decls.swapRemove(decl) == null) {
decl.analysis = .sema_failure;
const msg = try ErrorMsg.create(mod.gpa, .{
.container = .{ .file_scope = container_scope.file_scope },
.lazy = .{ .token_abs = name_token },
}, "redefinition of '{s}'", .{decl.name});
errdefer msg.destroy(mod.gpa);
const other_src_loc: SrcLoc = .{
.container = .{ .file_scope = decl.container.file_scope },
.lazy = .{ .node_abs = prev_src_node },
};
try mod.errNoteNonLazy(other_src_loc, msg, "previous definition here", .{});
try mod.failed_decls.putNoClobber(mod.gpa, decl, msg);
} else if (!srcHashEql(decl.contents_hash, contents_hash)) {
try outdated_decls.put(decl, {});
decl.contents_hash = contents_hash;
}
} else {
const new_decl = try mod.createNewDecl(&container_scope.base, name, decl_node, name_hash, contents_hash);
container_scope.decls.putAssumeCapacity(new_decl, {});
if (var_decl.extern_export_token) |maybe_export_token| {
const token_tags = tree.tokens.items(.tag);
if (token_tags[maybe_export_token] == .keyword_export) {
mod.comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = new_decl });
}
}
new_decl.is_pub = var_decl.visib_token != null;
}
}
pub fn deleteDecl(
mod: *Module,
decl: *Decl,
outdated_decls: ?*std.AutoArrayHashMap(*Decl, void),
) !void {
const tracy = trace(@src());
defer tracy.end();
log.debug("deleting decl '{s}'", .{decl.name});
if (outdated_decls) |map| {
_ = map.swapRemove(decl);
try map.ensureCapacity(map.count() + decl.dependants.count());
}
try mod.deletion_set.ensureCapacity(mod.gpa, mod.deletion_set.count() +
decl.dependencies.count());
// Remove from the namespace it resides in. In the case of an anonymous Decl it will
// not be present in the set, and this does nothing.
decl.container.removeDecl(decl);
const name_hash = decl.fullyQualifiedNameHash();
mod.decl_table.removeAssertDiscard(name_hash);
// Remove itself from its dependencies, because we are about to destroy the decl pointer.
for (decl.dependencies.items()) |entry| {
const dep = entry.key;
dep.removeDependant(decl);
if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
// We don't recursively perform a deletion here, because during the update,
// another reference to it may turn up.
dep.deletion_flag = true;
mod.deletion_set.putAssumeCapacity(dep, {});
}
}
// Anything that depends on this deleted decl needs to be re-analyzed.
for (decl.dependants.items()) |entry| {
const dep = entry.key;
dep.removeDependency(decl);
if (outdated_decls) |map| {
map.putAssumeCapacity(dep, {});
} else if (std.debug.runtime_safety) {
// If `outdated_decls` is `null`, it means we're being called from
// `Compilation` after `performAllTheWork` and we cannot queue up any
// more work. `dep` must necessarily be another Decl that is no longer
// being referenced, and will be in the `deletion_set`. Otherwise,
// something has gone wrong.
assert(mod.deletion_set.contains(dep));
}
}
if (mod.failed_decls.swapRemove(decl)) |entry| {
entry.value.destroy(mod.gpa);
}
if (mod.emit_h_failed_decls.swapRemove(decl)) |entry| {
entry.value.destroy(mod.gpa);
}
_ = mod.compile_log_decls.swapRemove(decl);
mod.deleteDeclExports(decl);
mod.comp.bin_file.freeDecl(decl);
decl.destroy(mod);
}
/// Delete all the Export objects that are caused by this Decl. Re-analysis of
/// this Decl will cause them to be re-created (or not).
fn deleteDeclExports(mod: *Module, decl: *Decl) void {
const kv = mod.export_owners.swapRemove(decl) orelse return;
for (kv.value) |exp| {
if (mod.decl_exports.getEntry(exp.exported_decl)) |decl_exports_kv| {
// Remove exports with owner_decl matching the regenerating decl.
const list = decl_exports_kv.value;
var i: usize = 0;
var new_len = list.len;
while (i < new_len) {
if (list[i].owner_decl == decl) {
mem.copyBackwards(*Export, list[i..], list[i + 1 .. new_len]);
new_len -= 1;
} else {
i += 1;
}
}
decl_exports_kv.value = mod.gpa.shrink(list, new_len);
if (new_len == 0) {
mod.decl_exports.removeAssertDiscard(exp.exported_decl);
}
}
if (mod.comp.bin_file.cast(link.File.Elf)) |elf| {
elf.deleteExport(exp.link.elf);
}
if (mod.comp.bin_file.cast(link.File.MachO)) |macho| {
macho.deleteExport(exp.link.macho);
}
if (mod.failed_exports.swapRemove(exp)) |entry| {
entry.value.destroy(mod.gpa);
}
_ = mod.symbol_exports.swapRemove(exp.options.name);
mod.gpa.free(exp.options.name);
mod.gpa.destroy(exp);
}
mod.gpa.free(kv.value);
}
pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn) !void {
const tracy = trace(@src());
defer tracy.end();
// Use the Decl's arena for function memory.
var arena = decl.typed_value.most_recent.arena.?.promote(mod.gpa);
defer decl.typed_value.most_recent.arena.?.* = arena.state;
const fn_ty = decl.typed_value.most_recent.typed_value.ty;
const param_inst_list = try mod.gpa.alloc(*ir.Inst, fn_ty.fnParamLen());
defer mod.gpa.free(param_inst_list);
for (param_inst_list) |*param_inst, param_index| {
const param_type = fn_ty.fnParamType(param_index);
const name = func.zir.nullTerminatedString(func.zir.extra[param_index]);
const arg_inst = try arena.allocator.create(ir.Inst.Arg);
arg_inst.* = .{
.base = .{
.tag = .arg,
.ty = param_type,
.src = .unneeded,
},
.name = name,
};
param_inst.* = &arg_inst.base;
}
var sema: Sema = .{
.mod = mod,
.gpa = mod.gpa,
.arena = &arena.allocator,
.code = func.zir,
.inst_map = try mod.gpa.alloc(*ir.Inst, func.zir.instructions.len),
.owner_decl = decl,
.func = func,
.owner_func = func,
.param_inst_list = param_inst_list,
};
defer mod.gpa.free(sema.inst_map);
var inner_block: Scope.Block = .{
.parent = null,
.sema = &sema,
.src_decl = decl,
.instructions = .{},
.inlining = null,
.is_comptime = false,
};
defer inner_block.instructions.deinit(mod.gpa);
// TZIR currently requires the arg parameters to be the first N instructions
try inner_block.instructions.appendSlice(mod.gpa, param_inst_list);
func.state = .in_progress;
log.debug("set {s} to in_progress", .{decl.name});
_ = try sema.root(&inner_block);
const instructions = try arena.allocator.dupe(*ir.Inst, inner_block.instructions.items);
func.state = .success;
func.body = .{ .instructions = instructions };
log.debug("set {s} to success", .{decl.name});
}
fn markOutdatedDecl(mod: *Module, decl: *Decl) !void {
log.debug("mark {s} outdated", .{decl.name});
try mod.comp.work_queue.writeItem(.{ .analyze_decl = decl });
if (mod.failed_decls.swapRemove(decl)) |entry| {
entry.value.destroy(mod.gpa);
}
if (mod.emit_h_failed_decls.swapRemove(decl)) |entry| {
entry.value.destroy(mod.gpa);
}
_ = mod.compile_log_decls.swapRemove(decl);
decl.analysis = .outdated;
}
fn allocateNewDecl(
mod: *Module,
scope: *Scope,
src_node: ast.Node.Index,
contents_hash: std.zig.SrcHash,
) !*Decl {
// If we have emit-h then we must allocate a bigger structure to store the emit-h state.
const new_decl: *Decl = if (mod.emit_h != null) blk: {
const parent_struct = try mod.gpa.create(DeclPlusEmitH);
parent_struct.* = .{
.emit_h = .{},
.decl = undefined,
};
break :blk &parent_struct.decl;
} else try mod.gpa.create(Decl);
new_decl.* = .{
.name = "",
.container = scope.namespace(),
.src_node = src_node,
.typed_value = .{ .never_succeeded = {} },
.analysis = .unreferenced,
.deletion_flag = false,
.contents_hash = contents_hash,
.link = switch (mod.comp.bin_file.tag) {
.coff => .{ .coff = link.File.Coff.TextBlock.empty },
.elf => .{ .elf = link.File.Elf.TextBlock.empty },
.macho => .{ .macho = link.File.MachO.TextBlock.empty },
.c => .{ .c = link.File.C.DeclBlock.empty },
.wasm => .{ .wasm = link.File.Wasm.DeclBlock.empty },
.spirv => .{ .spirv = {} },
},
.fn_link = switch (mod.comp.bin_file.tag) {
.coff => .{ .coff = {} },
.elf => .{ .elf = link.File.Elf.SrcFn.empty },
.macho => .{ .macho = link.File.MachO.SrcFn.empty },
.c => .{ .c = link.File.C.FnBlock.empty },
.wasm => .{ .wasm = link.File.Wasm.FnData.empty },
.spirv => .{ .spirv = .{} },
},
.generation = 0,
.is_pub = false,
};
return new_decl;
}
fn createNewDecl(
mod: *Module,
scope: *Scope,
decl_name: []const u8,
src_node: ast.Node.Index,
name_hash: Scope.NameHash,
contents_hash: std.zig.SrcHash,
) !*Decl {
try mod.decl_table.ensureCapacity(mod.gpa, mod.decl_table.items().len + 1);
const new_decl = try mod.allocateNewDecl(scope, src_node, contents_hash);
errdefer mod.gpa.destroy(new_decl);
new_decl.name = try mem.dupeZ(mod.gpa, u8, decl_name);
mod.decl_table.putAssumeCapacityNoClobber(name_hash, new_decl);
return new_decl;
}
/// Get error value for error tag `name`.
pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).Entry {
const gop = try mod.global_error_set.getOrPut(mod.gpa, name);
if (gop.found_existing)
return gop.entry.*;
errdefer mod.global_error_set.removeAssertDiscard(name);
try mod.error_name_list.ensureCapacity(mod.gpa, mod.error_name_list.items.len + 1);
gop.entry.key = try mod.gpa.dupe(u8, name);
gop.entry.value = @intCast(ErrorInt, mod.error_name_list.items.len);
mod.error_name_list.appendAssumeCapacity(gop.entry.key);
return gop.entry.*;
}
pub fn analyzeExport(
mod: *Module,
scope: *Scope,
src: LazySrcLoc,
borrowed_symbol_name: []const u8,
exported_decl: *Decl,
) !void {
try mod.ensureDeclAnalyzed(exported_decl);
const typed_value = exported_decl.typed_value.most_recent.typed_value;
switch (typed_value.ty.zigTypeTag()) {
.Fn => {},
else => return mod.fail(scope, src, "unable to export type '{}'", .{typed_value.ty}),
}
try mod.decl_exports.ensureCapacity(mod.gpa, mod.decl_exports.items().len + 1);
try mod.export_owners.ensureCapacity(mod.gpa, mod.export_owners.items().len + 1);
const new_export = try mod.gpa.create(Export);
errdefer mod.gpa.destroy(new_export);
const symbol_name = try mod.gpa.dupe(u8, borrowed_symbol_name);
errdefer mod.gpa.free(symbol_name);
const owner_decl = scope.ownerDecl().?;
new_export.* = .{
.options = .{ .name = symbol_name },
.src = src,
.link = switch (mod.comp.bin_file.tag) {
.coff => .{ .coff = {} },
.elf => .{ .elf = link.File.Elf.Export{} },
.macho => .{ .macho = link.File.MachO.Export{} },
.c => .{ .c = {} },
.wasm => .{ .wasm = {} },
.spirv => .{ .spirv = {} },
},
.owner_decl = owner_decl,
.exported_decl = exported_decl,
.status = .in_progress,
};
// Add to export_owners table.
const eo_gop = mod.export_owners.getOrPutAssumeCapacity(owner_decl);
if (!eo_gop.found_existing) {
eo_gop.entry.value = &[0]*Export{};
}
eo_gop.entry.value = try mod.gpa.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
eo_gop.entry.value[eo_gop.entry.value.len - 1] = new_export;
errdefer eo_gop.entry.value = mod.gpa.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
// Add to exported_decl table.
const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl);
if (!de_gop.found_existing) {
de_gop.entry.value = &[0]*Export{};
}
de_gop.entry.value = try mod.gpa.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
de_gop.entry.value[de_gop.entry.value.len - 1] = new_export;
errdefer de_gop.entry.value = mod.gpa.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
if (mod.symbol_exports.get(symbol_name)) |other_export| {
new_export.status = .failed_retryable;
try mod.failed_exports.ensureCapacity(mod.gpa, mod.failed_exports.items().len + 1);
const msg = try mod.errMsg(
scope,
src,
"exported symbol collision: {s}",
.{symbol_name},
);
errdefer msg.destroy(mod.gpa);
try mod.errNote(
&other_export.owner_decl.container.base,
other_export.src,
msg,
"other symbol here",
.{},
);
mod.failed_exports.putAssumeCapacityNoClobber(new_export, msg);
new_export.status = .failed;
return;
}
try mod.symbol_exports.putNoClobber(mod.gpa, symbol_name, new_export);
mod.comp.bin_file.updateDeclExports(mod, exported_decl, de_gop.entry.value) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => {
new_export.status = .failed_retryable;
try mod.failed_exports.ensureCapacity(mod.gpa, mod.failed_exports.items().len + 1);
const msg = try mod.errMsg(scope, src, "unable to export: {s}", .{@errorName(err)});
mod.failed_exports.putAssumeCapacityNoClobber(new_export, msg);
},
};
}
pub fn constInst(mod: *Module, arena: *Allocator, src: LazySrcLoc, typed_value: TypedValue) !*ir.Inst {
const const_inst = try arena.create(ir.Inst.Constant);
const_inst.* = .{
.base = .{
.tag = ir.Inst.Constant.base_tag,
.ty = typed_value.ty,
.src = src,
},
.val = typed_value.val,
};
return &const_inst.base;
}
pub fn constType(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.type),
.val = try ty.toValue(arena),
});
}
pub fn constVoid(mod: *Module, arena: *Allocator, src: LazySrcLoc) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.void),
.val = Value.initTag(.void_value),
});
}
pub fn constNoReturn(mod: *Module, arena: *Allocator, src: LazySrcLoc) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.noreturn),
.val = Value.initTag(.unreachable_value),
});
}
pub fn constUndef(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = ty,
.val = Value.initTag(.undef),
});
}
pub fn constBool(mod: *Module, arena: *Allocator, src: LazySrcLoc, v: bool) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = Type.initTag(.bool),
.val = ([2]Value{ Value.initTag(.bool_false), Value.initTag(.bool_true) })[@boolToInt(v)],
});
}
pub fn constIntUnsigned(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type, int: u64) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = ty,
.val = try Value.Tag.int_u64.create(arena, int),
});
}
pub fn constIntSigned(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type, int: i64) !*ir.Inst {
return mod.constInst(arena, src, .{
.ty = ty,
.val = try Value.Tag.int_i64.create(arena, int),
});
}
pub fn constIntBig(mod: *Module, arena: *Allocator, src: LazySrcLoc, ty: Type, big_int: BigIntConst) !*ir.Inst {
if (big_int.positive) {
if (big_int.to(u64)) |x| {
return mod.constIntUnsigned(arena, src, ty, x);
} else |err| switch (err) {
error.NegativeIntoUnsigned => unreachable,
error.TargetTooSmall => {}, // handled below
}
return mod.constInst(arena, src, .{
.ty = ty,
.val = try Value.Tag.int_big_positive.create(arena, big_int.limbs),
});
} else {
if (big_int.to(i64)) |x| {
return mod.constIntSigned(arena, src, ty, x);
} else |err| switch (err) {
error.NegativeIntoUnsigned => unreachable,
error.TargetTooSmall => {}, // handled below
}
return mod.constInst(arena, src, .{
.ty = ty,
.val = try Value.Tag.int_big_negative.create(arena, big_int.limbs),
});
}
}
pub fn createAnonymousDecl(
mod: *Module,
scope: *Scope,
decl_arena: *std.heap.ArenaAllocator,
typed_value: TypedValue,
) !*Decl {
const name_index = mod.getNextAnonNameIndex();
const scope_decl = scope.ownerDecl().?;
const name = try std.fmt.allocPrint(mod.gpa, "{s}__anon_{d}", .{ scope_decl.name, name_index });
defer mod.gpa.free(name);
const name_hash = scope.namespace().fullyQualifiedNameHash(name);
const src_hash: std.zig.SrcHash = undefined;
const new_decl = try mod.createNewDecl(scope, name, scope_decl.src_node, name_hash, src_hash);
const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
decl_arena_state.* = decl_arena.state;
new_decl.typed_value = .{
.most_recent = .{
.typed_value = typed_value,
.arena = decl_arena_state,
},
};
new_decl.analysis = .complete;
new_decl.generation = mod.generation;
// TODO: This generates the Decl into the machine code file if it is of a
// type that is non-zero size. We should be able to further improve the
// compiler to omit Decls which are only referenced at compile-time and not runtime.
if (typed_value.ty.hasCodeGenBits()) {
try mod.comp.bin_file.allocateDeclIndexes(new_decl);
try mod.comp.work_queue.writeItem(.{ .codegen_decl = new_decl });
}
return new_decl;
}
pub fn createContainerDecl(
mod: *Module,
scope: *Scope,
base_token: std.zig.ast.TokenIndex,
decl_arena: *std.heap.ArenaAllocator,
typed_value: TypedValue,
) !*Decl {
const scope_decl = scope.ownerDecl().?;
const name = try mod.getAnonTypeName(scope, base_token);
defer mod.gpa.free(name);
const name_hash = scope.namespace().fullyQualifiedNameHash(name);
const src_hash: std.zig.SrcHash = undefined;
const new_decl = try mod.createNewDecl(scope, name, scope_decl.src_node, name_hash, src_hash);
const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
decl_arena_state.* = decl_arena.state;
new_decl.typed_value = .{
.most_recent = .{
.typed_value = typed_value,
.arena = decl_arena_state,
},
};
new_decl.analysis = .complete;
new_decl.generation = mod.generation;
return new_decl;
}
fn getAnonTypeName(mod: *Module, scope: *Scope, base_token: std.zig.ast.TokenIndex) ![]u8 {
// TODO add namespaces, generic function signatrues
const tree = scope.tree();
const token_tags = tree.tokens.items(.tag);
const base_name = switch (token_tags[base_token]) {
.keyword_struct => "struct",
.keyword_enum => "enum",
.keyword_union => "union",
.keyword_opaque => "opaque",
else => unreachable,
};
const loc = tree.tokenLocation(0, base_token);
return std.fmt.allocPrint(mod.gpa, "{s}:{d}:{d}", .{ base_name, loc.line, loc.column });
}
fn getNextAnonNameIndex(mod: *Module) usize {
return @atomicRmw(usize, &mod.next_anon_name_index, .Add, 1, .Monotonic);
}
pub fn lookupDeclName(mod: *Module, scope: *Scope, ident_name: []const u8) ?*Decl {
const namespace = scope.namespace();
const name_hash = namespace.fullyQualifiedNameHash(ident_name);
return mod.decl_table.get(name_hash);
}
pub fn makeIntType(arena: *Allocator, signedness: std.builtin.Signedness, bits: u16) !Type {
const int_payload = try arena.create(Type.Payload.Bits);
int_payload.* = .{
.base = .{
.tag = switch (signedness) {
.signed => .int_signed,
.unsigned => .int_unsigned,
},
},
.data = bits,
};
return Type.initPayload(&int_payload.base);
}
/// We don't return a pointer to the new error note because the pointer
/// becomes invalid when you add another one.
pub fn errNote(
mod: *Module,
scope: *Scope,
src: LazySrcLoc,
parent: *ErrorMsg,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
return mod.errNoteNonLazy(src.toSrcLoc(scope), parent, format, args);
}
pub fn errNoteNonLazy(
mod: *Module,
src_loc: SrcLoc,
parent: *ErrorMsg,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
const msg = try std.fmt.allocPrint(mod.gpa, format, args);
errdefer mod.gpa.free(msg);
parent.notes = try mod.gpa.realloc(parent.notes, parent.notes.len + 1);
parent.notes[parent.notes.len - 1] = .{
.src_loc = src_loc,
.msg = msg,
};
}
pub fn errMsg(
mod: *Module,
scope: *Scope,
src: LazySrcLoc,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!*ErrorMsg {
return ErrorMsg.create(mod.gpa, src.toSrcLoc(scope), format, args);
}
pub fn fail(
mod: *Module,
scope: *Scope,
src: LazySrcLoc,
comptime format: []const u8,
args: anytype,
) InnerError {
const err_msg = try mod.errMsg(scope, src, format, args);
return mod.failWithOwnedErrorMsg(scope, err_msg);
}
/// Same as `fail`, except given an absolute byte offset, and the function sets up the `LazySrcLoc`
/// for pointing at it relatively by subtracting from the containing `Decl`.
pub fn failOff(
mod: *Module,
scope: *Scope,
byte_offset: u32,
comptime format: []const u8,
args: anytype,
) InnerError {
const decl_byte_offset = scope.srcDecl().?.srcByteOffset();
const src: LazySrcLoc = .{ .byte_offset = byte_offset - decl_byte_offset };
return mod.fail(scope, src, format, args);
}
/// Same as `fail`, except given a token index, and the function sets up the `LazySrcLoc`
/// for pointing at it relatively by subtracting from the containing `Decl`.
pub fn failTok(
mod: *Module,
scope: *Scope,
token_index: ast.TokenIndex,
comptime format: []const u8,
args: anytype,
) InnerError {
const src = scope.srcDecl().?.tokSrcLoc(token_index);
return mod.fail(scope, src, format, args);
}
/// Same as `fail`, except given an AST node index, and the function sets up the `LazySrcLoc`
/// for pointing at it relatively by subtracting from the containing `Decl`.
pub fn failNode(
mod: *Module,
scope: *Scope,
node_index: ast.Node.Index,
comptime format: []const u8,
args: anytype,
) InnerError {
const src = scope.srcDecl().?.nodeSrcLoc(node_index);
return mod.fail(scope, src, format, args);
}
pub fn failWithOwnedErrorMsg(mod: *Module, scope: *Scope, err_msg: *ErrorMsg) InnerError {
@setCold(true);
{
errdefer err_msg.destroy(mod.gpa);
try mod.failed_decls.ensureCapacity(mod.gpa, mod.failed_decls.items().len + 1);
try mod.failed_files.ensureCapacity(mod.gpa, mod.failed_files.items().len + 1);
}
switch (scope.tag) {
.block => {
const block = scope.cast(Scope.Block).?;
if (block.sema.owner_func) |func| {
func.state = .sema_failure;
} else {
block.sema.owner_decl.analysis = .sema_failure;
block.sema.owner_decl.generation = mod.generation;
}
mod.failed_decls.putAssumeCapacityNoClobber(block.sema.owner_decl, err_msg);
},
.gen_zir => {
const gen_zir = scope.cast(Scope.GenZir).?;
gen_zir.astgen.decl.analysis = .sema_failure;
gen_zir.astgen.decl.generation = mod.generation;
mod.failed_decls.putAssumeCapacityNoClobber(gen_zir.astgen.decl, err_msg);
},
.local_val => {
const gen_zir = scope.cast(Scope.LocalVal).?.gen_zir;
gen_zir.astgen.decl.analysis = .sema_failure;
gen_zir.astgen.decl.generation = mod.generation;
mod.failed_decls.putAssumeCapacityNoClobber(gen_zir.astgen.decl, err_msg);
},
.local_ptr => {
const gen_zir = scope.cast(Scope.LocalPtr).?.gen_zir;
gen_zir.astgen.decl.analysis = .sema_failure;
gen_zir.astgen.decl.generation = mod.generation;
mod.failed_decls.putAssumeCapacityNoClobber(gen_zir.astgen.decl, err_msg);
},
.file => unreachable,
.container => unreachable,
.decl_ref => {
const decl_ref = scope.cast(Scope.DeclRef).?;
decl_ref.decl.analysis = .sema_failure;
decl_ref.decl.generation = mod.generation;
mod.failed_decls.putAssumeCapacityNoClobber(decl_ref.decl, err_msg);
},
}
return error.AnalysisFail;
}
fn srcHashEql(a: std.zig.SrcHash, b: std.zig.SrcHash) bool {
return @bitCast(u128, a) == @bitCast(u128, b);
}
pub fn intAdd(allocator: *Allocator, lhs: Value, rhs: Value) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.add(lhs_bigint, rhs_bigint);
const result_limbs = result_bigint.limbs[0..result_bigint.len];
if (result_bigint.positive) {
return Value.Tag.int_big_positive.create(allocator, result_limbs);
} else {
return Value.Tag.int_big_negative.create(allocator, result_limbs);
}
}
pub fn intSub(allocator: *Allocator, lhs: Value, rhs: Value) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.sub(lhs_bigint, rhs_bigint);
const result_limbs = result_bigint.limbs[0..result_bigint.len];
if (result_bigint.positive) {
return Value.Tag.int_big_positive.create(allocator, result_limbs);
} else {
return Value.Tag.int_big_negative.create(allocator, result_limbs);
}
}
pub fn intMul(allocator: *Allocator, lhs: Value, rhs: Value) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len + rhs_bigint.limbs.len + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
var limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
);
defer allocator.free(limbs_buffer);
result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, allocator);
const result_limbs = result_bigint.limbs[0..result_bigint.len];
if (result_bigint.positive) {
return Value.Tag.int_big_positive.create(allocator, result_limbs);
} else {
return Value.Tag.int_big_negative.create(allocator, result_limbs);
}
}
pub fn floatAdd(
arena: *Allocator,
float_type: Type,
src: LazySrcLoc,
lhs: Value,
rhs: Value,
) !Value {
switch (float_type.tag()) {
.f16 => {
@panic("TODO add __trunctfhf2 to compiler-rt");
//const lhs_val = lhs.toFloat(f16);
//const rhs_val = rhs.toFloat(f16);
//return Value.Tag.float_16.create(arena, lhs_val + rhs_val);
},
.f32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val + rhs_val);
},
.f64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val + rhs_val);
},
.f128, .comptime_float, .c_longdouble => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val + rhs_val);
},
else => unreachable,
}
}
pub fn floatSub(
arena: *Allocator,
float_type: Type,
src: LazySrcLoc,
lhs: Value,
rhs: Value,
) !Value {
switch (float_type.tag()) {
.f16 => {
@panic("TODO add __trunctfhf2 to compiler-rt");
//const lhs_val = lhs.toFloat(f16);
//const rhs_val = rhs.toFloat(f16);
//return Value.Tag.float_16.create(arena, lhs_val - rhs_val);
},
.f32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val - rhs_val);
},
.f64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val - rhs_val);
},
.f128, .comptime_float, .c_longdouble => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val - rhs_val);
},
else => unreachable,
}
}
pub fn floatMul(
arena: *Allocator,
float_type: Type,
src: LazySrcLoc,
lhs: Value,
rhs: Value,
) !Value {
switch (float_type.tag()) {
.f16 => {
@panic("TODO add __trunctfhf2 to compiler-rt");
//const lhs_val = lhs.toFloat(f16);
//const rhs_val = rhs.toFloat(f16);
//return Value.Tag.float_16.create(arena, lhs_val * rhs_val);
},
.f32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val * rhs_val);
},
.f64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val * rhs_val);
},
.f128, .comptime_float, .c_longdouble => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val * rhs_val);
},
else => unreachable,
}
}
pub fn simplePtrType(
mod: *Module,
arena: *Allocator,
elem_ty: Type,
mutable: bool,
size: std.builtin.TypeInfo.Pointer.Size,
) Allocator.Error!Type {
if (!mutable and size == .Slice and elem_ty.eql(Type.initTag(.u8))) {
return Type.initTag(.const_slice_u8);
}
// TODO stage1 type inference bug
const T = Type.Tag;
const type_payload = try arena.create(Type.Payload.ElemType);
type_payload.* = .{
.base = .{
.tag = switch (size) {
.One => if (mutable) T.single_mut_pointer else T.single_const_pointer,
.Many => if (mutable) T.many_mut_pointer else T.many_const_pointer,
.C => if (mutable) T.c_mut_pointer else T.c_const_pointer,
.Slice => if (mutable) T.mut_slice else T.const_slice,
},
},
.data = elem_ty,
};
return Type.initPayload(&type_payload.base);
}
pub fn ptrType(
mod: *Module,
arena: *Allocator,
elem_ty: Type,
sentinel: ?Value,
@"align": u32,
bit_offset: u16,
host_size: u16,
mutable: bool,
@"allowzero": bool,
@"volatile": bool,
size: std.builtin.TypeInfo.Pointer.Size,
) Allocator.Error!Type {
assert(host_size == 0 or bit_offset < host_size * 8);
// TODO check if type can be represented by simplePtrType
return Type.Tag.pointer.create(arena, .{
.pointee_type = elem_ty,
.sentinel = sentinel,
.@"align" = @"align",
.bit_offset = bit_offset,
.host_size = host_size,
.@"allowzero" = @"allowzero",
.mutable = mutable,
.@"volatile" = @"volatile",
.size = size,
});
}
pub fn optionalType(mod: *Module, arena: *Allocator, child_type: Type) Allocator.Error!Type {
switch (child_type.tag()) {
.single_const_pointer => return Type.Tag.optional_single_const_pointer.create(
arena,
child_type.elemType(),
),
.single_mut_pointer => return Type.Tag.optional_single_mut_pointer.create(
arena,
child_type.elemType(),
),
else => return Type.Tag.optional.create(arena, child_type),
}
}
pub fn arrayType(
mod: *Module,
arena: *Allocator,
len: u64,
sentinel: ?Value,
elem_type: Type,
) Allocator.Error!Type {
if (elem_type.eql(Type.initTag(.u8))) {
if (sentinel) |some| {
if (some.eql(Value.initTag(.zero))) {
return Type.Tag.array_u8_sentinel_0.create(arena, len);
}
} else {
return Type.Tag.array_u8.create(arena, len);
}
}
if (sentinel) |some| {
return Type.Tag.array_sentinel.create(arena, .{
.len = len,
.sentinel = some,
.elem_type = elem_type,
});
}
return Type.Tag.array.create(arena, .{
.len = len,
.elem_type = elem_type,
});
}
pub fn errorUnionType(
mod: *Module,
arena: *Allocator,
error_set: Type,
payload: Type,
) Allocator.Error!Type {
assert(error_set.zigTypeTag() == .ErrorSet);
if (error_set.eql(Type.initTag(.anyerror)) and payload.eql(Type.initTag(.void))) {
return Type.initTag(.anyerror_void_error_union);
}
return Type.Tag.error_union.create(arena, .{
.error_set = error_set,
.payload = payload,
});
}
pub fn dumpInst(mod: *Module, scope: *Scope, inst: *ir.Inst) void {
const zir_module = scope.namespace();
const source = zir_module.getSource(mod) catch @panic("dumpInst failed to get source");
const loc = std.zig.findLineColumn(source, inst.src);
if (inst.tag == .constant) {
std.debug.print("constant ty={} val={} src={s}:{d}:{d}\n", .{
inst.ty,
inst.castTag(.constant).?.val,
zir_module.subFilePath(),
loc.line + 1,
loc.column + 1,
});
} else if (inst.deaths == 0) {
std.debug.print("{s} ty={} src={s}:{d}:{d}\n", .{
@tagName(inst.tag),
inst.ty,
zir_module.subFilePath(),
loc.line + 1,
loc.column + 1,
});
} else {
std.debug.print("{s} ty={} deaths={b} src={s}:{d}:{d}\n", .{
@tagName(inst.tag),
inst.ty,
inst.deaths,
zir_module.subFilePath(),
loc.line + 1,
loc.column + 1,
});
}
}
pub fn getTarget(mod: Module) Target {
return mod.comp.bin_file.options.target;
}
pub fn optimizeMode(mod: Module) std.builtin.Mode {
return mod.comp.bin_file.options.optimize_mode;
}
/// Given an identifier token, obtain the string for it.
/// If the token uses @"" syntax, parses as a string, reports errors if applicable,
/// and allocates the result within `scope.arena()`.
/// Otherwise, returns a reference to the source code bytes directly.
/// See also `appendIdentStr` and `parseStrLit`.
pub fn identifierTokenString(mod: *Module, scope: *Scope, token: ast.TokenIndex) InnerError![]const u8 {
const tree = scope.tree();
const token_tags = tree.tokens.items(.tag);
assert(token_tags[token] == .identifier);
const ident_name = tree.tokenSlice(token);
if (!mem.startsWith(u8, ident_name, "@")) {
return ident_name;
}
var buf: ArrayListUnmanaged(u8) = .{};
defer buf.deinit(mod.gpa);
try parseStrLit(mod, scope, token, &buf, ident_name, 1);
const duped = try scope.arena().dupe(u8, buf.items);
return duped;
}
/// `scope` is only used for error reporting.
/// The string is stored in `arena` regardless of whether it uses @"" syntax.
pub fn identifierTokenStringTreeArena(
mod: *Module,
scope: *Scope,
token: ast.TokenIndex,
tree: *const ast.Tree,
arena: *Allocator,
) InnerError![]u8 {
const token_tags = tree.tokens.items(.tag);
assert(token_tags[token] == .identifier);
const ident_name = tree.tokenSlice(token);
if (!mem.startsWith(u8, ident_name, "@")) {
return arena.dupe(u8, ident_name);
}
var buf: ArrayListUnmanaged(u8) = .{};
defer buf.deinit(mod.gpa);
try parseStrLit(mod, scope, token, &buf, ident_name, 1);
return arena.dupe(u8, buf.items);
}
/// Given an identifier token, obtain the string for it (possibly parsing as a string
/// literal if it is @"" syntax), and append the string to `buf`.
/// See also `identifierTokenString` and `parseStrLit`.
pub fn appendIdentStr(
mod: *Module,
scope: *Scope,
token: ast.TokenIndex,
buf: *ArrayListUnmanaged(u8),
) InnerError!void {
const tree = scope.tree();
const token_tags = tree.tokens.items(.tag);
assert(token_tags[token] == .identifier);
const ident_name = tree.tokenSlice(token);
if (!mem.startsWith(u8, ident_name, "@")) {
return buf.appendSlice(mod.gpa, ident_name);
} else {
return mod.parseStrLit(scope, token, buf, ident_name, 1);
}
}
/// Appends the result to `buf`.
pub fn parseStrLit(
mod: *Module,
scope: *Scope,
token: ast.TokenIndex,
buf: *ArrayListUnmanaged(u8),
bytes: []const u8,
offset: u32,
) InnerError!void {
const tree = scope.tree();
const token_starts = tree.tokens.items(.start);
const raw_string = bytes[offset..];
var buf_managed = buf.toManaged(mod.gpa);
const result = std.zig.string_literal.parseAppend(&buf_managed, raw_string);
buf.* = buf_managed.toUnmanaged();
switch (try result) {
.success => return,
.invalid_character => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"invalid string literal character: '{c}'",
.{raw_string[bad_index]},
);
},
.expected_hex_digits => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"expected hex digits after '\\x'",
.{},
);
},
.invalid_hex_escape => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"invalid hex digit: '{c}'",
.{raw_string[bad_index]},
);
},
.invalid_unicode_escape => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"invalid unicode digit: '{c}'",
.{raw_string[bad_index]},
);
},
.missing_matching_rbrace => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"missing matching '}}' character",
.{},
);
},
.expected_unicode_digits => |bad_index| {
return mod.failOff(
scope,
token_starts[token] + offset + @intCast(u32, bad_index),
"expected unicode digits after '\\u'",
.{},
);
},
}
}
pub fn unloadFile(mod: *Module, file_scope: *Scope.File) void {
if (file_scope.status == .unloaded_parse_failure) {
mod.failed_files.swapRemove(file_scope).?.value.destroy(mod.gpa);
}
file_scope.unload(mod.gpa);
} | src/Module.zig |
const std = @import("std");
const clap = @import("clap");
const mem = std.mem;
const io = std.io;
const json = std.json;
const path = std.os.path;
const Sha3_256 = std.crypto.Sha3_256;
const warn = std.debug.warn;
const Dir = std.os.Dir;
const Entry = std.os.Dir.Entry;
const base64 = std.base64.standard_encoder;
fn hashDir(allocator: *std.mem.Allocator, output_buf: *std.Buffer, full_path: []const u8) !void {
var buf = &try std.Buffer.init(allocator, "");
defer buf.deinit();
var stream = io.BufferOutStream.init(buf);
try walkTree(allocator, &stream.stream, full_path);
var h = Sha3_256.init();
var out: [Sha3_256.digest_length]u8 = undefined;
h.update(buf.toSlice());
h.final(out[0..]);
try output_buf.resize(std.base64.Base64Encoder.calcSize(out.len));
base64.encode(output_buf.toSlice(), out[0..]);
}
fn walkTree(allocator: *std.mem.Allocator, stream: var, full_path: []const u8) anyerror!void {
var dir = try Dir.open(allocator, full_path);
defer dir.close();
var full_entry_buf = std.ArrayList(u8).init(allocator);
defer full_entry_buf.deinit();
var h = Sha3_256.init();
var out: [Sha3_256.digest_length]u8 = undefined;
while (try dir.next()) |entry| {
if (entry.name[0] == '.' or mem.eql(u8, entry.name, "zig-cache")) {
continue;
}
try full_entry_buf.resize(full_path.len + entry.name.len + 1);
const full_entry_path = full_entry_buf.toSlice();
mem.copy(u8, full_entry_path, full_path);
full_entry_path[full_path.len] = path.sep;
mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name);
switch (entry.kind) {
Entry.Kind.File => {
const content = try io.readFileAlloc(allocator, full_entry_path);
errdefer allocator.free(content);
h.reset();
h.update(content);
h.final(out[0..]);
try stream.print("{x} {s}\n", out, full_entry_path);
allocator.free(content);
},
Entry.Kind.Directory => {
try walkTree(allocator, stream, full_entry_path);
},
else => {},
}
}
}
pub fn main() !void {
const stdout_file = try std.io.getStdOut();
var stdout_out_stream = stdout_file.outStream();
const stdout = &stdout_out_stream.stream;
var direct_allocator = std.heap.DirectAllocator.init();
const allocator = &direct_allocator.allocator;
defer direct_allocator.deinit();
// First we specify what parameters our program can take.
const params = comptime []clap.Param([]const u8){
clap.Param([]const u8).option(
"Base64 encoded hash of the directory",
clap.Names.both("hash"),
),
clap.Param([]const u8).flag(
"Verifies the hash provided by --hash flag against the directory",
clap.Names.both("verify"),
),
clap.Param([]const u8).flag(
"calculates and prints checksum of a directory",
clap.Names.both("sum"),
),
clap.Param([]const u8).positional("hash"),
clap.Param([]const u8).positional("verify"),
};
var os_iter = clap.args.OsIterator.init(allocator);
const iter = &os_iter.iter;
defer os_iter.deinit();
var buf = &try std.Buffer.init(allocator, "");
defer buf.deinit();
const exe = try iter.next();
var args = try clap.ComptimeClap([]const u8, params).parse(allocator, clap.args.OsIterator.Error, iter);
defer args.deinit();
if (args.flag("--sum")) {
const pos = args.positionals();
if (pos.len != 1) {
warn("missing dir path");
return;
}
try hashDir(allocator, buf, pos[0]);
warn("{}", buf.toSlice());
return;
}
if (args.flag("--verify")) {
const pos = args.positionals();
if (pos.len != 1) {
warn("missing dir path");
return;
}
var h = args.option("--hash");
if (h == null) {
warn("missing --hash flag value");
return;
}
try hashDir(allocator, buf, pos[0]);
if (buf.eql(h.?)) {
warn("pass");
} else {
warn("failed validation want {} got {}", h, buf.toSlice());
}
return;
}
return try clap.help(stdout, params);
} | src/main.zig |
const std = @import("../std.zig");
const builtin = std.builtin;
const io = std.io;
const testing = std.testing;
const assert = std.debug.assert;
const trait = std.meta.trait;
const meta = std.meta;
const math = std.math;
/// Creates a stream which allows for writing bit fields to another stream
pub fn BitWriter(endian: builtin.Endian, comptime WriterType: type) type {
return struct {
forward_writer: WriterType,
bit_buffer: u8,
bit_count: u4,
pub const Error = WriterType.Error;
pub const Writer = io.Writer(*Self, Error, write);
/// Deprecated: use `Writer`
pub const OutStream = io.OutStream(*Self, Error, write);
const Self = @This();
const u8_bit_count = comptime meta.bitCount(u8);
const u4_bit_count = comptime meta.bitCount(u4);
pub fn init(forward_writer: WriterType) Self {
return Self{
.forward_writer = forward_writer,
.bit_buffer = 0,
.bit_count = 0,
};
}
/// Write the specified number of bits to the stream from the least significant bits of
/// the specified unsigned int value. Bits will only be written to the stream when there
/// are enough to fill a byte.
pub fn writeBits(self: *Self, value: anytype, bits: usize) Error!void {
if (bits == 0) return;
const U = @TypeOf(value);
comptime assert(trait.isUnsignedInt(U));
//by extending the buffer to a minimum of u8 we can cover a number of edge cases
// related to shifting and casting.
const u_bit_count = comptime meta.bitCount(U);
const buf_bit_count = bc: {
assert(u_bit_count >= bits);
break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
};
const Buf = std.meta.Int(.unsigned, buf_bit_count);
const BufShift = math.Log2Int(Buf);
const buf_value = @intCast(Buf, value);
const high_byte_shift = @intCast(BufShift, buf_bit_count - u8_bit_count);
var in_buffer = switch (endian) {
.Big => buf_value << @intCast(BufShift, buf_bit_count - bits),
.Little => buf_value,
};
var in_bits = bits;
if (self.bit_count > 0) {
const bits_remaining = u8_bit_count - self.bit_count;
const n = @intCast(u3, if (bits_remaining > bits) bits else bits_remaining);
switch (endian) {
.Big => {
const shift = @intCast(BufShift, high_byte_shift + self.bit_count);
const v = @intCast(u8, in_buffer >> shift);
self.bit_buffer |= v;
in_buffer <<= n;
},
.Little => {
const v = @truncate(u8, in_buffer) << @intCast(u3, self.bit_count);
self.bit_buffer |= v;
in_buffer >>= n;
},
}
self.bit_count += n;
in_bits -= n;
//if we didn't fill the buffer, it's because bits < bits_remaining;
if (self.bit_count != u8_bit_count) return;
try self.forward_writer.writeByte(self.bit_buffer);
self.bit_buffer = 0;
self.bit_count = 0;
}
//at this point we know bit_buffer is empty
//copy bytes until we can't fill one anymore, then leave the rest in bit_buffer
while (in_bits >= u8_bit_count) {
switch (endian) {
.Big => {
const v = @intCast(u8, in_buffer >> high_byte_shift);
try self.forward_writer.writeByte(v);
in_buffer <<= @intCast(u3, u8_bit_count - 1);
in_buffer <<= 1;
},
.Little => {
const v = @truncate(u8, in_buffer);
try self.forward_writer.writeByte(v);
in_buffer >>= @intCast(u3, u8_bit_count - 1);
in_buffer >>= 1;
},
}
in_bits -= u8_bit_count;
}
if (in_bits > 0) {
self.bit_count = @intCast(u4, in_bits);
self.bit_buffer = switch (endian) {
.Big => @truncate(u8, in_buffer >> high_byte_shift),
.Little => @truncate(u8, in_buffer),
};
}
}
/// Flush any remaining bits to the stream.
pub fn flushBits(self: *Self) Error!void {
if (self.bit_count == 0) return;
try self.forward_writer.writeByte(self.bit_buffer);
self.bit_buffer = 0;
self.bit_count = 0;
}
pub fn write(self: *Self, buffer: []const u8) Error!usize {
// TODO: I'm not sure this is a good idea, maybe flushBits should be forced
if (self.bit_count > 0) {
for (buffer) |b, i|
try self.writeBits(b, u8_bit_count);
return buffer.len;
}
return self.forward_writer.write(buffer);
}
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
/// Deprecated: use `writer`
pub fn outStream(self: *Self) OutStream {
return .{ .context = self };
}
};
}
pub fn bitWriter(
comptime endian: builtin.Endian,
underlying_stream: anytype,
) BitWriter(endian, @TypeOf(underlying_stream)) {
return BitWriter(endian, @TypeOf(underlying_stream)).init(underlying_stream);
}
test "api coverage" {
var mem_be = [_]u8{0} ** 2;
var mem_le = [_]u8{0} ** 2;
var mem_out_be = io.fixedBufferStream(&mem_be);
var bit_stream_be = bitWriter(.Big, mem_out_be.writer());
try bit_stream_be.writeBits(@as(u2, 1), 1);
try bit_stream_be.writeBits(@as(u5, 2), 2);
try bit_stream_be.writeBits(@as(u128, 3), 3);
try bit_stream_be.writeBits(@as(u8, 4), 4);
try bit_stream_be.writeBits(@as(u9, 5), 5);
try bit_stream_be.writeBits(@as(u1, 1), 1);
testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_be.flushBits();
testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(@as(u32, 0b110011010000101), 16);
testing.expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
try bit_stream_be.writeBits(@as(u0, 0), 0);
var mem_out_le = io.fixedBufferStream(&mem_le);
var bit_stream_le = bitWriter(.Little, mem_out_le.writer());
try bit_stream_le.writeBits(@as(u2, 1), 1);
try bit_stream_le.writeBits(@as(u5, 2), 2);
try bit_stream_le.writeBits(@as(u128, 3), 3);
try bit_stream_le.writeBits(@as(u8, 4), 4);
try bit_stream_le.writeBits(@as(u9, 5), 5);
try bit_stream_le.writeBits(@as(u1, 1), 1);
testing.expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_le.flushBits();
testing.expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(@as(u32, 0b1100110100001011), 16);
testing.expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
try bit_stream_le.writeBits(@as(u0, 0), 0);
} | lib/std/io/bit_writer.zig |
const std = @import("std");
const leb = std.leb;
const macho = std.macho;
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
pub const ExternSymbol = struct {
/// Symbol name.
/// We own the memory, therefore we'll need to free it by calling `deinit`.
/// In self-hosted, we don't expect it to be null ever.
/// However, this is for backwards compatibility with LLD when
/// we'll be patching things up post mortem.
name: ?[]u8 = null,
/// Id of the dynamic library where the specified entries can be found.
/// Id of 0 means self.
/// TODO this should really be an id into the table of all defined
/// dylibs.
dylib_ordinal: i64 = 0,
/// Id of the segment where this symbol is defined (will have its address
/// resolved).
segment: u16 = 0,
/// Offset relative to the start address of the `segment`.
offset: u32 = 0,
pub fn deinit(self: *ExternSymbol, allocator: *Allocator) void {
if (self.name) |name| {
allocator.free(name);
}
}
};
pub fn rebaseInfoSize(symbols: []*const ExternSymbol) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (symbols) |symbol| {
size += 2;
try leb.writeILEB128(writer, symbol.offset);
size += 1;
}
size += 1 + stream.bytes_written;
return size;
}
pub fn writeRebaseInfo(symbols: []*const ExternSymbol, writer: anytype) !void {
for (symbols) |symbol| {
try writer.writeByte(macho.REBASE_OPCODE_SET_TYPE_IMM | @truncate(u4, macho.REBASE_TYPE_POINTER));
try writer.writeByte(macho.REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, symbol.segment));
try leb.writeILEB128(writer, symbol.offset);
try writer.writeByte(macho.REBASE_OPCODE_DO_REBASE_IMM_TIMES | @truncate(u4, 1));
}
try writer.writeByte(macho.REBASE_OPCODE_DONE);
}
pub fn bindInfoSize(symbols: []*const ExternSymbol) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (symbols) |symbol| {
size += 1;
if (symbol.dylib_ordinal > 15) {
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
}
size += 1;
if (symbol.name) |name| {
size += 1;
size += name.len;
size += 1;
}
size += 1;
try leb.writeILEB128(writer, symbol.offset);
size += 2;
}
size += stream.bytes_written;
return size;
}
pub fn writeBindInfo(symbols: []*const ExternSymbol, writer: anytype) !void {
for (symbols) |symbol| {
if (symbol.dylib_ordinal > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
} else if (symbol.dylib_ordinal > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
}
try writer.writeByte(macho.BIND_OPCODE_SET_TYPE_IMM | @truncate(u4, macho.BIND_TYPE_POINTER));
if (symbol.name) |name| {
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(name);
try writer.writeByte(0);
}
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, symbol.segment));
try leb.writeILEB128(writer, symbol.offset);
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
}
pub fn lazyBindInfoSize(symbols: []*const ExternSymbol) !u64 {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: u64 = 0;
for (symbols) |symbol| {
size += 1;
try leb.writeILEB128(writer, symbol.offset);
size += 1;
if (symbol.dylib_ordinal > 15) {
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
}
if (symbol.name) |name| {
size += 1;
size += name.len;
size += 1;
}
size += 2;
}
size += stream.bytes_written;
return size;
}
pub fn writeLazyBindInfo(symbols: []*const ExternSymbol, writer: anytype) !void {
for (symbols) |symbol| {
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, symbol.segment));
try leb.writeILEB128(writer, symbol.offset);
if (symbol.dylib_ordinal > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
} else if (symbol.dylib_ordinal > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
}
if (symbol.name) |name| {
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(name);
try writer.writeByte(0);
}
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
} | src/link/MachO/imports.zig |
const std = @import("index.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const AtomicRmwOp = builtin.AtomicRmwOp;
const AtomicOrder = builtin.AtomicOrder;
/// Thread-safe initialization of global data.
/// TODO use a mutex instead of a spinlock
pub fn lazyInit(comptime T: type) LazyInit(T) {
return LazyInit(T){
.data = undefined,
.state = 0,
};
}
fn LazyInit(comptime T: type) type {
return struct {
state: u8, // TODO make this an enum
data: Data,
const Self = this;
// TODO this isn't working for void, investigate and then remove this special case
const Data = if (@sizeOf(T) == 0) u8 else T;
const Ptr = if (T == void) void else *T;
/// Returns a usable pointer to the initialized data,
/// or returns null, indicating that the caller should
/// perform the initialization and then call resolve().
pub fn get(self: *Self) ?Ptr {
while (true) {
var state = @cmpxchgWeak(u8, &self.state, 0, 1, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return null;
switch (state) {
0 => continue,
1 => {
// TODO mutex instead of a spinlock
continue;
},
2 => {
if (@sizeOf(T) == 0) {
return T(undefined);
} else {
return &self.data;
}
},
else => unreachable,
}
}
}
pub fn resolve(self: *Self) void {
const prev = @atomicRmw(u8, &self.state, AtomicRmwOp.Xchg, 2, AtomicOrder.SeqCst);
assert(prev == 1); // resolve() called twice
}
};
}
var global_number = lazyInit(i32);
test "std.lazyInit" {
if (global_number.get()) |_| @panic("bad") else {
global_number.data = 1234;
global_number.resolve();
}
if (global_number.get()) |x| {
assert(x.* == 1234);
} else {
@panic("bad");
}
if (global_number.get()) |x| {
assert(x.* == 1234);
} else {
@panic("bad");
}
}
var global_void = lazyInit(void);
test "std.lazyInit(void)" {
if (global_void.get()) |_| @panic("bad") else {
global_void.resolve();
}
assert(global_void.get() != null);
assert(global_void.get() != null);
} | std/lazy_init.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const info = std.log.info;
const print = std.debug.print;
const fmt = std.fmt;
const utils = @import("utils.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const Waypoint = struct {
y: isize,
x: isize,
pub fn swap(self: *Waypoint) void {
const tmp = self.x;
self.x = self.y;
self.y = tmp;
}
};
const Action = union(enum) {
l: isize,
r: isize,
n: isize,
s: isize,
e: isize,
w: isize,
f: isize,
pub fn fromLine(line: []const u8) Action {
const name = line[0];
const val = fmt.parseInt(isize, line[1..line.len], 10) catch unreachable;
return switch (name) {
'L' => Action{ .l = val },
'R' => Action{ .r = val },
'N' => Action{ .n = val },
'S' => Action{ .s = val },
'E' => Action{ .e = val },
'W' => Action{ .w = val },
'F' => Action{ .f = val },
else => unreachable,
};
}
};
const Ship = struct {
y: isize = 0,
x: isize = 0,
facing: isize = 90,
waypoint: ?Waypoint = undefined,
pub fn init(x: isize, y: isize, facing: isize, waypoint: ?Waypoint) Ship {
return Ship{
.y = y,
.x = x,
.facing = facing,
.waypoint = waypoint,
};
}
pub fn move(self: *Ship, action: Action) void {
if (self.waypoint) |*waypoint| {
// move the ship and waypoint as in p2
return switch (action) {
.l => |val| self.move(Action{ .r = 360 - val }),
.r => |val| {
if (val != 0) {
// fix sign
const x = waypoint.x;
const y = waypoint.y;
waypoint.swap();
waypoint.x = -waypoint.x;
// rotate 90 degrees right
self.move(Action{ .r = val - 90 });
}
},
.n => |val| waypoint.y -= val,
.s => |val| waypoint.y += val,
.e => |val| waypoint.x += val,
.w => |val| waypoint.x -= val,
.f => |val| {
self.x += waypoint.x * val;
self.y += waypoint.y * val;
},
};
} else {
// just move the ship as in p1
return switch (action) {
.l => |val| self.facing = @mod(self.facing - val, 360),
.r => |val| self.facing = @mod(self.facing + val, 360),
.n => |val| self.y -= val,
.s => |val| self.y += val,
.e => |val| self.x += val,
.w => |val| self.x -= val,
.f => |val| {
switch (self.facing) {
0 => self.y -= val,
90 => self.x += val,
180 => self.y += val,
270 => self.x -= val,
else => unreachable,
}
},
};
}
info("ship now at: y: {} x: {} [facing {}]", .{ self.y, self.x, self.facing });
}
pub fn distanceFrom(self: Ship, y: isize, x: isize) isize {
const a = self.y - y;
const b = self.x - x;
const aa = if (a >= 0) a else -a;
const bb = if (b >= 0) b else -b;
return aa + bb;
}
};
pub fn main() !void {
const begin = @divTrunc(std.time.nanoTimestamp(), 1000);
// setup
//
defer _ = gpa.deinit();
var allo = &gpa.allocator;
var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1");
defer allo.free(lines.buffer);
// p1
var ship1 = Ship.init(0, 0, 90, null);
var ship2 = Ship.init(0, 0, 90, Waypoint{
.x = 10,
.y = -1,
});
while (lines.next()) |line| {
const action = Action.fromLine(line);
ship1.move(action);
ship2.move(action);
}
print("p1: {}\n", .{ship1.distanceFrom(0, 0)});
print("p2: {}\n", .{ship2.distanceFrom(0, 0)});
const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin;
print("all done in {} microseconds\n", .{delta});
} | day_12/src/main.zig |
const std = @import("std");
const panic = std.debug.panic;
const c = @import("c.zig");
const window_width = 800;
const window_height = 600;
const window_title = "Furious Fowls";
// GLFW error callback.
fn errorCallback(err: c_int, description: [*c]const u8) callconv(.C) void {
panic("Error: {}\n", .{@as([*:0]const u8, description)});
}
pub fn main() !void {
// Set up GLFW and the window.
_ = c.glfwSetErrorCallback(errorCallback);
if (c.glfwInit() == c.GLFW_FALSE) {
panic("GLFW init failure\n", .{});
}
defer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CLIENT_API, c.GLFW_NO_API);
c.glfwWindowHint(c.GLFW_RESIZABLE, c.GLFW_FALSE);
const window = c.glfwCreateWindow(window_width, window_height, window_title, null, null);
if (window == null) {
panic("GLFW window failure\n", .{});
}
defer c.glfwDestroyWindow(window);
// Set up BGFX and the renderer.
const platform_data = c.getPlatformData(window);
c.bgfx_set_platform_data(&platform_data);
var init: c.bgfx_init_t = undefined;
c.bgfx_init_ctor(&init);
if (!c.bgfx_init(&init)) {
panic("BGFX init failure\n", .{});
}
defer c.bgfx_shutdown();
c.bgfx_reset(window_width, window_height, c.BGFX_RESET_VSYNC, init.resolution.format);
c.bgfx_set_debug(c.BGFX_DEBUG_TEXT);
c.bgfx_set_view_clear(0, c.BGFX_CLEAR_COLOR | c.BGFX_CLEAR_DEPTH, 0x303030ff, 1.0, 0);
c.bgfx_set_view_rect(0, 0, 0, window_width, window_height);
var i: i32 = 0;
while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) {
c.glfwWaitEventsTimeout(0.1);
// set view 0 default viewport.
c.bgfx_set_view_rect(0, 0, 0, window_width, window_height);
// this dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
var encoder = c.bgfx_encoder_begin(true);
c.bgfx_encoder_touch(encoder, 0);
c.bgfx_encoder_end(encoder);
// use debug font to print information about this example.
c.bgfx_dbg_text_clear(0, false);
c.bgfx_dbg_text_printf(0, 1, 0x0f, "color can be changed with ansi \x1b[9;me\x1b[10;ms\x1b[11;mc\x1b[12;ma\x1b[13;mp\x1b[14;me\x1b[0m code too.");
c.bgfx_dbg_text_printf(80, 1, 0x0f, "\x1b[;0m \x1b[;1m \x1b[; 2m \x1b[; 3m \x1b[; 4m \x1b[; 5m \x1b[; 6m \x1b[; 7m \x1b[0m");
c.bgfx_dbg_text_printf(80, 2, 0x0f, "\x1b[;8m \x1b[;9m \x1b[;10m \x1b[;11m \x1b[;12m \x1b[;13m \x1b[;14m \x1b[;15m \x1b[0m");
c.bgfx_dbg_text_printf(0, 3, 0x1f, "bgfx/examples/25-c99");
var buf: [128]u8 = undefined;
const str = std.fmt.bufPrintZ(&buf, "description: initialization and debug text with c99 api. Frame: {}", .{i}) catch unreachable;
c.bgfx_dbg_text_printf(0, 4, 0x3f, str);
i += 1;
// advance to next frame. rendering thread will be kicked to
// process submitted rendering primitives.
_ = c.bgfx_frame(false);
}
}
test "It works" {
std.debug.assert(1 + 1 == 3);
} | src/main.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const mem = std.mem;
const meta = std.meta;
const ast = std.zig.ast;
const Token = std.zig.Token;
const indent_delta = 4;
const asm_indent_delta = 2;
pub const Error = error{
/// Ran out of memory allocating call stack frames to complete rendering.
OutOfMemory,
};
/// Returns whether anything changed
pub fn render(allocator: *mem.Allocator, stream: anytype, tree: *ast.Tree) (@TypeOf(stream).Error || Error)!bool {
// cannot render an invalid tree
std.debug.assert(tree.errors.len == 0);
var change_detection_stream = std.io.changeDetectionStream(tree.source, stream);
var auto_indenting_stream = std.io.autoIndentingStream(indent_delta, change_detection_stream.writer());
try renderRoot(allocator, &auto_indenting_stream, tree);
return change_detection_stream.changeDetected();
}
fn renderRoot(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
) (@TypeOf(ais.*).Error || Error)!void {
// render all the line comments at the beginning of the file
for (tree.token_ids) |token_id, i| {
if (token_id != .LineComment) break;
const token_loc = tree.token_locs[i];
try ais.writer().print("{s}\n", .{mem.trimRight(u8, tree.tokenSliceLoc(token_loc), " ")});
const next_token = tree.token_locs[i + 1];
const loc = tree.tokenLocationLoc(token_loc.end, next_token);
if (loc.line >= 2) {
try ais.insertNewline();
}
}
var decl_i: ast.NodeIndex = 0;
const root_decls = tree.root_node.decls();
if (root_decls.len == 0) return;
while (true) {
var decl = root_decls[decl_i];
// This loop does the following:
//
// - Iterates through line/doc comment tokens that precedes the current
// decl.
// - Figures out the first token index (`copy_start_token_index`) which
// hasn't been copied to the output stream yet.
// - Detects `zig fmt: (off|on)` in the line comment tokens, and
// determines whether the current decl should be reformatted or not.
//
var token_index = decl.firstToken();
var fmt_active = true;
var found_fmt_directive = false;
var copy_start_token_index = token_index;
while (token_index != 0) {
token_index -= 1;
const token_id = tree.token_ids[token_index];
switch (token_id) {
.LineComment => {},
.DocComment => {
copy_start_token_index = token_index;
continue;
},
else => break,
}
const token_loc = tree.token_locs[token_index];
if (mem.eql(u8, mem.trim(u8, tree.tokenSliceLoc(token_loc)[2..], " "), "zig fmt: off")) {
if (!found_fmt_directive) {
fmt_active = false;
found_fmt_directive = true;
}
} else if (mem.eql(u8, mem.trim(u8, tree.tokenSliceLoc(token_loc)[2..], " "), "zig fmt: on")) {
if (!found_fmt_directive) {
fmt_active = true;
found_fmt_directive = true;
}
}
}
if (!fmt_active) {
// Reformatting is disabled for the current decl and possibly some
// more decls that follow.
// Find the next `decl` for which reformatting is re-enabled.
token_index = decl.firstToken();
while (!fmt_active) {
decl_i += 1;
if (decl_i >= root_decls.len) {
// If there's no next reformatted `decl`, just copy the
// remaining input tokens and bail out.
const start = tree.token_locs[copy_start_token_index].start;
try copyFixingWhitespace(ais, tree.source[start..]);
return;
}
decl = root_decls[decl_i];
var decl_first_token_index = decl.firstToken();
while (token_index < decl_first_token_index) : (token_index += 1) {
const token_id = tree.token_ids[token_index];
switch (token_id) {
.LineComment => {},
.Eof => unreachable,
else => continue,
}
const token_loc = tree.token_locs[token_index];
if (mem.eql(u8, mem.trim(u8, tree.tokenSliceLoc(token_loc)[2..], " "), "zig fmt: on")) {
fmt_active = true;
} else if (mem.eql(u8, mem.trim(u8, tree.tokenSliceLoc(token_loc)[2..], " "), "zig fmt: off")) {
fmt_active = false;
}
}
}
// Found the next `decl` for which reformatting is enabled. Copy
// the input tokens before the `decl` that haven't been copied yet.
var copy_end_token_index = decl.firstToken();
token_index = copy_end_token_index;
while (token_index != 0) {
token_index -= 1;
const token_id = tree.token_ids[token_index];
switch (token_id) {
.LineComment => {},
.DocComment => {
copy_end_token_index = token_index;
continue;
},
else => break,
}
}
const start = tree.token_locs[copy_start_token_index].start;
const end = tree.token_locs[copy_end_token_index].start;
try copyFixingWhitespace(ais, tree.source[start..end]);
}
try renderTopLevelDecl(allocator, ais, tree, decl);
decl_i += 1;
if (decl_i >= root_decls.len) return;
try renderExtraNewline(tree, ais, root_decls[decl_i]);
}
}
fn renderExtraNewline(tree: *ast.Tree, ais: anytype, node: *ast.Node) @TypeOf(ais.*).Error!void {
return renderExtraNewlineToken(tree, ais, node.firstToken());
}
fn renderExtraNewlineToken(
tree: *ast.Tree,
ais: anytype,
first_token: ast.TokenIndex,
) @TypeOf(ais.*).Error!void {
var prev_token = first_token;
if (prev_token == 0) return;
var newline_threshold: usize = 2;
while (tree.token_ids[prev_token - 1] == .DocComment) {
if (tree.tokenLocation(tree.token_locs[prev_token - 1].end, prev_token).line == 1) {
newline_threshold += 1;
}
prev_token -= 1;
}
const prev_token_end = tree.token_locs[prev_token - 1].end;
const loc = tree.tokenLocation(prev_token_end, first_token);
if (loc.line >= newline_threshold) {
try ais.insertNewline();
}
}
fn renderTopLevelDecl(allocator: *mem.Allocator, ais: anytype, tree: *ast.Tree, decl: *ast.Node) (@TypeOf(ais.*).Error || Error)!void {
try renderContainerDecl(allocator, ais, tree, decl, .Newline);
}
fn renderContainerDecl(allocator: *mem.Allocator, ais: anytype, tree: *ast.Tree, decl: *ast.Node, space: Space) (@TypeOf(ais.*).Error || Error)!void {
switch (decl.tag) {
.FnProto => {
const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);
try renderDocComments(tree, ais, fn_proto, fn_proto.getDocComments());
if (fn_proto.getBodyNode()) |body_node| {
try renderExpression(allocator, ais, tree, decl, .Space);
try renderExpression(allocator, ais, tree, body_node, space);
} else {
try renderExpression(allocator, ais, tree, decl, .None);
try renderToken(tree, ais, tree.nextToken(decl.lastToken()), space);
}
},
.Use => {
const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl);
if (use_decl.visib_token) |visib_token| {
try renderToken(tree, ais, visib_token, .Space); // pub
}
try renderToken(tree, ais, use_decl.use_token, .Space); // usingnamespace
try renderExpression(allocator, ais, tree, use_decl.expr, .None);
try renderToken(tree, ais, use_decl.semicolon_token, space); // ;
},
.VarDecl => {
const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl);
try renderDocComments(tree, ais, var_decl, var_decl.getDocComments());
try renderVarDecl(allocator, ais, tree, var_decl);
},
.TestDecl => {
const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl);
try renderDocComments(tree, ais, test_decl, test_decl.doc_comments);
try renderToken(tree, ais, test_decl.test_token, .Space);
if (test_decl.name) |name|
try renderExpression(allocator, ais, tree, name, .Space);
try renderExpression(allocator, ais, tree, test_decl.body_node, space);
},
.ContainerField => {
const field = @fieldParentPtr(ast.Node.ContainerField, "base", decl);
try renderDocComments(tree, ais, field, field.doc_comments);
if (field.comptime_token) |t| {
try renderToken(tree, ais, t, .Space); // comptime
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.nextToken(field.lastToken());
break :blk tree.token_ids[maybe_comma] == .Comma;
};
// The trailing comma is emitted at the end, but if it's not present
// we still have to respect the specified `space` parameter
const last_token_space: Space = if (src_has_trailing_comma) .None else space;
if (field.type_expr == null and field.value_expr == null) {
try renderToken(tree, ais, field.name_token, last_token_space); // name
} else if (field.type_expr != null and field.value_expr == null) {
try renderToken(tree, ais, field.name_token, .None); // name
try renderToken(tree, ais, tree.nextToken(field.name_token), .Space); // :
if (field.align_expr) |align_value_expr| {
try renderExpression(allocator, ais, tree, field.type_expr.?, .Space); // type
const lparen_token = tree.prevToken(align_value_expr.firstToken());
const align_kw = tree.prevToken(lparen_token);
const rparen_token = tree.nextToken(align_value_expr.lastToken());
try renderToken(tree, ais, align_kw, .None); // align
try renderToken(tree, ais, lparen_token, .None); // (
try renderExpression(allocator, ais, tree, align_value_expr, .None); // alignment
try renderToken(tree, ais, rparen_token, last_token_space); // )
} else {
try renderExpression(allocator, ais, tree, field.type_expr.?, last_token_space); // type
}
} else if (field.type_expr == null and field.value_expr != null) {
try renderToken(tree, ais, field.name_token, .Space); // name
try renderToken(tree, ais, tree.nextToken(field.name_token), .Space); // =
try renderExpression(allocator, ais, tree, field.value_expr.?, last_token_space); // value
} else {
try renderToken(tree, ais, field.name_token, .None); // name
try renderToken(tree, ais, tree.nextToken(field.name_token), .Space); // :
if (field.align_expr) |align_value_expr| {
try renderExpression(allocator, ais, tree, field.type_expr.?, .Space); // type
const lparen_token = tree.prevToken(align_value_expr.firstToken());
const align_kw = tree.prevToken(lparen_token);
const rparen_token = tree.nextToken(align_value_expr.lastToken());
try renderToken(tree, ais, align_kw, .None); // align
try renderToken(tree, ais, lparen_token, .None); // (
try renderExpression(allocator, ais, tree, align_value_expr, .None); // alignment
try renderToken(tree, ais, rparen_token, .Space); // )
} else {
try renderExpression(allocator, ais, tree, field.type_expr.?, .Space); // type
}
try renderToken(tree, ais, tree.prevToken(field.value_expr.?.firstToken()), .Space); // =
try renderExpression(allocator, ais, tree, field.value_expr.?, last_token_space); // value
}
if (src_has_trailing_comma) {
const comma = tree.nextToken(field.lastToken());
try renderToken(tree, ais, comma, space);
}
},
.Comptime => {
assert(!decl.requireSemiColon());
try renderExpression(allocator, ais, tree, decl, space);
},
.DocComment => {
const comment = @fieldParentPtr(ast.Node.DocComment, "base", decl);
const kind = tree.token_ids[comment.first_line];
try renderToken(tree, ais, comment.first_line, .Newline);
var tok_i = comment.first_line + 1;
while (true) : (tok_i += 1) {
const tok_id = tree.token_ids[tok_i];
if (tok_id == kind) {
try renderToken(tree, ais, tok_i, .Newline);
} else if (tok_id == .LineComment) {
continue;
} else {
break;
}
}
},
else => unreachable,
}
}
fn renderExpression(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
base: *ast.Node,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
switch (base.tag) {
.Identifier,
.IntegerLiteral,
.FloatLiteral,
.StringLiteral,
.CharLiteral,
.BoolLiteral,
.NullLiteral,
.Unreachable,
.ErrorType,
.UndefinedLiteral,
=> {
const casted_node = base.cast(ast.Node.OneToken).?;
return renderToken(tree, ais, casted_node.token, space);
},
.AnyType => {
const any_type = base.castTag(.AnyType).?;
if (mem.eql(u8, tree.tokenSlice(any_type.token), "var")) {
// TODO remove in next release cycle
try ais.writer().writeAll("anytype");
if (space == .Comma) try ais.writer().writeAll(",\n");
return;
}
return renderToken(tree, ais, any_type.token, space);
},
.Block, .LabeledBlock => {
const block: struct {
label: ?ast.TokenIndex,
statements: []*ast.Node,
lbrace: ast.TokenIndex,
rbrace: ast.TokenIndex,
} = b: {
if (base.castTag(.Block)) |block| {
break :b .{
.label = null,
.statements = block.statements(),
.lbrace = block.lbrace,
.rbrace = block.rbrace,
};
} else if (base.castTag(.LabeledBlock)) |block| {
break :b .{
.label = block.label,
.statements = block.statements(),
.lbrace = block.lbrace,
.rbrace = block.rbrace,
};
} else {
unreachable;
}
};
if (block.label) |label| {
try renderToken(tree, ais, label, Space.None);
try renderToken(tree, ais, tree.nextToken(label), Space.Space);
}
if (block.statements.len == 0) {
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, block.lbrace, Space.None);
} else {
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, block.lbrace, Space.Newline);
for (block.statements) |statement, i| {
try renderStatement(allocator, ais, tree, statement);
if (i + 1 < block.statements.len) {
try renderExtraNewline(tree, ais, block.statements[i + 1]);
}
}
}
return renderToken(tree, ais, block.rbrace, space);
},
.Defer => {
const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base);
try renderToken(tree, ais, defer_node.defer_token, Space.Space);
if (defer_node.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
return renderExpression(allocator, ais, tree, defer_node.expr, space);
},
.Comptime => {
const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base);
try renderToken(tree, ais, comptime_node.comptime_token, Space.Space);
return renderExpression(allocator, ais, tree, comptime_node.expr, space);
},
.Nosuspend => {
const nosuspend_node = @fieldParentPtr(ast.Node.Nosuspend, "base", base);
if (mem.eql(u8, tree.tokenSlice(nosuspend_node.nosuspend_token), "noasync")) {
// TODO: remove this
try ais.writer().writeAll("nosuspend ");
} else {
try renderToken(tree, ais, nosuspend_node.nosuspend_token, Space.Space);
}
return renderExpression(allocator, ais, tree, nosuspend_node.expr, space);
},
.Suspend => {
const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base);
if (suspend_node.body) |body| {
try renderToken(tree, ais, suspend_node.suspend_token, Space.Space);
return renderExpression(allocator, ais, tree, body, space);
} else {
return renderToken(tree, ais, suspend_node.suspend_token, space);
}
},
.Catch => {
const infix_op_node = @fieldParentPtr(ast.Node.Catch, "base", base);
const op_space = Space.Space;
try renderExpression(allocator, ais, tree, infix_op_node.lhs, op_space);
const after_op_space = blk: {
const same_line = tree.tokensOnSameLine(infix_op_node.op_token, tree.nextToken(infix_op_node.op_token));
break :blk if (same_line) op_space else Space.Newline;
};
try renderToken(tree, ais, infix_op_node.op_token, after_op_space);
if (infix_op_node.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
ais.pushIndentOneShot();
return renderExpression(allocator, ais, tree, infix_op_node.rhs, space);
},
.Add,
.AddWrap,
.ArrayCat,
.ArrayMult,
.Assign,
.AssignBitAnd,
.AssignBitOr,
.AssignBitShiftLeft,
.AssignBitShiftRight,
.AssignBitXor,
.AssignDiv,
.AssignSub,
.AssignSubWrap,
.AssignMod,
.AssignAdd,
.AssignAddWrap,
.AssignMul,
.AssignMulWrap,
.BangEqual,
.BitAnd,
.BitOr,
.BitShiftLeft,
.BitShiftRight,
.BitXor,
.BoolAnd,
.BoolOr,
.Div,
.EqualEqual,
.ErrorUnion,
.GreaterOrEqual,
.GreaterThan,
.LessOrEqual,
.LessThan,
.MergeErrorSets,
.Mod,
.Mul,
.MulWrap,
.Period,
.Range,
.Sub,
.SubWrap,
.OrElse,
=> {
const infix_op_node = @fieldParentPtr(ast.Node.SimpleInfixOp, "base", base);
const op_space = switch (base.tag) {
.Period, .ErrorUnion, .Range => Space.None,
else => Space.Space,
};
try renderExpression(allocator, ais, tree, infix_op_node.lhs, op_space);
const after_op_space = blk: {
const loc = tree.tokenLocation(tree.token_locs[infix_op_node.op_token].end, tree.nextToken(infix_op_node.op_token));
break :blk if (loc.line == 0) op_space else Space.Newline;
};
{
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, infix_op_node.op_token, after_op_space);
}
ais.pushIndentOneShot();
return renderExpression(allocator, ais, tree, infix_op_node.rhs, space);
},
.BitNot,
.BoolNot,
.Negation,
.NegationWrap,
.OptionalType,
.AddressOf,
=> {
const casted_node = @fieldParentPtr(ast.Node.SimplePrefixOp, "base", base);
try renderToken(tree, ais, casted_node.op_token, Space.None);
return renderExpression(allocator, ais, tree, casted_node.rhs, space);
},
.Try,
.Resume,
.Await,
=> {
const casted_node = @fieldParentPtr(ast.Node.SimplePrefixOp, "base", base);
try renderToken(tree, ais, casted_node.op_token, Space.Space);
return renderExpression(allocator, ais, tree, casted_node.rhs, space);
},
.ArrayType => {
const array_type = @fieldParentPtr(ast.Node.ArrayType, "base", base);
return renderArrayType(
allocator,
ais,
tree,
array_type.op_token,
array_type.rhs,
array_type.len_expr,
null,
space,
);
},
.ArrayTypeSentinel => {
const array_type = @fieldParentPtr(ast.Node.ArrayTypeSentinel, "base", base);
return renderArrayType(
allocator,
ais,
tree,
array_type.op_token,
array_type.rhs,
array_type.len_expr,
array_type.sentinel,
space,
);
},
.PtrType => {
const ptr_type = @fieldParentPtr(ast.Node.PtrType, "base", base);
const op_tok_id = tree.token_ids[ptr_type.op_token];
switch (op_tok_id) {
.Asterisk, .AsteriskAsterisk => try ais.writer().writeByte('*'),
.LBracket => if (tree.token_ids[ptr_type.op_token + 2] == .Identifier)
try ais.writer().writeAll("[*c")
else
try ais.writer().writeAll("[*"),
else => unreachable,
}
if (ptr_type.ptr_info.sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, ais, colon_token, Space.None); // :
const sentinel_space = switch (op_tok_id) {
.LBracket => Space.None,
else => Space.Space,
};
try renderExpression(allocator, ais, tree, sentinel, sentinel_space);
}
switch (op_tok_id) {
.Asterisk, .AsteriskAsterisk => {},
.LBracket => try ais.writer().writeByte(']'),
else => unreachable,
}
if (ptr_type.ptr_info.allowzero_token) |allowzero_token| {
try renderToken(tree, ais, allowzero_token, Space.Space); // allowzero
}
if (ptr_type.ptr_info.align_info) |align_info| {
const lparen_token = tree.prevToken(align_info.node.firstToken());
const align_token = tree.prevToken(lparen_token);
try renderToken(tree, ais, align_token, Space.None); // align
try renderToken(tree, ais, lparen_token, Space.None); // (
try renderExpression(allocator, ais, tree, align_info.node, Space.None);
if (align_info.bit_range) |bit_range| {
const colon1 = tree.prevToken(bit_range.start.firstToken());
const colon2 = tree.prevToken(bit_range.end.firstToken());
try renderToken(tree, ais, colon1, Space.None); // :
try renderExpression(allocator, ais, tree, bit_range.start, Space.None);
try renderToken(tree, ais, colon2, Space.None); // :
try renderExpression(allocator, ais, tree, bit_range.end, Space.None);
const rparen_token = tree.nextToken(bit_range.end.lastToken());
try renderToken(tree, ais, rparen_token, Space.Space); // )
} else {
const rparen_token = tree.nextToken(align_info.node.lastToken());
try renderToken(tree, ais, rparen_token, Space.Space); // )
}
}
if (ptr_type.ptr_info.const_token) |const_token| {
try renderToken(tree, ais, const_token, Space.Space); // const
}
if (ptr_type.ptr_info.volatile_token) |volatile_token| {
try renderToken(tree, ais, volatile_token, Space.Space); // volatile
}
return renderExpression(allocator, ais, tree, ptr_type.rhs, space);
},
.SliceType => {
const slice_type = @fieldParentPtr(ast.Node.SliceType, "base", base);
try renderToken(tree, ais, slice_type.op_token, Space.None); // [
if (slice_type.ptr_info.sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, ais, colon_token, Space.None); // :
try renderExpression(allocator, ais, tree, sentinel, Space.None);
try renderToken(tree, ais, tree.nextToken(sentinel.lastToken()), Space.None); // ]
} else {
try renderToken(tree, ais, tree.nextToken(slice_type.op_token), Space.None); // ]
}
if (slice_type.ptr_info.allowzero_token) |allowzero_token| {
try renderToken(tree, ais, allowzero_token, Space.Space); // allowzero
}
if (slice_type.ptr_info.align_info) |align_info| {
const lparen_token = tree.prevToken(align_info.node.firstToken());
const align_token = tree.prevToken(lparen_token);
try renderToken(tree, ais, align_token, Space.None); // align
try renderToken(tree, ais, lparen_token, Space.None); // (
try renderExpression(allocator, ais, tree, align_info.node, Space.None);
if (align_info.bit_range) |bit_range| {
const colon1 = tree.prevToken(bit_range.start.firstToken());
const colon2 = tree.prevToken(bit_range.end.firstToken());
try renderToken(tree, ais, colon1, Space.None); // :
try renderExpression(allocator, ais, tree, bit_range.start, Space.None);
try renderToken(tree, ais, colon2, Space.None); // :
try renderExpression(allocator, ais, tree, bit_range.end, Space.None);
const rparen_token = tree.nextToken(bit_range.end.lastToken());
try renderToken(tree, ais, rparen_token, Space.Space); // )
} else {
const rparen_token = tree.nextToken(align_info.node.lastToken());
try renderToken(tree, ais, rparen_token, Space.Space); // )
}
}
if (slice_type.ptr_info.const_token) |const_token| {
try renderToken(tree, ais, const_token, Space.Space);
}
if (slice_type.ptr_info.volatile_token) |volatile_token| {
try renderToken(tree, ais, volatile_token, Space.Space);
}
return renderExpression(allocator, ais, tree, slice_type.rhs, space);
},
.ArrayInitializer, .ArrayInitializerDot => {
var rtoken: ast.TokenIndex = undefined;
var exprs: []*ast.Node = undefined;
const lhs: union(enum) { dot: ast.TokenIndex, node: *ast.Node } = switch (base.tag) {
.ArrayInitializerDot => blk: {
const casted = @fieldParentPtr(ast.Node.ArrayInitializerDot, "base", base);
rtoken = casted.rtoken;
exprs = casted.list();
break :blk .{ .dot = casted.dot };
},
.ArrayInitializer => blk: {
const casted = @fieldParentPtr(ast.Node.ArrayInitializer, "base", base);
rtoken = casted.rtoken;
exprs = casted.list();
break :blk .{ .node = casted.lhs };
},
else => unreachable,
};
const lbrace = switch (lhs) {
.dot => |dot| tree.nextToken(dot),
.node => |node| tree.nextToken(node.lastToken()),
};
switch (lhs) {
.dot => |dot| try renderToken(tree, ais, dot, Space.None),
.node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
}
if (exprs.len == 0) {
try renderToken(tree, ais, lbrace, Space.None);
return renderToken(tree, ais, rtoken, space);
}
if (exprs.len == 1 and exprs[0].tag != .MultilineStringLiteral and tree.token_ids[exprs[0].*.lastToken() + 1] == .RBrace) {
const expr = exprs[0];
try renderToken(tree, ais, lbrace, Space.None);
try renderExpression(allocator, ais, tree, expr, Space.None);
return renderToken(tree, ais, rtoken, space);
}
// scan to find row size
if (rowSize(tree, exprs, rtoken) != null) {
{
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, lbrace, Space.Newline);
var expr_index: usize = 0;
while (rowSize(tree, exprs[expr_index..], rtoken)) |row_size| {
const row_exprs = exprs[expr_index..];
// A place to store the width of each expression and its column's maximum
var widths = try allocator.alloc(usize, row_exprs.len + row_size);
defer allocator.free(widths);
mem.set(usize, widths, 0);
var expr_newlines = try allocator.alloc(bool, row_exprs.len);
defer allocator.free(expr_newlines);
mem.set(bool, expr_newlines, false);
var expr_widths = widths[0 .. widths.len - row_size];
var column_widths = widths[widths.len - row_size ..];
// Find next row with trailing comment (if any) to end the current section
var section_end = sec_end: {
var this_line_first_expr: usize = 0;
var this_line_size = rowSize(tree, row_exprs, rtoken);
for (row_exprs) |expr, i| {
// Ignore comment on first line of this section
if (i == 0 or tree.tokensOnSameLine(row_exprs[0].firstToken(), expr.lastToken())) continue;
// Track start of line containing comment
if (!tree.tokensOnSameLine(row_exprs[this_line_first_expr].firstToken(), expr.lastToken())) {
this_line_first_expr = i;
this_line_size = rowSize(tree, row_exprs[this_line_first_expr..], rtoken);
}
const maybe_comma = expr.lastToken() + 1;
const maybe_comment = expr.lastToken() + 2;
if (maybe_comment < tree.token_ids.len) {
if (tree.token_ids[maybe_comma] == .Comma and
tree.token_ids[maybe_comment] == .LineComment and
tree.tokensOnSameLine(expr.lastToken(), maybe_comment))
{
var comment_token_loc = tree.token_locs[maybe_comment];
const comment_is_empty = mem.trimRight(u8, tree.tokenSliceLoc(comment_token_loc), " ").len == 2;
if (!comment_is_empty) {
// Found row ending in comment
break :sec_end i - this_line_size.? + 1;
}
}
}
}
break :sec_end row_exprs.len;
};
expr_index += section_end;
const section_exprs = row_exprs[0..section_end];
// Null stream for counting the printed length of each expression
var line_find_stream = std.io.findByteWriter('\n', std.io.null_writer);
var counting_stream = std.io.countingWriter(line_find_stream.writer());
var auto_indenting_stream = std.io.autoIndentingStream(indent_delta, counting_stream.writer());
// Calculate size of columns in current section
var column_counter: usize = 0;
var single_line = true;
for (section_exprs) |expr, i| {
if (i + 1 < section_exprs.len) {
counting_stream.bytes_written = 0;
line_find_stream.byte_found = false;
try renderExpression(allocator, &auto_indenting_stream, tree, expr, Space.None);
const width = @intCast(usize, counting_stream.bytes_written);
expr_widths[i] = width;
expr_newlines[i] = line_find_stream.byte_found;
if (!line_find_stream.byte_found) {
const column = column_counter % row_size;
column_widths[column] = std.math.max(column_widths[column], width);
const expr_last_token = expr.*.lastToken() + 1;
const next_expr = section_exprs[i + 1];
const loc = tree.tokenLocation(tree.token_locs[expr_last_token].start, next_expr.*.firstToken());
column_counter += 1;
if (loc.line != 0) single_line = false;
} else {
single_line = false;
column_counter = 0;
}
} else {
counting_stream.bytes_written = 0;
try renderExpression(allocator, &auto_indenting_stream, tree, expr, Space.None);
const width = @intCast(usize, counting_stream.bytes_written);
expr_widths[i] = width;
expr_newlines[i] = line_find_stream.byte_found;
if (!line_find_stream.byte_found) {
const column = column_counter % row_size;
column_widths[column] = std.math.max(column_widths[column], width);
}
break;
}
}
// Render exprs in current section
column_counter = 0;
var last_col_index: usize = row_size - 1;
for (section_exprs) |expr, i| {
if (i + 1 < section_exprs.len) {
const next_expr = section_exprs[i + 1];
try renderExpression(allocator, ais, tree, expr, Space.None);
const comma = tree.nextToken(expr.*.lastToken());
if (column_counter != last_col_index) {
if (!expr_newlines[i] and !expr_newlines[i + 1]) {
// Neither the current or next expression is multiline
try renderToken(tree, ais, comma, Space.Space); // ,
assert(column_widths[column_counter % row_size] >= expr_widths[i]);
const padding = column_widths[column_counter % row_size] - expr_widths[i];
try ais.writer().writeByteNTimes(' ', padding);
column_counter += 1;
continue;
}
}
if (single_line and row_size != 1) {
try renderToken(tree, ais, comma, Space.Space); // ,
continue;
}
column_counter = 0;
try renderToken(tree, ais, comma, Space.Newline); // ,
try renderExtraNewline(tree, ais, next_expr);
} else {
const maybe_comma = tree.nextToken(expr.*.lastToken());
if (tree.token_ids[maybe_comma] == .Comma) {
try renderExpression(allocator, ais, tree, expr, Space.None); // ,
try renderToken(tree, ais, maybe_comma, Space.Newline); // ,
} else {
try renderExpression(allocator, ais, tree, expr, Space.Comma); // ,
}
}
}
if (expr_index == exprs.len) {
break;
}
}
}
return renderToken(tree, ais, rtoken, space);
}
// Single line
try renderToken(tree, ais, lbrace, Space.Space);
for (exprs) |expr, i| {
if (i + 1 < exprs.len) {
const next_expr = exprs[i + 1];
try renderExpression(allocator, ais, tree, expr, Space.None);
const comma = tree.nextToken(expr.*.lastToken());
try renderToken(tree, ais, comma, Space.Space); // ,
} else {
try renderExpression(allocator, ais, tree, expr, Space.Space);
}
}
return renderToken(tree, ais, rtoken, space);
},
.StructInitializer, .StructInitializerDot => {
var rtoken: ast.TokenIndex = undefined;
var field_inits: []*ast.Node = undefined;
const lhs: union(enum) { dot: ast.TokenIndex, node: *ast.Node } = switch (base.tag) {
.StructInitializerDot => blk: {
const casted = @fieldParentPtr(ast.Node.StructInitializerDot, "base", base);
rtoken = casted.rtoken;
field_inits = casted.list();
break :blk .{ .dot = casted.dot };
},
.StructInitializer => blk: {
const casted = @fieldParentPtr(ast.Node.StructInitializer, "base", base);
rtoken = casted.rtoken;
field_inits = casted.list();
break :blk .{ .node = casted.lhs };
},
else => unreachable,
};
const lbrace = switch (lhs) {
.dot => |dot| tree.nextToken(dot),
.node => |node| tree.nextToken(node.lastToken()),
};
if (field_inits.len == 0) {
switch (lhs) {
.dot => |dot| try renderToken(tree, ais, dot, Space.None),
.node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
}
{
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, lbrace, Space.None);
}
return renderToken(tree, ais, rtoken, space);
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(rtoken);
break :blk tree.token_ids[maybe_comma] == .Comma;
};
const src_same_line = blk: {
const loc = tree.tokenLocation(tree.token_locs[lbrace].end, rtoken);
break :blk loc.line == 0;
};
const expr_outputs_one_line = blk: {
// render field expressions until a LF is found
for (field_inits) |field_init| {
var find_stream = std.io.findByteWriter('\n', std.io.null_writer);
var auto_indenting_stream = std.io.autoIndentingStream(indent_delta, find_stream.writer());
try renderExpression(allocator, &auto_indenting_stream, tree, field_init, Space.None);
if (find_stream.byte_found) break :blk false;
}
break :blk true;
};
if (field_inits.len == 1) blk: {
if (field_inits[0].cast(ast.Node.FieldInitializer)) |field_init| {
switch (field_init.expr.tag) {
.StructInitializer,
.StructInitializerDot,
=> break :blk,
else => {},
}
}
// if the expression outputs to multiline, make this struct multiline
if (!expr_outputs_one_line or src_has_trailing_comma) {
break :blk;
}
switch (lhs) {
.dot => |dot| try renderToken(tree, ais, dot, Space.None),
.node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
}
try renderToken(tree, ais, lbrace, Space.Space);
try renderExpression(allocator, ais, tree, field_inits[0], Space.Space);
return renderToken(tree, ais, rtoken, space);
}
if (!src_has_trailing_comma and src_same_line and expr_outputs_one_line) {
// render all on one line, no trailing comma
switch (lhs) {
.dot => |dot| try renderToken(tree, ais, dot, Space.None),
.node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
}
try renderToken(tree, ais, lbrace, Space.Space);
for (field_inits) |field_init, i| {
if (i + 1 < field_inits.len) {
try renderExpression(allocator, ais, tree, field_init, Space.None);
const comma = tree.nextToken(field_init.lastToken());
try renderToken(tree, ais, comma, Space.Space);
} else {
try renderExpression(allocator, ais, tree, field_init, Space.Space);
}
}
return renderToken(tree, ais, rtoken, space);
}
{
switch (lhs) {
.dot => |dot| try renderToken(tree, ais, dot, Space.None),
.node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
}
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, lbrace, Space.Newline);
for (field_inits) |field_init, i| {
if (i + 1 < field_inits.len) {
const next_field_init = field_inits[i + 1];
try renderExpression(allocator, ais, tree, field_init, Space.None);
const comma = tree.nextToken(field_init.lastToken());
try renderToken(tree, ais, comma, Space.Newline);
try renderExtraNewline(tree, ais, next_field_init);
} else {
try renderExpression(allocator, ais, tree, field_init, Space.Comma);
}
}
}
return renderToken(tree, ais, rtoken, space);
},
.Call => {
const call = @fieldParentPtr(ast.Node.Call, "base", base);
if (call.async_token) |async_token| {
try renderToken(tree, ais, async_token, Space.Space);
}
try renderExpression(allocator, ais, tree, call.lhs, Space.None);
const lparen = tree.nextToken(call.lhs.lastToken());
if (call.params_len == 0) {
try renderToken(tree, ais, lparen, Space.None);
return renderToken(tree, ais, call.rtoken, space);
}
const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(call.rtoken);
break :blk tree.token_ids[maybe_comma] == .Comma;
};
if (src_has_trailing_comma) {
{
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, lparen, Space.Newline); // (
const params = call.params();
for (params) |param_node, i| {
if (i + 1 < params.len) {
const next_node = params[i + 1];
try renderExpression(allocator, ais, tree, param_node, Space.None);
// Unindent the comma for multiline string literals
const maybe_multiline_string = param_node.firstToken();
const is_multiline_string = tree.token_ids[maybe_multiline_string] == .MultilineStringLiteralLine;
if (is_multiline_string) ais.popIndent();
defer if (is_multiline_string) ais.pushIndent();
const comma = tree.nextToken(param_node.lastToken());
try renderToken(tree, ais, comma, Space.Newline); // ,
try renderExtraNewline(tree, ais, next_node);
} else {
try renderExpression(allocator, ais, tree, param_node, Space.Comma);
}
}
}
return renderToken(tree, ais, call.rtoken, space);
}
try renderToken(tree, ais, lparen, Space.None); // (
const params = call.params();
for (params) |param_node, i| {
const maybe_comment = param_node.firstToken() - 1;
const maybe_multiline_string = param_node.firstToken();
if (tree.token_ids[maybe_multiline_string] == .MultilineStringLiteralLine or tree.token_ids[maybe_comment] == .LineComment) {
ais.pushIndentOneShot();
}
try renderExpression(allocator, ais, tree, param_node, Space.None);
if (i + 1 < params.len) {
const comma = tree.nextToken(param_node.lastToken());
try renderToken(tree, ais, comma, Space.Space);
}
}
return renderToken(tree, ais, call.rtoken, space); // )
},
.ArrayAccess => {
const suffix_op = base.castTag(.ArrayAccess).?;
const lbracket = tree.nextToken(suffix_op.lhs.lastToken());
const rbracket = tree.nextToken(suffix_op.index_expr.lastToken());
try renderExpression(allocator, ais, tree, suffix_op.lhs, Space.None);
try renderToken(tree, ais, lbracket, Space.None); // [
const starts_with_comment = tree.token_ids[lbracket + 1] == .LineComment;
const ends_with_comment = tree.token_ids[rbracket - 1] == .LineComment;
{
const new_space = if (ends_with_comment) Space.Newline else Space.None;
ais.pushIndent();
defer ais.popIndent();
try renderExpression(allocator, ais, tree, suffix_op.index_expr, new_space);
}
if (starts_with_comment) try ais.maybeInsertNewline();
return renderToken(tree, ais, rbracket, space); // ]
},
.Slice => {
const suffix_op = base.castTag(.Slice).?;
try renderExpression(allocator, ais, tree, suffix_op.lhs, Space.None);
const lbracket = tree.prevToken(suffix_op.start.firstToken());
const dotdot = tree.nextToken(suffix_op.start.lastToken());
const after_start_space_bool = nodeCausesSliceOpSpace(suffix_op.start) or
(if (suffix_op.end) |end| nodeCausesSliceOpSpace(end) else false);
const after_start_space = if (after_start_space_bool) Space.Space else Space.None;
const after_op_space = if (suffix_op.end != null) after_start_space else Space.None;
try renderToken(tree, ais, lbracket, Space.None); // [
try renderExpression(allocator, ais, tree, suffix_op.start, after_start_space);
try renderToken(tree, ais, dotdot, after_op_space); // ..
if (suffix_op.end) |end| {
const after_end_space = if (suffix_op.sentinel != null) Space.Space else Space.None;
try renderExpression(allocator, ais, tree, end, after_end_space);
}
if (suffix_op.sentinel) |sentinel| {
const colon = tree.prevToken(sentinel.firstToken());
try renderToken(tree, ais, colon, Space.None); // :
try renderExpression(allocator, ais, tree, sentinel, Space.None);
}
return renderToken(tree, ais, suffix_op.rtoken, space); // ]
},
.Deref => {
const suffix_op = base.castTag(.Deref).?;
try renderExpression(allocator, ais, tree, suffix_op.lhs, Space.None);
return renderToken(tree, ais, suffix_op.rtoken, space); // .*
},
.UnwrapOptional => {
const suffix_op = base.castTag(.UnwrapOptional).?;
try renderExpression(allocator, ais, tree, suffix_op.lhs, Space.None);
try renderToken(tree, ais, tree.prevToken(suffix_op.rtoken), Space.None); // .
return renderToken(tree, ais, suffix_op.rtoken, space); // ?
},
.Break => {
const flow_expr = base.castTag(.Break).?;
const maybe_rhs = flow_expr.getRHS();
const maybe_label = flow_expr.getLabel();
if (maybe_label == null and maybe_rhs == null) {
return renderToken(tree, ais, flow_expr.ltoken, space); // break
}
try renderToken(tree, ais, flow_expr.ltoken, Space.Space); // break
if (maybe_label) |label| {
const colon = tree.nextToken(flow_expr.ltoken);
try renderToken(tree, ais, colon, Space.None); // :
if (maybe_rhs == null) {
return renderToken(tree, ais, label, space); // label
}
try renderToken(tree, ais, label, Space.Space); // label
}
return renderExpression(allocator, ais, tree, maybe_rhs.?, space);
},
.Continue => {
const flow_expr = base.castTag(.Continue).?;
if (flow_expr.getLabel()) |label| {
try renderToken(tree, ais, flow_expr.ltoken, Space.Space); // continue
const colon = tree.nextToken(flow_expr.ltoken);
try renderToken(tree, ais, colon, Space.None); // :
return renderToken(tree, ais, label, space); // label
} else {
return renderToken(tree, ais, flow_expr.ltoken, space); // continue
}
},
.Return => {
const flow_expr = base.castTag(.Return).?;
if (flow_expr.getRHS()) |rhs| {
try renderToken(tree, ais, flow_expr.ltoken, Space.Space);
return renderExpression(allocator, ais, tree, rhs, space);
} else {
return renderToken(tree, ais, flow_expr.ltoken, space);
}
},
.Payload => {
const payload = @fieldParentPtr(ast.Node.Payload, "base", base);
try renderToken(tree, ais, payload.lpipe, Space.None);
try renderExpression(allocator, ais, tree, payload.error_symbol, Space.None);
return renderToken(tree, ais, payload.rpipe, space);
},
.PointerPayload => {
const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base);
try renderToken(tree, ais, payload.lpipe, Space.None);
if (payload.ptr_token) |ptr_token| {
try renderToken(tree, ais, ptr_token, Space.None);
}
try renderExpression(allocator, ais, tree, payload.value_symbol, Space.None);
return renderToken(tree, ais, payload.rpipe, space);
},
.PointerIndexPayload => {
const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base);
try renderToken(tree, ais, payload.lpipe, Space.None);
if (payload.ptr_token) |ptr_token| {
try renderToken(tree, ais, ptr_token, Space.None);
}
try renderExpression(allocator, ais, tree, payload.value_symbol, Space.None);
if (payload.index_symbol) |index_symbol| {
const comma = tree.nextToken(payload.value_symbol.lastToken());
try renderToken(tree, ais, comma, Space.Space);
try renderExpression(allocator, ais, tree, index_symbol, Space.None);
}
return renderToken(tree, ais, payload.rpipe, space);
},
.GroupedExpression => {
const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base);
try renderToken(tree, ais, grouped_expr.lparen, Space.None);
{
ais.pushIndentOneShot();
try renderExpression(allocator, ais, tree, grouped_expr.expr, Space.None);
}
return renderToken(tree, ais, grouped_expr.rparen, space);
},
.FieldInitializer => {
const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base);
try renderToken(tree, ais, field_init.period_token, Space.None); // .
try renderToken(tree, ais, field_init.name_token, Space.Space); // name
try renderToken(tree, ais, tree.nextToken(field_init.name_token), Space.Space); // =
return renderExpression(allocator, ais, tree, field_init.expr, space);
},
.ContainerDecl => {
const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base);
if (container_decl.layout_token) |layout_token| {
try renderToken(tree, ais, layout_token, Space.Space);
}
switch (container_decl.init_arg_expr) {
.None => {
try renderToken(tree, ais, container_decl.kind_token, Space.Space); // union
},
.Enum => |enum_tag_type| {
try renderToken(tree, ais, container_decl.kind_token, Space.None); // union
const lparen = tree.nextToken(container_decl.kind_token);
const enum_token = tree.nextToken(lparen);
try renderToken(tree, ais, lparen, Space.None); // (
try renderToken(tree, ais, enum_token, Space.None); // enum
if (enum_tag_type) |expr| {
try renderToken(tree, ais, tree.nextToken(enum_token), Space.None); // (
try renderExpression(allocator, ais, tree, expr, Space.None);
const rparen = tree.nextToken(expr.lastToken());
try renderToken(tree, ais, rparen, Space.None); // )
try renderToken(tree, ais, tree.nextToken(rparen), Space.Space); // )
} else {
try renderToken(tree, ais, tree.nextToken(enum_token), Space.Space); // )
}
},
.Type => |type_expr| {
try renderToken(tree, ais, container_decl.kind_token, Space.None); // union
const lparen = tree.nextToken(container_decl.kind_token);
const rparen = tree.nextToken(type_expr.lastToken());
try renderToken(tree, ais, lparen, Space.None); // (
try renderExpression(allocator, ais, tree, type_expr, Space.None);
try renderToken(tree, ais, rparen, Space.Space); // )
},
}
if (container_decl.fields_and_decls_len == 0) {
{
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, container_decl.lbrace_token, Space.None); // {
}
return renderToken(tree, ais, container_decl.rbrace_token, space); // }
}
const src_has_trailing_comma = blk: {
var maybe_comma = tree.prevToken(container_decl.lastToken());
// Doc comments for a field may also appear after the comma, eg.
// field_name: T, // comment attached to field_name
if (tree.token_ids[maybe_comma] == .DocComment)
maybe_comma = tree.prevToken(maybe_comma);
break :blk tree.token_ids[maybe_comma] == .Comma;
};
const fields_and_decls = container_decl.fieldsAndDecls();
// Check if the first declaration and the { are on the same line
const src_has_newline = !tree.tokensOnSameLine(
container_decl.lbrace_token,
fields_and_decls[0].firstToken(),
);
// We can only print all the elements in-line if all the
// declarations inside are fields
const src_has_only_fields = blk: {
for (fields_and_decls) |decl| {
if (decl.tag != .ContainerField) break :blk false;
}
break :blk true;
};
if (src_has_trailing_comma or !src_has_only_fields) {
// One declaration per line
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, container_decl.lbrace_token, .Newline); // {
for (fields_and_decls) |decl, i| {
try renderContainerDecl(allocator, ais, tree, decl, .Newline);
if (i + 1 < fields_and_decls.len) {
try renderExtraNewline(tree, ais, fields_and_decls[i + 1]);
}
}
} else if (src_has_newline) {
// All the declarations on the same line, but place the items on
// their own line
try renderToken(tree, ais, container_decl.lbrace_token, .Newline); // {
ais.pushIndent();
defer ais.popIndent();
for (fields_and_decls) |decl, i| {
const space_after_decl: Space = if (i + 1 >= fields_and_decls.len) .Newline else .Space;
try renderContainerDecl(allocator, ais, tree, decl, space_after_decl);
}
} else {
// All the declarations on the same line
try renderToken(tree, ais, container_decl.lbrace_token, .Space); // {
for (fields_and_decls) |decl| {
try renderContainerDecl(allocator, ais, tree, decl, .Space);
}
}
return renderToken(tree, ais, container_decl.rbrace_token, space); // }
},
.ErrorSetDecl => {
const err_set_decl = @fieldParentPtr(ast.Node.ErrorSetDecl, "base", base);
const lbrace = tree.nextToken(err_set_decl.error_token);
if (err_set_decl.decls_len == 0) {
try renderToken(tree, ais, err_set_decl.error_token, Space.None);
try renderToken(tree, ais, lbrace, Space.None);
return renderToken(tree, ais, err_set_decl.rbrace_token, space);
}
if (err_set_decl.decls_len == 1) blk: {
const node = err_set_decl.decls()[0];
// if there are any doc comments or same line comments
// don't try to put it all on one line
if (node.cast(ast.Node.ErrorTag)) |tag| {
if (tag.doc_comments != null) break :blk;
} else {
break :blk;
}
try renderToken(tree, ais, err_set_decl.error_token, Space.None); // error
try renderToken(tree, ais, lbrace, Space.None); // {
try renderExpression(allocator, ais, tree, node, Space.None);
return renderToken(tree, ais, err_set_decl.rbrace_token, space); // }
}
try renderToken(tree, ais, err_set_decl.error_token, Space.None); // error
const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(err_set_decl.rbrace_token);
break :blk tree.token_ids[maybe_comma] == .Comma;
};
if (src_has_trailing_comma) {
{
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, lbrace, Space.Newline); // {
const decls = err_set_decl.decls();
for (decls) |node, i| {
if (i + 1 < decls.len) {
try renderExpression(allocator, ais, tree, node, Space.None);
try renderToken(tree, ais, tree.nextToken(node.lastToken()), Space.Newline); // ,
try renderExtraNewline(tree, ais, decls[i + 1]);
} else {
try renderExpression(allocator, ais, tree, node, Space.Comma);
}
}
}
return renderToken(tree, ais, err_set_decl.rbrace_token, space); // }
} else {
try renderToken(tree, ais, lbrace, Space.Space); // {
const decls = err_set_decl.decls();
for (decls) |node, i| {
if (i + 1 < decls.len) {
try renderExpression(allocator, ais, tree, node, Space.None);
const comma_token = tree.nextToken(node.lastToken());
assert(tree.token_ids[comma_token] == .Comma);
try renderToken(tree, ais, comma_token, Space.Space); // ,
try renderExtraNewline(tree, ais, decls[i + 1]);
} else {
try renderExpression(allocator, ais, tree, node, Space.Space);
}
}
return renderToken(tree, ais, err_set_decl.rbrace_token, space); // }
}
},
.ErrorTag => {
const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", base);
try renderDocComments(tree, ais, tag, tag.doc_comments);
return renderToken(tree, ais, tag.name_token, space); // name
},
.MultilineStringLiteral => {
const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base);
{
const locked_indents = ais.lockOneShotIndent();
defer {
var i: u8 = 0;
while (i < locked_indents) : (i += 1) ais.popIndent();
}
try ais.maybeInsertNewline();
for (multiline_str_literal.lines()) |t| try renderToken(tree, ais, t, Space.None);
}
},
.BuiltinCall => {
const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base);
// TODO remove after 0.7.0 release
if (mem.eql(u8, tree.tokenSlice(builtin_call.builtin_token), "@OpaqueType"))
return ais.writer().writeAll("opaque {}");
// TODO remove after 0.7.0 release
{
const params = builtin_call.paramsConst();
if (mem.eql(u8, tree.tokenSlice(builtin_call.builtin_token), "@Type") and
params.len == 1)
{
if (params[0].castTag(.EnumLiteral)) |enum_literal|
if (mem.eql(u8, tree.tokenSlice(enum_literal.name), "Opaque"))
return ais.writer().writeAll("opaque {}");
}
}
try renderToken(tree, ais, builtin_call.builtin_token, Space.None); // @name
const src_params_trailing_comma = blk: {
if (builtin_call.params_len == 0) break :blk false;
const last_node = builtin_call.params()[builtin_call.params_len - 1];
const maybe_comma = tree.nextToken(last_node.lastToken());
break :blk tree.token_ids[maybe_comma] == .Comma;
};
const lparen = tree.nextToken(builtin_call.builtin_token);
if (!src_params_trailing_comma) {
try renderToken(tree, ais, lparen, Space.None); // (
// render all on one line, no trailing comma
const params = builtin_call.params();
for (params) |param_node, i| {
const maybe_comment = param_node.firstToken() - 1;
if (param_node.*.tag == .MultilineStringLiteral or tree.token_ids[maybe_comment] == .LineComment) {
ais.pushIndentOneShot();
}
try renderExpression(allocator, ais, tree, param_node, Space.None);
if (i + 1 < params.len) {
const comma_token = tree.nextToken(param_node.lastToken());
try renderToken(tree, ais, comma_token, Space.Space); // ,
}
}
} else {
// one param per line
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, lparen, Space.Newline); // (
for (builtin_call.params()) |param_node| {
try renderExpression(allocator, ais, tree, param_node, Space.Comma);
}
}
return renderToken(tree, ais, builtin_call.rparen_token, space); // )
},
.FnProto => {
const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", base);
if (fn_proto.getVisibToken()) |visib_token_index| {
const visib_token = tree.token_ids[visib_token_index];
assert(visib_token == .Keyword_pub or visib_token == .Keyword_export);
try renderToken(tree, ais, visib_token_index, Space.Space); // pub
}
if (fn_proto.getExternExportInlineToken()) |extern_export_inline_token| {
if (fn_proto.getIsExternPrototype() == null and fn_proto.getIsInline() == null)
try renderToken(tree, ais, extern_export_inline_token, Space.Space); // extern/export/inline
}
if (fn_proto.getLibName()) |lib_name| {
try renderExpression(allocator, ais, tree, lib_name, Space.Space);
}
const lparen = if (fn_proto.getNameToken()) |name_token| blk: {
try renderToken(tree, ais, fn_proto.fn_token, Space.Space); // fn
try renderToken(tree, ais, name_token, Space.None); // name
break :blk tree.nextToken(name_token);
} else blk: {
try renderToken(tree, ais, fn_proto.fn_token, Space.Space); // fn
break :blk tree.nextToken(fn_proto.fn_token);
};
assert(tree.token_ids[lparen] == .LParen);
const rparen = tree.prevToken(
// the first token for the annotation expressions is the left
// parenthesis, hence the need for two prevToken
if (fn_proto.getAlignExpr()) |align_expr|
tree.prevToken(tree.prevToken(align_expr.firstToken()))
else if (fn_proto.getSectionExpr()) |section_expr|
tree.prevToken(tree.prevToken(section_expr.firstToken()))
else if (fn_proto.getCallconvExpr()) |callconv_expr|
tree.prevToken(tree.prevToken(callconv_expr.firstToken()))
else switch (fn_proto.return_type) {
.Explicit => |node| node.firstToken(),
.InferErrorSet => |node| tree.prevToken(node.firstToken()),
.Invalid => unreachable,
},
);
assert(tree.token_ids[rparen] == .RParen);
const src_params_trailing_comma = blk: {
const maybe_comma = tree.token_ids[rparen - 1];
break :blk maybe_comma == .Comma or maybe_comma == .LineComment;
};
if (!src_params_trailing_comma) {
try renderToken(tree, ais, lparen, Space.None); // (
// render all on one line, no trailing comma
for (fn_proto.params()) |param_decl, i| {
try renderParamDecl(allocator, ais, tree, param_decl, Space.None);
if (i + 1 < fn_proto.params_len or fn_proto.getVarArgsToken() != null) {
const comma = tree.nextToken(param_decl.lastToken());
try renderToken(tree, ais, comma, Space.Space); // ,
}
}
if (fn_proto.getVarArgsToken()) |var_args_token| {
try renderToken(tree, ais, var_args_token, Space.None);
}
} else {
// one param per line
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, lparen, Space.Newline); // (
for (fn_proto.params()) |param_decl| {
try renderParamDecl(allocator, ais, tree, param_decl, Space.Comma);
}
if (fn_proto.getVarArgsToken()) |var_args_token| {
try renderToken(tree, ais, var_args_token, Space.Comma);
}
}
try renderToken(tree, ais, rparen, Space.Space); // )
if (fn_proto.getAlignExpr()) |align_expr| {
const align_rparen = tree.nextToken(align_expr.lastToken());
const align_lparen = tree.prevToken(align_expr.firstToken());
const align_kw = tree.prevToken(align_lparen);
try renderToken(tree, ais, align_kw, Space.None); // align
try renderToken(tree, ais, align_lparen, Space.None); // (
try renderExpression(allocator, ais, tree, align_expr, Space.None);
try renderToken(tree, ais, align_rparen, Space.Space); // )
}
if (fn_proto.getSectionExpr()) |section_expr| {
const section_rparen = tree.nextToken(section_expr.lastToken());
const section_lparen = tree.prevToken(section_expr.firstToken());
const section_kw = tree.prevToken(section_lparen);
try renderToken(tree, ais, section_kw, Space.None); // section
try renderToken(tree, ais, section_lparen, Space.None); // (
try renderExpression(allocator, ais, tree, section_expr, Space.None);
try renderToken(tree, ais, section_rparen, Space.Space); // )
}
if (fn_proto.getCallconvExpr()) |callconv_expr| {
const callconv_rparen = tree.nextToken(callconv_expr.lastToken());
const callconv_lparen = tree.prevToken(callconv_expr.firstToken());
const callconv_kw = tree.prevToken(callconv_lparen);
try renderToken(tree, ais, callconv_kw, Space.None); // callconv
try renderToken(tree, ais, callconv_lparen, Space.None); // (
try renderExpression(allocator, ais, tree, callconv_expr, Space.None);
try renderToken(tree, ais, callconv_rparen, Space.Space); // )
} else if (fn_proto.getIsExternPrototype() != null) {
try ais.writer().writeAll("callconv(.C) ");
} else if (fn_proto.getIsAsync() != null) {
try ais.writer().writeAll("callconv(.Async) ");
} else if (fn_proto.getIsInline() != null) {
try ais.writer().writeAll("callconv(.Inline) ");
}
switch (fn_proto.return_type) {
.Explicit => |node| {
return renderExpression(allocator, ais, tree, node, space);
},
.InferErrorSet => |node| {
try renderToken(tree, ais, tree.prevToken(node.firstToken()), Space.None); // !
return renderExpression(allocator, ais, tree, node, space);
},
.Invalid => unreachable,
}
},
.AnyFrameType => {
const anyframe_type = @fieldParentPtr(ast.Node.AnyFrameType, "base", base);
if (anyframe_type.result) |result| {
try renderToken(tree, ais, anyframe_type.anyframe_token, Space.None); // anyframe
try renderToken(tree, ais, result.arrow_token, Space.None); // ->
return renderExpression(allocator, ais, tree, result.return_type, space);
} else {
return renderToken(tree, ais, anyframe_type.anyframe_token, space); // anyframe
}
},
.DocComment => unreachable, // doc comments are attached to nodes
.Switch => {
const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base);
try renderToken(tree, ais, switch_node.switch_token, Space.Space); // switch
try renderToken(tree, ais, tree.nextToken(switch_node.switch_token), Space.None); // (
const rparen = tree.nextToken(switch_node.expr.lastToken());
const lbrace = tree.nextToken(rparen);
if (switch_node.cases_len == 0) {
try renderExpression(allocator, ais, tree, switch_node.expr, Space.None);
try renderToken(tree, ais, rparen, Space.Space); // )
try renderToken(tree, ais, lbrace, Space.None); // {
return renderToken(tree, ais, switch_node.rbrace, space); // }
}
try renderExpression(allocator, ais, tree, switch_node.expr, Space.None);
try renderToken(tree, ais, rparen, Space.Space); // )
{
ais.pushIndentNextLine();
defer ais.popIndent();
try renderToken(tree, ais, lbrace, Space.Newline); // {
const cases = switch_node.cases();
for (cases) |node, i| {
try renderExpression(allocator, ais, tree, node, Space.Comma);
if (i + 1 < cases.len) {
try renderExtraNewline(tree, ais, cases[i + 1]);
}
}
}
return renderToken(tree, ais, switch_node.rbrace, space); // }
},
.SwitchCase => {
const switch_case = @fieldParentPtr(ast.Node.SwitchCase, "base", base);
assert(switch_case.items_len != 0);
const src_has_trailing_comma = blk: {
const last_node = switch_case.items()[switch_case.items_len - 1];
const maybe_comma = tree.nextToken(last_node.lastToken());
break :blk tree.token_ids[maybe_comma] == .Comma;
};
if (switch_case.items_len == 1 or !src_has_trailing_comma) {
const items = switch_case.items();
for (items) |node, i| {
if (i + 1 < items.len) {
try renderExpression(allocator, ais, tree, node, Space.None);
const comma_token = tree.nextToken(node.lastToken());
try renderToken(tree, ais, comma_token, Space.Space); // ,
try renderExtraNewline(tree, ais, items[i + 1]);
} else {
try renderExpression(allocator, ais, tree, node, Space.Space);
}
}
} else {
const items = switch_case.items();
for (items) |node, i| {
if (i + 1 < items.len) {
try renderExpression(allocator, ais, tree, node, Space.None);
const comma_token = tree.nextToken(node.lastToken());
try renderToken(tree, ais, comma_token, Space.Newline); // ,
try renderExtraNewline(tree, ais, items[i + 1]);
} else {
try renderExpression(allocator, ais, tree, node, Space.Comma);
}
}
}
try renderToken(tree, ais, switch_case.arrow_token, Space.Space); // =>
if (switch_case.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
return renderExpression(allocator, ais, tree, switch_case.expr, space);
},
.SwitchElse => {
const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base);
return renderToken(tree, ais, switch_else.token, space);
},
.Else => {
const else_node = @fieldParentPtr(ast.Node.Else, "base", base);
const body_is_block = nodeIsBlock(else_node.body);
const same_line = body_is_block or tree.tokensOnSameLine(else_node.else_token, else_node.body.lastToken());
const after_else_space = if (same_line or else_node.payload != null) Space.Space else Space.Newline;
try renderToken(tree, ais, else_node.else_token, after_else_space);
if (else_node.payload) |payload| {
const payload_space = if (same_line) Space.Space else Space.Newline;
try renderExpression(allocator, ais, tree, payload, payload_space);
}
if (same_line) {
return renderExpression(allocator, ais, tree, else_node.body, space);
} else {
ais.pushIndent();
defer ais.popIndent();
return renderExpression(allocator, ais, tree, else_node.body, space);
}
},
.While => {
const while_node = @fieldParentPtr(ast.Node.While, "base", base);
if (while_node.label) |label| {
try renderToken(tree, ais, label, Space.None); // label
try renderToken(tree, ais, tree.nextToken(label), Space.Space); // :
}
if (while_node.inline_token) |inline_token| {
try renderToken(tree, ais, inline_token, Space.Space); // inline
}
try renderToken(tree, ais, while_node.while_token, Space.Space); // while
try renderToken(tree, ais, tree.nextToken(while_node.while_token), Space.None); // (
try renderExpression(allocator, ais, tree, while_node.condition, Space.None);
const cond_rparen = tree.nextToken(while_node.condition.lastToken());
const body_is_block = nodeIsBlock(while_node.body);
var block_start_space: Space = undefined;
var after_body_space: Space = undefined;
if (body_is_block) {
block_start_space = Space.BlockStart;
after_body_space = if (while_node.@"else" == null) space else Space.SpaceOrOutdent;
} else if (tree.tokensOnSameLine(cond_rparen, while_node.body.lastToken())) {
block_start_space = Space.Space;
after_body_space = if (while_node.@"else" == null) space else Space.Space;
} else {
block_start_space = Space.Newline;
after_body_space = if (while_node.@"else" == null) space else Space.Newline;
}
{
const rparen_space = if (while_node.payload != null or while_node.continue_expr != null) Space.Space else block_start_space;
try renderToken(tree, ais, cond_rparen, rparen_space); // )
}
if (while_node.payload) |payload| {
const payload_space = if (while_node.continue_expr != null) Space.Space else block_start_space;
try renderExpression(allocator, ais, tree, payload, payload_space);
}
if (while_node.continue_expr) |continue_expr| {
const rparen = tree.nextToken(continue_expr.lastToken());
const lparen = tree.prevToken(continue_expr.firstToken());
const colon = tree.prevToken(lparen);
try renderToken(tree, ais, colon, Space.Space); // :
try renderToken(tree, ais, lparen, Space.None); // (
try renderExpression(allocator, ais, tree, continue_expr, Space.None);
try renderToken(tree, ais, rparen, block_start_space); // )
}
{
if (!body_is_block) ais.pushIndent();
defer if (!body_is_block) ais.popIndent();
try renderExpression(allocator, ais, tree, while_node.body, after_body_space);
}
if (while_node.@"else") |@"else"| {
return renderExpression(allocator, ais, tree, &@"else".base, space);
}
},
.For => {
const for_node = @fieldParentPtr(ast.Node.For, "base", base);
if (for_node.label) |label| {
try renderToken(tree, ais, label, Space.None); // label
try renderToken(tree, ais, tree.nextToken(label), Space.Space); // :
}
if (for_node.inline_token) |inline_token| {
try renderToken(tree, ais, inline_token, Space.Space); // inline
}
try renderToken(tree, ais, for_node.for_token, Space.Space); // for
try renderToken(tree, ais, tree.nextToken(for_node.for_token), Space.None); // (
try renderExpression(allocator, ais, tree, for_node.array_expr, Space.None);
const rparen = tree.nextToken(for_node.array_expr.lastToken());
const body_is_block = for_node.body.tag.isBlock();
const src_one_line_to_body = !body_is_block and tree.tokensOnSameLine(rparen, for_node.body.firstToken());
const body_on_same_line = body_is_block or src_one_line_to_body;
try renderToken(tree, ais, rparen, Space.Space); // )
const space_after_payload = if (body_on_same_line) Space.Space else Space.Newline;
try renderExpression(allocator, ais, tree, for_node.payload, space_after_payload); // |x|
const space_after_body = blk: {
if (for_node.@"else") |@"else"| {
const src_one_line_to_else = tree.tokensOnSameLine(rparen, @"else".firstToken());
if (body_is_block or src_one_line_to_else) {
break :blk Space.Space;
} else {
break :blk Space.Newline;
}
} else {
break :blk space;
}
};
{
if (!body_on_same_line) ais.pushIndent();
defer if (!body_on_same_line) ais.popIndent();
try renderExpression(allocator, ais, tree, for_node.body, space_after_body); // { body }
}
if (for_node.@"else") |@"else"| {
return renderExpression(allocator, ais, tree, &@"else".base, space); // else
}
},
.If => {
const if_node = @fieldParentPtr(ast.Node.If, "base", base);
const lparen = tree.nextToken(if_node.if_token);
const rparen = tree.nextToken(if_node.condition.lastToken());
try renderToken(tree, ais, if_node.if_token, Space.Space); // if
try renderToken(tree, ais, lparen, Space.None); // (
try renderExpression(allocator, ais, tree, if_node.condition, Space.None); // condition
const body_is_if_block = if_node.body.tag == .If;
const body_is_block = nodeIsBlock(if_node.body);
if (body_is_if_block) {
try renderExtraNewline(tree, ais, if_node.body);
} else if (body_is_block) {
const after_rparen_space = if (if_node.payload == null) Space.BlockStart else Space.Space;
try renderToken(tree, ais, rparen, after_rparen_space); // )
if (if_node.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.BlockStart); // |x|
}
if (if_node.@"else") |@"else"| {
try renderExpression(allocator, ais, tree, if_node.body, Space.SpaceOrOutdent);
return renderExpression(allocator, ais, tree, &@"else".base, space);
} else {
return renderExpression(allocator, ais, tree, if_node.body, space);
}
}
const src_has_newline = !tree.tokensOnSameLine(rparen, if_node.body.lastToken());
if (src_has_newline) {
const after_rparen_space = if (if_node.payload == null) Space.Newline else Space.Space;
{
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, rparen, after_rparen_space); // )
}
if (if_node.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Newline);
}
if (if_node.@"else") |@"else"| {
const else_is_block = nodeIsBlock(@"else".body);
{
ais.pushIndent();
defer ais.popIndent();
try renderExpression(allocator, ais, tree, if_node.body, Space.Newline);
}
if (else_is_block) {
try renderToken(tree, ais, @"else".else_token, Space.Space); // else
if (@"else".payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
return renderExpression(allocator, ais, tree, @"else".body, space);
} else {
const after_else_space = if (@"else".payload == null) Space.Newline else Space.Space;
try renderToken(tree, ais, @"else".else_token, after_else_space); // else
if (@"else".payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Newline);
}
ais.pushIndent();
defer ais.popIndent();
return renderExpression(allocator, ais, tree, @"else".body, space);
}
} else {
ais.pushIndent();
defer ais.popIndent();
return renderExpression(allocator, ais, tree, if_node.body, space);
}
}
// Single line if statement
try renderToken(tree, ais, rparen, Space.Space); // )
if (if_node.payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
if (if_node.@"else") |@"else"| {
try renderExpression(allocator, ais, tree, if_node.body, Space.Space);
try renderToken(tree, ais, @"else".else_token, Space.Space);
if (@"else".payload) |payload| {
try renderExpression(allocator, ais, tree, payload, Space.Space);
}
return renderExpression(allocator, ais, tree, @"else".body, space);
} else {
return renderExpression(allocator, ais, tree, if_node.body, space);
}
},
.Asm => {
const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base);
try renderToken(tree, ais, asm_node.asm_token, Space.Space); // asm
if (asm_node.volatile_token) |volatile_token| {
try renderToken(tree, ais, volatile_token, Space.Space); // volatile
try renderToken(tree, ais, tree.nextToken(volatile_token), Space.None); // (
} else {
try renderToken(tree, ais, tree.nextToken(asm_node.asm_token), Space.None); // (
}
asmblk: {
ais.pushIndent();
defer ais.popIndent();
if (asm_node.outputs.len == 0 and asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
try renderExpression(allocator, ais, tree, asm_node.template, Space.None);
break :asmblk;
}
try renderExpression(allocator, ais, tree, asm_node.template, Space.Newline);
ais.setIndentDelta(asm_indent_delta);
defer ais.setIndentDelta(indent_delta);
const colon1 = tree.nextToken(asm_node.template.lastToken());
const colon2 = if (asm_node.outputs.len == 0) blk: {
try renderToken(tree, ais, colon1, Space.Newline); // :
break :blk tree.nextToken(colon1);
} else blk: {
try renderToken(tree, ais, colon1, Space.Space); // :
ais.pushIndent();
defer ais.popIndent();
for (asm_node.outputs) |*asm_output, i| {
if (i + 1 < asm_node.outputs.len) {
const next_asm_output = asm_node.outputs[i + 1];
try renderAsmOutput(allocator, ais, tree, asm_output, Space.None);
const comma = tree.prevToken(next_asm_output.firstToken());
try renderToken(tree, ais, comma, Space.Newline); // ,
try renderExtraNewlineToken(tree, ais, next_asm_output.firstToken());
} else if (asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
try renderAsmOutput(allocator, ais, tree, asm_output, Space.Newline);
break :asmblk;
} else {
try renderAsmOutput(allocator, ais, tree, asm_output, Space.Newline);
const comma_or_colon = tree.nextToken(asm_output.lastToken());
break :blk switch (tree.token_ids[comma_or_colon]) {
.Comma => tree.nextToken(comma_or_colon),
else => comma_or_colon,
};
}
}
unreachable;
};
const colon3 = if (asm_node.inputs.len == 0) blk: {
try renderToken(tree, ais, colon2, Space.Newline); // :
break :blk tree.nextToken(colon2);
} else blk: {
try renderToken(tree, ais, colon2, Space.Space); // :
ais.pushIndent();
defer ais.popIndent();
for (asm_node.inputs) |*asm_input, i| {
if (i + 1 < asm_node.inputs.len) {
const next_asm_input = &asm_node.inputs[i + 1];
try renderAsmInput(allocator, ais, tree, asm_input, Space.None);
const comma = tree.prevToken(next_asm_input.firstToken());
try renderToken(tree, ais, comma, Space.Newline); // ,
try renderExtraNewlineToken(tree, ais, next_asm_input.firstToken());
} else if (asm_node.clobbers.len == 0) {
try renderAsmInput(allocator, ais, tree, asm_input, Space.Newline);
break :asmblk;
} else {
try renderAsmInput(allocator, ais, tree, asm_input, Space.Newline);
const comma_or_colon = tree.nextToken(asm_input.lastToken());
break :blk switch (tree.token_ids[comma_or_colon]) {
.Comma => tree.nextToken(comma_or_colon),
else => comma_or_colon,
};
}
}
unreachable;
};
try renderToken(tree, ais, colon3, Space.Space); // :
ais.pushIndent();
defer ais.popIndent();
for (asm_node.clobbers) |clobber_node, i| {
if (i + 1 >= asm_node.clobbers.len) {
try renderExpression(allocator, ais, tree, clobber_node, Space.Newline);
break :asmblk;
} else {
try renderExpression(allocator, ais, tree, clobber_node, Space.None);
const comma = tree.nextToken(clobber_node.lastToken());
try renderToken(tree, ais, comma, Space.Space); // ,
}
}
}
return renderToken(tree, ais, asm_node.rparen, space);
},
.EnumLiteral => {
const enum_literal = @fieldParentPtr(ast.Node.EnumLiteral, "base", base);
try renderToken(tree, ais, enum_literal.dot, Space.None); // .
return renderToken(tree, ais, enum_literal.name, space); // name
},
.ContainerField,
.Root,
.VarDecl,
.Use,
.TestDecl,
=> unreachable,
}
}
fn renderArrayType(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
lbracket: ast.TokenIndex,
rhs: *ast.Node,
len_expr: *ast.Node,
opt_sentinel: ?*ast.Node,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
const rbracket = tree.nextToken(if (opt_sentinel) |sentinel|
sentinel.lastToken()
else
len_expr.lastToken());
const starts_with_comment = tree.token_ids[lbracket + 1] == .LineComment;
const ends_with_comment = tree.token_ids[rbracket - 1] == .LineComment;
const new_space = if (ends_with_comment) Space.Newline else Space.None;
{
const do_indent = (starts_with_comment or ends_with_comment);
if (do_indent) ais.pushIndent();
defer if (do_indent) ais.popIndent();
try renderToken(tree, ais, lbracket, Space.None); // [
try renderExpression(allocator, ais, tree, len_expr, new_space);
if (starts_with_comment) {
try ais.maybeInsertNewline();
}
if (opt_sentinel) |sentinel| {
const colon_token = tree.prevToken(sentinel.firstToken());
try renderToken(tree, ais, colon_token, Space.None); // :
try renderExpression(allocator, ais, tree, sentinel, Space.None);
}
if (starts_with_comment) {
try ais.maybeInsertNewline();
}
}
try renderToken(tree, ais, rbracket, Space.None); // ]
return renderExpression(allocator, ais, tree, rhs, space);
}
fn renderAsmOutput(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
asm_output: *const ast.Node.Asm.Output,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
try ais.writer().writeAll("[");
try renderExpression(allocator, ais, tree, asm_output.symbolic_name, Space.None);
try ais.writer().writeAll("] ");
try renderExpression(allocator, ais, tree, asm_output.constraint, Space.None);
try ais.writer().writeAll(" (");
switch (asm_output.kind) {
.Variable => |variable_name| {
try renderExpression(allocator, ais, tree, &variable_name.base, Space.None);
},
.Return => |return_type| {
try ais.writer().writeAll("-> ");
try renderExpression(allocator, ais, tree, return_type, Space.None);
},
}
return renderToken(tree, ais, asm_output.lastToken(), space); // )
}
fn renderAsmInput(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
asm_input: *const ast.Node.Asm.Input,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
try ais.writer().writeAll("[");
try renderExpression(allocator, ais, tree, asm_input.symbolic_name, Space.None);
try ais.writer().writeAll("] ");
try renderExpression(allocator, ais, tree, asm_input.constraint, Space.None);
try ais.writer().writeAll(" (");
try renderExpression(allocator, ais, tree, asm_input.expr, Space.None);
return renderToken(tree, ais, asm_input.lastToken(), space); // )
}
fn renderVarDecl(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
var_decl: *ast.Node.VarDecl,
) (@TypeOf(ais.*).Error || Error)!void {
if (var_decl.getVisibToken()) |visib_token| {
try renderToken(tree, ais, visib_token, Space.Space); // pub
}
if (var_decl.getExternExportToken()) |extern_export_token| {
try renderToken(tree, ais, extern_export_token, Space.Space); // extern
if (var_decl.getLibName()) |lib_name| {
try renderExpression(allocator, ais, tree, lib_name, Space.Space); // "lib"
}
}
if (var_decl.getComptimeToken()) |comptime_token| {
try renderToken(tree, ais, comptime_token, Space.Space); // comptime
}
if (var_decl.getThreadLocalToken()) |thread_local_token| {
try renderToken(tree, ais, thread_local_token, Space.Space); // threadlocal
}
try renderToken(tree, ais, var_decl.mut_token, Space.Space); // var
const name_space = if (var_decl.getTypeNode() == null and
(var_decl.getAlignNode() != null or
var_decl.getSectionNode() != null or
var_decl.getInitNode() != null))
Space.Space
else
Space.None;
try renderToken(tree, ais, var_decl.name_token, name_space);
if (var_decl.getTypeNode()) |type_node| {
try renderToken(tree, ais, tree.nextToken(var_decl.name_token), Space.Space);
const s = if (var_decl.getAlignNode() != null or
var_decl.getSectionNode() != null or
var_decl.getInitNode() != null) Space.Space else Space.None;
try renderExpression(allocator, ais, tree, type_node, s);
}
if (var_decl.getAlignNode()) |align_node| {
const lparen = tree.prevToken(align_node.firstToken());
const align_kw = tree.prevToken(lparen);
const rparen = tree.nextToken(align_node.lastToken());
try renderToken(tree, ais, align_kw, Space.None); // align
try renderToken(tree, ais, lparen, Space.None); // (
try renderExpression(allocator, ais, tree, align_node, Space.None);
const s = if (var_decl.getSectionNode() != null or var_decl.getInitNode() != null) Space.Space else Space.None;
try renderToken(tree, ais, rparen, s); // )
}
if (var_decl.getSectionNode()) |section_node| {
const lparen = tree.prevToken(section_node.firstToken());
const section_kw = tree.prevToken(lparen);
const rparen = tree.nextToken(section_node.lastToken());
try renderToken(tree, ais, section_kw, Space.None); // linksection
try renderToken(tree, ais, lparen, Space.None); // (
try renderExpression(allocator, ais, tree, section_node, Space.None);
const s = if (var_decl.getInitNode() != null) Space.Space else Space.None;
try renderToken(tree, ais, rparen, s); // )
}
if (var_decl.getInitNode()) |init_node| {
const eq_token = var_decl.getEqToken().?;
const eq_space = blk: {
const loc = tree.tokenLocation(tree.token_locs[eq_token].end, tree.nextToken(eq_token));
break :blk if (loc.line == 0) Space.Space else Space.Newline;
};
{
ais.pushIndent();
defer ais.popIndent();
try renderToken(tree, ais, eq_token, eq_space); // =
}
ais.pushIndentOneShot();
try renderExpression(allocator, ais, tree, init_node, Space.None);
}
try renderToken(tree, ais, var_decl.semicolon_token, Space.Newline);
}
fn renderParamDecl(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
param_decl: ast.Node.FnProto.ParamDecl,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
try renderDocComments(tree, ais, param_decl, param_decl.doc_comments);
if (param_decl.comptime_token) |comptime_token| {
try renderToken(tree, ais, comptime_token, Space.Space);
}
if (param_decl.noalias_token) |noalias_token| {
try renderToken(tree, ais, noalias_token, Space.Space);
}
if (param_decl.name_token) |name_token| {
try renderToken(tree, ais, name_token, Space.None);
try renderToken(tree, ais, tree.nextToken(name_token), Space.Space); // :
}
switch (param_decl.param_type) {
.any_type, .type_expr => |node| try renderExpression(allocator, ais, tree, node, space),
}
}
fn renderStatement(
allocator: *mem.Allocator,
ais: anytype,
tree: *ast.Tree,
base: *ast.Node,
) (@TypeOf(ais.*).Error || Error)!void {
switch (base.tag) {
.VarDecl => {
const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);
try renderVarDecl(allocator, ais, tree, var_decl);
},
else => {
if (base.requireSemiColon()) {
try renderExpression(allocator, ais, tree, base, Space.None);
const semicolon_index = tree.nextToken(base.lastToken());
assert(tree.token_ids[semicolon_index] == .Semicolon);
try renderToken(tree, ais, semicolon_index, Space.Newline);
} else {
try renderExpression(allocator, ais, tree, base, Space.Newline);
}
},
}
}
const Space = enum {
None,
Newline,
Comma,
Space,
SpaceOrOutdent,
NoNewline,
NoComment,
BlockStart,
};
fn renderTokenOffset(
tree: *ast.Tree,
ais: anytype,
token_index: ast.TokenIndex,
space: Space,
token_skip_bytes: usize,
) (@TypeOf(ais.*).Error || Error)!void {
if (space == Space.BlockStart) {
// If placing the lbrace on the current line would cause an uggly gap then put the lbrace on the next line
const new_space = if (ais.isLineOverIndented()) Space.Newline else Space.Space;
return renderToken(tree, ais, token_index, new_space);
}
var token_loc = tree.token_locs[token_index];
try ais.writer().writeAll(mem.trimRight(u8, tree.tokenSliceLoc(token_loc)[token_skip_bytes..], " "));
if (space == Space.NoComment)
return;
var next_token_id = tree.token_ids[token_index + 1];
var next_token_loc = tree.token_locs[token_index + 1];
if (space == Space.Comma) switch (next_token_id) {
.Comma => return renderToken(tree, ais, token_index + 1, Space.Newline),
.LineComment => {
try ais.writer().writeAll(", ");
return renderToken(tree, ais, token_index + 1, Space.Newline);
},
else => {
if (token_index + 2 < tree.token_ids.len and
tree.token_ids[token_index + 2] == .MultilineStringLiteralLine)
{
try ais.writer().writeAll(",");
return;
} else {
try ais.writer().writeAll(",");
try ais.insertNewline();
return;
}
},
};
// Skip over same line doc comments
var offset: usize = 1;
if (next_token_id == .DocComment) {
const loc = tree.tokenLocationLoc(token_loc.end, next_token_loc);
if (loc.line == 0) {
offset += 1;
next_token_id = tree.token_ids[token_index + offset];
next_token_loc = tree.token_locs[token_index + offset];
}
}
if (next_token_id != .LineComment) {
switch (space) {
Space.None, Space.NoNewline => return,
Space.Newline => {
if (next_token_id == .MultilineStringLiteralLine) {
return;
} else {
try ais.insertNewline();
return;
}
},
Space.Space, Space.SpaceOrOutdent => {
if (next_token_id == .MultilineStringLiteralLine)
return;
try ais.writer().writeByte(' ');
return;
},
Space.NoComment, Space.Comma, Space.BlockStart => unreachable,
}
}
while (true) {
const comment_is_empty = mem.trimRight(u8, tree.tokenSliceLoc(next_token_loc), " ").len == 2;
if (comment_is_empty) {
switch (space) {
Space.Newline => {
offset += 1;
token_loc = next_token_loc;
next_token_id = tree.token_ids[token_index + offset];
next_token_loc = tree.token_locs[token_index + offset];
if (next_token_id != .LineComment) {
try ais.insertNewline();
return;
}
},
else => break,
}
} else {
break;
}
}
var loc = tree.tokenLocationLoc(token_loc.end, next_token_loc);
if (loc.line == 0) {
if (tree.token_ids[token_index] != .MultilineStringLiteralLine) {
try ais.writer().writeByte(' ');
}
try ais.writer().writeAll(mem.trimRight(u8, tree.tokenSliceLoc(next_token_loc), " "));
offset = 2;
token_loc = next_token_loc;
next_token_loc = tree.token_locs[token_index + offset];
next_token_id = tree.token_ids[token_index + offset];
if (next_token_id != .LineComment) {
switch (space) {
.None, .Space, .SpaceOrOutdent => {
try ais.insertNewline();
},
.Newline => {
if (next_token_id == .MultilineStringLiteralLine) {
return;
} else {
try ais.insertNewline();
return;
}
},
.NoNewline => {},
.NoComment, .Comma, .BlockStart => unreachable,
}
return;
}
loc = tree.tokenLocationLoc(token_loc.end, next_token_loc);
}
while (true) {
// translate-c doesn't generate correct newlines
// in generated code (loc.line == 0) so treat that case
// as though there was meant to be a newline between the tokens
var newline_count = if (loc.line <= 1) @as(u8, 1) else @as(u8, 2);
while (newline_count > 0) : (newline_count -= 1) try ais.insertNewline();
try ais.writer().writeAll(mem.trimRight(u8, tree.tokenSliceLoc(next_token_loc), " "));
offset += 1;
token_loc = next_token_loc;
next_token_loc = tree.token_locs[token_index + offset];
next_token_id = tree.token_ids[token_index + offset];
if (next_token_id != .LineComment) {
switch (space) {
.Newline => {
if (next_token_id == .MultilineStringLiteralLine) {
return;
} else {
try ais.insertNewline();
return;
}
},
.None, .Space, .SpaceOrOutdent => {
try ais.insertNewline();
},
.NoNewline => {},
.NoComment, .Comma, .BlockStart => unreachable,
}
return;
}
loc = tree.tokenLocationLoc(token_loc.end, next_token_loc);
}
}
fn renderToken(
tree: *ast.Tree,
ais: anytype,
token_index: ast.TokenIndex,
space: Space,
) (@TypeOf(ais.*).Error || Error)!void {
return renderTokenOffset(tree, ais, token_index, space, 0);
}
fn renderDocComments(
tree: *ast.Tree,
ais: anytype,
node: anytype,
doc_comments: ?*ast.Node.DocComment,
) (@TypeOf(ais.*).Error || Error)!void {
const comment = doc_comments orelse return;
return renderDocCommentsToken(tree, ais, comment, node.firstToken());
}
fn renderDocCommentsToken(
tree: *ast.Tree,
ais: anytype,
comment: *ast.Node.DocComment,
first_token: ast.TokenIndex,
) (@TypeOf(ais.*).Error || Error)!void {
var tok_i = comment.first_line;
while (true) : (tok_i += 1) {
switch (tree.token_ids[tok_i]) {
.DocComment, .ContainerDocComment => {
if (comment.first_line < first_token) {
try renderToken(tree, ais, tok_i, Space.Newline);
} else {
try renderToken(tree, ais, tok_i, Space.NoComment);
try ais.insertNewline();
}
},
.LineComment => continue,
else => break,
}
}
}
fn nodeIsBlock(base: *const ast.Node) bool {
return switch (base.tag) {
.Block,
.LabeledBlock,
.If,
.For,
.While,
.Switch,
=> true,
else => false,
};
}
fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
return switch (base.tag) {
.Catch,
.Add,
.AddWrap,
.ArrayCat,
.ArrayMult,
.Assign,
.AssignBitAnd,
.AssignBitOr,
.AssignBitShiftLeft,
.AssignBitShiftRight,
.AssignBitXor,
.AssignDiv,
.AssignSub,
.AssignSubWrap,
.AssignMod,
.AssignAdd,
.AssignAddWrap,
.AssignMul,
.AssignMulWrap,
.BangEqual,
.BitAnd,
.BitOr,
.BitShiftLeft,
.BitShiftRight,
.BitXor,
.BoolAnd,
.BoolOr,
.Div,
.EqualEqual,
.ErrorUnion,
.GreaterOrEqual,
.GreaterThan,
.LessOrEqual,
.LessThan,
.MergeErrorSets,
.Mod,
.Mul,
.MulWrap,
.Range,
.Sub,
.SubWrap,
.OrElse,
=> true,
else => false,
};
}
fn copyFixingWhitespace(ais: anytype, slice: []const u8) @TypeOf(ais.*).Error!void {
for (slice) |byte| switch (byte) {
'\t' => try ais.writer().writeAll(" "),
'\r' => {},
else => try ais.writer().writeByte(byte),
};
}
// Returns the number of nodes in `expr` that are on the same line as `rtoken`,
// or null if they all are on the same line.
fn rowSize(tree: *ast.Tree, exprs: []*ast.Node, rtoken: ast.TokenIndex) ?usize {
const first_token = exprs[0].firstToken();
const first_loc = tree.tokenLocation(tree.token_locs[first_token].start, rtoken);
if (first_loc.line == 0) {
const maybe_comma = tree.prevToken(rtoken);
if (tree.token_ids[maybe_comma] == .Comma)
return 1;
return null; // no newlines
}
var count: usize = 1;
for (exprs) |expr, i| {
if (i + 1 < exprs.len) {
const expr_last_token = expr.lastToken() + 1;
const loc = tree.tokenLocation(tree.token_locs[expr_last_token].start, exprs[i + 1].firstToken());
if (loc.line != 0) return count;
count += 1;
} else {
return count;
}
}
unreachable;
} | lib/std/zig/render.zig |
const std = @import("std");
const multiboot = @import("multiboot.zig");
const image_info = @import("image_info.zig");
const Console = @import("Console.zig");
const descriptor = @import("descriptor.zig");
const err = std.log.err;
const warn = std.log.warn;
const dbg = std.log.debug;
const info = std.log.info;
const emerg = std.log.emerg;
var maybe_console: ?Console = null;
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
if (maybe_console == null) {
return;
}
var console = &maybe_console.?;
var prefix: []const u8 = undefined;
console.foreground_color = .default;
console.background_color = .default;
switch (message_level) {
.emerg => {
console.background_color = .red;
console.foreground_color = .white;
prefix = "emergency";
},
.alert => {
console.background_color = .cyan;
console.foreground_color = .white;
prefix = "alert";
},
.crit => {
console.background_color = .yellow;
console.foreground_color = .white;
prefix = "critical";
},
.err => {
console.foreground_color = .light_red;
prefix = "error";
},
.warn => {
console.foreground_color = .light_yellow;
prefix = "warning";
},
.notice => {
console.foreground_color = .light_cyan;
prefix = "notice";
},
.info => {
prefix = "info";
},
.debug => {
console.foreground_color = .light_blue;
prefix = "debug";
},
}
console.write_string(prefix);
console.foreground_color = .default;
console.background_color = .default;
console.write_string(": ");
console.write_formatted(format, args);
console.write_string("\n");
}
pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
//x86.interrupt.disable();
std.log.emerg("Unrecoverable panic occured:", .{});
std.log.emerg(" {s}", .{msg});
std.log.emerg("Please restart the computer.", .{});
if (error_return_trace) |trace| {
// TODO
}
while (true) {}
}
fn print_banner() void {
var console = &maybe_console.?;
console.foreground_color = .light_red;
// Line 0
console.write_string("@@@@@ @@@@@\n");
// Line 1
console.write_string("@....@ @....@");
console.foreground_color = .default;
console.write_string(" Ribbon Operating System \n");
console.foreground_color = .light_red;
// Line 2
console.write_string("@.....@.....@\n");
// Line 3
console.write_string("@....@ @....@");
console.foreground_color = .default;
console.write_string(" Copyright (c) 2021 YeonJiKun <<EMAIL>> \n");
console.foreground_color = .light_red;
// Line 4
console.write_string("@@@@@ @@@@@\n");
// Line 5
console.write_string("\n");
console.foreground_color = .default;
warn("============================ NO WARRANTY! ============================", .{});
warn("This software does not come with ANY WARRANTY!", .{});
warn("YeonJiKun is not responsible for any damage caused by this software.", .{});
warn("Use at your own risk!", .{});
warn("============================ NO WARRANTY! ============================", .{});
console.write_string("\n");
}
export fn x_main_entry(multiboot_magic: u32, multiboot_info: *const multiboot.MultibootInfo) noreturn {
maybe_console = Console.initialize();
var console = &maybe_console.?;
console.clear_and_reset_cursor();
print_banner();
info("Start address of the kernel image: V{X}", .{image_info.start_virtual_address()});
info("End address of the kernel image: V{X}", .{image_info.end_virtual_address()});
dbg("multiboot_info={}", .{multiboot_info});
std.testing.expect(multiboot_magic == multiboot.magic) catch {
emerg("multiboot_magic({X}) is NOT {}!", .{ multiboot_magic, multiboot.magic });
@panic("Multiboot magic mismatch");
};
if (!multiboot_info._is_memory_map_present) {
emerg("Bootloader didn't pass memory information to the OS!", .{});
@panic("No memory information from the bootloader");
}
info("Setting up descriptors...", .{});
descriptor.initialize();
while (true) {}
} | kernel/main.zig |
const std = @import("std");
const builtin = @import("builtin");
pub fn suggestVectorSizeForCpu(comptime T: type, cpu: std.Target.Cpu) ?usize {
switch (cpu.arch) {
.x86_64 => {
// Note: This is mostly just guesswork. It'd be great if someone more qualified were to take a
// proper look at this.
if (T == bool and std.Target.x86.featureSetHas(.prefer_mask_registers)) return 64;
const vector_bit_size = blk: {
if (std.Target.x86.featureSetHas(.avx512f)) break :blk 512;
if (std.Target.x86.featureSetHas(.prefer_256_bit)) break :blk 256;
if (std.Target.x86.featureSetHas(.prefer_128_bit)) break :blk 128;
return null;
};
const element_bit_size = std.math.max(8, std.math.ceilPowerOfTwo(T, @bitSizeOf(T)));
return @divExact(vector_bit_size, element_bit_size);
},
else => {
return null;
},
}
}
/// Suggests a target-dependant vector size for a given type, or null if scalars are recommended.
/// Not yet implemented for every CPU architecture.
pub fn suggestVectorSize(comptime T: type) ?usize {
return suggestVectorSizeForCpu(T, builtin.cpu);
}
fn vectorLength(comptime VectorType: type) comptime_int {
return switch (@typeInfo(VectorType)) {
.Vector => |info| info.len,
.Array => |info| info.len,
else => @compileError("Invalid type " ++ @typeName(VectorType)),
};
}
/// Returns the smallest type of unsigned ints capable of indexing any element within the given vector type.
pub fn VectorIndex(comptime VectorType: type) type {
return std.math.IntFittingRange(0, vectorLength(VectorType) - 1);
}
/// Returns the smallest type of unsigned ints capable of holding the length of the given vector type.
pub fn VectorCount(comptime VectorType: type) type {
return std.math.IntFittingRange(0, vectorLength(VectorType));
}
/// Returns a vector containing the first `len` integers in order from 0 to `len`-1.
/// For example, `iota(i32, 8)` will return a vector containing `.{0, 1, 2, 3, 4, 5, 6, 7}`.
pub fn iota(comptime T: type, comptime len: usize) @Vector(len, T) {
var out: [len]T = undefined;
for (out) |*element, i| {
element.* = switch (@typeInfo(T)) {
.Int => @intCast(T, i),
.Float => @intToFloat(T, i),
else => @compileError("Can't use type " ++ @typeName(T) ++ " in iota."),
};
}
return @as(@Vector(len, T), out);
}
/// Returns a vector containing the same elements as the input, but repeated until the desired length is reached.
/// For example, `repeat(8, [_]u32{1, 2, 3})` will return a vector containing `.{1, 2, 3, 1, 2, 3, 1, 2}`.
pub fn repeat(comptime len: usize, vec: anytype) @Vector(len, std.meta.Child(@TypeOf(vec))) {
const Child = std.meta.Child(@TypeOf(vec));
return @shuffle(Child, vec, undefined, iota(i32, len) % @splat(len, @intCast(i32, vectorLength(@TypeOf(vec)))));
}
/// Returns a vector containing all elements of the first vector at the lower indices followed by all elements of the second vector
/// at the higher indices.
pub fn join(a: anytype, b: anytype) @Vector(vectorLength(@TypeOf(a)) + vectorLength(@TypeOf(b)), std.meta.Child(@TypeOf(a))) {
const Child = std.meta.Child(@TypeOf(a));
const a_len = vectorLength(@TypeOf(a));
const b_len = vectorLength(@TypeOf(b));
return @shuffle(Child, a, b, @as([a_len]i32, iota(i32, a_len)) ++ @as([b_len]i32, ~iota(i32, b_len)));
}
/// Returns a vector whose elements alternates between those of each input vector.
/// For example, `interlace(.{[4]u32{11, 12, 13, 14}, [4]u32{21, 22, 23, 24}})` returns a vector containing `.{11, 21, 12, 22, 13, 23, 14, 24}`.
pub fn interlace(vecs: anytype) @Vector(vectorLength(@TypeOf(vecs[0])) * vecs.len, std.meta.Child(@TypeOf(vecs[0]))) {
// interlace doesn't work on MIPS, for some reason.
// Notes from earlier debug attempt:
// The indices are correct. The problem seems to be with the @shuffle builtin.
// On MIPS, the test that interlaces small_base gives { 0, 2, 0, 0, 64, 255, 248, 200, 0, 0 }.
// Calling this with two inputs seems to work fine, but I'll let the compile error trigger for all inputs, just to be safe.
comptime if (builtin.cpu.arch.isMIPS()) @compileError("TODO: Find out why interlace() doesn't work on MIPS");
const VecType = @TypeOf(vecs[0]);
const vecs_arr = @as([vecs.len]VecType, vecs);
const Child = std.meta.Child(@TypeOf(vecs_arr[0]));
if (vecs_arr.len == 1) return vecs_arr[0];
const a_vec_count = (1 + vecs_arr.len) >> 1;
const b_vec_count = vecs_arr.len >> 1;
const a = interlace(@ptrCast(*const [a_vec_count]VecType, vecs_arr[0..a_vec_count]).*);
const b = interlace(@ptrCast(*const [b_vec_count]VecType, vecs_arr[a_vec_count..]).*);
const a_len = vectorLength(@TypeOf(a));
const b_len = vectorLength(@TypeOf(b));
const len = a_len + b_len;
const indices = comptime blk: {
const count_up = iota(i32, len);
const cycle = @divFloor(count_up, @splat(len, @intCast(i32, vecs_arr.len)));
const select_mask = repeat(len, join(@splat(a_vec_count, true), @splat(b_vec_count, false)));
const a_indices = count_up - cycle * @splat(len, @intCast(i32, b_vec_count));
const b_indices = shiftElementsRight(count_up - cycle * @splat(len, @intCast(i32, a_vec_count)), a_vec_count, 0);
break :blk @select(i32, select_mask, a_indices, ~b_indices);
};
return @shuffle(Child, a, b, indices);
}
/// The contents of `interlaced` is evenly split between vec_count vectors that are returned as an array. They "take turns",
/// recieving one element from `interlaced` at a time.
pub fn deinterlace(
comptime vec_count: usize,
interlaced: anytype,
) [vec_count]@Vector(
vectorLength(@TypeOf(interlaced)) / vec_count,
std.meta.Child(@TypeOf(interlaced)),
) {
const vec_len = vectorLength(@TypeOf(interlaced)) / vec_count;
const Child = std.meta.Child(@TypeOf(interlaced));
var out: [vec_count]@Vector(vec_len, Child) = undefined;
comptime var i: usize = 0; // for-loops don't work for this, apparently.
inline while (i < out.len) : (i += 1) {
const indices = comptime iota(i32, vec_len) * @splat(vec_len, @intCast(i32, vec_count)) + @splat(vec_len, @intCast(i32, i));
out[i] = @shuffle(Child, interlaced, undefined, indices);
}
return out;
}
pub fn extract(
vec: anytype,
comptime first: VectorIndex(@TypeOf(vec)),
comptime count: VectorCount(@TypeOf(vec)),
) @Vector(count, std.meta.Child(@TypeOf(vec))) {
const Child = std.meta.Child(@TypeOf(vec));
const len = vectorLength(@TypeOf(vec));
std.debug.assert(@intCast(comptime_int, first) + @intCast(comptime_int, count) <= len);
return @shuffle(Child, vec, undefined, iota(i32, count) + @splat(count, @intCast(i32, first)));
}
test "vector patterns" {
if (@import("builtin").zig_backend != .stage1) return error.SkipZigTest;
const base = @Vector(4, u32){ 10, 20, 30, 40 };
const other_base = @Vector(4, u32){ 55, 66, 77, 88 };
const small_bases = [5]@Vector(2, u8){
@Vector(2, u8){ 0, 1 },
@Vector(2, u8){ 2, 3 },
@Vector(2, u8){ 4, 5 },
@Vector(2, u8){ 6, 7 },
@Vector(2, u8){ 8, 9 },
};
try std.testing.expectEqual([6]u32{ 10, 20, 30, 40, 10, 20 }, repeat(6, base));
try std.testing.expectEqual([8]u32{ 10, 20, 30, 40, 55, 66, 77, 88 }, join(base, other_base));
try std.testing.expectEqual([2]u32{ 20, 30 }, extract(base, 1, 2));
if (comptime !builtin.cpu.arch.isMIPS()) {
try std.testing.expectEqual([8]u32{ 10, 55, 20, 66, 30, 77, 40, 88 }, interlace(.{ base, other_base }));
const small_braid = interlace(small_bases);
try std.testing.expectEqual([10]u8{ 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 }, small_braid);
try std.testing.expectEqual(small_bases, deinterlace(small_bases.len, small_braid));
}
}
/// Joins two vectors, shifts them leftwards (towards lower indices) and extracts the leftmost elements into a vector the size of a and b.
pub fn mergeShift(a: anytype, b: anytype, comptime shift: VectorCount(@TypeOf(a, b))) @TypeOf(a, b) {
const len = vectorLength(@TypeOf(a, b));
return extract(join(a, b), shift, len);
}
/// Elements are shifted rightwards (towards higher indices). New elements are added to the left, and the rightmost elements are cut off
/// so that the size of the vector stays the same.
pub fn shiftElementsRight(vec: anytype, comptime amount: VectorCount(@TypeOf(vec)), shift_in: std.meta.Child(@TypeOf(vec))) @TypeOf(vec) {
// It may be possible to implement shifts and rotates with a runtime-friendly slice of two joined vectors, as the length of the
// slice would be comptime-known. This would permit vector shifts and rotates by a non-comptime-known amount.
// However, I am unsure whether compiler optimizations would handle that well enough on all platforms.
const len = vectorLength(@TypeOf(vec));
return mergeShift(@splat(len, shift_in), vec, len - amount);
}
/// Elements are shifted leftwards (towards lower indices). New elements are added to the right, and the leftmost elements are cut off
/// so that no elements with indices below 0 remain.
pub fn shiftElementsLeft(vec: anytype, comptime amount: VectorCount(@TypeOf(vec)), shift_in: std.meta.Child(@TypeOf(vec))) @TypeOf(vec) {
const len = vectorLength(@TypeOf(vec));
return mergeShift(vec, @splat(len, shift_in), amount);
}
/// Elements are shifted leftwards (towards lower indices). Elements that leave to the left will reappear to the right in the same order.
pub fn rotateElementsLeft(vec: anytype, comptime amount: VectorCount(@TypeOf(vec))) @TypeOf(vec) {
return mergeShift(vec, vec, amount);
}
/// Elements are shifted rightwards (towards higher indices). Elements that leave to the right will reappear to the left in the same order.
pub fn rotateElementsRight(vec: anytype, comptime amount: VectorCount(@TypeOf(vec))) @TypeOf(vec) {
return rotateElementsLeft(vec, vectorLength(@TypeOf(vec)) - amount);
}
pub fn reverseOrder(vec: anytype) @TypeOf(vec) {
const Child = std.meta.Child(@TypeOf(vec));
const len = vectorLength(@TypeOf(vec));
return @shuffle(Child, vec, undefined, @splat(len, @intCast(i32, len) - 1) - iota(i32, len));
}
test "vector shifting" {
const base = @Vector(4, u32){ 10, 20, 30, 40 };
try std.testing.expectEqual([4]u32{ 30, 40, 999, 999 }, shiftElementsLeft(base, 2, 999));
try std.testing.expectEqual([4]u32{ 999, 999, 10, 20 }, shiftElementsRight(base, 2, 999));
try std.testing.expectEqual([4]u32{ 20, 30, 40, 10 }, rotateElementsLeft(base, 1));
try std.testing.expectEqual([4]u32{ 40, 10, 20, 30 }, rotateElementsRight(base, 1));
try std.testing.expectEqual([4]u32{ 40, 30, 20, 10 }, reverseOrder(base));
}
pub fn firstTrue(vec: anytype) ?VectorIndex(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
const IndexInt = VectorIndex(@TypeOf(vec));
if (!@reduce(.Or, vec)) {
return null;
}
const indices = @select(IndexInt, vec, iota(IndexInt, len), @splat(len, ~@as(IndexInt, 0)));
return @reduce(.Min, indices);
}
pub fn lastTrue(vec: anytype) ?VectorIndex(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
const IndexInt = VectorIndex(@TypeOf(vec));
if (!@reduce(.Or, vec)) {
return null;
}
const indices = @select(IndexInt, vec, iota(IndexInt, len), @splat(len, @as(IndexInt, 0)));
return @reduce(.Max, indices);
}
pub fn countTrues(vec: anytype) VectorCount(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
const CountIntType = VectorCount(@TypeOf(vec));
const one_if_true = @select(CountIntType, vec, @splat(len, @as(CountIntType, 1)), @splat(len, @as(CountIntType, 0)));
return @reduce(.Add, one_if_true);
}
pub fn firstIndexOfValue(vec: anytype, value: std.meta.Child(@TypeOf(vec))) ?VectorIndex(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
return firstTrue(vec == @splat(len, value));
}
pub fn lastIndexOfValue(vec: anytype, value: std.meta.Child(@TypeOf(vec))) ?VectorIndex(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
return lastTrue(vec == @splat(len, value));
}
pub fn countElementsWithValue(vec: anytype, value: std.meta.Child(@TypeOf(vec))) VectorCount(@TypeOf(vec)) {
const len = vectorLength(@TypeOf(vec));
return countTrues(vec == @splat(len, value));
}
test "vector searching" {
const base = @Vector(8, u32){ 6, 4, 7, 4, 4, 2, 3, 7 };
try std.testing.expectEqual(@as(?u3, 1), firstIndexOfValue(base, 4));
try std.testing.expectEqual(@as(?u3, 4), lastIndexOfValue(base, 4));
try std.testing.expectEqual(@as(?u3, null), lastIndexOfValue(base, 99));
try std.testing.expectEqual(@as(u4, 3), countElementsWithValue(base, 4));
}
/// Same as prefixScan, but with a user-provided, mathematically associative function.
pub fn prefixScanWithFunc(
comptime hop: isize,
vec: anytype,
/// The error type that `func` might return. Set this to `void` if `func` doesn't return an error union.
comptime ErrorType: type,
comptime func: fn (@TypeOf(vec), @TypeOf(vec)) if (ErrorType == void) @TypeOf(vec) else ErrorType!@TypeOf(vec),
/// When one operand of the operation performed by `func` is this value, the result must equal the other operand.
/// For example, this should be 0 for addition or 1 for multiplication.
comptime identity: std.meta.Child(@TypeOf(vec)),
) if (ErrorType == void) @TypeOf(vec) else ErrorType!@TypeOf(vec) {
// I haven't debugged this, but it might be a cousin of sorts to what's going on with interlace.
comptime if (builtin.cpu.arch.isMIPS()) @compileError("TODO: Find out why prefixScan doesn't work on MIPS");
const len = vectorLength(@TypeOf(vec));
if (hop == 0) @compileError("hop can not be 0; you'd be going nowhere forever!");
const abs_hop = if (hop < 0) -hop else hop;
var acc = vec;
comptime var i = 0;
inline while ((abs_hop << i) < len) : (i += 1) {
const shifted = if (hop < 0) shiftElementsLeft(acc, abs_hop << i, identity) else shiftElementsRight(acc, abs_hop << i, identity);
acc = if (ErrorType == void) func(acc, shifted) else try func(acc, shifted);
}
return acc;
}
/// Returns a vector whose elements are the result of performing the specified operation on the corresponding
/// element of the input vector and every hop'th element that came before it (or after, if hop is negative).
/// Supports the same operations as the @reduce() builtin. Takes O(logN) to compute.
/// The scan is not linear, which may affect floating point errors. This may affect the determinism of
/// algorithms that use this function.
pub fn prefixScan(comptime op: std.builtin.ReduceOp, comptime hop: isize, vec: anytype) @TypeOf(vec) {
const VecType = @TypeOf(vec);
const Child = std.meta.Child(VecType);
const len = vectorLength(VecType);
const identity = comptime switch (@typeInfo(Child)) {
.Bool => switch (op) {
.Or, .Xor => false,
.And => true,
else => @compileError("Invalid prefixScan operation " ++ @tagName(op) ++ " for vector of booleans."),
},
.Int => switch (op) {
.Max => std.math.minInt(Child),
.Add, .Or, .Xor => 0,
.Mul => 1,
.And, .Min => std.math.maxInt(Child),
},
.Float => switch (op) {
.Max => -std.math.inf(Child),
.Add => 0,
.Mul => 1,
.Min => std.math.inf(Child),
else => @compileError("Invalid prefixScan operation " ++ @tagName(op) ++ " for vector of floats."),
},
else => @compileError("Invalid type " ++ @typeName(VecType) ++ " for prefixScan."),
};
const fn_container = struct {
fn opFn(a: VecType, b: VecType) VecType {
return if (Child == bool) switch (op) {
.And => @select(bool, a, b, @splat(len, false)),
.Or => @select(bool, a, @splat(len, true), b),
.Xor => a != b,
else => unreachable,
} else switch (op) {
.And => a & b,
.Or => a | b,
.Xor => a ^ b,
.Add => a + b,
.Mul => a * b,
.Min => @minimum(a, b),
.Max => @maximum(a, b),
};
}
};
return prefixScanWithFunc(hop, vec, void, fn_container.opFn, identity);
}
test "vector prefix scan" {
if (comptime builtin.cpu.arch.isMIPS()) {
return error.SkipZigTest;
}
const int_base = @Vector(4, i32){ 11, 23, 9, -21 };
const float_base = @Vector(4, f32){ 2, 0.5, -10, 6.54321 };
const bool_base = @Vector(4, bool){ true, false, true, false };
try std.testing.expectEqual(iota(u8, 32) + @splat(32, @as(u8, 1)), prefixScan(.Add, 1, @splat(32, @as(u8, 1))));
try std.testing.expectEqual(@Vector(4, i32){ 11, 3, 1, 1 }, prefixScan(.And, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 31, 31, -1 }, prefixScan(.Or, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 28, 21, -2 }, prefixScan(.Xor, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 34, 43, 22 }, prefixScan(.Add, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 253, 2277, -47817 }, prefixScan(.Mul, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 11, 9, -21 }, prefixScan(.Min, 1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 23, 23, 23 }, prefixScan(.Max, 1, int_base));
// Trying to predict all inaccuracies when adding and multiplying floats with prefixScans would be a mess, so we don't test those.
try std.testing.expectEqual(@Vector(4, f32){ 2, 0.5, -10, -10 }, prefixScan(.Min, 1, float_base));
try std.testing.expectEqual(@Vector(4, f32){ 2, 2, 2, 6.54321 }, prefixScan(.Max, 1, float_base));
try std.testing.expectEqual(@Vector(4, bool){ true, true, false, false }, prefixScan(.Xor, 1, bool_base));
try std.testing.expectEqual(@Vector(4, bool){ true, true, true, true }, prefixScan(.Or, 1, bool_base));
try std.testing.expectEqual(@Vector(4, bool){ true, false, false, false }, prefixScan(.And, 1, bool_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 23, 20, 2 }, prefixScan(.Add, 2, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 22, 11, -12, -21 }, prefixScan(.Add, -1, int_base));
try std.testing.expectEqual(@Vector(4, i32){ 11, 23, 9, -10 }, prefixScan(.Add, 3, int_base));
} | lib/std/simd.zig |
// from Holding Hands
// by <NAME>
//
// Now that we have tails all figured out, can you implement trunks?
//
const std = @import("std");
const Elephant = struct {
letter: u8,
tail: ?*Elephant = null,
trunk: ?*Elephant = null,
visited: bool = false,
// Elephant tail methods!
pub fn getTail(self: *Elephant) *Elephant {
return self.tail.?; // Remember, this means "orelse unreachable"
}
pub fn hasTail(self: *Elephant) bool {
return (self.tail != null);
}
// Your Elephant trunk methods go here!
// ---------------------------------------------------
pub fn hasTrunk(self: *Elephant) bool {
return (self.trunk != null);
}
pub fn getTrunk(self: *Elephant) *Elephant {
return self.trunk.?;
}
// ---------------------------------------------------
pub fn visit(self: *Elephant) void {
self.visited = true;
}
pub fn print(self: *Elephant) void {
// Prints elephant letter and [v]isited
var v: u8 = if (self.visited) 'v' else ' ';
std.debug.print("{u}{u} ", .{ self.letter, v });
}
};
pub fn main() void {
var elephantA = Elephant{ .letter = 'A' };
var elephantB = Elephant{ .letter = 'B' };
var elephantC = Elephant{ .letter = 'C' };
// We link the elephants so that each tail "points" to the next.
elephantA.tail = &elephantB;
elephantB.tail = &elephantC;
// And link the elephants so that each trunk "points" to the previous.
elephantB.trunk = &elephantA;
elephantC.trunk = &elephantB;
visitElephants(&elephantA);
std.debug.print("\n", .{});
}
// This function visits all elephants twice, tails to trunks.
fn visitElephants(first_elephant: *Elephant) void {
var e = first_elephant;
// We follow the tails!
while (true) {
e.print();
e.visit();
// This gets the next elephant or stops.
if (e.hasTail()) {
e = e.getTail();
} else {
break;
}
}
// We follow the trunks!
while (true) {
e.print();
// This gets the previous elephant or stops.
if (e.hasTrunk()) {
e = e.getTrunk();
} else {
break;
}
}
} | exercises/049_quiz6.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day5");
defer input_.deinit();
const result = try part1(&input_);
try stdout.print("5a: {}\n", .{ result });
std.debug.assert(result == 8622);
}
{
var input_ = try input.readFile("inputs/day5");
defer input_.deinit();
const result = try part2(&input_);
try stdout.print("5b: {}\n", .{ result });
std.debug.assert(result == 22037);
}
}
fn part1(input_: anytype) !usize {
return solve(input_, false);
}
fn part2(input_: anytype) !usize {
return solve(input_, true);
}
const Line = struct {
start: Coord,
end: Coord,
fn init(s: []const u8) !@This() {
var parts = std.mem.split(u8, s, " -> ");
const start = parts.next() orelse return error.InvalidInput;
const end = parts.next() orelse return error.InvalidInput;
return Line {
.start = try Coord.init(start),
.end = try Coord.init(end),
};
}
};
const Coord = struct {
const max = 999;
const Type = std.math.IntFittingRange(0, max);
x: Type,
y: Type,
fn init(s: []const u8) !@This() {
var parts = std.mem.split(u8, s, ",");
const x = parts.next() orelse return error.InvalidInput;
const y = parts.next() orelse return error.InvalidInput;
return Coord {
.x = try std.fmt.parseInt(Type, x, 10),
.y = try std.fmt.parseInt(Type, y, 10),
};
}
};
const Pos = enum {
none,
one,
many,
fn markVent(self: *@This()) void {
self.* = switch (self.*) {
.none => .one,
.one => .many,
.many => .many,
};
}
};
fn solve(input_: anytype, consider_diagonals: bool) !usize {
var result: usize = 0;
var grid: [Coord.max + 1][Coord.max + 1]Pos = [_][Coord.max + 1]Pos { [_]Pos{ .none } ** (Coord.max + 1) } ** (Coord.max + 1);
while (try input_.next()) |line_s| {
const line = try Line.init(line_s);
if (!consider_diagonals and line.start.x != line.end.x and line.start.y != line.end.y) {
continue;
}
var x = line.start.x;
var y = line.start.y;
while (true) {
grid[x][y].markVent();
if (x == line.end.x and y == line.end.y) {
break;
}
switch (std.math.order(line.start.x, line.end.x)) {
.lt => x += 1,
.eq => {},
.gt => x -= 1,
}
switch (std.math.order(line.start.y, line.end.y)) {
.lt => y += 1,
.eq => {},
.gt => y -= 1,
}
}
}
for (grid) |*row| {
result += std.mem.count(Pos, row, &[_]Pos { .many });
}
return result;
}
test "day 5 example 1" {
const input_ =
\\0,9 -> 5,9
\\8,0 -> 0,8
\\9,4 -> 3,4
\\2,2 -> 2,1
\\7,0 -> 7,4
\\6,4 -> 2,0
\\0,9 -> 2,9
\\3,4 -> 1,4
\\0,0 -> 8,8
\\5,5 -> 8,2
;
try std.testing.expectEqual(@as(usize, 5), try part1(&input.readString(input_)));
try std.testing.expectEqual(@as(usize, 12), try part2(&input.readString(input_)));
} | src/day5.zig |
const interface = @import("interface.zig");
const Interface = interface.Interface;
const SelfType = interface.SelfType;
const std = @import("std");
const mem = std.mem;
const expectEqual = std.testing.expectEqual;
const assert = std.debug.assert;
test "Simple NonOwning interface" {
const NonOwningTest = struct {
fn run() !void {
const Fooer = Interface(struct {
foo: fn (*SelfType) usize,
}, interface.Storage.NonOwning);
const TestFooer = struct {
const Self = @This();
state: usize,
pub fn foo(self: *Self) usize {
const tmp = self.state;
self.state += 1;
return tmp;
}
};
var f = TestFooer{ .state = 42 };
var fooer = try Fooer.init(&f);
defer fooer.deinit();
try expectEqual(@as(usize, 42), fooer.call("foo", .{}));
try expectEqual(@as(usize, 43), fooer.call("foo", .{}));
}
};
try NonOwningTest.run();
comptime try NonOwningTest.run();
}
test "Comptime only interface" {
// return error.SkipZigTest;
const TestIFace = Interface(struct {
foo: fn (*SelfType, u8) u8,
}, interface.Storage.Comptime);
const TestType = struct {
const Self = @This();
state: u8,
pub fn foo(self: Self, a: u8) u8 {
return self.state + a;
}
};
comptime var iface = try TestIFace.init(TestType{ .state = 0 });
try expectEqual(@as(u8, 42), iface.call("foo", .{42}));
}
test "Owning interface with optional function and a non-method function" {
const OwningOptionalFuncTest = struct {
fn run() !void {
const TestOwningIface = Interface(struct {
someFn: ?fn (*const SelfType, usize, usize) usize,
otherFn: fn (*SelfType, usize) anyerror!void,
thirdFn: fn (usize) usize,
}, interface.Storage.Owning);
const TestStruct = struct {
const Self = @This();
state: usize,
pub fn someFn(self: Self, a: usize, b: usize) usize {
return self.state * a + b;
}
// Note that our return type need only coerce to the virtual function's
// return type.
pub fn otherFn(self: *Self, new_state: usize) void {
self.state = new_state;
}
pub fn thirdFn(arg: usize) usize {
return arg + 1;
}
};
var iface_instance = try TestOwningIface.init(comptime TestStruct{ .state = 0 }, std.testing.allocator);
defer iface_instance.deinit();
try iface_instance.call("otherFn", .{100});
try expectEqual(@as(usize, 42), iface_instance.call("someFn", .{ 0, 42 }).?);
try expectEqual(@as(usize, 101), iface_instance.call("thirdFn", .{100}));
}
};
try OwningOptionalFuncTest.run();
}
test "Interface with virtual async function implemented by an async function" {
const AsyncIFace = Interface(struct {
pub const async_call_stack_size = 1024;
foo: fn (*SelfType) callconv(.Async) void,
}, interface.Storage.NonOwning);
const Impl = struct {
const Self = @This();
state: usize,
frame: anyframe = undefined,
pub fn foo(self: *Self) void {
suspend {
self.frame = @frame();
}
self.state += 1;
suspend {}
self.state += 1;
}
};
var i = Impl{ .state = 0 };
var instance = try AsyncIFace.init(&i);
_ = async instance.call("foo", .{});
try expectEqual(@as(usize, 0), i.state);
resume i.frame;
try expectEqual(@as(usize, 1), i.state);
resume i.frame;
try expectEqual(@as(usize, 2), i.state);
}
test "Interface with virtual async function implemented by a blocking function" {
const AsyncIFace = Interface(struct {
readBytes: fn (*SelfType, []u8) callconv(.Async) anyerror!void,
}, interface.Storage.Inline(8));
const Impl = struct {
const Self = @This();
pub fn readBytes(self: Self, outBuf: []u8) void {
_ = self;
for (outBuf) |*c| {
c.* = 3;
}
}
};
var instance = try AsyncIFace.init(Impl{});
var buf: [256]u8 = undefined;
try await async instance.call("readBytes", .{buf[0..]});
try expectEqual([_]u8{3} ** 256, buf);
} | examples.zig |
const std = @import("std");
const os = std.os;
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
const xkb = @import("xkbcommon");
const gpa = std.heap.c_allocator;
pub fn main() anyerror!void {
wlr.log.init(.debug);
var server: Server = undefined;
try server.init();
defer server.deinit();
var buf: [11]u8 = undefined;
const socket = try server.wl_server.addSocketAuto(&buf);
if (os.argv.len >= 2) {
const cmd = std.mem.span(os.argv[1]);
var child = try std.ChildProcess.init(&[_][]const u8{ "/bin/sh", "-c", cmd }, gpa);
var env_map = try std.process.getEnvMap(gpa);
try env_map.set("WAYLAND_DISPLAY", socket);
child.env_map = &env_map;
try child.spawn();
}
try server.backend.start();
std.log.info("Runnnig compositor on WAYLAND_DISPLAY={}", .{socket});
server.wl_server.run();
}
const Server = struct {
wl_server: *wl.Server,
backend: *wlr.Backend,
renderer: *wlr.Renderer,
output_layout: *wlr.OutputLayout,
new_output: wl.Listener(*wlr.Output) = wl.Listener(*wlr.Output).init(newOutput),
xdg_shell: *wlr.XdgShell,
new_xdg_surface: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(newXdgSurface),
views: wl.list.Head(View, "link") = undefined,
seat: *wlr.Seat,
new_input: wl.Listener(*wlr.InputDevice) = wl.Listener(*wlr.InputDevice).init(newInput),
request_set_cursor: wl.Listener(*wlr.Seat.event.RequestSetCursor) = wl.Listener(*wlr.Seat.event.RequestSetCursor).init(requestSetCursor),
request_set_selection: wl.Listener(*wlr.Seat.event.RequestSetSelection) = wl.Listener(*wlr.Seat.event.RequestSetSelection).init(requestSetSelection),
keyboards: wl.list.Head(Keyboard, "link") = undefined,
cursor: *wlr.Cursor,
cursor_mgr: *wlr.XcursorManager,
cursor_motion: wl.Listener(*wlr.Pointer.event.Motion) = wl.Listener(*wlr.Pointer.event.Motion).init(cursorMotion),
cursor_motion_absolute: wl.Listener(*wlr.Pointer.event.MotionAbsolute) = wl.Listener(*wlr.Pointer.event.MotionAbsolute).init(cursorMotionAbsolute),
cursor_button: wl.Listener(*wlr.Pointer.event.Button) = wl.Listener(*wlr.Pointer.event.Button).init(cursorButton),
cursor_axis: wl.Listener(*wlr.Pointer.event.Axis) = wl.Listener(*wlr.Pointer.event.Axis).init(cursorAxis),
cursor_frame: wl.Listener(*wlr.Cursor) = wl.Listener(*wlr.Cursor).init(cursorFrame),
cursor_mode: enum { passthrough, move, resize } = .passthrough,
grabbed_view: ?*View = null,
grab_x: f64 = 0,
grab_y: f64 = 0,
grab_box: wlr.Box = undefined,
resize_edges: wlr.Edges = .{},
fn init(server: *Server) !void {
const wl_server = try wl.Server.create();
const backend = try wlr.Backend.autocreate(wl_server, null);
server.* = .{
.wl_server = wl_server,
.backend = backend,
.renderer = backend.getRenderer() orelse return error.GetRendererFailed,
.output_layout = try wlr.OutputLayout.create(),
.xdg_shell = try wlr.XdgShell.create(wl_server),
.seat = try wlr.Seat.create(wl_server, "default"),
.cursor = try wlr.Cursor.create(),
.cursor_mgr = try wlr.XcursorManager.create(null, 24),
};
try server.renderer.initServer(wl_server);
_ = try wlr.Compositor.create(server.wl_server, server.renderer);
_ = try wlr.DataDeviceManager.create(server.wl_server);
server.backend.events.new_output.add(&server.new_output);
server.xdg_shell.events.new_surface.add(&server.new_xdg_surface);
server.views.init();
server.backend.events.new_input.add(&server.new_input);
server.seat.events.request_set_cursor.add(&server.request_set_cursor);
server.seat.events.request_set_selection.add(&server.request_set_selection);
server.keyboards.init();
server.cursor.attachOutputLayout(server.output_layout);
try server.cursor_mgr.load(1);
server.cursor.events.motion.add(&server.cursor_motion);
server.cursor.events.motion_absolute.add(&server.cursor_motion_absolute);
server.cursor.events.button.add(&server.cursor_button);
server.cursor.events.axis.add(&server.cursor_axis);
server.cursor.events.frame.add(&server.cursor_frame);
}
fn deinit(server: *Server) void {
server.wl_server.destroyClients();
server.wl_server.destroy();
}
fn newOutput(listener: *wl.Listener(*wlr.Output), wlr_output: *wlr.Output) void {
const server = @fieldParentPtr(Server, "new_output", listener);
if (wlr_output.preferredMode()) |mode| {
wlr_output.setMode(mode);
wlr_output.enable(true);
wlr_output.commit() catch return;
}
const output = gpa.create(Output) catch {
std.log.crit("failed to allocate new output", .{});
return;
};
output.* = .{
.server = server,
.wlr_output = wlr_output,
};
wlr_output.events.frame.add(&output.frame);
server.output_layout.addAuto(wlr_output);
}
fn newXdgSurface(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void {
const server = @fieldParentPtr(Server, "new_xdg_surface", listener);
if (xdg_surface.role != .toplevel) return;
// Don't add the view to server.views until it is mapped
const view = gpa.create(View) catch {
std.log.crit("failed to allocate new view", .{});
return;
};
view.* = .{
.server = server,
.xdg_surface = xdg_surface,
};
xdg_surface.events.map.add(&view.map);
xdg_surface.events.unmap.add(&view.unmap);
xdg_surface.events.destroy.add(&view.destroy);
xdg_surface.role_data.toplevel.events.request_move.add(&view.request_move);
xdg_surface.role_data.toplevel.events.request_resize.add(&view.request_resize);
}
const ViewAtResult = struct {
view: *View,
surface: *wlr.Surface,
sx: f64,
sy: f64,
};
fn viewAt(server: *Server, lx: f64, ly: f64) ?ViewAtResult {
var it = server.views.iterator(.forward);
while (it.next()) |view| {
var sx: f64 = undefined;
var sy: f64 = undefined;
const x = lx - @intToFloat(f64, view.x);
const y = ly - @intToFloat(f64, view.y);
if (view.xdg_surface.surfaceAt(x, y, &sx, &sy)) |surface| {
return ViewAtResult{
.view = view,
.surface = surface,
.sx = sx,
.sy = sy,
};
}
}
return null;
}
fn focusView(server: *Server, view: *View, surface: *wlr.Surface) void {
if (server.seat.keyboard_state.focused_surface) |previous_surface| {
if (previous_surface == surface) return;
if (previous_surface.isXdgSurface()) {
const xdg_surface = wlr.XdgSurface.fromWlrSurface(previous_surface);
_ = xdg_surface.role_data.toplevel.setActivated(false);
}
}
view.link.remove();
server.views.prepend(view);
_ = view.xdg_surface.role_data.toplevel.setActivated(true);
const wlr_keyboard = server.seat.getKeyboard() orelse return;
server.seat.keyboardNotifyEnter(surface, &wlr_keyboard.keycodes, wlr_keyboard.num_keycodes, &wlr_keyboard.modifiers);
}
fn newInput(listener: *wl.Listener(*wlr.InputDevice), device: *wlr.InputDevice) void {
const server = @fieldParentPtr(Server, "new_input", listener);
switch (device.type) {
.keyboard => Keyboard.create(server, device) catch |err| {
std.log.err("failed to create keyboard: {}", .{err});
return;
},
.pointer => server.cursor.attachInputDevice(device),
else => {},
}
server.seat.setCapabilities(.{
.pointer = true,
.keyboard = server.keyboards.length() > 0,
});
}
fn requestSetCursor(
listener: *wl.Listener(*wlr.Seat.event.RequestSetCursor),
event: *wlr.Seat.event.RequestSetCursor,
) void {
const server = @fieldParentPtr(Server, "request_set_cursor", listener);
if (event.seat_client == server.seat.pointer_state.focused_client)
server.cursor.setSurface(event.surface, event.hotspot_x, event.hotspot_y);
}
fn requestSetSelection(
listener: *wl.Listener(*wlr.Seat.event.RequestSetSelection),
event: *wlr.Seat.event.RequestSetSelection,
) void {
const server = @fieldParentPtr(Server, "request_set_selection", listener);
server.seat.setSelection(event.source, event.serial);
}
fn cursorMotion(
listener: *wl.Listener(*wlr.Pointer.event.Motion),
event: *wlr.Pointer.event.Motion,
) void {
const server = @fieldParentPtr(Server, "cursor_motion", listener);
server.cursor.move(event.device, event.delta_x, event.delta_y);
server.processCursorMotion(event.time_msec);
}
fn cursorMotionAbsolute(
listener: *wl.Listener(*wlr.Pointer.event.MotionAbsolute),
event: *wlr.Pointer.event.MotionAbsolute,
) void {
const server = @fieldParentPtr(Server, "cursor_motion_absolute", listener);
server.cursor.warpAbsolute(event.device, event.x, event.y);
server.processCursorMotion(event.time_msec);
}
fn processCursorMotion(server: *Server, time_msec: u32) void {
switch (server.cursor_mode) {
.passthrough => if (server.viewAt(server.cursor.x, server.cursor.y)) |res| {
server.seat.pointerNotifyEnter(res.surface, res.sx, res.sy);
server.seat.pointerNotifyMotion(time_msec, res.sx, res.sy);
} else {
server.cursor_mgr.setCursorImage("left_ptr", server.cursor);
server.seat.pointerClearFocus();
},
.move => {
server.grabbed_view.?.x = @floatToInt(i32, server.cursor.x - server.grab_x);
server.grabbed_view.?.y = @floatToInt(i32, server.cursor.y - server.grab_y);
},
.resize => {
const view = server.grabbed_view.?;
const border_x = @floatToInt(i32, server.cursor.x - server.grab_x);
const border_y = @floatToInt(i32, server.cursor.y - server.grab_y);
var new_left = server.grab_box.x;
var new_right = server.grab_box.x + server.grab_box.width;
var new_top = server.grab_box.y;
var new_bottom = server.grab_box.y + server.grab_box.height;
if (server.resize_edges.top) {
new_top = border_y;
if (new_top >= new_bottom)
new_top = new_bottom - 1;
} else if (server.resize_edges.bottom) {
new_bottom = border_y;
if (new_bottom <= new_top)
new_bottom = new_top + 1;
}
if (server.resize_edges.left) {
new_left = border_x;
if (new_left >= new_right)
new_left = new_right - 1;
} else if (server.resize_edges.right) {
new_right = border_x;
if (new_right <= new_left)
new_right = new_left + 1;
}
var geo_box: wlr.Box = undefined;
view.xdg_surface.getGeometry(&geo_box);
view.x = new_left - geo_box.x;
view.y = new_top - geo_box.y;
const new_width = @intCast(u32, new_right - new_left);
const new_height = @intCast(u32, new_bottom - new_top);
_ = view.xdg_surface.role_data.toplevel.setSize(new_width, new_height);
},
}
}
fn cursorButton(
listener: *wl.Listener(*wlr.Pointer.event.Button),
event: *wlr.Pointer.event.Button,
) void {
const server = @fieldParentPtr(Server, "cursor_button", listener);
_ = server.seat.pointerNotifyButton(event.time_msec, event.button, event.state);
if (event.state == .released) {
server.cursor_mode = .passthrough;
} else if (server.viewAt(server.cursor.x, server.cursor.y)) |res| {
server.focusView(res.view, res.surface);
}
}
fn cursorAxis(
listener: *wl.Listener(*wlr.Pointer.event.Axis),
event: *wlr.Pointer.event.Axis,
) void {
const server = @fieldParentPtr(Server, "cursor_axis", listener);
server.seat.pointerNotifyAxis(
event.time_msec,
event.orientation,
event.delta,
event.delta_discrete,
event.source,
);
}
fn cursorFrame(listener: *wl.Listener(*wlr.Cursor), wlr_cursor: *wlr.Cursor) void {
const server = @fieldParentPtr(Server, "cursor_frame", listener);
server.seat.pointerNotifyFrame();
}
/// Assumes the modifier used for compositor keybinds is pressed
/// Returns true if the key was handled
fn handleKeybind(server: *Server, key: xkb.Keysym) bool {
switch (key) {
// Exit the compositor
.Escape => server.wl_server.terminate(),
// Focus the next view in the stack, pushing the current top to the back
.F1 => {
if (server.views.length() < 2) return true;
const view = @fieldParentPtr(View, "link", server.views.link.next.?);
view.link.remove();
server.views.append(view);
server.focusView(view, view.xdg_surface.surface);
},
else => return false,
}
return true;
}
};
const Output = struct {
const RenderData = struct {
wlr_output: *wlr.Output,
view: *View,
renderer: *wlr.Renderer,
when: *os.timespec,
};
server: *Server,
wlr_output: *wlr.Output,
frame: wl.Listener(*wlr.Output) = wl.Listener(*wlr.Output).init(frame),
fn frame(listener: *wl.Listener(*wlr.Output), wlr_output: *wlr.Output) void {
const output = @fieldParentPtr(Output, "frame", listener);
const server = output.server;
var now: os.timespec = undefined;
os.clock_gettime(os.CLOCK_MONOTONIC, &now) catch @panic("CLOCK_MONOTONIC not supported");
wlr_output.attachRender(null) catch return;
var width: c_int = undefined;
var height: c_int = undefined;
wlr_output.effectiveResolution(&width, &height);
server.renderer.begin(width, height);
const color = [4]f32{ 0.3, 0.3, 0.3, 1.0 };
server.renderer.clear(&color);
// In reverse order to render views at the front of the list on top
var it = server.views.iterator(.reverse);
while (it.next()) |view| {
var rdata = RenderData{
.wlr_output = wlr_output,
.view = view,
.renderer = server.renderer,
.when = &now,
};
view.xdg_surface.forEachSurface(*RenderData, renderSurface, &rdata);
}
wlr_output.renderSoftwareCursors(null);
server.renderer.end();
// Pending changes are automatically rolled back on failure
wlr_output.commit() catch {};
}
fn renderSurface(surface: *wlr.Surface, sx: c_int, sy: c_int, rdata: *RenderData) callconv(.C) void {
const wlr_output = rdata.wlr_output;
const texture = surface.getTexture() orelse return;
var ox: f64 = 0;
var oy: f64 = 0;
rdata.view.server.output_layout.outputCoords(wlr_output, &ox, &oy);
ox += @intToFloat(f64, rdata.view.x + sx);
oy += @intToFloat(f64, rdata.view.y + sy);
var box = wlr.Box{
.x = @floatToInt(c_int, ox * wlr_output.scale),
.y = @floatToInt(c_int, oy * wlr_output.scale),
.width = @floatToInt(c_int, @intToFloat(f32, surface.current.width) * wlr_output.scale),
.height = @floatToInt(c_int, @intToFloat(f32, surface.current.height) * wlr_output.scale),
};
var matrix: [9]f32 = undefined;
const transform = wlr.Output.transformInvert(surface.current.transform);
wlr.matrix.projectBox(&matrix, &box, transform, 0, &wlr_output.transform_matrix);
// wlroots will log an error for us
rdata.renderer.renderTextureWithMatrix(texture, &matrix, 1) catch {};
surface.sendFrameDone(rdata.when);
}
};
const View = struct {
server: *Server,
link: wl.list.Link = undefined,
xdg_surface: *wlr.XdgSurface,
x: i32 = 0,
y: i32 = 0,
map: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(map),
unmap: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(unmap),
destroy: wl.Listener(*wlr.XdgSurface) = wl.Listener(*wlr.XdgSurface).init(destroy),
request_move: wl.Listener(*wlr.XdgToplevel.event.Move) = wl.Listener(*wlr.XdgToplevel.event.Move).init(requestMove),
request_resize: wl.Listener(*wlr.XdgToplevel.event.Resize) = wl.Listener(*wlr.XdgToplevel.event.Resize).init(requestResize),
fn map(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void {
const view = @fieldParentPtr(View, "map", listener);
view.server.views.prepend(view);
view.x -= xdg_surface.geometry.x;
view.y -= xdg_surface.geometry.y;
view.server.focusView(view, xdg_surface.surface);
}
fn unmap(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void {
const view = @fieldParentPtr(View, "unmap", listener);
view.link.remove();
}
fn destroy(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void {
const view = @fieldParentPtr(View, "destroy", listener);
gpa.destroy(view);
}
fn requestMove(
listener: *wl.Listener(*wlr.XdgToplevel.event.Move),
event: *wlr.XdgToplevel.event.Move,
) void {
const view = @fieldParentPtr(View, "request_move", listener);
const server = view.server;
server.grabbed_view = view;
server.cursor_mode = .move;
server.grab_x = server.cursor.x - @intToFloat(f64, view.x);
server.grab_y = server.cursor.y - @intToFloat(f64, view.y);
}
fn requestResize(
listener: *wl.Listener(*wlr.XdgToplevel.event.Resize),
event: *wlr.XdgToplevel.event.Resize,
) void {
const view = @fieldParentPtr(View, "request_resize", listener);
const server = view.server;
server.grabbed_view = view;
server.cursor_mode = .resize;
server.resize_edges = event.edges;
var box: wlr.Box = undefined;
view.xdg_surface.getGeometry(&box);
const border_x = view.x + box.x + if (event.edges.right) box.width else 0;
const border_y = view.y + box.y + if (event.edges.bottom) box.height else 0;
server.grab_x = server.cursor.x - @intToFloat(f64, border_x);
server.grab_y = server.cursor.y - @intToFloat(f64, border_y);
server.grab_box = box;
server.grab_box.x += view.x;
server.grab_box.y += view.y;
}
};
const Keyboard = struct {
server: *Server,
link: wl.list.Link = undefined,
device: *wlr.InputDevice,
modifiers: wl.Listener(*wlr.Keyboard) = wl.Listener(*wlr.Keyboard).init(modifiers),
key: wl.Listener(*wlr.Keyboard.event.Key) = wl.Listener(*wlr.Keyboard.event.Key).init(key),
fn create(server: *Server, device: *wlr.InputDevice) !void {
const keyboard = try gpa.create(Keyboard);
errdefer gpa.destroy(keyboard);
keyboard.* = .{
.server = server,
.device = device,
};
const context = xkb.Context.new(.no_flags) orelse return error.ContextFailed;
defer context.unref();
const keymap = xkb.Keymap.newFromNames(context, null, .no_flags) orelse return error.KeymapFailed;
defer keymap.unref();
const wlr_keyboard = device.device.keyboard;
if (!wlr_keyboard.setKeymap(keymap)) return error.SetKeymapFailed;
wlr_keyboard.setRepeatInfo(25, 600);
wlr_keyboard.events.modifiers.add(&keyboard.modifiers);
wlr_keyboard.events.key.add(&keyboard.key);
server.seat.setKeyboard(device);
server.keyboards.append(keyboard);
}
fn modifiers(listener: *wl.Listener(*wlr.Keyboard), wlr_keyboard: *wlr.Keyboard) void {
const keyboard = @fieldParentPtr(Keyboard, "modifiers", listener);
keyboard.server.seat.setKeyboard(keyboard.device);
keyboard.server.seat.keyboardNotifyModifiers(&wlr_keyboard.modifiers);
}
fn key(listener: *wl.Listener(*wlr.Keyboard.event.Key), event: *wlr.Keyboard.event.Key) void {
const keyboard = @fieldParentPtr(Keyboard, "key", listener);
const wlr_keyboard = keyboard.device.device.keyboard;
// Translate libinput keycode -> xkbcommon
const keycode = event.keycode + 8;
var handled = false;
if (wlr_keyboard.getModifiers().alt and event.state == .pressed) {
for (wlr_keyboard.xkb_state.?.keyGetSyms(keycode)) |sym| {
if (keyboard.server.handleKeybind(sym)) {
handled = true;
break;
}
}
}
if (!handled) {
keyboard.server.seat.setKeyboard(keyboard.device);
keyboard.server.seat.keyboardNotifyKey(event.time_msec, event.keycode, event.state);
}
}
}; | tinywl/tinywl.zig |
const __builtin_va_list = extern struct {
padding: u32,
};
pub const va_list = __builtin_va_list;
pub const __gnuc_va_list = __builtin_va_list;
pub const ANDROID_LOG_UNKNOWN = @enumToInt(enum_android_LogPriority.ANDROID_LOG_UNKNOWN);
pub const ANDROID_LOG_DEFAULT = @enumToInt(enum_android_LogPriority.ANDROID_LOG_DEFAULT);
pub const ANDROID_LOG_VERBOSE = @enumToInt(enum_android_LogPriority.ANDROID_LOG_VERBOSE);
pub const ANDROID_LOG_DEBUG = @enumToInt(enum_android_LogPriority.ANDROID_LOG_DEBUG);
pub const ANDROID_LOG_INFO = @enumToInt(enum_android_LogPriority.ANDROID_LOG_INFO);
pub const ANDROID_LOG_WARN = @enumToInt(enum_android_LogPriority.ANDROID_LOG_WARN);
pub const ANDROID_LOG_ERROR = @enumToInt(enum_android_LogPriority.ANDROID_LOG_ERROR);
pub const ANDROID_LOG_FATAL = @enumToInt(enum_android_LogPriority.ANDROID_LOG_FATAL);
pub const ANDROID_LOG_SILENT = @enumToInt(enum_android_LogPriority.ANDROID_LOG_SILENT);
pub const enum_android_LogPriority = enum(c_int) {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT = 1,
ANDROID_LOG_VERBOSE = 2,
ANDROID_LOG_DEBUG = 3,
ANDROID_LOG_INFO = 4,
ANDROID_LOG_WARN = 5,
ANDROID_LOG_ERROR = 6,
ANDROID_LOG_FATAL = 7,
ANDROID_LOG_SILENT = 8,
_,
};
pub const android_LogPriority = enum_android_LogPriority;
pub extern fn __android_log_write(prio: c_int, tag: [*c]const u8, text: [*c]const u8) c_int;
pub extern fn __android_log_print(prio: c_int, tag: [*c]const u8, fmt: [*c]const u8, ...) c_int;
pub extern fn __android_log_vprint(prio: c_int, tag: [*c]const u8, fmt: [*c]const u8, ap: va_list) c_int;
pub extern fn __android_log_assert(cond: [*c]const u8, tag: [*c]const u8, fmt: [*c]const u8, ...) noreturn;
pub const LOG_ID_MIN = @enumToInt(enum_log_id.LOG_ID_MIN);
pub const LOG_ID_MAIN = @enumToInt(enum_log_id.LOG_ID_MAIN);
pub const LOG_ID_RADIO = @enumToInt(enum_log_id.LOG_ID_RADIO);
pub const LOG_ID_EVENTS = @enumToInt(enum_log_id.LOG_ID_EVENTS);
pub const LOG_ID_SYSTEM = @enumToInt(enum_log_id.LOG_ID_SYSTEM);
pub const LOG_ID_CRASH = @enumToInt(enum_log_id.LOG_ID_CRASH);
pub const LOG_ID_STATS = @enumToInt(enum_log_id.LOG_ID_STATS);
pub const LOG_ID_SECURITY = @enumToInt(enum_log_id.LOG_ID_SECURITY);
pub const LOG_ID_KERNEL = @enumToInt(enum_log_id.LOG_ID_KERNEL);
pub const LOG_ID_MAX = @enumToInt(enum_log_id.LOG_ID_MAX);
pub const enum_log_id = enum(c_int) {
LOG_ID_MIN = 0,
LOG_ID_MAIN = 0,
LOG_ID_RADIO = 1,
LOG_ID_EVENTS = 2,
LOG_ID_SYSTEM = 3,
LOG_ID_CRASH = 4,
LOG_ID_STATS = 5,
LOG_ID_SECURITY = 6,
LOG_ID_KERNEL = 7,
LOG_ID_MAX = 8,
_,
};
pub const log_id_t = enum_log_id;
pub extern fn __android_log_buf_write(bufID: c_int, prio: c_int, tag: [*c]const u8, text: [*c]const u8) c_int;
pub extern fn __android_log_buf_print(bufID: c_int, prio: c_int, tag: [*c]const u8, fmt: [*c]const u8, ...) c_int;
pub extern fn android_get_application_target_sdk_version(...) c_int;
pub extern fn android_get_device_api_level(...) c_int;
pub const ptrdiff_t = c_long;
pub const wchar_t = c_uint;
const struct_unnamed_1 = extern struct {
__clang_max_align_nonce1: c_longlong align(8),
__clang_max_align_nonce2: c_longdouble align(16),
};
pub const max_align_t = struct_unnamed_1;
pub const __int8_t = i8;
pub const __uint8_t = u8;
pub const __int16_t = c_short;
pub const __uint16_t = c_ushort;
pub const __int32_t = c_int;
pub const __uint32_t = c_uint;
pub const __int64_t = c_long;
pub const __uint64_t = c_ulong;
pub const __intptr_t = c_long;
pub const __uintptr_t = c_ulong;
pub const int_least8_t = i8;
pub const uint_least8_t = u8;
pub const int_least16_t = i16;
pub const uint_least16_t = u16;
pub const int_least32_t = i32;
pub const uint_least32_t = u32;
pub const int_least64_t = i64;
pub const uint_least64_t = u64;
pub const int_fast8_t = i8;
pub const uint_fast8_t = u8;
pub const int_fast64_t = i64;
pub const uint_fast64_t = u64;
pub const int_fast16_t = i64;
pub const uint_fast16_t = u64;
pub const int_fast32_t = i64;
pub const uint_fast32_t = u64;
pub const uintmax_t = u64;
pub const intmax_t = i64;
pub const __s8 = i8;
pub const __u8 = u8;
pub const __s16 = c_short;
pub const __u16 = c_ushort;
pub const __s32 = c_int;
pub const __u32 = c_uint;
pub const __s64 = c_longlong;
pub const __u64 = c_ulonglong;
const struct_unnamed_2 = extern struct {
fds_bits: [16]c_ulong,
};
pub const __kernel_fd_set = struct_unnamed_2;
pub const __kernel_sighandler_t = ?fn (c_int) callconv(.C) void;
pub const __kernel_key_t = c_int;
pub const __kernel_mqd_t = c_int;
pub const __kernel_old_uid_t = c_ushort;
pub const __kernel_old_gid_t = c_ushort;
pub const __kernel_long_t = c_long;
pub const __kernel_ulong_t = c_ulong;
pub const __kernel_ino_t = __kernel_ulong_t;
pub const __kernel_mode_t = c_uint;
pub const __kernel_pid_t = c_int;
pub const __kernel_ipc_pid_t = c_int;
pub const __kernel_uid_t = c_uint;
pub const __kernel_gid_t = c_uint;
pub const __kernel_suseconds_t = __kernel_long_t;
pub const __kernel_daddr_t = c_int;
pub const __kernel_uid32_t = c_uint;
pub const __kernel_gid32_t = c_uint;
pub const __kernel_old_dev_t = c_uint;
pub const __kernel_size_t = __kernel_ulong_t;
pub const __kernel_ssize_t = __kernel_long_t;
pub const __kernel_ptrdiff_t = __kernel_long_t;
const struct_unnamed_3 = extern struct {
val: [2]c_int,
};
pub const __kernel_fsid_t = struct_unnamed_3;
pub const __kernel_off_t = __kernel_long_t;
pub const __kernel_loff_t = c_longlong;
pub const __kernel_time_t = __kernel_long_t;
pub const __kernel_time64_t = c_longlong;
pub const __kernel_clock_t = __kernel_long_t;
pub const __kernel_timer_t = c_int;
pub const __kernel_clockid_t = c_int;
pub const __kernel_caddr_t = [*c]u8;
pub const __kernel_uid16_t = c_ushort;
pub const __kernel_gid16_t = c_ushort;
pub const __le16 = __u16;
pub const __be16 = __u16;
pub const __le32 = __u32;
pub const __be32 = __u32;
pub const __le64 = __u64;
pub const __be64 = __u64;
pub const __sum16 = __u16;
pub const __wsum = __u32;
pub const __poll_t = c_uint;
const struct_unnamed_4 = extern struct {
flags: u32,
stack_base: ?*c_void,
stack_size: usize,
guard_size: usize,
sched_policy: i32,
sched_priority: i32,
__reserved: [16]u8,
};
pub const pthread_attr_t = struct_unnamed_4;
const struct_unnamed_5 = extern struct {
__private: [4]i64,
};
pub const pthread_barrier_t = struct_unnamed_5;
pub const pthread_barrierattr_t = c_int;
const struct_unnamed_6 = extern struct {
__private: [12]i32,
};
pub const pthread_cond_t = struct_unnamed_6;
pub const pthread_condattr_t = c_long;
pub const pthread_key_t = c_int;
const struct_unnamed_7 = extern struct {
__private: [10]i32,
};
pub const pthread_mutex_t = struct_unnamed_7;
pub const pthread_mutexattr_t = c_long;
pub const pthread_once_t = c_int;
const struct_unnamed_8 = extern struct {
__private: [14]i32,
};
pub const pthread_rwlock_t = struct_unnamed_8;
pub const pthread_rwlockattr_t = c_long;
const struct_unnamed_9 = extern struct {
__private: i64,
};
pub const pthread_spinlock_t = struct_unnamed_9;
pub const pthread_t = c_long;
pub const __gid_t = __kernel_gid32_t;
pub const gid_t = __gid_t;
pub const __uid_t = __kernel_uid32_t;
pub const uid_t = __uid_t;
pub const __pid_t = __kernel_pid_t;
pub const pid_t = __pid_t;
pub const __id_t = u32;
pub const id_t = __id_t;
pub const blkcnt_t = c_ulong;
pub const blksize_t = c_ulong;
pub const caddr_t = __kernel_caddr_t;
pub const clock_t = __kernel_clock_t;
pub const __clockid_t = __kernel_clockid_t;
pub const clockid_t = __clockid_t;
pub const daddr_t = __kernel_daddr_t;
pub const fsblkcnt_t = c_ulong;
pub const fsfilcnt_t = c_ulong;
pub const __mode_t = __kernel_mode_t;
pub const mode_t = __mode_t;
pub const __key_t = __kernel_key_t;
pub const key_t = __key_t;
pub const __ino_t = __kernel_ino_t;
pub const ino_t = __ino_t;
pub const ino64_t = u64;
pub const __nlink_t = u32;
pub const nlink_t = __nlink_t;
pub const __timer_t = ?*c_void;
pub const timer_t = __timer_t;
pub const __suseconds_t = __kernel_suseconds_t;
pub const suseconds_t = __suseconds_t;
pub const __useconds_t = u32;
pub const useconds_t = __useconds_t;
pub const dev_t = u64;
pub const __time_t = __kernel_time_t;
pub const time_t = __time_t;
pub const off_t = i64;
pub const loff_t = off_t;
pub const off64_t = loff_t;
pub const __socklen_t = u32;
pub const socklen_t = __socklen_t;
pub const __va_list = __builtin_va_list;
pub const uint_t = c_uint;
pub const uint = c_uint;
pub const u_char = u8;
pub const u_short = c_ushort;
pub const u_int = c_uint;
pub const u_long = c_ulong;
pub const u_int32_t = u32;
pub const u_int16_t = u16;
pub const u_int8_t = u8;
pub const u_int64_t = u64;
pub const AAssetManager = opaque {};
pub const AAssetDir = opaque {};
pub const AAsset = opaque {};
pub const AASSET_MODE_UNKNOWN = @enumToInt(enum_unnamed_10.AASSET_MODE_UNKNOWN);
pub const AASSET_MODE_RANDOM = @enumToInt(enum_unnamed_10.AASSET_MODE_RANDOM);
pub const AASSET_MODE_STREAMING = @enumToInt(enum_unnamed_10.AASSET_MODE_STREAMING);
pub const AASSET_MODE_BUFFER = @enumToInt(enum_unnamed_10.AASSET_MODE_BUFFER);
const enum_unnamed_10 = enum(c_int) {
AASSET_MODE_UNKNOWN = 0,
AASSET_MODE_RANDOM = 1,
AASSET_MODE_STREAMING = 2,
AASSET_MODE_BUFFER = 3,
_,
};
pub extern fn AAssetManager_openDir(mgr: ?*AAssetManager, dirName: [*c]const u8) ?*AAssetDir;
pub extern fn AAssetManager_open(mgr: ?*AAssetManager, filename: [*c]const u8, mode: c_int) ?*AAsset;
pub extern fn AAssetDir_getNextFileName(assetDir: ?*AAssetDir) [*c]const u8;
pub extern fn AAssetDir_rewind(assetDir: ?*AAssetDir) void;
pub extern fn AAssetDir_close(assetDir: ?*AAssetDir) void;
pub extern fn AAsset_read(asset: ?*AAsset, buf: ?*c_void, count: usize) c_int;
pub extern fn AAsset_seek(asset: ?*AAsset, offset: off_t, whence: c_int) off_t;
pub extern fn AAsset_seek64(asset: ?*AAsset, offset: off64_t, whence: c_int) off64_t;
pub extern fn AAsset_close(asset: ?*AAsset) void;
pub extern fn AAsset_getBuffer(asset: ?*AAsset) ?*const c_void;
pub extern fn AAsset_getLength(asset: ?*AAsset) off_t;
pub extern fn AAsset_getLength64(asset: ?*AAsset) off64_t;
pub extern fn AAsset_getRemainingLength(asset: ?*AAsset) off_t;
pub extern fn AAsset_getRemainingLength64(asset: ?*AAsset) off64_t;
pub extern fn AAsset_openFileDescriptor(asset: ?*AAsset, outStart: [*c]off_t, outLength: [*c]off_t) c_int;
pub extern fn AAsset_openFileDescriptor64(asset: ?*AAsset, outStart: [*c]off64_t, outLength: [*c]off64_t) c_int;
pub extern fn AAsset_isAllocated(asset: ?*AAsset) c_int;
pub const AConfiguration = opaque {};
pub const ACONFIGURATION_ORIENTATION_ANY = 0;
pub const ACONFIGURATION_ORIENTATION_PORT = 1;
pub const ACONFIGURATION_ORIENTATION_LAND = 2;
pub const ACONFIGURATION_ORIENTATION_SQUARE = 3;
pub const ACONFIGURATION_TOUCHSCREEN_ANY = 0;
pub const ACONFIGURATION_TOUCHSCREEN_NOTOUCH = 1;
pub const ACONFIGURATION_TOUCHSCREEN_STYLUS = 2;
pub const ACONFIGURATION_TOUCHSCREEN_FINGER = 3;
pub const ACONFIGURATION_DENSITY_DEFAULT = 0;
pub const ACONFIGURATION_DENSITY_LOW = 120;
pub const ACONFIGURATION_DENSITY_MEDIUM = 160;
pub const ACONFIGURATION_DENSITY_TV = 213;
pub const ACONFIGURATION_DENSITY_HIGH = 240;
pub const ACONFIGURATION_DENSITY_XHIGH = 320;
pub const ACONFIGURATION_DENSITY_XXHIGH = 480;
pub const ACONFIGURATION_DENSITY_XXXHIGH = 640;
pub const ACONFIGURATION_DENSITY_ANY = 65534;
pub const ACONFIGURATION_DENSITY_NONE = 65535;
pub const ACONFIGURATION_KEYBOARD_ANY = 0;
pub const ACONFIGURATION_KEYBOARD_NOKEYS = 1;
pub const ACONFIGURATION_KEYBOARD_QWERTY = 2;
pub const ACONFIGURATION_KEYBOARD_12KEY = 3;
pub const ACONFIGURATION_NAVIGATION_ANY = 0;
pub const ACONFIGURATION_NAVIGATION_NONAV = 1;
pub const ACONFIGURATION_NAVIGATION_DPAD = 2;
pub const ACONFIGURATION_NAVIGATION_TRACKBALL = 3;
pub const ACONFIGURATION_NAVIGATION_WHEEL = 4;
pub const ACONFIGURATION_KEYSHIDDEN_ANY = 0;
pub const ACONFIGURATION_KEYSHIDDEN_NO = 1;
pub const ACONFIGURATION_KEYSHIDDEN_YES = 2;
pub const ACONFIGURATION_KEYSHIDDEN_SOFT = 3;
pub const ACONFIGURATION_NAVHIDDEN_ANY = 0;
pub const ACONFIGURATION_NAVHIDDEN_NO = 1;
pub const ACONFIGURATION_NAVHIDDEN_YES = 2;
pub const ACONFIGURATION_SCREENSIZE_ANY = 0;
pub const ACONFIGURATION_SCREENSIZE_SMALL = 1;
pub const ACONFIGURATION_SCREENSIZE_NORMAL = 2;
pub const ACONFIGURATION_SCREENSIZE_LARGE = 3;
pub const ACONFIGURATION_SCREENSIZE_XLARGE = 4;
pub const ACONFIGURATION_SCREENLONG_ANY = 0;
pub const ACONFIGURATION_SCREENLONG_NO = 1;
pub const ACONFIGURATION_SCREENLONG_YES = 2;
pub const ACONFIGURATION_SCREENROUND_ANY = 0;
pub const ACONFIGURATION_SCREENROUND_NO = 1;
pub const ACONFIGURATION_SCREENROUND_YES = 2;
pub const ACONFIGURATION_WIDE_COLOR_GAMUT_ANY = 0;
pub const ACONFIGURATION_WIDE_COLOR_GAMUT_NO = 1;
pub const ACONFIGURATION_WIDE_COLOR_GAMUT_YES = 2;
pub const ACONFIGURATION_HDR_ANY = 0;
pub const ACONFIGURATION_HDR_NO = 1;
pub const ACONFIGURATION_HDR_YES = 2;
pub const ACONFIGURATION_UI_MODE_TYPE_ANY = 0;
pub const ACONFIGURATION_UI_MODE_TYPE_NORMAL = 1;
pub const ACONFIGURATION_UI_MODE_TYPE_DESK = 2;
pub const ACONFIGURATION_UI_MODE_TYPE_CAR = 3;
pub const ACONFIGURATION_UI_MODE_TYPE_TELEVISION = 4;
pub const ACONFIGURATION_UI_MODE_TYPE_APPLIANCE = 5;
pub const ACONFIGURATION_UI_MODE_TYPE_WATCH = 6;
pub const ACONFIGURATION_UI_MODE_TYPE_VR_HEADSET = 7;
pub const ACONFIGURATION_UI_MODE_NIGHT_ANY = 0;
pub const ACONFIGURATION_UI_MODE_NIGHT_NO = 1;
pub const ACONFIGURATION_UI_MODE_NIGHT_YES = 2;
pub const ACONFIGURATION_SCREEN_WIDTH_DP_ANY = 0;
pub const ACONFIGURATION_SCREEN_HEIGHT_DP_ANY = 0;
pub const ACONFIGURATION_SMALLEST_SCREEN_WIDTH_DP_ANY = 0;
pub const ACONFIGURATION_LAYOUTDIR_ANY = 0;
pub const ACONFIGURATION_LAYOUTDIR_LTR = 1;
pub const ACONFIGURATION_LAYOUTDIR_RTL = 2;
pub const ACONFIGURATION_MCC = 1;
pub const ACONFIGURATION_MNC = 2;
pub const ACONFIGURATION_LOCALE = 4;
pub const ACONFIGURATION_TOUCHSCREEN = 8;
pub const ACONFIGURATION_KEYBOARD = 16;
pub const ACONFIGURATION_KEYBOARD_HIDDEN = 32;
pub const ACONFIGURATION_NAVIGATION = 64;
pub const ACONFIGURATION_ORIENTATION = 128;
pub const ACONFIGURATION_DENSITY = 256;
pub const ACONFIGURATION_SCREEN_SIZE = 512;
pub const ACONFIGURATION_VERSION = 1024;
pub const ACONFIGURATION_SCREEN_LAYOUT = 2048;
pub const ACONFIGURATION_UI_MODE = 4096;
pub const ACONFIGURATION_SMALLEST_SCREEN_SIZE = 8192;
pub const ACONFIGURATION_LAYOUTDIR = 16384;
pub const ACONFIGURATION_SCREEN_ROUND = 32768;
pub const ACONFIGURATION_COLOR_MODE = 65536;
pub const ACONFIGURATION_MNC_ZERO = 65535;
pub extern fn AConfiguration_new(...) ?*AConfiguration;
pub extern fn AConfiguration_delete(config: ?*AConfiguration) void;
pub extern fn AConfiguration_fromAssetManager(out: ?*AConfiguration, am: ?*AAssetManager) void;
pub extern fn AConfiguration_copy(dest: ?*AConfiguration, src: ?*AConfiguration) void;
pub extern fn AConfiguration_getMcc(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setMcc(config: ?*AConfiguration, mcc: i32) void;
pub extern fn AConfiguration_getMnc(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setMnc(config: ?*AConfiguration, mnc: i32) void;
pub extern fn AConfiguration_getLanguage(config: ?*AConfiguration, outLanguage: [*c]u8) void;
pub extern fn AConfiguration_setLanguage(config: ?*AConfiguration, language: [*c]const u8) void;
pub extern fn AConfiguration_getCountry(config: ?*AConfiguration, outCountry: [*c]u8) void;
pub extern fn AConfiguration_setCountry(config: ?*AConfiguration, country: [*c]const u8) void;
pub extern fn AConfiguration_getOrientation(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setOrientation(config: ?*AConfiguration, orientation: i32) void;
pub extern fn AConfiguration_getTouchscreen(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setTouchscreen(config: ?*AConfiguration, touchscreen: i32) void;
pub extern fn AConfiguration_getDensity(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setDensity(config: ?*AConfiguration, density: i32) void;
pub extern fn AConfiguration_getKeyboard(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setKeyboard(config: ?*AConfiguration, keyboard: i32) void;
pub extern fn AConfiguration_getNavigation(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setNavigation(config: ?*AConfiguration, navigation: i32) void;
pub extern fn AConfiguration_getKeysHidden(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setKeysHidden(config: ?*AConfiguration, keysHidden: i32) void;
pub extern fn AConfiguration_getNavHidden(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setNavHidden(config: ?*AConfiguration, navHidden: i32) void;
pub extern fn AConfiguration_getSdkVersion(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setSdkVersion(config: ?*AConfiguration, sdkVersion: i32) void;
pub extern fn AConfiguration_getScreenSize(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setScreenSize(config: ?*AConfiguration, screenSize: i32) void;
pub extern fn AConfiguration_getScreenLong(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setScreenLong(config: ?*AConfiguration, screenLong: i32) void;
pub extern fn AConfiguration_getScreenRound(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setScreenRound(config: ?*AConfiguration, screenRound: i32) void;
pub extern fn AConfiguration_getUiModeType(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setUiModeType(config: ?*AConfiguration, uiModeType: i32) void;
pub extern fn AConfiguration_getUiModeNight(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setUiModeNight(config: ?*AConfiguration, uiModeNight: i32) void;
pub extern fn AConfiguration_getScreenWidthDp(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setScreenWidthDp(config: ?*AConfiguration, value: i32) void;
pub extern fn AConfiguration_getScreenHeightDp(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setScreenHeightDp(config: ?*AConfiguration, value: i32) void;
pub extern fn AConfiguration_getSmallestScreenWidthDp(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setSmallestScreenWidthDp(config: ?*AConfiguration, value: i32) void;
pub extern fn AConfiguration_getLayoutDirection(config: ?*AConfiguration) i32;
pub extern fn AConfiguration_setLayoutDirection(config: ?*AConfiguration, value: i32) void;
pub extern fn AConfiguration_diff(config1: ?*AConfiguration, config2: ?*AConfiguration) i32;
pub extern fn AConfiguration_match(base: ?*AConfiguration, requested: ?*AConfiguration) i32;
pub extern fn AConfiguration_isBetterThan(base: ?*AConfiguration, @"test": ?*AConfiguration, requested: ?*AConfiguration) i32;
pub const struct_ALooper = opaque {};
pub const ALooper = struct_ALooper;
pub extern fn ALooper_forThread(...) ?*ALooper;
pub const ALOOPER_PREPARE_ALLOW_NON_CALLBACKS = @enumToInt(enum_unnamed_12.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
const enum_unnamed_12 = enum(c_int) {
ALOOPER_PREPARE_ALLOW_NON_CALLBACKS = 1,
_,
};
pub extern fn ALooper_prepare(opts: c_int) ?*ALooper;
pub const ALOOPER_POLL_WAKE = @enumToInt(enum_unnamed_13.ALOOPER_POLL_WAKE);
pub const ALOOPER_POLL_CALLBACK = @enumToInt(enum_unnamed_13.ALOOPER_POLL_CALLBACK);
pub const ALOOPER_POLL_TIMEOUT = @enumToInt(enum_unnamed_13.ALOOPER_POLL_TIMEOUT);
pub const ALOOPER_POLL_ERROR = @enumToInt(enum_unnamed_13.ALOOPER_POLL_ERROR);
const enum_unnamed_13 = enum(c_int) {
ALOOPER_POLL_WAKE = -1,
ALOOPER_POLL_CALLBACK = -2,
ALOOPER_POLL_TIMEOUT = -3,
ALOOPER_POLL_ERROR = -4,
_,
};
pub extern fn ALooper_acquire(looper: ?*ALooper) void;
pub extern fn ALooper_release(looper: ?*ALooper) void;
pub const ALOOPER_EVENT_INPUT = @enumToInt(enum_unnamed_14.ALOOPER_EVENT_INPUT);
pub const ALOOPER_EVENT_OUTPUT = @enumToInt(enum_unnamed_14.ALOOPER_EVENT_OUTPUT);
pub const ALOOPER_EVENT_ERROR = @enumToInt(enum_unnamed_14.ALOOPER_EVENT_ERROR);
pub const ALOOPER_EVENT_HANGUP = @enumToInt(enum_unnamed_14.ALOOPER_EVENT_HANGUP);
pub const ALOOPER_EVENT_INVALID = @enumToInt(enum_unnamed_14.ALOOPER_EVENT_INVALID);
const enum_unnamed_14 = enum(c_int) {
ALOOPER_EVENT_INPUT = 1,
ALOOPER_EVENT_OUTPUT = 2,
ALOOPER_EVENT_ERROR = 4,
ALOOPER_EVENT_HANGUP = 8,
ALOOPER_EVENT_INVALID = 16,
_,
};
pub const ALooper_callbackFunc = ?fn (c_int, c_int, ?*c_void) callconv(.C) c_int;
pub extern fn ALooper_pollOnce(timeoutMillis: c_int, outFd: [*c]c_int, outEvents: [*c]c_int, outData: [*c]?*c_void) c_int;
pub extern fn ALooper_pollAll(timeoutMillis: c_int, outFd: [*c]c_int, outEvents: [*c]c_int, outData: [*c]?*c_void) c_int;
pub extern fn ALooper_wake(looper: ?*ALooper) void;
pub extern fn ALooper_addFd(looper: ?*ALooper, fd: c_int, ident: c_int, events: c_int, callback: ALooper_callbackFunc, data: ?*c_void) c_int;
pub extern fn ALooper_removeFd(looper: ?*ALooper, fd: c_int) c_int;
pub const jboolean = u8;
pub const jbyte = i8;
pub const jchar = u16;
pub const jshort = i16;
pub const jint = i32;
pub const jlong = i64;
pub const jfloat = f32;
pub const jdouble = f64;
pub const jsize = jint;
pub const jobject = ?*c_void;
pub const jclass = jobject;
pub const jstring = jobject;
pub const jarray = jobject;
pub const jobjectArray = jarray;
pub const jbooleanArray = jarray;
pub const jbyteArray = jarray;
pub const jcharArray = jarray;
pub const jshortArray = jarray;
pub const jintArray = jarray;
pub const jlongArray = jarray;
pub const jfloatArray = jarray;
pub const jdoubleArray = jarray;
pub const jthrowable = jobject;
pub const jweak = jobject;
pub const struct__jfieldID = opaque {};
pub const jfieldID = ?*struct__jfieldID;
pub const struct__jmethodID = opaque {};
pub const jmethodID = ?*struct__jmethodID;
pub const struct_JNIInvokeInterface = extern struct {
reserved0: ?*c_void,
reserved1: ?*c_void,
reserved2: ?*c_void,
DestroyJavaVM: fn (*JavaVM) callconv(.C) jint,
AttachCurrentThread: fn (*JavaVM, **JNIEnv, ?*c_void) callconv(.C) jint,
DetachCurrentThread: fn (*JavaVM) callconv(.C) jint,
GetEnv: fn (*JavaVM, *?*c_void, jint) callconv(.C) jint,
AttachCurrentThreadAsDaemon: fn (*JavaVM, **JNIEnv, ?*c_void) callconv(.C) jint,
};
pub const union_jvalue = extern union {
z: jboolean,
b: jbyte,
c: jchar,
s: jshort,
i: jint,
j: jlong,
f: jfloat,
d: jdouble,
l: jobject,
};
pub const jvalue = union_jvalue;
pub const JNIInvalidRefType = @enumToInt(enum_jobjectRefType.JNIInvalidRefType);
pub const JNILocalRefType = @enumToInt(enum_jobjectRefType.JNILocalRefType);
pub const JNIGlobalRefType = @enumToInt(enum_jobjectRefType.JNIGlobalRefType);
pub const JNIWeakGlobalRefType = @enumToInt(enum_jobjectRefType.JNIWeakGlobalRefType);
pub const enum_jobjectRefType = enum(c_int) {
JNIInvalidRefType = 0,
JNILocalRefType = 1,
JNIGlobalRefType = 2,
JNIWeakGlobalRefType = 3,
_,
};
pub const jobjectRefType = enum_jobjectRefType;
const struct_unnamed_15 = extern struct {
name: [*c]const u8,
signature: [*c]const u8,
fnPtr: ?*c_void,
};
pub const JNINativeMethod = struct_unnamed_15;
pub const JNINativeInterface = extern struct {
reserved0: ?*c_void,
reserved1: ?*c_void,
reserved2: ?*c_void,
reserved3: ?*c_void,
GetVersion: fn (*JNIEnv) callconv(.C) jint,
DefineClass: fn (*JNIEnv, [*c]const u8, jobject, [*c]const jbyte, jsize) callconv(.C) jclass,
FindClass: fn (*JNIEnv, [*c]const u8) callconv(.C) jclass,
FromReflectedMethod: fn (*JNIEnv, jobject) callconv(.C) jmethodID,
FromReflectedField: fn (*JNIEnv, jobject) callconv(.C) jfieldID,
ToReflectedMethod: fn (*JNIEnv, jclass, jmethodID, jboolean) callconv(.C) jobject,
GetSuperclass: fn (*JNIEnv, jclass) callconv(.C) jclass,
IsAssignableFrom: fn (*JNIEnv, jclass, jclass) callconv(.C) jboolean,
ToReflectedField: fn (*JNIEnv, jclass, jfieldID, jboolean) callconv(.C) jobject,
Throw: fn (*JNIEnv, jthrowable) callconv(.C) jint,
ThrowNew: fn (*JNIEnv, jclass, [*c]const u8) callconv(.C) jint,
ExceptionOccurred: fn (*JNIEnv) callconv(.C) jthrowable,
ExceptionDescribe: fn (*JNIEnv) callconv(.C) void,
ExceptionClear: fn (*JNIEnv) callconv(.C) void,
FatalError: fn (*JNIEnv, [*c]const u8) callconv(.C) void,
PushLocalFrame: fn (*JNIEnv, jint) callconv(.C) jint,
PopLocalFrame: fn (*JNIEnv, jobject) callconv(.C) jobject,
NewGlobalRef: fn (*JNIEnv, jobject) callconv(.C) jobject,
DeleteGlobalRef: fn (*JNIEnv, jobject) callconv(.C) void,
DeleteLocalRef: fn (*JNIEnv, jobject) callconv(.C) void,
IsSameObject: fn (*JNIEnv, jobject, jobject) callconv(.C) jboolean,
NewLocalRef: fn (*JNIEnv, jobject) callconv(.C) jobject,
EnsureLocalCapacity: fn (*JNIEnv, jint) callconv(.C) jint,
AllocObject: fn (*JNIEnv, jclass) callconv(.C) jobject,
NewObject: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jobject,
NewObjectV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jobject,
NewObjectA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jobject,
GetObjectClass: fn (*JNIEnv, jobject) callconv(.C) jclass,
IsInstanceOf: fn (*JNIEnv, jobject, jclass) callconv(.C) jboolean,
GetMethodID: fn (*JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(.C) jmethodID,
CallObjectMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jobject,
CallObjectMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jobject,
CallObjectMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jobject,
CallBooleanMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jboolean,
CallBooleanMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jboolean,
CallBooleanMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jboolean,
CallByteMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jbyte,
CallByteMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jbyte,
CallByteMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jbyte,
CallCharMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jchar,
CallCharMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jchar,
CallCharMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jchar,
CallShortMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jshort,
CallShortMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jshort,
CallShortMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jshort,
CallIntMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jint,
CallIntMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jint,
CallIntMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jint,
CallLongMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jlong,
CallLongMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jlong,
CallLongMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jlong,
CallFloatMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jfloat,
CallFloatMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jfloat,
CallFloatMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jfloat,
CallDoubleMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) jdouble,
CallDoubleMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) jdouble,
CallDoubleMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) jdouble,
CallVoidMethod: fn (*JNIEnv, jobject, jmethodID, ...) callconv(.C) void,
CallVoidMethodV: fn (*JNIEnv, jobject, jmethodID, va_list) callconv(.C) void,
CallVoidMethodA: fn (*JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(.C) void,
CallNonvirtualObjectMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jobject,
CallNonvirtualObjectMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jobject,
CallNonvirtualObjectMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jobject,
CallNonvirtualBooleanMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jboolean,
CallNonvirtualBooleanMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jboolean,
CallNonvirtualBooleanMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jboolean,
CallNonvirtualByteMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jbyte,
CallNonvirtualByteMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jbyte,
CallNonvirtualByteMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jbyte,
CallNonvirtualCharMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jchar,
CallNonvirtualCharMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jchar,
CallNonvirtualCharMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jchar,
CallNonvirtualShortMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jshort,
CallNonvirtualShortMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jshort,
CallNonvirtualShortMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jshort,
CallNonvirtualIntMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jint,
CallNonvirtualIntMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jint,
CallNonvirtualIntMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jint,
CallNonvirtualLongMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jlong,
CallNonvirtualLongMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jlong,
CallNonvirtualLongMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jlong,
CallNonvirtualFloatMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jfloat,
CallNonvirtualFloatMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jfloat,
CallNonvirtualFloatMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jfloat,
CallNonvirtualDoubleMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) jdouble,
CallNonvirtualDoubleMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) jdouble,
CallNonvirtualDoubleMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) jdouble,
CallNonvirtualVoidMethod: fn (*JNIEnv, jobject, jclass, jmethodID, ...) callconv(.C) void,
CallNonvirtualVoidMethodV: fn (*JNIEnv, jobject, jclass, jmethodID, va_list) callconv(.C) void,
CallNonvirtualVoidMethodA: fn (*JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(.C) void,
GetFieldID: fn (*JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(.C) jfieldID,
GetObjectField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jobject,
GetBooleanField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jboolean,
GetByteField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jbyte,
GetCharField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jchar,
GetShortField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jshort,
GetIntField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jint,
GetLongField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jlong,
GetFloatField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jfloat,
GetDoubleField: fn (*JNIEnv, jobject, jfieldID) callconv(.C) jdouble,
SetObjectField: fn (*JNIEnv, jobject, jfieldID, jobject) callconv(.C) void,
SetBooleanField: fn (*JNIEnv, jobject, jfieldID, jboolean) callconv(.C) void,
SetByteField: fn (*JNIEnv, jobject, jfieldID, jbyte) callconv(.C) void,
SetCharField: fn (*JNIEnv, jobject, jfieldID, jchar) callconv(.C) void,
SetShortField: fn (*JNIEnv, jobject, jfieldID, jshort) callconv(.C) void,
SetIntField: fn (*JNIEnv, jobject, jfieldID, jint) callconv(.C) void,
SetLongField: fn (*JNIEnv, jobject, jfieldID, jlong) callconv(.C) void,
SetFloatField: fn (*JNIEnv, jobject, jfieldID, jfloat) callconv(.C) void,
SetDoubleField: fn (*JNIEnv, jobject, jfieldID, jdouble) callconv(.C) void,
GetStaticMethodID: fn (*JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(.C) jmethodID,
CallStaticObjectMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jobject,
CallStaticObjectMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jobject,
CallStaticObjectMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jobject,
CallStaticBooleanMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jboolean,
CallStaticBooleanMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jboolean,
CallStaticBooleanMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jboolean,
CallStaticByteMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jbyte,
CallStaticByteMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jbyte,
CallStaticByteMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jbyte,
CallStaticCharMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jchar,
CallStaticCharMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jchar,
CallStaticCharMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jchar,
CallStaticShortMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jshort,
CallStaticShortMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jshort,
CallStaticShortMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jshort,
CallStaticIntMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jint,
CallStaticIntMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jint,
CallStaticIntMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jint,
CallStaticLongMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jlong,
CallStaticLongMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jlong,
CallStaticLongMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jlong,
CallStaticFloatMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jfloat,
CallStaticFloatMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jfloat,
CallStaticFloatMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jfloat,
CallStaticDoubleMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) jdouble,
CallStaticDoubleMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) jdouble,
CallStaticDoubleMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) jdouble,
CallStaticVoidMethod: fn (*JNIEnv, jclass, jmethodID, ...) callconv(.C) void,
CallStaticVoidMethodV: fn (*JNIEnv, jclass, jmethodID, va_list) callconv(.C) void,
CallStaticVoidMethodA: fn (*JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(.C) void,
GetStaticFieldID: fn (*JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(.C) jfieldID,
GetStaticObjectField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jobject,
GetStaticBooleanField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jboolean,
GetStaticByteField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jbyte,
GetStaticCharField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jchar,
GetStaticShortField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jshort,
GetStaticIntField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jint,
GetStaticLongField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jlong,
GetStaticFloatField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jfloat,
GetStaticDoubleField: fn (*JNIEnv, jclass, jfieldID) callconv(.C) jdouble,
SetStaticObjectField: fn (*JNIEnv, jclass, jfieldID, jobject) callconv(.C) void,
SetStaticBooleanField: fn (*JNIEnv, jclass, jfieldID, jboolean) callconv(.C) void,
SetStaticByteField: fn (*JNIEnv, jclass, jfieldID, jbyte) callconv(.C) void,
SetStaticCharField: fn (*JNIEnv, jclass, jfieldID, jchar) callconv(.C) void,
SetStaticShortField: fn (*JNIEnv, jclass, jfieldID, jshort) callconv(.C) void,
SetStaticIntField: fn (*JNIEnv, jclass, jfieldID, jint) callconv(.C) void,
SetStaticLongField: fn (*JNIEnv, jclass, jfieldID, jlong) callconv(.C) void,
SetStaticFloatField: fn (*JNIEnv, jclass, jfieldID, jfloat) callconv(.C) void,
SetStaticDoubleField: fn (*JNIEnv, jclass, jfieldID, jdouble) callconv(.C) void,
NewString: fn (*JNIEnv, [*c]const jchar, jsize) callconv(.C) jstring,
GetStringLength: fn (*JNIEnv, jstring) callconv(.C) jsize,
GetStringChars: fn (*JNIEnv, jstring, [*c]jboolean) callconv(.C) [*c]const jchar,
ReleaseStringChars: fn (*JNIEnv, jstring, [*c]const jchar) callconv(.C) void,
NewStringUTF: fn (*JNIEnv, [*c]const u8) callconv(.C) jstring,
GetStringUTFLength: fn (*JNIEnv, jstring) callconv(.C) jsize,
GetStringUTFChars: fn (*JNIEnv, jstring, [*c]jboolean) callconv(.C) [*c]const u8,
ReleaseStringUTFChars: fn (*JNIEnv, jstring, [*c]const u8) callconv(.C) void,
GetArrayLength: fn (*JNIEnv, jarray) callconv(.C) jsize,
NewObjectArray: fn (*JNIEnv, jsize, jclass, jobject) callconv(.C) jobjectArray,
GetObjectArrayElement: fn (*JNIEnv, jobjectArray, jsize) callconv(.C) jobject,
SetObjectArrayElement: fn (*JNIEnv, jobjectArray, jsize, jobject) callconv(.C) void,
NewBooleanArray: fn (*JNIEnv, jsize) callconv(.C) jbooleanArray,
NewByteArray: fn (*JNIEnv, jsize) callconv(.C) jbyteArray,
NewCharArray: fn (*JNIEnv, jsize) callconv(.C) jcharArray,
NewShortArray: fn (*JNIEnv, jsize) callconv(.C) jshortArray,
NewIntArray: fn (*JNIEnv, jsize) callconv(.C) jintArray,
NewLongArray: fn (*JNIEnv, jsize) callconv(.C) jlongArray,
NewFloatArray: fn (*JNIEnv, jsize) callconv(.C) jfloatArray,
NewDoubleArray: fn (*JNIEnv, jsize) callconv(.C) jdoubleArray,
GetBooleanArrayElements: fn (*JNIEnv, jbooleanArray, [*c]jboolean) callconv(.C) [*c]jboolean,
GetByteArrayElements: fn (*JNIEnv, jbyteArray, [*c]jboolean) callconv(.C) [*c]jbyte,
GetCharArrayElements: fn (*JNIEnv, jcharArray, [*c]jboolean) callconv(.C) [*c]jchar,
GetShortArrayElements: fn (*JNIEnv, jshortArray, [*c]jboolean) callconv(.C) [*c]jshort,
GetIntArrayElements: fn (*JNIEnv, jintArray, [*c]jboolean) callconv(.C) [*c]jint,
GetLongArrayElements: fn (*JNIEnv, jlongArray, [*c]jboolean) callconv(.C) [*c]jlong,
GetFloatArrayElements: fn (*JNIEnv, jfloatArray, [*c]jboolean) callconv(.C) [*c]jfloat,
GetDoubleArrayElements: fn (*JNIEnv, jdoubleArray, [*c]jboolean) callconv(.C) [*c]jdouble,
ReleaseBooleanArrayElements: fn (*JNIEnv, jbooleanArray, [*c]jboolean, jint) callconv(.C) void,
ReleaseByteArrayElements: fn (*JNIEnv, jbyteArray, [*c]jbyte, jint) callconv(.C) void,
ReleaseCharArrayElements: fn (*JNIEnv, jcharArray, [*c]jchar, jint) callconv(.C) void,
ReleaseShortArrayElements: fn (*JNIEnv, jshortArray, [*c]jshort, jint) callconv(.C) void,
ReleaseIntArrayElements: fn (*JNIEnv, jintArray, [*c]jint, jint) callconv(.C) void,
ReleaseLongArrayElements: fn (*JNIEnv, jlongArray, [*c]jlong, jint) callconv(.C) void,
ReleaseFloatArrayElements: fn (*JNIEnv, jfloatArray, [*c]jfloat, jint) callconv(.C) void,
ReleaseDoubleArrayElements: fn (*JNIEnv, jdoubleArray, [*c]jdouble, jint) callconv(.C) void,
GetBooleanArrayRegion: fn (*JNIEnv, jbooleanArray, jsize, jsize, [*c]jboolean) callconv(.C) void,
GetByteArrayRegion: fn (*JNIEnv, jbyteArray, jsize, jsize, [*c]jbyte) callconv(.C) void,
GetCharArrayRegion: fn (*JNIEnv, jcharArray, jsize, jsize, [*c]jchar) callconv(.C) void,
GetShortArrayRegion: fn (*JNIEnv, jshortArray, jsize, jsize, [*c]jshort) callconv(.C) void,
GetIntArrayRegion: fn (*JNIEnv, jintArray, jsize, jsize, [*c]jint) callconv(.C) void,
GetLongArrayRegion: fn (*JNIEnv, jlongArray, jsize, jsize, [*c]jlong) callconv(.C) void,
GetFloatArrayRegion: fn (*JNIEnv, jfloatArray, jsize, jsize, [*c]jfloat) callconv(.C) void,
GetDoubleArrayRegion: fn (*JNIEnv, jdoubleArray, jsize, jsize, [*c]jdouble) callconv(.C) void,
SetBooleanArrayRegion: fn (*JNIEnv, jbooleanArray, jsize, jsize, [*c]const jboolean) callconv(.C) void,
SetByteArrayRegion: fn (*JNIEnv, jbyteArray, jsize, jsize, [*c]const jbyte) callconv(.C) void,
SetCharArrayRegion: fn (*JNIEnv, jcharArray, jsize, jsize, [*c]const jchar) callconv(.C) void,
SetShortArrayRegion: fn (*JNIEnv, jshortArray, jsize, jsize, [*c]const jshort) callconv(.C) void,
SetIntArrayRegion: fn (*JNIEnv, jintArray, jsize, jsize, [*c]const jint) callconv(.C) void,
SetLongArrayRegion: fn (*JNIEnv, jlongArray, jsize, jsize, [*c]const jlong) callconv(.C) void,
SetFloatArrayRegion: fn (*JNIEnv, jfloatArray, jsize, jsize, [*c]const jfloat) callconv(.C) void,
SetDoubleArrayRegion: fn (*JNIEnv, jdoubleArray, jsize, jsize, [*c]const jdouble) callconv(.C) void,
RegisterNatives: fn (*JNIEnv, jclass, [*c]const JNINativeMethod, jint) callconv(.C) jint,
UnregisterNatives: fn (*JNIEnv, jclass) callconv(.C) jint,
MonitorEnter: fn (*JNIEnv, jobject) callconv(.C) jint,
MonitorExit: fn (*JNIEnv, jobject) callconv(.C) jint,
GetJavaVM: fn (*JNIEnv, [*c][*c]JavaVM) callconv(.C) jint,
GetStringRegion: fn (*JNIEnv, jstring, jsize, jsize, [*c]jchar) callconv(.C) void,
GetStringUTFRegion: fn (*JNIEnv, jstring, jsize, jsize, [*c]u8) callconv(.C) void,
GetPrimitiveArrayCritical: fn (*JNIEnv, jarray, [*c]jboolean) callconv(.C) ?*c_void,
ReleasePrimitiveArrayCritical: fn (*JNIEnv, jarray, ?*c_void, jint) callconv(.C) void,
GetStringCritical: fn (*JNIEnv, jstring, [*c]jboolean) callconv(.C) [*c]const jchar,
ReleaseStringCritical: fn (*JNIEnv, jstring, [*c]const jchar) callconv(.C) void,
NewWeakGlobalRef: fn (*JNIEnv, jobject) callconv(.C) jweak,
DeleteWeakGlobalRef: fn (*JNIEnv, jweak) callconv(.C) void,
ExceptionCheck: fn (*JNIEnv) callconv(.C) jboolean,
NewDirectByteBuffer: fn (*JNIEnv, ?*c_void, jlong) callconv(.C) jobject,
GetDirectBufferAddress: fn (*JNIEnv, jobject) callconv(.C) ?*c_void,
GetDirectBufferCapacity: fn (*JNIEnv, jobject) callconv(.C) jlong,
GetObjectRefType: fn (*JNIEnv, jobject) callconv(.C) jobjectRefType,
};
pub const struct__JNIEnv = extern struct {
functions: [*c]const JNINativeInterface,
};
pub const struct__JavaVM = extern struct {
functions: [*c]const struct_JNIInvokeInterface,
};
pub const C_JNIEnv = *const JNINativeInterface;
pub const JNIEnv = *const JNINativeInterface;
pub const JavaVM = *const struct_JNIInvokeInterface;
pub const struct_JavaVMAttachArgs = extern struct {
version: jint,
name: [*c]const u8,
group: jobject,
};
pub const JavaVMAttachArgs = struct_JavaVMAttachArgs;
pub const struct_JavaVMOption = extern struct {
optionString: [*c]const u8,
extraInfo: ?*c_void,
};
pub const JavaVMOption = struct_JavaVMOption;
pub const struct_JavaVMInitArgs = extern struct {
version: jint,
nOptions: jint,
options: [*c]JavaVMOption,
ignoreUnrecognized: jboolean,
};
pub const JavaVMInitArgs = struct_JavaVMInitArgs;
pub extern fn JNI_GetDefaultJavaVMInitArgs(?*c_void) jint;
pub extern fn JNI_CreateJavaVM([*c][*c]JavaVM, [*c][*c]JNIEnv, ?*c_void) jint;
pub extern fn JNI_GetCreatedJavaVMs([*c][*c]JavaVM, jsize, [*c]jsize) jint;
pub extern fn JNI_OnLoad(vm: [*c]JavaVM, reserved: ?*c_void) jint;
pub extern fn JNI_OnUnload(vm: [*c]JavaVM, reserved: ?*c_void) void;
pub const AKEYCODE_UNKNOWN = @enumToInt(enum_unnamed_16.AKEYCODE_UNKNOWN);
pub const AKEYCODE_SOFT_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_SOFT_LEFT);
pub const AKEYCODE_SOFT_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_SOFT_RIGHT);
pub const AKEYCODE_HOME = @enumToInt(enum_unnamed_16.AKEYCODE_HOME);
pub const AKEYCODE_BACK = @enumToInt(enum_unnamed_16.AKEYCODE_BACK);
pub const AKEYCODE_CALL = @enumToInt(enum_unnamed_16.AKEYCODE_CALL);
pub const AKEYCODE_ENDCALL = @enumToInt(enum_unnamed_16.AKEYCODE_ENDCALL);
pub const AKEYCODE_0 = @enumToInt(enum_unnamed_16.AKEYCODE_0);
pub const AKEYCODE_1 = @enumToInt(enum_unnamed_16.AKEYCODE_1);
pub const AKEYCODE_2 = @enumToInt(enum_unnamed_16.AKEYCODE_2);
pub const AKEYCODE_3 = @enumToInt(enum_unnamed_16.AKEYCODE_3);
pub const AKEYCODE_4 = @enumToInt(enum_unnamed_16.AKEYCODE_4);
pub const AKEYCODE_5 = @enumToInt(enum_unnamed_16.AKEYCODE_5);
pub const AKEYCODE_6 = @enumToInt(enum_unnamed_16.AKEYCODE_6);
pub const AKEYCODE_7 = @enumToInt(enum_unnamed_16.AKEYCODE_7);
pub const AKEYCODE_8 = @enumToInt(enum_unnamed_16.AKEYCODE_8);
pub const AKEYCODE_9 = @enumToInt(enum_unnamed_16.AKEYCODE_9);
pub const AKEYCODE_STAR = @enumToInt(enum_unnamed_16.AKEYCODE_STAR);
pub const AKEYCODE_POUND = @enumToInt(enum_unnamed_16.AKEYCODE_POUND);
pub const AKEYCODE_DPAD_UP = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_UP);
pub const AKEYCODE_DPAD_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_DOWN);
pub const AKEYCODE_DPAD_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_LEFT);
pub const AKEYCODE_DPAD_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_RIGHT);
pub const AKEYCODE_DPAD_CENTER = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_CENTER);
pub const AKEYCODE_VOLUME_UP = @enumToInt(enum_unnamed_16.AKEYCODE_VOLUME_UP);
pub const AKEYCODE_VOLUME_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_VOLUME_DOWN);
pub const AKEYCODE_POWER = @enumToInt(enum_unnamed_16.AKEYCODE_POWER);
pub const AKEYCODE_CAMERA = @enumToInt(enum_unnamed_16.AKEYCODE_CAMERA);
pub const AKEYCODE_CLEAR = @enumToInt(enum_unnamed_16.AKEYCODE_CLEAR);
pub const AKEYCODE_A = @enumToInt(enum_unnamed_16.AKEYCODE_A);
pub const AKEYCODE_B = @enumToInt(enum_unnamed_16.AKEYCODE_B);
pub const AKEYCODE_C = @enumToInt(enum_unnamed_16.AKEYCODE_C);
pub const AKEYCODE_D = @enumToInt(enum_unnamed_16.AKEYCODE_D);
pub const AKEYCODE_E = @enumToInt(enum_unnamed_16.AKEYCODE_E);
pub const AKEYCODE_F = @enumToInt(enum_unnamed_16.AKEYCODE_F);
pub const AKEYCODE_G = @enumToInt(enum_unnamed_16.AKEYCODE_G);
pub const AKEYCODE_H = @enumToInt(enum_unnamed_16.AKEYCODE_H);
pub const AKEYCODE_I = @enumToInt(enum_unnamed_16.AKEYCODE_I);
pub const AKEYCODE_J = @enumToInt(enum_unnamed_16.AKEYCODE_J);
pub const AKEYCODE_K = @enumToInt(enum_unnamed_16.AKEYCODE_K);
pub const AKEYCODE_L = @enumToInt(enum_unnamed_16.AKEYCODE_L);
pub const AKEYCODE_M = @enumToInt(enum_unnamed_16.AKEYCODE_M);
pub const AKEYCODE_N = @enumToInt(enum_unnamed_16.AKEYCODE_N);
pub const AKEYCODE_O = @enumToInt(enum_unnamed_16.AKEYCODE_O);
pub const AKEYCODE_P = @enumToInt(enum_unnamed_16.AKEYCODE_P);
pub const AKEYCODE_Q = @enumToInt(enum_unnamed_16.AKEYCODE_Q);
pub const AKEYCODE_R = @enumToInt(enum_unnamed_16.AKEYCODE_R);
pub const AKEYCODE_S = @enumToInt(enum_unnamed_16.AKEYCODE_S);
pub const AKEYCODE_T = @enumToInt(enum_unnamed_16.AKEYCODE_T);
pub const AKEYCODE_U = @enumToInt(enum_unnamed_16.AKEYCODE_U);
pub const AKEYCODE_V = @enumToInt(enum_unnamed_16.AKEYCODE_V);
pub const AKEYCODE_W = @enumToInt(enum_unnamed_16.AKEYCODE_W);
pub const AKEYCODE_X = @enumToInt(enum_unnamed_16.AKEYCODE_X);
pub const AKEYCODE_Y = @enumToInt(enum_unnamed_16.AKEYCODE_Y);
pub const AKEYCODE_Z = @enumToInt(enum_unnamed_16.AKEYCODE_Z);
pub const AKEYCODE_COMMA = @enumToInt(enum_unnamed_16.AKEYCODE_COMMA);
pub const AKEYCODE_PERIOD = @enumToInt(enum_unnamed_16.AKEYCODE_PERIOD);
pub const AKEYCODE_ALT_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_ALT_LEFT);
pub const AKEYCODE_ALT_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_ALT_RIGHT);
pub const AKEYCODE_SHIFT_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_SHIFT_LEFT);
pub const AKEYCODE_SHIFT_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_SHIFT_RIGHT);
pub const AKEYCODE_TAB = @enumToInt(enum_unnamed_16.AKEYCODE_TAB);
pub const AKEYCODE_SPACE = @enumToInt(enum_unnamed_16.AKEYCODE_SPACE);
pub const AKEYCODE_SYM = @enumToInt(enum_unnamed_16.AKEYCODE_SYM);
pub const AKEYCODE_EXPLORER = @enumToInt(enum_unnamed_16.AKEYCODE_EXPLORER);
pub const AKEYCODE_ENVELOPE = @enumToInt(enum_unnamed_16.AKEYCODE_ENVELOPE);
pub const AKEYCODE_ENTER = @enumToInt(enum_unnamed_16.AKEYCODE_ENTER);
pub const AKEYCODE_DEL = @enumToInt(enum_unnamed_16.AKEYCODE_DEL);
pub const AKEYCODE_GRAVE = @enumToInt(enum_unnamed_16.AKEYCODE_GRAVE);
pub const AKEYCODE_MINUS = @enumToInt(enum_unnamed_16.AKEYCODE_MINUS);
pub const AKEYCODE_EQUALS = @enumToInt(enum_unnamed_16.AKEYCODE_EQUALS);
pub const AKEYCODE_LEFT_BRACKET = @enumToInt(enum_unnamed_16.AKEYCODE_LEFT_BRACKET);
pub const AKEYCODE_RIGHT_BRACKET = @enumToInt(enum_unnamed_16.AKEYCODE_RIGHT_BRACKET);
pub const AKEYCODE_BACKSLASH = @enumToInt(enum_unnamed_16.AKEYCODE_BACKSLASH);
pub const AKEYCODE_SEMICOLON = @enumToInt(enum_unnamed_16.AKEYCODE_SEMICOLON);
pub const AKEYCODE_APOSTROPHE = @enumToInt(enum_unnamed_16.AKEYCODE_APOSTROPHE);
pub const AKEYCODE_SLASH = @enumToInt(enum_unnamed_16.AKEYCODE_SLASH);
pub const AKEYCODE_AT = @enumToInt(enum_unnamed_16.AKEYCODE_AT);
pub const AKEYCODE_NUM = @enumToInt(enum_unnamed_16.AKEYCODE_NUM);
pub const AKEYCODE_HEADSETHOOK = @enumToInt(enum_unnamed_16.AKEYCODE_HEADSETHOOK);
pub const AKEYCODE_FOCUS = @enumToInt(enum_unnamed_16.AKEYCODE_FOCUS);
pub const AKEYCODE_PLUS = @enumToInt(enum_unnamed_16.AKEYCODE_PLUS);
pub const AKEYCODE_MENU = @enumToInt(enum_unnamed_16.AKEYCODE_MENU);
pub const AKEYCODE_NOTIFICATION = @enumToInt(enum_unnamed_16.AKEYCODE_NOTIFICATION);
pub const AKEYCODE_SEARCH = @enumToInt(enum_unnamed_16.AKEYCODE_SEARCH);
pub const AKEYCODE_MEDIA_PLAY_PAUSE = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_PLAY_PAUSE);
pub const AKEYCODE_MEDIA_STOP = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_STOP);
pub const AKEYCODE_MEDIA_NEXT = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_NEXT);
pub const AKEYCODE_MEDIA_PREVIOUS = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_PREVIOUS);
pub const AKEYCODE_MEDIA_REWIND = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_REWIND);
pub const AKEYCODE_MEDIA_FAST_FORWARD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_FAST_FORWARD);
pub const AKEYCODE_MUTE = @enumToInt(enum_unnamed_16.AKEYCODE_MUTE);
pub const AKEYCODE_PAGE_UP = @enumToInt(enum_unnamed_16.AKEYCODE_PAGE_UP);
pub const AKEYCODE_PAGE_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_PAGE_DOWN);
pub const AKEYCODE_PICTSYMBOLS = @enumToInt(enum_unnamed_16.AKEYCODE_PICTSYMBOLS);
pub const AKEYCODE_SWITCH_CHARSET = @enumToInt(enum_unnamed_16.AKEYCODE_SWITCH_CHARSET);
pub const AKEYCODE_BUTTON_A = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_A);
pub const AKEYCODE_BUTTON_B = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_B);
pub const AKEYCODE_BUTTON_C = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_C);
pub const AKEYCODE_BUTTON_X = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_X);
pub const AKEYCODE_BUTTON_Y = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_Y);
pub const AKEYCODE_BUTTON_Z = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_Z);
pub const AKEYCODE_BUTTON_L1 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_L1);
pub const AKEYCODE_BUTTON_R1 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_R1);
pub const AKEYCODE_BUTTON_L2 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_L2);
pub const AKEYCODE_BUTTON_R2 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_R2);
pub const AKEYCODE_BUTTON_THUMBL = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_THUMBL);
pub const AKEYCODE_BUTTON_THUMBR = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_THUMBR);
pub const AKEYCODE_BUTTON_START = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_START);
pub const AKEYCODE_BUTTON_SELECT = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_SELECT);
pub const AKEYCODE_BUTTON_MODE = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_MODE);
pub const AKEYCODE_ESCAPE = @enumToInt(enum_unnamed_16.AKEYCODE_ESCAPE);
pub const AKEYCODE_FORWARD_DEL = @enumToInt(enum_unnamed_16.AKEYCODE_FORWARD_DEL);
pub const AKEYCODE_CTRL_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_CTRL_LEFT);
pub const AKEYCODE_CTRL_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_CTRL_RIGHT);
pub const AKEYCODE_CAPS_LOCK = @enumToInt(enum_unnamed_16.AKEYCODE_CAPS_LOCK);
pub const AKEYCODE_SCROLL_LOCK = @enumToInt(enum_unnamed_16.AKEYCODE_SCROLL_LOCK);
pub const AKEYCODE_META_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_META_LEFT);
pub const AKEYCODE_META_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_META_RIGHT);
pub const AKEYCODE_FUNCTION = @enumToInt(enum_unnamed_16.AKEYCODE_FUNCTION);
pub const AKEYCODE_SYSRQ = @enumToInt(enum_unnamed_16.AKEYCODE_SYSRQ);
pub const AKEYCODE_BREAK = @enumToInt(enum_unnamed_16.AKEYCODE_BREAK);
pub const AKEYCODE_MOVE_HOME = @enumToInt(enum_unnamed_16.AKEYCODE_MOVE_HOME);
pub const AKEYCODE_MOVE_END = @enumToInt(enum_unnamed_16.AKEYCODE_MOVE_END);
pub const AKEYCODE_INSERT = @enumToInt(enum_unnamed_16.AKEYCODE_INSERT);
pub const AKEYCODE_FORWARD = @enumToInt(enum_unnamed_16.AKEYCODE_FORWARD);
pub const AKEYCODE_MEDIA_PLAY = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_PLAY);
pub const AKEYCODE_MEDIA_PAUSE = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_PAUSE);
pub const AKEYCODE_MEDIA_CLOSE = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_CLOSE);
pub const AKEYCODE_MEDIA_EJECT = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_EJECT);
pub const AKEYCODE_MEDIA_RECORD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_RECORD);
pub const AKEYCODE_F1 = @enumToInt(enum_unnamed_16.AKEYCODE_F1);
pub const AKEYCODE_F2 = @enumToInt(enum_unnamed_16.AKEYCODE_F2);
pub const AKEYCODE_F3 = @enumToInt(enum_unnamed_16.AKEYCODE_F3);
pub const AKEYCODE_F4 = @enumToInt(enum_unnamed_16.AKEYCODE_F4);
pub const AKEYCODE_F5 = @enumToInt(enum_unnamed_16.AKEYCODE_F5);
pub const AKEYCODE_F6 = @enumToInt(enum_unnamed_16.AKEYCODE_F6);
pub const AKEYCODE_F7 = @enumToInt(enum_unnamed_16.AKEYCODE_F7);
pub const AKEYCODE_F8 = @enumToInt(enum_unnamed_16.AKEYCODE_F8);
pub const AKEYCODE_F9 = @enumToInt(enum_unnamed_16.AKEYCODE_F9);
pub const AKEYCODE_F10 = @enumToInt(enum_unnamed_16.AKEYCODE_F10);
pub const AKEYCODE_F11 = @enumToInt(enum_unnamed_16.AKEYCODE_F11);
pub const AKEYCODE_F12 = @enumToInt(enum_unnamed_16.AKEYCODE_F12);
pub const AKEYCODE_NUM_LOCK = @enumToInt(enum_unnamed_16.AKEYCODE_NUM_LOCK);
pub const AKEYCODE_NUMPAD_0 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_0);
pub const AKEYCODE_NUMPAD_1 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_1);
pub const AKEYCODE_NUMPAD_2 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_2);
pub const AKEYCODE_NUMPAD_3 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_3);
pub const AKEYCODE_NUMPAD_4 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_4);
pub const AKEYCODE_NUMPAD_5 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_5);
pub const AKEYCODE_NUMPAD_6 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_6);
pub const AKEYCODE_NUMPAD_7 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_7);
pub const AKEYCODE_NUMPAD_8 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_8);
pub const AKEYCODE_NUMPAD_9 = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_9);
pub const AKEYCODE_NUMPAD_DIVIDE = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_DIVIDE);
pub const AKEYCODE_NUMPAD_MULTIPLY = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_MULTIPLY);
pub const AKEYCODE_NUMPAD_SUBTRACT = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_SUBTRACT);
pub const AKEYCODE_NUMPAD_ADD = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_ADD);
pub const AKEYCODE_NUMPAD_DOT = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_DOT);
pub const AKEYCODE_NUMPAD_COMMA = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_COMMA);
pub const AKEYCODE_NUMPAD_ENTER = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_ENTER);
pub const AKEYCODE_NUMPAD_EQUALS = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_EQUALS);
pub const AKEYCODE_NUMPAD_LEFT_PAREN = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_LEFT_PAREN);
pub const AKEYCODE_NUMPAD_RIGHT_PAREN = @enumToInt(enum_unnamed_16.AKEYCODE_NUMPAD_RIGHT_PAREN);
pub const AKEYCODE_VOLUME_MUTE = @enumToInt(enum_unnamed_16.AKEYCODE_VOLUME_MUTE);
pub const AKEYCODE_INFO = @enumToInt(enum_unnamed_16.AKEYCODE_INFO);
pub const AKEYCODE_CHANNEL_UP = @enumToInt(enum_unnamed_16.AKEYCODE_CHANNEL_UP);
pub const AKEYCODE_CHANNEL_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_CHANNEL_DOWN);
pub const AKEYCODE_ZOOM_IN = @enumToInt(enum_unnamed_16.AKEYCODE_ZOOM_IN);
pub const AKEYCODE_ZOOM_OUT = @enumToInt(enum_unnamed_16.AKEYCODE_ZOOM_OUT);
pub const AKEYCODE_TV = @enumToInt(enum_unnamed_16.AKEYCODE_TV);
pub const AKEYCODE_WINDOW = @enumToInt(enum_unnamed_16.AKEYCODE_WINDOW);
pub const AKEYCODE_GUIDE = @enumToInt(enum_unnamed_16.AKEYCODE_GUIDE);
pub const AKEYCODE_DVR = @enumToInt(enum_unnamed_16.AKEYCODE_DVR);
pub const AKEYCODE_BOOKMARK = @enumToInt(enum_unnamed_16.AKEYCODE_BOOKMARK);
pub const AKEYCODE_CAPTIONS = @enumToInt(enum_unnamed_16.AKEYCODE_CAPTIONS);
pub const AKEYCODE_SETTINGS = @enumToInt(enum_unnamed_16.AKEYCODE_SETTINGS);
pub const AKEYCODE_TV_POWER = @enumToInt(enum_unnamed_16.AKEYCODE_TV_POWER);
pub const AKEYCODE_TV_INPUT = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT);
pub const AKEYCODE_STB_POWER = @enumToInt(enum_unnamed_16.AKEYCODE_STB_POWER);
pub const AKEYCODE_STB_INPUT = @enumToInt(enum_unnamed_16.AKEYCODE_STB_INPUT);
pub const AKEYCODE_AVR_POWER = @enumToInt(enum_unnamed_16.AKEYCODE_AVR_POWER);
pub const AKEYCODE_AVR_INPUT = @enumToInt(enum_unnamed_16.AKEYCODE_AVR_INPUT);
pub const AKEYCODE_PROG_RED = @enumToInt(enum_unnamed_16.AKEYCODE_PROG_RED);
pub const AKEYCODE_PROG_GREEN = @enumToInt(enum_unnamed_16.AKEYCODE_PROG_GREEN);
pub const AKEYCODE_PROG_YELLOW = @enumToInt(enum_unnamed_16.AKEYCODE_PROG_YELLOW);
pub const AKEYCODE_PROG_BLUE = @enumToInt(enum_unnamed_16.AKEYCODE_PROG_BLUE);
pub const AKEYCODE_APP_SWITCH = @enumToInt(enum_unnamed_16.AKEYCODE_APP_SWITCH);
pub const AKEYCODE_BUTTON_1 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_1);
pub const AKEYCODE_BUTTON_2 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_2);
pub const AKEYCODE_BUTTON_3 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_3);
pub const AKEYCODE_BUTTON_4 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_4);
pub const AKEYCODE_BUTTON_5 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_5);
pub const AKEYCODE_BUTTON_6 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_6);
pub const AKEYCODE_BUTTON_7 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_7);
pub const AKEYCODE_BUTTON_8 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_8);
pub const AKEYCODE_BUTTON_9 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_9);
pub const AKEYCODE_BUTTON_10 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_10);
pub const AKEYCODE_BUTTON_11 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_11);
pub const AKEYCODE_BUTTON_12 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_12);
pub const AKEYCODE_BUTTON_13 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_13);
pub const AKEYCODE_BUTTON_14 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_14);
pub const AKEYCODE_BUTTON_15 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_15);
pub const AKEYCODE_BUTTON_16 = @enumToInt(enum_unnamed_16.AKEYCODE_BUTTON_16);
pub const AKEYCODE_LANGUAGE_SWITCH = @enumToInt(enum_unnamed_16.AKEYCODE_LANGUAGE_SWITCH);
pub const AKEYCODE_MANNER_MODE = @enumToInt(enum_unnamed_16.AKEYCODE_MANNER_MODE);
pub const AKEYCODE_3D_MODE = @enumToInt(enum_unnamed_16.AKEYCODE_3D_MODE);
pub const AKEYCODE_CONTACTS = @enumToInt(enum_unnamed_16.AKEYCODE_CONTACTS);
pub const AKEYCODE_CALENDAR = @enumToInt(enum_unnamed_16.AKEYCODE_CALENDAR);
pub const AKEYCODE_MUSIC = @enumToInt(enum_unnamed_16.AKEYCODE_MUSIC);
pub const AKEYCODE_CALCULATOR = @enumToInt(enum_unnamed_16.AKEYCODE_CALCULATOR);
pub const AKEYCODE_ZENKAKU_HANKAKU = @enumToInt(enum_unnamed_16.AKEYCODE_ZENKAKU_HANKAKU);
pub const AKEYCODE_EISU = @enumToInt(enum_unnamed_16.AKEYCODE_EISU);
pub const AKEYCODE_MUHENKAN = @enumToInt(enum_unnamed_16.AKEYCODE_MUHENKAN);
pub const AKEYCODE_HENKAN = @enumToInt(enum_unnamed_16.AKEYCODE_HENKAN);
pub const AKEYCODE_KATAKANA_HIRAGANA = @enumToInt(enum_unnamed_16.AKEYCODE_KATAKANA_HIRAGANA);
pub const AKEYCODE_YEN = @enumToInt(enum_unnamed_16.AKEYCODE_YEN);
pub const AKEYCODE_RO = @enumToInt(enum_unnamed_16.AKEYCODE_RO);
pub const AKEYCODE_KANA = @enumToInt(enum_unnamed_16.AKEYCODE_KANA);
pub const AKEYCODE_ASSIST = @enumToInt(enum_unnamed_16.AKEYCODE_ASSIST);
pub const AKEYCODE_BRIGHTNESS_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_BRIGHTNESS_DOWN);
pub const AKEYCODE_BRIGHTNESS_UP = @enumToInt(enum_unnamed_16.AKEYCODE_BRIGHTNESS_UP);
pub const AKEYCODE_MEDIA_AUDIO_TRACK = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_AUDIO_TRACK);
pub const AKEYCODE_SLEEP = @enumToInt(enum_unnamed_16.AKEYCODE_SLEEP);
pub const AKEYCODE_WAKEUP = @enumToInt(enum_unnamed_16.AKEYCODE_WAKEUP);
pub const AKEYCODE_PAIRING = @enumToInt(enum_unnamed_16.AKEYCODE_PAIRING);
pub const AKEYCODE_MEDIA_TOP_MENU = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_TOP_MENU);
pub const AKEYCODE_11 = @enumToInt(enum_unnamed_16.AKEYCODE_11);
pub const AKEYCODE_12 = @enumToInt(enum_unnamed_16.AKEYCODE_12);
pub const AKEYCODE_LAST_CHANNEL = @enumToInt(enum_unnamed_16.AKEYCODE_LAST_CHANNEL);
pub const AKEYCODE_TV_DATA_SERVICE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_DATA_SERVICE);
pub const AKEYCODE_VOICE_ASSIST = @enumToInt(enum_unnamed_16.AKEYCODE_VOICE_ASSIST);
pub const AKEYCODE_TV_RADIO_SERVICE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_RADIO_SERVICE);
pub const AKEYCODE_TV_TELETEXT = @enumToInt(enum_unnamed_16.AKEYCODE_TV_TELETEXT);
pub const AKEYCODE_TV_NUMBER_ENTRY = @enumToInt(enum_unnamed_16.AKEYCODE_TV_NUMBER_ENTRY);
pub const AKEYCODE_TV_TERRESTRIAL_ANALOG = @enumToInt(enum_unnamed_16.AKEYCODE_TV_TERRESTRIAL_ANALOG);
pub const AKEYCODE_TV_TERRESTRIAL_DIGITAL = @enumToInt(enum_unnamed_16.AKEYCODE_TV_TERRESTRIAL_DIGITAL);
pub const AKEYCODE_TV_SATELLITE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_SATELLITE);
pub const AKEYCODE_TV_SATELLITE_BS = @enumToInt(enum_unnamed_16.AKEYCODE_TV_SATELLITE_BS);
pub const AKEYCODE_TV_SATELLITE_CS = @enumToInt(enum_unnamed_16.AKEYCODE_TV_SATELLITE_CS);
pub const AKEYCODE_TV_SATELLITE_SERVICE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_SATELLITE_SERVICE);
pub const AKEYCODE_TV_NETWORK = @enumToInt(enum_unnamed_16.AKEYCODE_TV_NETWORK);
pub const AKEYCODE_TV_ANTENNA_CABLE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_ANTENNA_CABLE);
pub const AKEYCODE_TV_INPUT_HDMI_1 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_HDMI_1);
pub const AKEYCODE_TV_INPUT_HDMI_2 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_HDMI_2);
pub const AKEYCODE_TV_INPUT_HDMI_3 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_HDMI_3);
pub const AKEYCODE_TV_INPUT_HDMI_4 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_HDMI_4);
pub const AKEYCODE_TV_INPUT_COMPOSITE_1 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_COMPOSITE_1);
pub const AKEYCODE_TV_INPUT_COMPOSITE_2 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_COMPOSITE_2);
pub const AKEYCODE_TV_INPUT_COMPONENT_1 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_COMPONENT_1);
pub const AKEYCODE_TV_INPUT_COMPONENT_2 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_COMPONENT_2);
pub const AKEYCODE_TV_INPUT_VGA_1 = @enumToInt(enum_unnamed_16.AKEYCODE_TV_INPUT_VGA_1);
pub const AKEYCODE_TV_AUDIO_DESCRIPTION = @enumToInt(enum_unnamed_16.AKEYCODE_TV_AUDIO_DESCRIPTION);
pub const AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = @enumToInt(enum_unnamed_16.AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP);
pub const AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN);
pub const AKEYCODE_TV_ZOOM_MODE = @enumToInt(enum_unnamed_16.AKEYCODE_TV_ZOOM_MODE);
pub const AKEYCODE_TV_CONTENTS_MENU = @enumToInt(enum_unnamed_16.AKEYCODE_TV_CONTENTS_MENU);
pub const AKEYCODE_TV_MEDIA_CONTEXT_MENU = @enumToInt(enum_unnamed_16.AKEYCODE_TV_MEDIA_CONTEXT_MENU);
pub const AKEYCODE_TV_TIMER_PROGRAMMING = @enumToInt(enum_unnamed_16.AKEYCODE_TV_TIMER_PROGRAMMING);
pub const AKEYCODE_HELP = @enumToInt(enum_unnamed_16.AKEYCODE_HELP);
pub const AKEYCODE_NAVIGATE_PREVIOUS = @enumToInt(enum_unnamed_16.AKEYCODE_NAVIGATE_PREVIOUS);
pub const AKEYCODE_NAVIGATE_NEXT = @enumToInt(enum_unnamed_16.AKEYCODE_NAVIGATE_NEXT);
pub const AKEYCODE_NAVIGATE_IN = @enumToInt(enum_unnamed_16.AKEYCODE_NAVIGATE_IN);
pub const AKEYCODE_NAVIGATE_OUT = @enumToInt(enum_unnamed_16.AKEYCODE_NAVIGATE_OUT);
pub const AKEYCODE_STEM_PRIMARY = @enumToInt(enum_unnamed_16.AKEYCODE_STEM_PRIMARY);
pub const AKEYCODE_STEM_1 = @enumToInt(enum_unnamed_16.AKEYCODE_STEM_1);
pub const AKEYCODE_STEM_2 = @enumToInt(enum_unnamed_16.AKEYCODE_STEM_2);
pub const AKEYCODE_STEM_3 = @enumToInt(enum_unnamed_16.AKEYCODE_STEM_3);
pub const AKEYCODE_DPAD_UP_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_UP_LEFT);
pub const AKEYCODE_DPAD_DOWN_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_DOWN_LEFT);
pub const AKEYCODE_DPAD_UP_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_UP_RIGHT);
pub const AKEYCODE_DPAD_DOWN_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_DPAD_DOWN_RIGHT);
pub const AKEYCODE_MEDIA_SKIP_FORWARD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_SKIP_FORWARD);
pub const AKEYCODE_MEDIA_SKIP_BACKWARD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_SKIP_BACKWARD);
pub const AKEYCODE_MEDIA_STEP_FORWARD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_STEP_FORWARD);
pub const AKEYCODE_MEDIA_STEP_BACKWARD = @enumToInt(enum_unnamed_16.AKEYCODE_MEDIA_STEP_BACKWARD);
pub const AKEYCODE_SOFT_SLEEP = @enumToInt(enum_unnamed_16.AKEYCODE_SOFT_SLEEP);
pub const AKEYCODE_CUT = @enumToInt(enum_unnamed_16.AKEYCODE_CUT);
pub const AKEYCODE_COPY = @enumToInt(enum_unnamed_16.AKEYCODE_COPY);
pub const AKEYCODE_PASTE = @enumToInt(enum_unnamed_16.AKEYCODE_PASTE);
pub const AKEYCODE_SYSTEM_NAVIGATION_UP = @enumToInt(enum_unnamed_16.AKEYCODE_SYSTEM_NAVIGATION_UP);
pub const AKEYCODE_SYSTEM_NAVIGATION_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_SYSTEM_NAVIGATION_DOWN);
pub const AKEYCODE_SYSTEM_NAVIGATION_LEFT = @enumToInt(enum_unnamed_16.AKEYCODE_SYSTEM_NAVIGATION_LEFT);
pub const AKEYCODE_SYSTEM_NAVIGATION_RIGHT = @enumToInt(enum_unnamed_16.AKEYCODE_SYSTEM_NAVIGATION_RIGHT);
pub const AKEYCODE_ALL_APPS = @enumToInt(enum_unnamed_16.AKEYCODE_ALL_APPS);
pub const AKEYCODE_REFRESH = @enumToInt(enum_unnamed_16.AKEYCODE_REFRESH);
pub const AKEYCODE_THUMBS_UP = @enumToInt(enum_unnamed_16.AKEYCODE_THUMBS_UP);
pub const AKEYCODE_THUMBS_DOWN = @enumToInt(enum_unnamed_16.AKEYCODE_THUMBS_DOWN);
pub const AKEYCODE_PROFILE_SWITCH = @enumToInt(enum_unnamed_16.AKEYCODE_PROFILE_SWITCH);
const enum_unnamed_16 = enum(c_int) {
AKEYCODE_UNKNOWN = 0,
AKEYCODE_SOFT_LEFT = 1,
AKEYCODE_SOFT_RIGHT = 2,
AKEYCODE_HOME = 3,
AKEYCODE_BACK = 4,
AKEYCODE_CALL = 5,
AKEYCODE_ENDCALL = 6,
AKEYCODE_0 = 7,
AKEYCODE_1 = 8,
AKEYCODE_2 = 9,
AKEYCODE_3 = 10,
AKEYCODE_4 = 11,
AKEYCODE_5 = 12,
AKEYCODE_6 = 13,
AKEYCODE_7 = 14,
AKEYCODE_8 = 15,
AKEYCODE_9 = 16,
AKEYCODE_STAR = 17,
AKEYCODE_POUND = 18,
AKEYCODE_DPAD_UP = 19,
AKEYCODE_DPAD_DOWN = 20,
AKEYCODE_DPAD_LEFT = 21,
AKEYCODE_DPAD_RIGHT = 22,
AKEYCODE_DPAD_CENTER = 23,
AKEYCODE_VOLUME_UP = 24,
AKEYCODE_VOLUME_DOWN = 25,
AKEYCODE_POWER = 26,
AKEYCODE_CAMERA = 27,
AKEYCODE_CLEAR = 28,
AKEYCODE_A = 29,
AKEYCODE_B = 30,
AKEYCODE_C = 31,
AKEYCODE_D = 32,
AKEYCODE_E = 33,
AKEYCODE_F = 34,
AKEYCODE_G = 35,
AKEYCODE_H = 36,
AKEYCODE_I = 37,
AKEYCODE_J = 38,
AKEYCODE_K = 39,
AKEYCODE_L = 40,
AKEYCODE_M = 41,
AKEYCODE_N = 42,
AKEYCODE_O = 43,
AKEYCODE_P = 44,
AKEYCODE_Q = 45,
AKEYCODE_R = 46,
AKEYCODE_S = 47,
AKEYCODE_T = 48,
AKEYCODE_U = 49,
AKEYCODE_V = 50,
AKEYCODE_W = 51,
AKEYCODE_X = 52,
AKEYCODE_Y = 53,
AKEYCODE_Z = 54,
AKEYCODE_COMMA = 55,
AKEYCODE_PERIOD = 56,
AKEYCODE_ALT_LEFT = 57,
AKEYCODE_ALT_RIGHT = 58,
AKEYCODE_SHIFT_LEFT = 59,
AKEYCODE_SHIFT_RIGHT = 60,
AKEYCODE_TAB = 61,
AKEYCODE_SPACE = 62,
AKEYCODE_SYM = 63,
AKEYCODE_EXPLORER = 64,
AKEYCODE_ENVELOPE = 65,
AKEYCODE_ENTER = 66,
AKEYCODE_DEL = 67,
AKEYCODE_GRAVE = 68,
AKEYCODE_MINUS = 69,
AKEYCODE_EQUALS = 70,
AKEYCODE_LEFT_BRACKET = 71,
AKEYCODE_RIGHT_BRACKET = 72,
AKEYCODE_BACKSLASH = 73,
AKEYCODE_SEMICOLON = 74,
AKEYCODE_APOSTROPHE = 75,
AKEYCODE_SLASH = 76,
AKEYCODE_AT = 77,
AKEYCODE_NUM = 78,
AKEYCODE_HEADSETHOOK = 79,
AKEYCODE_FOCUS = 80,
AKEYCODE_PLUS = 81,
AKEYCODE_MENU = 82,
AKEYCODE_NOTIFICATION = 83,
AKEYCODE_SEARCH = 84,
AKEYCODE_MEDIA_PLAY_PAUSE = 85,
AKEYCODE_MEDIA_STOP = 86,
AKEYCODE_MEDIA_NEXT = 87,
AKEYCODE_MEDIA_PREVIOUS = 88,
AKEYCODE_MEDIA_REWIND = 89,
AKEYCODE_MEDIA_FAST_FORWARD = 90,
AKEYCODE_MUTE = 91,
AKEYCODE_PAGE_UP = 92,
AKEYCODE_PAGE_DOWN = 93,
AKEYCODE_PICTSYMBOLS = 94,
AKEYCODE_SWITCH_CHARSET = 95,
AKEYCODE_BUTTON_A = 96,
AKEYCODE_BUTTON_B = 97,
AKEYCODE_BUTTON_C = 98,
AKEYCODE_BUTTON_X = 99,
AKEYCODE_BUTTON_Y = 100,
AKEYCODE_BUTTON_Z = 101,
AKEYCODE_BUTTON_L1 = 102,
AKEYCODE_BUTTON_R1 = 103,
AKEYCODE_BUTTON_L2 = 104,
AKEYCODE_BUTTON_R2 = 105,
AKEYCODE_BUTTON_THUMBL = 106,
AKEYCODE_BUTTON_THUMBR = 107,
AKEYCODE_BUTTON_START = 108,
AKEYCODE_BUTTON_SELECT = 109,
AKEYCODE_BUTTON_MODE = 110,
AKEYCODE_ESCAPE = 111,
AKEYCODE_FORWARD_DEL = 112,
AKEYCODE_CTRL_LEFT = 113,
AKEYCODE_CTRL_RIGHT = 114,
AKEYCODE_CAPS_LOCK = 115,
AKEYCODE_SCROLL_LOCK = 116,
AKEYCODE_META_LEFT = 117,
AKEYCODE_META_RIGHT = 118,
AKEYCODE_FUNCTION = 119,
AKEYCODE_SYSRQ = 120,
AKEYCODE_BREAK = 121,
AKEYCODE_MOVE_HOME = 122,
AKEYCODE_MOVE_END = 123,
AKEYCODE_INSERT = 124,
AKEYCODE_FORWARD = 125,
AKEYCODE_MEDIA_PLAY = 126,
AKEYCODE_MEDIA_PAUSE = 127,
AKEYCODE_MEDIA_CLOSE = 128,
AKEYCODE_MEDIA_EJECT = 129,
AKEYCODE_MEDIA_RECORD = 130,
AKEYCODE_F1 = 131,
AKEYCODE_F2 = 132,
AKEYCODE_F3 = 133,
AKEYCODE_F4 = 134,
AKEYCODE_F5 = 135,
AKEYCODE_F6 = 136,
AKEYCODE_F7 = 137,
AKEYCODE_F8 = 138,
AKEYCODE_F9 = 139,
AKEYCODE_F10 = 140,
AKEYCODE_F11 = 141,
AKEYCODE_F12 = 142,
AKEYCODE_NUM_LOCK = 143,
AKEYCODE_NUMPAD_0 = 144,
AKEYCODE_NUMPAD_1 = 145,
AKEYCODE_NUMPAD_2 = 146,
AKEYCODE_NUMPAD_3 = 147,
AKEYCODE_NUMPAD_4 = 148,
AKEYCODE_NUMPAD_5 = 149,
AKEYCODE_NUMPAD_6 = 150,
AKEYCODE_NUMPAD_7 = 151,
AKEYCODE_NUMPAD_8 = 152,
AKEYCODE_NUMPAD_9 = 153,
AKEYCODE_NUMPAD_DIVIDE = 154,
AKEYCODE_NUMPAD_MULTIPLY = 155,
AKEYCODE_NUMPAD_SUBTRACT = 156,
AKEYCODE_NUMPAD_ADD = 157,
AKEYCODE_NUMPAD_DOT = 158,
AKEYCODE_NUMPAD_COMMA = 159,
AKEYCODE_NUMPAD_ENTER = 160,
AKEYCODE_NUMPAD_EQUALS = 161,
AKEYCODE_NUMPAD_LEFT_PAREN = 162,
AKEYCODE_NUMPAD_RIGHT_PAREN = 163,
AKEYCODE_VOLUME_MUTE = 164,
AKEYCODE_INFO = 165,
AKEYCODE_CHANNEL_UP = 166,
AKEYCODE_CHANNEL_DOWN = 167,
AKEYCODE_ZOOM_IN = 168,
AKEYCODE_ZOOM_OUT = 169,
AKEYCODE_TV = 170,
AKEYCODE_WINDOW = 171,
AKEYCODE_GUIDE = 172,
AKEYCODE_DVR = 173,
AKEYCODE_BOOKMARK = 174,
AKEYCODE_CAPTIONS = 175,
AKEYCODE_SETTINGS = 176,
AKEYCODE_TV_POWER = 177,
AKEYCODE_TV_INPUT = 178,
AKEYCODE_STB_POWER = 179,
AKEYCODE_STB_INPUT = 180,
AKEYCODE_AVR_POWER = 181,
AKEYCODE_AVR_INPUT = 182,
AKEYCODE_PROG_RED = 183,
AKEYCODE_PROG_GREEN = 184,
AKEYCODE_PROG_YELLOW = 185,
AKEYCODE_PROG_BLUE = 186,
AKEYCODE_APP_SWITCH = 187,
AKEYCODE_BUTTON_1 = 188,
AKEYCODE_BUTTON_2 = 189,
AKEYCODE_BUTTON_3 = 190,
AKEYCODE_BUTTON_4 = 191,
AKEYCODE_BUTTON_5 = 192,
AKEYCODE_BUTTON_6 = 193,
AKEYCODE_BUTTON_7 = 194,
AKEYCODE_BUTTON_8 = 195,
AKEYCODE_BUTTON_9 = 196,
AKEYCODE_BUTTON_10 = 197,
AKEYCODE_BUTTON_11 = 198,
AKEYCODE_BUTTON_12 = 199,
AKEYCODE_BUTTON_13 = 200,
AKEYCODE_BUTTON_14 = 201,
AKEYCODE_BUTTON_15 = 202,
AKEYCODE_BUTTON_16 = 203,
AKEYCODE_LANGUAGE_SWITCH = 204,
AKEYCODE_MANNER_MODE = 205,
AKEYCODE_3D_MODE = 206,
AKEYCODE_CONTACTS = 207,
AKEYCODE_CALENDAR = 208,
AKEYCODE_MUSIC = 209,
AKEYCODE_CALCULATOR = 210,
AKEYCODE_ZENKAKU_HANKAKU = 211,
AKEYCODE_EISU = 212,
AKEYCODE_MUHENKAN = 213,
AKEYCODE_HENKAN = 214,
AKEYCODE_KATAKANA_HIRAGANA = 215,
AKEYCODE_YEN = 216,
AKEYCODE_RO = 217,
AKEYCODE_KANA = 218,
AKEYCODE_ASSIST = 219,
AKEYCODE_BRIGHTNESS_DOWN = 220,
AKEYCODE_BRIGHTNESS_UP = 221,
AKEYCODE_MEDIA_AUDIO_TRACK = 222,
AKEYCODE_SLEEP = 223,
AKEYCODE_WAKEUP = 224,
AKEYCODE_PAIRING = 225,
AKEYCODE_MEDIA_TOP_MENU = 226,
AKEYCODE_11 = 227,
AKEYCODE_12 = 228,
AKEYCODE_LAST_CHANNEL = 229,
AKEYCODE_TV_DATA_SERVICE = 230,
AKEYCODE_VOICE_ASSIST = 231,
AKEYCODE_TV_RADIO_SERVICE = 232,
AKEYCODE_TV_TELETEXT = 233,
AKEYCODE_TV_NUMBER_ENTRY = 234,
AKEYCODE_TV_TERRESTRIAL_ANALOG = 235,
AKEYCODE_TV_TERRESTRIAL_DIGITAL = 236,
AKEYCODE_TV_SATELLITE = 237,
AKEYCODE_TV_SATELLITE_BS = 238,
AKEYCODE_TV_SATELLITE_CS = 239,
AKEYCODE_TV_SATELLITE_SERVICE = 240,
AKEYCODE_TV_NETWORK = 241,
AKEYCODE_TV_ANTENNA_CABLE = 242,
AKEYCODE_TV_INPUT_HDMI_1 = 243,
AKEYCODE_TV_INPUT_HDMI_2 = 244,
AKEYCODE_TV_INPUT_HDMI_3 = 245,
AKEYCODE_TV_INPUT_HDMI_4 = 246,
AKEYCODE_TV_INPUT_COMPOSITE_1 = 247,
AKEYCODE_TV_INPUT_COMPOSITE_2 = 248,
AKEYCODE_TV_INPUT_COMPONENT_1 = 249,
AKEYCODE_TV_INPUT_COMPONENT_2 = 250,
AKEYCODE_TV_INPUT_VGA_1 = 251,
AKEYCODE_TV_AUDIO_DESCRIPTION = 252,
AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253,
AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254,
AKEYCODE_TV_ZOOM_MODE = 255,
AKEYCODE_TV_CONTENTS_MENU = 256,
AKEYCODE_TV_MEDIA_CONTEXT_MENU = 257,
AKEYCODE_TV_TIMER_PROGRAMMING = 258,
AKEYCODE_HELP = 259,
AKEYCODE_NAVIGATE_PREVIOUS = 260,
AKEYCODE_NAVIGATE_NEXT = 261,
AKEYCODE_NAVIGATE_IN = 262,
AKEYCODE_NAVIGATE_OUT = 263,
AKEYCODE_STEM_PRIMARY = 264,
AKEYCODE_STEM_1 = 265,
AKEYCODE_STEM_2 = 266,
AKEYCODE_STEM_3 = 267,
AKEYCODE_DPAD_UP_LEFT = 268,
AKEYCODE_DPAD_DOWN_LEFT = 269,
AKEYCODE_DPAD_UP_RIGHT = 270,
AKEYCODE_DPAD_DOWN_RIGHT = 271,
AKEYCODE_MEDIA_SKIP_FORWARD = 272,
AKEYCODE_MEDIA_SKIP_BACKWARD = 273,
AKEYCODE_MEDIA_STEP_FORWARD = 274,
AKEYCODE_MEDIA_STEP_BACKWARD = 275,
AKEYCODE_SOFT_SLEEP = 276,
AKEYCODE_CUT = 277,
AKEYCODE_COPY = 278,
AKEYCODE_PASTE = 279,
AKEYCODE_SYSTEM_NAVIGATION_UP = 280,
AKEYCODE_SYSTEM_NAVIGATION_DOWN = 281,
AKEYCODE_SYSTEM_NAVIGATION_LEFT = 282,
AKEYCODE_SYSTEM_NAVIGATION_RIGHT = 283,
AKEYCODE_ALL_APPS = 284,
AKEYCODE_REFRESH = 285,
AKEYCODE_THUMBS_UP = 286,
AKEYCODE_THUMBS_DOWN = 287,
AKEYCODE_PROFILE_SWITCH = 288,
_,
};
pub const AKEY_STATE_UNKNOWN = @enumToInt(enum_unnamed_17.AKEY_STATE_UNKNOWN);
pub const AKEY_STATE_UP = @enumToInt(enum_unnamed_17.AKEY_STATE_UP);
pub const AKEY_STATE_DOWN = @enumToInt(enum_unnamed_17.AKEY_STATE_DOWN);
pub const AKEY_STATE_VIRTUAL = @enumToInt(enum_unnamed_17.AKEY_STATE_VIRTUAL);
const enum_unnamed_17 = enum(c_int) {
AKEY_STATE_UNKNOWN = -1,
AKEY_STATE_UP = 0,
AKEY_STATE_DOWN = 1,
AKEY_STATE_VIRTUAL = 2,
_,
};
pub const AMETA_NONE = @enumToInt(enum_unnamed_18.AMETA_NONE);
pub const AMETA_ALT_ON = @enumToInt(enum_unnamed_18.AMETA_ALT_ON);
pub const AMETA_ALT_LEFT_ON = @enumToInt(enum_unnamed_18.AMETA_ALT_LEFT_ON);
pub const AMETA_ALT_RIGHT_ON = @enumToInt(enum_unnamed_18.AMETA_ALT_RIGHT_ON);
pub const AMETA_SHIFT_ON = @enumToInt(enum_unnamed_18.AMETA_SHIFT_ON);
pub const AMETA_SHIFT_LEFT_ON = @enumToInt(enum_unnamed_18.AMETA_SHIFT_LEFT_ON);
pub const AMETA_SHIFT_RIGHT_ON = @enumToInt(enum_unnamed_18.AMETA_SHIFT_RIGHT_ON);
pub const AMETA_SYM_ON = @enumToInt(enum_unnamed_18.AMETA_SYM_ON);
pub const AMETA_FUNCTION_ON = @enumToInt(enum_unnamed_18.AMETA_FUNCTION_ON);
pub const AMETA_CTRL_ON = @enumToInt(enum_unnamed_18.AMETA_CTRL_ON);
pub const AMETA_CTRL_LEFT_ON = @enumToInt(enum_unnamed_18.AMETA_CTRL_LEFT_ON);
pub const AMETA_CTRL_RIGHT_ON = @enumToInt(enum_unnamed_18.AMETA_CTRL_RIGHT_ON);
pub const AMETA_META_ON = @enumToInt(enum_unnamed_18.AMETA_META_ON);
pub const AMETA_META_LEFT_ON = @enumToInt(enum_unnamed_18.AMETA_META_LEFT_ON);
pub const AMETA_META_RIGHT_ON = @enumToInt(enum_unnamed_18.AMETA_META_RIGHT_ON);
pub const AMETA_CAPS_LOCK_ON = @enumToInt(enum_unnamed_18.AMETA_CAPS_LOCK_ON);
pub const AMETA_NUM_LOCK_ON = @enumToInt(enum_unnamed_18.AMETA_NUM_LOCK_ON);
pub const AMETA_SCROLL_LOCK_ON = @enumToInt(enum_unnamed_18.AMETA_SCROLL_LOCK_ON);
const enum_unnamed_18 = enum(c_int) {
AMETA_NONE = 0,
AMETA_ALT_ON = 2,
AMETA_ALT_LEFT_ON = 16,
AMETA_ALT_RIGHT_ON = 32,
AMETA_SHIFT_ON = 1,
AMETA_SHIFT_LEFT_ON = 64,
AMETA_SHIFT_RIGHT_ON = 128,
AMETA_SYM_ON = 4,
AMETA_FUNCTION_ON = 8,
AMETA_CTRL_ON = 4096,
AMETA_CTRL_LEFT_ON = 8192,
AMETA_CTRL_RIGHT_ON = 16384,
AMETA_META_ON = 65536,
AMETA_META_LEFT_ON = 131072,
AMETA_META_RIGHT_ON = 262144,
AMETA_CAPS_LOCK_ON = 1048576,
AMETA_NUM_LOCK_ON = 2097152,
AMETA_SCROLL_LOCK_ON = 4194304,
_,
};
pub const AInputEvent = opaque {};
pub const AInputEventType = enum(c_int) {
AINPUT_EVENT_TYPE_KEY = 1,
AINPUT_EVENT_TYPE_MOTION = 2,
_,
};
pub const AKEY_EVENT_ACTION_DOWN = @enumToInt(AKeyEventActionType.AKEY_EVENT_ACTION_DOWN);
pub const AKEY_EVENT_ACTION_UP = @enumToInt(AKeyEventActionType.AKEY_EVENT_ACTION_UP);
pub const AKEY_EVENT_ACTION_MULTIPLE = @enumToInt(AKeyEventActionType.AKEY_EVENT_ACTION_MULTIPLE);
pub const AKeyEventActionType = enum(c_int) {
AKEY_EVENT_ACTION_DOWN = 0,
AKEY_EVENT_ACTION_UP = 1,
AKEY_EVENT_ACTION_MULTIPLE = 2,
_,
};
pub const AKEY_EVENT_FLAG_WOKE_HERE = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_WOKE_HERE);
pub const AKEY_EVENT_FLAG_SOFT_KEYBOARD = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_SOFT_KEYBOARD);
pub const AKEY_EVENT_FLAG_KEEP_TOUCH_MODE = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_KEEP_TOUCH_MODE);
pub const AKEY_EVENT_FLAG_FROM_SYSTEM = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_FROM_SYSTEM);
pub const AKEY_EVENT_FLAG_EDITOR_ACTION = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_EDITOR_ACTION);
pub const AKEY_EVENT_FLAG_CANCELED = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_CANCELED);
pub const AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
pub const AKEY_EVENT_FLAG_LONG_PRESS = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_LONG_PRESS);
pub const AKEY_EVENT_FLAG_CANCELED_LONG_PRESS = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_CANCELED_LONG_PRESS);
pub const AKEY_EVENT_FLAG_TRACKING = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_TRACKING);
pub const AKEY_EVENT_FLAG_FALLBACK = @enumToInt(enum_unnamed_21.AKEY_EVENT_FLAG_FALLBACK);
const enum_unnamed_21 = enum(c_int) {
AKEY_EVENT_FLAG_WOKE_HERE = 1,
AKEY_EVENT_FLAG_SOFT_KEYBOARD = 2,
AKEY_EVENT_FLAG_KEEP_TOUCH_MODE = 4,
AKEY_EVENT_FLAG_FROM_SYSTEM = 8,
AKEY_EVENT_FLAG_EDITOR_ACTION = 16,
AKEY_EVENT_FLAG_CANCELED = 32,
AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY = 64,
AKEY_EVENT_FLAG_LONG_PRESS = 128,
AKEY_EVENT_FLAG_CANCELED_LONG_PRESS = 256,
AKEY_EVENT_FLAG_TRACKING = 512,
AKEY_EVENT_FLAG_FALLBACK = 1024,
_,
};
pub const AMOTION_EVENT_ACTION_MASK = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_MASK);
pub const AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK);
pub const AMOTION_EVENT_ACTION_DOWN = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_DOWN);
pub const AMOTION_EVENT_ACTION_UP = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_UP);
pub const AMOTION_EVENT_ACTION_MOVE = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_MOVE);
pub const AMOTION_EVENT_ACTION_CANCEL = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_CANCEL);
pub const AMOTION_EVENT_ACTION_OUTSIDE = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_OUTSIDE);
pub const AMOTION_EVENT_ACTION_POINTER_DOWN = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_POINTER_DOWN);
pub const AMOTION_EVENT_ACTION_POINTER_UP = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_POINTER_UP);
pub const AMOTION_EVENT_ACTION_HOVER_MOVE = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_HOVER_MOVE);
pub const AMOTION_EVENT_ACTION_SCROLL = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_SCROLL);
pub const AMOTION_EVENT_ACTION_HOVER_ENTER = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_HOVER_ENTER);
pub const AMOTION_EVENT_ACTION_HOVER_EXIT = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_HOVER_EXIT);
pub const AMOTION_EVENT_ACTION_BUTTON_PRESS = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_BUTTON_PRESS);
pub const AMOTION_EVENT_ACTION_BUTTON_RELEASE = @enumToInt(AMotionEventActionType.AMOTION_EVENT_ACTION_BUTTON_RELEASE);
pub const AMotionEventActionType = enum(c_int) {
AMOTION_EVENT_ACTION_MASK = 255,
AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = 65280,
AMOTION_EVENT_ACTION_DOWN = 0,
AMOTION_EVENT_ACTION_UP = 1,
AMOTION_EVENT_ACTION_MOVE = 2,
AMOTION_EVENT_ACTION_CANCEL = 3,
AMOTION_EVENT_ACTION_OUTSIDE = 4,
AMOTION_EVENT_ACTION_POINTER_DOWN = 5,
AMOTION_EVENT_ACTION_POINTER_UP = 6,
AMOTION_EVENT_ACTION_HOVER_MOVE = 7,
AMOTION_EVENT_ACTION_SCROLL = 8,
AMOTION_EVENT_ACTION_HOVER_ENTER = 9,
AMOTION_EVENT_ACTION_HOVER_EXIT = 10,
AMOTION_EVENT_ACTION_BUTTON_PRESS = 11,
AMOTION_EVENT_ACTION_BUTTON_RELEASE = 12,
_,
};
pub const AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED = @enumToInt(enum_unnamed_23.AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED);
const enum_unnamed_23 = enum(c_int) {
AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED = 1,
_,
};
pub const AMOTION_EVENT_EDGE_FLAG_NONE = @enumToInt(enum_unnamed_24.AMOTION_EVENT_EDGE_FLAG_NONE);
pub const AMOTION_EVENT_EDGE_FLAG_TOP = @enumToInt(enum_unnamed_24.AMOTION_EVENT_EDGE_FLAG_TOP);
pub const AMOTION_EVENT_EDGE_FLAG_BOTTOM = @enumToInt(enum_unnamed_24.AMOTION_EVENT_EDGE_FLAG_BOTTOM);
pub const AMOTION_EVENT_EDGE_FLAG_LEFT = @enumToInt(enum_unnamed_24.AMOTION_EVENT_EDGE_FLAG_LEFT);
pub const AMOTION_EVENT_EDGE_FLAG_RIGHT = @enumToInt(enum_unnamed_24.AMOTION_EVENT_EDGE_FLAG_RIGHT);
const enum_unnamed_24 = enum(c_int) {
AMOTION_EVENT_EDGE_FLAG_NONE = 0,
AMOTION_EVENT_EDGE_FLAG_TOP = 1,
AMOTION_EVENT_EDGE_FLAG_BOTTOM = 2,
AMOTION_EVENT_EDGE_FLAG_LEFT = 4,
AMOTION_EVENT_EDGE_FLAG_RIGHT = 8,
_,
};
pub const AMOTION_EVENT_AXIS_X = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_X);
pub const AMOTION_EVENT_AXIS_Y = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_Y);
pub const AMOTION_EVENT_AXIS_PRESSURE = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_PRESSURE);
pub const AMOTION_EVENT_AXIS_SIZE = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_SIZE);
pub const AMOTION_EVENT_AXIS_TOUCH_MAJOR = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_TOUCH_MAJOR);
pub const AMOTION_EVENT_AXIS_TOUCH_MINOR = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_TOUCH_MINOR);
pub const AMOTION_EVENT_AXIS_TOOL_MAJOR = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_TOOL_MAJOR);
pub const AMOTION_EVENT_AXIS_TOOL_MINOR = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_TOOL_MINOR);
pub const AMOTION_EVENT_AXIS_ORIENTATION = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_ORIENTATION);
pub const AMOTION_EVENT_AXIS_VSCROLL = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_VSCROLL);
pub const AMOTION_EVENT_AXIS_HSCROLL = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_HSCROLL);
pub const AMOTION_EVENT_AXIS_Z = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_Z);
pub const AMOTION_EVENT_AXIS_RX = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RX);
pub const AMOTION_EVENT_AXIS_RY = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RY);
pub const AMOTION_EVENT_AXIS_RZ = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RZ);
pub const AMOTION_EVENT_AXIS_HAT_X = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_HAT_X);
pub const AMOTION_EVENT_AXIS_HAT_Y = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_HAT_Y);
pub const AMOTION_EVENT_AXIS_LTRIGGER = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_LTRIGGER);
pub const AMOTION_EVENT_AXIS_RTRIGGER = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RTRIGGER);
pub const AMOTION_EVENT_AXIS_THROTTLE = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_THROTTLE);
pub const AMOTION_EVENT_AXIS_RUDDER = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RUDDER);
pub const AMOTION_EVENT_AXIS_WHEEL = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_WHEEL);
pub const AMOTION_EVENT_AXIS_GAS = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GAS);
pub const AMOTION_EVENT_AXIS_BRAKE = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_BRAKE);
pub const AMOTION_EVENT_AXIS_DISTANCE = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_DISTANCE);
pub const AMOTION_EVENT_AXIS_TILT = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_TILT);
pub const AMOTION_EVENT_AXIS_SCROLL = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_SCROLL);
pub const AMOTION_EVENT_AXIS_RELATIVE_X = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RELATIVE_X);
pub const AMOTION_EVENT_AXIS_RELATIVE_Y = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_RELATIVE_Y);
pub const AMOTION_EVENT_AXIS_GENERIC_1 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_1);
pub const AMOTION_EVENT_AXIS_GENERIC_2 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_2);
pub const AMOTION_EVENT_AXIS_GENERIC_3 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_3);
pub const AMOTION_EVENT_AXIS_GENERIC_4 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_4);
pub const AMOTION_EVENT_AXIS_GENERIC_5 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_5);
pub const AMOTION_EVENT_AXIS_GENERIC_6 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_6);
pub const AMOTION_EVENT_AXIS_GENERIC_7 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_7);
pub const AMOTION_EVENT_AXIS_GENERIC_8 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_8);
pub const AMOTION_EVENT_AXIS_GENERIC_9 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_9);
pub const AMOTION_EVENT_AXIS_GENERIC_10 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_10);
pub const AMOTION_EVENT_AXIS_GENERIC_11 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_11);
pub const AMOTION_EVENT_AXIS_GENERIC_12 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_12);
pub const AMOTION_EVENT_AXIS_GENERIC_13 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_13);
pub const AMOTION_EVENT_AXIS_GENERIC_14 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_14);
pub const AMOTION_EVENT_AXIS_GENERIC_15 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_15);
pub const AMOTION_EVENT_AXIS_GENERIC_16 = @enumToInt(enum_unnamed_25.AMOTION_EVENT_AXIS_GENERIC_16);
const enum_unnamed_25 = enum(c_int) {
AMOTION_EVENT_AXIS_X = 0,
AMOTION_EVENT_AXIS_Y = 1,
AMOTION_EVENT_AXIS_PRESSURE = 2,
AMOTION_EVENT_AXIS_SIZE = 3,
AMOTION_EVENT_AXIS_TOUCH_MAJOR = 4,
AMOTION_EVENT_AXIS_TOUCH_MINOR = 5,
AMOTION_EVENT_AXIS_TOOL_MAJOR = 6,
AMOTION_EVENT_AXIS_TOOL_MINOR = 7,
AMOTION_EVENT_AXIS_ORIENTATION = 8,
AMOTION_EVENT_AXIS_VSCROLL = 9,
AMOTION_EVENT_AXIS_HSCROLL = 10,
AMOTION_EVENT_AXIS_Z = 11,
AMOTION_EVENT_AXIS_RX = 12,
AMOTION_EVENT_AXIS_RY = 13,
AMOTION_EVENT_AXIS_RZ = 14,
AMOTION_EVENT_AXIS_HAT_X = 15,
AMOTION_EVENT_AXIS_HAT_Y = 16,
AMOTION_EVENT_AXIS_LTRIGGER = 17,
AMOTION_EVENT_AXIS_RTRIGGER = 18,
AMOTION_EVENT_AXIS_THROTTLE = 19,
AMOTION_EVENT_AXIS_RUDDER = 20,
AMOTION_EVENT_AXIS_WHEEL = 21,
AMOTION_EVENT_AXIS_GAS = 22,
AMOTION_EVENT_AXIS_BRAKE = 23,
AMOTION_EVENT_AXIS_DISTANCE = 24,
AMOTION_EVENT_AXIS_TILT = 25,
AMOTION_EVENT_AXIS_SCROLL = 26,
AMOTION_EVENT_AXIS_RELATIVE_X = 27,
AMOTION_EVENT_AXIS_RELATIVE_Y = 28,
AMOTION_EVENT_AXIS_GENERIC_1 = 32,
AMOTION_EVENT_AXIS_GENERIC_2 = 33,
AMOTION_EVENT_AXIS_GENERIC_3 = 34,
AMOTION_EVENT_AXIS_GENERIC_4 = 35,
AMOTION_EVENT_AXIS_GENERIC_5 = 36,
AMOTION_EVENT_AXIS_GENERIC_6 = 37,
AMOTION_EVENT_AXIS_GENERIC_7 = 38,
AMOTION_EVENT_AXIS_GENERIC_8 = 39,
AMOTION_EVENT_AXIS_GENERIC_9 = 40,
AMOTION_EVENT_AXIS_GENERIC_10 = 41,
AMOTION_EVENT_AXIS_GENERIC_11 = 42,
AMOTION_EVENT_AXIS_GENERIC_12 = 43,
AMOTION_EVENT_AXIS_GENERIC_13 = 44,
AMOTION_EVENT_AXIS_GENERIC_14 = 45,
AMOTION_EVENT_AXIS_GENERIC_15 = 46,
AMOTION_EVENT_AXIS_GENERIC_16 = 47,
_,
};
pub const AMOTION_EVENT_BUTTON_PRIMARY = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_PRIMARY);
pub const AMOTION_EVENT_BUTTON_SECONDARY = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_SECONDARY);
pub const AMOTION_EVENT_BUTTON_TERTIARY = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_TERTIARY);
pub const AMOTION_EVENT_BUTTON_BACK = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_BACK);
pub const AMOTION_EVENT_BUTTON_FORWARD = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_FORWARD);
pub const AMOTION_EVENT_BUTTON_STYLUS_PRIMARY = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_STYLUS_PRIMARY);
pub const AMOTION_EVENT_BUTTON_STYLUS_SECONDARY = @enumToInt(enum_unnamed_26.AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
const enum_unnamed_26 = enum(c_int) {
AMOTION_EVENT_BUTTON_PRIMARY = 1,
AMOTION_EVENT_BUTTON_SECONDARY = 2,
AMOTION_EVENT_BUTTON_TERTIARY = 4,
AMOTION_EVENT_BUTTON_BACK = 8,
AMOTION_EVENT_BUTTON_FORWARD = 16,
AMOTION_EVENT_BUTTON_STYLUS_PRIMARY = 32,
AMOTION_EVENT_BUTTON_STYLUS_SECONDARY = 64,
_,
};
pub const AMOTION_EVENT_TOOL_TYPE_UNKNOWN = @enumToInt(enum_unnamed_27.AMOTION_EVENT_TOOL_TYPE_UNKNOWN);
pub const AMOTION_EVENT_TOOL_TYPE_FINGER = @enumToInt(enum_unnamed_27.AMOTION_EVENT_TOOL_TYPE_FINGER);
pub const AMOTION_EVENT_TOOL_TYPE_STYLUS = @enumToInt(enum_unnamed_27.AMOTION_EVENT_TOOL_TYPE_STYLUS);
pub const AMOTION_EVENT_TOOL_TYPE_MOUSE = @enumToInt(enum_unnamed_27.AMOTION_EVENT_TOOL_TYPE_MOUSE);
pub const AMOTION_EVENT_TOOL_TYPE_ERASER = @enumToInt(enum_unnamed_27.AMOTION_EVENT_TOOL_TYPE_ERASER);
const enum_unnamed_27 = enum(c_int) {
AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0,
AMOTION_EVENT_TOOL_TYPE_FINGER = 1,
AMOTION_EVENT_TOOL_TYPE_STYLUS = 2,
AMOTION_EVENT_TOOL_TYPE_MOUSE = 3,
AMOTION_EVENT_TOOL_TYPE_ERASER = 4,
_,
};
pub const AINPUT_SOURCE_CLASS_MASK = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_MASK);
pub const AINPUT_SOURCE_CLASS_NONE = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_NONE);
pub const AINPUT_SOURCE_CLASS_BUTTON = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_BUTTON);
pub const AINPUT_SOURCE_CLASS_POINTER = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_POINTER);
pub const AINPUT_SOURCE_CLASS_NAVIGATION = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_NAVIGATION);
pub const AINPUT_SOURCE_CLASS_POSITION = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_POSITION);
pub const AINPUT_SOURCE_CLASS_JOYSTICK = @enumToInt(enum_unnamed_28.AINPUT_SOURCE_CLASS_JOYSTICK);
const enum_unnamed_28 = enum(c_int) {
AINPUT_SOURCE_CLASS_MASK = 255,
AINPUT_SOURCE_CLASS_NONE = 0,
AINPUT_SOURCE_CLASS_BUTTON = 1,
AINPUT_SOURCE_CLASS_POINTER = 2,
AINPUT_SOURCE_CLASS_NAVIGATION = 4,
AINPUT_SOURCE_CLASS_POSITION = 8,
AINPUT_SOURCE_CLASS_JOYSTICK = 16,
_,
};
pub const AINPUT_SOURCE_UNKNOWN = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_UNKNOWN);
pub const AINPUT_SOURCE_KEYBOARD = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_KEYBOARD);
pub const AINPUT_SOURCE_DPAD = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_DPAD);
pub const AINPUT_SOURCE_GAMEPAD = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_GAMEPAD);
pub const AINPUT_SOURCE_TOUCHSCREEN = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_TOUCHSCREEN);
pub const AINPUT_SOURCE_MOUSE = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_MOUSE);
pub const AINPUT_SOURCE_STYLUS = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_STYLUS);
pub const AINPUT_SOURCE_BLUETOOTH_STYLUS = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_BLUETOOTH_STYLUS);
pub const AINPUT_SOURCE_TRACKBALL = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_TRACKBALL);
pub const AINPUT_SOURCE_MOUSE_RELATIVE = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_MOUSE_RELATIVE);
pub const AINPUT_SOURCE_TOUCHPAD = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_TOUCHPAD);
pub const AINPUT_SOURCE_TOUCH_NAVIGATION = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_TOUCH_NAVIGATION);
pub const AINPUT_SOURCE_JOYSTICK = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_JOYSTICK);
pub const AINPUT_SOURCE_ROTARY_ENCODER = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_ROTARY_ENCODER);
pub const AINPUT_SOURCE_ANY = @enumToInt(enum_unnamed_29.AINPUT_SOURCE_ANY);
const enum_unnamed_29 = enum(c_int) {
AINPUT_SOURCE_UNKNOWN = 0,
AINPUT_SOURCE_KEYBOARD = 257,
AINPUT_SOURCE_DPAD = 513,
AINPUT_SOURCE_GAMEPAD = 1025,
AINPUT_SOURCE_TOUCHSCREEN = 4098,
AINPUT_SOURCE_MOUSE = 8194,
AINPUT_SOURCE_STYLUS = 16386,
AINPUT_SOURCE_BLUETOOTH_STYLUS = 49154,
AINPUT_SOURCE_TRACKBALL = 65540,
AINPUT_SOURCE_MOUSE_RELATIVE = 131076,
AINPUT_SOURCE_TOUCHPAD = 1048584,
AINPUT_SOURCE_TOUCH_NAVIGATION = 2097152,
AINPUT_SOURCE_JOYSTICK = 16777232,
AINPUT_SOURCE_ROTARY_ENCODER = 4194304,
AINPUT_SOURCE_ANY = 4294967040,
_,
};
pub const AINPUT_KEYBOARD_TYPE_NONE = @enumToInt(enum_unnamed_30.AINPUT_KEYBOARD_TYPE_NONE);
pub const AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC = @enumToInt(enum_unnamed_30.AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC);
pub const AINPUT_KEYBOARD_TYPE_ALPHABETIC = @enumToInt(enum_unnamed_30.AINPUT_KEYBOARD_TYPE_ALPHABETIC);
const enum_unnamed_30 = enum(c_int) {
AINPUT_KEYBOARD_TYPE_NONE = 0,
AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC = 1,
AINPUT_KEYBOARD_TYPE_ALPHABETIC = 2,
_,
};
pub const AINPUT_MOTION_RANGE_X = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_X);
pub const AINPUT_MOTION_RANGE_Y = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_Y);
pub const AINPUT_MOTION_RANGE_PRESSURE = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_PRESSURE);
pub const AINPUT_MOTION_RANGE_SIZE = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_SIZE);
pub const AINPUT_MOTION_RANGE_TOUCH_MAJOR = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_TOUCH_MAJOR);
pub const AINPUT_MOTION_RANGE_TOUCH_MINOR = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_TOUCH_MINOR);
pub const AINPUT_MOTION_RANGE_TOOL_MAJOR = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_TOOL_MAJOR);
pub const AINPUT_MOTION_RANGE_TOOL_MINOR = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_TOOL_MINOR);
pub const AINPUT_MOTION_RANGE_ORIENTATION = @enumToInt(enum_unnamed_31.AINPUT_MOTION_RANGE_ORIENTATION);
const enum_unnamed_31 = enum(c_int) {
AINPUT_MOTION_RANGE_X = 0,
AINPUT_MOTION_RANGE_Y = 1,
AINPUT_MOTION_RANGE_PRESSURE = 2,
AINPUT_MOTION_RANGE_SIZE = 3,
AINPUT_MOTION_RANGE_TOUCH_MAJOR = 4,
AINPUT_MOTION_RANGE_TOUCH_MINOR = 5,
AINPUT_MOTION_RANGE_TOOL_MAJOR = 6,
AINPUT_MOTION_RANGE_TOOL_MINOR = 7,
AINPUT_MOTION_RANGE_ORIENTATION = 8,
_,
};
pub extern fn AInputEvent_getType(event: ?*const AInputEvent) i32;
pub extern fn AInputEvent_getDeviceId(event: ?*const AInputEvent) i32;
pub extern fn AInputEvent_getSource(event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getAction(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getFlags(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getKeyCode(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getScanCode(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getMetaState(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getRepeatCount(key_event: ?*const AInputEvent) i32;
pub extern fn AKeyEvent_getDownTime(key_event: ?*const AInputEvent) i64;
pub extern fn AKeyEvent_getEventTime(key_event: ?*const AInputEvent) i64;
pub extern fn AMotionEvent_getAction(motion_event: ?*const AInputEvent) i32;
pub extern fn AMotionEvent_getFlags(motion_event: ?*const AInputEvent) i32;
pub extern fn AMotionEvent_getMetaState(motion_event: ?*const AInputEvent) i32;
pub extern fn AMotionEvent_getButtonState(motion_event: ?*const AInputEvent) i32;
pub extern fn AMotionEvent_getEdgeFlags(motion_event: ?*const AInputEvent) i32;
pub extern fn AMotionEvent_getDownTime(motion_event: ?*const AInputEvent) i64;
pub extern fn AMotionEvent_getEventTime(motion_event: ?*const AInputEvent) i64;
pub extern fn AMotionEvent_getXOffset(motion_event: ?*const AInputEvent) f32;
pub extern fn AMotionEvent_getYOffset(motion_event: ?*const AInputEvent) f32;
pub extern fn AMotionEvent_getXPrecision(motion_event: ?*const AInputEvent) f32;
pub extern fn AMotionEvent_getYPrecision(motion_event: ?*const AInputEvent) f32;
pub extern fn AMotionEvent_getPointerCount(motion_event: ?*const AInputEvent) usize;
pub extern fn AMotionEvent_getPointerId(motion_event: ?*const AInputEvent, pointer_index: usize) i32;
pub extern fn AMotionEvent_getToolType(motion_event: ?*const AInputEvent, pointer_index: usize) i32;
pub extern fn AMotionEvent_getRawX(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getRawY(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getX(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getY(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getPressure(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getSize(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getTouchMajor(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getTouchMinor(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getToolMajor(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getToolMinor(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getOrientation(motion_event: ?*const AInputEvent, pointer_index: usize) f32;
pub extern fn AMotionEvent_getAxisValue(motion_event: ?*const AInputEvent, axis: i32, pointer_index: usize) f32;
pub extern fn AMotionEvent_getHistorySize(motion_event: ?*const AInputEvent) usize;
pub extern fn AMotionEvent_getHistoricalEventTime(motion_event: ?*const AInputEvent, history_index: usize) i64;
pub extern fn AMotionEvent_getHistoricalRawX(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalRawY(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalX(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalY(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalPressure(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalSize(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalTouchMajor(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalTouchMinor(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalToolMajor(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalToolMinor(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalOrientation(motion_event: ?*const AInputEvent, pointer_index: usize, history_index: usize) f32;
pub extern fn AMotionEvent_getHistoricalAxisValue(motion_event: ?*const AInputEvent, axis: i32, pointer_index: usize, history_index: usize) f32;
pub const AInputQueue = opaque {};
pub extern fn AInputQueue_attachLooper(queue: ?*AInputQueue, looper: ?*ALooper, ident: c_int, callback: ALooper_callbackFunc, data: ?*c_void) void;
pub extern fn AInputQueue_detachLooper(queue: ?*AInputQueue) void;
pub extern fn AInputQueue_hasEvents(queue: ?*AInputQueue) i32;
pub extern fn AInputQueue_getEvent(queue: ?*AInputQueue, outEvent: *?*AInputEvent) i32;
pub extern fn AInputQueue_preDispatchEvent(queue: ?*AInputQueue, event: ?*AInputEvent) i32;
pub extern fn AInputQueue_finishEvent(queue: ?*AInputQueue, event: ?*AInputEvent, handled: c_int) void;
const struct_unnamed_32 = extern struct {
quot: intmax_t,
rem: intmax_t,
};
pub const imaxdiv_t = struct_unnamed_32;
pub extern fn imaxabs(__i: intmax_t) intmax_t;
pub extern fn imaxdiv(__numerator: intmax_t, __denominator: intmax_t) imaxdiv_t;
pub extern fn strtoimax(__s: [*c]const u8, __end_ptr: [*c][*c]u8, __base: c_int) intmax_t;
pub extern fn strtoumax(__s: [*c]const u8, __end_ptr: [*c][*c]u8, __base: c_int) uintmax_t;
pub extern fn wcstoimax(__s: [*c]const wchar_t, __end_ptr: [*c][*c]wchar_t, __base: c_int) intmax_t;
pub extern fn wcstoumax(__s: [*c]const wchar_t, __end_ptr: [*c][*c]wchar_t, __base: c_int) uintmax_t;
pub const ADATASPACE_UNKNOWN = @enumToInt(enum_ADataSpace.ADATASPACE_UNKNOWN);
pub const ADATASPACE_SCRGB_LINEAR = @enumToInt(enum_ADataSpace.ADATASPACE_SCRGB_LINEAR);
pub const ADATASPACE_SRGB = @enumToInt(enum_ADataSpace.ADATASPACE_SRGB);
pub const ADATASPACE_SCRGB = @enumToInt(enum_ADataSpace.ADATASPACE_SCRGB);
pub const ADATASPACE_DISPLAY_P3 = @enumToInt(enum_ADataSpace.ADATASPACE_DISPLAY_P3);
pub const ADATASPACE_BT2020_PQ = @enumToInt(enum_ADataSpace.ADATASPACE_BT2020_PQ);
pub const enum_ADataSpace = enum(c_int) {
ADATASPACE_UNKNOWN = 0,
ADATASPACE_SCRGB_LINEAR = 406913024,
ADATASPACE_SRGB = 142671872,
ADATASPACE_SCRGB = 411107328,
ADATASPACE_DISPLAY_P3 = 143261696,
ADATASPACE_BT2020_PQ = 163971072,
_,
};
pub const struct_ARect = extern struct {
left: i32,
top: i32,
right: i32,
bottom: i32,
};
pub const ARect = struct_ARect;
pub const AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM);
pub const AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM);
pub const AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM);
pub const AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM);
pub const AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT);
pub const AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM);
pub const AHARDWAREBUFFER_FORMAT_BLOB = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_BLOB);
pub const AHARDWAREBUFFER_FORMAT_D16_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_D16_UNORM);
pub const AHARDWAREBUFFER_FORMAT_D24_UNORM = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_D24_UNORM);
pub const AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT);
pub const AHARDWAREBUFFER_FORMAT_D32_FLOAT = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_D32_FLOAT);
pub const AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT);
pub const AHARDWAREBUFFER_FORMAT_S8_UINT = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_S8_UINT);
pub const AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420 = @enumToInt(enum_AHardwareBuffer_Format.AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420);
pub const enum_AHardwareBuffer_Format = enum(c_int) {
AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM = 1,
AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM = 2,
AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM = 3,
AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM = 4,
AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT = 22,
AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM = 43,
AHARDWAREBUFFER_FORMAT_BLOB = 33,
AHARDWAREBUFFER_FORMAT_D16_UNORM = 48,
AHARDWAREBUFFER_FORMAT_D24_UNORM = 49,
AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT = 50,
AHARDWAREBUFFER_FORMAT_D32_FLOAT = 51,
AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT = 52,
AHARDWAREBUFFER_FORMAT_S8_UINT = 53,
AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420 = 35,
_,
};
pub const AHARDWAREBUFFER_USAGE_CPU_READ_NEVER = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_READ_NEVER);
pub const AHARDWAREBUFFER_USAGE_CPU_READ_RARELY = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_READ_RARELY);
pub const AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
pub const AHARDWAREBUFFER_USAGE_CPU_READ_MASK = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_READ_MASK);
pub const AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER);
pub const AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY);
pub const AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN);
pub const AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK);
pub const AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE);
pub const AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER);
pub const AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT);
pub const AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY);
pub const AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT);
pub const AHARDWAREBUFFER_USAGE_VIDEO_ENCODE = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VIDEO_ENCODE);
pub const AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA);
pub const AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER);
pub const AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP);
pub const AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE);
pub const AHARDWAREBUFFER_USAGE_VENDOR_0 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_0);
pub const AHARDWAREBUFFER_USAGE_VENDOR_1 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_1);
pub const AHARDWAREBUFFER_USAGE_VENDOR_2 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_2);
pub const AHARDWAREBUFFER_USAGE_VENDOR_3 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_3);
pub const AHARDWAREBUFFER_USAGE_VENDOR_4 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_4);
pub const AHARDWAREBUFFER_USAGE_VENDOR_5 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_5);
pub const AHARDWAREBUFFER_USAGE_VENDOR_6 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_6);
pub const AHARDWAREBUFFER_USAGE_VENDOR_7 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_7);
pub const AHARDWAREBUFFER_USAGE_VENDOR_8 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_8);
pub const AHARDWAREBUFFER_USAGE_VENDOR_9 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_9);
pub const AHARDWAREBUFFER_USAGE_VENDOR_10 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_10);
pub const AHARDWAREBUFFER_USAGE_VENDOR_11 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_11);
pub const AHARDWAREBUFFER_USAGE_VENDOR_12 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_12);
pub const AHARDWAREBUFFER_USAGE_VENDOR_13 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_13);
pub const AHARDWAREBUFFER_USAGE_VENDOR_14 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_14);
pub const AHARDWAREBUFFER_USAGE_VENDOR_15 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_15);
pub const AHARDWAREBUFFER_USAGE_VENDOR_16 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_16);
pub const AHARDWAREBUFFER_USAGE_VENDOR_17 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_17);
pub const AHARDWAREBUFFER_USAGE_VENDOR_18 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_18);
pub const AHARDWAREBUFFER_USAGE_VENDOR_19 = @enumToInt(enum_AHardwareBuffer_UsageFlags.AHARDWAREBUFFER_USAGE_VENDOR_19);
pub const enum_AHardwareBuffer_UsageFlags = enum(c_ulong) {
AHARDWAREBUFFER_USAGE_CPU_READ_NEVER = 0,
AHARDWAREBUFFER_USAGE_CPU_READ_RARELY = 2,
AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN = 3,
AHARDWAREBUFFER_USAGE_CPU_READ_MASK = 15,
AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER = 0,
AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY = 32,
AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN = 48,
AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK = 240,
AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE = 256,
AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER = 512,
AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT = 512,
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY = 2048,
AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT = 16384,
AHARDWAREBUFFER_USAGE_VIDEO_ENCODE = 65536,
AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA = 8388608,
AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER = 16777216,
AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP = 33554432,
AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE = 67108864,
AHARDWAREBUFFER_USAGE_VENDOR_0 = 268435456,
AHARDWAREBUFFER_USAGE_VENDOR_1 = 536870912,
AHARDWAREBUFFER_USAGE_VENDOR_2 = 1073741824,
AHARDWAREBUFFER_USAGE_VENDOR_3 = 2147483648,
AHARDWAREBUFFER_USAGE_VENDOR_4 = 281474976710656,
AHARDWAREBUFFER_USAGE_VENDOR_5 = 562949953421312,
AHARDWAREBUFFER_USAGE_VENDOR_6 = 1125899906842624,
AHARDWAREBUFFER_USAGE_VENDOR_7 = 2251799813685248,
AHARDWAREBUFFER_USAGE_VENDOR_8 = 4503599627370496,
AHARDWAREBUFFER_USAGE_VENDOR_9 = 9007199254740992,
AHARDWAREBUFFER_USAGE_VENDOR_10 = 18014398509481984,
AHARDWAREBUFFER_USAGE_VENDOR_11 = 36028797018963968,
AHARDWAREBUFFER_USAGE_VENDOR_12 = 72057594037927936,
AHARDWAREBUFFER_USAGE_VENDOR_13 = 144115188075855872,
AHARDWAREBUFFER_USAGE_VENDOR_14 = 288230376151711744,
AHARDWAREBUFFER_USAGE_VENDOR_15 = 576460752303423488,
AHARDWAREBUFFER_USAGE_VENDOR_16 = 1152921504606846976,
AHARDWAREBUFFER_USAGE_VENDOR_17 = 2305843009213693952,
AHARDWAREBUFFER_USAGE_VENDOR_18 = 4611686018427387904,
AHARDWAREBUFFER_USAGE_VENDOR_19 = 9223372036854775808,
_,
};
pub const struct_AHardwareBuffer_Desc = extern struct {
width: u32,
height: u32,
layers: u32,
format: u32,
usage: u64,
stride: u32,
rfu0: u32,
rfu1: u64,
};
pub const AHardwareBuffer_Desc = struct_AHardwareBuffer_Desc;
pub const struct_AHardwareBuffer_Plane = extern struct {
data: ?*c_void,
pixelStride: u32,
rowStride: u32,
};
pub const AHardwareBuffer_Plane = struct_AHardwareBuffer_Plane;
pub const struct_AHardwareBuffer_Planes = extern struct {
planeCount: u32,
planes: [4]AHardwareBuffer_Plane,
};
pub const AHardwareBuffer_Planes = struct_AHardwareBuffer_Planes;
pub const struct_AHardwareBuffer = opaque {};
pub const AHardwareBuffer = struct_AHardwareBuffer;
pub extern fn AHardwareBuffer_allocate(desc: [*c]const AHardwareBuffer_Desc, outBuffer: [*c]?*AHardwareBuffer) c_int;
pub extern fn AHardwareBuffer_acquire(buffer: ?*AHardwareBuffer) void;
pub extern fn AHardwareBuffer_release(buffer: ?*AHardwareBuffer) void;
pub extern fn AHardwareBuffer_describe(buffer: ?*const AHardwareBuffer, outDesc: [*c]AHardwareBuffer_Desc) void;
pub extern fn AHardwareBuffer_lock(buffer: ?*AHardwareBuffer, usage: u64, fence: i32, rect: [*c]const ARect, outVirtualAddress: [*c]?*c_void) c_int;
pub extern fn AHardwareBuffer_lockPlanes(buffer: ?*AHardwareBuffer, usage: u64, fence: i32, rect: [*c]const ARect, outPlanes: [*c]AHardwareBuffer_Planes) c_int;
pub extern fn AHardwareBuffer_unlock(buffer: ?*AHardwareBuffer, fence: [*c]i32) c_int;
pub extern fn AHardwareBuffer_sendHandleToUnixSocket(buffer: ?*const AHardwareBuffer, socketFd: c_int) c_int;
pub extern fn AHardwareBuffer_recvHandleFromUnixSocket(socketFd: c_int, outBuffer: [*c]?*AHardwareBuffer) c_int;
pub extern fn AHardwareBuffer_isSupported(desc: [*c]const AHardwareBuffer_Desc) c_int;
pub extern fn AHardwareBuffer_lockAndGetInfo(buffer: ?*AHardwareBuffer, usage: u64, fence: i32, rect: [*c]const ARect, outVirtualAddress: [*c]?*c_void, outBytesPerPixel: [*c]i32, outBytesPerStride: [*c]i32) c_int;
pub const WINDOW_FORMAT_RGBA_8888 = @enumToInt(enum_ANativeWindow_LegacyFormat.WINDOW_FORMAT_RGBA_8888);
pub const WINDOW_FORMAT_RGBX_8888 = @enumToInt(enum_ANativeWindow_LegacyFormat.WINDOW_FORMAT_RGBX_8888);
pub const WINDOW_FORMAT_RGB_565 = @enumToInt(enum_ANativeWindow_LegacyFormat.WINDOW_FORMAT_RGB_565);
pub const enum_ANativeWindow_LegacyFormat = enum(c_int) {
WINDOW_FORMAT_RGBA_8888 = 1,
WINDOW_FORMAT_RGBX_8888 = 2,
WINDOW_FORMAT_RGB_565 = 4,
_,
};
pub const ANATIVEWINDOW_TRANSFORM_IDENTITY = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_IDENTITY);
pub const ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL);
pub const ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL);
pub const ANATIVEWINDOW_TRANSFORM_ROTATE_90 = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_ROTATE_90);
pub const ANATIVEWINDOW_TRANSFORM_ROTATE_180 = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_ROTATE_180);
pub const ANATIVEWINDOW_TRANSFORM_ROTATE_270 = @enumToInt(enum_ANativeWindowTransform.ANATIVEWINDOW_TRANSFORM_ROTATE_270);
pub const enum_ANativeWindowTransform = enum(c_int) {
ANATIVEWINDOW_TRANSFORM_IDENTITY = 0,
ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL = 1,
ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL = 2,
ANATIVEWINDOW_TRANSFORM_ROTATE_90 = 4,
ANATIVEWINDOW_TRANSFORM_ROTATE_180 = 3,
ANATIVEWINDOW_TRANSFORM_ROTATE_270 = 7,
_,
};
pub const struct_ANativeWindow = opaque {};
pub const ANativeWindow = struct_ANativeWindow;
pub const struct_ANativeWindow_Buffer = extern struct {
width: i32,
height: i32,
stride: i32,
format: i32,
bits: ?*c_void,
reserved: [6]u32,
};
pub const ANativeWindow_Buffer = struct_ANativeWindow_Buffer;
pub extern fn ANativeWindow_acquire(window: ?*ANativeWindow) void;
pub extern fn ANativeWindow_release(window: ?*ANativeWindow) void;
pub extern fn ANativeWindow_getWidth(window: ?*ANativeWindow) i32;
pub extern fn ANativeWindow_getHeight(window: ?*ANativeWindow) i32;
pub extern fn ANativeWindow_getFormat(window: ?*ANativeWindow) i32;
pub extern fn ANativeWindow_setBuffersGeometry(window: ?*ANativeWindow, width: i32, height: i32, format: i32) i32;
pub extern fn ANativeWindow_lock(window: ?*ANativeWindow, outBuffer: [*c]ANativeWindow_Buffer, inOutDirtyBounds: [*c]ARect) i32;
pub extern fn ANativeWindow_unlockAndPost(window: ?*ANativeWindow) i32;
pub extern fn ANativeWindow_setBuffersTransform(window: ?*ANativeWindow, transform: i32) i32;
pub extern fn ANativeWindow_setBuffersDataSpace(window: ?*ANativeWindow, dataSpace: i32) i32;
pub extern fn ANativeWindow_getBuffersDataSpace(window: ?*ANativeWindow) i32;
pub const ANativeActivityCallbacks = extern struct {
onStart: ?fn (*ANativeActivity) callconv(.C) void,
onResume: ?fn (*ANativeActivity) callconv(.C) void,
onSaveInstanceState: ?fn (*ANativeActivity, *usize) callconv(.C) ?[*]u8,
onPause: ?fn (*ANativeActivity) callconv(.C) void,
onStop: ?fn (*ANativeActivity) callconv(.C) void,
onDestroy: ?fn (*ANativeActivity) callconv(.C) void,
onWindowFocusChanged: ?fn (*ANativeActivity, c_int) callconv(.C) void,
onNativeWindowCreated: ?fn (*ANativeActivity, *ANativeWindow) callconv(.C) void,
onNativeWindowResized: ?fn (*ANativeActivity, *ANativeWindow) callconv(.C) void,
onNativeWindowRedrawNeeded: ?fn (*ANativeActivity, *ANativeWindow) callconv(.C) void,
onNativeWindowDestroyed: ?fn (*ANativeActivity, *ANativeWindow) callconv(.C) void,
onInputQueueCreated: ?fn (*ANativeActivity, *AInputQueue) callconv(.C) void,
onInputQueueDestroyed: ?fn (*ANativeActivity, *AInputQueue) callconv(.C) void,
onContentRectChanged: ?fn (*ANativeActivity, *const ARect) callconv(.C) void,
onConfigurationChanged: ?fn (*ANativeActivity) callconv(.C) void,
onLowMemory: ?fn (*ANativeActivity) callconv(.C) void,
};
pub const ANativeActivity = extern struct {
callbacks: *ANativeActivityCallbacks,
vm: *JavaVM,
env: *JNIEnv,
clazz: jobject,
internalDataPath: [*:0]const u8,
externalDataPath: [*:0]const u8,
sdkVersion: i32,
instance: ?*c_void,
assetManager: ?*AAssetManager,
obbPath: [*:0]const u8,
};
pub const ANativeActivity_createFunc = fn ([*c]ANativeActivity, ?*c_void, usize) callconv(.C) void;
pub extern fn ANativeActivity_finish(activity: [*c]ANativeActivity) void;
pub extern fn ANativeActivity_setWindowFormat(activity: [*c]ANativeActivity, format: i32) void;
pub extern fn ANativeActivity_setWindowFlags(activity: [*c]ANativeActivity, addFlags: u32, removeFlags: u32) void;
pub const ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT = @enumToInt(enum_unnamed_33.ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT);
pub const ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED = @enumToInt(enum_unnamed_33.ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED);
const enum_unnamed_33 = enum(c_int) {
ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT = 1,
ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED = 2,
_,
};
pub extern fn ANativeActivity_showSoftInput(activity: [*c]ANativeActivity, flags: u32) void;
pub const ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY = @enumToInt(enum_unnamed_34.ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY);
pub const ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS = @enumToInt(enum_unnamed_34.ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS);
const enum_unnamed_34 = enum(c_int) {
ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY = 1,
ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS = 2,
_,
};
pub extern fn ANativeActivity_hideSoftInput(activity: [*c]ANativeActivity, flags: u32) void;
pub const __llvm__ = 1;
pub const __clang__ = 1;
pub const __clang_major__ = 10;
pub const __clang_minor__ = 0;
pub const __clang_patchlevel__ = 0;
pub const __clang_version__ = "10.0.0 ";
pub const __GNUC__ = 4;
pub const __GNUC_MINOR__ = 2;
pub const __GNUC_PATCHLEVEL__ = 1;
pub const __GXX_ABI_VERSION = 1002;
pub const __ATOMIC_RELAXED = 0;
pub const __ATOMIC_CONSUME = 1;
pub const __ATOMIC_ACQUIRE = 2;
pub const __ATOMIC_RELEASE = 3;
pub const __ATOMIC_ACQ_REL = 4;
pub const __ATOMIC_SEQ_CST = 5;
pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = 0;
pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = 1;
pub const __OPENCL_MEMORY_SCOPE_DEVICE = 2;
pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = 3;
pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = 4;
pub const __PRAGMA_REDEFINE_EXTNAME = 1;
pub const __VERSION__ = "Clang 10.0.0 ";
pub const __OBJC_BOOL_IS_BOOL = 0;
pub const __CONSTANT_CFSTRINGS__ = 1;
pub const __OPTIMIZE__ = 1;
pub const __ORDER_LITTLE_ENDIAN__ = 1234;
pub const __ORDER_BIG_ENDIAN__ = 4321;
pub const __ORDER_PDP_ENDIAN__ = 3412;
pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__;
pub const __LITTLE_ENDIAN__ = 1;
pub const _LP64 = 1;
pub const __LP64__ = 1;
pub const __CHAR_BIT__ = 8;
pub const __SCHAR_MAX__ = 127;
pub const __SHRT_MAX__ = 32767;
pub const __INT_MAX__ = 2147483647;
pub const __LONG_MAX__ = @as(c_long, 9223372036854775807);
pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807);
pub const __WCHAR_MAX__ = @as(c_uint, 4294967295);
pub const __WINT_MAX__ = @as(c_uint, 4294967295);
pub const __INTMAX_MAX__ = @as(c_long, 9223372036854775807);
pub const __SIZE_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __UINTMAX_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __PTRDIFF_MAX__ = @as(c_long, 9223372036854775807);
pub const __INTPTR_MAX__ = @as(c_long, 9223372036854775807);
pub const __UINTPTR_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __SIZEOF_DOUBLE__ = 8;
pub const __SIZEOF_FLOAT__ = 4;
pub const __SIZEOF_INT__ = 4;
pub const __SIZEOF_LONG__ = 8;
pub const __SIZEOF_LONG_DOUBLE__ = 16;
pub const __SIZEOF_LONG_LONG__ = 8;
pub const __SIZEOF_POINTER__ = 8;
pub const __SIZEOF_SHORT__ = 2;
pub const __SIZEOF_PTRDIFF_T__ = 8;
pub const __SIZEOF_SIZE_T__ = 8;
pub const __SIZEOF_WCHAR_T__ = 4;
pub const __SIZEOF_WINT_T__ = 4;
pub const __SIZEOF_INT128__ = 16;
pub const __INTMAX_FMTd__ = "ld";
pub const __INTMAX_FMTi__ = "li";
pub const __INTMAX_C_SUFFIX__ = L;
pub const __UINTMAX_FMTo__ = "lo";
pub const __UINTMAX_FMTu__ = "lu";
pub const __UINTMAX_FMTx__ = "lx";
pub const __UINTMAX_FMTX__ = "lX";
pub const __UINTMAX_C_SUFFIX__ = UL;
pub const __INTMAX_WIDTH__ = 64;
pub const __PTRDIFF_FMTd__ = "ld";
pub const __PTRDIFF_FMTi__ = "li";
pub const __PTRDIFF_WIDTH__ = 64;
pub const __INTPTR_FMTd__ = "ld";
pub const __INTPTR_FMTi__ = "li";
pub const __INTPTR_WIDTH__ = 64;
pub const __SIZE_FMTo__ = "lo";
pub const __SIZE_FMTu__ = "lu";
pub const __SIZE_FMTx__ = "lx";
pub const __SIZE_FMTX__ = "lX";
pub const __SIZE_WIDTH__ = 64;
pub const __WCHAR_WIDTH__ = 32;
pub const __WINT_WIDTH__ = 32;
pub const __SIG_ATOMIC_WIDTH__ = 32;
pub const __SIG_ATOMIC_MAX__ = 2147483647;
pub const __UINTMAX_WIDTH__ = 64;
pub const __UINTPTR_FMTo__ = "lo";
pub const __UINTPTR_FMTu__ = "lu";
pub const __UINTPTR_FMTx__ = "lx";
pub const __UINTPTR_FMTX__ = "lX";
pub const __UINTPTR_WIDTH__ = 64;
pub const __FLT16_HAS_DENORM__ = 1;
pub const __FLT16_DIG__ = 3;
pub const __FLT16_DECIMAL_DIG__ = 5;
pub const __FLT16_HAS_INFINITY__ = 1;
pub const __FLT16_HAS_QUIET_NAN__ = 1;
pub const __FLT16_MANT_DIG__ = 11;
pub const __FLT16_MAX_10_EXP__ = 4;
pub const __FLT16_MAX_EXP__ = 16;
pub const __FLT16_MIN_10_EXP__ = -4;
pub const __FLT16_MIN_EXP__ = -13;
pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45);
pub const __FLT_HAS_DENORM__ = 1;
pub const __FLT_DIG__ = 6;
pub const __FLT_DECIMAL_DIG__ = 9;
pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7);
pub const __FLT_HAS_INFINITY__ = 1;
pub const __FLT_HAS_QUIET_NAN__ = 1;
pub const __FLT_MANT_DIG__ = 24;
pub const __FLT_MAX_10_EXP__ = 38;
pub const __FLT_MAX_EXP__ = 128;
pub const __FLT_MAX__ = @as(f32, 3.40282347e+38);
pub const __FLT_MIN_10_EXP__ = -37;
pub const __FLT_MIN_EXP__ = -125;
pub const __FLT_MIN__ = @as(f32, 1.17549435e-38);
pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324;
pub const __DBL_HAS_DENORM__ = 1;
pub const __DBL_DIG__ = 15;
pub const __DBL_DECIMAL_DIG__ = 17;
pub const __DBL_EPSILON__ = 2.2204460492503131e-16;
pub const __DBL_HAS_INFINITY__ = 1;
pub const __DBL_HAS_QUIET_NAN__ = 1;
pub const __DBL_MANT_DIG__ = 53;
pub const __DBL_MAX_10_EXP__ = 308;
pub const __DBL_MAX_EXP__ = 1024;
pub const __DBL_MAX__ = 1.7976931348623157e+308;
pub const __DBL_MIN_10_EXP__ = -307;
pub const __DBL_MIN_EXP__ = -1021;
pub const __DBL_MIN__ = 2.2250738585072014e-308;
pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 6.47517511943802511092443895822764655e-4966);
pub const __LDBL_HAS_DENORM__ = 1;
pub const __LDBL_DIG__ = 33;
pub const __LDBL_DECIMAL_DIG__ = 36;
pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.92592994438723585305597794258492732e-34);
pub const __LDBL_HAS_INFINITY__ = 1;
pub const __LDBL_HAS_QUIET_NAN__ = 1;
pub const __LDBL_MANT_DIG__ = 113;
pub const __LDBL_MAX_10_EXP__ = 4932;
pub const __LDBL_MAX_EXP__ = 16384;
pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176508575932662800702e+4932);
pub const __LDBL_MIN_10_EXP__ = -4931;
pub const __LDBL_MIN_EXP__ = -16381;
pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626267781732175260e-4932);
pub const __POINTER_WIDTH__ = 64;
pub const __BIGGEST_ALIGNMENT__ = 16;
pub const __CHAR_UNSIGNED__ = 1;
pub const __WCHAR_UNSIGNED__ = 1;
pub const __WINT_UNSIGNED__ = 1;
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__ = "ld";
pub const __INT64_FMTi__ = "li";
pub const __INT64_C_SUFFIX__ = L;
pub const __UINT8_FMTo__ = "hho";
pub const __UINT8_FMTu__ = "hhu";
pub const __UINT8_FMTx__ = "hhx";
pub const __UINT8_FMTX__ = "hhX";
pub const __UINT8_MAX__ = 255;
pub const __INT8_MAX__ = 127;
pub const __UINT16_FMTo__ = "ho";
pub const __UINT16_FMTu__ = "hu";
pub const __UINT16_FMTx__ = "hx";
pub const __UINT16_FMTX__ = "hX";
pub const __UINT16_MAX__ = 65535;
pub const __INT16_MAX__ = 32767;
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__ = @as(c_uint, 4294967295);
pub const __INT32_MAX__ = 2147483647;
pub const __UINT64_FMTo__ = "lo";
pub const __UINT64_FMTu__ = "lu";
pub const __UINT64_FMTx__ = "lx";
pub const __UINT64_FMTX__ = "lX";
pub const __UINT64_C_SUFFIX__ = UL;
pub const __UINT64_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __INT64_MAX__ = @as(c_long, 9223372036854775807);
pub const __INT_LEAST8_MAX__ = 127;
pub const __INT_LEAST8_FMTd__ = "hhd";
pub const __INT_LEAST8_FMTi__ = "hhi";
pub const __UINT_LEAST8_MAX__ = 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__ = 32767;
pub const __INT_LEAST16_FMTd__ = "hd";
pub const __INT_LEAST16_FMTi__ = "hi";
pub const __UINT_LEAST16_MAX__ = 65535;
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__ = 2147483647;
pub const __INT_LEAST32_FMTd__ = "d";
pub const __INT_LEAST32_FMTi__ = "i";
pub const __UINT_LEAST32_MAX__ = @as(c_uint, 4294967295);
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_long, 9223372036854775807);
pub const __INT_LEAST64_FMTd__ = "ld";
pub const __INT_LEAST64_FMTi__ = "li";
pub const __UINT_LEAST64_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __UINT_LEAST64_FMTo__ = "lo";
pub const __UINT_LEAST64_FMTu__ = "lu";
pub const __UINT_LEAST64_FMTx__ = "lx";
pub const __UINT_LEAST64_FMTX__ = "lX";
pub const __INT_FAST8_MAX__ = 127;
pub const __INT_FAST8_FMTd__ = "hhd";
pub const __INT_FAST8_FMTi__ = "hhi";
pub const __UINT_FAST8_MAX__ = 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__ = 32767;
pub const __INT_FAST16_FMTd__ = "hd";
pub const __INT_FAST16_FMTi__ = "hi";
pub const __UINT_FAST16_MAX__ = 65535;
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__ = 2147483647;
pub const __INT_FAST32_FMTd__ = "d";
pub const __INT_FAST32_FMTi__ = "i";
pub const __UINT_FAST32_MAX__ = @as(c_uint, 4294967295);
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_long, 9223372036854775807);
pub const __INT_FAST64_FMTd__ = "ld";
pub const __INT_FAST64_FMTi__ = "li";
pub const __UINT_FAST64_MAX__ = @as(c_ulong, 18446744073709551615);
pub const __UINT_FAST64_FMTo__ = "lo";
pub const __UINT_FAST64_FMTu__ = "lu";
pub const __UINT_FAST64_FMTx__ = "lx";
pub const __UINT_FAST64_FMTX__ = "lX";
pub const __FINITE_MATH_ONLY__ = 0;
pub const __GNUC_STDC_INLINE__ = 1;
pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = 1;
pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_INT_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_LONG_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = 2;
pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = 2;
pub const __GCC_ATOMIC_BOOL_LOCK_FREE = 2;
pub const __GCC_ATOMIC_CHAR_LOCK_FREE = 2;
pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = 2;
pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = 2;
pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = 2;
pub const __GCC_ATOMIC_SHORT_LOCK_FREE = 2;
pub const __GCC_ATOMIC_INT_LOCK_FREE = 2;
pub const __GCC_ATOMIC_LONG_LOCK_FREE = 2;
pub const __GCC_ATOMIC_LLONG_LOCK_FREE = 2;
pub const __GCC_ATOMIC_POINTER_LOCK_FREE = 2;
pub const __PIC__ = 2;
pub const __pic__ = 2;
pub const __FLT_EVAL_METHOD__ = 0;
pub const __FLT_RADIX__ = 2;
pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__;
pub const __SSP_STRONG__ = 2;
pub const __AARCH64EL__ = 1;
pub const __aarch64__ = 1;
pub const __ARM_ACLE = 200;
pub const __ARM_ARCH = 8;
pub const __ARM_ARCH_PROFILE = 'A';
pub const __ARM_64BIT_STATE = 1;
pub const __ARM_PCS_AAPCS64 = 1;
pub const __ARM_ARCH_ISA_A64 = 1;
pub const __ARM_FEATURE_CLZ = 1;
pub const __ARM_FEATURE_FMA = 1;
pub const __ARM_FEATURE_LDREX = 0xF;
pub const __ARM_FEATURE_IDIV = 1;
pub const __ARM_FEATURE_DIV = 1;
pub const __ARM_FEATURE_NUMERIC_MAXMIN = 1;
pub const __ARM_FEATURE_DIRECTED_ROUNDING = 1;
pub const __ARM_ALIGN_MAX_STACK_PWR = 4;
pub const __ARM_FP = 0xE;
pub const __ARM_FP16_FORMAT_IEEE = 1;
pub const __ARM_FP16_ARGS = 1;
pub const __ARM_SIZEOF_WCHAR_T = 4;
pub const __ARM_SIZEOF_MINIMAL_ENUM = 4;
pub const __ARM_NEON = 1;
pub const __ARM_NEON_FP = 0xE;
pub const __ARM_FEATURE_UNALIGNED = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = 1;
pub const unix = 1;
pub const __unix = 1;
pub const __unix__ = 1;
pub const linux = 1;
pub const __linux = 1;
pub const __linux__ = 1;
pub const __ELF__ = 1;
pub const __gnu_linux__ = 1;
pub const __STDC__ = 1;
pub const __STDC_HOSTED__ = 1;
pub const __STDC_VERSION__ = @as(c_long, 201112);
pub const __STDC_UTF_16__ = 1;
pub const __STDC_UTF_32__ = 1;
pub const _DEBUG = 1;
pub const ANDROID = 1;
pub const APPNAME = "ziggy";
pub const DANDROIDVERSION = 29;
pub inline fn va_start(ap: anytype, param: anytype) @TypeOf(__builtin_va_start(ap, param)) {
return __builtin_va_start(ap, param);
}
pub inline fn va_end(ap: anytype) @TypeOf(__builtin_va_end(ap)) {
return __builtin_va_end(ap);
}
pub inline fn va_arg(ap: anytype, type_1: anytype) @TypeOf(__builtin_va_arg(ap, type_1)) {
return __builtin_va_arg(ap, type_1);
}
pub inline fn __va_copy(d: anytype, s: anytype) @TypeOf(__builtin_va_copy(d, s)) {
return __builtin_va_copy(d, s);
}
pub inline fn va_copy(dest: anytype, src: anytype) @TypeOf(__builtin_va_copy(dest, src)) {
return __builtin_va_copy(dest, src);
}
pub const __GNUC_VA_LIST = 1;
pub const __BIONIC__ = 1;
pub inline fn __BIONIC_CAST(_: anytype, _t: anytype, _v: anytype) @TypeOf((@import("std").meta.cast(_t, _v))) {
return (@import("std").meta.cast(_t, _v));
}
pub inline fn __BIONIC_ALIGN(__value: anytype, __alignment: anytype) @TypeOf((__value + (__alignment - 1)) & ~__alignment - 1) {
return (__value + (__alignment - 1)) & ~__alignment - 1;
}
pub inline fn __P(protos: anytype) @TypeOf(protos) {
return protos;
}
pub inline fn __CONCAT(x: anytype, y: anytype) @TypeOf(__CONCAT1(x, y)) {
return __CONCAT1(x, y);
}
pub inline fn ___CONCAT(x: anytype, y: anytype) @TypeOf(__CONCAT(x, y)) {
return __CONCAT(x, y);
}
pub inline fn ___STRING(x: anytype) @TypeOf(__STRING(x)) {
return __STRING(x);
}
pub const __always_inline = __attribute__(__always_inline__);
pub const __attribute_const__ = __attribute__(__const__);
pub const __attribute_pure__ = __attribute__(__pure__);
pub const __dead = __attribute__(__noreturn__);
pub const __noreturn = __attribute__(__noreturn__);
pub const __mallocfunc = __attribute__(__malloc__);
pub const __packed = __attribute__(__packed__);
pub const __returns_twice = __attribute__(__returns_twice__);
pub const __unused = __attribute__(__unused__);
pub const __used = __attribute__(__used__);
pub inline fn __printflike(x: anytype, y: anytype) @TypeOf(__attribute__(__format__(printf, x, y))) {
return __attribute__(__format__(printf, x, y));
}
pub inline fn __scanflike(x: anytype, y: anytype) @TypeOf(__attribute__(__format__(scanf, x, y))) {
return __attribute__(__format__(scanf, x, y));
}
pub inline fn __strftimelike(x: anytype) @TypeOf(__attribute__(__format__(strftime, x, 0))) {
return __attribute__(__format__(strftime, x, 0));
}
pub inline fn __predict_true(exp: anytype) @TypeOf(__builtin_expect(exp != 0, 1)) {
return __builtin_expect(exp != 0, 1);
}
pub inline fn __predict_false(exp: anytype) @TypeOf(__builtin_expect(exp != 0, 0)) {
return __builtin_expect(exp != 0, 0);
}
pub const __wur = __attribute__(__warn_unused_result__);
pub inline fn __errorattr(msg: anytype) @TypeOf(__attribute__(unavailable(msg))) {
return __attribute__(unavailable(msg));
}
pub inline fn __warnattr(msg: anytype) @TypeOf(__attribute__(deprecated(msg))) {
return __attribute__(deprecated(msg));
}
pub inline fn __warnattr_real(msg: anytype) @TypeOf(__attribute__(deprecated(msg))) {
return __attribute__(deprecated(msg));
}
pub inline fn __enable_if(cond: anytype, msg: anytype) @TypeOf(__attribute__(enable_if(cond, msg))) {
return __attribute__(enable_if(cond, msg));
}
pub inline fn __clang_error_if(cond: anytype, msg: anytype) @TypeOf(__attribute__(diagnose_if(cond, msg, "error"))) {
return __attribute__(diagnose_if(cond, msg, "error"));
}
pub inline fn __clang_warning_if(cond: anytype, msg: anytype) @TypeOf(__attribute__(diagnose_if(cond, msg, "warning"))) {
return __attribute__(diagnose_if(cond, msg, "warning"));
}
pub inline fn __RENAME_LDBL(_: anytype, rewrite_api_level: anytype, regular_api_level: anytype) @TypeOf(__INTRODUCED_IN(regular_api_level)) {
_ = rewrite_api_level;
return __INTRODUCED_IN(regular_api_level);
}
pub inline fn __RENAME_STAT64(_: anytype, rewrite_api_level: anytype, regular_api_level: anytype) @TypeOf(__INTRODUCED_IN(regular_api_level)) {
_ = rewrite_api_level;
return __INTRODUCED_IN(regular_api_level);
}
pub const __WORDSIZE = 64;
pub const __BIONIC_FORTIFY_UNKNOWN_SIZE = size_t - 1;
pub const __bos_level = 0;
pub inline fn __bosn(s: anytype, n: anytype) @TypeOf(__builtin_object_size(s, n)) {
return __builtin_object_size(s, n);
}
pub inline fn __bos(s: anytype) @TypeOf(__bosn(s, __bos_level)) {
return __bosn(s, __bos_level);
}
pub const __pass_object_size = __pass_object_size_n(__bos_level);
pub const __pass_object_size0 = __pass_object_size_n(0);
pub inline fn __bos_unevaluated_lt(bos_val: anytype, val: anytype) @TypeOf(bos_val != @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) and (bos_val < val))) {
return bos_val != @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) and (bos_val < val));
}
pub inline fn __bos_unevaluated_le(bos_val: anytype, val: anytype) @TypeOf(bos_val != @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) and (bos_val <= val))) {
return bos_val != @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) and (bos_val <= val));
}
pub inline fn __bos_dynamic_check_impl_and(bos_val: anytype, op: anytype, index: anytype, cond: anytype) @TypeOf(bos_val == @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) or ((__builtin_constant_p(index) != 0) and (bos_val ++ (op ++ @boolToInt((index != 0) and (cond != 0))) != 0)))) {
return bos_val == @boolToInt((__BIONIC_FORTIFY_UNKNOWN_SIZE != 0) or ((__builtin_constant_p(index) != 0) and (bos_val ++ (op ++ @boolToInt((index != 0) and (cond != 0))) != 0)));
}
pub inline fn __bos_dynamic_check_impl(bos_val: anytype, op: anytype, index: anytype) @TypeOf(__bos_dynamic_check_impl_and(bos_val, op, index, 1)) {
return __bos_dynamic_check_impl_and(bos_val, op, index, 1);
}
pub const __overloadable = __attribute__(overloadable);
pub const __LIBC_HIDDEN__ = __attribute__(visibility("hidden"));
pub const __LIBC32_LEGACY_PUBLIC__ = __attribute__(visibility("hidden"));
pub inline fn __size_mul_overflow(a: anytype, b: anytype, result: anytype) @TypeOf(__builtin_umull_overflow(a, b, result)) {
return __builtin_umull_overflow(a, b, result);
}
pub inline fn __unsafe_check_mul_overflow(x: anytype, y: anytype) @TypeOf(__SIZE_TYPE__ - (1 / @boolToInt(x < y))) {
return __SIZE_TYPE__ - (1 / @boolToInt(x < y));
}
pub const __VERSIONER_NO_GUARD = __attribute__(annotate("versioner_no_guard"));
pub const __ANDROID_API_FUTURE__ = 10000;
pub const __ANDROID_API__ = __ANDROID_API_FUTURE__;
pub const __ANDROID_API_G__ = 9;
pub const __ANDROID_API_I__ = 14;
pub const __ANDROID_API_J__ = 16;
pub const __ANDROID_API_J_MR1__ = 17;
pub const __ANDROID_API_J_MR2__ = 18;
pub const __ANDROID_API_K__ = 19;
pub const __ANDROID_API_L__ = 21;
pub const __ANDROID_API_L_MR1__ = 22;
pub const __ANDROID_API_M__ = 23;
pub const __ANDROID_API_N__ = 24;
pub const __ANDROID_API_N_MR1__ = 25;
pub const __ANDROID_API_O__ = 26;
pub const __ANDROID_API_O_MR1__ = 27;
pub const __ANDROID_API_P__ = 28;
pub const __ANDROID_API_Q__ = 29;
pub const __ANDROID_API_R__ = 30;
pub const __NDK_MAJOR__ = 21;
pub const __NDK_MINOR__ = 1;
pub const __NDK_BETA__ = 0;
pub const __NDK_BUILD__ = 6352462;
pub const __NDK_CANARY__ = 0;
pub const NULL = (@import("std").meta.cast(?*c_void, 0));
pub inline fn offsetof(t: anytype, d: anytype) @TypeOf(__builtin_offsetof(t, d)) {
return __builtin_offsetof(t, d);
}
pub const WCHAR_MAX = __WCHAR_MAX__;
pub const WCHAR_MIN = '\x00';
pub inline fn INT8_C(c: anytype) @TypeOf(c) {
return c;
}
pub inline fn INT_LEAST8_C(c: anytype) @TypeOf(INT8_C(c)) {
return INT8_C(c);
}
pub inline fn INT_FAST8_C(c: anytype) @TypeOf(INT8_C(c)) {
return INT8_C(c);
}
pub inline fn UINT8_C(c: anytype) @TypeOf(c) {
return c;
}
pub inline fn UINT_LEAST8_C(c: anytype) @TypeOf(UINT8_C(c)) {
return UINT8_C(c);
}
pub inline fn UINT_FAST8_C(c: anytype) @TypeOf(UINT8_C(c)) {
return UINT8_C(c);
}
pub inline fn INT16_C(c: anytype) @TypeOf(c) {
return c;
}
pub inline fn INT_LEAST16_C(c: anytype) @TypeOf(INT16_C(c)) {
return INT16_C(c);
}
pub inline fn INT_FAST16_C(c: anytype) @TypeOf(INT32_C(c)) {
return INT32_C(c);
}
pub inline fn UINT16_C(c: anytype) @TypeOf(c) {
return c;
}
pub inline fn UINT_LEAST16_C(c: anytype) @TypeOf(UINT16_C(c)) {
return UINT16_C(c);
}
pub inline fn UINT_FAST16_C(c: anytype) @TypeOf(UINT32_C(c)) {
return UINT32_C(c);
}
pub inline fn INT32_C(c: anytype) @TypeOf(c) {
return c;
}
pub inline fn INT_LEAST32_C(c: anytype) @TypeOf(INT32_C(c)) {
return INT32_C(c);
}
pub inline fn INT_FAST32_C(c: anytype) @TypeOf(INT32_C(c)) {
return INT32_C(c);
}
pub inline fn UINT_LEAST32_C(c: anytype) @TypeOf(UINT32_C(c)) {
return UINT32_C(c);
}
pub inline fn UINT_FAST32_C(c: anytype) @TypeOf(UINT32_C(c)) {
return UINT32_C(c);
}
pub inline fn INT_LEAST64_C(c: anytype) @TypeOf(INT64_C(c)) {
return INT64_C(c);
}
pub inline fn INT_FAST64_C(c: anytype) @TypeOf(INT64_C(c)) {
return INT64_C(c);
}
pub inline fn UINT_LEAST64_C(c: anytype) @TypeOf(UINT64_C(c)) {
return UINT64_C(c);
}
pub inline fn UINT_FAST64_C(c: anytype) @TypeOf(UINT64_C(c)) {
return UINT64_C(c);
}
pub inline fn INTMAX_C(c: anytype) @TypeOf(INT64_C(c)) {
return INT64_C(c);
}
pub inline fn UINTMAX_C(c: anytype) @TypeOf(UINT64_C(c)) {
return UINT64_C(c);
}
pub inline fn INTPTR_C(c: anytype) @TypeOf(INT64_C(c)) {
return INT64_C(c);
}
pub inline fn UINTPTR_C(c: anytype) @TypeOf(UINT64_C(c)) {
return UINT64_C(c);
}
pub inline fn PTRDIFF_C(c: anytype) @TypeOf(INT64_C(c)) {
return INT64_C(c);
}
pub const INT8_MIN = -128;
pub const INT8_MAX = 127;
pub const INT_LEAST8_MIN = INT8_MIN;
pub const INT_LEAST8_MAX = INT8_MAX;
pub const INT_FAST8_MIN = INT8_MIN;
pub const INT_FAST8_MAX = INT8_MAX;
pub const UINT8_MAX = 255;
pub const UINT_LEAST8_MAX = UINT8_MAX;
pub const UINT_FAST8_MAX = UINT8_MAX;
pub const INT16_MIN = -32768;
pub const INT16_MAX = 32767;
pub const INT_LEAST16_MIN = INT16_MIN;
pub const INT_LEAST16_MAX = INT16_MAX;
pub const INT_FAST16_MIN = INT32_MIN;
pub const INT_FAST16_MAX = INT32_MAX;
pub const UINT16_MAX = 65535;
pub const UINT_LEAST16_MAX = UINT16_MAX;
pub const UINT_FAST16_MAX = UINT32_MAX;
pub const INT32_MIN = -2147483647 - 1;
pub const INT32_MAX = 2147483647;
pub const INT_LEAST32_MIN = INT32_MIN;
pub const INT_LEAST32_MAX = INT32_MAX;
pub const INT_FAST32_MIN = INT32_MIN;
pub const INT_FAST32_MAX = INT32_MAX;
pub const UINT32_MAX = @as(c_uint, 4294967295);
pub const UINT_LEAST32_MAX = UINT32_MAX;
pub const UINT_FAST32_MAX = UINT32_MAX;
pub const INT64_MIN = INT64_C(-9223372036854775807) - 1;
pub const INT64_MAX = INT64_C(9223372036854775807);
pub const INT_LEAST64_MIN = INT64_MIN;
pub const INT_LEAST64_MAX = INT64_MAX;
pub const INT_FAST64_MIN = INT64_MIN;
pub const INT_FAST64_MAX = INT64_MAX;
pub const UINT64_MAX = UINT64_C(18446744073709551615);
pub const UINT_LEAST64_MAX = UINT64_MAX;
pub const UINT_FAST64_MAX = UINT64_MAX;
pub const INTMAX_MIN = INT64_MIN;
pub const INTMAX_MAX = INT64_MAX;
pub const UINTMAX_MAX = UINT64_MAX;
pub const SIG_ATOMIC_MAX = INT32_MAX;
pub const SIG_ATOMIC_MIN = INT32_MIN;
pub const WINT_MAX = UINT32_MAX;
pub const WINT_MIN = 0;
pub const INTPTR_MIN = INT64_MIN;
pub const INTPTR_MAX = INT64_MAX;
pub const UINTPTR_MAX = UINT64_MAX;
pub const PTRDIFF_MIN = INT64_MIN;
pub const PTRDIFF_MAX = INT64_MAX;
pub const SIZE_MAX = UINT64_MAX;
pub const __BITS_PER_LONG = 64;
pub const __FD_SETSIZE = 1024;
pub const __bitwise = __bitwise__;
pub const __aligned_u64 = __u64 ++ __attribute__(aligned(8));
pub const __aligned_be64 = __be64 ++ __attribute__(aligned(8));
pub const __aligned_le64 = __le64 ++ __attribute__(aligned(8));
pub const JNIEXPORT = __attribute__(visibility("default"));
pub const JNI_FALSE = 0;
pub const JNI_TRUE = 1;
pub const JNI_VERSION_1_1 = 0x00010001;
pub const JNI_VERSION_1_2 = 0x00010002;
pub const JNI_VERSION_1_4 = 0x00010004;
pub const JNI_VERSION_1_6 = 0x00010006;
pub const JNI_OK = 0;
pub const JNI_ERR = -1;
pub const JNI_EDETACHED = -2;
pub const JNI_EVERSION = -3;
pub const JNI_ENOMEM = -4;
pub const JNI_EEXIST = -5;
pub const JNI_EINVAL = -6;
pub const JNI_COMMIT = 1;
pub const JNI_ABORT = 2;
pub const AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT = 8;
pub const __PRI_64_prefix = "l";
pub const __PRI_PTR_prefix = "l";
pub const __PRI_FAST_prefix = __PRI_PTR_prefix;
pub const PRId8 = "d";
pub const PRId16 = "d";
pub const PRId32 = "d";
pub const PRId64 = __PRI_64_prefix ++ "d";
pub const PRIdLEAST8 = "d";
pub const PRIdLEAST16 = "d";
pub const PRIdLEAST32 = "d";
pub const PRIdLEAST64 = __PRI_64_prefix ++ "d";
pub const PRIdFAST8 = "d";
pub const PRIdFAST16 = __PRI_FAST_prefix ++ "d";
pub const PRIdFAST32 = __PRI_FAST_prefix ++ "d";
pub const PRIdFAST64 = __PRI_64_prefix ++ "d";
pub const PRIdMAX = "jd";
pub const PRIdPTR = __PRI_PTR_prefix ++ "d";
pub const PRIi8 = "i";
pub const PRIi16 = "i";
pub const PRIi32 = "i";
pub const PRIi64 = __PRI_64_prefix ++ "i";
pub const PRIiLEAST8 = "i";
pub const PRIiLEAST16 = "i";
pub const PRIiLEAST32 = "i";
pub const PRIiLEAST64 = __PRI_64_prefix ++ "i";
pub const PRIiFAST8 = "i";
pub const PRIiFAST16 = __PRI_FAST_prefix ++ "i";
pub const PRIiFAST32 = __PRI_FAST_prefix ++ "i";
pub const PRIiFAST64 = __PRI_64_prefix ++ "i";
pub const PRIiMAX = "ji";
pub const PRIiPTR = __PRI_PTR_prefix ++ "i";
pub const PRIo8 = "o";
pub const PRIo16 = "o";
pub const PRIo32 = "o";
pub const PRIo64 = __PRI_64_prefix ++ "o";
pub const PRIoLEAST8 = "o";
pub const PRIoLEAST16 = "o";
pub const PRIoLEAST32 = "o";
pub const PRIoLEAST64 = __PRI_64_prefix ++ "o";
pub const PRIoFAST8 = "o";
pub const PRIoFAST16 = __PRI_FAST_prefix ++ "o";
pub const PRIoFAST32 = __PRI_FAST_prefix ++ "o";
pub const PRIoFAST64 = __PRI_64_prefix ++ "o";
pub const PRIoMAX = "jo";
pub const PRIoPTR = __PRI_PTR_prefix ++ "o";
pub const PRIu8 = "u";
pub const PRIu16 = "u";
pub const PRIu32 = "u";
pub const PRIu64 = __PRI_64_prefix ++ "u";
pub const PRIuLEAST8 = "u";
pub const PRIuLEAST16 = "u";
pub const PRIuLEAST32 = "u";
pub const PRIuLEAST64 = __PRI_64_prefix ++ "u";
pub const PRIuFAST8 = "u";
pub const PRIuFAST16 = __PRI_FAST_prefix ++ "u";
pub const PRIuFAST32 = __PRI_FAST_prefix ++ "u";
pub const PRIuFAST64 = __PRI_64_prefix ++ "u";
pub const PRIuMAX = "ju";
pub const PRIuPTR = __PRI_PTR_prefix ++ "u";
pub const PRIx8 = "x";
pub const PRIx16 = "x";
pub const PRIx32 = "x";
pub const PRIx64 = __PRI_64_prefix ++ "x";
pub const PRIxLEAST8 = "x";
pub const PRIxLEAST16 = "x";
pub const PRIxLEAST32 = "x";
pub const PRIxLEAST64 = __PRI_64_prefix ++ "x";
pub const PRIxFAST8 = "x";
pub const PRIxFAST16 = __PRI_FAST_prefix ++ "x";
pub const PRIxFAST32 = __PRI_FAST_prefix ++ "x";
pub const PRIxFAST64 = __PRI_64_prefix ++ "x";
pub const PRIxMAX = "jx";
pub const PRIxPTR = __PRI_PTR_prefix ++ "x";
pub const PRIX8 = "X";
pub const PRIX16 = "X";
pub const PRIX32 = "X";
pub const PRIX64 = __PRI_64_prefix ++ "X";
pub const PRIXLEAST8 = "X";
pub const PRIXLEAST16 = "X";
pub const PRIXLEAST32 = "X";
pub const PRIXLEAST64 = __PRI_64_prefix ++ "X";
pub const PRIXFAST8 = "X";
pub const PRIXFAST16 = __PRI_FAST_prefix ++ "X";
pub const PRIXFAST32 = __PRI_FAST_prefix ++ "X";
pub const PRIXFAST64 = __PRI_64_prefix ++ "X";
pub const PRIXMAX = "jX";
pub const PRIXPTR = __PRI_PTR_prefix ++ "X";
pub const SCNd8 = "hhd";
pub const SCNd16 = "hd";
pub const SCNd32 = "d";
pub const SCNd64 = __PRI_64_prefix ++ "d";
pub const SCNdLEAST8 = "hhd";
pub const SCNdLEAST16 = "hd";
pub const SCNdLEAST32 = "d";
pub const SCNdLEAST64 = __PRI_64_prefix ++ "d";
pub const SCNdFAST8 = "hhd";
pub const SCNdFAST16 = __PRI_FAST_prefix ++ "d";
pub const SCNdFAST32 = __PRI_FAST_prefix ++ "d";
pub const SCNdFAST64 = __PRI_64_prefix ++ "d";
pub const SCNdMAX = "jd";
pub const SCNdPTR = __PRI_PTR_prefix ++ "d";
pub const SCNi8 = "hhi";
pub const SCNi16 = "hi";
pub const SCNi32 = "i";
pub const SCNi64 = __PRI_64_prefix ++ "i";
pub const SCNiLEAST8 = "hhi";
pub const SCNiLEAST16 = "hi";
pub const SCNiLEAST32 = "i";
pub const SCNiLEAST64 = __PRI_64_prefix ++ "i";
pub const SCNiFAST8 = "hhi";
pub const SCNiFAST16 = __PRI_FAST_prefix ++ "i";
pub const SCNiFAST32 = __PRI_FAST_prefix ++ "i";
pub const SCNiFAST64 = __PRI_64_prefix ++ "i";
pub const SCNiMAX = "ji";
pub const SCNiPTR = __PRI_PTR_prefix ++ "i";
pub const SCNo8 = "hho";
pub const SCNo16 = "ho";
pub const SCNo32 = "o";
pub const SCNo64 = __PRI_64_prefix ++ "o";
pub const SCNoLEAST8 = "hho";
pub const SCNoLEAST16 = "ho";
pub const SCNoLEAST32 = "o";
pub const SCNoLEAST64 = __PRI_64_prefix ++ "o";
pub const SCNoFAST8 = "hho";
pub const SCNoFAST16 = __PRI_FAST_prefix ++ "o";
pub const SCNoFAST32 = __PRI_FAST_prefix ++ "o";
pub const SCNoFAST64 = __PRI_64_prefix ++ "o";
pub const SCNoMAX = "jo";
pub const SCNoPTR = __PRI_PTR_prefix ++ "o";
pub const SCNu8 = "hhu";
pub const SCNu16 = "hu";
pub const SCNu32 = "u";
pub const SCNu64 = __PRI_64_prefix ++ "u";
pub const SCNuLEAST8 = "hhu";
pub const SCNuLEAST16 = "hu";
pub const SCNuLEAST32 = "u";
pub const SCNuLEAST64 = __PRI_64_prefix ++ "u";
pub const SCNuFAST8 = "hhu";
pub const SCNuFAST16 = __PRI_FAST_prefix ++ "u";
pub const SCNuFAST32 = __PRI_FAST_prefix ++ "u";
pub const SCNuFAST64 = __PRI_64_prefix ++ "u";
pub const SCNuMAX = "ju";
pub const SCNuPTR = __PRI_PTR_prefix ++ "u";
pub const SCNx8 = "hhx";
pub const SCNx16 = "hx";
pub const SCNx32 = "x";
pub const SCNx64 = __PRI_64_prefix ++ "x";
pub const SCNxLEAST8 = "hhx";
pub const SCNxLEAST16 = "hx";
pub const SCNxLEAST32 = "x";
pub const SCNxLEAST64 = __PRI_64_prefix ++ "x";
pub const SCNxFAST8 = "hhx";
pub const SCNxFAST16 = __PRI_FAST_prefix ++ "x";
pub const SCNxFAST32 = __PRI_FAST_prefix ++ "x";
pub const SCNxFAST64 = __PRI_64_prefix ++ "x";
pub const SCNxMAX = "jx";
pub const SCNxPTR = __PRI_PTR_prefix ++ "x";
pub const log_id = enum_log_id;
pub const _jfieldID = struct__jfieldID;
pub const _jmethodID = struct__jmethodID;
pub const JNIInvokeInterface = struct_JNIInvokeInterface;
pub const _JNIEnv = struct__JNIEnv;
pub const _JavaVM = struct__JavaVM;
pub const ADataSpace = enum_ADataSpace;
pub const AHardwareBuffer_Format = enum_AHardwareBuffer_Format;
pub const AHardwareBuffer_UsageFlags = enum_AHardwareBuffer_UsageFlags;
pub const ANativeWindow_LegacyFormat = enum_ANativeWindow_LegacyFormat;
pub const ANativeWindowTransform = enum_ANativeWindowTransform;
pub extern fn __system_property_get(name: [*:0]const u8, value: [*]u8) callconv(.C) c_int; | src/android-bind.zig |
pub const NDF_ERROR_START = @as(u32, 63744);
pub const NDF_E_LENGTH_EXCEEDED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895616));
pub const NDF_E_NOHELPERCLASS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895615));
pub const NDF_E_CANCELLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895614));
pub const NDF_E_DISABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895612));
pub const NDF_E_BAD_PARAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895611));
pub const NDF_E_VALIDATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895610));
pub const NDF_E_UNKNOWN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895609));
pub const NDF_E_PROBLEM_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2146895608));
pub const RF_WORKAROUND = @as(u32, 536870912);
pub const RF_USER_ACTION = @as(u32, 268435456);
pub const RF_USER_CONFIRMATION = @as(u32, 134217728);
pub const RF_INFORMATION_ONLY = @as(u32, 33554432);
pub const RF_UI_ONLY = @as(u32, 16777216);
pub const RF_SHOW_EVENTS = @as(u32, 8388608);
pub const RF_VALIDATE_HELPTOPIC = @as(u32, 4194304);
pub const RF_REPRO = @as(u32, 2097152);
pub const RF_CONTACT_ADMIN = @as(u32, 131072);
pub const RF_RESERVED = @as(u32, 1073741824);
pub const RF_RESERVED_CA = @as(u32, 2147483648);
pub const RF_RESERVED_LNI = @as(u32, 65536);
pub const RCF_ISLEAF = @as(u32, 1);
pub const RCF_ISCONFIRMED = @as(u32, 2);
pub const RCF_ISTHIRDPARTY = @as(u32, 4);
pub const DF_IMPERSONATION = @as(u32, 2147483648);
pub const DF_TRACELESS = @as(u32, 1073741824);
pub const NDF_INBOUND_FLAG_EDGETRAVERSAL = @as(u32, 1);
pub const NDF_INBOUND_FLAG_HEALTHCHECK = @as(u32, 2);
pub const NDF_ADD_CAPTURE_TRACE = @as(u32, 1);
pub const NDF_APPLY_INCLUSION_LIST_FILTER = @as(u32, 2);
//--------------------------------------------------------------------------------
// Section: Types (25)
//--------------------------------------------------------------------------------
pub const ATTRIBUTE_TYPE = enum(i32) {
INVALID = 0,
BOOLEAN = 1,
INT8 = 2,
UINT8 = 3,
INT16 = 4,
UINT16 = 5,
INT32 = 6,
UINT32 = 7,
INT64 = 8,
UINT64 = 9,
STRING = 10,
GUID = 11,
LIFE_TIME = 12,
SOCKADDR = 13,
OCTET_STRING = 14,
};
pub const AT_INVALID = ATTRIBUTE_TYPE.INVALID;
pub const AT_BOOLEAN = ATTRIBUTE_TYPE.BOOLEAN;
pub const AT_INT8 = ATTRIBUTE_TYPE.INT8;
pub const AT_UINT8 = ATTRIBUTE_TYPE.UINT8;
pub const AT_INT16 = ATTRIBUTE_TYPE.INT16;
pub const AT_UINT16 = ATTRIBUTE_TYPE.UINT16;
pub const AT_INT32 = ATTRIBUTE_TYPE.INT32;
pub const AT_UINT32 = ATTRIBUTE_TYPE.UINT32;
pub const AT_INT64 = ATTRIBUTE_TYPE.INT64;
pub const AT_UINT64 = ATTRIBUTE_TYPE.UINT64;
pub const AT_STRING = ATTRIBUTE_TYPE.STRING;
pub const AT_GUID = ATTRIBUTE_TYPE.GUID;
pub const AT_LIFE_TIME = ATTRIBUTE_TYPE.LIFE_TIME;
pub const AT_SOCKADDR = ATTRIBUTE_TYPE.SOCKADDR;
pub const AT_OCTET_STRING = ATTRIBUTE_TYPE.OCTET_STRING;
pub const OCTET_STRING = extern struct {
dwLength: u32,
lpValue: ?*u8,
};
pub const LIFE_TIME = extern struct {
startTime: FILETIME,
endTime: FILETIME,
};
pub const DIAG_SOCKADDR = extern struct {
family: u16,
data: [126]CHAR,
};
pub const HELPER_ATTRIBUTE = extern struct {
pwszName: ?PWSTR,
type: ATTRIBUTE_TYPE,
Anonymous: extern union {
Boolean: BOOL,
Char: u8,
Byte: u8,
Short: i16,
Word: u16,
Int: i32,
DWord: u32,
Int64: i64,
UInt64: u64,
PWStr: ?PWSTR,
Guid: Guid,
LifeTime: LIFE_TIME,
Address: DIAG_SOCKADDR,
OctetString: OCTET_STRING,
},
};
pub const REPAIR_SCOPE = enum(i32) {
SYSTEM = 0,
USER = 1,
APPLICATION = 2,
PROCESS = 3,
};
pub const RS_SYSTEM = REPAIR_SCOPE.SYSTEM;
pub const RS_USER = REPAIR_SCOPE.USER;
pub const RS_APPLICATION = REPAIR_SCOPE.APPLICATION;
pub const RS_PROCESS = REPAIR_SCOPE.PROCESS;
pub const REPAIR_RISK = enum(i32) {
NOROLLBACK = 0,
ROLLBACK = 1,
NORISK = 2,
};
pub const RR_NOROLLBACK = REPAIR_RISK.NOROLLBACK;
pub const RR_ROLLBACK = REPAIR_RISK.ROLLBACK;
pub const RR_NORISK = REPAIR_RISK.NORISK;
pub const UI_INFO_TYPE = enum(i32) {
INVALID = 0,
NONE = 1,
SHELL_COMMAND = 2,
HELP_PANE = 3,
DUI = 4,
};
pub const UIT_INVALID = UI_INFO_TYPE.INVALID;
pub const UIT_NONE = UI_INFO_TYPE.NONE;
pub const UIT_SHELL_COMMAND = UI_INFO_TYPE.SHELL_COMMAND;
pub const UIT_HELP_PANE = UI_INFO_TYPE.HELP_PANE;
pub const UIT_DUI = UI_INFO_TYPE.DUI;
pub const ShellCommandInfo = extern struct {
pwszOperation: ?PWSTR,
pwszFile: ?PWSTR,
pwszParameters: ?PWSTR,
pwszDirectory: ?PWSTR,
nShowCmd: u32,
};
pub const UiInfo = extern struct {
type: UI_INFO_TYPE,
Anonymous: extern union {
pwzNull: ?PWSTR,
ShellInfo: ShellCommandInfo,
pwzHelpUrl: ?PWSTR,
pwzDui: ?PWSTR,
},
};
pub const RepairInfo = extern struct {
guid: Guid,
pwszClassName: ?PWSTR,
pwszDescription: ?PWSTR,
sidType: u32,
cost: i32,
flags: u32,
scope: REPAIR_SCOPE,
risk: REPAIR_RISK,
UiInfo: UiInfo,
rootCauseIndex: i32,
};
pub const RepairInfoEx = extern struct {
repair: RepairInfo,
repairRank: u16,
};
pub const RootCauseInfo = extern struct {
pwszDescription: ?PWSTR,
rootCauseID: Guid,
rootCauseFlags: u32,
networkInterfaceID: Guid,
pRepairs: ?*RepairInfoEx,
repairCount: u16,
};
pub const DIAGNOSIS_STATUS = enum(i32) {
NOT_IMPLEMENTED = 0,
CONFIRMED = 1,
REJECTED = 2,
INDETERMINATE = 3,
DEFERRED = 4,
PASSTHROUGH = 5,
};
pub const DS_NOT_IMPLEMENTED = DIAGNOSIS_STATUS.NOT_IMPLEMENTED;
pub const DS_CONFIRMED = DIAGNOSIS_STATUS.CONFIRMED;
pub const DS_REJECTED = DIAGNOSIS_STATUS.REJECTED;
pub const DS_INDETERMINATE = DIAGNOSIS_STATUS.INDETERMINATE;
pub const DS_DEFERRED = DIAGNOSIS_STATUS.DEFERRED;
pub const DS_PASSTHROUGH = DIAGNOSIS_STATUS.PASSTHROUGH;
pub const REPAIR_STATUS = enum(i32) {
NOT_IMPLEMENTED = 0,
REPAIRED = 1,
UNREPAIRED = 2,
DEFERRED = 3,
USER_ACTION = 4,
};
pub const RS_NOT_IMPLEMENTED = REPAIR_STATUS.NOT_IMPLEMENTED;
pub const RS_REPAIRED = REPAIR_STATUS.REPAIRED;
pub const RS_UNREPAIRED = REPAIR_STATUS.UNREPAIRED;
pub const RS_DEFERRED = REPAIR_STATUS.DEFERRED;
pub const RS_USER_ACTION = REPAIR_STATUS.USER_ACTION;
pub const PROBLEM_TYPE = enum(i32) {
INVALID = 0,
LOW_HEALTH = 1,
LOWER_HEALTH = 2,
DOWN_STREAM_HEALTH = 4,
HIGH_UTILIZATION = 8,
HIGHER_UTILIZATION = 16,
UP_STREAM_UTILIZATION = 32,
};
pub const PT_INVALID = PROBLEM_TYPE.INVALID;
pub const PT_LOW_HEALTH = PROBLEM_TYPE.LOW_HEALTH;
pub const PT_LOWER_HEALTH = PROBLEM_TYPE.LOWER_HEALTH;
pub const PT_DOWN_STREAM_HEALTH = PROBLEM_TYPE.DOWN_STREAM_HEALTH;
pub const PT_HIGH_UTILIZATION = PROBLEM_TYPE.HIGH_UTILIZATION;
pub const PT_HIGHER_UTILIZATION = PROBLEM_TYPE.HIGHER_UTILIZATION;
pub const PT_UP_STREAM_UTILIZATION = PROBLEM_TYPE.UP_STREAM_UTILIZATION;
pub const HYPOTHESIS = extern struct {
pwszClassName: ?PWSTR,
pwszDescription: ?PWSTR,
celt: u32,
rgAttributes: ?*HELPER_ATTRIBUTE,
};
pub const HelperAttributeInfo = extern struct {
pwszName: ?PWSTR,
type: ATTRIBUTE_TYPE,
};
pub const DiagnosticsInfo = extern struct {
cost: i32,
flags: u32,
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetDiagHelper_Value = @import("../zig.zig").Guid.initString("c0b35746-ebf5-11d8-bbe9-505054503030");
pub const IID_INetDiagHelper = &IID_INetDiagHelper_Value;
pub const INetDiagHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Initialize: fn(
self: *const INetDiagHelper,
celt: u32,
rgAttributes: [*]HELPER_ATTRIBUTE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDiagnosticsInfo: fn(
self: *const INetDiagHelper,
ppInfo: ?*?*DiagnosticsInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeyAttributes: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgAttributes: [*]?*HELPER_ATTRIBUTE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LowHealth: fn(
self: *const INetDiagHelper,
pwszInstanceDescription: ?[*:0]const u16,
ppwszDescription: ?*?PWSTR,
pDeferredTime: ?*i32,
pStatus: ?*DIAGNOSIS_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HighUtilization: fn(
self: *const INetDiagHelper,
pwszInstanceDescription: ?[*:0]const u16,
ppwszDescription: ?*?PWSTR,
pDeferredTime: ?*i32,
pStatus: ?*DIAGNOSIS_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLowerHypotheses: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgHypotheses: [*]?*HYPOTHESIS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDownStreamHypotheses: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgHypotheses: [*]?*HYPOTHESIS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHigherHypotheses: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgHypotheses: [*]?*HYPOTHESIS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUpStreamHypotheses: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgHypotheses: [*]?*HYPOTHESIS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Repair: fn(
self: *const INetDiagHelper,
pInfo: ?*RepairInfo,
pDeferredTime: ?*i32,
pStatus: ?*REPAIR_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Validate: fn(
self: *const INetDiagHelper,
problem: PROBLEM_TYPE,
pDeferredTime: ?*i32,
pStatus: ?*REPAIR_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRepairInfo: fn(
self: *const INetDiagHelper,
problem: PROBLEM_TYPE,
pcelt: ?*u32,
ppInfo: [*]?*RepairInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLifeTime: fn(
self: *const INetDiagHelper,
pLifeTime: ?*LIFE_TIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLifeTime: fn(
self: *const INetDiagHelper,
lifeTime: LIFE_TIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCacheTime: fn(
self: *const INetDiagHelper,
pCacheTime: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributes: fn(
self: *const INetDiagHelper,
pcelt: ?*u32,
pprgAttributes: [*]?*HELPER_ATTRIBUTE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cancel: fn(
self: *const INetDiagHelper,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cleanup: fn(
self: *const INetDiagHelper,
) 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 INetDiagHelper_Initialize(self: *const T, celt: u32, rgAttributes: [*]HELPER_ATTRIBUTE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).Initialize(@ptrCast(*const INetDiagHelper, self), celt, rgAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetDiagnosticsInfo(self: *const T, ppInfo: ?*?*DiagnosticsInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetDiagnosticsInfo(@ptrCast(*const INetDiagHelper, self), ppInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetKeyAttributes(self: *const T, pcelt: ?*u32, pprgAttributes: [*]?*HELPER_ATTRIBUTE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetKeyAttributes(@ptrCast(*const INetDiagHelper, self), pcelt, pprgAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_LowHealth(self: *const T, pwszInstanceDescription: ?[*:0]const u16, ppwszDescription: ?*?PWSTR, pDeferredTime: ?*i32, pStatus: ?*DIAGNOSIS_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).LowHealth(@ptrCast(*const INetDiagHelper, self), pwszInstanceDescription, ppwszDescription, pDeferredTime, pStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_HighUtilization(self: *const T, pwszInstanceDescription: ?[*:0]const u16, ppwszDescription: ?*?PWSTR, pDeferredTime: ?*i32, pStatus: ?*DIAGNOSIS_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).HighUtilization(@ptrCast(*const INetDiagHelper, self), pwszInstanceDescription, ppwszDescription, pDeferredTime, pStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetLowerHypotheses(self: *const T, pcelt: ?*u32, pprgHypotheses: [*]?*HYPOTHESIS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetLowerHypotheses(@ptrCast(*const INetDiagHelper, self), pcelt, pprgHypotheses);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetDownStreamHypotheses(self: *const T, pcelt: ?*u32, pprgHypotheses: [*]?*HYPOTHESIS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetDownStreamHypotheses(@ptrCast(*const INetDiagHelper, self), pcelt, pprgHypotheses);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetHigherHypotheses(self: *const T, pcelt: ?*u32, pprgHypotheses: [*]?*HYPOTHESIS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetHigherHypotheses(@ptrCast(*const INetDiagHelper, self), pcelt, pprgHypotheses);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetUpStreamHypotheses(self: *const T, pcelt: ?*u32, pprgHypotheses: [*]?*HYPOTHESIS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetUpStreamHypotheses(@ptrCast(*const INetDiagHelper, self), pcelt, pprgHypotheses);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_Repair(self: *const T, pInfo: ?*RepairInfo, pDeferredTime: ?*i32, pStatus: ?*REPAIR_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).Repair(@ptrCast(*const INetDiagHelper, self), pInfo, pDeferredTime, pStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_Validate(self: *const T, problem: PROBLEM_TYPE, pDeferredTime: ?*i32, pStatus: ?*REPAIR_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).Validate(@ptrCast(*const INetDiagHelper, self), problem, pDeferredTime, pStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetRepairInfo(self: *const T, problem: PROBLEM_TYPE, pcelt: ?*u32, ppInfo: [*]?*RepairInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetRepairInfo(@ptrCast(*const INetDiagHelper, self), problem, pcelt, ppInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetLifeTime(self: *const T, pLifeTime: ?*LIFE_TIME) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetLifeTime(@ptrCast(*const INetDiagHelper, self), pLifeTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_SetLifeTime(self: *const T, lifeTime: LIFE_TIME) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).SetLifeTime(@ptrCast(*const INetDiagHelper, self), lifeTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetCacheTime(self: *const T, pCacheTime: ?*FILETIME) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetCacheTime(@ptrCast(*const INetDiagHelper, self), pCacheTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_GetAttributes(self: *const T, pcelt: ?*u32, pprgAttributes: [*]?*HELPER_ATTRIBUTE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).GetAttributes(@ptrCast(*const INetDiagHelper, self), pcelt, pprgAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_Cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).Cancel(@ptrCast(*const INetDiagHelper, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelper_Cleanup(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelper.VTable, self.vtable).Cleanup(@ptrCast(*const INetDiagHelper, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const HypothesisResult = extern struct {
hypothesis: HYPOTHESIS,
pathStatus: DIAGNOSIS_STATUS,
};
// TODO: this type is limited to platform 'windows6.1'
const IID_INetDiagHelperUtilFactory_Value = @import("../zig.zig").Guid.initString("104613fb-bc57-4178-95ba-88809698354a");
pub const IID_INetDiagHelperUtilFactory = &IID_INetDiagHelperUtilFactory_Value;
pub const INetDiagHelperUtilFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateUtilityInstance: fn(
self: *const INetDiagHelperUtilFactory,
riid: ?*const Guid,
ppvObject: ?*?*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 INetDiagHelperUtilFactory_CreateUtilityInstance(self: *const T, riid: ?*const Guid, ppvObject: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelperUtilFactory.VTable, self.vtable).CreateUtilityInstance(@ptrCast(*const INetDiagHelperUtilFactory, self), riid, ppvObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_INetDiagHelperEx_Value = @import("../zig.zig").Guid.initString("972dab4d-e4e3-4fc6-ae54-5f65ccde4a15");
pub const IID_INetDiagHelperEx = &IID_INetDiagHelperEx_Value;
pub const INetDiagHelperEx = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ReconfirmLowHealth: fn(
self: *const INetDiagHelperEx,
celt: u32,
pResults: [*]HypothesisResult,
ppwszUpdatedDescription: ?*?PWSTR,
pUpdatedStatus: ?*DIAGNOSIS_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUtilities: fn(
self: *const INetDiagHelperEx,
pUtilities: ?*INetDiagHelperUtilFactory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReproduceFailure: fn(
self: *const INetDiagHelperEx,
) 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 INetDiagHelperEx_ReconfirmLowHealth(self: *const T, celt: u32, pResults: [*]HypothesisResult, ppwszUpdatedDescription: ?*?PWSTR, pUpdatedStatus: ?*DIAGNOSIS_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelperEx.VTable, self.vtable).ReconfirmLowHealth(@ptrCast(*const INetDiagHelperEx, self), celt, pResults, ppwszUpdatedDescription, pUpdatedStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelperEx_SetUtilities(self: *const T, pUtilities: ?*INetDiagHelperUtilFactory) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelperEx.VTable, self.vtable).SetUtilities(@ptrCast(*const INetDiagHelperEx, self), pUtilities);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn INetDiagHelperEx_ReproduceFailure(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelperEx.VTable, self.vtable).ReproduceFailure(@ptrCast(*const INetDiagHelperEx, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_INetDiagHelperInfo_Value = @import("../zig.zig").Guid.initString("c0b35747-ebf5-11d8-bbe9-505054503030");
pub const IID_INetDiagHelperInfo = &IID_INetDiagHelperInfo_Value;
pub const INetDiagHelperInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAttributeInfo: fn(
self: *const INetDiagHelperInfo,
pcelt: ?*u32,
pprgAttributeInfos: [*]?*HelperAttributeInfo,
) 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 INetDiagHelperInfo_GetAttributeInfo(self: *const T, pcelt: ?*u32, pprgAttributeInfos: [*]?*HelperAttributeInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagHelperInfo.VTable, self.vtable).GetAttributeInfo(@ptrCast(*const INetDiagHelperInfo, self), pcelt, pprgAttributeInfos);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_INetDiagExtensibleHelper_Value = @import("../zig.zig").Guid.initString("c0b35748-ebf5-11d8-bbe9-505054503030");
pub const IID_INetDiagExtensibleHelper = &IID_INetDiagExtensibleHelper_Value;
pub const INetDiagExtensibleHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ResolveAttributes: fn(
self: *const INetDiagExtensibleHelper,
celt: u32,
rgKeyAttributes: [*]HELPER_ATTRIBUTE,
pcelt: ?*u32,
prgMatchValues: [*]?*HELPER_ATTRIBUTE,
) 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 INetDiagExtensibleHelper_ResolveAttributes(self: *const T, celt: u32, rgKeyAttributes: [*]HELPER_ATTRIBUTE, pcelt: ?*u32, prgMatchValues: [*]?*HELPER_ATTRIBUTE) callconv(.Inline) HRESULT {
return @ptrCast(*const INetDiagExtensibleHelper.VTable, self.vtable).ResolveAttributes(@ptrCast(*const INetDiagExtensibleHelper, self), celt, rgKeyAttributes, pcelt, prgMatchValues);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (16)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateIncident(
helperClassName: ?[*:0]const u16,
celt: u32,
attributes: [*]HELPER_ATTRIBUTE,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateWinSockIncident(
sock: ?SOCKET,
host: ?[*:0]const u16,
port: u16,
appId: ?[*:0]const u16,
userId: ?*SID,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateWebIncident(
url: ?[*:0]const u16,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateWebIncidentEx(
url: ?[*:0]const u16,
useWinHTTP: BOOL,
moduleName: ?PWSTR,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateSharingIncident(
UNCPath: ?[*:0]const u16,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateDNSIncident(
hostname: ?[*:0]const u16,
queryType: u16,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCreateConnectivityIncident(
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "NDFAPI" fn NdfCreateNetConnectionIncident(
handle: ?*?*anyopaque,
id: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfCreatePnrpIncident(
cloudname: ?[*:0]const u16,
peername: ?[*:0]const u16,
diagnosePublish: BOOL,
appId: ?[*:0]const u16,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfCreateGroupingIncident(
CloudName: ?[*:0]const u16,
GroupName: ?[*:0]const u16,
Identity: ?[*:0]const u16,
Invitation: ?[*:0]const u16,
Addresses: ?*SOCKET_ADDRESS_LIST,
appId: ?[*:0]const u16,
handle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfExecuteDiagnosis(
handle: ?*anyopaque,
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "NDFAPI" fn NdfCloseIncident(
handle: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfDiagnoseIncident(
Handle: ?*anyopaque,
RootCauseCount: ?*u32,
RootCauses: ?*?*RootCauseInfo,
dwWait: u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfRepairIncident(
Handle: ?*anyopaque,
RepairEx: ?*RepairInfoEx,
dwWait: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfCancelIncident(
Handle: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.1'
pub extern "NDFAPI" fn NdfGetTraceFile(
Handle: ?*anyopaque,
TraceFileLocation: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// 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 (11)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const CHAR = @import("../foundation.zig").CHAR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IUnknown = @import("../system/com.zig").IUnknown;
const PWSTR = @import("../foundation.zig").PWSTR;
const SID = @import("../security.zig").SID;
const SOCKET = @import("../networking/win_sock.zig").SOCKET;
const SOCKET_ADDRESS_LIST = @import("../networking/win_sock.zig").SOCKET_ADDRESS_LIST;
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/network_management/network_diagnostics_framework.zig |
const std = @import("std");
const Answer = struct { @"0": u32, @"1": u32 };
const Digit = std.bit_set.IntegerBitSet(7);
const ObservedDigits = [10]Digit;
const OutputDigits = [4]Digit;
const zero = Digit{ .mask = 0b1110111 };
const one = Digit{ .mask = 0b0100100 };
const two = Digit{ .mask = 0b1011101 };
const three = Digit{ .mask = 0b1101101 };
const four = Digit{ .mask = 0b0101110 };
const five = Digit{ .mask = 0b1101011 };
const six = Digit{ .mask = 0b1111011 };
const seven = Digit{ .mask = 0b0100101 };
const eight = Digit{ .mask = 0b1111111 };
const nine = Digit{ .mask = 0b1101111 };
const all_digits = [_]Digit{ zero, one, two, three, four, five, six, seven, eight, nine };
fn intersect(x: Digit, y: Digit) Digit {
var z = Digit.initEmpty();
var i: usize = 0;
while (i < Digit.bit_length) : (i += 1) {
if (x.isSet(i) and y.isSet(i)) {
z.set(i);
}
}
return z;
}
fn onion(x: Digit, y: Digit) Digit {
var z = x;
var i: usize = 0;
while (i < Digit.bit_length) : (i += 1) {
if (y.isSet(i)) {
z.set(i);
}
}
return z;
}
fn minus(x: Digit, y: Digit) Digit {
var z = x;
var i: usize = 0;
while (i < Digit.bit_length) : (i += 1) {
if (y.isSet(i)) {
z.unset(i);
}
}
return z;
}
fn subset(x: Digit, y: Digit) bool {
var i: usize = 0;
while (i < Digit.bit_length) : (i += 1) {
if (!x.isSet(i) and y.isSet(i)) {
return false;
}
}
return true;
}
fn equal(x: Digit, y: Digit) bool {
var i: usize = 0;
while (i < Digit.bit_length) : (i += 1) {
if (x.isSet(i) != y.isSet(i)) {
return false;
}
}
return true;
}
// Produces much garbage
fn permutations(n: usize, allocator: *std.mem.Allocator) error{OutOfMemory}!std.ArrayList(std.ArrayList(usize)) {
if (n == 0) {
var perms = std.ArrayList(std.ArrayList(usize)).init(allocator);
try perms.append(std.ArrayList(usize).init(allocator));
return perms;
} else {
var rec_perms = try permutations(n - 1, allocator);
var perms = std.ArrayList(std.ArrayList(usize)).init(allocator);
for (rec_perms.items) |rec_perm| {
var i: usize = 0;
while (i <= rec_perm.items.len) : (i += 1) {
var perm = std.ArrayList(usize).init(allocator);
try perm.resize(n - 1);
std.mem.copy(usize, perm.items, rec_perm.items);
try perm.insert(i, n - 1);
try perms.append(perm);
}
}
return perms;
}
}
fn run(filename: []const u8) !Answer {
const file = try std.fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader()).reader();
var buffer: [4096]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var observed_digits = std.ArrayList(ObservedDigits).init(&arena.allocator);
var output_digits = std.ArrayList(OutputDigits).init(&arena.allocator);
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
var observed_and_output_tokens = std.mem.tokenize(u8, line, "|");
var observed_tokens = std.mem.tokenize(u8, observed_and_output_tokens.next().?, " ");
{
var i: usize = 0;
var digits: ObservedDigits = undefined;
while (observed_tokens.next()) |token| : (i += 1) {
var digit = Digit.initEmpty();
for (token) |c| {
digit.set(@as(usize, c - 'a'));
}
digits[i] = digit;
}
try observed_digits.append(digits);
}
var output_tokens = std.mem.tokenize(u8, observed_and_output_tokens.next().?, " ");
{
var i: usize = 0;
var digits: OutputDigits = undefined;
while (output_tokens.next()) |token| : (i += 1) {
var digit = Digit.initEmpty();
for (token) |c| {
digit.set(@as(usize, c - 'a'));
}
digits[i] = digit;
}
try output_digits.append(digits);
}
}
var total: u32 = 0;
for (output_digits.items) |digits| {
for (digits) |digit| {
switch (digit.count()) {
// Digits 1, 7, 4, or 8 have this many segments
2, 3, 4, 7 => {
total += 1;
},
else => {},
}
}
}
const perms = try permutations(Digit.bit_length, &arena.allocator);
var grand_total: u32 = 0;
{
var i: usize = 0;
while (i < output_digits.items.len) : (i += 1) {
var num_valid_perms: u32 = 0;
for (perms.items) |perm| {
outer: for (observed_digits.items[i]) |digit| {
var permuted_digit = Digit.initEmpty();
var j: usize = 0;
while (j < Digit.bit_length) : (j += 1) {
if (digit.isSet(j)) {
permuted_digit.set(perm.items[j]);
}
}
j = 0;
while (j < 10) : (j += 1) {
if (equal(permuted_digit, all_digits[j])) {
break;
}
} else {
// Not equal to any of the digits
break :outer;
}
} else {
// Found the correct permutation
num_valid_perms += 1;
for (output_digits.items[i]) |digit, digit_i| {
var permuted_digit = Digit.initEmpty();
var j: usize = 0;
while (j < Digit.bit_length) : (j += 1) {
if (digit.isSet(j)) {
permuted_digit.set(perm.items[j]);
}
}
j = 0;
const pow10 = [_]u32{ 1000, 100, 10, 1 };
while (j < 10) : (j += 1) {
if (equal(permuted_digit, all_digits[j])) {
grand_total += pow10[digit_i] * @intCast(u32, j);
break;
}
} else {
unreachable();
}
}
}
}
}
}
return Answer{ .@"0" = total, .@"1" = grand_total };
}
pub fn main() !void {
const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt");
std.debug.print("{d}\n", .{answer.@"0"});
std.debug.print("{d}\n", .{answer.@"1"});
}
test {
const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt");
try std.testing.expectEqual(@as(u32, 26), answer.@"0");
try std.testing.expectEqual(@as(u32, 61229), answer.@"1");
} | src/day08.zig |
const pow = @import("std/math").pow;
// https://drafts.csswg.org/css-syntax/#tokenization
// 4. Tokenization
pub const Tokenizer = struct{
data: []u8,
idx: usize,
curr: u8,
next: u8,
reconsumed: bool,
};
// https://infra.spec.whatwg.org/#surrogate
// A surrogate is a code point that is in the range U+D800 to U+DFFF, inclusive.
fn isSurrogate(c: u8) -> bool {
0xD800 <= c and c <= 0xDFFF
}
pub const Token = enum {
Assoc: AssocToken,
Function: []u8,
Preserved: PreservedToken,
};
pub const AssocToken = enum {
LBracket,
LParen,
LBrace,
};
pub const AssocEnding = enum {
RBracket,
RParen,
RBrace,
};
pub fn getEnding(a: AssocToken) -> AssocEnding {
switch (a) {
AssocToken.LBrace => AssocEnding.RBrace,
AssocToken.LBracket => AssocEnding.RBracket,
AssocToken.LParen => AssocEnding.RParen,
}
}
pub const PreservedToken = enum {
Ident: []u8,
AtKeyword: []u8,
Hash: struct{data: []u8, isID: bool},
String: []u8,
URL: []u8,
BadString,
BadURL,
Delim: u8,
Number: struct{data: []u8, num: f32, typeIsNumber: bool},
Percentage: struct{data: []u8, num: f32},
Dimension: struct{data: []u8, unit: []u8, num: f32, typeIsNumber: bool},
Whitespace: []u8,
CDO,
CDC,
Colon,
Semicolon,
Comma,
AssocEnding: AssocEnding,
EOF,
};
// https://drafts.csswg.org/css-syntax/#tokenizer-definitions
// 4.2. Definitions
// This section defines several terms used during the tokenization phase.
// next input code point
// The first code point in the input stream that has not yet been consumed.
pub fn nextCP(t: Tokenizer) -> u8 {
if (t.reconsumed) {
t.curr;
} else {
t.next;
}
}
pub fn consumeNextCP(t: Tokenizer) -> u8 {
if (e.reconsumed) {
t.reconsumed = false;
} else {
t.curr = t.next;
t.next = t.data[t.idx+=1] %% _EOF;
}
t.curr;
}
// advances the tokenizer based on a pre-determined number
pub fn advance(t: Tokenizer, n: usize) -> void {
t.idx += n;
}
// fn consumeUntilChar(t: Tokenizer, char: u8, consumeEnding: bool) -> ?[]u8 {
// const start = t.idx;
// const found = advanceUntilCharOrEOF(t, char, consumeEnding);
// if (!found) {
// t.idx = start;
// null;
// } else {
// t.data[start : t.idx]
// }
// }
pub fn advanceUntilCharOrEOF(
t: Tokenizer, char: u8, consumeEnding: bool,
) -> bool {
var nxt = if (t.idx >= t.data.len) {
t.data.len;
} else {
t.idx + 1;
};
const found =
while (true) {
if ((t.data[nxt] %% break) == char) {
break true;
}
nxt += 1;
false;
} else {
false;
};
t.idx = if (consumeEnding) {
nxt;
} else {
nxt-1;
};
return found
}
pub const TwoCP = struct{a:u8, b:u8};
pub const ThreeCP = struct{a:u8, b:u8, c:u8};
pub fn nextTwoCP(t: Tokenizer) -> TwoCP {
// TODO: Should not be reconsumed here. Add an assertion.
TwoCP{a = t.next, b = t.data[t.idx+1] %% _EOF};
}
pub fn currAndNextTwoCP(t: Tokenizer) -> ThreeCP {
// TODO: Should not be reconsumed here. Add an assertion.
ThreeCP{a = t.curr, b = t.next, c = t.data[t.idx+1] %% _EOF};
}
pub fn nextThreeCP(t: Tokenizer) -> ThreeCP {
// TODO: Should not be reconsumed here. Add an assertion.
ThreeCP{a = t.next, b = t.data[t.idx+1] %% _EOF, c = t.data[t.idx+2] %% _EOF};
}
pub fn advanceIfNextCP(t: Tokenizer, char: u8) -> bool {
return if (t.next == char) {
t.idx += 1;
true;
} else {
false;
}
}
// current input code point
// The last code point to have been consumed.
pub fn currCP(t: Tokenizer) -> u8 {
t.curr;
}
pub fn advanceIfCurrCP(t: Tokenizer, char: u8) -> bool {
return if (t.curr == char) {
t.idx += 1;
true;
} else {
false;
}
}
// reconsume the current input code point
// Push the current input code point back onto the front of the input stream, so that the next time you are instructed to consume the next input code point, it will instead reconsume the current input code point.
pub fn reconsume(t: Tokenizer) -> u8 {
t.reconsumed = true;
}
// EOF code point
// A conceptual code point representing the end of the input stream. Whenever the input stream is empty, the next input code point is always an EOF code point.
pub const _EOF = 0x8899;
// digit
// A code point between U+0030 DIGIT ZERO (0) and U+0039 DIGIT NINE (9).
pub fn isDigit(c: u8) -> bool {
c ^ 0x30 < 10
}
// hex digit
// A digit, or a code point between U+0041 LATIN CAPITAL LETTER A (A) and U+0046 LATIN CAPITAL LETTER F (F), or a code point between U+0061 LATIN SMALL LETTER A (a) and U+0066 LATIN SMALL LETTER F (f).
pub fn isHexDigit(c: u8) -> bool {
isDigit(c) or (((c-1) | 0x20) ^ 0x60) < 6
}
// uppercase letter
// A code point between U+0041 LATIN CAPITAL LETTER A (A) and U+005A LATIN CAPITAL LETTER Z (Z).
pub fn isUppercase(c: u8) -> bool {
((c-1) ^ 0x40) < 26
// 'A' <= c and c <= 'Z'
}
// lowercase letter
// A code point between U+0061 LATIN SMALL LETTER A (a) and U+007A LATIN SMALL LETTER Z (z).
pub fn isLowercase(c: u8) -> bool {
((c-1) ^ 0x60) < 26
//'a' <= c and c <= 'z'
}
// letter
// An uppercase letter or a lowercase letter.
pub fn isLetter(c: u8) -> bool {
(((c-1) | 0x20) ^ 0x60) < 26
//'A' <= c and c <= 'Z' or 'a' <= c and c <= 'z'
}
// non-ASCII code point
// A code point with a value equal to or greater than U+0080 <control>.
pub fn isNonASCIICP(c: u8) -> bool {
c >= 0x80
}
// name-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
pub fn isNameStartCP(c: u8) -> bool {
isLetter(c) or c == 0x5F or isNonASCIICP(c)
}
// name code point
// A name-start code point, a digit, or U+002D HYPHEN-MINUS (-).
pub fn isNameCP(c: u8) -> bool {
isNameStartCP(c) or isDigit(c) or c == 0x2D
}
// non-printable code point
// A code point between U+0000 NULL and U+0008 BACKSPACE, or U+000B LINE TABULATION, or a code point between U+000E SHIFT OUT and U+001F INFORMATION SEPARATOR ONE, or U+007F DELETE.
pub fn isNonPrintableCP(c: u8) -> bool {
switch (c) {
0x80, 0x0B, 0x0E...0x1F, 0x7F => true,
else => false,
}
}
// newline
// U+000A LINE FEED. Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are not included in this definition, as they are converted to U+000A LINE FEED during preprocessing.
pub const newline = 0x0A;
// whitespace
// A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
pub fn isWhitespace(c: u8) -> bool {
switch (c) {
0x09, 0x20, newline => true,
else => false,
}
}
// The `leavePadding` param leaves that many whitespace characters before the
// next non-whitespace character, or fewer if there were insufficient spaces.
// It returns the amout of padding left.
pub fn consumeWhitespace(t: Tokenizer, leavePadding: usize) -> usize {
const start = t.idx;
var nxt = start+1;
if (!isWhitespace(t.data[nxt] %% _EOF)) {
return 0;
}
nxt += 1;
while (isWhitespace(t.data[nxt] %% _EOF)) {
nxt += 1;
}
t.idx = nxt-1-leavePadding;
if (t.idx < start) {
leavePadding -= start-t.idx;
t.idx = start;
}
t.curr = t.data[t.idx];
t.next = t.data[t.idx+1] %% _EOF;
return leavePadding;
}
// maximum allowed code point
// The greatest code point defined by Unicode: U+10FFFF.
pub const maxCP = 0x10FFFF;
pub const replacementChar = 0xFFFD;
// identifier
// A portion of the CSS source that has the same syntax as an <ident-token>. Also appears in <at-keyword-token>, <function-token>, <hash-token> with the "id" type flag, and the unit of <dimension-token>.
// representation
// The representation of a token is the subsequence of the input stream consumed by the invocation of the consume a token algorithm that produced it. This is preserved for a few algorithms that rely on subtle details of the input text, which a simple "re-serialization" of the tokens might disturb.
// The representation is only consumed by internal algorithms, and never directly exposed, so it’s not actually required to preserve the exact text; equivalent methods, such as associating each token with offsets into the source text, also suffice.
// Note: In particular, the representation preserves details such as whether .009 was written as .009 or 9e-3, and whether a character was written literally or as a CSS escape. The former is necessary to properly parse <urange> productions; the latter is basically an accidental leak of the tokenizing abstraction, but allowed because it makes the impl easier to define.
// If a token is ever produced by an algorithm directly, rather than thru the tokenization algorithm in this specification, its representation is the empty string.
// https://drafts.csswg.org/css-syntax/#tokenizer-algorithms
// 4.3. Tokenizer Algorithms
//
// The algorithms defined in this section transform a stream of code points into a stream of tokens.
// https://drafts.csswg.org/css-syntax/#consume-token
// 4.3.1. Consume a token
//
// This section describes how to consume a token from a stream of code points. It will return a single token of any type.
pub fn consumeToken(t: Tokenizer) -> Token {
_ = consumeComments(t);
const cp = consumeNextCP(t);
switch (cp) {
newline, 0x09, 0x20 => { // newline, tab, space
consumeWhitespace(t, 0);
Token.Whitespace;
},
'#' =>
if (isNameCP(nextCP(t)) or twoCPsAreValidEscape(nextTwoCP(t))) {
var h = Token.Hash{};
h.isID = inputStreamStartIdent(t);
h.data = consumeName(t);
h
} else {
Token.Delim(cp);
},
'"', '\'' => consumeStringToken(t),
'(' => Hash.LParen,
')' => Hash.RParen,
',' => Hash.Comma,
'+', '-' => {
if (inputStreamStartNumber(t)) {
reconsume(t);
return consumeNumericToken(t);
}
if (cp == '-') {
const two = nextTwoCp(t);
if (two.a == '-' and two.b == '>') {
_ = consumeNextCP(t);
_ = consumeNextCP(t);
Token.CDC;
} else if (inputStreamStartIdent(t)) {
reconsume(t);
consumeIdentLikeToken(t);
} else {
Token.Delim(cp);
}
}
},
'.' =>
if (inputStreamStartNumber(t)) {
reconsume(t);
consumeNumericT(t);
},
':' => Token.Colon,
';' => Token.Semicolon,
'<' => {
const three = nextThreeCP(t);
if (three.a == '!' and three.b == '-' and three.c == '-') {
_ = consumeNextCP(t);
_ = consumeNextCP(t);
_ = consumeNextCP(t);
Token.CDO;
} else {
Token.Delim(cp);
}
},
'@' =>
if (threeCPsStartIdent(nextThreeCP(t))) {
Token.AtKeyword(consumeName(t));
} else {
Token.Delim(cp);
},
'[' => Token.LBracket,
'\\' =>
if (inputStreamValidEscape(t)) {
reconsume(t);
consumeIdentLikeToken(t)
} else {
// TODO: handle parse error
Token.Delim(cp);
},
']' => Token.RBracket,
'{' => Token.LBrace,
'}' => Token.RBrace,
'0'...'9' => {
reconsume(t);
consumeNumericToken(t);
},
_EOF =>
Token.EOF,
else =>
if (isNameStartCP(cp)) {
reconsume(t);
consumeIdentLikeToken(t);
} else {
Token.Delim(cp);
}
}
}
// https://drafts.csswg.org/css-syntax/#consume-comment
// 4.3.2. Consume comments
//
// This section describes how to consume comments from a stream of code points. It returns nothing.
pub fn consumeComments(t: Tokenizer) -> void {
var two: struct{a: u8, b: u8};
while (true) {
two = nextTwoCP(t);
if (two.a != '/' or two.b != '*') {
return;
}
advance(t, 2); // Move past `/*`
_ = advanceIfNextCP(t, '/'); // Prevent `/*/` from halting the loop below
while (advanceUntilCharOrEOF(t, '/', false) and !advanceIfCurrCP(t, '*')) {
// Found '/' but not '*/'
}
}
}
// https://drafts.csswg.org/css-syntax/#consume-numeric-token
// 4.3.3. Consume a numeric token
//
// This section describes how to consume a numeric token from a stream of code points. It returns either a <number-token>, <percentage-token>, or <dimension-token>.
pub fn consumeNumericToken(t: Tokenizer) -> Token {
const number = consumeNumber(t);
if (threeCPsStartIdent(nextThreeCP(t))) {
return Token.Dimension{
data = number.data,
unit = consumeName(t),
num = number.num,
typeIsNumber = true,
};
if (advanceIfNextCP(t, '%')) {
return Token.Percentage{
data = number.data,
num = number.num,
};
}
return Token.Number{
data = number.data,
num = number.num,
typeIsNumber = true,
};
}
}
// https://drafts.csswg.org/css-syntax/#consume-ident-like-token
// 4.3.4. Consume an ident-like token
//
// This section describes how to consume an ident-like token from a stream of code points. It returns an <ident-token>, <function-token>, <url-token>, or <bad-url-token>.
pub fn consumeIdentLikeToken(t: Tokenizer) -> Token {
const string = consumeName(t);
if (advanceIfNextCP(t, '(')) {
if (string.toLower() == "url") {
const hasPadding = consumeWhitespace(t, 1) != 0;
const c = if (hasPadding) {
nextTwoCP(t).b;
} else {
nextCP(t);
};
if (c == '\'' or c == '"') {
Token.Function(string);
} else {
consumeURLToken(t);
}
} else {
Token.Function(string);
}
} else {
Token.Ident(string);
}
}
// https://drafts.csswg.org/css-syntax/#consume-string-token
// 4.3.5. Consume a string token
//
// This section describes how to consume a string token from a stream of code points. It returns either a <string-token> or <bad-string-token>.
//
// This algorithm may be called with an ending code point, which denotes the code point that ends the string. If an ending code point is not specified, the current input code point is used.
pub fn consumeStringToken(t: Tokenizer) -> Token {
const str = []u8{};
const end = currCP(t);
while (true) {
switch (consumeNextCP(t)) {
end => return Token.String(str),
_EOF => return Token.String(str), // TODO: Handle parser error
newline => {
// TODO: Handle parser error
reconsume(t);
return Token.BadString;
},
0x5C => // `\`
switch (nextCP(t)) {
_EOF => {}, // do nothing
newline => advance(t, 1),
else => str.append(consumeEscapedCP(t)),
},
else => str.append(currCP(t)),
}
}
}
// https://drafts.csswg.org/css-syntax/#consume-url-token
// 4.3.6. Consume a url token
//
// This section describes how to consume a url token from a stream of code points. It returns either a <url-token> or a <bad-url-token>.
//
// Note: This algorithm assumes that the initial "url(" has already been consumed.
pub fn consumeURLToken(t: Tokenizer) -> Token {
const url = []u8{};
_ = consumeWhitespace(t, 0);
if (nextCP(t) == _EOF) {
return Token.URL(url); // TODO: Handle parse error
}
while (true) {
switch (consumeNextCP(t)) {
')' => return Token.URL(url),
_EOF => return Token.URL(url), // TODO: Handle parse error
newline, 0x09, 0x20 => {// newline, tab, space
consumeWhitespace(t, 0);
if (advanceIfNextCP(t, ')')) {
return Token.URL(url);
}
if (advanceIfNextCP(t, _EOF)) {
return Token.URL(url); // TODO: Handle parse error
}
consumeBadURL(t); // TODO: No "handle parse error" ??????
return Token.BadURL;
},
'"', '\'', '(', 0x80, 0x0B, 0x0E...0x1F, 0x7F => {
consumeBadURL(t); // TODO: Handle parse error
return Token.BadURL;
},
'\\' =>
if (inputStreamValidEscape(t)) {
url.append(consumeEscapedCP(t));
} else {
consumeBadURL(t); // TODO: Handle parse error
return Token.BadURL;
},
else => url.append(currCP(t)),
}
}
}
// https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
// 4.3.7. Consume an escaped code point
//
// This section describes how to consume an escaped code point. It assumes that the U+005C REVERSE SOLIDUS (\) has already been consumed and that the next input code point has already been verified to not be a newline. It will return a code point.
pub fn consumeEscapedCP(t: Tokenizer) -> u8 {
const cp = consumeNextCP(t);
var hexNum = tryHexCharToNumber(cp);
if (hexNum) { // is hex digit
var count = 1;
const limit = 6;
while (count < limit) : (count += 1) {
if (tryHexCharToNumber(nextCP(t))) |val| {
hexNum = (hexNum << 4) + val;
advance(t, 1);
}
}
if (isWhitespace(nextCP(t))) {
advance(t, 1);
}
if (hexNum == 0 or isSurrogate(hexNum) or hexNum > maxCP) {
replacementChar;
} else {
hexNum;
}
} else {
cp;
}
}
// If `c` is a valid hex digit, the return will be < 16, else 0xFF is returned.
pub fn tryHexCharToNumber(c: u8) -> ?u8 {
const d = c ^ 0x30;
if (d < 10) {
return d;
}
const h = 10 + (((c-1) | 0x20) ^ 0x60);
if (h < 16) {
return h;
}
return null; // failed
}
// https://drafts.csswg.org/css-syntax/#starts-with-a-valid-escape
// 4.3.8. Check if two code points are a valid escape
//
// This section describes how to check if two code points are a valid escape. The algorithm described here can be called explicitly with two code points, or can be called with the input stream itself. In the latter case, the two code points in question are the current input code point and the next input code point, in that order.
//
// Note: This algorithm will not consume any additional code point.
pub fn twoCPsAreValidEscape(two: TwoCP) -> bool {
a == '\\' and b != newline and b != _EOF
}
pub fn inputStreamValidEscape(t: Tokenizer) -> bool {
twoCPsAreValidEscape(TwoCP{a = currCP(t), b = nextCP(t)})
}
// https://drafts.csswg.org/css-syntax/#would-start-an-identifier
// 4.3.9. Check if three code points would start an identifier
//
// This section describes how to check if three code points would start an identifier. The algorithm described here can be called explicitly with three code points, or can be called with the input stream itself. In the latter case, the three code points in question are the current input code point and the next two input code points, in that order.
//
// Note: This algorithm will not consume any additional code points.
pub fn threeCPsStartIdent(three: ThreeCP) -> bool {
switch (a) {
'-' => b == '-' or isNameStartCP(b) or twoCPsAreValidEscape(b, c),
'\\' => twoCPsAreValidEscape(a, b),
else => isNameStartCP(a),
}
}
pub fn inputStreamStartIdent(t: Tokenizer) -> bool {
threeCPsStartIdent(currAndNextTwoCP(t))
}
// https://drafts.csswg.org/css-syntax/#starts-with-a-number
// 4.3.10. Check if three code points would start a number
//
// This section describes how to check if three code points would start a number. The algorithm described here can be called explicitly with three code points, or can be called with the input stream itself. In the latter case, the three code points in question are the current input code point and the next two input code points, in that order.
//
// Note: This algorithm will not consume any additional code points.
pub fn threeCPsStartNumber(three: ThreeCP) -> bool {
switch(a) {
'+', '-' => isDigit(b) or (b == '.' and isDigit(c)),
'.' => isDigit(b),
else => isDigit(a),
}
}
pub fn inputStreamStartNumber(t: Tokenizer) -> bool {
threeCPsStartNumber(currAndNextTwoCP(t));
}
// https://drafts.csswg.org/css-syntax/#consume-name
// 4.3.11. Consume a name
//
// This section describes how to consume a name from a stream of code points. It returns a string containing the largest name that can be formed from adjacent code points in the stream, starting from the first.
//
// Note: This algorithm does not do the verification of the first few code points that are necessary to ensure the returned code points would constitute an <ident-token>. If that is the intended use, ensure that the stream starts with an identifier before calling this algorithm.
fn consumeName(t: Tokenizer) -> []u8 {
var result = []u8{};
var cp = consumeNextCP(t);
while (true) {
if (isNameCP(cp)) {
result.append(cp);
} else if (inputStreamValidEscape(t)) {
result.append(consumeEscapedCP(t));
} else {
reconsume(t);
return result;
}
cp = consumeNextCP(t);
}
}
// https://drafts.csswg.org/css-syntax/#consume-number
// 4.3.12. Consume a number
//
// This section describes how to consume a number from a stream of code points. It returns a numeric value, and a type which is either "integer" or "number".
//
// Note: This algorithm does not do the verification of the first few code points that are necessary to ensure a number can be obtained from the stream. Ensure that the stream starts with a number before calling this algorithm.
fn consumeNumber(t: Tokenizer) -> struct{val: i32, isNumber: bool} {
var repr = []u8{};
var isNumber = false;
var cp = nextCP(t);
switch (cp) {
'+', '-' => {
repr.append(cp);
advance(t, 1);
},
}
repr = appendDigits(t, repr);
if (nextCP(t) == '.') {
const afterNext = nextTwoCP(t).b;
repr.append('.', afterNext);
isNumber = true;
repr = appendDigits(t, repr);
}
return struct{val: i32, isNumber: bool}{
val = convertToNumber(repr),
isNumber = isNumber,
};
}
fn appendDigits(t: Tokenizer, repr: []u8) -> []u8 {
var cp = nextCP(t);
while (isDigit(cp)) {
repr.append(cp);
advance(t, 1);
}
}
// https://drafts.csswg.org/css-syntax/#convert-string-to-number
// 4.3.13. Convert a string to a number
//
// This section describes how to convert a string to a number. It returns a number.
//
// Note: This algorithm does not do any verification to ensure that the string contains only a number. Ensure that the string contains only a valid CSS number before calling this algorithm.
fn convertStringToNumber(repr: []u8) -> f32 {
var idx = 0;
const s = switch (%%repr[idx]) {
'-' => { idx = 1; -1 },
'+' => { idx = 1; 1 },
else => 1,
};
var i = 0;
while (idx < repr.len) : (idx += 1) {
const cp = %%repr[idx];
if (isDigit(cp)) {
i = (i * 10) + (cp - '0');
}
}
const dec = if ((repr[i] %% 'x') == '.') {idx += 1; "."} else "";
var f = 0;
var d = 0;
while (idx < repr.len) : (idx += 1) {
const cp = %%repr[idx];
if (isDigit(cp)) {
f = (f * 10) + (cp - '0');
d += 1;
}
}
const exp = switch(repr[idx] %% 'x') {
'E' => "E",
'e' => "e",
else => "",
};
const t = switch (repr[idx] %% 'x') {
'-' => { idx += 1; -1 },
'+' => { idx += 1; 1 },
else => 1,
};
var e = 0;
while (idx < repr.len) : (idx += 1) {
const cp = %%repr[idx];
if (isDigit(cp)) {
e = (e * 10) + (cp - '0');
}
}
s * (i + f * pow(10, -d)) * pow(10, t*e)
}
// https://drafts.csswg.org/css-syntax/#consume-remnants-of-bad-url
// 4.3.14. Consume the remnants of a bad url
//
// This section describes how to consume the remnants of a bad url from a stream of code points, "cleaning up" after the tokenizer realizes that it’s in the middle of a <bad-url-token> rather than a <url-token>. It returns nothing; its sole use is to consume enough of the input stream to reach a recovery point where normal tokenizing can resume.
fn consumeBadURL(t: Tokenizer) -> void {
var cp = consumeNextCP(t);
while (cp != ')' and cp != _EOF) {
if (inputStreamValidEscape(t)) {
_ = consumeEscapedCP(t);
}
}
} | parser/4_0_tokenization.zig |
const irq = @import("interrupts.zig");
const platform = @import("platform.zig");
const serial = @import("../../debug/serial.zig");
const scheduler = @import("../../scheduler.zig");
const IRQ_PIT = 0x00;
const CounterSelect = enum {
Counter0,
Counter1,
Counter2,
pub fn getRegister(c: CounterSelect) u16 {
return switch (c) {
.Counter0 => 0x40, // System clock.
.Counter1 => 0x41, // Unused.
.Counter2 => 0x42, // PC speakers.
};
}
pub fn getCounterOCW(c: CounterSelect) u8 {
return switch (c) {
.Counter0 => 0x00,
.Counter1 => 0x40,
.Counter2 => 0x80,
};
}
};
const PitError = error{InvalidFrequency};
const COMMAND_REGISTER: u16 = 0x43;
const OCW_BINARY_COUNT_BINARY: u8 = 0x00;
const OCW_BINARY_COUNT_BCD: u8 = 0x00; // Binary Coded Decimal
const OCW_MODE_TERMINAL_COUNT: u8 = 0x00;
const OCW_MODE_ONE_SHOT: u8 = 0x02;
const OCW_MODE_RATE_GENERATOR: u8 = 0x04;
const OCW_MODE_SQUARE_WAVE_GENERATOR: u8 = 0x06;
const OCW_MODE_SOFTWARE_TRIGGER: u8 = 0x08;
const OCW_MODE_HARDWARE_TRIGGER: u8 = 0x0A;
const OCW_READ_LOAD_LATCH: u8 = 0x00;
const OCW_READ_LOAD_LSB_ONLY: u8 = 0x10;
const OCW_READ_LOAD_MSB_ONLY: u8 = 0x20;
const OCW_READ_LOAD_DATA: u8 = 0x30;
const MAX_FREQUENCY: u32 = 1193180;
var ticks: u64 = 0;
var unused_ticks: u64 = 0; // Counter 1
var speaker_ticks: u64 = 0;
var cur_freq_0: u32 = undefined;
var cur_freq_1: u32 = undefined;
var cur_freq_2: u32 = undefined;
pub var time_ns: u32 = undefined;
pub var time_under_1_ns: u32 = undefined;
fn sendCommand(cmd: u8) void {
platform.out(COMMAND_REGISTER, cmd);
}
fn readBackCommand(cs: CounterSelect) u8 {
sendCommand(0xC2);
return platform.in(u8, cs.getRegister()) & 0x3F;
}
fn sendDataToCounter(cs: CounterSelect, data: u8) void {
platform.out(cs.getRegister(), data);
}
fn pitHandler(ctx: *platform.Context) usize {
ticks +%= 1;
return scheduler.pickNextTask(ctx);
}
fn computeReloadValue(freq: u32) u32 {
var reloadValue: u32 = 0x10000; // 19Hz.
if (freq > 18) {
if (freq < MAX_FREQUENCY) {
reloadValue = (MAX_FREQUENCY + (freq / 2)) / freq;
} else {
reloadValue = 1;
}
}
return reloadValue;
}
fn computeAdjustedFrequency(reloadValue: u32) u32 {
return (MAX_FREQUENCY + (reloadValue / 2)) / reloadValue;
}
fn setupCounter(cs: CounterSelect, freq: u32, mode: u8) PitError!void {
if (freq < 19 or freq > MAX_FREQUENCY) {
return PitError.InvalidFrequency;
}
const reloadValue = computeReloadValue(freq);
const frequency = computeAdjustedFrequency(reloadValue);
time_ns = 1000000000 / frequency;
time_under_1_ns = ((1000000000 % frequency) * 1000 + (frequency / 2)) / frequency;
switch (cs) {
.Counter0 => cur_freq_0 = frequency,
.Counter1 => cur_freq_1 = frequency,
.Counter2 => cur_freq_2 = frequency,
}
const reload_val_trunc = @truncate(u16, reloadValue);
sendCommand(mode | OCW_READ_LOAD_DATA | cs.getCounterOCW());
sendDataToCounter(cs, @truncate(u8, reload_val_trunc));
sendDataToCounter(cs, @truncate(u8, reload_val_trunc >> 8));
switch (cs) {
.Counter0 => ticks = 0,
.Counter1 => unused_ticks = 0,
.Counter2 => speaker_ticks = 0,
}
serial.printf("Frequency set at: {d}Hz, reload value: {d}Hz, real frequency: {d}Hz\n", .{ freq, reloadValue, frequency });
}
pub fn getTicks() u64 {
return ticks;
}
pub fn getFrequency() u32 {
return cur_freq_0;
}
pub fn initialize() void {
serial.writeText("PIT initialization\n");
defer serial.writeText("PIT initialized.\n");
// const freq: u32 = 10000;
const freq = 19; // TODO(w): choose the best frequency
setupCounter(CounterSelect.Counter0, freq, OCW_MODE_SQUARE_WAVE_GENERATOR | OCW_BINARY_COUNT_BINARY) catch |e| {
serial.ppanic("Invalid frequency: {d}\n", .{freq});
};
irq.registerIRQ(IRQ_PIT, pitHandler);
// TODO: runtimeTests.
}
fn runtimeTests() void {
platform.cli();
defer platform.sti();
// Force enable interrupts
} | src/kernel/arch/x86/pit.zig |
const __floatuntisf = @import("floatuntisf.zig").__floatuntisf;
const testing = @import("std").testing;
fn test__floatuntisf(a: u128, expected: f32) void {
const x = __floatuntisf(a);
testing.expect(x == expected);
}
test "floatuntisf" {
test__floatuntisf(0, 0.0);
test__floatuntisf(1, 1.0);
test__floatuntisf(2, 2.0);
test__floatuntisf(20, 20.0);
test__floatuntisf(0x7FFFFF8000000000, 0x1.FFFFFEp+62);
test__floatuntisf(0x7FFFFF0000000000, 0x1.FFFFFCp+62);
test__floatuntisf(make_ti(0x8000008000000000, 0), 0x1.000001p+127);
test__floatuntisf(make_ti(0x8000000000000800, 0), 0x1.0p+127);
test__floatuntisf(make_ti(0x8000010000000000, 0), 0x1.000002p+127);
test__floatuntisf(make_ti(0x8000000000000000, 0), 0x1.000000p+127);
test__floatuntisf(0x0007FB72E8000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72EA000000, 0x1.FEDCBA8p+50);
test__floatuntisf(0x0007FB72EB000000, 0x1.FEDCBACp+50);
test__floatuntisf(0x0007FB72EC000000, 0x1.FEDCBBp+50);
test__floatuntisf(0x0007FB72E6000000, 0x1.FEDCB98p+50);
test__floatuntisf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50);
test__floatuntisf(0x0007FB72E4000000, 0x1.FEDCB9p+50);
test__floatuntisf(0xFFFFFFFFFFFFFFFE, 0x1p+64);
test__floatuntisf(0xFFFFFFFFFFFFFFFF, 0x1p+64);
test__floatuntisf(0x0007FB72E8000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72EA000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72EB000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72EBFFFFFF, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72EC000000, 0x1.FEDCBCp+50);
test__floatuntisf(0x0007FB72E8000001, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72E6000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72E7000000, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72E7FFFFFF, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72E4000001, 0x1.FEDCBAp+50);
test__floatuntisf(0x0007FB72E4000000, 0x1.FEDCB8p+50);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCB90000000000001), 0x1.FEDCBAp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBA0000000000000), 0x1.FEDCBAp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBAFFFFFFFFFFFFF), 0x1.FEDCBAp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBB0000000000000), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBB0000000000001), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBBFFFFFFFFFFFFF), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBC0000000000000), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBC0000000000001), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBD0000000000000), 0x1.FEDCBCp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBD0000000000001), 0x1.FEDCBEp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBDFFFFFFFFFFFFF), 0x1.FEDCBEp+76);
test__floatuntisf(make_ti(0x0000000000001FED, 0xCBE0000000000000), 0x1.FEDCBEp+76);
}
fn make_ti(high: u64, low: u64) u128 {
var result: u128 = high;
result <<= 64;
result |= low;
return result;
} | lib/std/special/compiler_rt/floatuntisf_test.zig |
const lz = @import("./lz77.zig");
const hamlet = @embedFile("../fixtures/hamlet.txt");
const std = @import("std");
const assert = std.debug.assert;
const expect = std.testing.expect;
const math = std.math;
const mem = std.mem;
const UINT8_MAX = math.maxInt(u8);
test "hash4" {
try expect(lz.hash4(&[4]u8{ 0x00, 0x00, 0x00, 0x00 }) == 0x0000);
try expect(lz.hash4(&[4]u8{ 0x00, 0x00, 0x00, 0x01 }) == 0x5880);
try expect(lz.hash4(&[4]u8{ 0x10, 0x01, 0x10, 0x01 }) == 0x3380);
try expect(lz.hash4(&[4]u8{ 0xf0, 0x0f, 0xf0, 0x0f }) == 0x0489);
try expect(lz.hash4(&[4]u8{ 0xff, 0x0f, 0xf0, 0xff }) == 0x1f29);
try expect(lz.hash4(&[4]u8{ 0xff, 0xff, 0xff, 0xff }) == 0x30e4);
}
fn dummy_backref(dist: usize, len: usize, aux: anytype) bool {
_ = dist;
_ = len;
_ = aux;
return true;
}
fn dummy_lit(lit: u8, aux: anytype) bool {
_ = lit;
_ = aux;
return true;
}
test "empty" {
const empty = "";
try expect(lz.lz77_compress(empty[0..], 0, 100, 100, true, dummy_lit, dummy_backref, null));
}
const MAX_BLOCK_CAP = 50000;
const block_t: type = struct {
n: usize,
cap: usize,
data: [MAX_BLOCK_CAP]struct {
dist: usize,
litlen: usize,
},
};
fn output_backref(dist: usize, len: usize, aux: anytype) bool {
var block: *block_t = aux;
assert(block.cap <= MAX_BLOCK_CAP);
assert((dist == 0 and len <= UINT8_MAX) or (dist > 0 and len > 0));
assert(dist <= lz.LZ_WND_SIZE);
assert(block.n <= block.cap);
if (block.n == block.cap) {
return false;
}
block.data[block.n].dist = dist;
block.data[block.n].litlen = len;
block.n += 1;
return true;
}
fn output_lit(lit: u8, aux: anytype) bool {
return output_backref(0, @intCast(usize, lit), aux);
}
fn unpack(dst: [*]u8, b: *const block_t) void {
var dst_pos: usize = 0;
var i: usize = 0;
while (i < b.n) : (i += 1) {
if (b.data[i].dist == 0) {
lz.lz77_output_lit(dst, dst_pos, @intCast(u8, b.data[i].litlen));
dst_pos += 1;
} else {
lz.lz77_output_backref(dst, dst_pos, b.data[i].dist, b.data[i].litlen);
dst_pos += b.data[i].litlen;
}
}
}
test "literals" {
const src = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
for (src) |_, i| {
// Test compressing the i-length prefix of src.
b.n = 0;
try expect(lz.lz77_compress(src[0..], i, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == i);
var j: usize = i;
while (j < i) : (j += 1) {
try expect(b.data[j].dist == 0);
try expect(b.data[j].litlen == src[j]);
}
}
}
test "backref" {
const src = [_]u8{ 0, 1, 2, 3, 0, 1, 2, 3 };
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(src[0..], src.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 5);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 0);
try expect(b.data[1].dist == 0 and b.data[1].litlen == 1);
try expect(b.data[2].dist == 0 and b.data[2].litlen == 2);
try expect(b.data[3].dist == 0 and b.data[3].litlen == 3);
try expect(b.data[4].dist == 4 and b.data[4].litlen == 4); // 0, 1, 2, 3
}
test "aaa" {
// An x followed by 300 a's"
const s = "x" ++ ("a" ** 300);
var out: [301]u8 = undefined;
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(s, 301, 32768, 258, true, output_lit, output_backref, &b));
try expect(b.n == 4);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'x');
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'a');
try expect(b.data[2].dist == 1 and b.data[2].litlen == 258);
try expect(b.data[3].dist == 1 and b.data[3].litlen == 41);
unpack(&out, &b);
try expect(mem.eql(u8, s, out[0..]));
}
test "remaining_backref" {
const s = "abcdabcd";
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(s, s.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 5);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'a');
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'b');
try expect(b.data[2].dist == 0 and b.data[2].litlen == 'c');
try expect(b.data[3].dist == 0 and b.data[3].litlen == 'd');
try expect(b.data[4].dist == 4 and b.data[4].litlen == 4); // "abcd"
}
test "deferred" {
const s = "x" ++ "abcde" ++ "bcdefg" ++ "abcdefg";
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(s, s.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 11);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'x');
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'a');
try expect(b.data[2].dist == 0 and b.data[2].litlen == 'b');
try expect(b.data[3].dist == 0 and b.data[3].litlen == 'c');
try expect(b.data[4].dist == 0 and b.data[4].litlen == 'd');
try expect(b.data[5].dist == 0 and b.data[5].litlen == 'e');
try expect(b.data[6].dist == 4 and b.data[6].litlen == 4); // bcde
try expect(b.data[7].dist == 0 and b.data[7].litlen == 'f');
try expect(b.data[8].dist == 0 and b.data[8].litlen == 'g');
// Could match "abcd" here, but taking a literal "a" and then matching
// "bcdefg" is preferred.
try expect(b.data[9].dist == 0 and b.data[9].litlen == 'a');
try expect(b.data[10].dist == 7 and b.data[10].litlen == 6); // bcdefg
}
test "chain" {
const s = "hippo" ++ "hippie" ++ "hippos";
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(s, s.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 10);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'h');
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'i');
try expect(b.data[2].dist == 0 and b.data[2].litlen == 'p');
try expect(b.data[3].dist == 0 and b.data[3].litlen == 'p');
try expect(b.data[4].dist == 0 and b.data[4].litlen == 'o');
try expect(b.data[5].dist == 5 and b.data[5].litlen == 4); // hipp
try expect(b.data[6].dist == 0 and b.data[6].litlen == 'i');
try expect(b.data[7].dist == 0 and b.data[7].litlen == 'e');
// Don't go for "hipp"; look further back the chain.
try expect(b.data[8].dist == 11 and b.data[8].litlen == 5); // hippo
try expect(b.data[9].dist == 0 and b.data[9].litlen == 's');
}
test "output_fail" {
const s = "abcdbcde";
const t = "x123234512345";
const u = "0123123";
const v = "0123";
var b: block_t = undefined;
// Not even room for a literal.
b.cap = 0;
b.n = 0;
try expect(!lz.lz77_compress(s, s.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 0);
// No room for the backref.
b.cap = 4;
b.n = 0;
try expect(!lz.lz77_compress(s, s.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 4); // a, b, c, d (no room: bcd, e)
// No room for literal for deferred match.
b.cap = 8;
b.n = 0;
try expect(!lz.lz77_compress(t, t.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 8); // x, 1, 2, 3, 2, 3, 4, 5 (no room: 1, 2345)
// No room for final backref.
b.cap = 4;
b.n = 0;
try expect(!lz.lz77_compress(u, u.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 4); // 0, 1, 2, 3 (no room: 1, 2, 3)
// No room for final lit.
b.cap = 3;
b.n = 0;
try expect(!lz.lz77_compress(v, v.len, 100, 100, true, output_lit, output_backref, &b));
try expect(b.n == 3); // 0, 1, 2 (no room: 3)
}
test "outside_window" {
var s: [50000]u8 = undefined;
var b: block_t = undefined;
var i: usize = 0;
const second_foo_pos = 40000;
mem.set(u8, s[0..], ' ');
mem.copy(u8, s[1..], "foo");
mem.copy(u8, s[second_foo_pos..], "foo");
b.cap = MAX_BLOCK_CAP;
b.n = 0;
const max_dist = lz.LZ_WND_SIZE;
assert(second_foo_pos > max_dist + 2);
try expect(lz.lz77_compress(s[0..], s.len, max_dist, 100, true, output_lit, output_backref, &b));
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'f');
try expect(b.data[2].dist == 0 and b.data[2].litlen == 'o');
try expect(b.data[3].dist == 0 and b.data[3].litlen == 'o');
// Search for the next "foo". It can't be a backref, because it's outside the window.
var found_second_foo = false;
i = 4;
while (i < s.len - 2) : (i += 1) {
if (b.data[i].dist == 0 and b.data[i].litlen == 'f') {
try expect(b.data[i + 1].dist == 0);
try expect(b.data[i + 1].litlen == 'o');
try expect(b.data[i + 2].dist == 0);
try expect(b.data[i + 2].litlen == 'o');
found_second_foo = true;
}
}
try expect(found_second_foo);
}
test "hamlet" {
var out: [hamlet.len]u8 = undefined;
var b: block_t = undefined;
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(hamlet, hamlet.len, 32768, 258, true, output_lit, output_backref, &b));
// Lower this expectation in case of improvements to the algorithm.
try expect(b.n == 47990);
unpack(&out, &b);
try expect(mem.eql(u8, hamlet, out[0..]));
}
test "no_overlap" {
const s = "aaaa" ++ "aaaa" ++ "aaaa";
var overlap = true;
var b: block_t = undefined;
// With overlap.
b.cap = MAX_BLOCK_CAP;
b.n = 0;
overlap = true;
try expect(lz.lz77_compress(s, 12, 32768, 258, overlap, output_lit, output_backref, &b));
try expect(b.n == 2);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'a');
try expect(b.data[1].dist == 1 and b.data[1].litlen == 11);
// Without overlap.
b.cap = MAX_BLOCK_CAP;
b.n = 0;
overlap = false;
try expect(lz.lz77_compress(s, 12, 32768, 258, overlap, output_lit, output_backref, &b));
try expect(b.n == 7);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'a');
try expect(b.data[1].dist == 0 and b.data[1].litlen == 'a');
try expect(b.data[2].dist == 0 and b.data[2].litlen == 'a');
try expect(b.data[3].dist == 0 and b.data[3].litlen == 'a');
try expect(b.data[4].dist == 0 and b.data[4].litlen == 'a');
try expect(b.data[5].dist == 0 and b.data[5].litlen == 'a');
try expect(b.data[6].dist == 6 and b.data[6].litlen == 6);
}
test "max_len" {
var src: [100]u8 = undefined;
var b: block_t = undefined;
mem.set(u8, src[0..], 'x');
b.cap = MAX_BLOCK_CAP;
b.n = 0;
try expect(lz.lz77_compress(src[0..], src.len, 32768, 25, true, output_lit, output_backref, &b));
try expect(b.n == 5);
try expect(b.data[0].dist == 0 and b.data[0].litlen == 'x');
try expect(b.data[1].dist == 1 and b.data[1].litlen == 25);
try expect(b.data[2].dist == 1 and b.data[2].litlen == 25);
try expect(b.data[3].dist == 1 and b.data[3].litlen == 25);
try expect(b.data[4].dist == 1 and b.data[4].litlen == 24);
}
test "max_dist" {
const s = "1234" ++ "xxxxxxxxxx" ++ "1234";
var b: block_t = undefined;
var max_dist: usize = 0;
b.cap = MAX_BLOCK_CAP;
// Max dist: 14.
b.n = 0;
max_dist = 14;
try expect(lz.lz77_compress(s, s.len, max_dist, 258, true, output_lit, output_backref, &b));
try expect(b.n == 7);
try expect(b.data[0].dist == 0 and b.data[0].litlen == '1');
try expect(b.data[1].dist == 0 and b.data[1].litlen == '2');
try expect(b.data[2].dist == 0 and b.data[2].litlen == '3');
try expect(b.data[3].dist == 0 and b.data[3].litlen == '4');
try expect(b.data[4].dist == 0 and b.data[4].litlen == 'x');
try expect(b.data[5].dist == 1 and b.data[5].litlen == 9);
try expect(b.data[6].dist == 14 and b.data[6].litlen == 4);
// Max dist: 13.
b.n = 0;
max_dist = 13;
try expect(lz.lz77_compress(s, s.len, max_dist, 258, true, output_lit, output_backref, &b));
try expect(b.n == 10);
try expect(b.data[0].dist == 0 and b.data[0].litlen == '1');
try expect(b.data[1].dist == 0 and b.data[1].litlen == '2');
try expect(b.data[2].dist == 0 and b.data[2].litlen == '3');
try expect(b.data[3].dist == 0 and b.data[3].litlen == '4');
try expect(b.data[4].dist == 0 and b.data[4].litlen == 'x');
try expect(b.data[5].dist == 1 and b.data[5].litlen == 9);
try expect(b.data[6].dist == 0 and b.data[6].litlen == '1');
try expect(b.data[7].dist == 0 and b.data[7].litlen == '2');
try expect(b.data[8].dist == 0 and b.data[8].litlen == '3');
try expect(b.data[9].dist == 0 and b.data[9].litlen == '4');
}
test "output_backref64" {
var dst: [128]u8 = undefined;
var dst_pos: usize = 0;
var dist: usize = 0;
var len: usize = 0;
var expected: [128]u8 = undefined;
// non-overlapping
dst = [_]u8{ 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i' } ** 8 ++ [_]u8{0} ** 64;
dst_pos = 64;
dist = 64;
len = 64;
expected = [_]u8{ 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i' } ** 16;
lz.lz77_output_backref64(&dst, dst_pos, dist, len);
try expect(mem.eql(u8, dst[0..], expected[0..]));
// overlapping
dst = [_]u8{ 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i' } ** 8 ++ [_]u8{0} ** 64;
dst_pos = 56;
dist = 56;
len = 64;
expected = [_]u8{ 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i' } ** 15 ++ [_]u8{0} ** 8;
lz.lz77_output_backref64(&dst, dst_pos, dist, len);
try expect(mem.eql(u8, dst[0..], expected[0..]));
} | src/lz77_test.zig |
const MMIO = @import("mmio.zig").MMIO;
// Register definititions:
// IO PORTS:
const PINB = MMIO(0x23, u8, packed struct {
PINB0: u1 = 0,
PINB1: u1 = 0,
PINB2: u1 = 0,
PINB3: u1 = 0,
PINB4: u1 = 0,
PINB5: u1 = 0,
PINB6: u1 = 0,
PINB7: u1 = 0,
});
const DDRB = MMIO(0x24, u8, packed struct {
DDB0: u1 = 0,
DDB1: u1 = 0,
DDB2: u1 = 0,
DDB3: u1 = 0,
DDB4: u1 = 0,
DDB5: u1 = 0,
DDB6: u1 = 0,
DDB7: u1 = 0,
});
const PORTB = MMIO(0x25, u8, packed struct {
PORTB0: u1 = 0,
PORTB1: u1 = 0,
PORTB2: u1 = 0,
PORTB3: u1 = 0,
PORTB4: u1 = 0,
PORTB5: u1 = 0,
PORTB6: u1 = 0,
PORTB7: u1 = 0,
});
const PINC = MMIO(0x26, u8, packed struct {
PINC0: u1 = 0,
PINC1: u1 = 0,
PINC2: u1 = 0,
PINC3: u1 = 0,
PINC4: u1 = 0,
PINC5: u1 = 0,
PINC6: u1 = 0,
PINC7: u1 = 0,
});
const DDRC = MMIO(0x27, u8, packed struct {
DDC0: u1 = 0,
DDC1: u1 = 0,
DDC2: u1 = 0,
DDC3: u1 = 0,
DDC4: u1 = 0,
DDC5: u1 = 0,
DDC6: u1 = 0,
DDC7: u1 = 0,
});
const PORTC = MMIO(0x28, u8, packed struct {
PORTC0: u1 = 0,
PORTC1: u1 = 0,
PORTC2: u1 = 0,
PORTC3: u1 = 0,
PORTC4: u1 = 0,
PORTC5: u1 = 0,
PORTC6: u1 = 0,
PORTC7: u1 = 0,
});
const PIND = MMIO(0x29, u8, packed struct {
PIND0: u1 = 0,
PIND1: u1 = 0,
PIND2: u1 = 0,
PIND3: u1 = 0,
PIND4: u1 = 0,
PIND5: u1 = 0,
PIND6: u1 = 0,
PIND7: u1 = 0,
});
const DDRD = MMIO(0x2A, u8, packed struct {
DDD0: u1 = 0,
DDD1: u1 = 0,
DDD2: u1 = 0,
DDD3: u1 = 0,
DDD4: u1 = 0,
DDD5: u1 = 0,
DDD6: u1 = 0,
DDD7: u1 = 0,
});
const PORTD = MMIO(0x2B, u8, packed struct {
PORTD0: u1 = 0,
PORTD1: u1 = 0,
PORTD2: u1 = 0,
PORTD3: u1 = 0,
PORTD4: u1 = 0,
PORTD5: u1 = 0,
PORTD6: u1 = 0,
PORTD7: u1 = 0,
});
// pulse width modulator
//Timers
pub const TCCR2B = MMIO(0xB1, u8, packed struct {
CS2: u3 = 0,
WGM22: u1 = 0,
_: u2 = 0,
FOC2B: u1 = 0,
FOC2A: u1 = 0,
});
pub const TCCR2A = MMIO(0xB0, u8, packed struct {
WGM20: u1 = 0,
WGM21: u1 = 0,
_: u2 = 0,
COM2B: u2 = 0,
COM2A: u2 = 0,
});
//Timer counter 1 16-bit
pub const TCCR1C = MMIO(0x82, u8, packed struct {
_: u5 = 0,
FOC1B: u1 = 0,
FOC1A: u1 = 0,
});
pub const TCCR1B = MMIO(0x81, u8, packed struct {
CS1: u3 = 0,
WGM12: u1 = 0,
WGM13: u1 = 0,
_: u1 = 0,
ICES1: u1 = 0,
ICNC1: u1 = 0,
});
pub const TCCR1A = MMIO(0x80, u8, packed struct {
WGM10: u1 = 0,
WGM11: u1 = 0,
_: u2 = 0,
COM1B: u2 = 0,
COM1A: u2 = 0,
});
pub const TCCR0B = MMIO(0x45, u8, packed struct {
CS0: u3 = 0,
WGM02: u1 = 0,
_: u2 = 0,
FOC0B: u1 = 0,
FOC0A: u1 = 0,
});
pub const TCCR0A = MMIO(0x44, u8, packed struct {
WGM00: u1 = 0,
WGM01: u1 = 0,
_: u2 = 0,
COM0B: u2 = 0,
COM0A: u2 = 0,
});
//Timer counter 2 8-bit
pub const TCNT2 = @intToPtr(*volatile u8, 0xB2);
// Compare registers
pub const OCR2B = @intToPtr(*volatile u8, 0xB4);
pub const OCR2A = @intToPtr(*volatile u8, 0xB3);
//Timer counter 0 8-bit
pub const TCNT0 = @intToPtr(*volatile u8, 0x46);
// Compare Registers
pub const OCR0B = @intToPtr(*volatile u8, 0x47);
pub const OCR0A = @intToPtr(*volatile u8, 0x46);
//Timer counter 1 16-bit
pub const OCR1BH = @intToPtr(*volatile u8, 0x8B);
pub const OCR1BL = @intToPtr(*volatile u8, 0x8A);
pub const OCR1AH = @intToPtr(*volatile u8, 0x89);
pub const OCR1AL = @intToPtr(*volatile u8, 0x88);
pub const ICR1H = @intToPtr(*volatile u8, 0x87);
pub const ICR1L = @intToPtr(*volatile u8, 0x86);
pub const TCNT1H = @intToPtr(*volatile u8, 0x85);
pub const TCNT1L = @intToPtr(*volatile u8, 0x84);
// Analog-to-digital converter
pub const ADMUX = MMIO(0x7C, u8, packed struct {
MUX: u4 = 0,
_: u1 = 0,
ADLAR: u1 = 0,
REFS: u2 = 0,
});
pub const ADCSRA = MMIO(0x7A, u8, packed struct {
ADPS: u3 = 0,
ADIE: u1 = 0,
ADIF: u1 = 0,
ADATE: u1 = 0,
ADSC: u1 = 0,
ADEN: u1 = 0,
});
pub const ADCH = @intToPtr(*volatile u8, 0x79);
pub const ADCL = @intToPtr(*volatile u8, 0x78);
//
const MCUCR = MMIO(0x55, u8, packed struct {
IVCE: u1 = 0,
IVSEL: u1 = 0,
_1: u2 = 0,
PUD: u1 = 0,
BODSE: u1 = 0,
BODS: u1 = 0,
_2: u1 = 0,
});
/// Set the configuration registers as expected by the PWM and ADC functions
/// set the timers same as standard arduino setup.
// (see https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c )
pub fn init() void {
// PUD bit (Pull Up Disable) Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf#G1184233*
// make sure the bit is disabled for pullup resitors to work
// (already the default after reset)
//var val = MCUCR.read();
//val.PUD = 0;
//MCUCR.write(val);
// set timers config (for PWM and time functions)
TCCR0A.write(.{ .WGM01 = 1, .WGM00 = 1 });
TCCR0B.write(.{ .CS0 = 3 });
TCCR1A.write(.{ .WGM10 = 1 });
TCCR1B.write(.{ .CS1 = 3 });
TCCR2A.write(.{ .WGM20 = 1 });
TCCR2B.write(.{ .CS2 = 4 });
// set the analog-to-digital converter config
ADCSRA.write(.{ .ADPS = 3, .ADEN = 1 }); // 16 MHz / 128 = 125 KHz
}
fn setBit(byte: u8, bit: u3, val: bool) u8 {
return if (val) (byte | @as(u8, 1) << bit) else (byte & ~(@as(u8, 1) << bit));
}
/// Configure the pin before use.
pub fn setMode(comptime pin: comptime_int, comptime mode: enum { input, output, input_pullup, output_analog }) void {
// set the IO direction:
const out = switch (mode) {
.input, .input_pullup => false,
.output, .output_analog => true,
};
switch (pin) {
0...7 => DDRD.writeInt(setBit(DDRD.readInt(), (pin - 0), out)),
8...13 => DDRB.writeInt(setBit(DDRB.readInt(), (pin - 8), out)),
14...19 => DDRC.writeInt(setBit(DDRC.readInt(), (pin - 14), out)),
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
// set PWM for the pin
const com = if (mode == .output_analog) 0b10 else 0; // "clear output on compare match"
switch (pin) {
6 => { // OC0A
var r = TCCR0A.read();
r.COM0A = com;
TCCR0A.write(r);
},
5 => { // OC0B
var r = TCCR0A.read();
r.COM0B = com;
TCCR0A.write(r);
},
9 => { // OC1A
var r = TCCR1A.read();
r.COM1A = com;
TCCR1A.write(r);
},
10 => { // OC1B
var r = TCCR1A.read();
r.COM1B = com;
TCCR1A.write(r);
},
11 => { // OC2A
var r = TCCR2A.read();
r.COM2A = com;
TCCR2A.write(r);
},
3 => { // OC2B
var r = TCCR2A.read();
r.COM2B = com;
TCCR2A.write(r);
},
else => if (mode == .output_analog) @compileError("Not a valid PWM pin (allowed pins 3,5,6,9,10,11)."),
}
if (mode == .input_pullup) {
setPin(pin, .high);
} else {
setPin(pin, .low);
}
}
pub const PinState = enum { low, high };
pub fn getPin(comptime pin: comptime_int) PinState {
const is_set = switch (pin) {
0...7 => (PIND.readInt() & (1 << (pin - 0))),
8...13 => (PINB.readInt() & (1 << (pin - 8))),
14...19 => (PINC.readInt() & (1 << (pin - 14))),
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
};
return if (is_set != 0) .high else .low;
}
pub fn setPin(comptime pin: comptime_int, value: PinState) void {
switch (pin) {
0...7 => PORTD.writeInt(setBit(PORTD.readInt(), (pin - 0), (value == .high))),
8...13 => PORTB.writeInt(setBit(PORTB.readInt(), (pin - 8), (value == .high))),
14...19 => PORTC.writeInt(setBit(PORTC.readInt(), (pin - 14), (value == .high))),
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
}
pub fn togglePin(comptime pin: comptime_int) void {
switch (pin) {
0...7 => PORTD.writeInt(PORTD.readInt() ^ (1 << (pin - 0))),
8...13 => PORTB.writeInt(PORTB.readInt() ^ (1 << (pin - 8))),
14...19 => PORTC.writeInt(PORTC.readInt() ^ (1 << (pin - 14))),
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
}
/// the pin must be configured in output_analog mode
pub fn setPinAnalog(comptime pin: comptime_int, value: u8) void {
if (value == 0) {
setPin(pin, .low);
} else if (value == 255) {
setPin(pin, .high);
} else switch (pin) {
6 => OCR0A.* = value,
5 => OCR0B.* = value,
9 => OCR1AL.* = value,
10 => OCR1BL.* = value,
11 => OCR2A.* = value,
3 => OCR2B.* = value,
else => @compileError("Not valid PWM pin (allowed pins 3,5,6,9,10,11)."),
}
}
pub fn getPinAnalog(comptime pin: comptime_int) u16 {
// set channel & avcc as ref
ADMUX.write(.{ .REFS = 1, .MUX = pin });
//start conversion
ADCSRA.write(.{ .ADPS = 3, .ADEN = 1, .ADSC = 1 });
//wait until conversion end
while (ADCSRA.read().ADSC == 1) {}
var adc_val: u16 = ADCL.*; // ! ADCL must be read before ADCH.
adc_val |= @as(u16, ADCH.*) << 8;
return adc_val;
} | src/gpio.zig |
const std = @import("std");
const c = @import("c.zig");
const ext = @import("externs.zig");
const data = @import("data.zig");
const HashedArrayList = @import("libs/hashed_array_list.zig").HashedArrayList;
// Public includes
/// Utilities to make life easier
pub const util = @import("util.zig");
/// A set of default bindings for the Wren configuration that provide basic functionality
pub const bindings = @import("bindings.zig");
/// Bindings for working with foreign methods
pub const foreign = @import("foreign.zig");
// Convenience Signatures
pub const CString = [*c]const u8;
pub const MethodFnSig = (?fn (?*VM) callconv(.C) void);
// Version
pub const VERSION_MAJOR = c.WREN_VERSION_MAJOR;
pub const VERSION_MINOR = c.WREN_VERSION_MINOR;
pub const VERSION_PATCH = c.WREN_VERSION_PATCH;
pub const VERSION_STRING = c.WREN_VERSION_STRING;
pub const VERSION_NUMBER = c.WREN_VERSION_NUMBER;
pub const version = struct {
pub const major:i32 = VERSION_MAJOR;
pub const minor:i32 = VERSION_MINOR;
pub const patch:i32 = VERSION_PATCH;
pub const string:[]const u8 = VERSION_STRING;
pub const number:f32 = VERSION_NUMBER;
};
// Types
/// A single virtual machine for executing Wren code.
/// Wren has no global state, so all state stored by a running interpreter lives
/// here.
pub const VM = c.WrenVM;
/// A handle to a Wren object.
/// This lets code outside of the VM hold a persistent reference to an object.
/// After a handle is acquired, and until it is released, this ensures the
/// garbage collector will not reclaim the object it references.
pub const Handle = c.WrenHandle;
/// A generic allocation function that handles all explicit memory management
/// used by Wren. It's used like so:
/// - To allocate new memory, [memory] is NULL and [newSize] is the desired
/// size. It should return the allocated memory or NULL on failure.
/// - To attempt to grow an existing allocation, [memory] is the memory, and
/// [newSize] is the desired size. It should return [memory] if it was able to
/// grow it in place, or a new pointer if it had to move it.
/// - To shrink memory, [memory] and [newSize] are the same as above but it will
/// always return [memory].
/// - To free memory, [memory] will be the memory to free and [newSize] will be
/// zero. It should return NULL.
pub const ReallocateFn = c.WrenReallocateFn;
/// A function callable from Wren code, but implemented in C.
pub const ForeignMethodFnC = c.WrenForeignMethodFn;
/// A Zig-signatured version of ForeignMethodFnC for convenience
pub const ForeignMethodFn = fn (?*VM) void;
/// A finalizer function for freeing resources owned by an instance of a foreign
/// class. Unlike most foreign methods, finalizers do not have access to the VM
/// and should not interact with it since it's in the middle of a garbage
/// collection.
pub const FinalizerFn = c.WrenFinalizerFn;
/// Gives the host a chance to canonicalize the imported module name,
/// potentially taking into account the (previously resolved) name of the module
/// that contains the import. Typically, this is used to implement relative
/// imports.
pub const ResolveModuleFn = c.WrenResolveModuleFn;
/// Gives the host a chance to canonicalize the imported module name,
/// potentially taking into account the (previously resolved) name of the module
/// that contains the import. Typically, this is used to implement relative
/// imports.
pub const LoadModuleCompleteFn = c.WrenLoadModuleCompleteFn;
/// The result of a loadModuleFn call.
/// [source] is the source code for the module, or NULL if the module is not found.
/// [onComplete] an optional callback that will be called once Wren is done with the result.
pub const LoadModuleResult = c.WrenLoadModuleResult;
/// Loads and returns the source code for the module [name].
pub const LoadModuleFn = c.WrenLoadModuleFn;
/// Returns a pointer to a foreign method on [className] in [module] with
/// [signature].
pub const BindForeignMethodFn = c.WrenBindForeignMethodFn;
/// Displays a string of text to the user.
pub const WriteFn = c.WrenWriteFn;
/// Reports an error to the user.
///
/// An error detected during compile time is reported by calling this once with
/// [type] `WREN_ERROR_COMPILE`, the resolved name of the [module] and [line]
/// where the error occurs, and the compiler's error [message].
///
/// A runtime error is reported by calling this once with [type]
/// `WREN_ERROR_RUNTIME`, no [module] or [line], and the runtime error's
/// [message]. After that, a series of [type] `ERROR_STACK_TRACE` calls are
/// made for each line in the stack trace. Each of those has the resolved
/// [module] and [line] where the method or function is defined and [message] is
/// the name of the method or function.
pub const ErrorFn = c.WrenErrorFn;
/// Returns a pair of pointers to the foreign methods used to allocate and
/// finalize the data for instances of [className] in resolved [module].
pub const ForeignClassMethods = c.WrenForeignClassMethods;
/// The callback Wren uses to find a foreign class and get its foreign methods.
///
/// When a foreign class is declared, this will be called with the class's
/// module and name when the class body is executed. It should return the
/// foreign functions uses to allocate and (optionally) finalize the bytes
/// stored in the foreign object when an instance is created.
pub const BindForeignClassFn = c.WrenBindForeignClassFn;
/// The VM configuration for Wren
pub const Configuration = c.WrenConfiguration;
/// The result type, maps to ResType enum.
pub const InterpretResult = c.WrenInterpretResult;
/// The error type, maps to ErrType enum
pub const ErrorType = c.WrenErrorType;
/// The slot data type, maps to DataType enum
pub const Type = c.WrenType;
// Kind-of-enums
pub const ERROR_COMPILE = c.WREN_ERROR_COMPILE;
pub const ERROR_RUNTIME = c.WREN_ERROR_RUNTIME;
pub const ERROR_STACK_TRACE = c.WREN_ERROR_STACK_TRACE;
pub const RESULT_SUCCESS = c.WREN_RESULT_SUCCESS;
pub const RESULT_COMPILE_ERROR = c.WREN_RESULT_COMPILE_ERROR;
pub const RESULT_RUNTIME_ERROR = c.WREN_RESULT_RUNTIME_ERROR;
pub const TYPE_BOOL = c.WREN_TYPE_BOOL;
pub const TYPE_NUM = c.WREN_TYPE_NUM;
pub const TYPE_FOREIGN = c.WREN_TYPE_FOREIGN;
pub const TYPE_LIST = c.WREN_TYPE_LIST;
pub const TYPE_MAP = c.WREN_TYPE_MAP;
pub const TYPE_NULL = c.WREN_TYPE_NULL;
pub const TYPE_STRING = c.WREN_TYPE_STRING;
pub const TYPE_UNKNOWN = c.WREN_TYPE_UNKNOWN;
// Common
/// Get the current wren version number.
///
/// Can be used to range checks over versions.
pub const getVersionNumber = ext.wrenGetVersionNumber;
/// Initializes [configuration] with all of its default values.
///
/// Call this before setting the particular fields you care about.
pub const initConfiguration = ext.wrenInitConfiguration;
/// Creates a new Wren virtual machine using the given [configuration]. Wren
/// will copy the configuration data, so the argument passed to this can be
/// freed after calling this. If [configuration] is `NULL`, uses a default
/// configuration.
pub const newVM = ext.wrenNewVM;
/// Disposes of all resources is use by [vm], which was previously created by a
/// call to [newVM].
pub const freeVM = ext.wrenFreeVM;
/// Immediately run the garbage collector to free unused memory.
pub const collectGarbage = ext.wrenCollectGarbage;
/// Runs [source], a string of Wren source code in a new fiber in [vm] in the
/// context of resolved [module].
pub const interpret = ext.wrenInterpret;
/// Creates a handle that can be used to invoke a method with [signature] on
/// using a receiver and arguments that are set up on the stack.
///
/// This handle can be used repeatedly to directly invoke that method from C
/// code using [wrenCall].
///
/// When you are done with this handle, it must be released using
/// [wrenReleaseHandle].
pub const makeCallHandle = ext.wrenMakeCallHandle;
/// Calls [method], using the receiver and arguments previously set up on the
/// stack.
///
/// [method] must have been created by a call to [makeCallHandle]. The
/// arguments to the method must be already on the stack. The receiver should be
/// in slot 0 with the remaining arguments following it, in order. It is an
/// error if the number of arguments provided does not match the method's
/// signature.
///
/// After this returns, you can access the return value from slot 0 on the stack.
pub const call = ext.wrenCall;
/// Releases the reference stored in [handle]. After calling this, [handle] can
/// no longer be used.
pub const releaseHandle = ext.wrenReleaseHandle;
/// Returns the number of slots available to the current foreign method.
pub const getSlotCount = ext.wrenGetSlotCount;
/// Ensures that the foreign method stack has at least [numSlots] available for
/// use, growing the stack if needed.
///
/// Does not shrink the stack if it has more than enough slots.
///
/// It is an error to call this from a finalizer.
pub const ensureSlots = ext.wrenEnsureSlots;
/// Gets the type of the object in [slot].
pub const getSlotType = ext.wrenGetSlotType;
/// Reads a boolean value from [slot].
///
/// It is an error to call this if the slot does not contain a boolean value.
pub const getSlotBool = ext.wrenGetSlotBool;
/// Reads a byte array from [slot].
///
/// The memory for the returned string is owned by Wren. You can inspect it
/// while in your foreign method, but cannot keep a pointer to it after the
/// function returns, since the garbage collector may reclaim it.
///
/// Returns a pointer to the first byte of the array and fill [length] with the
/// number of bytes in the array.
///
/// It is an error to call this if the slot does not contain a string.
pub const getSlotBytes = ext.wrenGetSlotBytes;
/// Reads a number from [slot].
///
/// It is an error to call this if the slot does not contain a number.
pub const getSlotDouble = ext.wrenGetSlotDouble;
/// Reads a foreign object from [slot] and returns a pointer to the foreign data
/// stored with it.
///
/// It is an error to call this if the slot does not contain an instance of a
/// foreign class.
pub const getSlotForeign = ext.wrenGetSlotForeign;
/// Reads a string from [slot].
///
/// The memory for the returned string is owned by Wren. You can inspect it
/// while in your foreign method, but cannot keep a pointer to it after the
/// function returns, since the garbage collector may reclaim it.
///
/// It is an error to call this if the slot does not contain a string.
pub const getSlotString = ext.wrenGetSlotString;
/// Creates a handle for the value stored in [slot].
///
/// This will prevent the object that is referred to from being garbage collected
/// until the handle is released by calling [releaseHandle()].
pub const getSlotHandle = ext.wrenGetSlotHandle;
/// Stores the boolean [value] in [slot].
pub const setSlotBool = ext.wrenSetSlotBool;
/// Stores the array [length] of [bytes] in [slot].
///
/// The bytes are copied to a new string within Wren's heap, so you can free
/// memory used by them after this is called.
pub const setSlotBytes = ext.wrenSetSlotBytes;
/// Stores the numeric [value] in [slot].
pub const setSlotDouble = ext.wrenSetSlotDouble;
/// Creates a new instance of the foreign class stored in [classSlot] with [size]
/// bytes of raw storage and places the resulting object in [slot].
///
/// This does not invoke the foreign class's constructor on the new instance. If
/// you need that to happen, call the constructor from Wren, which will then
/// call the allocator foreign method. In there, call this to create the object
/// and then the constructor will be invoked when the allocator returns.
///
/// Returns a pointer to the foreign object's data.
pub const setSlotNewForeign = ext.wrenSetSlotNewForeign;
/// Stores a new empty list in [slot].
pub const setSlotNewList = ext.wrenSetSlotNewList;
/// Stores a new empty map in [slot].
pub const setSlotNewMap = ext.wrenSetSlotNewMap;
/// Stores null in [slot].
pub const setSlotNull = ext.wrenSetSlotNull;
/// Stores the string [text] in [slot].
///
/// The [text] is copied to a new string within Wren's heap, so you can free
/// memory used by it after this is called. The length is calculated using
/// [strlen()]. If the string may contain any null bytes in the middle, then you
/// should use [setSlotBytes()] instead.
pub const setSlotString = ext.wrenSetSlotString;
/// Stores the value captured in [handle] in [slot].
///
/// This does not release the handle for the value.
pub const setSlotHandle = ext.wrenSetSlotHandle;
/// Returns the number of elements in the list stored in [slot].
pub const getListCount = ext.wrenGetListCount;
/// Reads element [index] from the list in [listSlot] and stores it in
/// [elementSlot].
pub const getListElement = ext.wrenGetListElement;
/// Sets the value stored at [index] in the list at [listSlot],
/// to the value from [elementSlot].
pub const setListElement = ext.wrenSetListElement;
/// Takes the value stored at [elementSlot] and inserts it into the list stored
/// at [listSlot] at [index].
///
/// As in Wren, negative indexes can be used to insert from the end. To append
/// an element, use `-1` for the index.
pub const insertInList = ext.wrenInsertInList;
/// Returns the number of entries in the map stored in [slot].
pub const getMapCount = ext.wrenGetMapCount;
/// Returns true if the key in [keySlot] is found in the map placed in [mapSlot].
pub const getMapContainsKey = ext.wrenGetMapContainsKey;
//EXTENSION: Returns the key into the [keySlot] and value into [valueSlot] of the
// map in [mapSlot] at the map index of [index]
pub const getMapElement = ext.wrenGetMapElement;
/// Retrieves a value with the key in [keySlot] from the map in [mapSlot] and
/// stores it in [valueSlot].
pub const getMapValue = ext.wrenGetMapValue;
/// Takes the value stored at [valueSlot] and inserts it into the map stored
/// at [mapSlot] with key [keySlot].
pub const setMapValue = ext.wrenSetMapValue;
/// Removes a value from the map in [mapSlot], with the key from [keySlot],
/// and place it in [removedValueSlot]. If not found, [removedValueSlot] is
/// set to null, the same behaviour as the Wren Map API.
pub const removeMapValue = ext.wrenRemoveMapValue;
/// Looks up the top level variable with [name] in resolved [module] and stores
/// it in [slot].
pub const getVariable = ext.wrenGetVariable;
/// Looks up the top level variable with [name] in resolved [module],
/// returns false if not found. The module must be imported at the time,
/// use wrenHasModule to ensure that before calling.
pub const hasVariable = ext.wrenHasVariable;
/// Returns true if [module] has been imported/resolved before, false if not.
pub const hasModule = ext.wrenHasModule;
/// Sets the current fiber to be aborted, and uses the value in [slot] as the
/// runtime error object.
pub const abortFiber = ext.wrenAbortFiber;
/// Returns the user data associated with the WrenVM.
pub const getUserData = ext.wrenGetUserData;
/// Sets user data associated with the WrenVM.
pub const setUserData = ext.wrenSetUserData;
// Meta extension
pub const metaSource = ext.wrenMetaSource;
pub const metaBindForeignMethod = ext.wrenMetaBindForeignMethod;
// Random extension
pub const randomSource = ext.wrenRandomSource;
pub const randomBindForeignClass = ext.wrenRandomBindForeignClass;
pub const randomBindForeignMethod = ext.wrenRandomBindForeignMethod;
//////////////////////////////////////////////////////////////////////////////
pub const ForeignMethod = struct {
module:[]const u8,
className:[]const u8,
signature:[]const u8,
isStatic:bool,
ptr:ForeignMethodFnC,
};
pub const ForeignClass = struct {
module:[]const u8,
className:[]const u8,
methods:ForeignClassMethods,
};
pub const AllocateFnSigC = (?fn (?*VM) callconv(.C) void);
pub const FinalizeFnSigC = (?fn (?*c_void) callconv(.C) void);
// Zig-style signatures, pointer casted into the C style when stored
pub const AllocateFnSig = (?fn (?*VM) void);
pub const FinalizeFnSig = (?fn (?*c_void) void);
/// Data type returned from slot-checking functions
pub const DataType = enum(u32) {
wren_bool = 0,
wren_num = 1,
wren_foreign = 2,
wren_list = 3,
wren_map = 4,
wren_null = 5,
wren_string = 6,
wren_unknown = 7,
};
/// Result from a wren call or code execution
pub const ResType = enum(u32) {
success = 0,
compile_error = 1,
runtime_error = 2,
};
/// Type of error
pub const ErrType = enum(u32) {
compile = 0,
runtime = 1,
stack_trace = 2,
};
//////////////////////////////////////////////////////////////////////////////
pub fn init(allocator:*std.mem.Allocator) void {
data.allocator = allocator;
data.method_lookup = HashedArrayList(usize,ForeignMethod).init(data.allocator);
data.class_lookup = HashedArrayList(usize,ForeignClass).init(data.allocator);
}
pub fn deinit() void {
data.method_lookup.deinit();
data.class_lookup.deinit();
}
/// See setSlotAuto.
/// Allows manual specification of a type in case the
/// value type doesn't match the desired type for some reason
pub fn setSlotAutoTyped(vm:?*VM,comptime T:type,slot:c_int,value:anytype) void {
comptime var is_str = std.meta.trait.isZigString(T);
comptime var is_cstr = util.isCString(T);
comptime var is_int = std.meta.trait.isIntegral(T);
comptime var is_bool = (T == bool);
if(is_str) {
// TODO: Convert this fn to an error union
var cvt = data.allocator.dupeZ(u8,value) catch unreachable;
setSlotString(vm,slot,cvt);
} else if(is_cstr) {
setSlotString(vm,slot,value);
} else if(is_bool) {
setSlotBool(vm,slot,value);
} else if(is_int) {
setSlotDouble(vm,slot,@intToFloat(f64,value));
} else {
setSlotDouble(vm,slot,@floatCast(f64,value));
}
}
/// Replacement for setSlot* for the basic value types that casts to the
/// type of data that Wren uses.
/// Does not handle lists or maps.
pub fn setSlotAuto(vm:?*VM,slot:c_int,value:anytype) void {
setSlotAutoTyped(vm,@TypeOf(value),slot,value);
}
/// Replacement for getSlot[type] for the basic value types that casts to the
/// requested Zig data type. Expects that the slot has data in a compatible
/// data type.
/// Does not handle lists or maps.
pub fn getSlotAuto(vm:?*VM,comptime T:type,slot:c_int) T {
comptime var is_str = util.isCString(T) or std.meta.trait.isZigString(T);
comptime var is_int = std.meta.trait.isIntegral(T);
comptime var is_bool = (T == bool);
if(is_str) {
return std.mem.span(getSlotString(vm,slot));
} else if(is_bool) {
return getSlotBool(vm,slot);
} else if(is_int) {
return @floatToInt(T,getSlotDouble(vm,slot));
} else {
return @floatCast(T,getSlotDouble(vm,slot));
}
}
//////////////////////////////////////////////////////////////////////////////
/// This is a handle to a method in Wren that can be used to call the method
/// and optionally get data back.
/// arg_types shoud be a tuple of the Zig-compatible argument types of the
/// Wren method, and the return type should be the type you want back, or null.
pub fn MethodCallHandle(
/// The module name, usually "main"
comptime module:[*c]const u8,
/// The class name
comptime className:[*c]const u8,
/// The signature of the method
comptime signature:[*c]const u8,
/// A tuple or types being passed to the method, in the same order as
/// they are defined in the method.
/// - This will handle data conversions between Wren and Zig.
/// - To pass a list, either use a typed slice for single-typed lists, or
/// pass a tuple of types for a multi-type list.
/// - Strings are recognized by std.meta.trait.isZigString, as well as
/// [*c]const u8 and [*c] u8.
comptime arg_types:anytype,
/// The Zig type being returned for the method. The same auto-casting
/// rules apply as arg_types. Tuples are not supported yet.
comptime ret_type:anytype
) type {
return struct {
const Self = @This();
vm:?*VM = undefined,
method_sig:?*Handle = undefined,
class_handle:?*Handle = undefined,
slots:u8 = 0,
/// Prepare the handle by grabbing all needed handles and signatures.
/// Small performance hit.
pub fn init (vm:?*VM) !Self {
var sig = makeCallHandle(vm,signature);
if(sig == null) {
return error.InvalidSignature;
}
ensureSlots(vm, 1);
getVariable(vm, module, className, 0);
var hnd = getSlotHandle(vm, 0);
if(hnd == null) {
return error.InvalidClass;
}
return Self {
.vm = vm,
.method_sig = sig,
.class_handle = hnd,
.slots = arg_types.len + 1
};
}
/// Releases the Wren handles
pub fn deinit (self:*Self) void {
releaseHandle(self.vm,self.method_sig);
releaseHandle(self.vm,self.class_handle);
}
/// Calls the method that this type defines with a tuple of given values
/// that match the type def.
/// What currently works:
/// - OUT/IN All number types (i8/i32/usize/f16/f64/etc)
/// - OUT/IN Bool
/// - OUT/IN Strings (as []const u8])
/// - OUT/ Null
/// - OUT/IN Single-typed lists (as slice)
/// - OUT/-- Multi-typed lists (as tuple)
/// - OUT/IN Maps (as a hashmap, AutoHashMap or StringHashMap)
pub fn callMethod (self:*Self, args:anytype) !ret_type {
// TODO: Change this to ensure what we actually need, not overage amount
ensureSlots(self.vm, self.slots + 2);
setSlotHandle(self.vm, 0, self.class_handle);
// Process out our arguments
// TODO: Chop this crap up into separate fns
inline for(arg_types) |v,i| {
switch(@typeInfo(v)) {
.Int => setSlotDouble(self.vm, i + 1, @intToFloat(f64,args[i])),
.Float => setSlotDouble(self.vm, i + 1, @floatCast(f64,args[i])),
.Bool => setSlotBool(self.vm, i + 1, args[i]),
.Null => setSlotNull(self.vm, i + 1, args[i]),
.Pointer => |ptr| {
//String, or slice of strings or values (Wren list)
comptime var is_str = util.isCString(v) or std.meta.trait.isZigString(v);
if(ptr.size == .Slice) {
if(is_str) {
setSlotAuto(self.vm,i + 1,args[i]);
} else {
setSlotNewList(self.vm,i + 1);
inline for(args[i]) |vx,ix| {
setSlotAuto(self.vm,i + 2,vx);
insertInList(self.vm,i + 1,@intCast(c_int,ix),i + 2);
}
}
}
},
.Struct => |st| {
if(!st.is_tuple) {
// HASHMAPS HERE
if(!util.isHashMap(v)) return error.UnsupportedParameterType;
setSlotNewMap(self.vm,i+1);
var it = args[i].iterator();
while(it.next()) |entry| {
setSlotAuto(self.vm,i + 2,entry.key_ptr.*);
setSlotAuto(self.vm,i + 3,entry.value_ptr.*);
setMapValue(self.vm,i + 1,i + 2,i + 3);
}
} else {
// Tuples, used to pass multi-type Wren lists
setSlotNewList(self.vm,i + 1);
inline for(args[i]) |vt,it| { //tuple index
setSlotAuto(self.vm,i + 2,vt);
insertInList(self.vm,i + 1,@intCast(c_int,it),i + 2);
}
}
},
else => return error.UnsupportedParameterType,
}
}
// Call method
var cres:InterpretResult = call(self.vm,self.method_sig);
switch(@intToEnum(ResType,cres)) {
.compile_error => return error.CompileError,
.runtime_error => return error.RuntimeError,
else => { },
}
// Read our return back in
if(ret_type == void) return;
switch(@typeInfo(ret_type)) {
.Int => return @floatToInt(ret_type,getSlotDouble(self.vm,0)),
.Float => return @floatCast(ret_type,getSlotDouble(self.vm,0)),
.Bool => return getSlotBool(self.vm,0),
.Pointer => |ptr| {
comptime var T = ptr.child;
comptime var is_str = util.isCString(ret_type) or std.meta.trait.isZigString(ret_type);
if(ptr.size == .Slice) {
// String
if(is_str) {
return getSlotAuto(self.vm,ret_type,0);
}
// Single-type list(as slice)
ensureSlots(self.vm,2);
var idx:c_int = 0;
var list = std.ArrayList(T).init(data.allocator);
while(idx < getListCount(self.vm,0)) : (idx += 1) {
getListElement(self.vm,0,idx,1);
try list.append(getSlotAuto(self.vm,T,1));
}
return list.toOwnedSlice();
}
},
.Struct => |st| {
if (!st.is_tuple) {
// Hashmap
if(!util.isHashMap(ret_type)) return error.UnsupportedReturnType;
const kv_type = util.getHashMapTypes(ret_type);
var map = ret_type.init(data.allocator);
ensureSlots(self.vm,3);
var idx:c_int = 0;
var mc = getMapCount(self.vm,0);
while(idx < mc) : (idx += 1) {
getMapElement(self.vm,0,idx,1,2);
try map.put(getSlotAuto(self.vm,kv_type.key,1),
getSlotAuto(self.vm,kv_type.value,2));
}
return map;
} else {
//Tuple
// Not sure how to build the data in runtime?
//std.meta.Tuple
return error.UnsupportedReturnType;
}
},
else => return error.UnsupportedReturnType,
}
}
};
} | src/wren.zig |
const Allocator = std.mem.Allocator;
const Headers = @import("http").Headers;
const ParsingError = @import("errors.zig").ParsingError;
const std = @import("std");
pub fn parse(allocator: *Allocator, buffer: []const u8, max_headers: usize) ParsingError!Headers {
var remaining_bytes = buffer[0..];
var headers = Headers.init(allocator);
errdefer headers.deinit();
while (true) {
if (remaining_bytes.len < 2) {
return error.Invalid;
}
if (remaining_bytes[0] == '\r' and remaining_bytes[1] == '\n') {
break;
}
if (headers.len() >= max_headers) {
return error.TooManyHeaders;
}
var name_end = std.mem.indexOfScalar(u8, remaining_bytes, ':') orelse return error.Invalid;
var name = remaining_bytes[0..name_end];
remaining_bytes = remaining_bytes[name_end + 1 ..];
var value_end = std.mem.indexOf(u8, remaining_bytes, "\r\n") orelse return error.Invalid;
var value = remaining_bytes[0..value_end];
if (std.ascii.isBlank(value[0])) {
value = value[1..];
}
try headers.append(name, value);
remaining_bytes = remaining_bytes[value_end + 2 ..];
}
return headers;
}
const expect = std.testing.expect;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectError = std.testing.expectError;
test "Parse - Single header - Success" {
const content = "Content-Length: 10\r\n\r\n";
var headers = try parse(std.testing.allocator, content, 1);
defer headers.deinit();
const header = headers.items()[0];
try expectEqualStrings(header.name.raw(), "Content-Length");
try expectEqualStrings(header.value, "10");
}
test "Parse - No header - Success" {
const content = "\r\n";
var headers = try parse(std.testing.allocator, content, 1);
defer headers.deinit();
try expect(headers.len() == 0);
}
test "Parse - Multiple headers - Success" {
const content = "Content-Length: 10\r\nServer: Apache\r\n\r\n";
var headers = try parse(std.testing.allocator, content, 2);
defer headers.deinit();
const content_length = headers.items()[0];
try expectEqualStrings(content_length.name.raw(), "Content-Length");
try expectEqualStrings(content_length.value, "10");
const server = headers.items()[1];
try expectEqualStrings(server.name.raw(), "Server");
try expectEqualStrings(server.value, "Apache");
}
test "Parse - Ignore a missing whitespace between the semicolon and the header value - Success" {
const content = "Content-Length:10\r\n\r\n";
var headers = try parse(std.testing.allocator, content, 1);
defer headers.deinit();
const header = headers.items()[0];
try expectEqualStrings(header.name.raw(), "Content-Length");
try expectEqualStrings(header.value, "10");
}
test "Parse - When the last CRLF after the headers is missing - Returns Invalid" {
const content = "Content-Length: 10\r\n";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.Invalid, fail);
}
test "Parse - When a header's name does not end with a semicolon - Returns Invalid" {
const content = "Content-Length";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.Invalid, fail);
}
test "Parse - When a header's value does not exist - Returns Invalid" {
const content = "Content-Length:";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.Invalid, fail);
}
test "Parse - When parsing more headers than expected - Returns TooManyHeaders" {
const content = "Content-Length: 10\r\nServer: Apache\r\n\r\n";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.TooManyHeaders, fail);
}
test "Parse - Invalid character in the header's name - Returns InvalidHeaderName" {
const content = "Cont(ent-Length: 10\r\n\r\n";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.InvalidHeaderName, fail);
}
test "Parse - Invalid character in the header's value - Returns InvalidHeaderValue" {
const content = "My-Header: I\nvalid\r\n";
const fail = parse(std.testing.allocator, content, 1);
try expectError(error.InvalidHeaderValue, fail);
} | src/events/headers.zig |
const std = @import("std");
const assert = std.debug.assert;
const fmt = std.fmt;
const mem = std.mem;
const meta = std.meta;
const net = std.net;
const os = std.os;
const config = @import("config.zig");
const vsr = @import("vsr.zig");
const usage = fmt.comptimePrint(
\\Usage:
\\
\\ tigerbeetle [-h | --help]
\\
\\ tigerbeetle init [--directory=<path>] --cluster=<integer> --replica=<index>
\\
\\ tigerbeetle start [--directory=<path>] --cluster=<integer> --replica=<index> --addresses=<addresses>
\\
\\Commands:
\\
\\ init Create a new .tigerbeetle data file. Requires the --cluster and
\\ --replica options. The file will be created in the path set by
\\ the --directory option if provided. Otherwise, it will be created in
\\ the default {[default_directory]s}.
\\
\\ start Run a TigerBeetle replica as part of the cluster specified by the
\\ --cluster, --replica, and --addresses options. This requires an
\\ existing .tigerbeetle data file, either in the default
\\ {[default_directory]s} or the path set with --directory.
\\
\\Options:
\\
\\ -h, --help
\\ Print this help message and exit.
\\
\\ --directory=<path>
\\ Set the directory used to store .tigerbeetle data files. If this option is
\\ omitted, the default {[default_directory]s} will be used.
\\
\\ --cluster=<integer>
\\ Set the cluster ID to the provided 32-bit unsigned integer.
\\
\\ --replica=<index>
\\ Set the zero-based index that will be used for this replica process.
\\ The value of this option will be interpreted as an index into the --addresses array.
\\
\\ --addresses=<addresses>
\\ Set the addresses of all replicas in the cluster. Accepts a
\\ comma-separated list of IPv4 addresses with port numbers.
\\ Either the IPv4 address or port number, but not both, may be
\\ ommited in which case a default of {[default_address]s} or {[default_port]d}
\\ will be used.
\\
\\Examples:
\\
\\ tigerbeetle init --cluster=0 --replica=0 --directory=/var/lib/tigerbeetle
\\ tigerbeetle init --cluster=0 --replica=1 --directory=/var/lib/tigerbeetle
\\ tigerbeetle init --cluster=0 --replica=2 --directory=/var/lib/tigerbeetle
\\
\\ tigerbeetle start --cluster=0 --replica=0 --addresses=127.0.0.1:3003,127.0.0.1:3001,127.0.0.1:3002
\\ tigerbeetle start --cluster=0 --replica=1 --addresses=3003,3001,3002
\\ tigerbeetle start --cluster=0 --replica=2 --addresses=3003,3001,3002
\\
\\ tigerbeetle start --cluster=1 --replica=0 --addresses=192.168.0.1,192.168.0.2,192.168.0.3
\\
, .{
.default_directory = config.directory,
.default_address = config.address,
.default_port = config.port,
});
pub const Command = union(enum) {
init: struct {
cluster: u32,
replica: u8,
dir_fd: os.fd_t,
},
start: struct {
cluster: u32,
replica: u8,
addresses: []net.Address,
dir_fd: os.fd_t,
},
};
/// Parse the command line arguments passed to the tigerbeetle binary.
/// Exits the program with a non-zero exit code if an error is found.
pub fn parse_args(allocator: *std.mem.Allocator) Command {
var maybe_cluster: ?[]const u8 = null;
var maybe_replica: ?[]const u8 = null;
var maybe_addresses: ?[]const u8 = null;
var maybe_directory: ?[:0]const u8 = null;
var args = std.process.args();
// Skip argv[0] which is the name of this executable
_ = args.nextPosix();
const raw_command = args.nextPosix() orelse
fatal("no command provided, expected 'start' or 'init'", .{});
if (mem.eql(u8, raw_command, "-h") or mem.eql(u8, raw_command, "--help")) {
std.io.getStdOut().writeAll(usage) catch os.exit(1);
os.exit(0);
}
const command = meta.stringToEnum(meta.Tag(Command), raw_command) orelse
fatal("unknown command '{s}', expected 'start' or 'init'", .{raw_command});
while (args.nextPosix()) |arg| {
if (mem.startsWith(u8, arg, "--cluster")) {
maybe_cluster = parse_flag("--cluster", arg);
} else if (mem.startsWith(u8, arg, "--replica")) {
maybe_replica = parse_flag("--replica", arg);
} else if (mem.startsWith(u8, arg, "--addresses")) {
maybe_addresses = parse_flag("--addresses", arg);
} else if (mem.startsWith(u8, arg, "--directory")) {
maybe_directory = parse_flag("--directory", arg);
} else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
std.io.getStdOut().writeAll(usage) catch os.exit(1);
os.exit(0);
} else {
fatal("unexpected argument: '{s}'", .{arg});
}
}
const raw_cluster = maybe_cluster orelse fatal("required argument: --cluster", .{});
const raw_replica = maybe_replica orelse fatal("required argument: --replica", .{});
const cluster = parse_cluster(raw_cluster);
const replica = parse_replica(raw_replica);
const dir_path = maybe_directory orelse config.directory;
const dir_fd = os.openZ(dir_path, os.O_CLOEXEC | os.O_RDONLY, 0) catch |err|
fatal("failed to open directory '{s}': {}", .{ dir_path, err });
switch (command) {
.init => {
if (maybe_addresses != null) {
fatal("--addresses: supported only by 'start' command", .{});
}
return .{ .init = .{
.cluster = cluster,
.replica = replica,
.dir_fd = dir_fd,
} };
},
.start => {
const raw_addresses = maybe_addresses orelse
fatal("required argument: --addresses", .{});
const addresses = parse_addresses(allocator, raw_addresses);
if (replica >= addresses.len) {
fatal("--replica: value greater than length of --addresses array", .{});
}
return .{ .start = .{
.cluster = cluster,
.replica = replica,
.addresses = addresses,
.dir_fd = dir_fd,
} };
},
}
}
/// Format and print an error message followed by the usage string to stderr,
/// then exit with an exit code of 1.
fn fatal(comptime fmt_string: []const u8, args: anytype) noreturn {
const stderr = std.io.getStdErr().writer();
stderr.print("error: " ++ fmt_string ++ "\n", args) catch {};
os.exit(1);
}
/// Parse e.g. `--cluster=1a2b3c` into `1a2b3c` with error handling.
fn parse_flag(comptime flag: []const u8, arg: [:0]const u8) [:0]const u8 {
const value = arg[flag.len..];
if (value.len < 2) {
fatal("{s} argument requires a value", .{flag});
}
if (value[0] != '=') {
fatal("expected '=' after {s} but found '{c}'", .{ flag, value[0] });
}
return value[1..];
}
fn parse_cluster(raw_cluster: []const u8) u32 {
const cluster = fmt.parseUnsigned(u32, raw_cluster, 10) catch |err| switch (err) {
error.Overflow => fatal("--cluster: value exceeds a 32-bit unsigned integer", .{}),
error.InvalidCharacter => fatal("--cluster: value contains an invalid character", .{}),
};
return cluster;
}
/// Parse and allocate the addresses returning a slice into that array.
fn parse_addresses(allocator: *std.mem.Allocator, raw_addresses: []const u8) []net.Address {
return vsr.parse_addresses(allocator, raw_addresses) catch |err| switch (err) {
error.AddressHasTrailingComma => fatal("--addresses: invalid trailing comma", .{}),
error.AddressLimitExceeded => {
fatal("--addresses: too many addresses, at most {d} are allowed", .{
config.replicas_max,
});
},
error.AddressHasMoreThanOneColon => {
fatal("--addresses: invalid address with more than one colon", .{});
},
error.PortOverflow => fatal("--addresses: port exceeds 65535", .{}),
error.PortInvalid => fatal("--addresses: invalid port", .{}),
error.AddressInvalid => fatal("--addresses: invalid IPv4 address", .{}),
error.OutOfMemory => fatal("--addresses: out of memory", .{}),
};
}
fn parse_replica(raw_replica: []const u8) u8 {
comptime assert(config.replicas_max <= std.math.maxInt(u8));
const replica = fmt.parseUnsigned(u8, raw_replica, 10) catch |err| switch (err) {
error.Overflow => fatal("--replica: value exceeds an 8-bit unsigned integer", .{}),
error.InvalidCharacter => fatal("--replica: value contains an invalid character", .{}),
};
return replica;
} | src/cli.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Compilation = @import("Compilation.zig");
const llvm = @import("llvm_bindings.zig");
const link = @import("link.zig");
const Module = @import("Module.zig");
const TypedValue = @import("TypedValue.zig");
const ir = @import("ir.zig");
const Inst = ir.Inst;
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
pub fn targetTriple(allocator: *Allocator, target: std.Target) ![:0]u8 {
const llvm_arch = switch (target.cpu.arch) {
.arm => "arm",
.armeb => "armeb",
.aarch64 => "aarch64",
.aarch64_be => "aarch64_be",
.aarch64_32 => "aarch64_32",
.arc => "arc",
.avr => "avr",
.bpfel => "bpfel",
.bpfeb => "bpfeb",
.hexagon => "hexagon",
.mips => "mips",
.mipsel => "mipsel",
.mips64 => "mips64",
.mips64el => "mips64el",
.msp430 => "msp430",
.powerpc => "powerpc",
.powerpc64 => "powerpc64",
.powerpc64le => "powerpc64le",
.r600 => "r600",
.amdgcn => "amdgcn",
.riscv32 => "riscv32",
.riscv64 => "riscv64",
.sparc => "sparc",
.sparcv9 => "sparcv9",
.sparcel => "sparcel",
.s390x => "s390x",
.tce => "tce",
.tcele => "tcele",
.thumb => "thumb",
.thumbeb => "thumbeb",
.i386 => "i386",
.x86_64 => "x86_64",
.xcore => "xcore",
.nvptx => "nvptx",
.nvptx64 => "nvptx64",
.le32 => "le32",
.le64 => "le64",
.amdil => "amdil",
.amdil64 => "amdil64",
.hsail => "hsail",
.hsail64 => "hsail64",
.spir => "spir",
.spir64 => "spir64",
.kalimba => "kalimba",
.shave => "shave",
.lanai => "lanai",
.wasm32 => "wasm32",
.wasm64 => "wasm64",
.renderscript32 => "renderscript32",
.renderscript64 => "renderscript64",
.ve => "ve",
.spu_2 => return error.LLVMBackendDoesNotSupportSPUMarkII,
};
// TODO Add a sub-arch for some architectures depending on CPU features.
const llvm_os = switch (target.os.tag) {
.freestanding => "unknown",
.ananas => "ananas",
.cloudabi => "cloudabi",
.dragonfly => "dragonfly",
.freebsd => "freebsd",
.fuchsia => "fuchsia",
.ios => "ios",
.kfreebsd => "kfreebsd",
.linux => "linux",
.lv2 => "lv2",
.macos => "macosx",
.netbsd => "netbsd",
.openbsd => "openbsd",
.solaris => "solaris",
.windows => "windows",
.haiku => "haiku",
.minix => "minix",
.rtems => "rtems",
.nacl => "nacl",
.cnk => "cnk",
.aix => "aix",
.cuda => "cuda",
.nvcl => "nvcl",
.amdhsa => "amdhsa",
.ps4 => "ps4",
.elfiamcu => "elfiamcu",
.tvos => "tvos",
.watchos => "watchos",
.mesa3d => "mesa3d",
.contiki => "contiki",
.amdpal => "amdpal",
.hermit => "hermit",
.hurd => "hurd",
.wasi => "wasi",
.emscripten => "emscripten",
.uefi => "windows",
.other => "unknown",
};
const llvm_abi = switch (target.abi) {
.none => "unknown",
.gnu => "gnu",
.gnuabin32 => "gnuabin32",
.gnuabi64 => "gnuabi64",
.gnueabi => "gnueabi",
.gnueabihf => "gnueabihf",
.gnux32 => "gnux32",
.code16 => "code16",
.eabi => "eabi",
.eabihf => "eabihf",
.android => "android",
.musl => "musl",
.musleabi => "musleabi",
.musleabihf => "musleabihf",
.msvc => "msvc",
.itanium => "itanium",
.cygnus => "cygnus",
.coreclr => "coreclr",
.simulator => "simulator",
.macabi => "macabi",
};
return std.fmt.allocPrintZ(allocator, "{}-unknown-{}-{}", .{ llvm_arch, llvm_os, llvm_abi });
}
pub const LLVMIRModule = struct {
module: *Module,
llvm_module: *const llvm.ModuleRef,
target_machine: *const llvm.TargetMachineRef,
builder: *const llvm.BuilderRef,
output_path: []const u8,
gpa: *Allocator,
err_msg: ?*Compilation.ErrorMsg = null,
pub fn create(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*LLVMIRModule {
const self = try allocator.create(LLVMIRModule);
errdefer allocator.destroy(self);
const gpa = options.module.?.gpa;
initializeLLVMTargets();
const root_nameZ = try gpa.dupeZ(u8, options.root_name);
defer gpa.free(root_nameZ);
const llvm_module = llvm.ModuleRef.createWithName(root_nameZ.ptr);
errdefer llvm_module.disposeModule();
const llvm_target_triple = try targetTriple(gpa, options.target);
defer gpa.free(llvm_target_triple);
var error_message: [*:0]const u8 = undefined;
var target_ref: *const llvm.TargetRef = undefined;
if (llvm.TargetRef.getTargetFromTriple(llvm_target_triple.ptr, &target_ref, &error_message)) {
defer llvm.disposeMessage(error_message);
const stderr = std.io.getStdErr().outStream();
try stderr.print(
\\Zig is expecting LLVM to understand this target: '{s}'
\\However LLVM responded with: "{s}"
\\Zig is unable to continue. This is a bug in Zig:
\\https://github.com/ziglang/zig/issues/438
\\
,
.{
llvm_target_triple,
error_message,
},
);
return error.InvalidLLVMTriple;
}
const opt_level: llvm.CodeGenOptLevel = if (options.optimize_mode == .Debug) .None else .Aggressive;
const target_machine = llvm.TargetMachineRef.createTargetMachine(
target_ref,
llvm_target_triple.ptr,
"",
"",
opt_level,
.Static,
.Default,
);
errdefer target_machine.disposeTargetMachine();
const builder = llvm.BuilderRef.createBuilder();
errdefer builder.disposeBuilder();
self.* = .{
.module = options.module.?,
.llvm_module = llvm_module,
.target_machine = target_machine,
.builder = builder,
.output_path = sub_path,
.gpa = gpa,
};
return self;
}
pub fn deinit(self: *LLVMIRModule, allocator: *Allocator) void {
self.builder.disposeBuilder();
self.target_machine.disposeTargetMachine();
self.llvm_module.disposeModule();
allocator.destroy(self);
}
fn initializeLLVMTargets() void {
llvm.initializeAllTargets();
llvm.initializeAllTargetInfos();
llvm.initializeAllTargetMCs();
llvm.initializeAllAsmPrinters();
llvm.initializeAllAsmParsers();
}
pub fn flushModule(self: *LLVMIRModule, comp: *Compilation) !void {
if (comp.verbose_llvm_ir) {
const dump = self.llvm_module.printToString();
defer llvm.disposeMessage(dump);
const stderr = std.io.getStdErr().outStream();
try stderr.writeAll(std.mem.spanZ(dump));
}
{
var error_message: [*:0]const u8 = undefined;
// verifyModule always allocs the error_message even if there is no error
defer llvm.disposeMessage(error_message);
if (self.llvm_module.verifyModule(.ReturnStatus, &error_message)) {
const stderr = std.io.getStdErr().outStream();
try stderr.print("broken LLVM module found: {s}\nThis is a bug in the Zig compiler.", .{error_message});
return error.BrokenLLVMModule;
}
}
const output_pathZ = try self.gpa.dupeZ(u8, self.output_path);
defer self.gpa.free(output_pathZ);
var error_message: [*:0]const u8 = undefined;
// TODO: where to put the output object, zig-cache something?
// TODO: caching?
if (self.target_machine.emitToFile(
self.llvm_module,
output_pathZ.ptr,
.ObjectFile,
&error_message,
)) {
defer llvm.disposeMessage(error_message);
const stderr = std.io.getStdErr().outStream();
try stderr.print("LLVM failed to emit file: {s}\n", .{error_message});
return error.FailedToEmit;
}
}
pub fn updateDecl(self: *LLVMIRModule, module: *Module, decl: *Module.Decl) !void {
const typed_value = decl.typed_value.most_recent.typed_value;
self.gen(module, typed_value, decl.src()) catch |err| switch (err) {
error.CodegenFail => {
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, self.err_msg.?);
return;
},
else => |e| return e,
};
}
fn gen(self: *LLVMIRModule, module: *Module, typed_value: TypedValue, src: usize) !void {
switch (typed_value.ty.zigTypeTag()) {
.Fn => {
const func = typed_value.val.cast(Value.Payload.Function).?.func;
const llvm_func = try self.resolveLLVMFunction(func);
// We remove all the basic blocks of a function to support incremental
// compilation!
// TODO: remove all basic blocks if functions can have more than one
if (llvm_func.getFirstBasicBlock()) |bb| {
bb.deleteBasicBlock();
}
const entry_block = llvm_func.appendBasicBlock("Entry");
self.builder.positionBuilderAtEnd(entry_block);
const instructions = func.analysis.success.instructions;
for (instructions) |inst| {
switch (inst.tag) {
.breakpoint => try self.genBreakpoint(inst.castTag(.breakpoint).?),
.call => try self.genCall(inst.castTag(.call).?),
.unreach => self.genUnreach(inst.castTag(.unreach).?),
.retvoid => self.genRetVoid(inst.castTag(.retvoid).?),
.arg => self.genArg(inst.castTag(.arg).?),
.dbg_stmt => {
// TODO: implement debug info
},
else => |tag| return self.fail(src, "TODO implement LLVM codegen for Zir instruction: {}", .{tag}),
}
}
},
else => |ty| return self.fail(src, "TODO implement LLVM codegen for top-level decl type: {}", .{ty}),
}
}
fn genCall(self: *LLVMIRModule, inst: *Inst.Call) !void {
if (inst.func.cast(Inst.Constant)) |func_inst| {
if (func_inst.val.cast(Value.Payload.Function)) |func_val| {
const func = func_val.func;
const zig_fn_type = func.owner_decl.typed_value.most_recent.typed_value.ty;
const llvm_fn = try self.resolveLLVMFunction(func);
const num_args = inst.args.len;
const llvm_param_vals = try self.gpa.alloc(*const llvm.ValueRef, num_args);
defer self.gpa.free(llvm_param_vals);
for (inst.args) |arg, i| {
llvm_param_vals[i] = try self.resolveInst(arg);
}
// TODO: LLVMBuildCall2 handles opaque function pointers, according to llvm docs
// Do we need that?
const call = self.builder.buildCall(
llvm_fn,
if (num_args == 0) null else llvm_param_vals.ptr,
@intCast(c_uint, num_args),
"",
);
if (zig_fn_type.fnReturnType().zigTypeTag() == .NoReturn) {
_ = self.builder.buildUnreachable();
}
}
}
}
fn genRetVoid(self: *LLVMIRModule, inst: *Inst.NoOp) void {
_ = self.builder.buildRetVoid();
}
fn genUnreach(self: *LLVMIRModule, inst: *Inst.NoOp) void {
_ = self.builder.buildUnreachable();
}
fn genArg(self: *LLVMIRModule, inst: *Inst.Arg) void {
// TODO: implement this
}
fn genBreakpoint(self: *LLVMIRModule, inst: *Inst.NoOp) !void {
// TODO: Store this function somewhere such that we dont have to add it again
const fn_type = llvm.TypeRef.functionType(llvm.voidType(), null, 0, false);
const func = self.llvm_module.addFunction("llvm.debugtrap", fn_type);
// TODO: add assertion: LLVMGetIntrinsicID
_ = self.builder.buildCall(func, null, 0, "");
}
fn resolveInst(self: *LLVMIRModule, inst: *ir.Inst) !*const llvm.ValueRef {
if (inst.castTag(.constant)) |const_inst| {
return self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
}
return self.fail(inst.src, "TODO implement resolveInst", .{});
}
fn genTypedValue(self: *LLVMIRModule, src: usize, typed_value: TypedValue) !*const llvm.ValueRef {
const llvm_type = self.getLLVMType(typed_value.ty);
if (typed_value.val.isUndef())
return llvm_type.getUndef();
switch (typed_value.ty.zigTypeTag()) {
.Bool => return if (typed_value.val.toBool()) llvm_type.constAllOnes() else llvm_type.constNull(),
else => return self.fail(src, "TODO implement const of type '{}'", .{typed_value.ty}),
}
}
/// If the llvm function does not exist, create it
fn resolveLLVMFunction(self: *LLVMIRModule, func: *Module.Fn) !*const llvm.ValueRef {
// TODO: do we want to store this in our own datastructure?
if (self.llvm_module.getNamedFunction(func.owner_decl.name)) |llvm_fn| return llvm_fn;
const zig_fn_type = func.owner_decl.typed_value.most_recent.typed_value.ty;
const return_type = zig_fn_type.fnReturnType();
const fn_param_len = zig_fn_type.fnParamLen();
const fn_param_types = try self.gpa.alloc(Type, fn_param_len);
defer self.gpa.free(fn_param_types);
zig_fn_type.fnParamTypes(fn_param_types);
const llvm_param = try self.gpa.alloc(*const llvm.TypeRef, fn_param_len);
defer self.gpa.free(llvm_param);
for (fn_param_types) |fn_param, i| {
llvm_param[i] = self.getLLVMType(fn_param);
}
const fn_type = llvm.TypeRef.functionType(
self.getLLVMType(return_type),
if (fn_param_len == 0) null else llvm_param.ptr,
@intCast(c_uint, fn_param_len),
false,
);
const llvm_fn = self.llvm_module.addFunction(func.owner_decl.name, fn_type);
if (return_type.zigTypeTag() == .NoReturn) {
llvm_fn.addFnAttr("noreturn");
}
return llvm_fn;
}
fn getLLVMType(self: *LLVMIRModule, t: Type) *const llvm.TypeRef {
switch (t.zigTypeTag()) {
.Void => return llvm.voidType(),
.NoReturn => return llvm.voidType(),
.Int => {
const info = t.intInfo(self.module.getTarget());
return llvm.intType(info.bits);
},
.Bool => return llvm.intType(1),
else => unreachable,
}
}
pub fn fail(self: *LLVMIRModule, src: usize, comptime format: []const u8, args: anytype) error{ OutOfMemory, CodegenFail } {
@setCold(true);
std.debug.assert(self.err_msg == null);
self.err_msg = try Compilation.ErrorMsg.create(self.gpa, src, format, args);
return error.CodegenFail;
}
}; | src/llvm_backend.zig |
const std = @import("std");
const default_block_size = 0x2000;
const Superblock = struct {
inode_count: u32,
block_count: u32,
superuser_reserved_block_count: u32,
unallocated_block_count: u32,
unallocated_inode_count: u32,
superblock_block_number: u32,
log2_block_size: u32,
log2_fragment_size: u32,
block_group_block_count: u32,
block_group_fragment_count: u32,
block_group_inode_count: u32,
last_mount_time: u32,
last_written_time: u32,
mount_count_since_last_consistency_check: u16,
mount_count_allowed_before_consistency_check: u16,
ext2_signature: u16,
filesystem_state: u16,
error_handling_method: u16,
version_minor: u16,
last_consistency_check_time: u32,
interval_between_forced_consistency_checks: u32,
operating_system_id: u32,
version_major: u32,
user_id: u16,
group_id: u16,
const offset = 0x400;
const size = 0x400;
pub fn get_block_group_count(superblock: *Superblock) u64 {
const block_group_count = (superblock.block_count / superblock.block_group_block_count) + @boolToInt(superblock.block_count % superblock.block_group_block_count != 0);
const inode_group_count = (superblock.inode_count / superblock.block_group_inode_count) + @boolToInt(superblock.inode_count % superblock.block_group_inode_count != 0);
return block_group_count + inode_group_count;
}
pub fn get_from_memory(bytes: []const u8) *Superblock {
return @ptrCast(*Superblock, @alignCast(@alignOf(Superblock), bytes.ptr));
}
// TODO: handle corruption
pub fn get_filesystem_state(superblock: *Superblock) FilesystemState {
return @intToEnum(FilesystemState, superblock.filesystem_state);
}
// TODO: handle corruption
pub fn get_error_handling_method(superblock: *Superblock) ErrorHandlingMethod {
return @intToEnum(ErrorHandlingMethod, superblock.error_handling_method);
}
};
const FilesystemState = enum(u16) {
clean = 1,
errors = 2,
};
const ErrorHandlingMethod = enum(u16) {
ignore = 1,
remount_filesystem_as_readonly = 2,
panic = 3,
};
// TODO: extended
const BlockGroup = struct {
const Descriptor = struct {
block_usage_bitmap_block_address: u32,
inode_usage_bitmap_block_address: u32,
inode_table_starting_block_address: u32,
unallocated_block_count: u16,
unallocated_inode_count: u16,
directory_count: u16,
padding: [14]u8,
};
const descriptor_table_byte_offset = Superblock.offset + Superblock.size;
};
const INode = struct {
type_and_permissions: u16,
user_id: u16,
size_lower: u32,
last_access_time: u32,
creation_time: u32,
last_modification_time: u32,
deletion_time: u32,
group_id: u16,
hard_link_count: u16, // When this reaches 0, the data blocks are marked as unallocated
disk_sector_count: u32, //not counting the actual inode structure nor directory entries linking to the inode.
flags: u32,
os_specific1: u32,
direct_block_pointers: [12]u32,
singly_indirect_block_pointer: u32,
doubly_indirect_block_pointer: u32,
triply_indirect_block_pointer: u32,
generation_number: u32,
// not if version >= 1
reserved1: u32,
// not if version >= 1
reserved2: u32,
fragment_block_address: u32,
os_specific2: [12]u8,
};
const INodeType = enum(u16) {
fifo = 0x1000,
character_device = 0x2000,
directory = 0x4000,
block_device = 0x6000,
regular_file = 0x8000,
symbolic_link = 0xa000,
unix_socket = 0xc000,
};
const INodePermission = enum(u16) {
other_execute = 0x0001,
other_write = 0x0002,
other_read = 0x0004,
group_execute = 0x0008,
group_write = 0x0010,
group_read = 0x0020,
user_execute = 0x0040,
user_write = 0x0080,
user_read = 0x0100,
sticky_bit = 0x200,
set_group_id = 0x400,
set_user_id = 0x800,
}; | src/common/ext2.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const glfw = @import("glfw");
const gpu = @import("gpu");
pub const VSyncMode = enum {
/// Potential screen tearing.
/// No synchronization with monitor, render frames as fast as possible.
none,
/// No tearing, synchronizes rendering with monitor refresh rate, rendering frames when ready.
///
/// Tries to stay one frame ahead of the monitor, so when it's ready for the next frame it is
/// already prepared.
double,
/// No tearing, synchronizes rendering with monitor refresh rate, rendering frames when ready.
///
/// Tries to stay two frames ahead of the monitor, so when it's ready for the next frame it is
/// already prepared.
triple,
};
/// Application options that can be configured at init time.
pub const Options = struct {
/// The title of the window.
title: [*:0]const u8 = "Mach engine",
/// The width of the window.
width: u32 = 640,
/// The height of the window.
height: u32 = 480,
/// Monitor synchronization modes.
vsync: VSyncMode = .double,
/// GPU features required by the application.
required_features: ?[]gpu.Feature = null,
/// GPU limits required by the application.
required_limits: ?gpu.Limits = null,
/// Whether the application has a preference for low power or high performance GPU.
power_preference: gpu.PowerPreference = .none,
};
/// Window, events, inputs etc.
core: Core,
/// WebGPU driver - stores device, swap chains, targets and more
gpu_driver: GpuDriver,
allocator: Allocator,
/// The amount of time (in seconds) that has passed since the last frame was rendered.
///
/// For example, if you are animating a cube which should rotate 360 degrees every second,
/// instead of writing (360.0 / 60.0) and assuming the frame rate is 60hz, write
/// (360.0 * engine.delta_time)
delta_time: f64 = 0,
delta_time_ns: u64 = 0,
timer: std.time.Timer,
pub const Core = struct {
internal: union {
window: glfw.Window,
},
};
pub const GpuDriver = struct {
device: gpu.Device,
backend_type: gpu.Adapter.BackendType,
swap_chain: ?gpu.SwapChain,
swap_chain_format: gpu.Texture.Format,
native_instance: gpu.NativeInstance,
surface: ?gpu.Surface,
current_desc: gpu.SwapChain.Descriptor,
target_desc: gpu.SwapChain.Descriptor,
}; | src/Engine.zig |
const std = @import("std");
const string = []const u8;
const builtin = @import("builtin");
const zigmod = @import("../lib.zig");
const u = @import("index.zig");
const yaml = @import("./yaml.zig");
//
//
pub const Dep = struct {
const Self = @This();
alloc: std.mem.Allocator,
type: zigmod.DepType,
path: string,
id: string,
name: string,
main: string,
version: string,
c_include_dirs: []const string = &.{},
c_source_flags: []const string = &.{},
c_source_files: []const string = &.{},
only_os: []const string = &.{},
except_os: []const string = &.{},
yaml: ?yaml.Mapping,
deps: []zigmod.Dep,
keep: bool = false,
vcpkg: bool = false,
for_build: bool = false,
pub fn clean_path(self: Dep) !string {
if (self.type == .local) {
return if (self.path.len == 0) "../.." else self.path;
}
var p = self.path;
p = u.trim_prefix(p, "http://");
p = u.trim_prefix(p, "https://");
p = u.trim_prefix(p, "git://");
p = u.trim_suffix(p, ".git");
p = try std.mem.join(self.alloc, "/", &.{ @tagName(self.type), p });
return p;
}
pub fn clean_path_v(self: Dep) !string {
if (self.type == .http and self.version.len > 0) {
const i = std.mem.indexOf(u8, self.version, "-").?;
return std.mem.join(self.alloc, "/", &.{ "v", try self.clean_path(), self.version[i + 1 .. 15] });
}
return std.mem.join(self.alloc, "/", &.{ "v", try self.clean_path(), self.version });
}
pub fn is_for_this(self: Dep) bool {
const os = @tagName(builtin.os.tag);
if (self.only_os.len > 0) {
return u.list_contains(self.only_os, os);
}
if (self.except_os.len > 0) {
return !u.list_contains(self.except_os, os);
}
return true;
}
pub fn exact_version(self: Dep, dpath: string) !string {
if (self.version.len == 0) {
return try self.type.exact_version(self.alloc, dpath);
}
return switch (self.type) {
.git => blk: {
const vers = try u.parse_split(zigmod.DepType.GitVersion, "-").do(self.version);
if (vers.id.frozen()) break :blk self.version;
break :blk try self.type.exact_version(self.alloc, dpath);
},
else => self.version,
};
}
}; | src/util/dep.zig |
const std = @import("std");
const testing = std.testing;
pub const Scanner = struct {
const SIZE: usize = 8; // TODO this is the number of elements in Field enum
validate: bool,
total_valid: usize,
count: [SIZE]usize,
pub fn init(validate: bool) Scanner {
var self = Scanner{
.validate = validate,
.total_valid = 0,
.count = [_]usize{0} ** SIZE,
};
return self;
}
pub fn deinit(self: *Scanner) void {
_ = self;
}
pub fn add_line(self: *Scanner, line: []const u8) void {
// std.debug.warn("LINE [{}]\n", .{line});
var field_count: usize = 0;
var field: ?Field = null;
var it = std.mem.tokenize(u8, line, " :");
while (it.next()) |str| {
field_count += 1;
if (field == null) {
field = Field.parse(str);
// std.debug.warn("FIELD [{}]\n", .{field});
continue;
}
const valid = if (!self.validate) true else switch (field.?) {
.BYR => self.check_num(str, 1920, 2002),
.IYR => self.check_num(str, 2010, 2020),
.EYR => self.check_num(str, 2020, 2030),
.HGT => self.check_num_unit(str, "cm", 150, 193) or
self.check_num_unit(str, "in", 59, 76),
.HCL => self.check_hcl(str),
.ECL => self.check_ecl(str),
.PID => self.check_pid(str),
.CID => true,
};
if (valid) {
self.count[field.?.pos()] += 1;
}
field = null;
}
if (field_count == 0) {
// empty / blank lines indicate end of current passport data
self.done();
}
}
pub fn done(self: *Scanner) void {
// std.debug.warn("DONE\n", .{});
self.count[Field.CID.pos()] = 1; // always ok
var total: usize = 0;
for (self.count) |count| {
if (count > 0) {
total += 1;
}
}
if (total >= 8) {
self.total_valid += 1;
}
for (self.count) |_, pos| {
self.count[pos] = 0;
}
}
pub fn valid_count(self: Scanner) usize {
return self.total_valid;
}
// pid (Passport ID) - a nine-digit number, including leading zeroes.
fn check_pid(self: Scanner, str: []const u8) bool {
_ = self;
if (str.len != 9) {
return false;
}
var valid: i32 = std.fmt.parseInt(i32, str, 10) catch -1;
return valid >= 0;
}
// ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
fn check_ecl(self: Scanner, str: []const u8) bool {
_ = self;
if (std.mem.eql(u8, str, "amb")) return true;
if (std.mem.eql(u8, str, "blu")) return true;
if (std.mem.eql(u8, str, "brn")) return true;
if (std.mem.eql(u8, str, "gry")) return true;
if (std.mem.eql(u8, str, "grn")) return true;
if (std.mem.eql(u8, str, "hzl")) return true;
if (std.mem.eql(u8, str, "oth")) return true;
return false;
}
// hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
fn check_hcl(self: Scanner, str: []const u8) bool {
_ = self;
if (str.len != 7) {
return false;
}
if (str[0] != '#') {
return false;
}
var valid: i32 = std.fmt.parseInt(i32, str[1..], 16) catch -1;
return valid >= 0;
}
// byr (Birth Year) - four digits; at least 1920 and at most 2002.
// iyr (Issue Year) - four digits; at least 2010 and at most 2020.
// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
fn check_num(self: Scanner, str: []const u8, min: usize, max: usize) bool {
return self.check_num_unit(str, null, min, max);
}
// hgt (Height) - a number followed by either cm or in:
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
fn check_num_unit(self: Scanner, str: []const u8, unit: ?[]const u8, min: usize, max: usize) bool {
_ = self;
const top = str.len - if (unit != null) unit.?.len else 0;
var value: i32 = std.fmt.parseInt(i32, str[0..top], 10) catch -1;
if (value < min or value > max) {
return false;
}
if (unit != null and !std.mem.eql(u8, str[top..], unit.?)) {
return false;
}
return true;
}
const Field = enum(usize) {
BYR,
IYR,
EYR,
HGT,
HCL,
ECL,
PID,
CID,
pub fn parse(str: []const u8) ?Field {
if (std.mem.eql(u8, str, "byr")) return Field.BYR;
if (std.mem.eql(u8, str, "iyr")) return Field.IYR;
if (std.mem.eql(u8, str, "eyr")) return Field.EYR;
if (std.mem.eql(u8, str, "hgt")) return Field.HGT;
if (std.mem.eql(u8, str, "hcl")) return Field.HCL;
if (std.mem.eql(u8, str, "ecl")) return Field.ECL;
if (std.mem.eql(u8, str, "pid")) return Field.PID;
if (std.mem.eql(u8, str, "cid")) return Field.CID;
return null;
}
pub fn pos(field: Field) usize {
return @enumToInt(field);
}
};
};
test "sample no validation" {
const data: []const u8 =
\\ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
\\byr:1937 iyr:2017 cid:147 hgt:183cm
\\
\\iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
\\hcl:#cfa07d byr:1929
\\
\\hcl:#ae17e1 iyr:2013
\\eyr:2024
\\ecl:brn pid:760753108 byr:1931
\\hgt:179cm
\\
\\hcl:#cfa07d eyr:2025 pid:166559648
\\iyr:2011 ecl:brn hgt:59in
;
var scanner = Scanner.init(false);
defer scanner.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
scanner.add_line(line);
}
scanner.done();
const count = scanner.valid_count();
try testing.expect(count == 2);
}
test "sample invalid" {
const data: []const u8 =
\\eyr:1972 cid:100
\\hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
\\
\\iyr:2019
\\hcl:#602927 eyr:1967 hgt:170cm
\\ecl:grn pid:012533040 byr:1946
\\
\\hcl:dab227 iyr:2012
\\ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
\\
\\hgt:59cm ecl:zzz
\\eyr:2038 hcl:74454a iyr:2023
\\pid:3556412378 byr:2007
;
var scanner = Scanner.init(true);
defer scanner.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
scanner.add_line(line);
}
scanner.done();
const count = scanner.valid_count();
try testing.expect(count == 0);
}
test "sample valid" {
const data: []const u8 =
\\pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
\\hcl:#623a2f
\\
\\eyr:2029 ecl:blu cid:129 byr:1989
\\iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
\\
\\hcl:#888785
\\hgt:164cm byr:2001 iyr:2015 cid:88
\\pid:545766238 ecl:hzl
\\eyr:2022
\\
\\iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719
;
var scanner = Scanner.init(true);
defer scanner.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
scanner.add_line(line);
}
scanner.done();
const count = scanner.valid_count();
try testing.expect(count == 4);
} | 2020/p04/scanner.zig |
const std = @import("std");
const util = @import("util.zig");
pub const ZValue = union(enum) {
Object: std.StringArrayHashMap(ZValue),
Array: std.ArrayList(ZValue),
String: std.ArrayList(u8),
pub fn format(value: ZValue, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: ZValue, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
switch (self) {
.Object => |obj| {
try writer.writeAll("ZValue.Object = {\n");
var iter = obj.iterator();
while (iter.next()) |entry| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.print("{s} = ", .{entry.key_ptr.*});
try entry.value_ptr.*.log(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("}\n");
},
.Array => |arr| {
try writer.writeAll("ZValue.Array = [\n");
for (arr.items) |item| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try item.log(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("]\n");
},
.String => |str| try writer.print("ZValue.String = {s}\n", .{str.items}),
}
}
// TODO: is this even necessary? maybe for the case where an arena allocator wasn't used?
pub fn deinit(self: *ZValue) void {
switch (self) {
.Object => |*obj| {
var iter = obj.*.iterator();
while (iter.next()) |*entry| {
entry.*.value_ptr.*.deinit();
}
obj.*.deinit();
},
.Array => |*arr| {
for (arr.*.items) |*item| {
item.*.deinit();
}
arr.*.deinit();
},
.String => |*str| {
str.*.deinit();
},
}
}
};
pub const ZExpr = struct {
const Self = @This();
key: []const u8,
args: ?std.StringArrayHashMap(ZExprArg) = null,
accessors: ?std.ArrayList([]const u8) = null,
batch_args_list: ?std.ArrayList(std.ArrayList(ConcatList)) = null,
pub fn format(value: ZExpr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: ZExpr, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer.writeAll("ZExpr = {\n");
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.print("key = {s}\n", .{self.key});
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("args = ");
if (self.args) |args| {
try writer.writeAll("{\n");
var iter = args.iterator();
while (iter.next()) |entry| {
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try writer.print("{s} = ", .{entry.key_ptr.*});
try entry.value_ptr.*.log(writer, indent + 2);
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("}\n");
} else {
try writer.writeAll("null\n");
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("accessors = ");
if (self.accessors) |accessors| {
try writer.writeAll("[\n");
for (accessors.items) |accessor| {
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try writer.print("{s}\n", .{accessor});
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("]\n");
} else {
try writer.writeAll("null\n");
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("batch_args_set = ");
if (self.batch_args_list) |batch_args_list| {
try writer.writeAll("[\n");
for (batch_args_list.items) |batch_args| {
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try writer.writeAll("[\n");
for (batch_args.items) |c_list| {
try writer.writeByteNTimes(' ', (indent + 3) * 2);
try logConcatList(c_list, writer, indent + 3);
}
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try writer.writeAll("]\n");
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("]\n");
} else {
try writer.writeAll("null\n");
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("}\n");
}
pub fn setArgs
( self: *Self
, allocator_: std.mem.Allocator
, args_: std.ArrayList(ZExprArg)
, macros_: std.StringArrayHashMap(ZMacro)
)
!void
{
const macro = macros_.get(self.key) orelse return error.MacroKeyNotFound;
self.args = std.StringArrayHashMap(ZExprArg).init(allocator_);
for (macro.parameters.?.keys()) |key, i| {
if (i < args_.items.len) {
try self.args.?.putNoClobber(key, args_.items[i]);
}
}
}
pub fn evaluate
( self: Self
, allocator_: std.mem.Allocator
, result_: *ZValue
, init_result_: bool
, ext_accessors_: ?[][]const u8
, ctx_: ReductionContext
)
anyerror!bool
{
// get the macro for this expression
const macro = ctx_.macros.get(self.key) orelse return error.MacroKeyNotFound;
if (util.DEBUG) std.debug.print("evaluating macro -> {struct}", .{macro});
// use the macro default args if necessary
var expr_args: ?std.StringArrayHashMap(ConcatList) = null;
defer {
if (expr_args) |*eargs| {
eargs.deinit();
}
}
// set up a temporary list to concatenate our accessors and the external accessors
var expr_accessors: ?std.ArrayList([]const u8) = null;
defer {
if (expr_accessors) |*accessors| {
accessors.deinit();
}
}
if (self.batch_args_list) |batch_args_list| {
if (init_result_ and ext_accessors_ == null) {
result_.* = .{ .Array = std.ArrayList(ZValue).init(allocator_) };
}
if (ext_accessors_) |eacs| {
const idx = try std.fmt.parseUnsigned(usize, eacs[0], 10);
expr_args = try self.exprArgs(allocator_, ctx_.expr_args, batch_args_list.items[idx], macro);
const ctx = .{ .expr_args = expr_args, .macros = ctx_.macros };
expr_accessors = try self.exprAccessors(allocator_, if (eacs.len > 1) eacs[1..] else null);
return try reduce(allocator_, macro.value, result_, true, if (expr_accessors) |acs| acs.items else null, ctx);
}
for (batch_args_list.items) |batch_args| {
expr_args = try self.exprArgs(allocator_, ctx_.expr_args, batch_args, macro);
const ctx = .{ .expr_args = expr_args, .macros = ctx_.macros };
var value: ZValue = undefined;
_ = try reduce(allocator_, macro.value, &value, true, if (self.accessors) |acs| acs.items else null, ctx);
try result_.*.Array.append(value);
}
} else {
expr_args = try self.exprArgs(allocator_, ctx_.expr_args, null, macro);
expr_accessors = try self.exprAccessors(allocator_, ext_accessors_);
const ctx = .{ .expr_args = expr_args, .macros = ctx_.macros };
if (expr_accessors) |acs| {
return try reduce(allocator_, macro.value, result_, true, acs.items, ctx);
} else {
_ = try reduce(allocator_, macro.value, result_, init_result_, null, ctx);
}
}
return true;
}
fn exprAccessors
( self: Self
, allocator_: std.mem.Allocator
, ext_accessors_: ?[][]const u8
)
anyerror!?std.ArrayList([]const u8)
{
var expr_accessors: ?std.ArrayList([]const u8) = null;
if (self.accessors != null or ext_accessors_ != null) {
expr_accessors = std.ArrayList([]const u8).init(allocator_);
}
if (self.accessors) |acs| {
for (acs.items) |acc| {
try expr_accessors.?.append(acc);
}
}
if (ext_accessors_) |eacs| {
for (eacs) |eacc| {
try expr_accessors.?.append(eacc);
}
}
return expr_accessors;
}
fn exprArgs
( self: Self
, allocator_: std.mem.Allocator
, ctx_args_: ?std.StringArrayHashMap(ConcatList)
, batch_args_: ?std.ArrayList(ConcatList)
, macro_: ZMacro
)
anyerror!?std.StringArrayHashMap(ConcatList)
{
if (self.args == null) {
return null;
}
var expr_args = std.StringArrayHashMap(ConcatList).init(allocator_);
var arg_iter = self.args.?.iterator();
var bidx: usize = 0;
while (arg_iter.next()) |entry| {
const key = entry.key_ptr.*;
var res = try expr_args.getOrPut(key);
if (res.found_existing) return error.DuplicateKey;
res.value_ptr.* = ConcatList.init(allocator_);
const val = entry.value_ptr.*;
switch (val) {
.CList => |*c_list| {
for (c_list.items) |item| {
switch (item) {
.Parameter => |p| {
for (ctx_args_.?.get(p).?.items) |p_item| {
try res.value_ptr.*.append(p_item);
}
},
else => try res.value_ptr.*.append(item),
}
}
},
.BatchPlaceholder => {
for (batch_args_.?.items[bidx].items) |item| {
switch (item) {
.Parameter => |p| {
for (ctx_args_.?.get(p).?.items) |p_item| {
try res.value_ptr.*.append(p_item);
}
},
else => try res.value_ptr.*.append(item),
}
}
bidx += 1;
},
}
}
// get the remaining default parameters
if (self.args.?.count() < macro_.parameters.?.count()) {
var def_arg_iter = macro_.parameters.?.iterator();
while (def_arg_iter.next()) |entry| {
const key = entry.key_ptr.*;
if (expr_args.contains(key)) {
continue;
}
const val = entry.value_ptr.*;
if (val == null) {
return error.MissingDefaultValue;
}
try expr_args.putNoClobber(key, val.?);
}
}
return expr_args;
}
};
pub const ZExprArg = union(enum) {
CList: ConcatList,
BatchPlaceholder: void,
pub fn format(value: ZExprArg, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: ZExprArg, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer.writeAll("ZExprArg.");
switch (self) {
.CList => |list| try logConcatList(list, writer, indent),
.BatchPlaceholder => try writer.writeAll("BatchPlaceholder\n"),
}
}
};
pub const ConcatItem = union(enum) {
Object: std.StringArrayHashMap(ConcatList),
Array: std.ArrayList(ConcatList),
String: []const u8,
Parameter: []const u8,
Expression: ZExpr,
pub fn format(value: ConcatItem, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: ConcatItem, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
switch (self) {
.Object => |obj| {
try writer.writeAll("ConcatItem.Object = {\n");
var iter = obj.iterator();
while (iter.next()) |entry| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.print("{s} = ", .{entry.key_ptr.*});
try logConcatList(entry.value_ptr.*, writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("}\n");
},
.Array => |arr| {
try writer.writeAll("ConcatItem.Array = [\n");
for (arr.items) |item| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try logConcatList(item, writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("]\n");
},
.String => |s| try writer.print("ConcatItem.String = {s}\n", .{s}),
.Parameter => |p| try writer.print("ConcatItem.Parameter = {s}\n", .{p}),
.Expression => |e| try e.log(writer, indent),
}
}
};
pub const ConcatList = std.ArrayList(ConcatItem);
fn logConcatList(list: ConcatList, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer.writeAll("ConcatList = [\n");
for (list.items) |citem| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try citem.log(writer, indent + 1);
}
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("]\n");
}
pub const ZMacro = struct {
parameters: ?std.StringArrayHashMap(?ConcatList) = null,
value: ConcatList,
pub fn format(value: ZMacro, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: ZMacro, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer.writeAll("ZMacro = {\n");
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("parameters = ");
if (self.parameters) |parameters| {
try writer.writeAll("[\n");
var iter = parameters.iterator();
while (iter.next()) |entry| {
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try writer.print("{s} = ", .{entry.key_ptr.*});
if (entry.value_ptr.*) |default_value| {
try logConcatList(default_value, writer, indent + 2);
} else {
try writer.writeAll("null\n");
}
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("]\n");
} else {
try writer.writeAll("null\n");
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("value = ");
try logConcatList(self.value, writer, indent + 1);
try writer.writeByteNTimes(' ', indent * 2);
try writer.writeAll("}\n");
}
};
pub const ReductionContext = struct {
expr_args: ?std.StringArrayHashMap(ConcatList) = null,
macros: std.StringArrayHashMap(ZMacro),
pub fn format(value: ReductionContext, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer);
}
pub fn log(self: ReductionContext, writer: anytype) std.os.WriteError!void {
if (!util.DEBUG) return;
try writer.writeAll("ReductionContext = {\n");
try writer.writeAll(" expr_args = ");
if (self.expr_args) |expr_args| {
try writer.writeAll("{\n");
var iter = expr_args.iterator();
while (iter.next()) |entry| {
try writer.print(" {s} = ", .{entry.key_ptr.*});
try logConcatList(entry.value_ptr.*, writer, 3);
}
} else {
try writer.writeAll("null\n");
}
try writer.writeAll("}\n");
}
};
pub fn reduce
( allocator_: std.mem.Allocator
, concat_list_: ConcatList
, result_: *ZValue
, init_result_: bool
, accessors_: ?[][]const u8
, ctx_: ReductionContext
)
anyerror!bool
{
if (util.DEBUG) {
const held = std.debug.getStderrMutex().acquire();
defer held.release();
const stderr = std.io.getStdErr().writer();
try stderr.print("\n---[Reducing ConcatList]---\n{struct}\n", .{ctx_});
{
try logConcatList(concat_list_, stderr, 0);
}
if (accessors_) |acs| {
try stderr.writeAll("accessors = [\n");
for (acs) |item| {
try stderr.print(" {s}\n", .{item});
}
try stderr.writeAll("]\n");
}
}
if (concat_list_.items.len == 0) {
return error.CannotReduceEmptyConcatList;
}
const has_accessors = accessors_ != null and accessors_.?.len > 0;
const array_index: usize = idxblk: {
if (has_accessors) {
break :idxblk std.fmt.parseUnsigned(usize, accessors_.?[0], 10) catch 0;
}
break :idxblk 0;
};
var array_size: usize = 0;
for (concat_list_.items) |concat_item, i| {
// we only want to initialize the result_ when:
// 1. we're at the first concat item AND
// 2. the caller wants it initialized AND
// 3. there are no accessors left
// a. if there are accessors left, then there's no need to initialize the result yet since having accessors
// indicates that we want to drill down to get a specific value (i.e., there's no need to allocate
// memory for the 'outer/container' value of the actual value we want)
const init_res = i == 0 and init_result_ and !has_accessors;
switch (concat_item) {
.Object => |obj| {
if (init_res) {
result_.* = .{ .Object = std.StringArrayHashMap(ZValue).init(allocator_) };
}
var c_iter = obj.iterator();
while (c_iter.next()) |c_entry| {
const key = c_entry.key_ptr.*;
if (has_accessors) {
// if this is NOT the key we're trying to access then let's check the next one
if (!std.mem.eql(u8, key, accessors_.?[0])) {
continue;
}
const accessors: ?[][]const u8 = if (accessors_.?.len > 1) accessors_.?[1..] else null;
return try reduce(allocator_, c_entry.value_ptr.*, result_, true, accessors, ctx_);
}
var val: ZValue = undefined;
_ = try reduce(allocator_, c_entry.value_ptr.*, &val, true, null, ctx_);
try result_.*.Object.putNoClobber(key, val);
}
},
.Array => |arr| {
if (init_res) {
result_.* = .{ .Array = std.ArrayList(ZValue).init(allocator_) };
}
array_size += arr.items.len;
if (has_accessors) {
// if the array index is NOT within range then let's check the next concat item
if (array_index >= array_size) {
continue;
}
const accessors: ?[][]const u8 = if (accessors_.?.len > 1) accessors_.?[1..] else null;
return try reduce(allocator_, arr.items[array_index], result_, true, accessors, ctx_);
}
for (arr.items) |c_item| {
var val: ZValue = undefined;
_ = try reduce(allocator_, c_item, &val, true, null, ctx_);
try result_.*.Array.append(val);
}
},
.String => |str| {
if (has_accessors) return error.AttemptToAccessString;
if (init_res) {
result_.* = .{ .String = std.ArrayList(u8).init(allocator_) };
}
try result_.*.String.appendSlice(str);
},
.Parameter => |par| {
if (ctx_.expr_args) |args| {
const c_list = args.get(par) orelse return error.InvalidMacroParameter;
const did_reduce = try reduce(allocator_, c_list, result_, has_accessors or init_res, accessors_, ctx_);
if (has_accessors) {
return did_reduce;
}
} else {
return error.NoParamArgsProvided;
}
},
.Expression => |exp| {
const did_evaluate = try exp.evaluate(allocator_, result_, has_accessors or init_res, accessors_, ctx_);
if (has_accessors) {
return did_evaluate;
}
},
}
}
if (util.DEBUG) {
const held = std.debug.getStderrMutex().acquire();
defer held.release();
const stderr = std.io.getStdErr().writer();
try stderr.print("\n---[Result]---\n{struct}\n", .{result_.*});
}
return true;
}
/// These are the things that may be placed on the parse stack.
pub const StackElem = union(enum) {
TopLevelObject: std.StringArrayHashMap(ZValue),
Key: []const u8,
CList: ConcatList,
CItem: ConcatItem,
Placeholder: void,
ExprArgList: std.ArrayList(ZExprArg),
BSet: std.ArrayList(std.ArrayList(ConcatList)),
ParamMap: ?std.StringArrayHashMap(?ConcatList),
MacroDeclParam: []const u8,
pub fn format(value: StackElem, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try value.log(writer, 0);
}
pub fn log(self: StackElem, writer: anytype, indent: usize) std.os.WriteError!void {
if (!util.DEBUG) return;
switch (self) {
.TopLevelObject => |obj| {
const o = ZValue{ .Object = obj };
try o.log(writer, indent);
},
.Key => |k| try writer.print("Key = {s}\n", .{k}),
.CList => |l| {
try logConcatList(l, writer, indent);
},
.CItem => |c| try c.log(writer, indent),
.Placeholder => try writer.writeAll("Placeholder\n"),
.ExprArgList => |elist| {
try writer.writeAll("ExprArgList = [\n");
for (elist.items) |eitem| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try eitem.log(writer, indent + 1);
}
try writer.writeAll("]\n");
},
.BSet => |bset| {
try writer.writeAll("BSet = [\n");
for (bset.items) |arr| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("[\n");
for (arr.items) |item| {
try writer.writeByteNTimes(' ', (indent + 2) * 2);
try logConcatList(item, writer, indent + 2);
}
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.writeAll("]\n");
}
try writer.writeAll("]\n");
},
.ParamMap => |pm| {
if (pm) |map| {
try writer.writeAll("ParamMap = {\n");
var iter = map.iterator();
while (iter.next()) |entry| {
try writer.writeByteNTimes(' ', (indent + 1) * 2);
try writer.print("{s} = ", .{entry.key_ptr.*});
if (entry.value_ptr.*) |c_list| {
try logConcatList(c_list, writer, indent + 1);
} else {
try writer.writeAll("null\n");
}
}
try writer.writeAll("}\n");
} else {
try writer.writeAll("ParamMap = null\n");
}
},
.MacroDeclParam => |p| try writer.print("MacroDeclParam = {s}\n", .{p}),
}
}
};
//======================================================================================================================
//======================================================================================================================
//======================================================================================================================
//
//
// TESTS
//
//
//======================================================================================================================
//======================================================================================================================
//======================================================================================================================
test "concat list of objects reduction - no macros" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// object 0
var obj_0 = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
var c_list_0 = ConcatList.init(arena.allocator());
try c_list_0.append(.{ .String = "b" });
try obj_0.Object.putNoClobber("a", c_list_0);
// object 1
var obj_1 = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
var c_list_1 = ConcatList.init(arena.allocator());
try c_list_1.append(.{ .String = "d" });
try obj_1.Object.putNoClobber("c", c_list_1);
// fill in the concat list
// { a = b } + { c = d }
var c_list = ConcatList.init(arena.allocator());
try c_list.append(obj_0);
try c_list.append(obj_1);
// we need a macro map to call reduce() - we know it won't be used in this test, so just make an empty one
const ctx = .{ .macros = std.StringArrayHashMap(ZMacro).init(arena.allocator()) };
// get the result
// { a = b, c = d }
var result: ZValue = undefined;
const did_reduce = try reduce(arena.allocator(), c_list, &result, true, null, ctx);
try std.testing.expect(did_reduce);
// test the result
try std.testing.expect(result == .Object);
const b = result.Object.get("a") orelse return error.KeyNotFound;
const d = result.Object.get("c") orelse return error.KeyNotFound;
try std.testing.expectEqualStrings("b", b.String.items);
try std.testing.expectEqualStrings("d", d.String.items);
}
test "concat list of arrays reduction - no macros" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// array 0
var arr_0 = .{ .Array = std.ArrayList(ConcatList).init(arena.allocator()) };
var c_list_0 = ConcatList.init(arena.allocator());
try c_list_0.append(.{ .String = "a" });
try arr_0.Array.append(c_list_0);
// array 1
var arr_1 = .{ .Array = std.ArrayList(ConcatList).init(arena.allocator()) };
var c_list_1 = ConcatList.init(arena.allocator());
try c_list_1.append(.{ .String = "b" });
try arr_1.Array.append(c_list_1);
// fill in the concat list
// [ a ] + [ b ]
var c_list = ConcatList.init(arena.allocator());
try c_list.append(arr_0);
try c_list.append(arr_1);
// we need a macro map to call reduce() - we know it won't be used in this test, so just make an empty one
const ctx = .{ .macros = std.StringArrayHashMap(ZMacro).init(arena.allocator()) };
// get the result
// [ a, b ]
var result: ZValue = undefined;
const did_reduce = try reduce(arena.allocator(), c_list, &result, true, null, ctx);
try std.testing.expect(did_reduce);
// test the result
try std.testing.expect(result == .Array);
try std.testing.expectEqualStrings("a", result.Array.items[0].String.items);
try std.testing.expectEqualStrings("b", result.Array.items[1].String.items);
}
test "concat list of strings reduction - no macros" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// fill in the concat list
// "a" + "b"
var c_list = ConcatList.init(arena.allocator());
try c_list.append(.{ .String = "a" });
try c_list.append(.{ .String = "b" });
const ctx = .{ .macros = std.StringArrayHashMap(ZMacro).init(arena.allocator()) };
// get the result
// "ab"
var result: ZValue = undefined;
const did_reduce = try reduce(arena.allocator(), c_list, &result, true, null, ctx);
try std.testing.expect(did_reduce);
// test the result
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("ab", result.String.items);
}
test "macro expression evaluation - no accessors no batching" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $greet(name) = "Hello, " + %name + "!"
var value = ConcatList.init(arena.allocator());
try value.append(.{ .String = "Hello, " });
try value.append(.{ .Parameter = "name" });
try value.append(.{ .String = "!" });
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("name", null);
const macro = ZMacro{ .parameters = parameters, .value = value };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("greet", macro);
// expression
var c_list = ConcatList.init(arena.allocator());
try c_list.append(.{ .String = "Zooce" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("name", .{ .CList = c_list });
const expr = ZExpr{ .key = "greet", .args = args };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// "Hello, Zooce!"
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("Hello, Zooce!", result.String.items);
}
test "macro expression object single accessor evaluation - no batching" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $color(alpha) = {
// black = #000000 + %alpha
// red = #ff0000 + %alpha
// }
var black_val = ConcatList.init(arena.allocator());
try black_val.append(.{ .String = "#000000" });
try black_val.append(.{ .Parameter = "alpha" });
var red_val = ConcatList.init(arena.allocator());
try red_val.append(.{ .String = "#ff0000" });
try red_val.append(.{ .Parameter = "alpha" });
var color_obj = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
try color_obj.Object.putNoClobber("black", black_val);
try color_obj.Object.putNoClobber("red", red_val);
var color_val = ConcatList.init(arena.allocator());
try color_val.append(color_obj);
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("alpha", null);
const macro = ZMacro{ .parameters = parameters, .value = color_val };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("color", macro);
// expression
var alpha = ConcatList.init(arena.allocator());
try alpha.append(.{ .String = "ff" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("alpha", .{ .CList = alpha });
var accessors = std.ArrayList([]const u8).init(arena.allocator());
try accessors.append("black");
const expr = ZExpr{ .key = "color", .args = args, .accessors = accessors };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// "#000000ff"
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("#000000ff", result.String.items);
}
test "macro expression array single accessor evaluation - no batching" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $jobs(name) = [
// %name + " - <NAME>"
// %name + " - engineer"
// ]
var dog_walker_val = ConcatList.init(arena.allocator());
try dog_walker_val.append(.{ .Parameter = "name" });
try dog_walker_val.append(.{ .String = " - <NAME>" });
var engineer_val = ConcatList.init(arena.allocator());
try engineer_val.append(.{ .Parameter = "name" });
try engineer_val.append(.{ .String = " - engineer" });
var jobs_obj = .{ .Array = std.ArrayList(ConcatList).init(arena.allocator()) };
try jobs_obj.Array.append(dog_walker_val);
try jobs_obj.Array.append(engineer_val);
var jobs_val = ConcatList.init(arena.allocator());
try jobs_val.append(jobs_obj);
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("name", null);
const macro = ZMacro{ .parameters = parameters, .value = jobs_val };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("jobs", macro);
// expression
var name = ConcatList.init(arena.allocator());
try name.append(.{ .String = "Zooce" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("name", .{ .CList = name });
var accessors = std.ArrayList([]const u8).init(arena.allocator());
try accessors.append("1");
const expr = ZExpr{ .key = "jobs", .args = args, .accessors = accessors };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// "Zooce - engineer"
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("Zooce - engineer", result.String.items);
}
test "macro expression multiple accessor evaluation - no batching" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $macro(p1) = {
// k1 = [ a b %p1 ]
// k2 = "hello dude"
// }
var a = ConcatList.init(arena.allocator());
try a.append(.{ .String = "a" });
var b = ConcatList.init(arena.allocator());
try b.append(.{ .String = "b" });
var p = ConcatList.init(arena.allocator());
try p.append(.{ .Parameter = "p1" });
var k1_arr = .{ .Array = std.ArrayList(ConcatList).init(arena.allocator()) };
try k1_arr.Array.append(a);
try k1_arr.Array.append(b);
try k1_arr.Array.append(p);
var k1_val = ConcatList.init(arena.allocator());
try k1_val.append(k1_arr);
var k2_val = ConcatList.init(arena.allocator());
try k2_val.append(.{ .String = "hello dude" });
var macro_obj = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
try macro_obj.Object.putNoClobber("k1", k1_val);
try macro_obj.Object.putNoClobber("k2", k2_val);
var macro_val = ConcatList.init(arena.allocator());
try macro_val.append(macro_obj);
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("p1", null);
const macro = ZMacro{ .parameters = parameters, .value = macro_val };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("macro", macro);
// expression
var p1 = ConcatList.init(arena.allocator());
try p1.append(.{ .String = "Zooce" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("p1", .{ .CList = p1 });
var accessors = std.ArrayList([]const u8).init(arena.allocator());
try accessors.append("k1");
try accessors.append("1");
const expr = ZExpr{ .key = "macro", .args = args, .accessors = accessors };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// "b"
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("b", result.String.items);
}
test "macro expression with default value evaluation - no accessors no batching" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $greet(name, ack = "Hello") = %ack + ", " + %name + "!"
var value = ConcatList.init(arena.allocator());
try value.append(.{ .Parameter = "ack" });
try value.append(.{ .String = ", " });
try value.append(.{ .Parameter = "name" });
try value.append(.{ .String = "!" });
var ack = ConcatList.init(arena.allocator());
try ack.append(.{ .String = "Hello" });
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("name", null);
try parameters.putNoClobber("ack", ack);
const macro = ZMacro{ .parameters = parameters, .value = value };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("greet", macro);
// expression
var name_arg = ConcatList.init(arena.allocator());
try name_arg.append(.{ .String = "Zooce" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("name", .{ .CList = name_arg });
const expr = ZExpr{ .key = "greet", .args = args };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// "Hello, Zooce!"
try std.testing.expect(result == .String);
try std.testing.expectEqualStrings("Hello, Zooce!", result.String.items);
}
test "batched macro expression evaluation - no accessors" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $color(alpha, beta) = #ff0000 + %alpha + %beta
var value = ConcatList.init(arena.allocator());
try value.append(.{ .String = "#ff0000" });
try value.append(.{ .Parameter = "alpha" });
try value.append(.{ .Parameter = "beta" });
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("alpha", null);
try parameters.putNoClobber("beta", null);
const macro = ZMacro{ .parameters = parameters, .value = value };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("color", macro);
// expression
// $color(?, ff) % [
// [ 07 ]
// [ ff ]
// ]
var alpha1 = ConcatList.init(arena.allocator());
try alpha1.append(.{ .String = "07" });
var alpha1_batch = std.ArrayList(ConcatList).init(arena.allocator());
try alpha1_batch.append(alpha1);
var alpha2 = ConcatList.init(arena.allocator());
try alpha2.append(.{ .String = "ff" });
var alpha2_batch = std.ArrayList(ConcatList).init(arena.allocator());
try alpha2_batch.append(alpha2);
var batch_args_list = std.ArrayList(std.ArrayList(ConcatList)).init(arena.allocator());
try batch_args_list.append(alpha1_batch);
try batch_args_list.append(alpha2_batch);
var beta = ConcatList.init(arena.allocator());
try beta.append(.{ .String = "ff" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("alpha", .BatchPlaceholder);
try args.putNoClobber("beta", .{ .CList = beta });
const expr = ZExpr{ .key = "color", .args = args, .batch_args_list = batch_args_list };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// [ "#ff000007ff", "#ff0000ffff" ]
try std.testing.expect(result == .Array);
try std.testing.expectEqual(@as(usize, 2), result.Array.items.len);
try std.testing.expectEqualStrings("#ff000007ff", result.Array.items[0].String.items);
try std.testing.expectEqualStrings("#ff0000ffff", result.Array.items[1].String.items);
}
test "batched macro expression evaluation" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
// macro
// $color(alpha, beta) = {
// black = #000000 + %alpha + %beta
// red = #ff0000 + %alpha + %beta
// }
var black_val = ConcatList.init(arena.allocator());
try black_val.append(.{ .String = "#000000" });
try black_val.append(.{ .Parameter = "alpha" });
try black_val.append(.{ .Parameter = "beta" });
var red_val = ConcatList.init(arena.allocator());
try red_val.append(.{ .String = "#ff0000" });
try red_val.append(.{ .Parameter = "alpha" });
try red_val.append(.{ .Parameter = "beta" });
var color_obj = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
try color_obj.Object.putNoClobber("black", black_val);
try color_obj.Object.putNoClobber("red", red_val);
var color_val = ConcatList.init(arena.allocator());
try color_val.append(color_obj);
var parameters = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try parameters.putNoClobber("alpha", null);
try parameters.putNoClobber("beta", null);
const macro = ZMacro{ .parameters = parameters, .value = color_val };
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
try macros.putNoClobber("color", macro);
// expression
// $color(?, ff).black % [
// [ 07 ]
// [ ff ]
// ]
var alpha1 = ConcatList.init(arena.allocator());
try alpha1.append(.{ .String = "07" });
var alpha1_batch = std.ArrayList(ConcatList).init(arena.allocator());
try alpha1_batch.append(alpha1);
var alpha2 = ConcatList.init(arena.allocator());
try alpha2.append(.{ .String = "ff" });
var alpha2_batch = std.ArrayList(ConcatList).init(arena.allocator());
try alpha2_batch.append(alpha2);
var batch_args_list = std.ArrayList(std.ArrayList(ConcatList)).init(arena.allocator());
try batch_args_list.append(alpha1_batch);
try batch_args_list.append(alpha2_batch);
var beta = ConcatList.init(arena.allocator());
try beta.append(.{ .String = "ff" });
var args = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args.putNoClobber("alpha", .BatchPlaceholder);
try args.putNoClobber("beta", .{ .CList = beta });
var accessors = std.ArrayList([]const u8).init(arena.allocator());
try accessors.append("black");
const expr = ZExpr{ .key = "color", .args = args, .accessors = accessors, .batch_args_list = batch_args_list };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// [ "#00000007ff", "#000000ffff" ]
try std.testing.expect(result == .Array);
try std.testing.expectEqual(@as(usize, 2), result.Array.items.len);
try std.testing.expectEqualStrings("#00000007ff", result.Array.items[0].String.items);
try std.testing.expectEqualStrings("#000000ffff", result.Array.items[1].String.items);
}
test "crazy batched macro expression inside another macro expression" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var macros = std.StringArrayHashMap(ZMacro).init(arena.allocator());
// macro a
// $macro_a(a, b, c, d = "AF") = %a + %b + %c + %d
var a_val = ConcatList.init(arena.allocator());
try a_val.append(.{ .Parameter = "a" });
try a_val.append(.{ .Parameter = "b" });
try a_val.append(.{ .Parameter = "c" });
try a_val.append(.{ .Parameter = "d" });
var a_params = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try a_params.putNoClobber("a", null);
try a_params.putNoClobber("b", null);
try a_params.putNoClobber("c", null);
var d_par_def = ConcatList.init(arena.allocator());
try d_par_def.append(.{ .String = "AF" });
try a_params.putNoClobber("d", d_par_def);
const macro_a = ZMacro{ .parameters = a_params, .value = a_val };
try macros.putNoClobber("macro_a", macro_a);
// macro b
// $macro_b(param) = {
// key = $macro_a(%param, ?, "Hello, World!") % [
// [ 100 ] [ %param ] [ 10000 ]
// ]
// }
var arg_1 = ConcatList.init(arena.allocator());
try arg_1.append(.{ .Parameter = "param" });
var arg_3 = ConcatList.init(arena.allocator());
try arg_3.append(.{ .String = "Hello, World!" });
var args_a = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args_a.putNoClobber("a", .{ .CList = arg_1 });
try args_a.putNoClobber("b", .BatchPlaceholder);
try args_a.putNoClobber("c", .{ .CList = arg_3 });
var batch_1 = ConcatList.init(arena.allocator());
try batch_1.append(.{ .String = "100" });
var batch_set_1 = std.ArrayList(ConcatList).init(arena.allocator());
try batch_set_1.append(batch_1);
var batch_2 = ConcatList.init(arena.allocator());
try batch_2.append(.{ .Parameter = "param" });
var batch_set_2 = std.ArrayList(ConcatList).init(arena.allocator());
try batch_set_2.append(batch_2);
var batch_3 = ConcatList.init(arena.allocator());
try batch_3.append(.{ .String = "10000" });
var batch_set_3 = std.ArrayList(ConcatList).init(arena.allocator());
try batch_set_3.append(batch_3);
var batch_args_list = std.ArrayList(std.ArrayList(ConcatList)).init(arena.allocator());
try batch_args_list.append(batch_set_1);
try batch_args_list.append(batch_set_2);
try batch_args_list.append(batch_set_3);
const key_expr = ZExpr{ .key = "macro_a", .args = args_a, .batch_args_list = batch_args_list };
var key_val = ConcatList.init(arena.allocator());
try key_val.append(.{ .Expression = key_expr });
var obj = .{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
try obj.Object.putNoClobber("key", key_val );
var b_val = ConcatList.init(arena.allocator());
try b_val.append(obj);
var b_params = std.StringArrayHashMap(?ConcatList).init(arena.allocator());
try b_params.putNoClobber("param", null);
const macro_b = ZMacro{ .parameters = b_params, .value = b_val };
try macros.putNoClobber("macro_b", macro_b);
// expression
// $macro_b("Zooce")
var param = ConcatList.init(arena.allocator());
try param.append(.{ .String = "Zooce" });
var args_b = std.StringArrayHashMap(ZExprArg).init(arena.allocator());
try args_b.putNoClobber("param", .{ .CList = param });
const expr = ZExpr{ .key = "macro_b", .args = args_b };
// evaluate the expression
var result: ZValue = undefined;
const did_evaluate = try expr.evaluate(arena.allocator(), &result, true, null, .{ .macros = macros });
try std.testing.expect(did_evaluate);
// test the result
// { key = [ "Zooce100Hello, WorldAF", "ZooceZooceHello, WorldAF", "Zooce10000Hello, WorldAF" ] }
try std.testing.expect(result == .Object);
try std.testing.expectEqual(@as(usize, 1), result.Object.count());
const key_arr = result.Object.get("key") orelse return error.KeyNotFound;
try std.testing.expect(key_arr == .Array);
try std.testing.expectEqual(@as(usize, 3), key_arr.Array.items.len);
try std.testing.expectEqualStrings("Zooce100Hello, World!AF", key_arr.Array.items[0].String.items);
try std.testing.expectEqualStrings("ZooceZooceHello, World!AF", key_arr.Array.items[1].String.items);
try std.testing.expectEqualStrings("Zooce10000Hello, World!AF", key_arr.Array.items[2].String.items);
}
test "debug printing" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const item_1 = ConcatItem{ .String = "item 1" };
const item_2 = ConcatItem{ .String = "item 2" };
var item_list = ConcatList.init(arena.allocator());
try item_list.append(item_1);
try item_list.append(item_2);
var c_arr = ConcatItem{ .Array = std.ArrayList(ConcatList).init(arena.allocator()) };
try c_arr.Array.append(item_list);
var arr_list = ConcatList.init(arena.allocator());
try arr_list.append(c_arr);
var c_obj = ConcatItem{ .Object = std.StringArrayHashMap(ConcatList).init(arena.allocator()) };
try c_obj.Object.putNoClobber("key", arr_list);
std.debug.print("\n{union}\n", .{c_obj});
} | src/data.zig |
const std = @import("std");
const mem = std.mem;
const math = std.math;
const assert = std.debug.assert;
const expectEqual = std.testing.expectEqual;
pub const XXHash32 = XXHash(XH32);
pub const XXHash64 = XXHash(XH64);
const XH32 = struct {
pub const block_length = 16;
pub const Int = u32;
const primes = [5]u32{
0x9e3779b1,
0x85ebca77,
0xc2b2ae3d,
0x27d4eb2f,
0x165667b1,
};
acc1: u32,
acc2: u32,
acc3: u32,
acc4: u32,
msg_len: u64 = 0,
inline fn mix0(acc: u32, lane: u32) u32 {
return math.rotl(u32, acc +% lane *% primes[1], 13) *% primes[0];
}
inline fn mix32(acc: u32, lane: u32) u32 {
return math.rotl(u32, acc +% lane *% primes[2], 17) *% primes[3];
}
inline fn mix8(acc: u32, lane: u8) u32 {
return math.rotl(u32, acc +% lane *% primes[4], 11) *% primes[0];
}
pub fn init(seed: u32) XH32 {
return XH32{
.acc1 = seed +% primes[0] +% primes[1],
.acc2 = seed +% primes[1],
.acc3 = seed,
.acc4 = seed -% primes[0],
};
}
pub fn update(self: *XH32, b: []const u8) void {
assert(b.len % 16 == 0);
const ints = @ptrCast([*]align(1) const u32, b.ptr)[0 .. b.len >> 2];
var off: usize = 0;
while (off < ints.len) : (off += 4) {
const lane1 = mem.nativeToLittle(u32, ints[off + 0]);
const lane2 = mem.nativeToLittle(u32, ints[off + 1]);
const lane3 = mem.nativeToLittle(u32, ints[off + 2]);
const lane4 = mem.nativeToLittle(u32, ints[off + 3]);
self.acc1 = mix0(self.acc1, lane1);
self.acc2 = mix0(self.acc2, lane2);
self.acc3 = mix0(self.acc3, lane3);
self.acc4 = mix0(self.acc4, lane4);
}
self.msg_len += b.len;
}
pub fn final(self: *XH32, b: []const u8) u32 {
assert(b.len < 16);
var acc = if (self.msg_len < 16)
self.acc3 +% primes[4]
else
math.rotl(u32, self.acc1, 01) +%
math.rotl(u32, self.acc2, 07) +%
math.rotl(u32, self.acc3, 12) +%
math.rotl(u32, self.acc4, 18);
acc +%= @truncate(u32, self.msg_len +% b.len);
switch (@intCast(u4, b.len)) {
0 => {},
1 => {
acc = mix8(acc, b[0]);
},
2 => {
acc = mix8(acc, b[0]);
acc = mix8(acc, b[1]);
},
3 => {
acc = mix8(acc, b[0]);
acc = mix8(acc, b[1]);
acc = mix8(acc, b[2]);
},
4 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
},
5 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
},
6 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
acc = mix8(acc, b[5]);
},
7 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
acc = mix8(acc, b[5]);
acc = mix8(acc, b[6]);
},
8 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
},
9 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[8]);
},
10 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[8]);
acc = mix8(acc, b[9]);
},
11 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[8]);
acc = mix8(acc, b[9]);
acc = mix8(acc, b[10]);
},
12 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
const num3 = mem.readIntLittle(u32, b[8..12]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix32(acc, num3);
},
13 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
const num3 = mem.readIntLittle(u32, b[8..12]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[12]);
},
14 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
const num3 = mem.readIntLittle(u32, b[8..12]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[12]);
acc = mix8(acc, b[13]);
},
15 => {
const num1 = mem.readIntLittle(u32, b[0..4]);
const num2 = mem.readIntLittle(u32, b[4..8]);
const num3 = mem.readIntLittle(u32, b[8..12]);
acc = mix32(acc, num1);
acc = mix32(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[12]);
acc = mix8(acc, b[13]);
acc = mix8(acc, b[14]);
},
}
acc ^= acc >> 15;
acc *%= primes[1];
acc ^= acc >> 13;
acc *%= primes[2];
acc ^= acc >> 16;
return acc;
}
};
pub const XH64 = struct {
pub const block_length = 32;
pub const Int = u64;
const primes = [5]u64{
0x9e3779b185ebca87,
0xc2b2ae3d27d4eb4f,
0x165667b19e3779f9,
0x85ebca77c2b2ae63,
0x27d4eb2f165667c5,
};
acc1: u64,
acc2: u64,
acc3: u64,
acc4: u64,
msg_len: u64 = 0,
inline fn mix0(acc: u64, lane: u64) u64 {
return math.rotl(u64, acc +% lane *% primes[1], 31) *% primes[0];
}
inline fn mix1(acc: u64, lane: u64) u64 {
return (acc ^ mix0(0, lane)) *% primes[0] +% primes[3];
}
inline fn mix64(acc: u64, lane: u64) u64 {
return math.rotl(u64, acc ^ mix0(0, lane), 27) *% primes[0] +% primes[3];
}
inline fn mix32(acc: u64, lane: u32) u64 {
return math.rotl(u64, acc ^ (lane *% primes[0]), 23) *% primes[1] +% primes[2];
}
inline fn mix8(acc: u64, lane: u8) u64 {
return math.rotl(u64, acc ^ (lane *% primes[4]), 11) *% primes[0];
}
pub fn init(seed: u64) XH64 {
return XH64{
.acc1 = seed +% primes[0] +% primes[1],
.acc2 = seed +% primes[1],
.acc3 = seed,
.acc4 = seed -% primes[0],
};
}
pub fn update(self: *XH64, b: []const u8) void {
assert(b.len % 32 == 0);
const ints = @ptrCast([*]align(1) const u64, b.ptr)[0 .. b.len >> 3];
var off: usize = 0;
while (off < ints.len) : (off += 4) {
const lane1 = mem.nativeToLittle(u64, ints[off + 0]);
const lane2 = mem.nativeToLittle(u64, ints[off + 1]);
const lane3 = mem.nativeToLittle(u64, ints[off + 2]);
const lane4 = mem.nativeToLittle(u64, ints[off + 3]);
self.acc1 = mix0(self.acc1, lane1);
self.acc2 = mix0(self.acc2, lane2);
self.acc3 = mix0(self.acc3, lane3);
self.acc4 = mix0(self.acc4, lane4);
}
self.msg_len += b.len;
}
pub fn final(self: *XH64, b: []const u8) u64 {
assert(b.len < 32);
var acc = if (self.msg_len < 32)
self.acc3 +% primes[4]
else blk: {
var h =
math.rotl(u64, self.acc1, 01) +%
math.rotl(u64, self.acc2, 07) +%
math.rotl(u64, self.acc3, 12) +%
math.rotl(u64, self.acc4, 18);
h = mix1(h, self.acc1);
h = mix1(h, self.acc2);
h = mix1(h, self.acc3);
h = mix1(h, self.acc4);
break :blk h;
};
acc +%= self.msg_len +% b.len;
switch (@intCast(u5, b.len)) {
0 => {},
1 => {
acc = mix8(acc, b[0]);
},
2 => {
acc = mix8(acc, b[0]);
acc = mix8(acc, b[1]);
},
3 => {
acc = mix8(acc, b[0]);
acc = mix8(acc, b[1]);
acc = mix8(acc, b[2]);
},
4 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
},
5 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
},
6 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
acc = mix8(acc, b[5]);
},
7 => {
const num = mem.readIntLittle(u32, b[0..4]);
acc = mix32(acc, num);
acc = mix8(acc, b[4]);
acc = mix8(acc, b[5]);
acc = mix8(acc, b[6]);
},
8 => {
const num = mem.readIntLittle(u64, b[0..8]);
acc = mix64(acc, num);
},
9 => {
const num = mem.readIntLittle(u64, b[0..8]);
acc = mix64(acc, num);
acc = mix8(acc, b[8]);
},
10 => {
const num = mem.readIntLittle(u64, b[0..8]);
acc = mix64(acc, num);
acc = mix8(acc, b[8]);
acc = mix8(acc, b[9]);
},
11 => {
const num = mem.readIntLittle(u64, b[0..8]);
acc = mix64(acc, num);
acc = mix8(acc, b[8]);
acc = mix8(acc, b[9]);
acc = mix8(acc, b[10]);
},
12 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u32, b[8..12]);
acc = mix64(acc, num1);
acc = mix32(acc, num2);
},
13 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u32, b[8..12]);
acc = mix64(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[12]);
},
14 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u32, b[8..12]);
acc = mix64(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[12]);
acc = mix8(acc, b[13]);
},
15 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u32, b[8..12]);
acc = mix64(acc, num1);
acc = mix32(acc, num2);
acc = mix8(acc, b[12]);
acc = mix8(acc, b[13]);
acc = mix8(acc, b[14]);
},
16 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
},
17 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix8(acc, b[16]);
},
18 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix8(acc, b[16]);
acc = mix8(acc, b[17]);
},
19 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix8(acc, b[16]);
acc = mix8(acc, b[17]);
acc = mix8(acc, b[18]);
},
20 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u32, b[16..20]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix32(acc, num3);
},
21 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u32, b[16..20]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[20]);
},
22 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u32, b[16..20]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[20]);
acc = mix8(acc, b[21]);
},
23 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u32, b[16..20]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix32(acc, num3);
acc = mix8(acc, b[20]);
acc = mix8(acc, b[21]);
acc = mix8(acc, b[22]);
},
24 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
},
25 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix8(acc, b[24]);
},
26 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix8(acc, b[24]);
acc = mix8(acc, b[25]);
},
27 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix8(acc, b[24]);
acc = mix8(acc, b[25]);
acc = mix8(acc, b[26]);
},
28 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
const num4 = mem.readIntLittle(u32, b[24..28]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix32(acc, num4);
},
29 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
const num4 = mem.readIntLittle(u32, b[24..28]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix32(acc, num4);
acc = mix8(acc, b[28]);
},
30 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
const num4 = mem.readIntLittle(u32, b[24..28]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix32(acc, num4);
acc = mix8(acc, b[28]);
acc = mix8(acc, b[29]);
},
31 => {
const num1 = mem.readIntLittle(u64, b[0..8]);
const num2 = mem.readIntLittle(u64, b[8..16]);
const num3 = mem.readIntLittle(u64, b[16..24]);
const num4 = mem.readIntLittle(u32, b[24..28]);
acc = mix64(acc, num1);
acc = mix64(acc, num2);
acc = mix64(acc, num3);
acc = mix32(acc, num4);
acc = mix8(acc, b[28]);
acc = mix8(acc, b[29]);
acc = mix8(acc, b[30]);
},
}
acc ^= acc >> 33;
acc *%= primes[1];
acc ^= acc >> 29;
acc *%= primes[2];
acc ^= acc >> 32;
return acc;
}
};
fn XXHash(comptime Impl: type) type {
return struct {
const Self = @This();
pub const block_length = Impl.block_length;
state: Impl,
buf: [block_length]u8 = undefined,
buf_len: u8 = 0,
pub fn init(seed: Impl.Int) Self {
return Self{ .state = Impl.init(seed) };
}
pub fn update(self: *Self, b: []const u8) void {
var off: usize = 0;
if (self.buf_len != 0 and self.buf_len + b.len >= block_length) {
off += block_length - self.buf_len;
mem.copy(u8, self.buf[self.buf_len..], b[0..off]);
self.state.update(self.buf[0..]);
self.buf_len = 0;
}
const remain_len = b.len - off;
const aligned_len = remain_len - (remain_len % block_length);
self.state.update(b[off .. off + aligned_len]);
mem.copy(u8, self.buf[self.buf_len..], b[off + aligned_len ..]);
self.buf_len += @intCast(u8, b[off + aligned_len ..].len);
}
pub fn final(self: *Self) Impl.Int {
const rem_key = self.buf[0..self.buf_len];
return self.state.final(rem_key);
}
pub fn hash(seed: Impl.Int, input: []const u8) Impl.Int {
const aligned_len = input.len - (input.len % block_length);
var c = Impl.init(seed);
@call(.{ .modifier = .always_inline }, c.update, .{input[0..aligned_len]});
return @call(.{ .modifier = .always_inline }, c.final, .{input[aligned_len..]});
}
};
}
const prime32: u32 = 2654435761;
const prime64: u64 = 11400714785074694797;
const test_buffer1 = blk: {
@setEvalBranchQuota(3000);
var bytegen: u64 = prime32;
var buf: [2367]u8 = undefined;
for (buf) |*c| {
c.* = @truncate(u8, bytegen >> 56);
bytegen *%= prime64;
}
break :blk buf;
};
const test_buffer2 = blk: {
var buf: [100]u8 = undefined;
for (buf) |*c, i| c.* = i;
break :blk &buf;
};
const Test = struct {
seed: u64,
data: []const u8,
sum: u64,
fn new(seed: u64, data: []const u8, sum: u64) Test {
return Test{ .seed = seed, .data = data, .sum = sum };
}
};
const test_data32 = [_]Test{
// From the reference C implementation
Test.new(0, "", 0x02cc5d05),
Test.new(prime32, "", 0x36b78ae7),
Test.new(0, test_buffer1[0..1], 0xCF65B03E),
Test.new(prime32, test_buffer1[0..1], 0xB4545AA4),
Test.new(0, test_buffer1[0..14], 0x1208E7E2),
Test.new(prime32, test_buffer1[0..14], 0x6AF1D1FE),
Test.new(0, test_buffer1[0..222], 0x5BD11DBD),
Test.new(prime32, test_buffer1[0..222], 0x58803C5F),
// From the twox-hash rust crate
Test.new(0, &[_]u8{42}, 0xe0fe705f),
Test.new(0, "Hello, world!\x00", 0x9e5e7e93),
Test.new(0, test_buffer2, 0x7f89ba44),
Test.new(0x42c91977, "", 0xd6bf8459),
Test.new(0x42c91977, test_buffer2, 0x6d2f6c17),
};
const test_data64 = [_]Test{
// From the reference C implementation
Test.new(0, "", 0xef46db3751d8e999),
Test.new(prime32, test_buffer1[0..0], 0xac75fda2929b17ef),
Test.new(0, test_buffer1[0..1], 0xe934a84adb052768),
Test.new(prime32, test_buffer1[0..1], 0x5014607643a9b4c3),
Test.new(0, test_buffer1[0..4], 0x9136a0dca57457ee),
Test.new(0, test_buffer1[0..14], 0x8282dcc4994e35c8),
Test.new(prime32, test_buffer1[0..14], 0xc3bd6bf63deb6df0),
Test.new(0, test_buffer1[0..222], 0xb641ae8cb691c174),
Test.new(prime32, test_buffer1[0..222], 0x20cb8ab7ae10c14a),
// From the twox-hash rust crate
Test.new(0, &[_]u8{42}, 0x0a9edecebeb03ae4),
Test.new(0, "Hello, world!\x00", 0x7b06c531ea43e89f),
Test.new(0, test_buffer2, 0x6ac1e58032166597),
Test.new(0xae0543311b702d91, "", 0x4b6a04fcdf7a4672),
Test.new(0xae0543311b702d91, test_buffer2, 0x567e355e0682e1f1),
};
test "XXHash Test Vectors" {
for (test_data64) |t| try expectEqual(t.sum, XXHash64.hash(t.seed, t.data));
for (test_data32) |t| try expectEqual(t.sum, XXHash32.hash(@intCast(u32, t.seed), t.data));
} | src/xxhash.zig |
const std = @import("std");
const elf = std.elf;
const builtin = std.builtin;
const assert = std.debug.assert;
const R_AMD64_RELATIVE = 8;
const R_386_RELATIVE = 8;
const R_ARM_RELATIVE = 23;
const R_AARCH64_RELATIVE = 1027;
const R_RISCV_RELATIVE = 3;
const R_SPARC_RELATIVE = 22;
const R_RELATIVE = switch (builtin.cpu.arch) {
.i386 => R_386_RELATIVE,
.x86_64 => R_AMD64_RELATIVE,
.arm => R_ARM_RELATIVE,
.aarch64 => R_AARCH64_RELATIVE,
.riscv64 => R_RISCV_RELATIVE,
else => @compileError("Missing R_RELATIVE definition for this target"),
};
// Obtain a pointer to the _DYNAMIC array.
// We have to compute its address as a PC-relative quantity not to require a
// relocation that, at this point, is not yet applied.
fn getDynamicSymbol() [*]elf.Dyn {
return switch (builtin.cpu.arch) {
.i386 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ call 1f
\\ 1: pop %[ret]
\\ lea _DYNAMIC-1b(%[ret]), %[ret]
: [ret] "=r" (-> [*]elf.Dyn)
),
.x86_64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ lea _DYNAMIC(%%rip), %[ret]
: [ret] "=r" (-> [*]elf.Dyn)
),
// Work around the limited offset range of `ldr`
.arm => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ ldr %[ret], 1f
\\ add %[ret], pc
\\ b 2f
\\ 1: .word _DYNAMIC-1b
\\ 2:
: [ret] "=r" (-> [*]elf.Dyn)
),
// A simple `adr` is not enough as it has a limited offset range
.aarch64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ adrp %[ret], _DYNAMIC
\\ add %[ret], %[ret], #:lo12:_DYNAMIC
: [ret] "=r" (-> [*]elf.Dyn)
),
.riscv64 => asm volatile (
\\ .weak _DYNAMIC
\\ .hidden _DYNAMIC
\\ lla %[ret], _DYNAMIC
: [ret] "=r" (-> [*]elf.Dyn)
),
else => {
@compileError("PIE startup is not yet supported for this target!");
},
};
}
pub fn relocate(phdrs: []elf.Phdr) void {
@setRuntimeSafety(false);
const dynv = getDynamicSymbol();
// Recover the delta applied by the loader by comparing the effective and
// the theoretical load addresses for the `_DYNAMIC` symbol.
const base_addr = base: {
for (phdrs) |*phdr| {
if (phdr.p_type != elf.PT_DYNAMIC) continue;
break :base @ptrToInt(dynv) - phdr.p_vaddr;
}
// This is not supposed to happen for well-formed binaries.
std.os.abort();
};
var rel_addr: usize = 0;
var rela_addr: usize = 0;
var rel_size: usize = 0;
var rela_size: usize = 0;
{
var i: usize = 0;
while (dynv[i].d_tag != elf.DT_NULL) : (i += 1) {
switch (dynv[i].d_tag) {
elf.DT_REL => rel_addr = base_addr + dynv[i].d_val,
elf.DT_RELA => rela_addr = base_addr + dynv[i].d_val,
elf.DT_RELSZ => rel_size = dynv[i].d_val,
elf.DT_RELASZ => rela_size = dynv[i].d_val,
else => {},
}
}
}
// Apply the relocations.
if (rel_addr != 0) {
const rel = std.mem.bytesAsSlice(elf.Rel, @intToPtr([*]u8, rel_addr)[0..rel_size]);
for (rel) |r| {
if (r.r_type() != R_RELATIVE) continue;
@intToPtr(*usize, base_addr + r.r_offset).* += base_addr;
}
}
if (rela_addr != 0) {
const rela = std.mem.bytesAsSlice(elf.Rela, @intToPtr([*]u8, rela_addr)[0..rela_size]);
for (rela) |r| {
if (r.r_type() != R_RELATIVE) continue;
@intToPtr(*usize, base_addr + r.r_offset).* += base_addr + @bitCast(usize, r.r_addend);
}
}
} | lib/std/os/linux/start_pie.zig |
const x86 = @import("machine.zig");
const std = @import("std");
const assert = std.debug.assert;
usingnamespace(@import("types.zig"));
const AvxOpcode = x86.avx.AvxOpcode;
const Mnemonic = x86.Mnemonic;
const Instruction = x86.Instruction;
const Machine = x86.Machine;
const Operand = x86.operand.Operand;
const Immediate = x86.Immediate;
const OperandType = x86.operand.OperandType;
pub const Signature = struct {
const max_ops = 5;
operands: [max_ops]OperandType,
pub fn ops(
o1: OperandType,
o2: OperandType,
o3: OperandType,
o4: OperandType,
o5: OperandType,
) Signature {
return Signature {
.operands = [max_ops]OperandType { o1, o2, o3, o4, o5 },
};
}
pub fn ops0() Signature {
return ops(.none, .none, .none, .none, .none);
}
pub fn ops1(o1: OperandType) Signature {
return ops(o1, .none, .none, .none, .none);
}
pub fn ops2(o1: OperandType, o2: OperandType) Signature {
return ops(o1, o2, .none, .none, .none);
}
pub fn ops3(o1: OperandType, o2: OperandType, o3: OperandType) Signature {
return ops(o1, o2, o3, .none, .none);
}
pub fn ops4(o1: OperandType, o2: OperandType, o3: OperandType, o4: OperandType) Signature {
return ops(o1, o2, o3, o4, .none);
}
pub fn ops5(
o1: OperandType,
o2: OperandType,
o3: OperandType,
o4: OperandType,
o5: OperandType,
) Signature {
return ops(o1, o2, o3, o4, o5);
}
pub fn fromOperands(
operand1: ?*const Operand,
operand2: ?*const Operand,
operand3: ?*const Operand,
operand4: ?*const Operand,
operand5: ?*const Operand,
) Signature {
const o1 = if (operand1) |op| op.operandType() else OperandType.none;
const o2 = if (operand2) |op| op.operandType() else OperandType.none;
const o3 = if (operand3) |op| op.operandType() else OperandType.none;
const o4 = if (operand4) |op| op.operandType() else OperandType.none;
const o5 = if (operand5) |op| op.operandType() else OperandType.none;
return ops(o1, o2, o3, o4, o5);
}
pub fn debugPrint(self: Signature) void {
std.debug.warn("(", .{});
for (self.operands) |operand| {
if (operand == .none) {
continue;
}
std.debug.warn("{},", .{@tagName(operand)});
}
std.debug.warn("): ", .{});
}
pub fn matchTemplate(template: Signature, instance: Signature) bool {
for (template.operands) |templ, i| {
const rhs = instance.operands[i];
if (templ == .none and rhs == .none) {
continue;
} else if (!OperandType.matchTemplate(templ, rhs)) {
return false;
}
}
return true;
}
};
/// Special opcode edge cases
/// Some opcode/instruction combinations have special legacy edge cases we need
/// to check before we can confirm a match.
pub const OpcodeEdgeCase = enum {
None = 0x0,
/// Prior to x86-64, the instructions:
/// 90 XCHG EAX, EAX
/// and
/// 90 NOP
/// were encoded the same way and might be treated specially by the CPU.
/// However, on x86-64 `XCHG EAX,EAX` is no longer a NOP because it zeros
/// the upper 32 bits of the RAX register.
///
/// When AMD designed x86-64 they decide 90 should still be treated as a NOP.
/// This means we have to choose a different encoding on x86-64.
XCHG_EAX = 0x1,
/// sign-extended immediate value (ie this opcode sign extends)
Sign,
/// mark an encoding that will only work if the immediate doesn't need a
/// sign extension (ie this opcode zero extends)
///
/// eg: `MOV r64, imm32` can be encode in the same way as `MOV r32, imm32`
/// as long as the immediate is non-negative since all operations on 32 bit
/// registers implicitly zero extend
NoSign,
/// Not encodable on 64 bit mode
No64,
/// Not encodable on 32/16 bit mode
No32,
/// Valid encoding, but undefined behaviour
Undefined,
pub fn isEdgeCase(
self: OpcodeEdgeCase,
item: InstructionItem,
mode: Mode86,
op1: ?*const Operand,
op2: ?*const Operand,
op3: ?*const Operand,
op4: ?*const Operand,
op5: ?*const Operand,
) bool {
switch (self) {
.XCHG_EAX => {
return (mode == .x64 and op1.?.Reg == .EAX and op2.?.Reg == .EAX);
},
.NoSign, .Sign => {
const sign = self;
var imm_pos: u8 = undefined;
// figure out which operand is the immediate
if (op1 != null and op1.?.tag() == .Imm) {
imm_pos = 0;
} else if (op2 != null and op2.?.tag() == .Imm) {
imm_pos = 1;
} else if (op3 != null and op3.?.tag() == .Imm) {
imm_pos = 2;
} else if (op4 != null and op4.?.tag() == .Imm) {
imm_pos = 3;
} else if (op5 != null and op5.?.tag() == .Imm) {
imm_pos = 4;
} else {
unreachable;
}
const imm = switch (imm_pos) {
0 => op1.?.Imm,
1 => op2.?.Imm,
2 => op3.?.Imm,
3 => op4.?.Imm,
4 => op5.?.Imm,
else => unreachable,
};
switch (sign) {
// Matches edgecase when it's an unsigned immediate that will get sign extended
.Sign => {
const is_unsigned = imm.sign == .Unsigned;
return (is_unsigned and imm.willSignExtend(item.signature.operands[imm_pos]));
},
// Matches edgecase when it's a signed immedate that needs its sign extended
.NoSign => {
const is_signed = imm.sign == .Signed;
return (is_signed and imm.isNegative());
},
else => unreachable,
}
},
.No64 => unreachable,
.No32 => unreachable,
.Undefined => unreachable,
.None => return false,
}
}
};
// Quick refrences:
//
// * https://en.wikichip.org/wiki/intel/cpuid
// * https://en.wikipedia.org/wiki/X86_instruction_listings
// * https://www.felixcloutier.com/x86/
// * Intel manual: Vol 3, Ch 22.13 New instructions in the pentium and later ia-32 processors
pub const CpuFeature = enum {
pub const count = __num_cpu_features;
pub const MaskType = u128;
pub const all_features_mask = ~@as(CpuFeature.MaskType, 0);
pub const Presets = struct {
const _i386 = [_]CpuFeature { ._8086, ._186, ._286, ._386, ._087, ._287, ._387 };
const _i486 = [_]CpuFeature { ._8086, ._186, ._286, ._386, ._486, ._087, ._287, ._387 };
const x86_64 = [_]CpuFeature {
._8086, ._186, ._286, ._386, ._486, .x86_64, ._087, ._287, ._387
.CPUID, .P6,
.FPU, .TSC, .MSR, .CX8, .SEP, .CX16, .RSM, .MMX,
.SYSCALL,
};
};
/// Added in 8086 / 8088
_8086,
/// Added in 80186 / 80188
_186,
/// Added in 80286
_286,
/// Added in 80386
_386,
/// Added in 80486
_486,
/// Added in x86-64 (CPUID.80000001H:EDX.LM[29] (Long Mode))
x86_64,
/// Legacy 8086 instructions not implemented on later processors
_8086_Legacy,
/// Legacy 80186 instructions not implemented on later processors
_186_Legacy,
/// Legacy 80286 instructions not implemented on later processors
_286_Legacy,
/// Legacy 80386 instructions not implemented on later processors
_386_Legacy,
/// Legacy 80486 instructions not implemented on later processors
_486_Legacy,
/// Added in 8087 FPU, or CPUID.01H.EDX.FPU[0] = 1
_087,
/// Added in 80287 FPU, or CPUID.01H.EDX.FPU[0] = 1
_287,
/// Added in 80387 FPU, or CPUID.01H.EDX.FPU[0] = 1
_387,
/// Only works on Intel CPUs
Intel,
/// Only works on Amd CPUs
Amd,
/// Only works on Cyrix CPUs
Cyrix,
/// Added in AMD-V
AMD_V,
/// Added in VT-x
VT_X,
/// EFLAGS.ID[bit 21] can be set and cleared
CPUID,
/// CPUID.01H.EAX[11:8] = Family = 6 or 15 = 0110B or 1111B
P6,
/// (IA-32e mode supported) or (CPUID DisplayFamily_DisplayModel = 06H_0CH )
RSM,
//
// CPUID.(EAX=1).ECX
//
/// CPUID.01H.ECX.SSE3[0] = 1
SSE3,
/// CPUID.01H.ECX.PCLMULQDQ[1] = 1
PCLMULQDQ,
/// CPUID.01H.ECX.MONITOR[3] = 1
MONITOR,
/// CPUID.01H.ECX.VMX[5] = 1
VMX,
/// CPUID.01H.ECX.SMX[6] = 1
SMX,
/// CPUID.01H.ECX.SSSE3[9] = 1 (supplemental SSE3)
SSSE3,
/// CPUID.01H.ECX.FMA[12] = 1 (Fused Multiply and Add)
FMA,
/// CPUID.01H.ECX.CX16[13] = 1
CX16,
/// CPUID.01H.ECX.SSE4_1[19] = 1
SSE4_1,
/// CPUID.01H.ECX.SSE4_2[20] = 1
SSE4_2,
/// CPUID.01H.ECX.MOVBE[22] = 1
MOVBE,
/// CPUID.01H.ECX.POPCNT[23] = 1
POPCNT,
/// CPUID.01H.ECX.AES[25] = 1
AES,
/// CPUID.01H.ECX.XSAVE[26] = 1
XSAVE,
/// CPUID.01H.ECX.AVX[28] = 1
AVX,
/// CPUID.01H.ECX.F16C[29] = 1
F16C,
/// CPUID.01H.ECX.RDRAND[30] = 1
RDRAND,
//
// CPUID.(EAX=1).EDX
//
/// CPUID.01H.EDX.FPU[0] = 1
FPU,
/// CPUID.01H.EDX.TSC[4] = 1
TSC,
/// CPUID.01H.EDX.MSR[5] = 1
MSR,
/// CPUID.01H.EDX.CX8[8] = 1
CX8,
/// CPUID.01H.EDX.SEP[11] = 1 (SYSENTER and SYSEXIT)
SEP,
/// CPUID.01H.EDX.CMOV[15] = 1 (CMOVcc and FCMOVcc)
CMOV,
/// CPUID.01H.EDX.CLFSH[19] = 1 (CFLUSH)
CLFSH,
/// CPUID.01H.EDX.MMX[23] = 1
MMX,
/// CPUID.01H.EDX.FXSR[24] = 1 (FXSAVE, FXRSTOR)
FXSR,
/// CPUID.01H.EDX.SSE[25] = 1
SSE,
/// CPUID.01H.EDX.SSE2[26] = 1
SSE2,
//
// CPUID.(EAX=7, ECX=0).EBX
//
/// CPUID.EAX.07H.EBX.FSGSBASE[0] = 1
FSGSBASE,
/// CPUID.EAX.07H.EBX.SGX[2] = 1 (Software Guard eXtensions)
SGX,
/// CPUID.EAX.07H.EBX.BMI1[3] = 1 (Bit Manipulation Instructions 1)
BMI1,
/// CPUID.EAX.07H.EBX.HLE[4] = 1 (Hardware Lock Elision)
HLE,
/// CPUID.EAX.07H.EBX.AVX2[5] = 1 (Advanced Vector eXtension 2)
AVX2,
/// CPUID.EAX.07H.EBX.SMEP[7] = 1 (Supervisor Mode Execution Prevention)
SMEP,
/// CPUID.EAX.07H.EBX.BMI2[8] = 1 (Bit Manipulation Instructions 2)
BMI2,
/// CPUID.EAX.07H.EBX.INVPCID[10] = 1
INVPCID,
/// CPUID.EAX.07H.EBX.RTM[11] = 1
RTM,
/// CPUID.EAX.07H.EBX.MPX[14] = 1 (Memory Protection eXtension)
MPX,
/// CPUID.EAX.07H.EBX.AVX512F[16] = 1
AVX512F,
/// CPUID.EAX.07H.EBX.AVX512DQ[17] = 1 (Doubleword and Quadword)
AVX512DQ,
/// CPUID.EAX.07H.EBX.RDSEED[18] = 1
RDSEED,
/// CPUID.EAX.07H.EBX.ADX[19] = 1
ADX,
/// CPUID.EAX.07H.EBX.SMAP[20] = 1 (Supervisor Mode Access Prevention)
SMAP,
/// CPUID.EAX.07H.EBX.AVX512_I1FMA[21] = 1 (AVX512 Integer Fused Multiply Add)
AVX512_IFMA,
/// CPUID.EAX.07H.EBX.PCOMMIT[22] = 1
PCOMMIT,
/// CPUID.EAX.07H.EBX.CLFLUSHOPT[23] = 1
CLFLUSHOPT,
/// CPUID.EAX.07H.EBX.CLWB[24] = 1
CLWB,
/// CPUID.EAX.07H.EBX.AVX512PF[26] = 1 (AVX512 Prefetch Instructions)
AVX512PF,
/// CPUID.EAX.07H.EBX.AVX512ER[27] = 1 (AVX512 Exponential and Reciprocal)
AVX512ER,
/// CPUID.EAX.07H.EBX.AVX512CD[28] = 1 (AVX512 Conflict Detection)
AVX512CD,
/// CPUID.EAX.07H.EBX.SHA[29] = 1
SHA,
/// CPUID.EAX.07H.EBX.AVX512BW[30] = 1 (AVX512 Byte and Word)
AVX512BW,
/// CPUID.EAX.07H.EBX.AVX512_VL[31] = 1 (AVX512 Vector length extensions)
AVX512VL,
//
// CPUID.(EAX=7, ECX=0).ECX
//
/// CPUID.EAX.07H.ECX.PREFETCHWT1[0] = 1
PREFETCHWT1,
/// CPUID.EAX.07H.ECX.AVX512_VBMI[1] = 1 (AVX512 Vector Byte Manipulation Instructions)
AVX512_VBMI,
/// CPUID.EAX.07H.ECX.PKU[3] = 1 (Protection Key rights register for User pages)
PKU,
/// CPUID.EAX.07H.ECX.WAITPKG[5] = 1
WAITPKG,
/// CPUID.EAX.07H.ECX.AVX512_VBMI2[5] = 1 (AVX512 Vector Byte Manipulation Instructions 2)
AVX512_VBMI2,
/// CPUID.EAX.07H.ECX.CET_SS[7] = 1 (Control-flow Enforcement Technology - Shadow Stack)
CET_SS,
/// CPUID.EAX.07H.ECX.GFNI[8] = 1
GFNI,
/// CPUID.EAX.07H.ECX.VAES[9] = 1
VAES,
/// CPUID.EAX.07H.ECX.VPCLMULQDQ[10] = 1 (Carry-less multiplication )
VPCLMULQDQ,
/// CPUID.EAX.07H.ECX.AVX512_VNNI[11] = 1 (AVX512 Vector Neural Network Instructions)
AVX512_VNNI,
/// CPUID.EAX.07H.ECX.AVX512_BITALG[12] = 1 (AVX512 Bit Algorithms)
AVX512_BITALG,
/// CPUID.EAX.07H.ECX.AVX512_VPOPCNTDQ[14] = 1 (AVX512 Vector Population Count Dword and Qword)
AVX512_VPOPCNTDQ,
/// CPUID.EAX.07H.ECX.RDPID[22] = 1
RDPID,
/// CPUID.EAX.07H.ECX.CLDEMOTE[25] = 1
CLDEMOTE,
/// CPUID.EAX.07H.ECX.MOVDIRI[27] = 1
MOVDIRI,
/// CPUID.EAX.07H.ECX.MOVDIR64B[28] = 1
MOVDIR64B,
//
// CPUID.(EAX=7, ECX=1)
//
/// CPUID.(EAX=7, ECX=1).EAX.AVX512_BF16 (Brain Float16)
AVX512_BF16,
//
// CPUID.(EAX=7, ECX=0).EDX
//
/// CPUID.EAX.07H.EDX.AVX512_4VNNIW[2] = 1 (Vector Neural Network Instructions Word (4VNNIW))
AVX512_4VNNIW,
/// CPUID.EAX.07H.EDX.AVX512_4FMAPS[3] = 1 (Fused Multiply Accumulation Packed Single precision (4FMAPS))
AVX512_4FMAPS,
/// CPUID.EAX.07H.EDX.CET_IBT[20] = 1 (Control-flow Enforcement Technology - Indirect-Branch Tracking)
CET_IBT,
//
// CPUID.(EAX=0DH, ECX=1).EAX
//
/// CPUID.(EAX=0DH, ECX=1).EAX.XSAVEOPT[0]
XSAVEOPT,
/// CPUID.(EAX=0DH, ECX=1).EAX.XSAVEC[1]
XSAVEC,
/// CPUID.(EAX=0DH, ECX=1).EAX.XSS[3]
XSS,
//
// CPUID.(EAX=14H, ECX=0).EBX
//
/// CPUID.[EAX=14H, ECX=0).EBX.PTWRITE[4]
PTWRITE,
//
// CPUID.(EAX=0x8000_0001).ECX
//
/// CPUID.80000001H:ECX.LAHF_SAHF[0] LAHF/SAHF valid in 64 bit mode
LAHF_SAHF,
/// CPUID.80000001H:ECX.LZCNT[5] (AMD: (ABM Advanced Bit Manipulation))
LZCNT,
/// CPUID.80000001H:ECX.SSE4A[6]
SSE4A,
/// CPUID.80000001H:ECX.PREFETCHW[8] (aka 3DNowPrefetch)
PREFETCHW,
/// CPUID.80000001H:ECX.XOP[11]
XOP,
/// CPUID.80000001H:ECX.SKINIT[12] (SKINIT / STGI)
SKINIT,
/// CPUID.80000001H:ECX.LWP[15] (Light Weight Profiling)
LWP,
/// CPUID.80000001H:ECX.FMA4[16] (Fused Multiply Add 4 operands version)
FMA4,
/// CPUID.80000001H:ECX.TBM[21] (Trailing Bit Manipulation)
TBM,
//
// CPUID.(EAX=0x8000_0001).EDX
//
/// CPUID.80000001H:EDX.SYSCALL[8]
SYSCALL,
/// CPUID.80000001H:EDX.MMXEXT[22]
MMXEXT,
/// CPUID.80000001H:EDX.RDTSCP[27]
RDTSCP,
/// CPUID.80000001H:EDX.3DNOWEXT[30] (3DNow! Extensions, 3DNow!+)
_3DNOWEXT,
/// CPUID.80000001H:EDX.3DNOW[31] (3DNow!)
_3DNOW,
/// Cyrix EMMI (Extended Multi-Media Instructions) (6x86 MX and MII)
EMMI,
__num_cpu_features,
pub fn toMask(self: CpuFeature) MaskType {
return @shlExact(@as(MaskType, 1), @enumToInt(self));
}
pub fn arrayToMask(feature_array: []const CpuFeature) MaskType {
var res: MaskType = 0;
for (feature_array) |feature| {
res |= feature.toMask();
}
return res;
}
};
pub const InstructionPrefix = enum {
Lock,
Rep,
Repe,
Repne,
Bnd,
/// Either XACQUIRE or XRELEASE prefix, requires lock prefix to be used
Hle,
/// Either XACQUIRE or XRELEASE perfix, no lock prefix required
HleNoLock,
/// XRELEASE prefix, no lock prefix required
Xrelease,
};
pub const InstructionEncoding = enum {
ZO, // no operands
I, // immediate
I2, // IGNORE immediate
II, // immediate immediate
MII, // ModRM:r/m immediate immediate
RMII, // ModRM:reg ModRM:r/m immediate immediate
O, // opcode+reg.num
O2, // IGNORE opcode+reg.num
M, // ModRM:r/m
RM, // ModRM:reg ModRM:r/m
MR, // ModRM:r/m ModRM:reg
RMI, // ModRM:reg ModRM:r/m immediate
MRI, // ModRM:r/m ModRM:reg immediate
OI, // opcode+reg.num imm8/16/32/64
MI, // ModRM:r/m imm8/16/32/64
MSpec, // Special memory handling for instructions like MOVS,OUTS,XLAT, etc
D, // encode address or offset
FD, // AL/AX/EAX/RAX Moffs NA NA
TD, // Moffs (w) AL/AX/EAX/RAX NA NA
// AvxOpcodes encodings
RVM, // ModRM:reg (E)VEX:vvvv ModRM:r/m
MVR, // ModRM:r/m (E)VEX:vvvv ModRM:reg
RMV, // ModRM:reg ModRM:r/m (E)VEX:vvvv
RVMR, // ModRM:reg (E)VEX:vvvv ModRM:r/m imm8[7:4]:vvvv
RVRM, // ModRM:reg (E)VEX:vvvv imm8[7:4]:vvvv ModRM:r/m
RVMRI, // ModRM:reg (E)VEX:vvvv ModRM:r/m imm8[7:4]:vvvv imm8[3:0]
RVRMI, // ModRM:reg (E)VEX:vvvv imm8[7:4]:vvvv ModRM:r/m imm8[3:0]
RVMI, // ModRM:reg (E)VEX:vvvv ModRM:r/m imm8
VMI, // (E)VEX:vvvv ModRM:r/m imm8
VM, // (E)VEX.vvvv ModRM:r/m
MV, // ModRM:r/m (E)VEX:vvvv
vRMI, // ModRM:reg ModRM:r/m imm8
vMRI, // ModRM:r/m ModRM:reg imm8
vRM, // ModRM:reg ModRM:r/m
vMR, // ModRM:reg ModRM:r/m
vM, // ModRm:r/m
vZO, //
pub fn getMemPos(self: InstructionEncoding) ?u8 {
return switch (self) {
.M, .MR, .MRI, .MI, .MVR, .MV, .vMRI, .vMR, .vM => 0,
.RM, .RMI, .RMV, .VMI, .VM, .vRM => 1,
.RVM, .RVMR, .RVMI => 2,
else => null,
};
}
};
pub const OpcodeAnyTag = enum {
Op,
Avx,
};
pub const OpcodeAny = union(OpcodeAnyTag) {
Op: Opcode,
Avx: AvxOpcode,
};
pub const InstructionItem = struct {
mnemonic: Mnemonic,
signature: Signature,
opcode: OpcodeAny,
encoding: InstructionEncoding,
overides: Overides,
edge_case: OpcodeEdgeCase,
mode_edge_case: OpcodeEdgeCase,
disp_n: u8,
cpu_feature_mask: CpuFeature.MaskType,
fn create(
mnem: Mnemonic,
signature: Signature,
opcode: var,
encoding: InstructionEncoding,
overides: Overides,
extra_opts: var
) InstructionItem {
_ = @setEvalBranchQuota(100000);
var edge_case = OpcodeEdgeCase.None;
var mode_edge_case = OpcodeEdgeCase.None;
var cpu_feature_mask: CpuFeature.MaskType = 0;
var disp_n: u8 = 1;
const opcode_any = switch (@TypeOf(opcode)) {
Opcode => OpcodeAny { .Op = opcode },
AvxOpcode => x: {
if (encoding.getMemPos()) |pos| {
const op_type = signature.operands[pos];
disp_n = x86.avx.calcDispMultiplier(opcode, op_type);
} else {
// don't care if no memory
}
break :x OpcodeAny { .Avx = opcode };
},
else => @compileError("opcode: Expected Opcode or AvxOpcode, got: " ++ @TypeOf(opcode)),
};
if (@typeInfo(@TypeOf(extra_opts)) != .Struct) {
@compileError("extra_opts: Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
}
for (extra_opts) |opt, i| {
switch (@TypeOf(opt)) {
CpuFeature => cpu_feature_mask |= opt.toMask(),
InstructionPrefix => {
// TODO:
},
OpcodeEdgeCase => {
switch (opt) {
.No32, .No64 => {
assert(mode_edge_case == .None);
mode_edge_case = opt;
},
.Undefined => {
// TODO:
},
else => {
assert(edge_case == .None);
edge_case = opt;
},
}
},
else => |bad_type| {
@compileError("Unsupported feature/version field type: " ++ @typeName(bad_type));
},
}
}
return InstructionItem {
.mnemonic = mnem,
.signature = signature,
.opcode = opcode_any,
.encoding = encoding,
.overides = overides,
.edge_case = edge_case,
.mode_edge_case = mode_edge_case,
.disp_n = disp_n,
.cpu_feature_mask = cpu_feature_mask,
};
}
pub inline fn hasEdgeCase(self: InstructionItem) bool {
return self.edge_case != .None;
}
/// Check if this InstructionItem is encodable on the given machine
pub inline fn isMachineMatch(self: InstructionItem, machine: Machine) bool {
if (self.cpu_feature_mask & machine.cpu_feature_mask != self.cpu_feature_mask) {
return false;
}
switch (self.mode_edge_case) {
.None => {},
.No64 => if (machine.mode == .x64) return false,
.No32 => if (machine.mode == .x86_32 or machine.mode == .x86_16) return false,
else => unreachable,
}
return true;
}
pub fn matchesEdgeCase(
self: InstructionItem,
machine: Machine,
op1: ?*const Operand,
op2: ?*const Operand,
op3: ?*const Operand,
op4: ?*const Operand,
op5: ?*const Operand,
) bool {
return self.edge_case.isEdgeCase(self, machine.mode, op1, op2, op3, op4, op5);
}
/// Calculates the total length of instruction (without prefixes or rex)
fn calcLengthLegacy(self: *const InstructionItem, modrm: ?x86.operand.ModRmResult) u8 {
var result: u8 = 0;
switch (self.opcode) {
.Op => |op| result += op.byteCount(),
else => unreachable,
}
result += self.totalImmediateSize();
if (modrm) |rm| {
if (rm.sib != null) {
// modrm + sib byte
result += 2;
} else {
// modrm byte only
result += 1;
}
result += rm.disp_bit_size.valueBytes();
}
return result;
}
pub fn totalImmediateSize(self: InstructionItem) u8 {
var res: u8 = 0;
for (self.signature.operands) |ops| {
switch (ops) {
.imm8 => res += 1,
.imm16 => res += 2,
.imm32 => res += 4,
.imm64 => res += 8,
.none => break,
else => continue,
}
}
return res;
}
pub fn coerceImm(self: InstructionItem, op: ?*const Operand, pos: u8) Immediate {
switch (self.signature.operands[pos]) {
.imm8 => return op.?.*.Imm,
.imm16 => return op.?.*.Imm.coerce(.Bit16),
.imm32 => return op.?.*.Imm.coerce(.Bit32),
.imm64 => return op.?.*.Imm.coerce(.Bit64),
else => unreachable,
}
}
pub fn encode(
self: *const InstructionItem,
machine: Machine,
ctrl: ?*const EncodingControl,
op1: ?*const Operand,
op2: ?*const Operand,
op3: ?*const Operand,
op4: ?*const Operand,
op5: ?*const Operand,
) AsmError!Instruction {
return switch (self.encoding) {
.ZO => machine.encodeRMI(self, ctrl, null, null, null, self.overides),
.M => machine.encodeRMI(self, ctrl, null, op1, null, self.overides),
.MI => machine.encodeRMI(self, ctrl, null, op1, self.coerceImm(op2, 1), self.overides),
.RM => machine.encodeRMI(self, ctrl, op1, op2, null, self.overides),
.RMI => machine.encodeRMI(self, ctrl, op1, op2, self.coerceImm(op3, 2), self.overides),
.MRI => machine.encodeRMI(self, ctrl, op2, op1, self.coerceImm(op3, 2), self.overides),
.MR => machine.encodeRMI(self, ctrl, op2, op1, null, self.overides),
.I => machine.encodeRMI(self, ctrl, null, null, self.coerceImm(op1, 0), self.overides),
.I2 => machine.encodeRMI(self, ctrl, null, null, self.coerceImm(op2, 1), self.overides),
.II => machine.encodeRMII(self, ctrl, null, null, self.coerceImm(op1, 0), self.coerceImm(op2, 1), self.overides),
.MII => machine.encodeRMII(self, ctrl, null, op1, self.coerceImm(op2, 1), self.coerceImm(op3, 2), self.overides),
.RMII => machine.encodeRMII(self, ctrl, op1, op2, self.coerceImm(op3, 2), self.coerceImm(op4, 3), self.overides),
.O => machine.encodeOI(self, ctrl, op1, null, self.overides),
.O2 => machine.encodeOI(self, ctrl, op2, null, self.overides),
.OI => machine.encodeOI(self, ctrl, op1, self.coerceImm(op2, 1), self.overides),
.D => machine.encodeAddress(self, ctrl, op1, self.overides),
.FD => machine.encodeMOffset(self, ctrl, op1, op2, self.overides),
.TD => machine.encodeMOffset(self, ctrl, op2, op1, self.overides),
.MSpec => machine.encodeMSpecial(self, ctrl, op1, op2, self.overides),
.RVM => machine.encodeAvx(self, ctrl, op1, op2, op3, null, null, self.disp_n),
.MVR => machine.encodeAvx(self, ctrl, op3, op2, op1, null, null, self.disp_n),
.RMV => machine.encodeAvx(self, ctrl, op1, op3, op2, null, null, self.disp_n),
.VM => machine.encodeAvx(self, ctrl, null, op1, op2, null, null, self.disp_n),
.MV => machine.encodeAvx(self, ctrl, null, op2, op1, null, null, self.disp_n),
.RVMI => machine.encodeAvx(self, ctrl, op1, op2, op3, null, op4, self.disp_n),
.VMI => machine.encodeAvx(self, ctrl, null, op1, op2, null, op3, self.disp_n),
.RVMR => machine.encodeAvx(self, ctrl, op1, op2, op3, op4, null, self.disp_n),
.RVMRI => machine.encodeAvx(self, ctrl, op1, op2, op3, op4, op5, self.disp_n),
.RVRM => machine.encodeAvx(self, ctrl, op1, op2, op4, op3, null, self.disp_n),
.RVRMI => machine.encodeAvx(self, ctrl, op1, op2, op4, op3, op5, self.disp_n),
.vRMI => machine.encodeAvx(self, ctrl, op1, null, op2, null, op3, self.disp_n),
.vMRI => machine.encodeAvx(self, ctrl, op2, null, op1, null, op3, self.disp_n),
.vRM => machine.encodeAvx(self, ctrl, op1, null, op2, null, null, self.disp_n),
.vMR => machine.encodeAvx(self, ctrl, op2, null, op1, null, null, self.disp_n),
.vM => machine.encodeAvx(self, ctrl, null, null, op1, null, null, self.disp_n),
.vZO => machine.encodeAvx(self, ctrl, null, null, null, null, null, self.disp_n),
};
}
};
/// Generate a map from Mnemonic -> index in the instruction database
fn genMnemonicLookupTable() [Mnemonic.count]u16 {
comptime {
var result: [Mnemonic.count]u16 = undefined;
var current_mnem = Mnemonic._mnemonic_final;
_ = @setEvalBranchQuota(50000);
for (result) |*val| {
val.* = 0xffff;
}
for (instruction_database) |item, i| {
if (item.mnemonic != current_mnem) {
current_mnem = item.mnemonic;
if (current_mnem == ._mnemonic_final) {
break;
}
if (result[@enumToInt(current_mnem)] != 0xffff) {
@compileError("Mnemonic mislocated in lookup table. " ++ @tagName(current_mnem));
}
result[@enumToInt(current_mnem)] = @intCast(u16, i);
}
}
if (false) {
// Count the number of unimplemented mnemonics
var count: u16 = 0;
for (result) |val, mnem_index| {
if (val == 0xffff) {
@compileLog(@intToEnum(Mnemonic, mnem_index));
count += 1;
}
}
@compileLog("Unreferenced mnemonics: ", count);
}
return result;
}
}
pub fn lookupMnemonic(mnem: Mnemonic) usize {
const result = lookup_table[@enumToInt(mnem)];
if (result == 0xffff) {
std.debug.panic("Instruction {} not implemented yet", .{mnem});
}
return result;
}
pub fn getDatabaseItem(index: usize) *const InstructionItem {
return &instruction_database[index];
}
pub const lookup_table: [Mnemonic.count]u16 = genMnemonicLookupTable();
const Op1 = x86.Opcode.op1;
const Op2 = x86.Opcode.op2;
const Op3 = x86.Opcode.op3;
const Op1r = x86.Opcode.op1r;
const Op2r = x86.Opcode.op2r;
const Op3r = x86.Opcode.op3r;
// Opcodes with compulsory prefix that needs to precede other prefixes
const preOp1 = x86.Opcode.preOp1;
const preOp2 = x86.Opcode.preOp2;
const preOp1r = x86.Opcode.preOp1r;
const preOp2r = x86.Opcode.preOp2r;
const preOp3 = x86.Opcode.preOp3;
const preOp3r = x86.Opcode.preOp3r;
// Opcodes that are actually composed of multiple instructions
// eg: FSTENV needs prefix 0x9B before other prefixes, because 0x9B is
// actually the opcode FWAIT/WAIT
const compOp2 = x86.Opcode.compOp2;
const compOp1r = x86.Opcode.compOp1r;
const Op3DNow = x86.Opcode.op3DNow;
const ops0 = Signature.ops0;
const ops1 = Signature.ops1;
const ops2 = Signature.ops2;
const ops3 = Signature.ops3;
const ops4 = Signature.ops4;
const ops5 = Signature.ops5;
const vex = x86.avx.AvxOpcode.vex;
const vexr = x86.avx.AvxOpcode.vexr;
const evex = x86.avx.AvxOpcode.evex;
const evexr = x86.avx.AvxOpcode.evexr;
const xop = x86.avx.AvxOpcode.xop;
const xopr = x86.avx.AvxOpcode.xopr;
const instr = InstructionItem.create;
/// Create a vector instruction
fn vec(
mnem: Mnemonic,
signature: Signature,
opcode: var,
en: InstructionEncoding,
extra_opts: var
) InstructionItem {
return InstructionItem.create(mnem, signature, opcode, en, .ZO, extra_opts);
}
const cpu = CpuFeature;
const edge = OpcodeEdgeCase;
const No64 = OpcodeEdgeCase.No64;
const No32 = OpcodeEdgeCase.No32;
const Sign = OpcodeEdgeCase.Sign;
const NoSign = OpcodeEdgeCase.NoSign;
const Lock = InstructionPrefix.Lock;
const Rep = InstructionPrefix.Rep;
const Repe = InstructionPrefix.Repe;
const Repne = InstructionPrefix.Repne;
const Bnd = InstructionPrefix.Bnd;
const Hle = InstructionPrefix.Hle;
const HleNoLock = InstructionPrefix.HleNoLock;
const Xrelease = InstructionPrefix.Xrelease;
const _8086_Legacy = cpu._8086_Legacy;
const _186_Legacy = cpu._186_Legacy;
const _286_Legacy = cpu._286_Legacy;
const _386_Legacy = cpu._386_Legacy;
const _486_Legacy = cpu._486_Legacy;
const _8086 = cpu._8086;
const _186 = cpu._186;
const _286 = cpu._286;
const _386 = cpu._386;
const _486 = cpu._486;
const x86_64 = cpu.x86_64;
const P6 = cpu.P6;
const _087 = cpu._087;
const _187 = cpu._187;
const _287 = cpu._287;
const _387 = cpu._387;
const MMX = cpu.MMX;
const MMXEXT = cpu.MMXEXT;
const SSE = cpu.SSE;
const SSE2 = cpu.SSE2;
const SSE3 = cpu.SSE3;
const SSSE3 = cpu.SSSE3;
const SSE4A = cpu.SSE4A;
const SSE4_1 = cpu.SSE4_1;
const SSE4_2 = cpu.SSE4_2;
const AVX = cpu.AVX;
const AVX2 = cpu.AVX2;
const AVX512F = cpu.AVX512F;
const AVX512CD = cpu.AVX512CD;
const AVX512ER = cpu.AVX512ER;
const AVX512PF = cpu.AVX512PF;
const AVX512VL = cpu.AVX512VL;
const AVX512BW = cpu.AVX512BW;
const AVX512DQ = cpu.AVX512DQ;
const AVX512_BITALG = cpu.AVX512_BITALG;
const AVX512_IFMA = cpu.AVX512_IFMA;
const AVX512_VBMI = cpu.AVX512_VBMI;
const AVX512_VBMI2 = cpu.AVX512_VBMI2;
const AVX512_VNNI = cpu.AVX512_VNNI;
const AVX512_VPOPCNTDQ = cpu.AVX512_VPOPCNTDQ;
const FMA = cpu.FMA;
const GFNI = cpu.GFNI;
const VAES = cpu.VAES;
const nomem = x86.avx.TupleType.NoMem;
const full = x86.avx.TupleType.Full;
const half = x86.avx.TupleType.Half;
const t1s = x86.avx.TupleType.Tuple1Scalar;
const t1f = x86.avx.TupleType.Tuple1Fixed;
const tup2 = x86.avx.TupleType.Tuple2;
const tup4 = x86.avx.TupleType.Tuple4;
const tup8 = x86.avx.TupleType.Tuple8;
const fmem = x86.avx.TupleType.FullMem;
const hmem = x86.avx.TupleType.HalfMem;
const qmem = x86.avx.TupleType.QuarterMem;
const emem = x86.avx.TupleType.EighthMem;
const mem128 = x86.avx.TupleType.Mem128;
const dup = x86.avx.TupleType.Movddup;
// NOTE: Entries into this table should be from most specific to most general.
// For example, if a instruction takes both a reg64 and rm64 value, an operand
// of Operand.register(.RAX) can match both, while a Operand.registerRm(.RAX)
// can only match the rm64 value.
//
// Putting the most specific opcodes first enables us to reach every possible
// encoding for an instruction.
//
// User supplied immediates without an explicit size are allowed to match
// against larger immediate sizes:
// * imm8 <-> imm8, imm16, imm32, imm64
// * imm16 <-> imm16, imm32, imm64
// * imm32 <-> imm32, imm64
// So if there are multiple operand signatures that only differ by there
// immediate size, we must place the version with the smaller immediate size
// first. This insures that the shortest encoding is chosen when the operand
// is an Immediate without a fixed size.
pub const instruction_database = [_]InstructionItem {
//
// 8086 / 80186
//
// AAA
instr(.AAA, ops0(), Op1(0x37), .ZO, .ZO, .{_8086, No64} ),
// AAD
instr(.AAD, ops0(), Op2(0xD5, 0x0A), .ZO, .ZO, .{_8086, No64} ),
instr(.AAD, ops1(.imm8), Op1(0xD5), .I, .ZO, .{_8086, No64} ),
// AAM
instr(.AAM, ops0(), Op2(0xD4, 0x0A), .ZO, .ZO, .{_8086, No64} ),
instr(.AAM, ops1(.imm8), Op1(0xD4), .I, .ZO, .{_8086, No64} ),
// AAS
instr(.AAS, ops0(), Op1(0x3F), .ZO, .ZO, .{_8086, No64} ),
// ADC
instr(.ADC, ops2(.reg_al, .imm8), Op1(0x14), .I2, .ZO, .{_8086} ),
instr(.ADC, ops2(.rm8, .imm8), Op1r(0x80, 2), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.ADC, ops2(.rm16, .imm8), Op1r(0x83, 2), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.ADC, ops2(.rm32, .imm8), Op1r(0x83, 2), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.ADC, ops2(.rm64, .imm8), Op1r(0x83, 2), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.ADC, ops2(.reg_ax, .imm16), Op1(0x15), .I2, .Op16, .{_8086} ),
instr(.ADC, ops2(.reg_eax, .imm32), Op1(0x15), .I2, .Op32, .{_386} ),
instr(.ADC, ops2(.reg_rax, .imm32), Op1(0x15), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.ADC, ops2(.rm16, .imm16), Op1r(0x81, 2), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.ADC, ops2(.rm32, .imm32), Op1r(0x81, 2), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.ADC, ops2(.rm64, .imm32), Op1r(0x81, 2), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.ADC, ops2(.rm8, .reg8), Op1(0x10), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.ADC, ops2(.rm16, .reg16), Op1(0x11), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.ADC, ops2(.rm32, .reg32), Op1(0x11), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.ADC, ops2(.rm64, .reg64), Op1(0x11), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.ADC, ops2(.reg8, .rm8), Op1(0x12), .RM, .ZO, .{_8086} ),
instr(.ADC, ops2(.reg16, .rm16), Op1(0x13), .RM, .Op16, .{_8086} ),
instr(.ADC, ops2(.reg32, .rm32), Op1(0x13), .RM, .Op32, .{_386} ),
instr(.ADC, ops2(.reg64, .rm64), Op1(0x13), .RM, .REX_W, .{x86_64} ),
// ADD
instr(.ADD, ops2(.reg_al, .imm8), Op1(0x04), .I2, .ZO, .{_8086} ),
instr(.ADD, ops2(.rm8, .imm8), Op1r(0x80, 0), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.ADD, ops2(.rm16, .imm8), Op1r(0x83, 0), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.ADD, ops2(.rm32, .imm8), Op1r(0x83, 0), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.ADD, ops2(.rm64, .imm8), Op1r(0x83, 0), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.ADD, ops2(.reg_ax, .imm16), Op1(0x05), .I2, .Op16, .{_8086} ),
instr(.ADD, ops2(.reg_eax, .imm32), Op1(0x05), .I2, .Op32, .{_386} ),
instr(.ADD, ops2(.reg_rax, .imm32), Op1(0x05), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.ADD, ops2(.rm16, .imm16), Op1r(0x81, 0), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.ADD, ops2(.rm32, .imm32), Op1r(0x81, 0), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.ADD, ops2(.rm64, .imm32), Op1r(0x81, 0), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.ADD, ops2(.rm8, .reg8), Op1(0x00), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.ADD, ops2(.rm16, .reg16), Op1(0x01), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.ADD, ops2(.rm32, .reg32), Op1(0x01), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.ADD, ops2(.rm64, .reg64), Op1(0x01), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.ADD, ops2(.reg8, .rm8), Op1(0x02), .RM, .ZO, .{_8086} ),
instr(.ADD, ops2(.reg16, .rm16), Op1(0x03), .RM, .Op16, .{_8086} ),
instr(.ADD, ops2(.reg32, .rm32), Op1(0x03), .RM, .Op32, .{_386} ),
instr(.ADD, ops2(.reg64, .rm64), Op1(0x03), .RM, .REX_W, .{x86_64} ),
// AND
instr(.AND, ops2(.reg_al, .imm8), Op1(0x24), .I2, .ZO, .{_8086} ),
instr(.AND, ops2(.rm8, .imm8), Op1r(0x80, 4), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.AND, ops2(.rm16, .imm8), Op1r(0x83, 4), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.AND, ops2(.rm32, .imm8), Op1r(0x83, 4), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.AND, ops2(.rm64, .imm8), Op1r(0x83, 4), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.AND, ops2(.reg_ax, .imm16), Op1(0x25), .I2, .Op16, .{_8086} ),
instr(.AND, ops2(.reg_eax, .imm32), Op1(0x25), .I2, .Op32, .{_386} ),
instr(.AND, ops2(.reg_rax, .imm32), Op1(0x25), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.AND, ops2(.rm16, .imm16), Op1r(0x81, 4), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.AND, ops2(.rm32, .imm32), Op1r(0x81, 4), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.AND, ops2(.rm64, .imm32), Op1r(0x81, 4), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.AND, ops2(.rm8, .reg8), Op1(0x20), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.AND, ops2(.rm16, .reg16), Op1(0x21), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.AND, ops2(.rm32, .reg32), Op1(0x21), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.AND, ops2(.rm64, .reg64), Op1(0x21), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.AND, ops2(.reg8, .rm8), Op1(0x22), .RM, .ZO, .{_8086} ),
instr(.AND, ops2(.reg16, .rm16), Op1(0x23), .RM, .Op16, .{_8086} ),
instr(.AND, ops2(.reg32, .rm32), Op1(0x23), .RM, .Op32, .{_386} ),
instr(.AND, ops2(.reg64, .rm64), Op1(0x23), .RM, .REX_W, .{x86_64} ),
// BOUND
instr(.BOUND, ops2(.reg16, .rm16), Op1(0x62), .RM, .Op16, .{_186, No64} ),
instr(.BOUND, ops2(.reg32, .rm32), Op1(0x62), .RM, .Op32, .{_186, No64} ),
// CALL
instr(.CALL, ops1(.imm16), Op1(0xE8), .I, .Op16, .{_8086, Bnd, No64} ),
instr(.CALL, ops1(.imm32), Op1(0xE8), .I, .Op32, .{_386, Bnd} ),
//
instr(.CALL, ops1(.rm16), Op1r(0xFF, 2), .M, .Op16, .{_8086, Bnd, No64} ),
instr(.CALL, ops1(.rm32), Op1r(0xFF, 2), .M, .Op32, .{_386, Bnd, No64} ),
instr(.CALL, ops1(.rm64), Op1r(0xFF, 2), .M, .ZO, .{x86_64, Bnd, No32} ),
//
instr(.CALL, ops1(.ptr16_16), Op1r(0x9A, 4), .D, .Op16, .{_8086, No64} ),
instr(.CALL, ops1(.ptr16_32), Op1r(0x9A, 4), .D, .Op32, .{_386, No64} ),
//
instr(.CALL, ops1(.m16_16), Op1r(0xFF, 3), .M, .Op16, .{_8086} ),
instr(.CALL, ops1(.m16_32), Op1r(0xFF, 3), .M, .Op32, .{_386} ),
instr(.CALL, ops1(.m16_64), Op1r(0xFF, 3), .M, .REX_W, .{x86_64} ),
// CBW
instr(.CBW, ops0(), Op1(0x98), .ZO, .Op16, .{_8086} ),
instr(.CWDE, ops0(), Op1(0x98), .ZO, .Op32, .{_386} ),
instr(.CDQE, ops0(), Op1(0x98), .ZO, .REX_W, .{x86_64} ),
//
instr(.CWD, ops0(), Op1(0x99), .ZO, .Op16, .{_8086} ),
instr(.CDQ, ops0(), Op1(0x99), .ZO, .Op32, .{_386} ),
instr(.CQO, ops0(), Op1(0x99), .ZO, .REX_W, .{x86_64} ),
// CLC
instr(.CLC, ops0(), Op1(0xF8), .ZO, .ZO, .{_8086} ),
// CLD
instr(.CLD, ops0(), Op1(0xFC), .ZO, .ZO, .{_8086} ),
// CLI
instr(.CLI, ops0(), Op1(0xFA), .ZO, .ZO, .{_8086} ),
// CMC
instr(.CMC, ops0(), Op1(0xF5), .ZO, .ZO, .{_8086} ),
// CMP
instr(.CMP, ops2(.reg_al, .imm8), Op1(0x3C), .I2, .ZO, .{_8086} ),
instr(.CMP, ops2(.rm8, .imm8), Op1r(0x80, 7), .MI, .ZO, .{_8086} ),
instr(.CMP, ops2(.rm16, .imm8), Op1r(0x83, 7), .MI, .Op16, .{_8086, Sign} ),
instr(.CMP, ops2(.rm32, .imm8), Op1r(0x83, 7), .MI, .Op32, .{_386, Sign} ),
instr(.CMP, ops2(.rm64, .imm8), Op1r(0x83, 7), .MI, .REX_W, .{x86_64, Sign} ),
//
instr(.CMP, ops2(.reg_ax, .imm16), Op1(0x3D), .I2, .Op16, .{_8086} ),
instr(.CMP, ops2(.reg_eax, .imm32), Op1(0x3D), .I2, .Op32, .{_386} ),
instr(.CMP, ops2(.reg_rax, .imm32), Op1(0x3D), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.CMP, ops2(.rm16, .imm16), Op1r(0x81, 7), .MI, .Op16, .{_8086} ),
instr(.CMP, ops2(.rm32, .imm32), Op1r(0x81, 7), .MI, .Op32, .{_386} ),
instr(.CMP, ops2(.rm64, .imm32), Op1r(0x81, 7), .MI, .REX_W, .{x86_64, Sign} ),
//
instr(.CMP, ops2(.rm8, .reg8), Op1(0x38), .MR, .ZO, .{_8086} ),
instr(.CMP, ops2(.rm16, .reg16), Op1(0x39), .MR, .Op16, .{_8086} ),
instr(.CMP, ops2(.rm32, .reg32), Op1(0x39), .MR, .Op32, .{_386} ),
instr(.CMP, ops2(.rm64, .reg64), Op1(0x39), .MR, .REX_W, .{x86_64} ),
//
instr(.CMP, ops2(.reg8, .rm8), Op1(0x3A), .RM, .ZO, .{_8086} ),
instr(.CMP, ops2(.reg16, .rm16), Op1(0x3B), .RM, .Op16, .{_8086} ),
instr(.CMP, ops2(.reg32, .rm32), Op1(0x3B), .RM, .Op32, .{_386} ),
instr(.CMP, ops2(.reg64, .rm64), Op1(0x3B), .RM, .REX_W, .{x86_64} ),
// CMPS / CMPSB / CMPSW / CMPSD / CMPSQ
instr(.CMPS, ops2(.rm_mem8, .rm_mem8), Op1(0xA6), .MSpec, .ZO, .{_8086, Repe, Repne} ),
instr(.CMPS, ops2(.rm_mem16, .rm_mem16), Op1(0xA7), .MSpec, .Op16, .{_8086, Repe, Repne} ),
instr(.CMPS, ops2(.rm_mem32, .rm_mem32), Op1(0xA7), .MSpec, .Op32, .{_386, Repe, Repne} ),
instr(.CMPS, ops2(.rm_mem64, .rm_mem64), Op1(0xA7), .MSpec, .REX_W,.{x86_64, Repe, Repne} ),
//
instr(.CMPSB, ops0(), Op1(0xA6), .ZO, .ZO, .{_8086, Repe, Repne} ),
instr(.CMPSW, ops0(), Op1(0xA7), .ZO, .Op16, .{_8086, Repe, Repne} ),
// instr(.CMPSD, ops0(), Op1(0xA7), .ZO, .Op32, .{_386, Repe, Repne} ), // overloaded
instr(.CMPSQ, ops0(), Op1(0xA7), .ZO, .REX_W, .{x86_64, No32, Repe, Repne} ),
// DAA
instr(.DAA, ops0(), Op1(0x27), .ZO, .ZO, .{_8086, No64} ),
// DAS
instr(.DAS, ops0(), Op1(0x2F), .ZO, .ZO, .{_8086, No64} ),
// DEC
instr(.DEC, ops1(.reg16), Op1(0x48), .O, .Op16, .{_8086, No64} ),
instr(.DEC, ops1(.reg32), Op1(0x48), .O, .Op32, .{_386, No64} ),
instr(.DEC, ops1(.rm8), Op1r(0xFE, 1), .M, .ZO, .{_8086, Lock, Hle} ),
instr(.DEC, ops1(.rm16), Op1r(0xFF, 1), .M, .Op16, .{_8086, Lock, Hle} ),
instr(.DEC, ops1(.rm32), Op1r(0xFF, 1), .M, .Op32, .{_386, Lock, Hle} ),
instr(.DEC, ops1(.rm64), Op1r(0xFF, 1), .M, .REX_W, .{x86_64, Lock, Hle} ),
// DIV
instr(.DIV, ops1(.rm8), Op1r(0xF6, 6), .M, .ZO, .{_8086} ),
instr(.DIV, ops1(.rm16), Op1r(0xF7, 6), .M, .Op16, .{_8086} ),
instr(.DIV, ops1(.rm32), Op1r(0xF7, 6), .M, .Op32, .{_386} ),
instr(.DIV, ops1(.rm64), Op1r(0xF7, 6), .M, .REX_W, .{x86_64} ),
// ENTER
instr(.ENTER, ops2(.imm16, .imm8), Op1(0xC8), .II, .ZO, .{_186} ),
instr(.ENTERW, ops2(.imm16, .imm8), Op1(0xC8), .II, .Op16, .{_186} ),
instr(.ENTERD, ops2(.imm16, .imm8), Op1(0xC8), .II, .Op32, .{_386, No64} ),
instr(.ENTERQ, ops2(.imm16, .imm8), Op1(0xC8), .II, .ZO, .{x86_64, No32} ),
// HLT
instr(.HLT, ops0(), Op1(0xF4), .ZO, .ZO, .{_8086} ),
// IDIV
instr(.IDIV, ops1(.rm8), Op1r(0xF6, 7), .M, .ZO, .{_8086} ),
instr(.IDIV, ops1(.rm16), Op1r(0xF7, 7), .M, .Op16, .{_8086} ),
instr(.IDIV, ops1(.rm32), Op1r(0xF7, 7), .M, .Op32, .{_386} ),
instr(.IDIV, ops1(.rm64), Op1r(0xF7, 7), .M, .REX_W, .{x86_64} ),
// IMUL
instr(.IMUL, ops1(.rm8), Op1r(0xF6, 5), .M, .ZO, .{_8086} ),
instr(.IMUL, ops1(.rm16), Op1r(0xF7, 5), .M, .Op16, .{_8086} ),
instr(.IMUL, ops1(.rm32), Op1r(0xF7, 5), .M, .Op32, .{_386} ),
instr(.IMUL, ops1(.rm64), Op1r(0xF7, 5), .M, .REX_W, .{x86_64} ),
//
instr(.IMUL, ops2(.reg16, .rm16), Op2(0x0F, 0xAF), .RM, .Op16, .{_8086} ),
instr(.IMUL, ops2(.reg32, .rm32), Op2(0x0F, 0xAF), .RM, .Op32, .{_386} ),
instr(.IMUL, ops2(.reg64, .rm64), Op2(0x0F, 0xAF), .RM, .REX_W, .{x86_64} ),
//
instr(.IMUL, ops3(.reg16, .rm16, .imm8), Op1(0x6B), .RMI, .Op16, .{_186, Sign} ),
instr(.IMUL, ops3(.reg32, .rm32, .imm8), Op1(0x6B), .RMI, .Op32, .{_386, Sign} ),
instr(.IMUL, ops3(.reg64, .rm64, .imm8), Op1(0x6B), .RMI, .REX_W, .{x86_64, Sign} ),
//
instr(.IMUL, ops3(.reg16, .rm16, .imm16),Op1(0x69), .RMI, .Op16, .{_186} ),
instr(.IMUL, ops3(.reg32, .rm32, .imm32),Op1(0x69), .RMI, .Op32, .{_386} ),
instr(.IMUL, ops3(.reg64, .rm64, .imm32),Op1(0x69), .RMI, .REX_W, .{x86_64, Sign} ),
// IN
instr(.IN, ops2(.reg_al, .imm8), Op1(0xE4), .I2, .ZO, .{_8086} ),
instr(.IN, ops2(.reg_ax, .imm8), Op1(0xE5), .I2, .Op16, .{_8086} ),
instr(.IN, ops2(.reg_eax, .imm8), Op1(0xE5), .I2, .Op32, .{_386} ),
instr(.IN, ops2(.reg_al, .reg_dx), Op1(0xEC), .ZO, .ZO, .{_8086} ),
instr(.IN, ops2(.reg_ax, .reg_dx), Op1(0xED), .ZO, .Op16, .{_8086} ),
instr(.IN, ops2(.reg_eax, .reg_dx), Op1(0xED), .ZO, .Op32, .{_386} ),
// INC
instr(.INC, ops1(.reg16), Op1(0x40), .O, .Op16, .{_8086, No64} ),
instr(.INC, ops1(.reg32), Op1(0x40), .O, .Op32, .{_386, No64} ),
instr(.INC, ops1(.rm8), Op1r(0xFE, 0), .M, .ZO, .{_8086, Lock, Hle} ),
instr(.INC, ops1(.rm16), Op1r(0xFF, 0), .M, .Op16, .{_8086, Lock, Hle} ),
instr(.INC, ops1(.rm32), Op1r(0xFF, 0), .M, .Op32, .{_386, Lock, Hle} ),
instr(.INC, ops1(.rm64), Op1r(0xFF, 0), .M, .REX_W, .{x86_64, Lock, Hle} ),
// INS / INSB / INSW / INSD
instr(.INS, ops2(.rm_mem8, .reg_dx), Op1(0x6C), .MSpec, .ZO, .{_186, Rep} ),
instr(.INS, ops2(.rm_mem16, .reg_dx), Op1(0x6D), .MSpec, .Op16, .{_186, Rep} ),
instr(.INS, ops2(.rm_mem32, .reg_dx), Op1(0x6D), .MSpec, .Op32, .{x86_64, Rep} ),
//
instr(.INSB, ops0(), Op1(0x6C), .ZO, .ZO, .{_186, Rep} ),
instr(.INSW, ops0(), Op1(0x6D), .ZO, .Op16, .{_186, Rep} ),
instr(.INSD, ops0(), Op1(0x6D), .ZO, .Op32, .{_386, Rep} ),
// INT
instr(.INT3, ops0(), Op1(0xCC), .ZO, .ZO, .{_8086} ),
instr(.INT, ops1(.imm8), Op1(0xCD), .I, .ZO, .{_8086} ),
instr(.INTO, ops0(), Op1(0xCE), .ZO, .ZO, .{_8086, No64} ),
instr(.INT1, ops0(), Op1(0xF1), .ZO, .ZO, .{_386} ),
instr(.ICEBP, ops0(), Op1(0xF1), .ZO, .ZO, .{_386} ),
// IRET
instr(.IRET, ops0(), Op1(0xCF), .ZO, .ZO, .{_8086} ),
instr(.IRETW, ops0(), Op1(0xCF), .ZO, .Op16, .{_8086} ),
instr(.IRETD, ops0(), Op1(0xCF), .ZO, .Op32, .{_386, No64} ),
instr(.IRETQ, ops0(), Op1(0xCF), .ZO, .ZO, .{x86_64, No32} ),
// Jcc
instr(.JCXZ, ops1(.imm8), Op1(0xE3), .I, .Addr16, .{_8086, Sign, No64} ),
instr(.JECXZ, ops1(.imm8), Op1(0xE3), .I, .Addr32, .{_386, Sign} ),
instr(.JRCXZ, ops1(.imm8), Op1(0xE3), .I, .Addr64, .{x86_64, Sign, No32} ),
//
instr(.JA, ops1(.imm8), Op1(0x77), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JA, ops1(.imm16), Op2(0x0F, 0x87), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JA, ops1(.imm32), Op2(0x0F, 0x87), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JAE, ops1(.imm8), Op1(0x73), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JAE, ops1(.imm16), Op2(0x0F, 0x83), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JAE, ops1(.imm32), Op2(0x0F, 0x83), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JB, ops1(.imm8), Op1(0x72), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JB, ops1(.imm16), Op2(0x0F, 0x82), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JB, ops1(.imm32), Op2(0x0F, 0x82), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JBE, ops1(.imm8), Op1(0x76), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JBE, ops1(.imm16), Op2(0x0F, 0x86), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JBE, ops1(.imm32), Op2(0x0F, 0x86), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JC, ops1(.imm8), Op1(0x72), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JC, ops1(.imm16), Op2(0x0F, 0x82), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JC, ops1(.imm32), Op2(0x0F, 0x82), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JE, ops1(.imm8), Op1(0x74), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JE, ops1(.imm16), Op2(0x0F, 0x84), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JE, ops1(.imm32), Op2(0x0F, 0x84), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JG, ops1(.imm8), Op1(0x7F), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JG, ops1(.imm16), Op2(0x0F, 0x8F), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JG, ops1(.imm32), Op2(0x0F, 0x8F), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JGE, ops1(.imm8), Op1(0x7D), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JGE, ops1(.imm16), Op2(0x0F, 0x8D), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JGE, ops1(.imm32), Op2(0x0F, 0x8D), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JL, ops1(.imm8), Op1(0x7C), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JL, ops1(.imm16), Op2(0x0F, 0x8C), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JL, ops1(.imm32), Op2(0x0F, 0x8C), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JLE, ops1(.imm8), Op1(0x7E), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JLE, ops1(.imm16), Op2(0x0F, 0x8E), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JLE, ops1(.imm32), Op2(0x0F, 0x8E), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNA, ops1(.imm8), Op1(0x76), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNA, ops1(.imm16), Op2(0x0F, 0x86), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNA, ops1(.imm32), Op2(0x0F, 0x86), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNAE, ops1(.imm8), Op1(0x72), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNAE, ops1(.imm16), Op2(0x0F, 0x82), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNAE, ops1(.imm32), Op2(0x0F, 0x82), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNB, ops1(.imm8), Op1(0x73), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNB, ops1(.imm16), Op2(0x0F, 0x83), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNB, ops1(.imm32), Op2(0x0F, 0x83), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNBE, ops1(.imm8), Op1(0x77), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNBE, ops1(.imm16), Op2(0x0F, 0x87), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNBE, ops1(.imm32), Op2(0x0F, 0x87), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNC, ops1(.imm8), Op1(0x73), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNC, ops1(.imm16), Op2(0x0F, 0x83), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNC, ops1(.imm32), Op2(0x0F, 0x83), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNE, ops1(.imm8), Op1(0x75), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNE, ops1(.imm16), Op2(0x0F, 0x85), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNE, ops1(.imm32), Op2(0x0F, 0x85), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNG, ops1(.imm8), Op1(0x7E), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNG, ops1(.imm16), Op2(0x0F, 0x8E), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNG, ops1(.imm32), Op2(0x0F, 0x8E), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNGE, ops1(.imm8), Op1(0x7C), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNGE, ops1(.imm16), Op2(0x0F, 0x8C), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNGE, ops1(.imm32), Op2(0x0F, 0x8C), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNL, ops1(.imm8), Op1(0x7D), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNL, ops1(.imm16), Op2(0x0F, 0x8D), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNL, ops1(.imm32), Op2(0x0F, 0x8D), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNLE, ops1(.imm8), Op1(0x7F), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNLE, ops1(.imm16), Op2(0x0F, 0x8F), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNLE, ops1(.imm32), Op2(0x0F, 0x8F), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNO, ops1(.imm8), Op1(0x71), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNO, ops1(.imm16), Op2(0x0F, 0x81), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNO, ops1(.imm32), Op2(0x0F, 0x81), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNP, ops1(.imm8), Op1(0x7B), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNP, ops1(.imm16), Op2(0x0F, 0x8B), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNP, ops1(.imm32), Op2(0x0F, 0x8B), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNS, ops1(.imm8), Op1(0x79), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNS, ops1(.imm16), Op2(0x0F, 0x89), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNS, ops1(.imm32), Op2(0x0F, 0x89), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JNZ, ops1(.imm8), Op1(0x75), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JNZ, ops1(.imm16), Op2(0x0F, 0x85), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JNZ, ops1(.imm32), Op2(0x0F, 0x85), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JO, ops1(.imm8), Op1(0x70), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JO, ops1(.imm16), Op2(0x0F, 0x80), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JO, ops1(.imm32), Op2(0x0F, 0x80), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JP, ops1(.imm8), Op1(0x7A), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JP, ops1(.imm16), Op2(0x0F, 0x8A), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JP, ops1(.imm32), Op2(0x0F, 0x8A), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JPE, ops1(.imm8), Op1(0x7A), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JPE, ops1(.imm16), Op2(0x0F, 0x8A), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JPE, ops1(.imm32), Op2(0x0F, 0x8A), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JPO, ops1(.imm8), Op1(0x7B), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JPO, ops1(.imm16), Op2(0x0F, 0x8B), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JPO, ops1(.imm32), Op2(0x0F, 0x8B), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JS, ops1(.imm8), Op1(0x78), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JS, ops1(.imm16), Op2(0x0F, 0x88), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JS, ops1(.imm32), Op2(0x0F, 0x88), .I, .Op32, .{_386, Sign, Bnd} ),
instr(.JZ, ops1(.imm8), Op1(0x74), .I, .ZO, .{_8086, Sign, Bnd} ),
instr(.JZ, ops1(.imm16), Op2(0x0F, 0x84), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JZ, ops1(.imm32), Op2(0x0F, 0x84), .I, .Op32, .{_386, Sign, Bnd} ),
// JMP
instr(.JMP, ops1(.imm8), Op1(0xEB), .I, .ZO, .{_8086, Sign} ),
instr(.JMP, ops1(.imm16), Op1(0xE9), .I, .Op16, .{_8086, Sign, Bnd, No64} ),
instr(.JMP, ops1(.imm32), Op1(0xE9), .I, .Op32, .{_386, Sign, Bnd} ),
//
instr(.JMP, ops1(.rm16), Op1r(0xFF, 4), .M, .Op16, .{_8086, Bnd, No64} ),
instr(.JMP, ops1(.rm32), Op1r(0xFF, 4), .M, .Op32, .{_386, Bnd, No64} ),
instr(.JMP, ops1(.rm64), Op1r(0xFF, 4), .M, .ZO, .{x86_64, Bnd, No32} ),
//
instr(.JMP, ops1(.ptr16_16), Op1r(0xEA, 4), .D, .Op16, .{_8086, No64} ),
instr(.JMP, ops1(.ptr16_32), Op1r(0xEA, 4), .D, .Op32, .{_386, No64} ),
//
instr(.JMP, ops1(.m16_16), Op1r(0xFF, 5), .M, .Op16, .{_8086} ),
instr(.JMP, ops1(.m16_32), Op1r(0xFF, 5), .M, .Op32, .{_386} ),
instr(.JMP, ops1(.m16_64), Op1r(0xFF, 5), .M, .REX_W, .{x86_64} ),
// LAHF
instr(.LAHF, ops0(), Op1(0x9F), .ZO, .ZO, .{_8086, No64} ),
instr(.LAHF, ops0(), Op1(0x9F), .ZO, .ZO, .{_8086, cpu.LAHF_SAHF, No32} ),
// SAHF
instr(.SAHF, ops0(), Op1(0x9E), .ZO, .ZO, .{_8086, No64} ),
instr(.SAHF, ops0(), Op1(0x9E), .ZO, .ZO, .{_8086, cpu.LAHF_SAHF, No32} ),
// LDS / LSS / LES / LFS / LGS
instr(.LDS, ops2(.reg16, .m16_16), Op1(0xC5), .RM, .Op16, .{_8086, No64} ),
instr(.LDS, ops2(.reg32, .m16_32), Op1(0xC5), .RM, .Op32, .{_386, No64} ),
//
instr(.LSS, ops2(.reg16, .m16_16), Op2(0x0F, 0xB2), .RM, .Op16, .{_386} ),
instr(.LSS, ops2(.reg32, .m16_32), Op2(0x0F, 0xB2), .RM, .Op32, .{_386} ),
instr(.LSS, ops2(.reg64, .m16_64), Op2(0x0F, 0xB2), .RM, .REX_W, .{x86_64} ),
//
instr(.LES, ops2(.reg16, .m16_16), Op1(0xC4), .RM, .Op16, .{_8086, No64} ),
instr(.LES, ops2(.reg32, .m16_32), Op1(0xC4), .RM, .Op32, .{_386, No64} ),
//
instr(.LFS, ops2(.reg16, .m16_16), Op2(0x0F, 0xB4), .RM, .Op16, .{_386} ),
instr(.LFS, ops2(.reg32, .m16_32), Op2(0x0F, 0xB4), .RM, .Op32, .{_386} ),
instr(.LFS, ops2(.reg64, .m16_64), Op2(0x0F, 0xB4), .RM, .REX_W, .{x86_64} ),
//
instr(.LGS, ops2(.reg16, .m16_16), Op2(0x0F, 0xB5), .RM, .Op16, .{_386} ),
instr(.LGS, ops2(.reg32, .m16_32), Op2(0x0F, 0xB5), .RM, .Op32, .{_386} ),
instr(.LGS, ops2(.reg64, .m16_64), Op2(0x0F, 0xB5), .RM, .REX_W, .{x86_64} ),
//
// LEA
instr(.LEA, ops2(.reg16, .rm_mem16), Op1(0x8D), .RM, .Op16, .{_8086} ),
instr(.LEA, ops2(.reg32, .rm_mem32), Op1(0x8D), .RM, .Op32, .{_386} ),
instr(.LEA, ops2(.reg64, .rm_mem64), Op1(0x8D), .RM, .REX_W, .{x86_64} ),
// LEAVE
instr(.LEAVE, ops0(), Op1(0xC9), .ZO, .ZO, .{_186} ),
instr(.LEAVEW, ops0(), Op1(0xC9), .ZO, .Op16, .{_186} ),
instr(.LEAVED, ops0(), Op1(0xC9), .ZO, .Op32, .{_386, No64} ),
instr(.LEAVEQ, ops0(), Op1(0xC9), .ZO, .ZO, .{x86_64, No32} ),
// LOCK
instr(.LOCK, ops0(), Op1(0xF0), .ZO, .ZO, .{_8086} ),
// LODS / LODSB / LODSW / LODSD / LODSQ
instr(.LODS, ops2(.reg_al, .rm_mem8), Op1(0xAC), .MSpec, .ZO, .{_8086, Rep} ),
instr(.LODS, ops2(.reg_ax, .rm_mem16), Op1(0xAD), .MSpec, .Op16, .{_8086, Rep} ),
instr(.LODS, ops2(.reg_eax, .rm_mem32), Op1(0xAD), .MSpec, .Op32, .{_386, Rep} ),
instr(.LODS, ops2(.reg_rax, .rm_mem64), Op1(0xAD), .MSpec, .REX_W,.{x86_64, Rep} ),
//
instr(.LODSB, ops0(), Op1(0xAC), .ZO, .ZO, .{_8086, Rep} ),
instr(.LODSW, ops0(), Op1(0xAD), .ZO, .Op16, .{_8086, Rep} ),
instr(.LODSD, ops0(), Op1(0xAD), .ZO, .Op32, .{_386, Rep} ),
instr(.LODSQ, ops0(), Op1(0xAD), .ZO, .REX_W, .{x86_64, No32, Rep} ),
// LOOP
instr(.LOOP, ops1(.imm8), Op1(0xE2), .I, .ZO, .{_8086, Sign} ),
instr(.LOOPE, ops1(.imm8), Op1(0xE1), .I, .ZO, .{_8086, Sign} ),
instr(.LOOPNE, ops1(.imm8), Op1(0xE0), .I, .ZO, .{_8086, Sign} ),
//
instr(.LOOPW, ops1(.imm8), Op1(0xE2), .I, .Addr16, .{_386, Sign, No64} ),
instr(.LOOPEW, ops1(.imm8), Op1(0xE1), .I, .Addr16, .{_386, Sign, No64} ),
instr(.LOOPNEW, ops1(.imm8), Op1(0xE0), .I, .Addr16, .{_386, Sign, No64} ),
//
instr(.LOOPD, ops1(.imm8), Op1(0xE2), .I, .Addr32, .{_386, Sign} ),
instr(.LOOPED, ops1(.imm8), Op1(0xE1), .I, .Addr32, .{_386, Sign} ),
instr(.LOOPNED, ops1(.imm8), Op1(0xE0), .I, .Addr32, .{_386, Sign} ),
// MOV
instr(.MOV, ops2(.rm8, .reg8), Op1(0x88), .MR, .ZO, .{_8086, Xrelease} ),
instr(.MOV, ops2(.rm16, .reg16), Op1(0x89), .MR, .Op16, .{_8086, Xrelease} ),
instr(.MOV, ops2(.rm32, .reg32), Op1(0x89), .MR, .Op32, .{_386, Xrelease} ),
instr(.MOV, ops2(.rm64, .reg64), Op1(0x89), .MR, .REX_W, .{x86_64, Xrelease} ),
//
instr(.MOV, ops2(.reg8, .rm8), Op1(0x8A), .RM, .ZO, .{_8086} ),
instr(.MOV, ops2(.reg16, .rm16), Op1(0x8B), .RM, .Op16, .{_8086} ),
instr(.MOV, ops2(.reg32, .rm32), Op1(0x8B), .RM, .Op32, .{_386} ),
instr(.MOV, ops2(.reg64, .rm64), Op1(0x8B), .RM, .REX_W, .{x86_64} ),
//
instr(.MOV, ops2(.rm16, .reg_seg), Op1(0x8C), .MR, .Op16, .{_8086} ),
instr(.MOV, ops2(.rm32, .reg_seg), Op1(0x8C), .MR, .Op32, .{_386} ),
instr(.MOV, ops2(.rm64, .reg_seg), Op1(0x8C), .MR, .REX_W, .{x86_64} ),
//
instr(.MOV, ops2(.reg_seg, .rm16), Op1(0x8E), .RM, .Op16, .{_8086} ),
instr(.MOV, ops2(.reg_seg, .rm32), Op1(0x8E), .RM, .Op32, .{_386} ),
instr(.MOV, ops2(.reg_seg, .rm64), Op1(0x8E), .RM, .REX_W, .{x86_64} ),
instr(.MOV, ops2(.reg_al, .moffs8), Op1(0xA0), .FD, .ZO, .{_8086} ),
instr(.MOV, ops2(.reg_ax, .moffs16), Op1(0xA1), .FD, .Op16, .{_8086} ),
instr(.MOV, ops2(.reg_eax, .moffs32), Op1(0xA1), .FD, .Op32, .{_386} ),
instr(.MOV, ops2(.reg_rax, .moffs64), Op1(0xA1), .FD, .REX_W, .{x86_64} ),
instr(.MOV, ops2(.moffs8, .reg_al), Op1(0xA2), .TD, .ZO, .{_8086} ),
instr(.MOV, ops2(.moffs16, .reg_ax), Op1(0xA3), .TD, .Op16, .{_8086} ),
instr(.MOV, ops2(.moffs32, .reg_eax), Op1(0xA3), .TD, .Op32, .{_386} ),
instr(.MOV, ops2(.moffs64, .reg_rax), Op1(0xA3), .TD, .REX_W, .{x86_64} ),
//
instr(.MOV, ops2(.reg8, .imm8), Op1(0xB0), .OI, .ZO, .{_8086} ),
instr(.MOV, ops2(.reg16, .imm16), Op1(0xB8), .OI, .Op16, .{_8086} ),
instr(.MOV, ops2(.reg32, .imm32), Op1(0xB8), .OI, .Op32, .{_386} ),
instr(.MOV, ops2(.reg64, .imm32), Op1(0xB8), .OI, .ZO, .{x86_64, NoSign, No32} ),
instr(.MOV, ops2(.reg64, .imm64), Op1(0xB8), .OI, .REX_W, .{x86_64} ),
//
instr(.MOV, ops2(.rm8, .imm8), Op1r(0xC6, 0), .MI, .ZO, .{_8086, Xrelease} ),
instr(.MOV, ops2(.rm16, .imm16), Op1r(0xC7, 0), .MI, .Op16, .{_8086, Xrelease} ),
instr(.MOV, ops2(.rm32, .imm32), Op1r(0xC7, 0), .MI, .Op32, .{_386, Xrelease} ),
instr(.MOV, ops2(.rm64, .imm32), Op1r(0xC7, 0), .MI, .REX_W, .{x86_64, Xrelease} ),
// 386 MOV to/from Control Registers
instr(.MOV, ops2(.reg32, .reg_cr), Op2(0x0F, 0x20), .MR, .ZO, .{_386, No64} ),
instr(.MOV, ops2(.reg64, .reg_cr), Op2(0x0F, 0x20), .MR, .ZO, .{x86_64, No32} ),
//
instr(.MOV, ops2(.reg_cr, .reg32), Op2(0x0F, 0x22), .RM, .ZO, .{_386, No64} ),
instr(.MOV, ops2(.reg_cr, .reg64), Op2(0x0F, 0x22), .RM, .ZO, .{x86_64, No32} ),
// 386 MOV to/from Debug Registers
instr(.MOV, ops2(.reg32, .reg_dr), Op2(0x0F, 0x21), .MR, .ZO, .{_386, No64} ),
instr(.MOV, ops2(.reg64, .reg_dr), Op2(0x0F, 0x21), .MR, .ZO, .{x86_64, No32} ),
//
instr(.MOV, ops2(.reg_dr, .reg32), Op2(0x0F, 0x23), .RM, .ZO, .{_386, No64} ),
instr(.MOV, ops2(.reg_dr, .reg64), Op2(0x0F, 0x23), .RM, .ZO, .{x86_64, No32} ),
// MOVS / MOVSB / MOVSW / MOVSD / MOVSQ
instr(.MOVS, ops2(.rm_mem8, .rm_mem8), Op1(0xA4), .MSpec, .ZO, .{_8086, Rep} ),
instr(.MOVS, ops2(.rm_mem16, .rm_mem16), Op1(0xA5), .MSpec, .Op16, .{_8086, Rep} ),
instr(.MOVS, ops2(.rm_mem32, .rm_mem32), Op1(0xA5), .MSpec, .Op32, .{_386, Rep} ),
instr(.MOVS, ops2(.rm_mem64, .rm_mem64), Op1(0xA5), .MSpec, .REX_W,.{x86_64, Rep} ),
//
instr(.MOVSB, ops0(), Op1(0xA4), .ZO, .ZO, .{_8086, Rep} ),
instr(.MOVSW, ops0(), Op1(0xA5), .ZO, .Op16, .{_8086, Rep} ),
// instr(.MOVSD, ops0(), Op1(0xA5), .ZO, .Op32, .{_386, Rep} ), // overloaded
instr(.MOVSQ, ops0(), Op1(0xA5), .ZO, .REX_W, .{x86_64, No32, Rep} ),
// MUL
instr(.MUL, ops1(.rm8), Op1r(0xF6, 4), .M, .ZO, .{_8086} ),
instr(.MUL, ops1(.rm16), Op1r(0xF7, 4), .M, .Op16, .{_8086} ),
instr(.MUL, ops1(.rm32), Op1r(0xF7, 4), .M, .Op32, .{_386} ),
instr(.MUL, ops1(.rm64), Op1r(0xF7, 4), .M, .REX_W, .{x86_64} ),
// NEG
instr(.NEG, ops1(.rm8), Op1r(0xF6, 3), .M, .ZO, .{_8086, Lock, Hle} ),
instr(.NEG, ops1(.rm16), Op1r(0xF7, 3), .M, .Op16, .{_8086, Lock, Hle} ),
instr(.NEG, ops1(.rm32), Op1r(0xF7, 3), .M, .Op32, .{_386, Lock, Hle} ),
instr(.NEG, ops1(.rm64), Op1r(0xF7, 3), .M, .REX_W, .{x86_64, Lock, Hle} ),
// NOP
instr(.NOP, ops0(), Op1(0x90), .ZO, .ZO, .{_8086} ),
instr(.NOP, ops1(.rm16), Op2r(0x0F, 0x1F, 0), .M, .Op16, .{P6} ),
instr(.NOP, ops1(.rm32), Op2r(0x0F, 0x1F, 0), .M, .Op32, .{P6} ),
instr(.NOP, ops1(.rm64), Op2r(0x0F, 0x1F, 0), .M, .REX_W, .{x86_64} ),
// NOT
instr(.NOT, ops1(.rm8), Op1r(0xF6, 2), .M, .ZO, .{_8086, Lock, Hle} ),
instr(.NOT, ops1(.rm16), Op1r(0xF7, 2), .M, .Op16, .{_8086, Lock, Hle} ),
instr(.NOT, ops1(.rm32), Op1r(0xF7, 2), .M, .Op32, .{_386, Lock, Hle} ),
instr(.NOT, ops1(.rm64), Op1r(0xF7, 2), .M, .REX_W, .{x86_64, Lock, Hle} ),
// OR
instr(.OR, ops2(.reg_al, .imm8), Op1(0x0C), .I2, .ZO, .{_8086} ),
instr(.OR, ops2(.rm8, .imm8), Op1r(0x80, 1), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.OR, ops2(.rm16, .imm8), Op1r(0x83, 1), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.OR, ops2(.rm32, .imm8), Op1r(0x83, 1), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.OR, ops2(.rm64, .imm8), Op1r(0x83, 1), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.OR, ops2(.reg_ax, .imm16), Op1(0x0D), .I2, .Op16, .{_8086} ),
instr(.OR, ops2(.reg_eax, .imm32), Op1(0x0D), .I2, .Op32, .{_386} ),
instr(.OR, ops2(.reg_rax, .imm32), Op1(0x0D), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.OR, ops2(.rm16, .imm16), Op1r(0x81, 1), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.OR, ops2(.rm32, .imm32), Op1r(0x81, 1), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.OR, ops2(.rm64, .imm32), Op1r(0x81, 1), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.OR, ops2(.rm8, .reg8), Op1(0x08), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.OR, ops2(.rm16, .reg16), Op1(0x09), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.OR, ops2(.rm32, .reg32), Op1(0x09), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.OR, ops2(.rm64, .reg64), Op1(0x09), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.OR, ops2(.reg8, .rm8), Op1(0x0A), .RM, .ZO, .{_8086} ),
instr(.OR, ops2(.reg16, .rm16), Op1(0x0B), .RM, .Op16, .{_8086} ),
instr(.OR, ops2(.reg32, .rm32), Op1(0x0B), .RM, .Op32, .{_386} ),
instr(.OR, ops2(.reg64, .rm64), Op1(0x0B), .RM, .REX_W, .{x86_64} ),
// OUT
instr(.OUT, ops2(.imm8, .reg_al), Op1(0xE6), .I, .ZO, .{_8086} ),
instr(.OUT, ops2(.imm8, .reg_ax), Op1(0xE7), .I, .Op16, .{_8086} ),
instr(.OUT, ops2(.imm8, .reg_eax), Op1(0xE7), .I, .Op32, .{_386} ),
instr(.OUT, ops2(.reg_dx, .reg_al), Op1(0xEE), .ZO, .ZO, .{_8086} ),
instr(.OUT, ops2(.reg_dx, .reg_ax), Op1(0xEF), .ZO, .Op16, .{_8086} ),
instr(.OUT, ops2(.reg_dx, .reg_eax), Op1(0xEF), .ZO, .Op32, .{_386} ),
// OUTS / OUTSB / OUTSW / OUTSD
instr(.OUTS, ops2(.reg_dx, .rm_mem8), Op1(0x6E), .MSpec, .ZO, .{_186, Rep} ),
instr(.OUTS, ops2(.reg_dx, .rm_mem16), Op1(0x6F), .MSpec, .Op16, .{_186, Rep} ),
instr(.OUTS, ops2(.reg_dx, .rm_mem32), Op1(0x6F), .MSpec, .Op32, .{x86_64, Rep} ),
//
instr(.OUTSB, ops0(), Op1(0x6E), .ZO, .ZO, .{_186, Rep} ),
instr(.OUTSW, ops0(), Op1(0x6F), .ZO, .Op16, .{_186, Rep} ),
instr(.OUTSD, ops0(), Op1(0x6F), .ZO, .Op32, .{_386, Rep} ),
// POP
instr(.POP, ops1(.reg16), Op1(0x58), .O, .Op16, .{_8086} ),
instr(.POP, ops1(.reg32), Op1(0x58), .O, .Op32, .{_386, No64} ),
instr(.POP, ops1(.reg64), Op1(0x58), .O, .ZO, .{x86_64, No32} ),
//
instr(.POP, ops1(.rm16), Op1r(0x8F, 0), .M, .Op16, .{_8086} ),
instr(.POP, ops1(.rm32), Op1r(0x8F, 0), .M, .Op32, .{_386, No64} ),
instr(.POP, ops1(.rm64), Op1r(0x8F, 0), .M, .ZO, .{x86_64, No32} ),
//
instr(.POP, ops1(.reg_cs), Op1(0x0F), .ZO, .ZO, .{_8086_Legacy, No64} ),
instr(.POP, ops1(.reg_ds), Op1(0x1F), .ZO, .ZO, .{_8086, No64} ),
instr(.POP, ops1(.reg_es), Op1(0x07), .ZO, .ZO, .{_8086, No64} ),
instr(.POP, ops1(.reg_ss), Op1(0x17), .ZO, .ZO, .{_8086, No64} ),
instr(.POP, ops1(.reg_fs), Op2(0x0F, 0xA1), .ZO, .ZO, .{_386} ),
instr(.POP, ops1(.reg_gs), Op2(0x0F, 0xA9), .ZO, .ZO, .{_386} ),
//
instr(.POPW, ops1(.reg_ds), Op1(0x1F), .ZO, .Op16, .{_8086, No64} ),
instr(.POPW, ops1(.reg_es), Op1(0x07), .ZO, .Op16, .{_8086, No64} ),
instr(.POPW, ops1(.reg_ss), Op1(0x17), .ZO, .Op16, .{_8086, No64} ),
instr(.POPW, ops1(.reg_fs), Op2(0x0F, 0xA1), .ZO, .Op16, .{_386} ),
instr(.POPW, ops1(.reg_gs), Op2(0x0F, 0xA9), .ZO, .Op16, .{_386} ),
//
instr(.POPD, ops1(.reg_ds), Op1(0x1F), .ZO, .Op32, .{_8086, No64} ),
instr(.POPD, ops1(.reg_es), Op1(0x07), .ZO, .Op32, .{_8086, No64} ),
instr(.POPD, ops1(.reg_ss), Op1(0x17), .ZO, .Op32, .{_8086, No64} ),
instr(.POPD, ops1(.reg_fs), Op2(0x0F, 0xA1), .ZO, .Op32, .{_386, No64} ),
instr(.POPD, ops1(.reg_gs), Op2(0x0F, 0xA9), .ZO, .Op32, .{_386, No64} ),
//
instr(.POPQ, ops1(.reg_fs), Op2(0x0F, 0xA1), .ZO, .ZO, .{_386, No32} ),
instr(.POPQ, ops1(.reg_gs), Op2(0x0F, 0xA9), .ZO, .ZO, .{_386, No32} ),
// POPA
instr(.POPA, ops0(), Op1(0x60), .ZO, .ZO, .{_186, No64} ),
instr(.POPAW, ops0(), Op1(0x60), .ZO, .Op16, .{_186, No64} ),
instr(.POPAD, ops0(), Op1(0x60), .ZO, .Op32, .{_386, No64} ),
// POPF / POPFD / POPFQ
instr(.POPF, ops0(), Op1(0x9D), .ZO, .ZO, .{_8086} ),
instr(.POPFW, ops0(), Op1(0x9D), .ZO, .Op16, .{_8086} ),
instr(.POPFD, ops0(), Op1(0x9D), .ZO, .Op32, .{_386, No64} ),
instr(.POPFQ, ops0(), Op1(0x9D), .ZO, .ZO, .{x86_64, No32} ),
// PUSH
instr(.PUSH, ops1(.imm8), Op1(0x6A), .I, .ZO, .{_186} ),
instr(.PUSH, ops1(.imm16), Op1(0x68), .I, .Op16, .{_186} ),
instr(.PUSH, ops1(.imm32), Op1(0x68), .I, .Op32, .{_386} ),
//
instr(.PUSH, ops1(.reg16), Op1(0x50), .O, .Op16, .{_8086} ),
instr(.PUSH, ops1(.reg32), Op1(0x50), .O, .Op32, .{_386, No64} ),
instr(.PUSH, ops1(.reg64), Op1(0x50), .O, .ZO, .{x86_64, No32} ),
//
instr(.PUSH, ops1(.rm16), Op1r(0xFF, 6), .M, .Op16, .{_8086} ),
instr(.PUSH, ops1(.rm32), Op1r(0xFF, 6), .M, .Op32, .{_386, No64} ),
instr(.PUSH, ops1(.rm64), Op1r(0xFF, 6), .M, .ZO, .{x86_64, No32} ),
//
instr(.PUSH, ops1(.reg_cs), Op1(0x0E), .ZO, .ZO, .{_8086, No64} ),
instr(.PUSH, ops1(.reg_ds), Op1(0x1E), .ZO, .ZO, .{_8086, No64} ),
instr(.PUSH, ops1(.reg_es), Op1(0x06), .ZO, .ZO, .{_8086, No64} ),
instr(.PUSH, ops1(.reg_ss), Op1(0x16), .ZO, .ZO, .{_8086, No64} ),
instr(.PUSH, ops1(.reg_fs), Op2(0x0F, 0xA0), .ZO, .ZO, .{_386} ),
instr(.PUSH, ops1(.reg_gs), Op2(0x0F, 0xA8), .ZO, .ZO, .{_386} ),
//
instr(.PUSHW, ops1(.reg_cs), Op1(0x0E), .ZO, .Op16, .{_8086, No64} ),
instr(.PUSHW, ops1(.reg_ds), Op1(0x1E), .ZO, .Op16, .{_8086, No64} ),
instr(.PUSHW, ops1(.reg_es), Op1(0x06), .ZO, .Op16, .{_8086, No64} ),
instr(.PUSHW, ops1(.reg_ss), Op1(0x16), .ZO, .Op16, .{_8086, No64} ),
instr(.PUSHW, ops1(.reg_fs), Op2(0x0F, 0xA0), .ZO, .Op16, .{_386} ),
instr(.PUSHW, ops1(.reg_gs), Op2(0x0F, 0xA8), .ZO, .Op16, .{_386} ),
//
instr(.PUSHD, ops1(.reg_cs), Op1(0x0E), .ZO, .Op32, .{_8086, No64} ),
instr(.PUSHD, ops1(.reg_ds), Op1(0x1E), .ZO, .Op32, .{_8086, No64} ),
instr(.PUSHD, ops1(.reg_es), Op1(0x06), .ZO, .Op32, .{_8086, No64} ),
instr(.PUSHD, ops1(.reg_ss), Op1(0x16), .ZO, .Op32, .{_8086, No64} ),
instr(.PUSHD, ops1(.reg_fs), Op2(0x0F, 0xA0), .ZO, .Op32, .{_386, No64} ),
instr(.PUSHD, ops1(.reg_gs), Op2(0x0F, 0xA8), .ZO, .Op32, .{_386, No64} ),
//
instr(.PUSHQ, ops1(.reg_fs), Op2(0x0F, 0xA0), .ZO, .ZO, .{_386, No32} ),
instr(.PUSHQ, ops1(.reg_gs), Op2(0x0F, 0xA8), .ZO, .ZO, .{_386, No32} ),
// PUSHA
instr(.PUSHA, ops0(), Op1(0x60), .ZO, .ZO, .{_186, No64} ),
instr(.PUSHAW, ops0(), Op1(0x60), .ZO, .Op16, .{_186, No64} ),
instr(.PUSHAD, ops0(), Op1(0x60), .ZO, .Op32, .{_386, No64} ),
// PUSHF / PUSHFW / PUSHFD / PUSHFQ
instr(.PUSHF, ops0(), Op1(0x9C), .ZO, .ZO, .{_8086} ),
instr(.PUSHFW, ops0(), Op1(0x9C), .ZO, .Op16, .{_8086} ),
instr(.PUSHFD, ops0(), Op1(0x9C), .ZO, .Op32, .{_386, No64} ),
instr(.PUSHFQ, ops0(), Op1(0x9C), .ZO, .ZO, .{x86_64, No32} ),
// RCL / RCR / ROL / ROR
instr(.RCL, ops2(.rm8, .imm_1), Op1r(0xD0, 2), .M, .ZO, .{_8086} ),
instr(.RCL, ops2(.rm8, .reg_cl), Op1r(0xD2, 2), .M, .ZO, .{_8086} ),
instr(.RCL, ops2(.rm8, .imm8), Op1r(0xC0, 2), .MI, .ZO, .{_186} ),
instr(.RCL, ops2(.rm16, .imm_1), Op1r(0xD1, 2), .M, .Op16, .{_8086} ),
instr(.RCL, ops2(.rm32, .imm_1), Op1r(0xD1, 2), .M, .Op32, .{_386} ),
instr(.RCL, ops2(.rm64, .imm_1), Op1r(0xD1, 2), .M, .REX_W, .{x86_64} ),
instr(.RCL, ops2(.rm16, .imm8), Op1r(0xC1, 2), .MI, .Op16, .{_186} ),
instr(.RCL, ops2(.rm32, .imm8), Op1r(0xC1, 2), .MI, .Op32, .{_386} ),
instr(.RCL, ops2(.rm64, .imm8), Op1r(0xC1, 2), .MI, .REX_W, .{x86_64} ),
instr(.RCL, ops2(.rm16, .reg_cl), Op1r(0xD3, 2), .M, .Op16, .{_8086} ),
instr(.RCL, ops2(.rm32, .reg_cl), Op1r(0xD3, 2), .M, .Op32, .{_386} ),
instr(.RCL, ops2(.rm64, .reg_cl), Op1r(0xD3, 2), .M, .REX_W, .{x86_64} ),
//
instr(.RCR, ops2(.rm8, .imm_1), Op1r(0xD0, 3), .M, .ZO, .{_8086} ),
instr(.RCR, ops2(.rm8, .reg_cl), Op1r(0xD2, 3), .M, .ZO, .{_8086} ),
instr(.RCR, ops2(.rm8, .imm8), Op1r(0xC0, 3), .MI, .ZO, .{_186} ),
instr(.RCR, ops2(.rm16, .imm_1), Op1r(0xD1, 3), .M, .Op16, .{_8086} ),
instr(.RCR, ops2(.rm32, .imm_1), Op1r(0xD1, 3), .M, .Op32, .{_386} ),
instr(.RCR, ops2(.rm64, .imm_1), Op1r(0xD1, 3), .M, .REX_W, .{x86_64} ),
instr(.RCR, ops2(.rm16, .imm8), Op1r(0xC1, 3), .MI, .Op16, .{_186} ),
instr(.RCR, ops2(.rm32, .imm8), Op1r(0xC1, 3), .MI, .Op32, .{_386} ),
instr(.RCR, ops2(.rm64, .imm8), Op1r(0xC1, 3), .MI, .REX_W, .{x86_64} ),
instr(.RCR, ops2(.rm16, .reg_cl), Op1r(0xD3, 3), .M, .Op16, .{_8086} ),
instr(.RCR, ops2(.rm32, .reg_cl), Op1r(0xD3, 3), .M, .Op32, .{_386} ),
instr(.RCR, ops2(.rm64, .reg_cl), Op1r(0xD3, 3), .M, .REX_W, .{x86_64} ),
//
instr(.ROL, ops2(.rm8, .imm_1), Op1r(0xD0, 0), .M, .ZO, .{_8086} ),
instr(.ROL, ops2(.rm8, .reg_cl), Op1r(0xD2, 0), .M, .ZO, .{_8086} ),
instr(.ROL, ops2(.rm8, .imm8), Op1r(0xC0, 0), .MI, .ZO, .{_186} ),
instr(.ROL, ops2(.rm16, .imm_1), Op1r(0xD1, 0), .M, .Op16, .{_8086} ),
instr(.ROL, ops2(.rm32, .imm_1), Op1r(0xD1, 0), .M, .Op32, .{_386} ),
instr(.ROL, ops2(.rm64, .imm_1), Op1r(0xD1, 0), .M, .REX_W, .{x86_64} ),
instr(.ROL, ops2(.rm16, .imm8), Op1r(0xC1, 0), .MI, .Op16, .{_186} ),
instr(.ROL, ops2(.rm32, .imm8), Op1r(0xC1, 0), .MI, .Op32, .{_386} ),
instr(.ROL, ops2(.rm64, .imm8), Op1r(0xC1, 0), .MI, .REX_W, .{x86_64} ),
instr(.ROL, ops2(.rm16, .reg_cl), Op1r(0xD3, 0), .M, .Op16, .{_8086} ),
instr(.ROL, ops2(.rm32, .reg_cl), Op1r(0xD3, 0), .M, .Op32, .{_386} ),
instr(.ROL, ops2(.rm64, .reg_cl), Op1r(0xD3, 0), .M, .REX_W, .{x86_64} ),
//
instr(.ROR, ops2(.rm8, .imm_1), Op1r(0xD0, 1), .M, .ZO, .{_8086} ),
instr(.ROR, ops2(.rm8, .reg_cl), Op1r(0xD2, 1), .M, .ZO, .{_8086} ),
instr(.ROR, ops2(.rm8, .imm8), Op1r(0xC0, 1), .MI, .ZO, .{_186} ),
instr(.ROR, ops2(.rm16, .imm_1), Op1r(0xD1, 1), .M, .Op16, .{_8086} ),
instr(.ROR, ops2(.rm32, .imm_1), Op1r(0xD1, 1), .M, .Op32, .{_386} ),
instr(.ROR, ops2(.rm64, .imm_1), Op1r(0xD1, 1), .M, .REX_W, .{x86_64} ),
instr(.ROR, ops2(.rm16, .imm8), Op1r(0xC1, 1), .MI, .Op16, .{_186} ),
instr(.ROR, ops2(.rm32, .imm8), Op1r(0xC1, 1), .MI, .Op32, .{_386} ),
instr(.ROR, ops2(.rm64, .imm8), Op1r(0xC1, 1), .MI, .REX_W, .{x86_64} ),
instr(.ROR, ops2(.rm16, .reg_cl), Op1r(0xD3, 1), .M, .Op16, .{_8086} ),
instr(.ROR, ops2(.rm32, .reg_cl), Op1r(0xD3, 1), .M, .Op32, .{_386} ),
instr(.ROR, ops2(.rm64, .reg_cl), Op1r(0xD3, 1), .M, .REX_W, .{x86_64} ),
// REP / REPE / REPZ / REPNE / REPNZ
instr(.REP, ops0(), Op1(0xF3), .ZO, .ZO, .{_8086} ),
instr(.REPE, ops0(), Op1(0xF3), .ZO, .ZO, .{_8086} ),
instr(.REPZ, ops0(), Op1(0xF3), .ZO, .ZO, .{_8086} ),
instr(.REPNE, ops0(), Op1(0xF2), .ZO, .ZO, .{_8086} ),
instr(.REPNZ, ops0(), Op1(0xF2), .ZO, .ZO, .{_8086} ),
// RET
instr(.RET, ops0(), Op1(0xC3), .ZO, .ZO, .{_8086, Bnd} ),
instr(.RET, ops1(.imm16), Op1(0xC2), .I, .ZO, .{_8086, Bnd} ),
instr(.RETW, ops0(), Op1(0xC3), .ZO, .Op16, .{_8086, Bnd} ),
instr(.RETW, ops1(.imm16), Op1(0xC2), .I, .Op16, .{_8086, Bnd} ),
instr(.RETD, ops0(), Op1(0xC3), .ZO, .Op32, .{_386, Bnd, No64} ),
instr(.RETD, ops1(.imm16), Op1(0xC2), .I, .Op32, .{_386, Bnd, No64} ),
instr(.RETQ, ops0(), Op1(0xC3), .ZO, .ZO, .{x86_64, Bnd, No32} ),
instr(.RETQ, ops1(.imm16), Op1(0xC2), .I, .ZO, .{x86_64, Bnd, No32} ),
// RETF
instr(.RETF, ops0(), Op1(0xCB), .ZO, .ZO, .{_8086} ),
instr(.RETF, ops1(.imm16), Op1(0xCA), .I, .ZO, .{_8086} ),
instr(.RETFW, ops0(), Op1(0xCB), .ZO, .Op16, .{_8086} ),
instr(.RETFW, ops1(.imm16), Op1(0xCA), .I, .Op16, .{_8086} ),
instr(.RETFD, ops0(), Op1(0xCB), .ZO, .Op32, .{_386, No64} ),
instr(.RETFD, ops1(.imm16), Op1(0xCA), .I, .Op32, .{_386, No64} ),
instr(.RETFQ, ops0(), Op1(0xCB), .ZO, .ZO, .{x86_64, No32} ),
instr(.RETFQ, ops1(.imm16), Op1(0xCA), .I, .ZO, .{x86_64, No32} ),
// RETN
instr(.RETN, ops0(), Op1(0xC3), .ZO, .ZO, .{_8086, Bnd} ),
instr(.RETN, ops1(.imm16), Op1(0xC2), .I, .ZO, .{_8086, Bnd} ),
instr(.RETNW, ops0(), Op1(0xC3), .ZO, .Op16, .{_8086, Bnd} ),
instr(.RETNW, ops1(.imm16), Op1(0xC2), .I, .Op16, .{_8086, Bnd} ),
instr(.RETND, ops0(), Op1(0xC3), .ZO, .Op32, .{_386, Bnd, No64} ),
instr(.RETND, ops1(.imm16), Op1(0xC2), .I, .Op32, .{_386, Bnd, No64} ),
instr(.RETNQ, ops0(), Op1(0xC3), .ZO, .ZO, .{x86_64, Bnd, No32} ),
instr(.RETNQ, ops1(.imm16), Op1(0xC2), .I, .ZO, .{x86_64, Bnd, No32} ),
// SAL / SAR / SHL / SHR
instr(.SAL, ops2(.rm8, .imm_1), Op1r(0xD0, 4), .M, .ZO, .{_8086} ),
instr(.SAL, ops2(.rm8, .reg_cl), Op1r(0xD2, 4), .M, .ZO, .{_8086} ),
instr(.SAL, ops2(.rm8, .imm8), Op1r(0xC0, 4), .MI, .ZO, .{_186} ),
instr(.SAL, ops2(.rm16, .imm_1), Op1r(0xD1, 4), .M, .Op16, .{_8086} ),
instr(.SAL, ops2(.rm32, .imm_1), Op1r(0xD1, 4), .M, .Op32, .{_386} ),
instr(.SAL, ops2(.rm64, .imm_1), Op1r(0xD1, 4), .M, .REX_W, .{x86_64} ),
instr(.SAL, ops2(.rm16, .imm8), Op1r(0xC1, 4), .MI, .Op16, .{_186} ),
instr(.SAL, ops2(.rm32, .imm8), Op1r(0xC1, 4), .MI, .Op32, .{_386} ),
instr(.SAL, ops2(.rm64, .imm8), Op1r(0xC1, 4), .MI, .REX_W, .{x86_64} ),
instr(.SAL, ops2(.rm16, .reg_cl), Op1r(0xD3, 4), .M, .Op16, .{_8086} ),
instr(.SAL, ops2(.rm32, .reg_cl), Op1r(0xD3, 4), .M, .Op32, .{_386} ),
instr(.SAL, ops2(.rm64, .reg_cl), Op1r(0xD3, 4), .M, .REX_W, .{x86_64} ),
//
instr(.SAR, ops2(.rm8, .imm_1), Op1r(0xD0, 7), .M, .ZO, .{_8086} ),
instr(.SAR, ops2(.rm8, .reg_cl), Op1r(0xD2, 7), .M, .ZO, .{_8086} ),
instr(.SAR, ops2(.rm8, .imm8), Op1r(0xC0, 7), .MI, .ZO, .{_186} ),
instr(.SAR, ops2(.rm16, .imm_1), Op1r(0xD1, 7), .M, .Op16, .{_8086} ),
instr(.SAR, ops2(.rm32, .imm_1), Op1r(0xD1, 7), .M, .Op32, .{_386} ),
instr(.SAR, ops2(.rm64, .imm_1), Op1r(0xD1, 7), .M, .REX_W, .{x86_64} ),
instr(.SAR, ops2(.rm16, .imm8), Op1r(0xC1, 7), .MI, .Op16, .{_186} ),
instr(.SAR, ops2(.rm32, .imm8), Op1r(0xC1, 7), .MI, .Op32, .{_386} ),
instr(.SAR, ops2(.rm64, .imm8), Op1r(0xC1, 7), .MI, .REX_W, .{x86_64} ),
instr(.SAR, ops2(.rm16, .reg_cl), Op1r(0xD3, 7), .M, .Op16, .{_8086} ),
instr(.SAR, ops2(.rm32, .reg_cl), Op1r(0xD3, 7), .M, .Op32, .{_386} ),
instr(.SAR, ops2(.rm64, .reg_cl), Op1r(0xD3, 7), .M, .REX_W, .{x86_64} ),
//
instr(.SHL, ops2(.rm8, .imm_1), Op1r(0xD0, 4), .M, .ZO, .{_8086} ),
instr(.SHL, ops2(.rm8, .reg_cl), Op1r(0xD2, 4), .M, .ZO, .{_8086} ),
instr(.SHL, ops2(.rm8, .imm8), Op1r(0xC0, 4), .MI, .ZO, .{_186} ),
instr(.SHL, ops2(.rm16, .imm_1), Op1r(0xD1, 4), .M, .Op16, .{_8086} ),
instr(.SHL, ops2(.rm32, .imm_1), Op1r(0xD1, 4), .M, .Op32, .{_386} ),
instr(.SHL, ops2(.rm64, .imm_1), Op1r(0xD1, 4), .M, .REX_W, .{x86_64} ),
instr(.SHL, ops2(.rm16, .imm8), Op1r(0xC1, 4), .MI, .Op16, .{_186} ),
instr(.SHL, ops2(.rm32, .imm8), Op1r(0xC1, 4), .MI, .Op32, .{_386} ),
instr(.SHL, ops2(.rm64, .imm8), Op1r(0xC1, 4), .MI, .REX_W, .{x86_64} ),
instr(.SHL, ops2(.rm16, .reg_cl), Op1r(0xD3, 4), .M, .Op16, .{_8086} ),
instr(.SHL, ops2(.rm32, .reg_cl), Op1r(0xD3, 4), .M, .Op32, .{_386} ),
instr(.SHL, ops2(.rm64, .reg_cl), Op1r(0xD3, 4), .M, .REX_W, .{x86_64} ),
//
instr(.SHR, ops2(.rm8, .imm_1), Op1r(0xD0, 5), .M, .ZO, .{_8086} ),
instr(.SHR, ops2(.rm8, .reg_cl), Op1r(0xD2, 5), .M, .ZO, .{_8086} ),
instr(.SHR, ops2(.rm8, .imm8), Op1r(0xC0, 5), .MI, .ZO, .{_186} ),
instr(.SHR, ops2(.rm16, .imm_1), Op1r(0xD1, 5), .M, .Op16, .{_8086} ),
instr(.SHR, ops2(.rm32, .imm_1), Op1r(0xD1, 5), .M, .Op32, .{_386} ),
instr(.SHR, ops2(.rm64, .imm_1), Op1r(0xD1, 5), .M, .REX_W, .{x86_64} ),
instr(.SHR, ops2(.rm16, .imm8), Op1r(0xC1, 5), .MI, .Op16, .{_186} ),
instr(.SHR, ops2(.rm32, .imm8), Op1r(0xC1, 5), .MI, .Op32, .{_386} ),
instr(.SHR, ops2(.rm64, .imm8), Op1r(0xC1, 5), .MI, .REX_W, .{x86_64} ),
instr(.SHR, ops2(.rm16, .reg_cl), Op1r(0xD3, 5), .M, .Op16, .{_8086} ),
instr(.SHR, ops2(.rm32, .reg_cl), Op1r(0xD3, 5), .M, .Op32, .{_386} ),
instr(.SHR, ops2(.rm64, .reg_cl), Op1r(0xD3, 5), .M, .REX_W, .{x86_64} ),
// SBB
instr(.SBB, ops2(.reg_al, .imm8), Op1(0x1C), .I2, .ZO, .{_8086} ),
instr(.SBB, ops2(.rm8, .imm8), Op1r(0x80, 3), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.SBB, ops2(.rm16, .imm8), Op1r(0x83, 3), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.SBB, ops2(.rm32, .imm8), Op1r(0x83, 3), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.SBB, ops2(.rm64, .imm8), Op1r(0x83, 3), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.SBB, ops2(.reg_ax, .imm16), Op1(0x1D), .I2, .Op16, .{_8086} ),
instr(.SBB, ops2(.reg_eax, .imm32), Op1(0x1D), .I2, .Op32, .{_386} ),
instr(.SBB, ops2(.reg_rax, .imm32), Op1(0x1D), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.SBB, ops2(.rm16, .imm16), Op1r(0x81, 3), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.SBB, ops2(.rm32, .imm32), Op1r(0x81, 3), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.SBB, ops2(.rm64, .imm32), Op1r(0x81, 3), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.SBB, ops2(.rm8, .reg8), Op1(0x18), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.SBB, ops2(.rm16, .reg16), Op1(0x19), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.SBB, ops2(.rm32, .reg32), Op1(0x19), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.SBB, ops2(.rm64, .reg64), Op1(0x19), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.SBB, ops2(.reg8, .rm8), Op1(0x1A), .RM, .ZO, .{_8086} ),
instr(.SBB, ops2(.reg16, .rm16), Op1(0x1B), .RM, .Op16, .{_8086} ),
instr(.SBB, ops2(.reg32, .rm32), Op1(0x1B), .RM, .Op32, .{_386} ),
instr(.SBB, ops2(.reg64, .rm64), Op1(0x1B), .RM, .REX_W, .{x86_64} ),
// SCAS / SCASB / SCASW / SCASD / SCASQ
instr(.SCAS, ops2(.rm_mem8, .reg_al), Op1(0xAE), .MSpec, .ZO, .{_8086, Repe, Repne} ),
instr(.SCAS, ops2(.rm_mem16, .reg_ax), Op1(0xAF), .MSpec, .Op16, .{_8086, Repe, Repne} ),
instr(.SCAS, ops2(.rm_mem32, .reg_eax), Op1(0xAF), .MSpec, .Op32, .{_386, Repe, Repne} ),
instr(.SCAS, ops2(.rm_mem64, .reg_rax), Op1(0xAF), .MSpec, .REX_W,.{x86_64, Repe, Repne} ),
//
instr(.SCASB, ops0(), Op1(0xAE), .ZO, .ZO, .{_8086, Repe, Repne} ),
instr(.SCASW, ops0(), Op1(0xAF), .ZO, .Op16, .{_8086, Repe, Repne} ),
instr(.SCASD, ops0(), Op1(0xAF), .ZO, .Op32, .{_386, Repe, Repne} ),
instr(.SCASQ, ops0(), Op1(0xAF), .ZO, .REX_W, .{x86_64, No32, Repe, Repne} ),
// STC
instr(.STC, ops0(), Op1(0xF9), .ZO, .ZO, .{_8086} ),
// STD
instr(.STD, ops0(), Op1(0xFD), .ZO, .ZO, .{_8086} ),
// STI
instr(.STI, ops0(), Op1(0xFB), .ZO, .ZO, .{_8086} ),
// STOS / STOSB / STOSW / STOSD / STOSQ
instr(.STOS, ops2(.rm_mem8, .reg_al), Op1(0xAA), .MSpec, .ZO, .{_8086, Rep} ),
instr(.STOS, ops2(.rm_mem16, .reg_ax), Op1(0xAB), .MSpec, .Op16, .{_8086, Rep} ),
instr(.STOS, ops2(.rm_mem32, .reg_eax), Op1(0xAB), .MSpec, .Op32, .{_386, Rep} ),
instr(.STOS, ops2(.rm_mem64, .reg_rax), Op1(0xAB), .MSpec, .REX_W,.{x86_64, Rep} ),
//
instr(.STOSB, ops0(), Op1(0xAA), .ZO, .ZO, .{_8086, Rep} ),
instr(.STOSW, ops0(), Op1(0xAB), .ZO, .Op16, .{_8086, Rep} ),
instr(.STOSD, ops0(), Op1(0xAB), .ZO, .Op32, .{_386, Rep} ),
instr(.STOSQ, ops0(), Op1(0xAB), .ZO, .REX_W, .{x86_64, Rep} ),
// SUB
instr(.SUB, ops2(.reg_al, .imm8), Op1(0x2C), .I2, .ZO, .{_8086} ),
instr(.SUB, ops2(.rm8, .imm8), Op1r(0x80, 5), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.SUB, ops2(.rm16, .imm8), Op1r(0x83, 5), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.SUB, ops2(.rm32, .imm8), Op1r(0x83, 5), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.SUB, ops2(.rm64, .imm8), Op1r(0x83, 5), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.SUB, ops2(.reg_ax, .imm16), Op1(0x2D), .I2, .Op16, .{_8086} ),
instr(.SUB, ops2(.reg_eax, .imm32), Op1(0x2D), .I2, .Op32, .{_386} ),
instr(.SUB, ops2(.reg_rax, .imm32), Op1(0x2D), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.SUB, ops2(.rm16, .imm16), Op1r(0x81, 5), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.SUB, ops2(.rm32, .imm32), Op1r(0x81, 5), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.SUB, ops2(.rm64, .imm32), Op1r(0x81, 5), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.SUB, ops2(.rm8, .reg8), Op1(0x28), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.SUB, ops2(.rm16, .reg16), Op1(0x29), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.SUB, ops2(.rm32, .reg32), Op1(0x29), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.SUB, ops2(.rm64, .reg64), Op1(0x29), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.SUB, ops2(.reg8, .rm8), Op1(0x2A), .RM, .ZO, .{_8086} ),
instr(.SUB, ops2(.reg16, .rm16), Op1(0x2B), .RM, .Op16, .{_8086} ),
instr(.SUB, ops2(.reg32, .rm32), Op1(0x2B), .RM, .Op32, .{_386} ),
instr(.SUB, ops2(.reg64, .rm64), Op1(0x2B), .RM, .REX_W, .{x86_64} ),
// TEST
instr(.TEST, ops2(.reg_al, .imm8), Op1(0xA8), .I2, .ZO, .{_8086} ),
instr(.TEST, ops2(.reg_ax, .imm16), Op1(0xA9), .I2, .Op16, .{_8086} ),
instr(.TEST, ops2(.reg_eax, .imm32), Op1(0xA9), .I2, .Op32, .{_386} ),
instr(.TEST, ops2(.reg_rax, .imm32), Op1(0xA9), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.TEST, ops2(.rm8, .imm8), Op1r(0xF6, 0), .MI, .ZO, .{_8086} ),
instr(.TEST, ops2(.rm16, .imm16), Op1r(0xF7, 0), .MI, .Op16, .{_8086} ),
instr(.TEST, ops2(.rm32, .imm32), Op1r(0xF7, 0), .MI, .Op32, .{_386} ),
instr(.TEST, ops2(.rm64, .imm32), Op1r(0xF7, 0), .MI, .REX_W, .{x86_64} ),
//
instr(.TEST, ops2(.rm8, .reg8), Op1(0x84), .MR, .ZO, .{_8086} ),
instr(.TEST, ops2(.rm16, .reg16), Op1(0x85), .MR, .Op16, .{_8086} ),
instr(.TEST, ops2(.rm32, .reg32), Op1(0x85), .MR, .Op32, .{_386} ),
instr(.TEST, ops2(.rm64, .reg64), Op1(0x85), .MR, .REX_W, .{x86_64} ),
// WAIT
instr(.WAIT, ops0(), Op1(0x9B), .ZO, .ZO, .{_8086} ),
// XCHG
instr(.XCHG, ops2(.reg_ax, .reg16), Op1(0x90), .O2, .Op16, .{_8086} ),
instr(.XCHG, ops2(.reg16, .reg_ax), Op1(0x90), .O, .Op16, .{_8086} ),
instr(.XCHG, ops2(.reg_eax, .reg32), Op1(0x90), .O2, .Op32, .{_386, edge.XCHG_EAX} ),
instr(.XCHG, ops2(.reg32, .reg_eax), Op1(0x90), .O, .Op32, .{_386, edge.XCHG_EAX} ),
instr(.XCHG, ops2(.reg_rax, .reg64), Op1(0x90), .O2, .REX_W, .{x86_64} ),
instr(.XCHG, ops2(.reg64, .reg_rax), Op1(0x90), .O, .REX_W, .{x86_64} ),
//
instr(.XCHG, ops2(.rm8, .reg8), Op1(0x86), .MR, .ZO, .{_8086, Lock, HleNoLock} ),
instr(.XCHG, ops2(.reg8, .rm8), Op1(0x86), .RM, .ZO, .{_8086, Lock, HleNoLock} ),
instr(.XCHG, ops2(.rm16, .reg16), Op1(0x87), .MR, .Op16, .{_8086, Lock, HleNoLock} ),
instr(.XCHG, ops2(.reg16, .rm16), Op1(0x87), .RM, .Op16, .{_8086, Lock, HleNoLock} ),
instr(.XCHG, ops2(.rm32, .reg32), Op1(0x87), .MR, .Op32, .{_386, Lock, HleNoLock} ),
instr(.XCHG, ops2(.reg32, .rm32), Op1(0x87), .RM, .Op32, .{_386, Lock, HleNoLock} ),
instr(.XCHG, ops2(.rm64, .reg64), Op1(0x87), .MR, .REX_W, .{x86_64, Lock, HleNoLock} ),
instr(.XCHG, ops2(.reg64, .rm64), Op1(0x87), .RM, .REX_W, .{x86_64, Lock, HleNoLock} ),
// XLAT / XLATB
instr(.XLAT, ops2(.reg_al, .rm_mem8), Op1(0xD7), .MSpec, .ZO, .{_8086} ),
//
instr(.XLATB, ops0(), Op1(0xD7), .ZO, .ZO, .{_8086} ),
// XOR
instr(.XOR, ops2(.reg_al, .imm8), Op1(0x34), .I2, .ZO, .{_8086} ),
instr(.XOR, ops2(.rm8, .imm8), Op1r(0x80, 6), .MI, .ZO, .{_8086, Lock, Hle} ),
instr(.XOR, ops2(.rm16, .imm8), Op1r(0x83, 6), .MI, .Op16, .{_8086, Sign, Lock, Hle} ),
instr(.XOR, ops2(.rm32, .imm8), Op1r(0x83, 6), .MI, .Op32, .{_386, Sign, Lock, Hle} ),
instr(.XOR, ops2(.rm64, .imm8), Op1r(0x83, 6), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.XOR, ops2(.reg_ax, .imm16), Op1(0x35), .I2, .Op16, .{_8086} ),
instr(.XOR, ops2(.reg_eax, .imm32), Op1(0x35), .I2, .Op32, .{_386} ),
instr(.XOR, ops2(.reg_rax, .imm32), Op1(0x35), .I2, .REX_W, .{x86_64, Sign} ),
//
instr(.XOR, ops2(.rm16, .imm16), Op1r(0x81, 6), .MI, .Op16, .{_8086, Lock, Hle} ),
instr(.XOR, ops2(.rm32, .imm32), Op1r(0x81, 6), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.XOR, ops2(.rm64, .imm32), Op1r(0x81, 6), .MI, .REX_W, .{x86_64, Sign, Lock, Hle} ),
//
instr(.XOR, ops2(.rm8, .reg8), Op1(0x30), .MR, .ZO, .{_8086, Lock, Hle} ),
instr(.XOR, ops2(.rm16, .reg16), Op1(0x31), .MR, .Op16, .{_8086, Lock, Hle} ),
instr(.XOR, ops2(.rm32, .reg32), Op1(0x31), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.XOR, ops2(.rm64, .reg64), Op1(0x31), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.XOR, ops2(.reg8, .rm8), Op1(0x32), .RM, .ZO, .{_8086} ),
instr(.XOR, ops2(.reg16, .rm16), Op1(0x33), .RM, .Op16, .{_8086} ),
instr(.XOR, ops2(.reg32, .rm32), Op1(0x33), .RM, .Op32, .{_386} ),
instr(.XOR, ops2(.reg64, .rm64), Op1(0x33), .RM, .REX_W, .{x86_64} ),
//
// x87 -- 8087 / 80287 / 80387
//
// F2XM1
instr(.F2XM1, ops0(), Op2(0xD9, 0xF0), .ZO, .ZO, .{_087} ),
// FABS
instr(.FABS, ops0(), Op2(0xD9, 0xE1), .ZO, .ZO, .{_087} ),
// FADD / FADDP / FIADD
instr(.FADD, ops1(.rm_mem32), Op1r(0xD8, 0), .M, .ZO, .{_087} ),
instr(.FADD, ops1(.rm_mem64), Op1r(0xDC, 0), .M, .ZO, .{_087} ),
instr(.FADD, ops1(.reg_st), Op2(0xD8, 0xC0), .O, .ZO, .{_087} ),
instr(.FADD, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xC0), .O, .ZO, .{_087} ),
instr(.FADD, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xC0), .O2, .ZO, .{_087} ),
//
instr(.FADDP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xC0), .O, .ZO, .{_087} ),
instr(.FADDP, ops0(), Op2(0xDE, 0xC1), .ZO, .ZO, .{_087} ),
//
instr(.FIADD, ops1(.rm_mem16), Op1r(0xDE, 0), .M, .ZO, .{_087} ),
instr(.FIADD, ops1(.rm_mem32), Op1r(0xDA, 0), .M, .ZO, .{_087} ),
// FBLD
instr(.FBLD, ops1(.rm_mem80), Op1r(0xDF, 4), .M, .ZO, .{_087} ),
// FBSTP
instr(.FBSTP, ops1(.rm_mem80), Op1r(0xDF, 6), .M, .ZO, .{_087} ),
// FCHS
instr(.FCHS, ops0(), Op2(0xD9, 0xE0), .ZO, .ZO, .{_087} ),
instr(.FCHS, ops1(.reg_st0), Op2(0xD9, 0xE0), .ZO, .ZO, .{_087} ),
// FCLEX / FNCLEX
instr(.FCLEX, ops0(), compOp2(.FWAIT, 0xDB,0xE2),.ZO, .ZO, .{_087} ),
instr(.FNCLEX, ops0(), Op2(0xDB, 0xE2), .ZO, .ZO, .{_087} ),
// FCOM / FCOMP / FCOMPP
instr(.FCOM, ops1(.rm_mem32), Op1r(0xD8, 2), .M, .ZO, .{_087} ),
instr(.FCOM, ops1(.rm_mem64), Op1r(0xDC, 2), .M, .ZO, .{_087} ),
//
instr(.FCOM, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xD0), .O2, .ZO, .{_087} ),
instr(.FCOM, ops1(.reg_st), Op2(0xD8, 0xD0), .O, .ZO, .{_087} ),
instr(.FCOM, ops0(), Op2(0xD8, 0xD1), .ZO, .ZO, .{_087} ),
//
instr(.FCOMP, ops1(.rm_mem32), Op1r(0xD8, 3), .M, .ZO, .{_087} ),
instr(.FCOMP, ops1(.rm_mem64), Op1r(0xDC, 3), .M, .ZO, .{_087} ),
//
instr(.FCOMP, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xD8), .O2, .ZO, .{_087} ),
instr(.FCOMP, ops1(.reg_st), Op2(0xD8, 0xD8), .O, .ZO, .{_087} ),
instr(.FCOMP, ops0(), Op2(0xD8, 0xD9), .ZO, .ZO, .{_087} ),
//
instr(.FCOMPP, ops0(), Op2(0xDE, 0xD9), .ZO, .ZO, .{_087} ),
// FDECSTP
instr(.FDECSTP, ops0(), Op2(0xD9, 0xF6), .ZO, .ZO, .{_087} ),
// FDIV / FDIVP / FIDIV
instr(.FDIV, ops1(.rm_mem32), Op1r(0xD8, 6), .M, .ZO, .{_087} ),
instr(.FDIV, ops1(.rm_mem64), Op1r(0xDC, 6), .M, .ZO, .{_087} ),
//
instr(.FDIV, ops1(.reg_st), Op2(0xD8, 0xF0), .O, .ZO, .{_087} ),
instr(.FDIV, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xF0), .O2, .ZO, .{_087} ),
instr(.FDIV, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xF8), .O, .ZO, .{_087} ),
//
instr(.FDIVP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xF8), .O, .ZO, .{_087} ),
instr(.FDIVP, ops0(), Op2(0xDE, 0xF9), .ZO, .ZO, .{_087} ),
//
instr(.FIDIV, ops1(.rm_mem16), Op1r(0xDE, 6), .M, .ZO, .{_087} ),
instr(.FIDIV, ops1(.rm_mem32), Op1r(0xDA, 6), .M, .ZO, .{_087} ),
// FDIVR / FDIVRP / FIDIVR
instr(.FDIVR, ops1(.rm_mem32), Op1r(0xD8, 7), .M, .ZO, .{_087} ),
instr(.FDIVR, ops1(.rm_mem64), Op1r(0xDC, 7), .M, .ZO, .{_087} ),
//
instr(.FDIVR, ops1(.reg_st), Op2(0xD8, 0xF8), .O, .ZO, .{_087} ),
instr(.FDIVR, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xF0), .O, .ZO, .{_087} ),
instr(.FDIVR, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xF8), .O2, .ZO, .{_087} ),
//
instr(.FDIVRP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xF0), .O, .ZO, .{_087} ),
instr(.FDIVRP, ops0(), Op2(0xDE, 0xF1), .ZO, .ZO, .{_087} ),
//
instr(.FIDIVR, ops1(.rm_mem16), Op1r(0xDE, 7), .M, .ZO, .{_087} ),
instr(.FIDIVR, ops1(.rm_mem32), Op1r(0xDA, 7), .M, .ZO, .{_087} ),
// FFREE
instr(.FFREE, ops1(.reg_st), Op2(0xDD, 0xC0), .O, .ZO, .{_087} ),
// FICOM / FICOMP
instr(.FICOM, ops1(.rm_mem16), Op1r(0xDE, 2), .M, .ZO, .{_087} ),
instr(.FICOM, ops1(.rm_mem32), Op1r(0xDA, 2), .M, .ZO, .{_087} ),
//
instr(.FICOMP, ops1(.rm_mem16), Op1r(0xDE, 3), .M, .ZO, .{_087} ),
instr(.FICOMP, ops1(.rm_mem32), Op1r(0xDA, 3), .M, .ZO, .{_087} ),
// FILD
instr(.FILD, ops1(.rm_mem16), Op1r(0xDF, 0), .M, .ZO, .{_087} ),
instr(.FILD, ops1(.rm_mem32), Op1r(0xDB, 0), .M, .ZO, .{_087} ),
instr(.FILD, ops1(.rm_mem64), Op1r(0xDF, 5), .M, .ZO, .{_087} ),
// FINCSTP
instr(.FINCSTP, ops0(), Op2(0xD9, 0xF7), .ZO, .ZO, .{_087} ),
// FINIT / FNINIT
instr(.FINIT, ops0(), compOp2(.FWAIT, 0xDB,0xE3),.ZO, .ZO, .{_087} ),
instr(.FNINIT, ops0(), Op2(0xDB, 0xE3), .ZO, .ZO, .{_087} ),
// FIST
instr(.FIST, ops1(.rm_mem16), Op1r(0xDF, 2), .M, .ZO, .{_087} ),
instr(.FIST, ops1(.rm_mem32), Op1r(0xDB, 2), .M, .ZO, .{_087} ),
//
instr(.FISTP, ops1(.rm_mem16), Op1r(0xDF, 3), .M, .ZO, .{_087} ),
instr(.FISTP, ops1(.rm_mem32), Op1r(0xDB, 3), .M, .ZO, .{_087} ),
instr(.FISTP, ops1(.rm_mem64), Op1r(0xDF, 7), .M, .ZO, .{_087} ),
// FLD
instr(.FLD, ops1(.rm_mem32), Op1r(0xD9, 0), .M, .ZO, .{_087} ),
instr(.FLD, ops1(.rm_mem64), Op1r(0xDD, 0), .M, .ZO, .{_087} ),
instr(.FLD, ops1(.rm_mem80), Op1r(0xDB, 5), .M, .ZO, .{_087} ),
instr(.FLD, ops1(.reg_st), Op2(0xD9, 0xC0), .O, .ZO, .{_087} ),
instr(.FLDCW, ops1(.rm_mem16), Op1r(0xD9, 5), .M, .ZO, .{_087} ),
instr(.FLDCW, ops1(.rm_mem), Op1r(0xD9, 5), .M, .ZO, .{_087} ),
instr(.FLD1, ops0(), Op2(0xD9, 0xE8), .ZO, .ZO, .{_087} ),
instr(.FLDL2T, ops0(), Op2(0xD9, 0xE9), .ZO, .ZO, .{_087} ),
instr(.FLDL2E, ops0(), Op2(0xD9, 0xEA), .ZO, .ZO, .{_087} ),
instr(.FLDPI, ops0(), Op2(0xD9, 0xEB), .ZO, .ZO, .{_087} ),
instr(.FLDLG2, ops0(), Op2(0xD9, 0xEC), .ZO, .ZO, .{_087} ),
instr(.FLDLN2, ops0(), Op2(0xD9, 0xED), .ZO, .ZO, .{_087} ),
instr(.FLDZ, ops0(), Op2(0xD9, 0xEE), .ZO, .ZO, .{_087} ),
// FLDENV
instr(.FLDENV, ops1(.rm_mem), Op1r(0xD9, 4), .M, .ZO, .{_087} ),
instr(.FLDENVW, ops1(.rm_mem), Op1r(0xD9, 4), .M, .Op16, .{_087} ),
instr(.FLDENVD, ops1(.rm_mem), Op1r(0xD9, 4), .M, .Op32, .{_387} ),
// FMUL / FMULP / FIMUL
instr(.FMUL, ops1(.rm_mem32), Op1r(0xD8, 1), .M, .ZO, .{_087} ),
instr(.FMUL, ops1(.rm_mem64), Op1r(0xDC, 1), .M, .ZO, .{_087} ),
//
instr(.FMUL, ops1(.reg_st), Op2(0xD8, 0xC8), .O, .ZO, .{_087} ),
instr(.FMUL, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xC8), .O, .ZO, .{_087} ),
instr(.FMUL, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xC8), .O2, .ZO, .{_087} ),
//
instr(.FMULP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xC8), .O, .ZO, .{_087} ),
instr(.FMULP, ops0(), Op2(0xDE, 0xC9), .ZO, .ZO, .{_087} ),
//
instr(.FIMUL, ops1(.rm_mem16), Op1r(0xDE, 1), .M, .ZO, .{_087} ),
instr(.FIMUL, ops1(.rm_mem32), Op1r(0xDA, 1), .M, .ZO, .{_087} ),
// FNOP
instr(.FNOP, ops0(), Op2(0xD9, 0xD0), .ZO, .ZO, .{_087} ),
// FPATAN
instr(.FPATAN, ops0(), Op2(0xD9, 0xF3), .ZO, .ZO, .{_087} ),
// FPREM
instr(.FPREM, ops0(), Op2(0xD9, 0xF8), .ZO, .ZO, .{_087} ),
// FPTAN
instr(.FPTAN, ops0(), Op2(0xD9, 0xF2), .ZO, .ZO, .{_087} ),
// FRNDINT
instr(.FRNDINT, ops0(), Op2(0xD9, 0xFC), .ZO, .ZO, .{_087} ),
// FRSTOR
instr(.FRSTOR, ops1(.rm_mem), Op1r(0xDD, 4), .M, .ZO, .{_087} ),
instr(.FRSTORW, ops1(.rm_mem), Op1r(0xDD, 4), .M, .Op16, .{_087} ),
instr(.FRSTORD, ops1(.rm_mem), Op1r(0xDD, 4), .M, .Op32, .{_387} ),
// FSAVE / FNSAVE
instr(.FSAVE, ops1(.rm_mem), compOp1r(.FWAIT, 0xDD, 6), .M, .ZO, .{_087} ),
instr(.FSAVEW, ops1(.rm_mem), compOp1r(.FWAIT, 0xDD, 6), .M, .Op16, .{_087} ),
instr(.FSAVED, ops1(.rm_mem), compOp1r(.FWAIT, 0xDD, 6), .M, .Op32, .{_387} ),
instr(.FNSAVE, ops1(.rm_mem), Op1r(0xDD, 6), .M, .ZO, .{_087} ),
instr(.FNSAVEW, ops1(.rm_mem), Op1r(0xDD, 6), .M, .Op16, .{_087} ),
instr(.FNSAVED, ops1(.rm_mem), Op1r(0xDD, 6), .M, .Op32, .{_387} ),
// FSCALE
instr(.FSCALE, ops0(), Op2(0xD9, 0xFD), .ZO, .ZO, .{_087} ),
// FSQRT
instr(.FSQRT, ops0(), Op2(0xD9, 0xFA), .ZO, .ZO, .{_087} ),
// FST / FSTP
instr(.FST, ops1(.rm_mem32), Op1r(0xD9, 2), .M, .ZO, .{_087} ),
instr(.FST, ops1(.rm_mem64), Op1r(0xDD, 2), .M, .ZO, .{_087} ),
instr(.FST, ops1(.reg_st), Op2(0xDD, 0xD0), .O, .ZO, .{_087} ),
instr(.FST, ops2(.reg_st0, .reg_st), Op2(0xDD, 0xD0), .O2, .ZO, .{_087} ),
instr(.FSTP, ops1(.rm_mem32), Op1r(0xD9, 3), .M, .ZO, .{_087} ),
instr(.FSTP, ops1(.rm_mem64), Op1r(0xDD, 3), .M, .ZO, .{_087} ),
instr(.FSTP, ops1(.rm_mem80), Op1r(0xDB, 7), .M, .ZO, .{_087} ),
instr(.FSTP, ops1(.reg_st), Op2(0xDD, 0xD8), .O, .ZO, .{_087} ),
instr(.FSTP, ops2(.reg_st0, .reg_st), Op2(0xDD, 0xD8), .O2, .ZO, .{_087} ),
// FSTCW / FNSTCW
instr(.FSTCW, ops1(.rm_mem), compOp1r(.FWAIT, 0xD9, 7), .M, .ZO, .{_087} ),
instr(.FSTCW, ops1(.rm_mem16), compOp1r(.FWAIT, 0xD9, 7), .M, .ZO, .{_087} ),
instr(.FNSTCW, ops1(.rm_mem), Op1r(0xD9, 7), .M, .ZO, .{_087} ),
instr(.FNSTCW, ops1(.rm_mem16), Op1r(0xD9, 7), .M, .ZO, .{_087} ),
// FSTENV / FNSTENV
instr(.FSTENV, ops1(.rm_mem), compOp1r(.FWAIT, 0xD9, 6), .M, .ZO, .{_087} ),
instr(.FSTENVW, ops1(.rm_mem), compOp1r(.FWAIT, 0xD9, 6), .M, .Op16, .{_087} ),
instr(.FSTENVD, ops1(.rm_mem), compOp1r(.FWAIT, 0xD9, 6), .M, .Op32, .{_387} ),
instr(.FNSTENV, ops1(.rm_mem), Op1r(0xD9, 6), .M, .ZO, .{_087} ),
instr(.FNSTENVW,ops1(.rm_mem), Op1r(0xD9, 6), .M, .Op16, .{_087} ),
instr(.FNSTENVD,ops1(.rm_mem), Op1r(0xD9, 6), .M, .Op32, .{_387} ),
// FSTSW / FNSTSW
instr(.FSTSW, ops1(.rm_mem), compOp1r(.FWAIT, 0xDD, 7), .M, .ZO, .{_087} ),
instr(.FSTSW, ops1(.rm_mem16), compOp1r(.FWAIT, 0xDD, 7), .M, .ZO, .{_087} ),
instr(.FSTSW, ops1(.reg_ax), compOp2(.FWAIT, 0xDF,0xE0),.ZO, .ZO, .{_087} ),
instr(.FNSTSW, ops1(.rm_mem), Op1r(0xDD, 7), .M, .ZO, .{_087} ),
instr(.FNSTSW, ops1(.rm_mem16), Op1r(0xDD, 7), .M, .ZO, .{_087} ),
instr(.FNSTSW, ops1(.reg_ax), Op2(0xDF, 0xE0), .ZO, .ZO, .{_087} ),
// FSUB / FSUBP / FISUB
instr(.FSUB, ops1(.rm_mem32), Op1r(0xD8, 4), .M, .ZO, .{_087} ),
instr(.FSUB, ops1(.rm_mem64), Op1r(0xDC, 4), .M, .ZO, .{_087} ),
//
instr(.FSUB, ops1(.reg_st), Op2(0xD8, 0xE0), .O, .ZO, .{_087} ),
instr(.FSUB, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xE8), .O, .ZO, .{_087} ),
instr(.FSUB, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xE0), .O2, .ZO, .{_087} ),
//
instr(.FSUBP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xE8), .O, .ZO, .{_087} ),
instr(.FSUBP, ops0(), Op2(0xDE, 0xE9), .ZO, .ZO, .{_087} ),
//
instr(.FISUB, ops1(.rm_mem16), Op1r(0xDE, 4), .M, .ZO, .{_087} ),
instr(.FISUB, ops1(.rm_mem32), Op1r(0xDA, 4), .M, .ZO, .{_087} ),
// FSUBR / FSUBRP / FISUBR
instr(.FSUBR, ops1(.rm_mem32), Op1r(0xD8, 5), .M, .ZO, .{_087} ),
instr(.FSUBR, ops1(.rm_mem64), Op1r(0xDC, 5), .M, .ZO, .{_087} ),
//
instr(.FSUBR, ops1(.reg_st), Op2(0xD8, 0xE8), .O, .ZO, .{_087} ),
instr(.FSUBR, ops2(.reg_st0, .reg_st), Op2(0xD8, 0xE8), .O2, .ZO, .{_087} ),
instr(.FSUBR, ops2(.reg_st, .reg_st0), Op2(0xDC, 0xE0), .O, .ZO, .{_087} ),
//
instr(.FSUBRP, ops2(.reg_st, .reg_st0), Op2(0xDE, 0xE0), .O, .ZO, .{_087} ),
instr(.FSUBRP, ops0(), Op2(0xDE, 0xE1), .ZO, .ZO, .{_087} ),
//
instr(.FISUBR, ops1(.rm_mem16), Op1r(0xDE, 5), .M, .ZO, .{_087} ),
instr(.FISUBR, ops1(.rm_mem32), Op1r(0xDA, 5), .M, .ZO, .{_087} ),
// FTST
instr(.FTST, ops0(), Op2(0xD9, 0xE4), .ZO, .ZO, .{_087} ),
// FWAIT (alternate mnemonic for WAIT)
instr(.FWAIT, ops0(), Op1(0x9B), .ZO, .ZO, .{_087} ),
// FXAM
instr(.FXAM, ops0(), Op2(0xD9, 0xE5), .ZO, .ZO, .{_087} ),
// FXCH
instr(.FXCH, ops2(.reg_st0, .reg_st), Op2(0xD9, 0xC8), .O2, .ZO, .{_087} ),
instr(.FXCH, ops1(.reg_st), Op2(0xD9, 0xC8), .O, .ZO, .{_087} ),
instr(.FXCH, ops0(), Op2(0xD9, 0xC9), .ZO, .ZO, .{_087} ),
// FXTRACT
instr(.FXTRACT, ops0(), Op2(0xD9, 0xF4), .ZO, .ZO, .{_087} ),
// FYL2X
instr(.FYL2X, ops0(), Op2(0xD9, 0xF1), .ZO, .ZO, .{_087} ),
// FYL2XP1
instr(.FYL2XP1, ops0(), Op2(0xD9, 0xF9), .ZO, .ZO, .{_087} ),
//
// 80287
//
// instr(.FSETPM, ops0(), Op2(0xDB, 0xE4), .ZO, .ZO, .{cpu._287, edge.obsolete} ),
//
// 80387
//
instr(.FCOS, ops0(), Op2(0xD9, 0xFF), .ZO, .ZO, .{_387} ),
instr(.FPREM1, ops0(), Op2(0xD9, 0xF5), .ZO, .ZO, .{_387} ),
instr(.FSIN, ops0(), Op2(0xD9, 0xFE), .ZO, .ZO, .{_387} ),
instr(.FSINCOS, ops0(), Op2(0xD9, 0xFB), .ZO, .ZO, .{_387} ),
// FUCOM / FUCOMP / FUCOMPP
instr(.FUCOM, ops2(.reg_st0, .reg_st), Op2(0xDD, 0xE0), .O2, .ZO, .{_387} ),
instr(.FUCOM, ops1(.reg_st), Op2(0xDD, 0xE0), .O, .ZO, .{_387} ),
instr(.FUCOM, ops0(), Op2(0xDD, 0xE1), .ZO, .ZO, .{_387} ),
//
instr(.FUCOMP, ops2(.reg_st0, .reg_st), Op2(0xDD, 0xE8), .O2, .ZO, .{_387} ),
instr(.FUCOMP, ops1(.reg_st), Op2(0xDD, 0xE8), .O, .ZO, .{_387} ),
instr(.FUCOMP, ops0(), Op2(0xDD, 0xE9), .ZO, .ZO, .{_387} ),
//
instr(.FUCOMPP, ops0(), Op2(0xDA, 0xE9), .ZO, .ZO, .{_387} ),
//
// x87 -- Pentium Pro / P6
//
// FCMOVcc
instr(.FCMOVB, ops2(.reg_st0, .reg_st), Op2(0xDA, 0xC0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVB, ops1(.reg_st), Op2(0xDA, 0xC0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVE, ops2(.reg_st0, .reg_st), Op2(0xDA, 0xC8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVE, ops1(.reg_st), Op2(0xDA, 0xC8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVBE, ops2(.reg_st0, .reg_st), Op2(0xDA, 0xD0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVBE, ops1(.reg_st), Op2(0xDA, 0xD0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVU, ops2(.reg_st0, .reg_st), Op2(0xDA, 0xD8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVU, ops1(.reg_st), Op2(0xDA, 0xD8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVNB, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xC0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVNB, ops1(.reg_st), Op2(0xDB, 0xC0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVNE, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xC8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVNE, ops1(.reg_st), Op2(0xDB, 0xC8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVNBE, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xD0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVNBE, ops1(.reg_st), Op2(0xDB, 0xD0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
instr(.FCMOVNU, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xD8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCMOVNU, ops1(.reg_st), Op2(0xDB, 0xD8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
// FCOMI
instr(.FCOMI, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xF0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCOMI, ops1(.reg_st), Op2(0xDB, 0xF0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
// FCOMIP
instr(.FCOMIP, ops2(.reg_st0, .reg_st), Op2(0xDF, 0xF0), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FCOMIP, ops1(.reg_st), Op2(0xDF, 0xF0), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
// FUCOMI
instr(.FUCOMI, ops2(.reg_st0, .reg_st), Op2(0xDB, 0xE8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FUCOMI, ops1(.reg_st), Op2(0xDB, 0xE8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
// FUCOMIP
instr(.FUCOMIP, ops2(.reg_st0, .reg_st), Op2(0xDF, 0xE8), .O2, .ZO, .{cpu.CMOV, cpu.FPU} ),
instr(.FUCOMIP, ops1(.reg_st), Op2(0xDF, 0xE8), .O, .ZO, .{cpu.CMOV, cpu.FPU} ),
//
// x87 - other
// FISTTP - same as FSTP but won't cause a stack underflow exception
instr(.FISTTP, ops1(.rm_mem16), Op1r(0xDF, 1), .M, .ZO, .{SSE3} ),
instr(.FISTTP, ops1(.rm_mem32), Op1r(0xDB, 1), .M, .ZO, .{SSE3} ),
instr(.FISTTP, ops1(.rm_mem64), Op1r(0xDD, 1), .M, .ZO, .{SSE3} ),
//
// 80286
//
// NOTES: might want to handle operands like `r32/m16` better
instr(.ARPL, ops2(.rm16, .reg16), Op1(0x63), .MR, .ZO, .{No64, _286} ),
//
instr(.CLTS, ops0(), Op2(0x0F, 0x06), .ZO, .ZO, .{_286} ),
//
instr(.LAR, ops2(.reg16, .rm16), Op2(0x0F, 0x02), .RM, .Op16, .{_286} ),
instr(.LAR, ops2(.reg32, .rm32), Op2(0x0F, 0x02), .RM, .Op32, .{_386} ),
instr(.LAR, ops2(.reg64, .rm64), Op2(0x0F, 0x02), .RM, .REX_W, .{x86_64} ),
//
instr(.LGDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 2), .M, .ZO, .{No64, _286} ),
instr(.LGDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 2), .M, .ZO, .{No32, _286} ),
//
instr(.LIDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 3), .M, .ZO, .{No64, _286} ),
instr(.LIDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 3), .M, .ZO, .{No32, _286} ),
//
instr(.LLDT, ops1(.rm16), Op2r(0x0F, 0x00, 2), .M, .ZO, .{_286} ),
//
instr(.LMSW, ops1(.rm16), Op2r(0x0F, 0x01, 6), .M, .ZO, .{_286} ),
//
// instr(.LOADALL, ops1(.rm16), Op2r(0x0F, 0x01, 6), .M, .ZO, .{_286, _386} ), // undocumented
//
instr(.LSL, ops2(.reg16, .rm16), Op2(0x0F, 0x03), .RM, .Op16, .{_286} ),
instr(.LSL, ops2(.reg32, .rm32), Op2(0x0F, 0x03), .RM, .Op32, .{_386} ),
instr(.LSL, ops2(.reg64, .rm64), Op2(0x0F, 0x03), .RM, .REX_W, .{x86_64} ),
//
instr(.LTR, ops1(.rm16), Op2r(0x0F, 0x00, 3), .M, .ZO, .{_286} ),
//
instr(.SGDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 0), .M, .ZO, .{_286} ),
//
instr(.SIDT, ops1(.rm_mem), Op2r(0x0F, 0x01, 1), .M, .ZO, .{_286} ),
//
instr(.SLDT, ops1(.rm_mem16), Op2r(0x0F, 0x00, 0), .M, .ZO, .{_286} ),
instr(.SLDT, ops1(.rm_reg16), Op2r(0x0F, 0x00, 0), .M, .Op16, .{_286} ),
instr(.SLDT, ops1(.rm_reg32), Op2r(0x0F, 0x00, 0), .M, .Op32, .{_386} ),
instr(.SLDT, ops1(.rm_reg64), Op2r(0x0F, 0x00, 0), .M, .REX_W, .{x86_64} ),
//
instr(.SMSW, ops1(.rm_mem16), Op2r(0x0F, 0x01, 4), .M, .ZO, .{_286} ),
instr(.SMSW, ops1(.rm_reg16), Op2r(0x0F, 0x01, 4), .M, .Op16, .{_286} ),
instr(.SMSW, ops1(.rm_reg32), Op2r(0x0F, 0x01, 4), .M, .Op32, .{_386} ),
instr(.SMSW, ops1(.rm_reg64), Op2r(0x0F, 0x01, 4), .M, .REX_W, .{x86_64} ),
//
instr(.STR, ops1(.rm_mem16), Op2r(0x0F, 0x00, 1), .M, .ZO, .{_286} ),
instr(.STR, ops1(.rm_reg16), Op2r(0x0F, 0x00, 1), .M, .Op16, .{_286} ),
instr(.STR, ops1(.rm_reg32), Op2r(0x0F, 0x00, 1), .M, .Op32, .{_386} ),
instr(.STR, ops1(.rm_reg64), Op2r(0x0F, 0x00, 1), .M, .REX_W, .{x86_64} ),
//
instr(.VERR, ops1(.rm16), Op2r(0x0F, 0x00, 4), .M, .ZO, .{_286} ),
instr(.VERW, ops1(.rm16), Op2r(0x0F, 0x00, 5), .M, .ZO, .{_286} ),
//
// 80386
//
// BSF
instr(.BSF, ops2(.reg16, .rm16), Op2(0x0F, 0xBC), .RM, .Op16, .{_386} ),
instr(.BSF, ops2(.reg32, .rm32), Op2(0x0F, 0xBC), .RM, .Op32, .{_386} ),
instr(.BSF, ops2(.reg64, .rm64), Op2(0x0F, 0xBC), .RM, .REX_W, .{x86_64} ),
// BSR
instr(.BSR, ops2(.reg16, .rm16), Op2(0x0F, 0xBD), .RM, .Op16, .{_386} ),
instr(.BSR, ops2(.reg32, .rm32), Op2(0x0F, 0xBD), .RM, .Op32, .{_386} ),
instr(.BSR, ops2(.reg64, .rm64), Op2(0x0F, 0xBD), .RM, .REX_W, .{x86_64} ),
// BSR
instr(.BT, ops2(.rm16, .reg16), Op2(0x0F, 0xA3), .MR, .Op16, .{_386} ),
instr(.BT, ops2(.rm32, .reg32), Op2(0x0F, 0xA3), .MR, .Op32, .{_386} ),
instr(.BT, ops2(.rm64, .reg64), Op2(0x0F, 0xA3), .MR, .REX_W, .{x86_64} ),
//
instr(.BT, ops2(.rm16, .imm8), Op2r(0x0F, 0xBA, 4), .MI, .Op16, .{_386} ),
instr(.BT, ops2(.rm32, .imm8), Op2r(0x0F, 0xBA, 4), .MI, .Op32, .{_386} ),
instr(.BT, ops2(.rm64, .imm8), Op2r(0x0F, 0xBA, 4), .MI, .REX_W, .{x86_64} ),
// BTC
instr(.BTC, ops2(.rm16, .reg16), Op2(0x0F, 0xBB), .MR, .Op16, .{_386, Lock, Hle} ),
instr(.BTC, ops2(.rm32, .reg32), Op2(0x0F, 0xBB), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.BTC, ops2(.rm64, .reg64), Op2(0x0F, 0xBB), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.BTC, ops2(.rm16, .imm8), Op2r(0x0F, 0xBA, 7), .MI, .Op16, .{_386, Lock, Hle} ),
instr(.BTC, ops2(.rm32, .imm8), Op2r(0x0F, 0xBA, 7), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.BTC, ops2(.rm64, .imm8), Op2r(0x0F, 0xBA, 7), .MI, .REX_W, .{x86_64, Lock, Hle} ),
// BTR
instr(.BTR, ops2(.rm16, .reg16), Op2(0x0F, 0xB3), .MR, .Op16, .{_386, Lock, Hle} ),
instr(.BTR, ops2(.rm32, .reg32), Op2(0x0F, 0xB3), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.BTR, ops2(.rm64, .reg64), Op2(0x0F, 0xB3), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.BTR, ops2(.rm16, .imm8), Op2r(0x0F, 0xBA, 6), .MI, .Op16, .{_386, Lock, Hle} ),
instr(.BTR, ops2(.rm32, .imm8), Op2r(0x0F, 0xBA, 6), .MI, .Op32, .{_386, Lock, Hle} ),
instr(.BTR, ops2(.rm64, .imm8), Op2r(0x0F, 0xBA, 6), .MI, .REX_W, .{x86_64, Lock, Hle} ),
// BTS
instr(.BTS, ops2(.rm16, .reg16), Op2(0x0F, 0xAB), .MR, .Op16, .{_386, Lock, Hle} ),
instr(.BTS, ops2(.rm32, .reg32), Op2(0x0F, 0xAB), .MR, .Op32, .{_386, Lock, Hle} ),
instr(.BTS, ops2(.rm64, .reg64), Op2(0x0F, 0xAB), .MR, .REX_W, .{x86_64, Lock, Hle} ),
//
instr(.BTS, ops2(.rm16, .imm8), Op2r(0x0F, 0xBA, 5), .MI, .Op16, .{_386} ),
instr(.BTS, ops2(.rm32, .imm8), Op2r(0x0F, 0xBA, 5), .MI, .Op32, .{_386} ),
instr(.BTS, ops2(.rm64, .imm8), Op2r(0x0F, 0xBA, 5), .MI, .REX_W, .{x86_64} ),
// IBTS
instr(.IBTS, ops2(.rm16, .reg16), Op2(0x0F, 0xA7), .MR, .Op16, .{_386_Legacy, No64} ),
instr(.IBTS, ops2(.rm32, .reg32), Op2(0x0F, 0xA7), .MR, .Op32, .{_386_Legacy, No64} ),
// MOVSX / MOVSXD
instr(.MOVSX, ops2(.reg16, .rm8), Op2(0x0F, 0xBE), .RM, .Op16, .{_386} ),
instr(.MOVSX, ops2(.reg32, .rm8), Op2(0x0F, 0xBE), .RM, .Op32, .{_386} ),
instr(.MOVSX, ops2(.reg64, .rm8), Op2(0x0F, 0xBE), .RM, .REX_W, .{x86_64} ),
//
instr(.MOVSX, ops2(.reg16, .rm16), Op2(0x0F, 0xBF), .RM, .Op16, .{_386} ),
instr(.MOVSX, ops2(.reg32, .rm16), Op2(0x0F, 0xBF), .RM, .Op32, .{_386} ),
instr(.MOVSX, ops2(.reg64, .rm16), Op2(0x0F, 0xBF), .RM, .REX_W, .{x86_64} ),
//
instr(.MOVSXD, ops2(.reg16, .rm16), Op1(0x63), .RM, .Op16, .{_386} ),
instr(.MOVSXD, ops2(.reg16, .rm32), Op1(0x63), .RM, .Op16, .{_386} ),
instr(.MOVSXD, ops2(.reg32, .rm32), Op1(0x63), .RM, .Op32, .{_386} ),
instr(.MOVSXD, ops2(.reg64, .rm32), Op1(0x63), .RM, .REX_W, .{x86_64} ),
// MOVZX
instr(.MOVZX, ops2(.reg16, .rm8), Op2(0x0F, 0xB6), .RM, .Op16, .{_386} ),
instr(.MOVZX, ops2(.reg32, .rm8), Op2(0x0F, 0xB6), .RM, .Op32, .{_386} ),
instr(.MOVZX, ops2(.reg64, .rm8), Op2(0x0F, 0xB6), .RM, .REX_W, .{x86_64} ),
//
instr(.MOVZX, ops2(.reg16, .rm16), Op2(0x0F, 0xB7), .RM, .Op16, .{_386} ),
instr(.MOVZX, ops2(.reg32, .rm16), Op2(0x0F, 0xB7), .RM, .Op32, .{_386} ),
instr(.MOVZX, ops2(.reg64, .rm16), Op2(0x0F, 0xB7), .RM, .REX_W, .{x86_64} ),
// SETcc
instr(.SETA, ops1(.rm8), Op2(0x0F, 0x97), .M, .ZO, .{_386} ),
instr(.SETAE, ops1(.rm8), Op2(0x0F, 0x93), .M, .ZO, .{_386} ),
instr(.SETB, ops1(.rm8), Op2(0x0F, 0x92), .M, .ZO, .{_386} ),
instr(.SETBE, ops1(.rm8), Op2(0x0F, 0x96), .M, .ZO, .{_386} ),
instr(.SETC, ops1(.rm8), Op2(0x0F, 0x92), .M, .ZO, .{_386} ),
instr(.SETE, ops1(.rm8), Op2(0x0F, 0x94), .M, .ZO, .{_386} ),
instr(.SETG, ops1(.rm8), Op2(0x0F, 0x9F), .M, .ZO, .{_386} ),
instr(.SETGE, ops1(.rm8), Op2(0x0F, 0x9D), .M, .ZO, .{_386} ),
instr(.SETL, ops1(.rm8), Op2(0x0F, 0x9C), .M, .ZO, .{_386} ),
instr(.SETLE, ops1(.rm8), Op2(0x0F, 0x9E), .M, .ZO, .{_386} ),
instr(.SETNA, ops1(.rm8), Op2(0x0F, 0x96), .M, .ZO, .{_386} ),
instr(.SETNAE, ops1(.rm8), Op2(0x0F, 0x92), .M, .ZO, .{_386} ),
instr(.SETNB, ops1(.rm8), Op2(0x0F, 0x93), .M, .ZO, .{_386} ),
instr(.SETNBE, ops1(.rm8), Op2(0x0F, 0x97), .M, .ZO, .{_386} ),
instr(.SETNC, ops1(.rm8), Op2(0x0F, 0x93), .M, .ZO, .{_386} ),
instr(.SETNE, ops1(.rm8), Op2(0x0F, 0x95), .M, .ZO, .{_386} ),
instr(.SETNG, ops1(.rm8), Op2(0x0F, 0x9E), .M, .ZO, .{_386} ),
instr(.SETNGE, ops1(.rm8), Op2(0x0F, 0x9C), .M, .ZO, .{_386} ),
instr(.SETNL, ops1(.rm8), Op2(0x0F, 0x9D), .M, .ZO, .{_386} ),
instr(.SETNLE, ops1(.rm8), Op2(0x0F, 0x9F), .M, .ZO, .{_386} ),
instr(.SETNO, ops1(.rm8), Op2(0x0F, 0x91), .M, .ZO, .{_386} ),
instr(.SETNP, ops1(.rm8), Op2(0x0F, 0x9B), .M, .ZO, .{_386} ),
instr(.SETNS, ops1(.rm8), Op2(0x0F, 0x99), .M, .ZO, .{_386} ),
instr(.SETNZ, ops1(.rm8), Op2(0x0F, 0x95), .M, .ZO, .{_386} ),
instr(.SETO, ops1(.rm8), Op2(0x0F, 0x90), .M, .ZO, .{_386} ),
instr(.SETP, ops1(.rm8), Op2(0x0F, 0x9A), .M, .ZO, .{_386} ),
instr(.SETPE, ops1(.rm8), Op2(0x0F, 0x9A), .M, .ZO, .{_386} ),
instr(.SETPO, ops1(.rm8), Op2(0x0F, 0x9B), .M, .ZO, .{_386} ),
instr(.SETS, ops1(.rm8), Op2(0x0F, 0x98), .M, .ZO, .{_386} ),
instr(.SETZ, ops1(.rm8), Op2(0x0F, 0x94), .M, .ZO, .{_386} ),
// SHLD
instr(.SHLD, ops3(.rm16,.reg16,.imm8), Op2(0x0F, 0xA4), .MRI, .Op16, .{_386} ),
instr(.SHLD, ops3(.rm32,.reg32,.imm8), Op2(0x0F, 0xA4), .MRI, .Op32, .{_386} ),
instr(.SHLD, ops3(.rm64,.reg64,.imm8), Op2(0x0F, 0xA4), .MRI, .REX_W, .{x86_64} ),
//
instr(.SHLD, ops3(.rm16,.reg16,.reg_cl), Op2(0x0F, 0xA5), .MR, .Op16, .{_386} ),
instr(.SHLD, ops3(.rm32,.reg32,.reg_cl), Op2(0x0F, 0xA5), .MR, .Op32, .{_386} ),
instr(.SHLD, ops3(.rm64,.reg64,.reg_cl), Op2(0x0F, 0xA5), .MR, .REX_W, .{x86_64} ),
// SHLD
instr(.SHRD, ops3(.rm16,.reg16,.imm8), Op2(0x0F, 0xAC), .MRI, .Op16, .{_386} ),
instr(.SHRD, ops3(.rm32,.reg32,.imm8), Op2(0x0F, 0xAC), .MRI, .Op32, .{_386} ),
instr(.SHRD, ops3(.rm64,.reg64,.imm8), Op2(0x0F, 0xAC), .MRI, .REX_W, .{x86_64} ),
//
instr(.SHRD, ops3(.rm16,.reg16,.reg_cl), Op2(0x0F, 0xAD), .MR, .Op16, .{_386} ),
instr(.SHRD, ops3(.rm32,.reg32,.reg_cl), Op2(0x0F, 0xAD), .MR, .Op32, .{_386} ),
instr(.SHRD, ops3(.rm64,.reg64,.reg_cl), Op2(0x0F, 0xAD), .MR, .REX_W, .{x86_64} ),
// XBTS
instr(.XBTS, ops2(.reg16, .rm16), Op2(0x0F, 0xA6), .RM, .Op16, .{_386_Legacy, No64} ),
instr(.XBTS, ops2(.reg32, .rm32), Op2(0x0F, 0xA6), .RM, .Op32, .{_386_Legacy, No64} ),
//
// 80486
instr(.BSWAP, ops1(.reg16), Op2(0x0F, 0xC8), .O, .Op16, .{_486, edge.Undefined} ),
instr(.BSWAP, ops1(.reg32), Op2(0x0F, 0xC8), .O, .Op32, .{_486} ),
instr(.BSWAP, ops1(.reg64), Op2(0x0F, 0xC8), .O, .REX_W, .{x86_64} ),
// CMPXCHG
instr(.CMPXCHG, ops2(.rm8, .reg8 ), Op2(0x0F, 0xB0), .MR, .ZO, .{_486, Lock, Hle} ),
instr(.CMPXCHG, ops2(.rm16, .reg16), Op2(0x0F, 0xB1), .MR, .Op16, .{_486, Lock, Hle} ),
instr(.CMPXCHG, ops2(.rm32, .reg32), Op2(0x0F, 0xB1), .MR, .Op32, .{_486, Lock, Hle} ),
instr(.CMPXCHG, ops2(.rm64, .reg64), Op2(0x0F, 0xB1), .MR, .REX_W, .{x86_64, Lock, Hle} ),
// INVD
instr(.INVD, ops0(), Op2(0x0F, 0x08), .ZO, .ZO, .{_486} ),
// INVLPG
instr(.INVLPG, ops1(.rm_mem), Op2r(0x0F, 0x01, 7), .M, .ZO, .{_486} ),
// WBINVD
instr(.WBINVD, ops0(), Op2(0x0F, 0x09), .ZO, .ZO, .{_486} ),
// XADD
instr(.XADD, ops2(.rm8, .reg8 ), Op2(0x0F, 0xC0), .MR, .ZO, .{_486} ),
instr(.XADD, ops2(.rm16, .reg16), Op2(0x0F, 0xC1), .MR, .Op16, .{_486} ),
instr(.XADD, ops2(.rm32, .reg32), Op2(0x0F, 0xC1), .MR, .Op32, .{_486} ),
instr(.XADD, ops2(.rm64, .reg64), Op2(0x0F, 0xC1), .MR, .REX_W, .{x86_64} ),
//
// Pentium
//
instr(.CPUID, ops0(), Op2(0x0F, 0xA2), .ZO, .ZO, .{cpu.CPUID} ),
// CMPXCHG8B / CMPXCHG16B
instr(.CMPXCHG8B, ops1(.rm_mem64), Op2r(0x0F, 0xC7, 1), .M, .ZO, .{cpu.CX8, Lock, Hle} ),
instr(.CMPXCHG16B, ops1(.rm_mem128), Op2r(0x0F, 0xC7, 1), .M, .REX_W, .{cpu.CX16, Lock, Hle} ),
// RDMSR
instr(.RDMSR, ops0(), Op2(0x0F, 0x32), .ZO, .ZO, .{cpu.MSR} ),
// RDTSC
instr(.RDTSC, ops0(), Op2(0x0F, 0x31), .ZO, .ZO, .{cpu.TSC} ),
// WRMSR
instr(.WRMSR, ops0(), Op2(0x0F, 0x30), .ZO, .ZO, .{cpu.MSR} ),
// RSM
instr(.RSM, ops0(), Op2(0x0F, 0xAA), .ZO, .ZO, .{cpu.RSM} ),
//
// Pentium MMX
//
// RDPMC
instr(.RDPMC, ops0(), Op2(0x0F, 0x33), .ZO, .ZO, .{P6} ),
// EMMS
instr(.EMMS, ops0(), preOp2(._NP, 0x0F, 0x77), .ZO, .ZO, .{cpu.MMX} ),
//
// K6
//
instr(.SYSCALL, ops0(), Op2(0x0F, 0x05), .ZO, .ZO, .{cpu.SYSCALL, cpu.Intel, No32} ),
instr(.SYSCALL, ops0(), Op2(0x0F, 0x05), .ZO, .ZO, .{cpu.SYSCALL, cpu.Amd} ),
instr(.SYSCALL, ops0(), Op2(0x0F, 0x05), .ZO, .ZO, .{cpu.SYSCALL, No32} ),
//
instr(.SYSRET, ops0(), Op2(0x0F, 0x07), .ZO, .ZO, .{cpu.SYSCALL, cpu.Intel, No32} ),
instr(.SYSRET, ops0(), Op2(0x0F, 0x07), .ZO, .ZO, .{cpu.SYSCALL, cpu.Amd} ),
instr(.SYSRET, ops0(), Op2(0x0F, 0x07), .ZO, .ZO, .{cpu.SYSCALL, No32} ),
instr(.SYSRETQ, ops0(), Op2(0x0F, 0x07), .ZO, .REX_W, .{x86_64} ),
//
// Pentium Pro
//
// CMOVcc
instr(.CMOVA, ops2(.reg16, .rm16), Op2(0x0F, 0x47), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVA, ops2(.reg32, .rm32), Op2(0x0F, 0x47), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVA, ops2(.reg64, .rm64), Op2(0x0F, 0x47), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVAE, ops2(.reg16, .rm16), Op2(0x0F, 0x43), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVAE, ops2(.reg32, .rm32), Op2(0x0F, 0x43), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVAE, ops2(.reg64, .rm64), Op2(0x0F, 0x43), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVB, ops2(.reg16, .rm16), Op2(0x0F, 0x42), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVB, ops2(.reg32, .rm32), Op2(0x0F, 0x42), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVB, ops2(.reg64, .rm64), Op2(0x0F, 0x42), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVBE, ops2(.reg16, .rm16), Op2(0x0F, 0x46), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVBE, ops2(.reg32, .rm32), Op2(0x0F, 0x46), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVBE, ops2(.reg64, .rm64), Op2(0x0F, 0x46), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVC, ops2(.reg16, .rm16), Op2(0x0F, 0x42), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVC, ops2(.reg32, .rm32), Op2(0x0F, 0x42), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVC, ops2(.reg64, .rm64), Op2(0x0F, 0x42), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVE, ops2(.reg16, .rm16), Op2(0x0F, 0x44), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVE, ops2(.reg32, .rm32), Op2(0x0F, 0x44), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVE, ops2(.reg64, .rm64), Op2(0x0F, 0x44), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVG, ops2(.reg16, .rm16), Op2(0x0F, 0x4F), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVG, ops2(.reg32, .rm32), Op2(0x0F, 0x4F), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVG, ops2(.reg64, .rm64), Op2(0x0F, 0x4F), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVGE, ops2(.reg16, .rm16), Op2(0x0F, 0x4D), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVGE, ops2(.reg32, .rm32), Op2(0x0F, 0x4D), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVGE, ops2(.reg64, .rm64), Op2(0x0F, 0x4D), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVL, ops2(.reg16, .rm16), Op2(0x0F, 0x4C), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVL, ops2(.reg32, .rm32), Op2(0x0F, 0x4C), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVL, ops2(.reg64, .rm64), Op2(0x0F, 0x4C), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVLE, ops2(.reg16, .rm16), Op2(0x0F, 0x4E), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVLE, ops2(.reg32, .rm32), Op2(0x0F, 0x4E), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVLE, ops2(.reg64, .rm64), Op2(0x0F, 0x4E), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNA, ops2(.reg16, .rm16), Op2(0x0F, 0x46), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNA, ops2(.reg32, .rm32), Op2(0x0F, 0x46), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNA, ops2(.reg64, .rm64), Op2(0x0F, 0x46), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNAE, ops2(.reg16, .rm16), Op2(0x0F, 0x42), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNAE, ops2(.reg32, .rm32), Op2(0x0F, 0x42), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNAE, ops2(.reg64, .rm64), Op2(0x0F, 0x42), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNB, ops2(.reg16, .rm16), Op2(0x0F, 0x43), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNB, ops2(.reg32, .rm32), Op2(0x0F, 0x43), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNB, ops2(.reg64, .rm64), Op2(0x0F, 0x43), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNBE, ops2(.reg16, .rm16), Op2(0x0F, 0x47), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNBE, ops2(.reg32, .rm32), Op2(0x0F, 0x47), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNBE, ops2(.reg64, .rm64), Op2(0x0F, 0x47), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNC, ops2(.reg16, .rm16), Op2(0x0F, 0x43), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNC, ops2(.reg32, .rm32), Op2(0x0F, 0x43), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNC, ops2(.reg64, .rm64), Op2(0x0F, 0x43), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNE, ops2(.reg16, .rm16), Op2(0x0F, 0x45), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNE, ops2(.reg32, .rm32), Op2(0x0F, 0x45), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNE, ops2(.reg64, .rm64), Op2(0x0F, 0x45), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNG, ops2(.reg16, .rm16), Op2(0x0F, 0x4E), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNG, ops2(.reg32, .rm32), Op2(0x0F, 0x4E), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNG, ops2(.reg64, .rm64), Op2(0x0F, 0x4E), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNGE, ops2(.reg16, .rm16), Op2(0x0F, 0x4C), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNGE, ops2(.reg32, .rm32), Op2(0x0F, 0x4C), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNGE, ops2(.reg64, .rm64), Op2(0x0F, 0x4C), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNL, ops2(.reg16, .rm16), Op2(0x0F, 0x4D), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNL, ops2(.reg32, .rm32), Op2(0x0F, 0x4D), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNL, ops2(.reg64, .rm64), Op2(0x0F, 0x4D), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNLE, ops2(.reg16, .rm16), Op2(0x0F, 0x4F), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNLE, ops2(.reg32, .rm32), Op2(0x0F, 0x4F), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNLE, ops2(.reg64, .rm64), Op2(0x0F, 0x4F), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNO, ops2(.reg16, .rm16), Op2(0x0F, 0x41), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNO, ops2(.reg32, .rm32), Op2(0x0F, 0x41), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNO, ops2(.reg64, .rm64), Op2(0x0F, 0x41), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNP, ops2(.reg16, .rm16), Op2(0x0F, 0x4B), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNP, ops2(.reg32, .rm32), Op2(0x0F, 0x4B), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNP, ops2(.reg64, .rm64), Op2(0x0F, 0x4B), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNS, ops2(.reg16, .rm16), Op2(0x0F, 0x49), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNS, ops2(.reg32, .rm32), Op2(0x0F, 0x49), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNS, ops2(.reg64, .rm64), Op2(0x0F, 0x49), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVNZ, ops2(.reg16, .rm16), Op2(0x0F, 0x45), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVNZ, ops2(.reg32, .rm32), Op2(0x0F, 0x45), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVNZ, ops2(.reg64, .rm64), Op2(0x0F, 0x45), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVO, ops2(.reg16, .rm16), Op2(0x0F, 0x40), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVO, ops2(.reg32, .rm32), Op2(0x0F, 0x40), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVO, ops2(.reg64, .rm64), Op2(0x0F, 0x40), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVP, ops2(.reg16, .rm16), Op2(0x0F, 0x4A), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVP, ops2(.reg32, .rm32), Op2(0x0F, 0x4A), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVP, ops2(.reg64, .rm64), Op2(0x0F, 0x4A), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVPE, ops2(.reg16, .rm16), Op2(0x0F, 0x4A), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVPE, ops2(.reg32, .rm32), Op2(0x0F, 0x4A), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVPE, ops2(.reg64, .rm64), Op2(0x0F, 0x4A), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVPO, ops2(.reg16, .rm16), Op2(0x0F, 0x4B), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVPO, ops2(.reg32, .rm32), Op2(0x0F, 0x4B), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVPO, ops2(.reg64, .rm64), Op2(0x0F, 0x4B), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVS, ops2(.reg16, .rm16), Op2(0x0F, 0x48), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVS, ops2(.reg32, .rm32), Op2(0x0F, 0x48), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVS, ops2(.reg64, .rm64), Op2(0x0F, 0x48), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
//
instr(.CMOVZ, ops2(.reg16, .rm16), Op2(0x0F, 0x44), .RM, .Op16, .{cpu.CMOV} ),
instr(.CMOVZ, ops2(.reg32, .rm32), Op2(0x0F, 0x44), .RM, .Op32, .{cpu.CMOV} ),
instr(.CMOVZ, ops2(.reg64, .rm64), Op2(0x0F, 0x44), .RM, .REX_W, .{cpu.CMOV, x86_64} ),
// UD (first documented, but actually available since 80186)
instr(.UD0, ops0(), Op2(0x0F, 0xFF), .ZO, .ZO, .{_186_Legacy, No64} ),
instr(.UD0, ops2(.reg16, .rm16), Op2(0x0F, 0xFF), .RM, .Op16, .{_186} ),
instr(.UD0, ops2(.reg32, .rm32), Op2(0x0F, 0xFF), .RM, .Op32, .{_186} ),
instr(.UD0, ops2(.reg64, .rm64), Op2(0x0F, 0xFF), .RM, .REX_W, .{x86_64} ),
//
instr(.UD1, ops2(.reg16, .rm16), Op2(0x0F, 0xB9), .RM, .Op16, .{_186} ),
instr(.UD1, ops2(.reg32, .rm32), Op2(0x0F, 0xB9), .RM, .Op32, .{_186} ),
instr(.UD1, ops2(.reg64, .rm64), Op2(0x0F, 0xB9), .RM, .REX_W, .{x86_64} ),
//
instr(.UD2, ops0(), Op2(0x0F, 0x0B), .ZO, .ZO, .{P6} ),
//
// Pentium II
//
instr(.SYSENTER, ops0(), Op2(0x0F, 0x34), .ZO, .ZO, .{cpu.SEP, cpu.Amd, No64} ),
instr(.SYSENTER, ops0(), Op2(0x0F, 0x34), .ZO, .ZO, .{cpu.SEP, cpu.Intel} ),
instr(.SYSENTER, ops0(), Op2(0x0F, 0x34), .ZO, .ZO, .{cpu.SEP, No64} ),
//
instr(.SYSEXIT, ops0(), Op2(0x0F, 0x35), .ZO, .ZO, .{cpu.SEP, cpu.Amd, No64} ),
instr(.SYSEXIT, ops0(), Op2(0x0F, 0x35), .ZO, .ZO, .{cpu.SEP, cpu.Intel} ),
instr(.SYSEXIT, ops0(), Op2(0x0F, 0x35), .ZO, .ZO, .{cpu.SEP, No64} ),
//
instr(.SYSEXITQ, ops0(), Op2(0x0F, 0x35), .ZO, .REX_W, .{cpu.SEP, x86_64, cpu.Intel, No32} ),
//
// x86-64
//
instr(.RDTSCP, ops0(), Op3(0x0F, 0x01, 0xF9), .ZO, .ZO, .{x86_64} ),
instr(.SWAPGS, ops0(), Op3(0x0F, 0x01, 0xF8), .ZO, .ZO, .{x86_64} ),
//
// bit manipulation (ABM / BMI1 / BMI2)
//
// LZCNT
instr(.LZCNT, ops2(.reg16, .rm16), preOp2(._F3, 0x0F, 0xBD), .RM, .Op16, .{cpu.LZCNT} ),
instr(.LZCNT, ops2(.reg32, .rm32), preOp2(._F3, 0x0F, 0xBD), .RM, .Op32, .{cpu.LZCNT} ),
instr(.LZCNT, ops2(.reg64, .rm64), preOp2(._F3, 0x0F, 0xBD), .RM, .REX_W, .{cpu.LZCNT, x86_64} ),
// LZCNT
instr(.POPCNT, ops2(.reg16, .rm16), preOp2(._F3, 0x0F, 0xB8), .RM, .Op16, .{cpu.POPCNT} ),
instr(.POPCNT, ops2(.reg32, .rm32), preOp2(._F3, 0x0F, 0xB8), .RM, .Op32, .{cpu.POPCNT} ),
instr(.POPCNT, ops2(.reg64, .rm64), preOp2(._F3, 0x0F, 0xB8), .RM, .REX_W, .{cpu.POPCNT, x86_64} ),
// ANDN
instr(.ANDN, ops3(.reg32, .reg32, .rm32), vex(.LZ,._NP,._0F38,.W0, 0xF2), .RVM, .ZO, .{cpu.BMI1} ),
instr(.ANDN, ops3(.reg64, .reg64, .rm64), vex(.LZ,._NP,._0F38,.W1, 0xF2), .RVM, .ZO, .{cpu.BMI1} ),
// BEXTR
instr(.BEXTR, ops3(.reg32, .rm32, .reg32), vex(.LZ,._NP,._0F38,.W0, 0xF7), .RMV, .ZO, .{cpu.BMI1} ),
instr(.BEXTR, ops3(.reg64, .rm64, .reg64), vex(.LZ,._NP,._0F38,.W1, 0xF7), .RMV, .ZO, .{cpu.BMI1} ),
instr(.BEXTR, ops3(.reg32, .rm32, .imm32), xop(.LZ,._NP,._0Ah,.W0, 0x10), .vRMI, .ZO, .{cpu.TBM} ),
instr(.BEXTR, ops3(.reg64, .rm64, .imm32), xop(.LZ,._NP,._0Ah,.W1, 0x10), .vRMI, .ZO, .{cpu.TBM} ),
// BLSI
instr(.BLSI, ops2(.reg32, .rm32), vexr(.LZ,._NP,._0F38,.W0,0xF3, 3),.VM, .ZO, .{cpu.BMI1} ),
instr(.BLSI, ops2(.reg64, .rm64), vexr(.LZ,._NP,._0F38,.W1,0xF3, 3),.VM, .ZO, .{cpu.BMI1} ),
// BLSMSK
instr(.BLSMSK, ops2(.reg32, .rm32), vexr(.LZ,._NP,._0F38,.W0,0xF3, 2),.VM, .ZO, .{cpu.BMI1} ),
instr(.BLSMSK, ops2(.reg64, .rm64), vexr(.LZ,._NP,._0F38,.W1,0xF3, 2),.VM, .ZO, .{cpu.BMI1} ),
// BLSR
instr(.BLSR, ops2(.reg32, .rm32), vexr(.LZ,._NP,._0F38,.W0,0xF3, 1),.VM, .ZO, .{cpu.BMI1} ),
instr(.BLSR, ops2(.reg64, .rm64), vexr(.LZ,._NP,._0F38,.W1,0xF3, 1),.VM, .ZO, .{cpu.BMI1} ),
// BZHI
instr(.BZHI, ops3(.reg32, .rm32, .reg32), vex(.LZ,._NP,._0F38,.W0, 0xF5), .RMV, .ZO, .{cpu.BMI2} ),
instr(.BZHI, ops3(.reg64, .rm64, .reg64), vex(.LZ,._NP,._0F38,.W1, 0xF5), .RMV, .ZO, .{cpu.BMI2} ),
// MULX
instr(.MULX, ops3(.reg32, .reg32, .rm32), vex(.LZ,._F2,._0F38,.W0, 0xF6), .RVM, .ZO, .{cpu.BMI2} ),
instr(.MULX, ops3(.reg64, .reg64, .rm64), vex(.LZ,._F2,._0F38,.W1, 0xF6), .RVM, .ZO, .{cpu.BMI2} ),
// PDEP
instr(.PDEP, ops3(.reg32, .reg32, .rm32), vex(.LZ,._F2,._0F38,.W0, 0xF5), .RVM, .ZO, .{cpu.BMI2} ),
instr(.PDEP, ops3(.reg64, .reg64, .rm64), vex(.LZ,._F2,._0F38,.W1, 0xF5), .RVM, .ZO, .{cpu.BMI2} ),
// PEXT
instr(.PEXT, ops3(.reg32, .reg32, .rm32), vex(.LZ,._F3,._0F38,.W0, 0xF5), .RVM, .ZO, .{cpu.BMI2} ),
instr(.PEXT, ops3(.reg64, .reg64, .rm64), vex(.LZ,._F3,._0F38,.W1, 0xF5), .RVM, .ZO, .{cpu.BMI2} ),
// RORX
instr(.RORX, ops3(.reg32, .rm32, .imm8), vex(.LZ,._F2,._0F3A,.W0, 0xF0), .vRMI,.ZO, .{cpu.BMI2} ),
instr(.RORX, ops3(.reg64, .rm64, .imm8), vex(.LZ,._F2,._0F3A,.W1, 0xF0), .vRMI,.ZO, .{cpu.BMI2} ),
// SARX
instr(.SARX, ops3(.reg32, .rm32, .reg32), vex(.LZ,._F3,._0F38,.W0, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
instr(.SARX, ops3(.reg64, .rm64, .reg64), vex(.LZ,._F3,._0F38,.W1, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
// SHLX
instr(.SHLX, ops3(.reg32, .rm32, .reg32), vex(.LZ,._66,._0F38,.W0, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
instr(.SHLX, ops3(.reg64, .rm64, .reg64), vex(.LZ,._66,._0F38,.W1, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
// SHRX
instr(.SHRX, ops3(.reg32, .rm32, .reg32), vex(.LZ,._F2,._0F38,.W0, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
instr(.SHRX, ops3(.reg64, .rm64, .reg64), vex(.LZ,._F2,._0F38,.W1, 0xF7), .RMV, .ZO, .{cpu.BMI2} ),
// TZCNT
instr(.TZCNT, ops2(.reg16, .rm16), preOp2(._F3, 0x0F, 0xBC), .RM, .Op16, .{cpu.BMI1} ),
instr(.TZCNT, ops2(.reg32, .rm32), preOp2(._F3, 0x0F, 0xBC), .RM, .Op32, .{cpu.BMI1} ),
instr(.TZCNT, ops2(.reg64, .rm64), preOp2(._F3, 0x0F, 0xBC), .RM, .REX_W, .{cpu.BMI1, x86_64} ),
//
// XOP opcodes
//
//
// TBM
//
// BEXTR
// see above .BEXTR
// BLCFILL
instr(.BLCFILL, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 1), .VM, .ZO, .{cpu.TBM} ),
instr(.BLCFILL, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 1), .VM, .ZO, .{cpu.TBM} ),
// BLCI
instr(.BLCI, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x02, 6), .VM, .ZO, .{cpu.TBM} ),
instr(.BLCI, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x02, 6), .VM, .ZO, .{cpu.TBM} ),
// BLCIC
instr(.BLCIC, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 5), .VM, .ZO, .{cpu.TBM} ),
instr(.BLCIC, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 5), .VM, .ZO, .{cpu.TBM} ),
// BLCMSK
instr(.BLCMSK, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x02, 1), .VM, .ZO, .{cpu.TBM} ),
instr(.BLCMSK, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x02, 1), .VM, .ZO, .{cpu.TBM} ),
// BLCS
instr(.BLCS, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 3), .VM, .ZO, .{cpu.TBM} ),
instr(.BLCS, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 3), .VM, .ZO, .{cpu.TBM} ),
// BLSFILL
instr(.BLSFILL, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 2), .VM, .ZO, .{cpu.TBM} ),
instr(.BLSFILL, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 2), .VM, .ZO, .{cpu.TBM} ),
// BLSIC
instr(.BLSIC, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 6), .VM, .ZO, .{cpu.TBM} ),
instr(.BLSIC, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 6), .VM, .ZO, .{cpu.TBM} ),
// T1MSKC
instr(.T1MSKC, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 7), .VM, .ZO, .{cpu.TBM} ),
instr(.T1MSKC, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 7), .VM, .ZO, .{cpu.TBM} ),
// TZMSK
instr(.TZMSK, ops2(.reg32, .rm32), xopr(.LZ,._NP,._09h,.W0, 0x01, 4), .VM, .ZO, .{cpu.TBM} ),
instr(.TZMSK, ops2(.reg64, .rm64), xopr(.LZ,._NP,._09h,.W1, 0x01, 4), .VM, .ZO, .{cpu.TBM} ),
//
// LWP
//
// LLWPCB
instr(.LLWPCB, ops1(.reg32), xopr(.LZ,._NP,._09h,.W0, 0x12, 0), .vM, .ZO, .{cpu.LWP} ),
instr(.LLWPCB, ops1(.reg64), xopr(.LZ,._NP,._09h,.W1, 0x12, 0), .vM, .ZO, .{cpu.LWP} ),
// LWPINS
instr(.LWPINS, ops3(.reg32, .rm32, .imm32), xopr(.LZ,._NP,._0Ah,.W0, 0x12, 0), .VMI,.ZO, .{cpu.LWP} ),
instr(.LWPINS, ops3(.reg64, .rm32, .imm32), xopr(.LZ,._NP,._0Ah,.W1, 0x12, 0), .VMI,.ZO, .{cpu.LWP} ),
// LWPVAL
instr(.LWPVAL, ops3(.reg32, .rm32, .imm32), xopr(.LZ,._NP,._0Ah,.W0, 0x12, 1), .VMI,.ZO, .{cpu.LWP} ),
instr(.LWPVAL, ops3(.reg64, .rm32, .imm32), xopr(.LZ,._NP,._0Ah,.W1, 0x12, 1), .VMI,.ZO, .{cpu.LWP} ),
// SLWPCB
instr(.SLWPCB, ops1(.reg32), xopr(.LZ,._NP,._09h,.W0, 0x12, 1), .vM, .ZO, .{cpu.LWP} ),
instr(.SLWPCB, ops1(.reg64), xopr(.LZ,._NP,._09h,.W1, 0x12, 1), .vM, .ZO, .{cpu.LWP} ),
//
// XOP vector
//
// VFRCZPD
vec(.VFRCZPD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0x81), .vRM, .{cpu.XOP} ),
vec(.VFRCZPD, ops2(.ymml, .ymml_m256), xop(.L256,._NP,._09h,.W0, 0x81), .vRM, .{cpu.XOP} ),
// VFRCZPS
vec(.VFRCZPS, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0x80), .vRM, .{cpu.XOP} ),
vec(.VFRCZPS, ops2(.ymml, .ymml_m256), xop(.L256,._NP,._09h,.W0, 0x80), .vRM, .{cpu.XOP} ),
// VFRCZSD
vec(.VFRCZSD, ops2(.xmml, .xmml_m64), xop(.LZ,._NP,._09h,.W0, 0x83), .vRM, .{cpu.XOP} ),
// VFRCZSS
vec(.VFRCZSS, ops2(.xmml, .xmml_m32), xop(.LZ,._NP,._09h,.W0, 0x82), .vRM, .{cpu.XOP} ),
// VPCMOV
vec(.VPCMOV, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0xA2), .RVMR, .{cpu.XOP} ),
vec(.VPCMOV, ops4(.ymml, .ymml, .ymml_m256, .ymml), xop(.L256,._NP,._08h,.W0, 0xA2), .RVMR, .{cpu.XOP} ),
vec(.VPCMOV, ops4(.xmml, .xmml, .xmml, .xmml_m128), xop(.L128,._NP,._08h,.W1, 0xA2), .RVRM, .{cpu.XOP} ),
vec(.VPCMOV, ops4(.ymml, .ymml, .ymml, .ymml_m256), xop(.L256,._NP,._08h,.W1, 0xA2), .RVRM, .{cpu.XOP} ),
// VPCOMB / VPCOMW / VPCOMD / VPCOMQ
vec(.VPCOMB, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xCC), .RVMI, .{cpu.XOP} ),
vec(.VPCOMW, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xCD), .RVMI, .{cpu.XOP} ),
vec(.VPCOMD, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xCE), .RVMI, .{cpu.XOP} ),
vec(.VPCOMQ, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xCF), .RVMI, .{cpu.XOP} ),
// VPCOMUB / VPCOMUW / VPCOMUD / VPCOMUQ
vec(.VPCOMUB, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xEC), .RVMI, .{cpu.XOP} ),
vec(.VPCOMUW, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xED), .RVMI, .{cpu.XOP} ),
vec(.VPCOMUD, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xEE), .RVMI, .{cpu.XOP} ),
vec(.VPCOMUQ, ops4(.xmml, .xmml, .xmml_m128, .imm8), xop(.LZ,._NP,._08h,.W0, 0xEF), .RVMI, .{cpu.XOP} ),
// VPERMIL2PD
vec(.VPERMIL2PD, ops5(.xmml,.xmml,.xmml_m128,.xmml,.imm8), vex(.L128,._66,._0F3A,.W0, 0x49), .RVMRI,.{cpu.XOP} ),
vec(.VPERMIL2PD, ops5(.xmml,.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W1, 0x49), .RVRMI,.{cpu.XOP} ),
vec(.VPERMIL2PD, ops5(.ymml,.ymml,.ymml_m256,.ymml,.imm8), vex(.L256,._66,._0F3A,.W0, 0x49), .RVMRI,.{cpu.XOP} ),
vec(.VPERMIL2PD, ops5(.ymml,.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0x49), .RVRMI,.{cpu.XOP} ),
// VPERMIL2PS
vec(.VPERMIL2PS, ops5(.xmml,.xmml,.xmml_m128,.xmml,.imm8), vex(.L128,._66,._0F3A,.W0, 0x48), .RVMRI,.{cpu.XOP} ),
vec(.VPERMIL2PS, ops5(.xmml,.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W1, 0x48), .RVRMI,.{cpu.XOP} ),
vec(.VPERMIL2PS, ops5(.ymml,.ymml,.ymml_m256,.ymml,.imm8), vex(.L256,._66,._0F3A,.W0, 0x48), .RVMRI,.{cpu.XOP} ),
vec(.VPERMIL2PS, ops5(.ymml,.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0x48), .RVRMI,.{cpu.XOP} ),
// VPHADDBD / VPHADDBW / VPHADDBQ
vec(.VPHADDBW, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xC1), .vRM, .{cpu.XOP} ),
vec(.VPHADDBD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xC2), .vRM, .{cpu.XOP} ),
vec(.VPHADDBQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xC3), .vRM, .{cpu.XOP} ),
// VPHADDWD / VPHADDWQ
vec(.VPHADDWD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xC6), .vRM, .{cpu.XOP} ),
vec(.VPHADDWQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xC7), .vRM, .{cpu.XOP} ),
// VPHADDDQ
vec(.VPHADDDQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xCB), .vRM, .{cpu.XOP} ),
// VPHADDUBD / VPHADDUBW / VPHADDUBQ
vec(.VPHADDUBW, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xD1), .vRM, .{cpu.XOP} ),
vec(.VPHADDUBD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xD2), .vRM, .{cpu.XOP} ),
vec(.VPHADDUBQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xD3), .vRM, .{cpu.XOP} ),
// VPHADDUWD / VPHADDUWQ
vec(.VPHADDUWD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xD6), .vRM, .{cpu.XOP} ),
vec(.VPHADDUWQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xD7), .vRM, .{cpu.XOP} ),
// VPHADDUDQ
vec(.VPHADDUDQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xDB), .vRM, .{cpu.XOP} ),
// VPHSUBBW
vec(.VPHSUBBW, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xE1), .vRM, .{cpu.XOP} ),
// VPHSUBDQ
vec(.VPHSUBDQ, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xE3), .vRM, .{cpu.XOP} ),
// VPHSUBWD
vec(.VPHSUBWD, ops2(.xmml, .xmml_m128), xop(.L128,._NP,._09h,.W0, 0xE2), .vRM, .{cpu.XOP} ),
// VPMACSDD
vec(.VPMACSDD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x9E), .RVMR, .{cpu.XOP} ),
// VPMACSDQH
vec(.VPMACSDQH, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x9F), .RVMR, .{cpu.XOP} ),
// VPMACSDQL
vec(.VPMACSDQL, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x97), .RVMR, .{cpu.XOP} ),
// VPMACSSDD
vec(.VPMACSSDD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x8E), .RVMR, .{cpu.XOP} ),
// VPMACSSDQH
vec(.VPMACSSDQH, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x8F), .RVMR, .{cpu.XOP} ),
// VPMACSSDQL
vec(.VPMACSSDQL, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x87), .RVMR, .{cpu.XOP} ),
// VPMACSSWD
vec(.VPMACSSWD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x86), .RVMR, .{cpu.XOP} ),
// VPMACSSWW
vec(.VPMACSSWW, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x85), .RVMR, .{cpu.XOP} ),
// VPMACSWD
vec(.VPMACSWD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x96), .RVMR, .{cpu.XOP} ),
// VPMACSWW
vec(.VPMACSWW, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0x95), .RVMR, .{cpu.XOP} ),
// VPMADCSSWD
vec(.VPMADCSSWD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0xA6), .RVMR, .{cpu.XOP} ),
// VPMADCSWD
vec(.VPMADCSWD, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0xB6), .RVMR, .{cpu.XOP} ),
// VPPERM
vec(.VPPERM, ops4(.xmml, .xmml, .xmml_m128, .xmml), xop(.L128,._NP,._08h,.W0, 0xA3), .RVMR, .{cpu.XOP} ),
vec(.VPPERM, ops4(.xmml, .xmml, .xmml,.xmml_m128), xop(.L128,._NP,._08h,.W1, 0xA3), .RVRM, .{cpu.XOP} ),
// VPROTB / VPROTW / VPROTD / VPROTQ
// VPROTB
vec(.VPROTB, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x90), .RMV, .{cpu.XOP} ),
vec(.VPROTB, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x90), .RVM, .{cpu.XOP} ),
vec(.VPROTB, ops3(.xmml, .xmml_m128, .imm8), xop(.L128,._NP,._08h,.W0, 0xC0), .vRMI, .{cpu.XOP} ),
// VPROTW
vec(.VPROTW, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x91), .RMV, .{cpu.XOP} ),
vec(.VPROTW, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x91), .RVM, .{cpu.XOP} ),
vec(.VPROTW, ops3(.xmml, .xmml_m128, .imm8), xop(.L128,._NP,._08h,.W0, 0xC1), .vRMI, .{cpu.XOP} ),
// VPROTD
vec(.VPROTD, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x92), .RMV, .{cpu.XOP} ),
vec(.VPROTD, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x92), .RVM, .{cpu.XOP} ),
vec(.VPROTD, ops3(.xmml, .xmml_m128, .imm8), xop(.L128,._NP,._08h,.W0, 0xC2), .vRMI, .{cpu.XOP} ),
// VPROTQ
vec(.VPROTQ, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x93), .RMV, .{cpu.XOP} ),
vec(.VPROTQ, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x93), .RVM, .{cpu.XOP} ),
vec(.VPROTQ, ops3(.xmml, .xmml_m128, .imm8), xop(.L128,._NP,._08h,.W0, 0xC3), .vRMI, .{cpu.XOP} ),
// VPSHAB / VPSHAW / VPSHAD / VPSHAQ
// VPSHAB
vec(.VPSHAB, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x98), .RMV, .{cpu.XOP} ),
vec(.VPSHAB, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x98), .RVM, .{cpu.XOP} ),
// VPSHAW
vec(.VPSHAW, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x99), .RMV, .{cpu.XOP} ),
vec(.VPSHAW, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x99), .RVM, .{cpu.XOP} ),
// VPSHAD
vec(.VPSHAD, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x9A), .RMV, .{cpu.XOP} ),
vec(.VPSHAD, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x9A), .RVM, .{cpu.XOP} ),
// VPSHAQ
vec(.VPSHAQ, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x9B), .RMV, .{cpu.XOP} ),
vec(.VPSHAQ, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x9B), .RVM, .{cpu.XOP} ),
// VPSHLB / VPSHLW / VPSHLD / VPSHLQ
// VPSHLB
vec(.VPSHLB, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x94), .RMV, .{cpu.XOP} ),
vec(.VPSHLB, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x94), .RVM, .{cpu.XOP} ),
// VPSHLW
vec(.VPSHLW, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x95), .RMV, .{cpu.XOP} ),
vec(.VPSHLW, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x95), .RVM, .{cpu.XOP} ),
// VPSHLD
vec(.VPSHLD, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x96), .RMV, .{cpu.XOP} ),
vec(.VPSHLD, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x96), .RVM, .{cpu.XOP} ),
// VPSHLQ
vec(.VPSHLQ, ops3(.xmml, .xmml_m128, .xmml), xop(.L128,._NP,._09h,.W0, 0x97), .RMV, .{cpu.XOP} ),
vec(.VPSHLQ, ops3(.xmml, .xmml, .xmml_m128), xop(.L128,._NP,._09h,.W1, 0x97), .RVM, .{cpu.XOP} ),
//
// FMA4 (Fused Multiply Add 4 operands)
//
// VFMADDPD
vec(.VFMADDPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x69), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x69), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x69), .RVRM, .{cpu.FMA4} ),
vec(.VFMADDPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x69), .RVRM, .{cpu.FMA4} ),
// VFMADDPS
vec(.VFMADDPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x68), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x68), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x68), .RVRM, .{cpu.FMA4} ),
vec(.VFMADDPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x68), .RVRM, .{cpu.FMA4} ),
// VFMADDSD
vec(.VFMADDSD, ops4(.xmml, .xmml, .xmml_m64, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x6B), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSD, ops4(.xmml, .xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F3A,.W1, 0x6B), .RVRM, .{cpu.FMA4} ),
// VFMADDSS
vec(.VFMADDSS, ops4(.xmml, .xmml, .xmml_m32, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x6A), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSS, ops4(.xmml, .xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F3A,.W1, 0x6A), .RVRM, .{cpu.FMA4} ),
// VFMADDSUBPD
vec(.VFMADDSUBPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x5D), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSUBPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x5D), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSUBPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x5D), .RVRM, .{cpu.FMA4} ),
vec(.VFMADDSUBPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x5D), .RVRM, .{cpu.FMA4} ),
// VFMADDSUBPS
vec(.VFMADDSUBPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x5C), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSUBPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x5C), .RVMR, .{cpu.FMA4} ),
vec(.VFMADDSUBPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x5C), .RVRM, .{cpu.FMA4} ),
vec(.VFMADDSUBPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x5C), .RVRM, .{cpu.FMA4} ),
// VFMSUBADDPD
vec(.VFMSUBADDPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x5F), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBADDPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x5F), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBADDPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x5F), .RVRM, .{cpu.FMA4} ),
vec(.VFMSUBADDPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x5F), .RVRM, .{cpu.FMA4} ),
// VFMSUBADDPS
vec(.VFMSUBADDPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x5E), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBADDPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x5E), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBADDPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x5E), .RVRM, .{cpu.FMA4} ),
vec(.VFMSUBADDPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x5E), .RVRM, .{cpu.FMA4} ),
// VFMSUBPD
vec(.VFMSUBPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x6D), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x6D), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x6D), .RVRM, .{cpu.FMA4} ),
vec(.VFMSUBPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x6D), .RVRM, .{cpu.FMA4} ),
// VFMSUBPS
vec(.VFMSUBPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x6C), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x6C), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x6C), .RVRM, .{cpu.FMA4} ),
vec(.VFMSUBPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x6C), .RVRM, .{cpu.FMA4} ),
// VFMSUBSD
vec(.VFMSUBSD, ops4(.xmml, .xmml, .xmml_m64, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x6F), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBSD, ops4(.xmml, .xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F3A,.W1, 0x6F), .RVRM, .{cpu.FMA4} ),
// VFMSUBSS
vec(.VFMSUBSS, ops4(.xmml, .xmml, .xmml_m32, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x6E), .RVMR, .{cpu.FMA4} ),
vec(.VFMSUBSS, ops4(.xmml, .xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F3A,.W1, 0x6E), .RVRM, .{cpu.FMA4} ),
// VFNMADDPD
vec(.VFNMADDPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x79), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x79), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x79), .RVRM, .{cpu.FMA4} ),
vec(.VFNMADDPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x79), .RVRM, .{cpu.FMA4} ),
// VFNMADDPS
vec(.VFNMADDPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x78), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x78), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x78), .RVRM, .{cpu.FMA4} ),
vec(.VFNMADDPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x78), .RVRM, .{cpu.FMA4} ),
// VFNMADDSD
vec(.VFNMADDSD, ops4(.xmml, .xmml, .xmml_m64, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x7B), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDSD, ops4(.xmml, .xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F3A,.W1, 0x7B), .RVRM, .{cpu.FMA4} ),
// VFNMADDSS
vec(.VFNMADDSS, ops4(.xmml, .xmml, .xmml_m32, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x7A), .RVMR, .{cpu.FMA4} ),
vec(.VFNMADDSS, ops4(.xmml, .xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F3A,.W1, 0x7A), .RVRM, .{cpu.FMA4} ),
// VFNMSUBPD
vec(.VFNMSUBPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x7D), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x7D), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBPD, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x7D), .RVRM, .{cpu.FMA4} ),
vec(.VFNMSUBPD, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x7D), .RVRM, .{cpu.FMA4} ),
// VFNMSUBPS
vec(.VFNMSUBPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0, 0x7C), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0, 0x7C), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBPS, ops4(.xmml, .xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F3A,.W1, 0x7C), .RVRM, .{cpu.FMA4} ),
vec(.VFNMSUBPS, ops4(.ymml, .ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F3A,.W1, 0x7C), .RVRM, .{cpu.FMA4} ),
// VFNMSUBSD
vec(.VFNMSUBSD, ops4(.xmml, .xmml, .xmml_m64, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x7F), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBSD, ops4(.xmml, .xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F3A,.W1, 0x7F), .RVRM, .{cpu.FMA4} ),
// VFNMSUBSS
vec(.VFNMSUBSS, ops4(.xmml, .xmml, .xmml_m32, .xmml), vex(.LIG,._66,._0F3A,.W0, 0x7E), .RVMR, .{cpu.FMA4} ),
vec(.VFNMSUBSS, ops4(.xmml, .xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F3A,.W1, 0x7E), .RVRM, .{cpu.FMA4} ),
//
// Misc Extensions
//
// ADX
// ADCX
instr(.ADCX, ops2(.reg32, .rm32), preOp3(._66, 0x0F, 0x38, 0xF6), .RM, .Op32, .{cpu.ADX} ),
instr(.ADCX, ops2(.reg64, .rm64), preOp3(._66, 0x0F, 0x38, 0xF6), .RM, .REX_W, .{cpu.ADX} ),
// ADOX
instr(.ADOX, ops2(.reg32, .rm32), preOp3(._F3, 0x0F, 0x38, 0xF6), .RM, .Op32, .{cpu.ADX} ),
instr(.ADOX, ops2(.reg64, .rm64), preOp3(._F3, 0x0F, 0x38, 0xF6), .RM, .REX_W, .{cpu.ADX} ),
// CLDEMOTE
instr(.CLDEMOTE, ops1(.rm_mem8), preOp2r(._NP, 0x0F, 0x1C, 0), .M, .ZO, .{cpu.CLDEMOTE} ),
// CLFLUSHOPT
instr(.CLFLUSHOPT, ops1(.rm_mem8), preOp2r(._66, 0x0F, 0xAE, 7), .M, .ZO, .{cpu.CLFLUSHOPT} ),
// CET_IBT
instr(.ENDBR32, ops0(), preOp3(._F3, 0x0F, 0x1E, 0xFB), .ZO, .ZO, .{cpu.CET_IBT} ),
instr(.ENDBR64, ops0(), preOp3(._F3, 0x0F, 0x1E, 0xFA), .ZO, .ZO, .{cpu.CET_IBT} ),
// CET_SS
// CLRSSBSY
instr(.CLRSSBSY, ops1(.rm_mem64), preOp2r(._F3, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.CET_SS} ),
// INCSSPD / INCSSPQ
instr(.INCSSPD, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 5), .M, .Op32, .{cpu.CET_SS} ),
instr(.INCSSPQ, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 5), .M, .REX_W, .{cpu.CET_SS} ),
// RDSSP
instr(.RDSSPD, ops1(.reg32), preOp2r(._F3, 0x0F, 0x1E, 1), .M, .Op32, .{cpu.CET_SS} ),
instr(.RDSSPQ, ops1(.reg64), preOp2r(._F3, 0x0F, 0x1E, 1), .M, .REX_W, .{cpu.CET_SS} ),
// RSTORSSP
instr(.RSTORSSP, ops1(.rm_mem64), preOp2r(._F3, 0x0F, 0x01, 5), .M, .ZO, .{cpu.CET_SS} ),
// SAVEPREVSSP
instr(.SAVEPREVSSP,ops0(), preOp3(._F3, 0x0F, 0x01, 0xEA), .ZO,.ZO, .{cpu.CET_SS} ),
// SETSSBSY
instr(.SETSSBSY, ops0(), preOp3(._F3, 0x0F, 0x01, 0xE8), .ZO,.ZO, .{cpu.CET_SS} ),
// WRSS
instr(.WRSSD, ops2(.rm32, .reg32), Op3(0x0F, 0x38, 0xF6), .MR, .Op32, .{cpu.CET_SS} ),
instr(.WRSSQ, ops2(.rm64, .reg64), Op3(0x0F, 0x38, 0xF6), .MR, .REX_W, .{cpu.CET_SS} ),
// WRUSS
instr(.WRUSSD, ops2(.rm32, .reg32), preOp3(._66, 0x0F, 0x38, 0xF5), .MR, .Op32, .{cpu.CET_SS} ),
instr(.WRUSSQ, ops2(.rm64, .reg64), preOp3(._66, 0x0F, 0x38, 0xF5), .MR, .REX_W, .{cpu.CET_SS} ),
// CLWB
instr(.CLWB, ops1(.rm_mem8), preOp2r(._66, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.CLWB} ),
// FSGSBASE
// RDFSBASE
instr(.RDFSBASE, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 0), .M, .Op32, .{cpu.FSGSBASE} ),
instr(.RDFSBASE, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 0), .M, .REX_W, .{cpu.FSGSBASE} ),
// RDGSBASE
instr(.RDGSBASE, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 1), .M, .Op32, .{cpu.FSGSBASE} ),
instr(.RDGSBASE, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 1), .M, .REX_W, .{cpu.FSGSBASE} ),
// WRFSBASE
instr(.WRFSBASE, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 2), .M, .Op32, .{cpu.FSGSBASE} ),
instr(.WRFSBASE, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 2), .M, .REX_W, .{cpu.FSGSBASE} ),
// WRGSBASE
instr(.WRGSBASE, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 3), .M, .Op32, .{cpu.FSGSBASE} ),
instr(.WRGSBASE, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 3), .M, .REX_W, .{cpu.FSGSBASE} ),
// FXRSTOR
instr(.FXRSTOR, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 1), .M, .ZO, .{cpu.FXSR} ),
instr(.FXRSTOR64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 1), .M, .REX_W, .{cpu.FXSR, No32} ),
// FXSAVE
instr(.FXSAVE, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 0), .M, .ZO, .{cpu.FXSR} ),
instr(.FXSAVE64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 0), .M, .REX_W, .{cpu.FXSR, No32} ),
// SGX
instr(.ENCLS, ops0(), preOp3(._NP, 0x0F, 0x01, 0xCF), .ZO,.ZO, .{cpu.SGX} ),
instr(.ENCLU, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD7), .ZO,.ZO, .{cpu.SGX} ),
instr(.ENCLV, ops0(), preOp3(._NP, 0x0F, 0x01, 0xC0), .ZO,.ZO, .{cpu.SGX} ),
// SMX
instr(.GETSEC, ops0(), preOp2(._NP, 0x0F, 0x37), .ZO,.ZO, .{cpu.SMX} ),
// GFNI
instr(.GF2P8AFFINEINVQB, ops3(.xmml, .xmml_m128, .imm8), preOp3(._66, 0x0F, 0x3A, 0xCF), .RMI,.ZO, .{GFNI} ),
instr(.GF2P8AFFINEQB, ops3(.xmml, .xmml_m128, .imm8), preOp3(._66, 0x0F, 0x3A, 0xCE), .RMI,.ZO, .{GFNI} ),
instr(.GF2P8MULB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xCF), .RM, .ZO, .{GFNI} ),
// INVPCID
instr(.INVPCID, ops2(.reg32, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x82), .RM, .ZO, .{cpu.INVPCID, No64} ),
instr(.INVPCID, ops2(.reg64, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x82), .RM, .ZO, .{cpu.INVPCID, No32} ),
// MOVBE
instr(.MOVBE, ops2(.reg16, .rm_mem16), Op3(0x0F, 0x38, 0xF0), .RM, .Op16, .{cpu.MOVBE} ),
instr(.MOVBE, ops2(.reg32, .rm_mem32), Op3(0x0F, 0x38, 0xF0), .RM, .Op32, .{cpu.MOVBE} ),
instr(.MOVBE, ops2(.reg64, .rm_mem64), Op3(0x0F, 0x38, 0xF0), .RM, .REX_W, .{cpu.MOVBE} ),
//
instr(.MOVBE, ops2(.rm_mem16, .reg16), Op3(0x0F, 0x38, 0xF1), .MR, .Op16, .{cpu.MOVBE} ),
instr(.MOVBE, ops2(.rm_mem32, .reg32), Op3(0x0F, 0x38, 0xF1), .MR, .Op32, .{cpu.MOVBE} ),
instr(.MOVBE, ops2(.rm_mem64, .reg64), Op3(0x0F, 0x38, 0xF1), .MR, .REX_W, .{cpu.MOVBE} ),
// MOVDIRI
instr(.MOVDIRI, ops2(.rm_mem32, .reg32), preOp3(._NP, 0x0F, 0x38, 0xF9), .MR, .Op32, .{cpu.MOVDIRI} ),
instr(.MOVDIRI, ops2(.rm_mem64, .reg64), preOp3(._NP, 0x0F, 0x38, 0xF9), .MR, .REX_W, .{cpu.MOVDIRI} ),
// MOVDIR64B
instr(.MOVDIR64B, ops2(.reg16, .rm_mem), preOp3(._66, 0x0F, 0x38, 0xF8), .RM, .Addr16, .{cpu.MOVDIR64B, No64} ),
instr(.MOVDIR64B, ops2(.reg32, .rm_mem), preOp3(._66, 0x0F, 0x38, 0xF8), .RM, .Addr32, .{cpu.MOVDIR64B} ),
instr(.MOVDIR64B, ops2(.reg64, .rm_mem), preOp3(._66, 0x0F, 0x38, 0xF8), .RM, .Addr64, .{cpu.MOVDIR64B, No32} ),
// MPX
instr(.BNDCL, ops2(.bnd, .rm32), preOp2(._F3, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No64} ),
instr(.BNDCL, ops2(.bnd, .rm64), preOp2(._F3, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No32} ),
//
instr(.BNDCU, ops2(.bnd, .rm32), preOp2(._F2, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No64} ),
instr(.BNDCU, ops2(.bnd, .rm64), preOp2(._F2, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No32} ),
instr(.BNDCN, ops2(.bnd, .rm32), preOp2(._F2, 0x0F, 0x1B), .RM, .ZO, .{cpu.MPX, No64} ),
instr(.BNDCN, ops2(.bnd, .rm64), preOp2(._F2, 0x0F, 0x1B), .RM, .ZO, .{cpu.MPX, No32} ),
// TODO/NOTE: special `mib` encoding actually requires SIB and is not used as normal memory
instr(.BNDLDX, ops2(.bnd, .rm_mem), preOp2(._NP, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX} ),
//
instr(.BNDMK, ops2(.bnd, .rm_mem32), preOp2(._F3, 0x0F, 0x1B), .RM, .ZO, .{cpu.MPX, No64} ),
instr(.BNDMK, ops2(.bnd, .rm_mem64), preOp2(._F3, 0x0F, 0x1B), .RM, .ZO, .{cpu.MPX, No32} ),
//
instr(.BNDMOV, ops2(.bnd, .bnd_m64), preOp2(._66, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No64} ),
instr(.BNDMOV, ops2(.bnd, .bnd_m128), preOp2(._66, 0x0F, 0x1A), .RM, .ZO, .{cpu.MPX, No32} ),
instr(.BNDMOV, ops2(.bnd_m64, .bnd), preOp2(._66, 0x0F, 0x1B), .MR, .ZO, .{cpu.MPX, No64} ),
instr(.BNDMOV, ops2(.bnd_m128, .bnd), preOp2(._66, 0x0F, 0x1B), .MR, .ZO, .{cpu.MPX, No32} ),
// TODO/NOTE: special `mib` encoding actually requires SIB and is not used as normal memory
instr(.BNDSTX, ops2(.rm_mem, .bnd), preOp2(._NP, 0x0F, 0x1B), .MR, .ZO, .{cpu.MPX} ),
// PCOMMIT
instr(.PCOMMIT, ops0(), preOp3(._66, 0x0F, 0xAE, 0xF8), .ZO, .ZO, .{cpu.PCOMMIT} ),
// PKU
instr(.RDPKRU, ops0(), preOp3(._NP, 0x0F, 0x01, 0xEE), .ZO, .ZO, .{cpu.PKU} ),
instr(.WRPKRU, ops0(), preOp3(._NP, 0x0F, 0x01, 0xEF), .ZO, .ZO, .{cpu.PKU} ),
// PREFETCHW
instr(.PREFETCH, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 0), .M, .ZO, .{cpu._3DNOW} ),
instr(.PREFETCH, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 0), .M, .ZO, .{cpu.PREFETCHW, cpu.Amd} ),
instr(.PREFETCH, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 0), .M, .ZO, .{x86_64, cpu.Amd} ),
instr(.PREFETCHW, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 1), .M, .ZO, .{cpu.PREFETCHW} ),
instr(.PREFETCHW, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 1), .M, .ZO, .{cpu._3DNOW} ),
instr(.PREFETCHW, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 1), .M, .ZO, .{x86_64} ),
// PTWRITE
instr(.PTWRITE, ops1(.rm32), preOp2r(._F3, 0x0F, 0xAE, 4), .M, .Op32, .{cpu.PTWRITE} ),
instr(.PTWRITE, ops1(.rm64), preOp2r(._F3, 0x0F, 0xAE, 4), .M, .REX_W, .{cpu.PTWRITE} ),
// RDPID
instr(.RDPID, ops1(.reg32), preOp2r(._F3, 0x0F, 0xC7, 7), .M, .ZO, .{cpu.RDPID, No64} ),
instr(.RDPID, ops1(.reg64), preOp2r(._F3, 0x0F, 0xC7, 7), .M, .ZO, .{cpu.RDPID, No32} ),
// RDRAND
instr(.RDRAND, ops1(.reg16), preOp2r(.NFx, 0x0F, 0xC7, 6), .M, .Op16, .{cpu.RDRAND} ),
instr(.RDRAND, ops1(.reg32), preOp2r(.NFx, 0x0F, 0xC7, 6), .M, .Op32, .{cpu.RDRAND} ),
instr(.RDRAND, ops1(.reg64), preOp2r(.NFx, 0x0F, 0xC7, 6), .M, .REX_W, .{cpu.RDRAND} ),
// RDSEED
instr(.RDSEED, ops1(.reg16), preOp2r(.NFx, 0x0F, 0xC7, 7), .M, .Op16, .{cpu.RDSEED} ),
instr(.RDSEED, ops1(.reg32), preOp2r(.NFx, 0x0F, 0xC7, 7), .M, .Op32, .{cpu.RDSEED} ),
instr(.RDSEED, ops1(.reg64), preOp2r(.NFx, 0x0F, 0xC7, 7), .M, .REX_W, .{cpu.RDSEED} ),
// SMAP
instr(.CLAC, ops0(), preOp3(._NP, 0x0F, 0x01, 0xCA), .ZO, .ZO, .{cpu.SMAP} ),
instr(.STAC, ops0(), preOp3(._NP, 0x0F, 0x01, 0xCB), .ZO, .ZO, .{cpu.SMAP} ),
// TDX (HLE / RTM)
// HLE (NOTE: these instructions actually act as prefixes)
instr(.XACQUIRE, ops0(), Op1(0xF2), .ZO,.ZO, .{cpu.HLE} ),
instr(.XRELEASE, ops0(), Op1(0xF3), .ZO,.ZO, .{cpu.HLE} ),
// RTM
instr(.XABORT, ops1(.imm8), Op2(0xC6, 0xF8), .I, .ZO, .{cpu.RTM} ),
instr(.XBEGIN, ops1(.imm16), Op2(0xC7, 0xF8), .I, .Op16, .{cpu.RTM, Sign} ),
instr(.XBEGIN, ops1(.imm32), Op2(0xC7, 0xF8), .I, .Op32, .{cpu.RTM, Sign} ),
instr(.XEND, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD5), .ZO,.ZO, .{cpu.RTM} ),
// HLE or RTM
instr(.XTEST, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD6), .ZO,.ZO, .{cpu.HLE} ),
instr(.XTEST, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD6), .ZO,.ZO, .{cpu.RTM} ),
// WAITPKG
//
instr(.UMONITOR, ops1(.reg16), preOp2r(._F3, 0x0F, 0xAE, 6), .M, .Addr16, .{cpu.WAITPKG, No64} ),
instr(.UMONITOR, ops1(.reg32), preOp2r(._F3, 0x0F, 0xAE, 6), .M, .Addr32, .{cpu.WAITPKG} ),
instr(.UMONITOR, ops1(.reg64), preOp2r(._F3, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.WAITPKG, No32} ),
//
instr(.UMWAIT, ops3(.reg32,.reg_edx,.reg_eax),preOp2r(._F2, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.WAITPKG} ),
instr(.UMWAIT, ops1(.reg32), preOp2r(._F2, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.WAITPKG} ),
//
instr(.TPAUSE, ops3(.reg32,.reg_edx,.reg_eax),preOp2r(._66, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.WAITPKG} ),
instr(.TPAUSE, ops1(.reg32), preOp2r(._66, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.WAITPKG} ),
// XSAVE
// XGETBV
instr(.XGETBV, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD0), .ZO,.ZO, .{cpu.XSAVE} ),
// XSETBV
instr(.XSETBV, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD1), .ZO,.ZO, .{cpu.XSAVE} ),
// FXSAE
instr(.XSAVE, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 4), .M, .ZO, .{cpu.XSAVE} ),
instr(.XSAVE64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 4), .M, .REX_W, .{cpu.XSAVE, No32} ),
// FXRSTO
instr(.XRSTOR, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 5), .M, .ZO, .{cpu.XSAVE} ),
instr(.XRSTOR64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 5), .M, .REX_W, .{cpu.XSAVE, No32} ),
// XSAVEOPT
instr(.XSAVEOPT, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 6), .M, .ZO, .{cpu.XSAVEOPT} ),
instr(.XSAVEOPT64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xAE, 6), .M, .REX_W, .{cpu.XSAVEOPT, No32} ),
// XSAVEC
instr(.XSAVEC, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 4), .M, .ZO, .{cpu.XSAVEC} ),
instr(.XSAVEC64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 4), .M, .REX_W, .{cpu.XSAVEC, No32} ),
// XSS
instr(.XSAVES, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 5), .M, .ZO, .{cpu.XSS} ),
instr(.XSAVES64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 5), .M, .REX_W, .{cpu.XSS, No32} ),
//
instr(.XRSTORS, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 3), .M, .ZO, .{cpu.XSS} ),
instr(.XRSTORS64, ops1(.rm_mem), preOp2r(._NP, 0x0F, 0xC7, 3), .M, .REX_W, .{cpu.XSS, No32} ),
//
// AES instructions
//
instr(.AESDEC, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xDE), .RM, .ZO, .{cpu.AES} ),
instr(.AESDECLAST, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xDF), .RM, .ZO, .{cpu.AES} ),
instr(.AESENC, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xDC), .RM, .ZO, .{cpu.AES} ),
instr(.AESENCLAST, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xDD), .RM, .ZO, .{cpu.AES} ),
instr(.AESIMC, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38, 0xDB), .RM, .ZO, .{cpu.AES} ),
instr(.AESKEYGENASSIST, ops3(.xmml, .xmml_m128, .imm8), preOp3(._66, 0x0F, 0x3A, 0xDF), .RMI, .ZO, .{cpu.AES} ),
//
// SHA instructions
//
instr(.SHA1RNDS4, ops3(.xmml, .xmml_m128, .imm8), preOp3(._NP, 0x0F, 0x3A, 0xCC), .RMI, .ZO, .{cpu.SHA} ),
instr(.SHA1NEXTE, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xC8), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA1MSG1, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xC9), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA1MSG2, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xCA), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA256RNDS2, ops3(.xmml, .xmml_m128, .xmm0), preOp3(._NP, 0x0F, 0x38, 0xCB), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA256RNDS2, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xCB), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA256MSG1, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xCC), .RM, .ZO, .{cpu.SHA} ),
instr(.SHA256MSG2, ops2(.xmml, .xmml_m128), preOp3(._NP, 0x0F, 0x38, 0xCD), .RM, .ZO, .{cpu.SHA} ),
//
// SSE non-VEX/EVEX opcodes
//
// LDMXCSR
instr(.LDMXCSR, ops1(.rm_mem32), preOp2r(._NP, 0x0F, 0xAE, 2), .M, .ZO, .{SSE} ),
// STMXCSR
instr(.STMXCSR, ops1(.rm_mem32), preOp2r(._NP, 0x0F, 0xAE, 3), .M, .ZO, .{SSE} ),
// PREFETCH
instr(.PREFETCHNTA, ops1(.rm_mem8), Op2r(0x0F, 0x18, 0), .M, .ZO, .{SSE} ),
instr(.PREFETCHNTA, ops1(.rm_mem8), Op2r(0x0F, 0x18, 0), .M, .ZO, .{MMXEXT} ),
instr(.PREFETCHT0, ops1(.rm_mem8), Op2r(0x0F, 0x18, 1), .M, .ZO, .{SSE} ),
instr(.PREFETCHT0, ops1(.rm_mem8), Op2r(0x0F, 0x18, 1), .M, .ZO, .{MMXEXT} ),
instr(.PREFETCHT1, ops1(.rm_mem8), Op2r(0x0F, 0x18, 2), .M, .ZO, .{SSE} ),
instr(.PREFETCHT1, ops1(.rm_mem8), Op2r(0x0F, 0x18, 2), .M, .ZO, .{MMXEXT} ),
instr(.PREFETCHT2, ops1(.rm_mem8), Op2r(0x0F, 0x18, 3), .M, .ZO, .{SSE} ),
instr(.PREFETCHT2, ops1(.rm_mem8), Op2r(0x0F, 0x18, 3), .M, .ZO, .{MMXEXT} ),
// SFENCE
instr(.SFENCE, ops0(), preOp3(._NP, 0x0F, 0xAE, 0xF8), .ZO, .ZO, .{SSE} ),
instr(.SFENCE, ops0(), preOp3(._NP, 0x0F, 0xAE, 0xF8), .ZO, .ZO, .{MMXEXT} ),
// CLFLUSH
instr(.CLFLUSH, ops1(.rm_mem8), preOp2r(._NP, 0x0F, 0xAE, 7), .M, .ZO, .{SSE2} ),
// LFENCE
instr(.LFENCE, ops0(), preOp3(._NP, 0x0F, 0xAE, 0xE8), .ZO, .ZO, .{SSE2} ),
// MFENCE
instr(.MFENCE, ops0(), preOp3(._NP, 0x0F, 0xAE, 0xF0), .ZO, .ZO, .{SSE2} ),
// MOVNTI
instr(.MOVNTI, ops2(.rm_mem32, .reg32), preOp2(._NP, 0x0F, 0xC3), .MR, .Op32, .{SSE2} ),
instr(.MOVNTI, ops2(.rm_mem64, .reg64), preOp2(._NP, 0x0F, 0xC3), .MR, .REX_W, .{SSE2} ),
// PAUSE
instr(.PAUSE, ops0(), preOp1(._F3, 0x90), .ZO, .ZO, .{SSE2} ),
// MONITOR
instr(.MONITOR, ops0(), Op3(0x0F, 0x01, 0xC8), .ZO, .ZO, .{SSE3} ),
// MWAIT
instr(.MWAIT, ops0(), Op3(0x0F, 0x01, 0xC9), .ZO, .ZO, .{SSE3} ),
// CRC32
instr(.CRC32, ops2(.reg32, .rm8), preOp3(._F2, 0x0F, 0x38, 0xF0), .RM, .ZO, .{SSE4_2} ),
instr(.CRC32, ops2(.reg32, .rm16), preOp3(._F2, 0x0F, 0x38, 0xF1), .RM, .Op16, .{SSE4_2} ),
instr(.CRC32, ops2(.reg32, .rm32), preOp3(._F2, 0x0F, 0x38, 0xF1), .RM, .Op32, .{SSE4_2} ),
instr(.CRC32, ops2(.reg64, .rm64), preOp3(._F2, 0x0F, 0x38, 0xF1), .RM, .REX_W, .{SSE4_2} ),
//
// AMD-V
// CLGI
instr(.CLGI, ops0(), Op3(0x0F, 0x01, 0xDD), .ZO, .ZO, .{cpu.AMD_V} ),
// INVLPGA
instr(.INVLPGA, ops0(), Op3(0x0F, 0x01, 0xDF), .ZO, .ZO, .{cpu.AMD_V} ),
instr(.INVLPGA, ops2(.reg_ax, .reg_ecx), Op3(0x0F, 0x01, 0xDF), .ZO, .Addr16, .{cpu.AMD_V, No64} ),
instr(.INVLPGA, ops2(.reg_eax, .reg_ecx), Op3(0x0F, 0x01, 0xDF), .ZO, .Addr32, .{cpu.AMD_V} ),
instr(.INVLPGA, ops2(.reg_rax, .reg_ecx), Op3(0x0F, 0x01, 0xDF), .ZO, .Addr64, .{cpu.AMD_V, No32} ),
// SKINIT
instr(.SKINIT, ops0(), Op3(0x0F, 0x01, 0xDE), .ZO, .ZO, .{cpu.AMD_V, cpu.SKINIT} ),
instr(.SKINIT, ops1(.reg_eax), Op3(0x0F, 0x01, 0xDE), .ZO, .ZO, .{cpu.AMD_V, cpu.SKINIT} ),
// STGI
instr(.STGI, ops0(), Op3(0x0F, 0x01, 0xDC), .ZO, .ZO, .{cpu.AMD_V, cpu.SKINIT} ),
// VMLOAD
instr(.VMLOAD, ops0(), Op3(0x0F, 0x01, 0xDA), .ZO, .ZO, .{cpu.AMD_V} ),
instr(.VMLOAD, ops1(.reg_ax), Op3(0x0F, 0x01, 0xDA), .ZO, .Addr16, .{cpu.AMD_V, No64} ),
instr(.VMLOAD, ops1(.reg_eax), Op3(0x0F, 0x01, 0xDA), .ZO, .Addr32, .{cpu.AMD_V} ),
instr(.VMLOAD, ops1(.reg_rax), Op3(0x0F, 0x01, 0xDA), .ZO, .Addr64, .{cpu.AMD_V, No32} ),
// VMMCALL
instr(.VMMCALL, ops0(), Op3(0x0F, 0x01, 0xD9), .ZO, .ZO, .{cpu.AMD_V} ),
// VMRUN
instr(.VMRUN, ops0(), Op3(0x0F, 0x01, 0xD8), .ZO, .ZO, .{cpu.AMD_V} ),
instr(.VMRUN, ops1(.reg_ax), Op3(0x0F, 0x01, 0xD8), .ZO, .Addr16, .{cpu.AMD_V, No64} ),
instr(.VMRUN, ops1(.reg_eax), Op3(0x0F, 0x01, 0xD8), .ZO, .Addr32, .{cpu.AMD_V} ),
instr(.VMRUN, ops1(.reg_rax), Op3(0x0F, 0x01, 0xD8), .ZO, .Addr64, .{cpu.AMD_V, No32} ),
// VMSAVE
instr(.VMSAVE, ops0(), Op3(0x0F, 0x01, 0xDB), .ZO, .ZO, .{cpu.AMD_V} ),
instr(.VMSAVE, ops1(.reg_ax), Op3(0x0F, 0x01, 0xDB), .ZO, .Addr16, .{cpu.AMD_V, No64} ),
instr(.VMSAVE, ops1(.reg_eax), Op3(0x0F, 0x01, 0xDB), .ZO, .Addr32, .{cpu.AMD_V} ),
instr(.VMSAVE, ops1(.reg_rax), Op3(0x0F, 0x01, 0xDB), .ZO, .Addr64, .{cpu.AMD_V, No32} ),
//
// Intel VT-x
//
// INVEPT
instr(.INVEPT, ops2(.reg32, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x80), .M, .ZO, .{cpu.VT_X, No64} ),
instr(.INVEPT, ops2(.reg64, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x80), .M, .ZO, .{cpu.VT_X, No32} ),
// INVVPID
instr(.INVVPID, ops2(.reg32, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x80), .M, .ZO, .{cpu.VT_X, No64} ),
instr(.INVVPID, ops2(.reg64, .rm_mem128), preOp3(._66, 0x0F, 0x38, 0x80), .M, .ZO, .{cpu.VT_X, No32} ),
// VMCLEAR
instr(.VMCLEAR, ops1(.rm_mem64), preOp2r(._66, 0x0F, 0xC7, 6), .M, .ZO, .{cpu.VT_X} ),
// VMFUNC
instr(.VMFUNC, ops0(), preOp3(._NP, 0x0F, 0x01, 0xD4), .ZO, .ZO, .{cpu.VT_X} ),
// VMPTRLD
instr(.VMPTRLD, ops1(.rm_mem64), preOp2r(._NP, 0x0F, 0xC7, 6), .M, .ZO, .{cpu.VT_X} ),
// VMPTRST
instr(.VMPTRST, ops1(.rm_mem64), preOp2r(._NP, 0x0F, 0xC7, 7), .M, .ZO, .{cpu.VT_X} ),
// VMREAD
instr(.VMREAD, ops2(.rm32, .reg32), preOp2(._NP, 0x0F, 0x78), .MR, .Op32, .{cpu.VT_X, No64} ),
instr(.VMREAD, ops2(.rm64, .reg64), preOp2(._NP, 0x0F, 0x78), .MR, .ZO, .{cpu.VT_X, No32} ),
// VMWRITE
instr(.VMWRITE, ops2(.reg32, .rm32), preOp2(._NP, 0x0F, 0x79), .RM, .Op32, .{cpu.VT_X, No64} ),
instr(.VMWRITE, ops2(.reg64, .rm64), preOp2(._NP, 0x0F, 0x79), .RM, .ZO, .{cpu.VT_X, No32} ),
// VMCALL
instr(.VMCALL, ops0(), Op3(0x0F, 0x01, 0xC1), .ZO, .ZO, .{cpu.VT_X} ),
// VMLAUNCH
instr(.VMLAUNCH, ops0(), Op3(0x0F, 0x01, 0xC2), .ZO, .ZO, .{cpu.VT_X} ),
// VMRESUME
instr(.VMRESUME, ops0(), Op3(0x0F, 0x01, 0xC3), .ZO, .ZO, .{cpu.VT_X} ),
// VMXOFF
instr(.VMXOFF, ops0(), Op3(0x0F, 0x01, 0xC4), .ZO, .ZO, .{cpu.VT_X} ),
// VMXON
instr(.VMXON, ops1(.rm_mem64), Op3r(0x0F, 0x01, 0xC7, 6), .M, .ZO, .{cpu.VT_X} ),
//
// SIMD legacy instructions (MMX + SSE)
//
// ADDPD
instr(.ADDPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x58), .RM, .ZO, .{SSE2} ),
// ADDPS
instr(.ADDPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x58), .RM, .ZO, .{SSE} ),
// ADDSD
instr(.ADDSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x58), .RM, .ZO, .{SSE2} ),
// ADDSS
instr(.ADDSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x58), .RM, .ZO, .{SSE} ),
// ADDSUBPD
instr(.ADDSUBPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD0), .RM, .ZO, .{SSE3} ),
// ADDSUBPS
instr(.ADDSUBPS, ops2(.xmml, .xmml_m128), preOp2(._F2, 0x0F, 0xD0), .RM, .ZO, .{SSE3} ),
// ANDPD
instr(.ANDPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x54), .RM, .ZO, .{SSE2} ),
// ANDPS
instr(.ANDPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x54), .RM, .ZO, .{SSE} ),
// ANDNPD
instr(.ANDNPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x55), .RM, .ZO, .{SSE2} ),
// ANDNPS
instr(.ANDNPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x55), .RM, .ZO, .{SSE} ),
// BLENDPD
instr(.BLENDPD, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x0D), .RMI, .ZO, .{SSE4_1} ),
// BLENDPS
instr(.BLENDPS, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x0C), .RMI, .ZO, .{SSE4_1} ),
// BLENDVPD
instr(.BLENDVPD, ops3(.xmml,.xmml_m128,.xmm0), preOp3(._66,0x0F,0x38,0x15), .RM, .ZO, .{SSE4_1} ),
instr(.BLENDVPD, ops2(.xmml,.xmml_m128), preOp3(._66,0x0F,0x38,0x15), .RM, .ZO, .{SSE4_1} ),
// BLENDVPS
instr(.BLENDVPS, ops3(.xmml,.xmml_m128,.xmm0), preOp3(._66,0x0F,0x38,0x14), .RM, .ZO, .{SSE4_1} ),
instr(.BLENDVPS, ops2(.xmml,.xmml_m128), preOp3(._66,0x0F,0x38,0x14), .RM, .ZO, .{SSE4_1} ),
// CMPPD
instr(.CMPPD, ops3(.xmml,.xmml_m128,.imm8), preOp2(._66, 0x0F, 0xC2), .RMI, .ZO, .{SSE2} ),
// CMPPS
instr(.CMPPS, ops3(.xmml,.xmml_m128,.imm8), preOp2(._NP, 0x0F, 0xC2), .RMI, .ZO, .{SSE} ),
// CMPSD
instr(.CMPSD, ops0(), Op1(0xA7), .ZO, .Op32,.{_386, Repe, Repne} ), // overloaded
instr(.CMPSD, ops3(.xmml,.xmml_m64,.imm8), preOp2(._F2, 0x0F, 0xC2), .RMI, .ZO, .{SSE2} ),
// CMPSS
instr(.CMPSS, ops3(.xmml,.xmml_m32,.imm8), preOp2(._F3, 0x0F, 0xC2), .RMI, .ZO, .{SSE} ),
// COMISD
instr(.COMISD, ops2(.xmml, .xmml_m64), preOp2(._66, 0x0F, 0x2F), .RM, .ZO, .{SSE2} ),
// COMISS
instr(.COMISS, ops2(.xmml, .xmml_m32), preOp2(._NP, 0x0F, 0x2F), .RM, .ZO, .{SSE} ),
// CVTDQ2PD
instr(.CVTDQ2PD, ops2(.xmml, .xmml_m64), preOp2(._F3, 0x0F, 0xE6), .RM, .ZO, .{SSE2} ),
// CVTDQ2PS
instr(.CVTDQ2PS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x5B), .RM, .ZO, .{SSE2} ),
// CVTPD2DQ
instr(.CVTPD2DQ, ops2(.xmml, .xmml_m128), preOp2(._F2, 0x0F, 0xE6), .RM, .ZO, .{SSE2} ),
// CVTPD2PI
instr(.CVTPD2PI, ops2(.mm, .xmml_m128), preOp2(._66, 0x0F, 0x2D), .RM, .ZO, .{SSE2} ),
// CVTPD2PS
instr(.CVTPD2PS, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5A), .RM, .ZO, .{SSE2} ),
// CVTPI2PD
instr(.CVTPI2PD, ops2(.xmml, .mm_m64), preOp2(._66, 0x0F, 0x2A), .RM, .ZO, .{SSE2} ),
// CVTPI2PS
instr(.CVTPI2PS, ops2(.xmml, .mm_m64), preOp2(._NP, 0x0F, 0x2A), .RM, .ZO, .{SSE} ),
// CVTPS2DQ
instr(.CVTPS2DQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5B), .RM, .ZO, .{SSE2} ),
// CVTPS2PD
instr(.CVTPS2PD, ops2(.xmml, .xmml_m64), preOp2(._NP, 0x0F, 0x5A), .RM, .ZO, .{SSE2} ),
// CVTPS2PI
instr(.CVTPS2PI, ops2(.mm, .xmml_m64), preOp2(._NP, 0x0F, 0x2D), .RM, .ZO, .{SSE} ),
// CVTSD2SI
instr(.CVTSD2SI, ops2(.reg32, .xmml_m64), preOp2(._F2, 0x0F, 0x2D), .RM, .ZO, .{SSE2} ),
instr(.CVTSD2SI, ops2(.reg64, .xmml_m64), preOp2(._F2, 0x0F, 0x2D), .RM, .REX_W, .{SSE2} ),
// CVTSD2SS
instr(.CVTSD2SS, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x5A), .RM, .ZO, .{SSE2} ),
// CVTSI2SD
instr(.CVTSI2SD, ops2(.xmml, .rm32), preOp2(._F2, 0x0F, 0x2A), .RM, .ZO, .{SSE2} ),
instr(.CVTSI2SD, ops2(.xmml, .rm64), preOp2(._F2, 0x0F, 0x2A), .RM, .REX_W, .{SSE2} ),
// CVTSI2SS
instr(.CVTSI2SS, ops2(.xmml, .rm32), preOp2(._F3, 0x0F, 0x2A), .RM, .ZO, .{SSE} ),
instr(.CVTSI2SS, ops2(.xmml, .rm64), preOp2(._F3, 0x0F, 0x2A), .RM, .REX_W, .{SSE} ),
// CVTSS2SD
instr(.CVTSS2SD, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x5A), .RM, .ZO, .{SSE2} ),
// CVTSS2SI
instr(.CVTSS2SI, ops2(.reg32, .xmml_m32), preOp2(._F3, 0x0F, 0x2D), .RM, .ZO, .{SSE} ),
instr(.CVTSS2SI, ops2(.reg64, .xmml_m32), preOp2(._F3, 0x0F, 0x2D), .RM, .REX_W, .{SSE} ),
// CVTTPD2DQ
instr(.CVTTPD2DQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE6), .RM, .ZO, .{SSE2} ),
// CVTTPD2PI
instr(.CVTTPD2PI, ops2(.mm, .xmml_m128), preOp2(._66, 0x0F, 0x2C), .RM, .ZO, .{SSE2} ),
// CVTTPS2DQ
instr(.CVTTPS2DQ, ops2(.xmml, .xmml_m128), preOp2(._F3, 0x0F, 0x5B), .RM, .ZO, .{SSE2} ),
// CVTTPS2PI
instr(.CVTTPS2PI, ops2(.mm, .xmml_m64), preOp2(._NP, 0x0F, 0x2C), .RM, .ZO, .{SSE} ),
// CVTTSD2SI
instr(.CVTTSD2SI, ops2(.reg32, .xmml_m64), preOp2(._F2, 0x0F, 0x2C), .RM, .ZO, .{SSE2} ),
instr(.CVTTSD2SI, ops2(.reg64, .xmml_m64), preOp2(._F2, 0x0F, 0x2C), .RM, .REX_W, .{SSE2} ),
// CVTTSS2SI
instr(.CVTTSS2SI, ops2(.reg32, .xmml_m32), preOp2(._F3, 0x0F, 0x2C), .RM, .ZO, .{SSE} ),
instr(.CVTTSS2SI, ops2(.reg64, .xmml_m32), preOp2(._F3, 0x0F, 0x2C), .RM, .REX_W, .{SSE} ),
// DIVPD
instr(.DIVPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5E), .RM, .ZO, .{SSE2} ),
// DIVPS
instr(.DIVPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x5E), .RM, .ZO, .{SSE} ),
// DIVSD
instr(.DIVSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x5E), .RM, .ZO, .{SSE2} ),
// DIVSS
instr(.DIVSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x5E), .RM, .ZO, .{SSE} ),
// DPPD
instr(.DPPD, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x41), .RMI,.ZO, .{SSE4_1} ),
// DPPS
instr(.DPPS, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x40), .RMI,.ZO, .{SSE4_1} ),
// EXTRACTPS
instr(.EXTRACTPS, ops3(.rm32,.xmml,.imm8), preOp3(._66,0x0F,0x3A,0x17), .MRI,.ZO, .{SSE4_1} ),
instr(.EXTRACTPS, ops3(.reg64,.xmml,.imm8), preOp3(._66,0x0F,0x3A,0x17), .MRI,.ZO, .{SSE4_1, No32} ),
// HADDPD
instr(.HADDPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x7C), .RM, .ZO, .{SSE3} ),
// HADDPS
instr(.HADDPS, ops2(.xmml, .xmml_m128), preOp2(._F2, 0x0F, 0x7C), .RM, .ZO, .{SSE3} ),
// HSUBPD
instr(.HSUBPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x7D), .RM, .ZO, .{SSE3} ),
// HSUBPS
instr(.HSUBPS, ops2(.xmml, .xmml_m128), preOp2(._F2, 0x0F, 0x7D), .RM, .ZO, .{SSE3} ),
// INSERTPS
instr(.INSERTPS, ops3(.xmml,.xmml_m32,.imm8), preOp3(._66,0x0F,0x3A,0x21), .RMI,.ZO, .{SSE4_1} ),
// LDDQU
instr(.LDDQU, ops2(.xmml, .rm_mem128), preOp2(._F2, 0x0F, 0xF0), .RM, .ZO, .{SSE3} ),
// MASKMOVDQU
instr(.MASKMOVDQU,ops2(.xmml, .xmml), preOp2(._66, 0x0F, 0xF7), .RM, .ZO, .{SSE2} ),
// MASKMOVQ
instr(.MASKMOVQ, ops2(.mm, .mm), preOp2(._NP, 0x0F, 0xF7), .RM, .ZO, .{SSE} ),
instr(.MASKMOVQ, ops2(.mm, .mm), preOp2(._NP, 0x0F, 0xF7), .RM, .ZO, .{MMXEXT} ),
// MAXPD
instr(.MAXPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5F), .RM, .ZO, .{SSE2} ),
// MAXPS
instr(.MAXPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x5F), .RM, .ZO, .{SSE} ),
// MAXSD
instr(.MAXSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x5F), .RM, .ZO, .{SSE2} ),
// MAXSS
instr(.MAXSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x5F), .RM, .ZO, .{SSE} ),
// MINPD
instr(.MINPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5D), .RM, .ZO, .{SSE2} ),
// MINPS
instr(.MINPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x5D), .RM, .ZO, .{SSE} ),
// MINSD
instr(.MINSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x5D), .RM, .ZO, .{SSE2} ),
// MINSS
instr(.MINSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x5D), .RM, .ZO, .{SSE} ),
// MOVAPD
instr(.MOVAPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x28), .RM, .ZO, .{SSE2} ),
instr(.MOVAPD, ops2(.xmml_m128, .xmml), preOp2(._66, 0x0F, 0x29), .MR, .ZO, .{SSE2} ),
// MOVAPS
instr(.MOVAPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x28), .RM, .ZO, .{SSE} ),
instr(.MOVAPS, ops2(.xmml_m128, .xmml), preOp2(._NP, 0x0F, 0x29), .MR, .ZO, .{SSE} ),
// MOVD / MOVQ / MOVQ (2)
instr(.MOVD, ops2(.mm, .rm32), preOp2(._NP, 0x0F, 0x6E), .RM, .ZO, .{MMX} ),
instr(.MOVD, ops2(.rm32, .mm), preOp2(._NP, 0x0F, 0x7E), .MR, .ZO, .{MMX} ),
instr(.MOVD, ops2(.mm, .rm64), preOp2(._NP, 0x0F, 0x6E), .RM, .REX_W, .{MMX} ),
instr(.MOVD, ops2(.rm64, .mm), preOp2(._NP, 0x0F, 0x7E), .MR, .REX_W, .{MMX} ),
// xmm
instr(.MOVD, ops2(.xmml, .rm32), preOp2(._66, 0x0F, 0x6E), .RM, .ZO, .{SSE2} ),
instr(.MOVD, ops2(.rm32, .xmml), preOp2(._66, 0x0F, 0x7E), .MR, .ZO, .{SSE2} ),
instr(.MOVD, ops2(.xmml, .rm64), preOp2(._66, 0x0F, 0x6E), .RM, .REX_W, .{SSE2} ),
instr(.MOVD, ops2(.rm64, .xmml), preOp2(._66, 0x0F, 0x7E), .MR, .REX_W, .{SSE2} ),
// MOVQ
instr(.MOVQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x6F), .RM, .ZO, .{MMX} ),
instr(.MOVQ, ops2(.mm_m64, .mm), preOp2(._NP, 0x0F, 0x7F), .MR, .ZO, .{MMX} ),
instr(.MOVQ, ops2(.mm, .rm64), preOp2(._NP, 0x0F, 0x6E), .RM, .REX_W, .{MMX} ),
instr(.MOVQ, ops2(.rm64, .mm), preOp2(._NP, 0x0F, 0x7E), .MR, .REX_W, .{MMX} ),
// xmm
instr(.MOVQ, ops2(.xmml, .xmml_m64), preOp2(._F3, 0x0F, 0x7E), .RM, .ZO, .{SSE2} ),
instr(.MOVQ, ops2(.xmml_m64, .xmml), preOp2(._66, 0x0F, 0xD6), .MR, .ZO, .{SSE2} ),
instr(.MOVQ, ops2(.xmml, .rm64), preOp2(._66, 0x0F, 0x6E), .RM, .REX_W, .{SSE2} ),
instr(.MOVQ, ops2(.rm64, .xmml), preOp2(._66, 0x0F, 0x7E), .MR, .REX_W, .{SSE2} ),
// MOVDQA
instr(.MOVDDUP, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x12), .RM, .ZO, .{SSE3} ),
// MOVDQA
instr(.MOVDQA, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x6F), .RM, .ZO, .{SSE2} ),
instr(.MOVDQA, ops2(.xmml_m128, .xmml), preOp2(._66, 0x0F, 0x7F), .MR, .ZO, .{SSE2} ),
// MOVDQU
instr(.MOVDQU, ops2(.xmml, .xmml_m128), preOp2(._F3, 0x0F, 0x6F), .RM, .ZO, .{SSE2} ),
instr(.MOVDQU, ops2(.xmml_m128, .xmml), preOp2(._F3, 0x0F, 0x7F), .MR, .ZO, .{SSE2} ),
// MOVDQ2Q
instr(.MOVDQ2Q, ops2(.mm, .xmml), preOp2(._F2, 0x0F, 0xD6), .RM, .ZO, .{SSE2} ),
// MOVHLPS
instr(.MOVHLPS, ops2(.xmml, .xmml), preOp2(._NP, 0x0F, 0x12), .RM, .ZO, .{SSE} ),
// MOVHPD
instr(.MOVHPD, ops2(.xmml, .rm_mem64), preOp2(._66, 0x0F, 0x16), .RM, .ZO, .{SSE2} ),
// MOVHPS
instr(.MOVHPS, ops2(.xmml, .rm_mem64), preOp2(._NP, 0x0F, 0x16), .RM, .ZO, .{SSE} ),
// MOVLHPS
instr(.MOVLHPS, ops2(.xmml, .xmml), preOp2(._NP, 0x0F, 0x16), .RM, .ZO, .{SSE} ),
// MOVLPD
instr(.MOVLPD, ops2(.xmml, .rm_mem64), preOp2(._66, 0x0F, 0x12), .RM, .ZO, .{SSE2} ),
// MOVLPS
instr(.MOVLPS, ops2(.xmml, .rm_mem64), preOp2(._NP, 0x0F, 0x12), .RM, .ZO, .{SSE} ),
// MOVMSKPD
instr(.MOVMSKPD, ops2(.reg32, .xmml), preOp2(._66, 0x0F, 0x50), .RM, .ZO, .{SSE2} ),
instr(.MOVMSKPD, ops2(.reg64, .xmml), preOp2(._66, 0x0F, 0x50), .RM, .ZO, .{No32, SSE2} ),
// MOVMSKPS
instr(.MOVMSKPS, ops2(.reg32, .xmml), preOp2(._NP, 0x0F, 0x50), .RM, .ZO, .{SSE} ),
instr(.MOVMSKPS, ops2(.reg64, .xmml), preOp2(._NP, 0x0F, 0x50), .RM, .ZO, .{No32, SSE2} ),
// MOVNTDQA
instr(.MOVNTDQA, ops2(.xmml, .rm_mem128), preOp3(._66, 0x0F,0x38,0x2A), .RM, .ZO, .{SSE4_1} ),
// MOVNTDQ
instr(.MOVNTDQ, ops2(.rm_mem128, .xmml), preOp2(._66, 0x0F, 0xE7), .MR, .ZO, .{SSE2} ),
// MOVNTPD
instr(.MOVNTPD, ops2(.rm_mem128, .xmml), preOp2(._66, 0x0F, 0x2B), .MR, .ZO, .{SSE2} ),
// MOVNTPS
instr(.MOVNTPS, ops2(.rm_mem128, .xmml), preOp2(._NP, 0x0F, 0x2B), .MR, .ZO, .{SSE} ),
// MOVNTQ
instr(.MOVNTQ, ops2(.rm_mem64, .mm), preOp2(._NP, 0x0F, 0xE7), .MR, .ZO, .{SSE} ),
instr(.MOVNTQ, ops2(.rm_mem64, .mm), preOp2(._NP, 0x0F, 0xE7), .MR, .ZO, .{MMXEXT} ),
// MOVQ2DQ
instr(.MOVQ2DQ, ops2(.xmml, .mm), preOp2(._F3, 0x0F, 0xD6), .RM, .ZO, .{SSE2} ),
// MOVSD
instr(.MOVSD, ops0(), Op1(0xA5), .ZO,.Op32,.{_386, Rep} ), // overloaded
instr(.MOVSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x10), .RM, .ZO, .{SSE2} ),
instr(.MOVSD, ops2(.xmml_m64, .xmml), preOp2(._F2, 0x0F, 0x11), .MR, .ZO, .{SSE2} ),
// MOVSHDUP
instr(.MOVSHDUP, ops2(.xmml, .xmml_m128), preOp2(._F3, 0x0F, 0x16), .RM, .ZO, .{SSE3} ),
// MOVSLDUP
instr(.MOVSLDUP, ops2(.xmml, .xmml_m128), preOp2(._F3, 0x0F, 0x12), .RM, .ZO, .{SSE3} ),
// MOVSS
instr(.MOVSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x10), .RM, .ZO, .{SSE} ),
instr(.MOVSS, ops2(.xmml_m32, .xmml), preOp2(._F3, 0x0F, 0x11), .MR, .ZO, .{SSE} ),
// MOVUPD
instr(.MOVUPD, ops2(.xmml, .xmml_m64), preOp2(._66, 0x0F, 0x10), .RM, .ZO, .{SSE2} ),
instr(.MOVUPD, ops2(.xmml_m64, .xmml), preOp2(._66, 0x0F, 0x11), .MR, .ZO, .{SSE2} ),
// MOVUPS
instr(.MOVUPS, ops2(.xmml, .xmml_m32), preOp2(._NP, 0x0F, 0x10), .RM, .ZO, .{SSE} ),
instr(.MOVUPS, ops2(.xmml_m32, .xmml), preOp2(._NP, 0x0F, 0x11), .MR, .ZO, .{SSE} ),
// MPSADBW
instr(.MPSADBW, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66, 0x0F,0x3A,0x42), .RMI,.ZO, .{SSE4_1} ),
// MULPD
instr(.MULPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x59), .RM, .ZO, .{SSE2} ),
// MULPS
instr(.MULPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x59), .RM, .ZO, .{SSE} ),
// MULSD
instr(.MULSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x59), .RM, .ZO, .{SSE2} ),
// MULSS
instr(.MULSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x59), .RM, .ZO, .{SSE} ),
// ORPD
instr(.ORPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x56), .RM, .ZO, .{SSE2} ),
// ORPS
instr(.ORPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x56), .RM, .ZO, .{SSE} ),
// PABSB / PABSW /PABSD
// PABSB
instr(.PABSB, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x1C), .RM, .ZO, .{SSSE3} ),
instr(.PABSB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x1C), .RM, .ZO, .{SSSE3} ),
// PABSW
instr(.PABSW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x1D), .RM, .ZO, .{SSSE3} ),
instr(.PABSW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x1D), .RM, .ZO, .{SSSE3} ),
// PABSD
instr(.PABSD, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x1E), .RM, .ZO, .{SSSE3} ),
instr(.PABSD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x1E), .RM, .ZO, .{SSSE3} ),
// PACKSSWB / PACKSSDW
instr(.PACKSSWB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x63), .RM, .ZO, .{MMX} ),
instr(.PACKSSWB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x63), .RM, .ZO, .{SSE2} ),
//
instr(.PACKSSDW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x6B), .RM, .ZO, .{MMX} ),
instr(.PACKSSDW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x6B), .RM, .ZO, .{SSE2} ),
// PACKUSWB
instr(.PACKUSWB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x67), .RM, .ZO, .{MMX} ),
instr(.PACKUSWB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x67), .RM, .ZO, .{SSE2} ),
// PACKUSDW
instr(.PACKUSDW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F, 0x38,0x2B),.RM, .ZO, .{SSE4_1} ),
// PADDB / PADDW / PADDD / PADDQ
instr(.PADDB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xFC), .RM, .ZO, .{MMX} ),
instr(.PADDB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xFC), .RM, .ZO, .{SSE2} ),
//
instr(.PADDW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xFD), .RM, .ZO, .{MMX} ),
instr(.PADDW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xFD), .RM, .ZO, .{SSE2} ),
//
instr(.PADDD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xFE), .RM, .ZO, .{MMX} ),
instr(.PADDD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xFE), .RM, .ZO, .{SSE2} ),
//
instr(.PADDQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD4), .RM, .ZO, .{MMX} ),
instr(.PADDQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD4), .RM, .ZO, .{SSE2} ),
// PADDSB / PADDSW
instr(.PADDSB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEC), .RM, .ZO, .{MMX} ),
instr(.PADDSB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xEC), .RM, .ZO, .{SSE2} ),
//
instr(.PADDSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xED), .RM, .ZO, .{MMX} ),
instr(.PADDSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xED), .RM, .ZO, .{SSE2} ),
// PADDUSB / PADDSW
instr(.PADDUSB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDC), .RM, .ZO, .{MMX} ),
instr(.PADDUSB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDC), .RM, .ZO, .{SSE2} ),
//
instr(.PADDUSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDD), .RM, .ZO, .{MMX} ),
instr(.PADDUSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDD), .RM, .ZO, .{SSE2} ),
// PALIGNR
instr(.PALIGNR, ops3(.mm,.mm_m64,.imm8), preOp3(._NP,0x0F,0x3A,0x0F), .RMI,.ZO, .{SSSE3} ),
instr(.PALIGNR, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x0F), .RMI,.ZO, .{SSSE3} ),
// PAND
instr(.PAND, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDB), .RM, .ZO, .{MMX} ),
instr(.PAND, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDB), .RM, .ZO, .{SSE2} ),
// PANDN
instr(.PANDN, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDF), .RM, .ZO, .{MMX} ),
instr(.PANDN, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDF), .RM, .ZO, .{SSE2} ),
// PAVGB / PAVGW
instr(.PAVGB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE0), .RM, .ZO, .{SSE} ),
instr(.PAVGB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE0), .RM, .ZO, .{MMXEXT} ),
instr(.PAVGB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE0), .RM, .ZO, .{SSE2} ),
//
instr(.PAVGW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE3), .RM, .ZO, .{SSE} ),
instr(.PAVGW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE3), .RM, .ZO, .{MMXEXT} ),
instr(.PAVGW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE3), .RM, .ZO, .{SSE2} ),
// PBLENDVB
instr(.PBLENDVB, ops3(.xmml,.xmml_m128,.xmm0), preOp3(._66,0x0F,0x38,0x10), .RM, .ZO, .{SSE4_1} ),
instr(.PBLENDVB, ops2(.xmml,.xmml_m128), preOp3(._66,0x0F,0x38,0x10), .RM, .ZO, .{SSE4_1} ),
// PBLENDVW
instr(.PBLENDW, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x0E), .RMI,.ZO, .{SSE4_1} ),
// PCLMULQDQ
instr(.PCLMULQDQ, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x44), .RMI,.ZO, .{cpu.PCLMULQDQ} ),
// PCMPEQB / PCMPEQW / PCMPEQD
instr(.PCMPEQB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x74), .RM, .ZO, .{MMX} ),
instr(.PCMPEQB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x74), .RM, .ZO, .{SSE2} ),
//
instr(.PCMPEQW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x75), .RM, .ZO, .{MMX} ),
instr(.PCMPEQW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x75), .RM, .ZO, .{SSE2} ),
//
instr(.PCMPEQD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x76), .RM, .ZO, .{MMX} ),
instr(.PCMPEQD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x76), .RM, .ZO, .{SSE2} ),
// PCMPEQQ
instr(.PCMPEQQ, ops2(.xmml, .xmml_m128), preOp3(._66,0x0F,0x38,0x29), .RM, .ZO, .{SSE2} ),
// PCMPESTRI
instr(.PCMPESTRI, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x61), .RMI,.ZO, .{SSE4_2} ),
// PCMPESTRM
instr(.PCMPESTRM, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x60), .RMI,.ZO, .{SSE4_2} ),
// PCMPGTB / PCMPGTW / PCMPGTD
instr(.PCMPGTB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x64), .RM, .ZO, .{MMX} ),
instr(.PCMPGTB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x64), .RM, .ZO, .{SSE2} ),
//
instr(.PCMPGTW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x65), .RM, .ZO, .{MMX} ),
instr(.PCMPGTW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x65), .RM, .ZO, .{SSE2} ),
//
instr(.PCMPGTD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x66), .RM, .ZO, .{MMX} ),
instr(.PCMPGTD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x66), .RM, .ZO, .{SSE2} ),
// PCMPISTRI
instr(.PCMPISTRI, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x63), .RMI,.ZO, .{SSE4_2} ),
// PCMPISTRM
instr(.PCMPISTRM, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66,0x0F,0x3A,0x62), .RMI,.ZO, .{SSE4_2} ),
// PEXTRB / PEXTRD / PEXTRQ
instr(.PEXTRB, ops3(.reg32_m8, .xmml, .imm8),preOp3(._66,0x0F,0x3A,0x14), .MRI,.ZO, .{SSE4_1} ),
instr(.PEXTRB, ops3(.rm_reg64, .xmml, .imm8),preOp3(._66,0x0F,0x3A,0x14), .MRI,.ZO, .{SSE4_1, No32} ),
instr(.PEXTRD, ops3(.rm32, .xmml, .imm8), preOp3(._66,0x0F,0x3A,0x16), .MRI,.ZO, .{SSE4_1} ),
instr(.PEXTRQ, ops3(.rm64, .xmml, .imm8), preOp3(._66,0x0F,0x3A,0x16), .MRI,.REX_W, .{SSE4_1} ),
// PEXTRW
instr(.PEXTRW, ops3(.reg32, .mm, .imm8), preOp2(._NP,0x0F,0xC5), .RMI,.ZO, .{SSE} ),
instr(.PEXTRW, ops3(.reg32, .mm, .imm8), preOp2(._NP,0x0F,0xC5), .RMI,.ZO, .{MMXEXT} ),
instr(.PEXTRW, ops3(.reg64, .mm, .imm8), preOp2(._NP,0x0F,0xC5), .RMI,.ZO, .{SSE, No32} ),
instr(.PEXTRW, ops3(.reg64, .mm, .imm8), preOp2(._NP,0x0F,0xC5), .RMI,.ZO, .{MMXEXT, No32} ),
instr(.PEXTRW, ops3(.reg32, .xmml, .imm8), preOp2(._66,0x0F,0xC5), .RMI,.ZO, .{SSE2} ),
instr(.PEXTRW, ops3(.reg64, .xmml, .imm8), preOp2(._66,0x0F,0xC5), .RMI,.ZO, .{SSE2, No32} ),
instr(.PEXTRW, ops3(.reg32_m16,.xmml,.imm8), preOp3(._66,0x0F,0x3A,0x15), .MRI,.ZO, .{SSE4_1} ),
instr(.PEXTRW, ops3(.rm_reg64, .xmml, .imm8),preOp3(._66,0x0F,0x3A,0x15), .MRI,.ZO, .{SSE4_1, No32} ),
// PHADDW / PHADDD
instr(.PHADDW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x01), .RM, .ZO, .{SSSE3} ),
instr(.PHADDW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x01), .RM, .ZO, .{SSSE3} ),
instr(.PHADDD, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x02), .RM, .ZO, .{SSSE3} ),
instr(.PHADDD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x02), .RM, .ZO, .{SSSE3} ),
// PHADDSW
instr(.PHADDSW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x03), .RM, .ZO, .{SSSE3} ),
instr(.PHADDSW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x03), .RM, .ZO, .{SSSE3} ),
// PHMINPOSUW
instr(.PHMINPOSUW,ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x41), .RM, .ZO, .{SSE4_1} ),
// PHSUBW / PHSUBD
instr(.PHSUBW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x05), .RM, .ZO, .{SSSE3} ),
instr(.PHSUBW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x05), .RM, .ZO, .{SSSE3} ),
instr(.PHSUBD, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x06), .RM, .ZO, .{SSSE3} ),
instr(.PHSUBD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x06), .RM, .ZO, .{SSSE3} ),
// PHSUBSW
instr(.PHSUBSW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x07), .RM, .ZO, .{SSSE3} ),
instr(.PHSUBSW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x07), .RM, .ZO, .{SSSE3} ),
// PINSRB / PINSRD / PINSRQ
instr(.PINSRB, ops3(.xmml, .reg32_m8, .imm8),preOp3(._66,0x0F,0x3A,0x20), .RMI,.ZO, .{SSE4_1} ),
//
instr(.PINSRD, ops3(.xmml, .rm32, .imm8), preOp3(._66,0x0F,0x3A,0x22), .RMI,.ZO, .{SSE4_1} ),
//
instr(.PINSRQ, ops3(.xmml, .rm64, .imm8), preOp3(._66,0x0F,0x3A,0x22), .RMI,.REX_W, .{SSE4_1} ),
// PINSRW
instr(.PINSRW, ops3(.mm, .reg32_m16, .imm8), preOp2(._NP, 0x0F, 0xC4), .RMI,.ZO, .{SSE} ),
instr(.PINSRW, ops3(.mm, .reg32_m16, .imm8), preOp2(._NP, 0x0F, 0xC4), .RMI,.ZO, .{MMXEXT} ),
instr(.PINSRW, ops3(.xmml,.reg32_m16,.imm8), preOp2(._66, 0x0F, 0xC4), .RMI,.ZO, .{SSE2} ),
// PMADDUBSW
instr(.PMADDUBSW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x04), .RM, .ZO, .{SSSE3} ),
instr(.PMADDUBSW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x04), .RM, .ZO, .{SSSE3} ),
// PMADDWD
instr(.PMADDWD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF5), .RM, .ZO, .{MMX} ),
instr(.PMADDWD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF5), .RM, .ZO, .{SSE2} ),
// PMAXSB / PMAXSW / PMAXSD
instr(.PMAXSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEE), .RM, .ZO, .{SSE} ),
instr(.PMAXSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEE), .RM, .ZO, .{MMXEXT} ),
instr(.PMAXSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xEE), .RM, .ZO, .{SSE2} ),
instr(.PMAXSB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3C), .RM, .ZO, .{SSE4_1} ),
instr(.PMAXSD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3D), .RM, .ZO, .{SSE4_1} ),
// PMAXUB / PMAXUW
instr(.PMAXUB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDE), .RM, .ZO, .{SSE} ),
instr(.PMAXUB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDE), .RM, .ZO, .{MMXEXT} ),
instr(.PMAXUB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDE), .RM, .ZO, .{SSE2} ),
instr(.PMAXUW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3E), .RM, .ZO, .{SSE4_1} ),
// PMAXUD
instr(.PMAXUD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3F), .RM, .ZO, .{SSE4_1} ),
// PMINSB / PMINSW
instr(.PMINSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEA), .RM, .ZO, .{SSE} ),
instr(.PMINSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEA), .RM, .ZO, .{MMXEXT} ),
instr(.PMINSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xEA), .RM, .ZO, .{SSE2} ),
instr(.PMINSB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x38), .RM, .ZO, .{SSE4_1} ),
// PMINSD
instr(.PMINSD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x39), .RM, .ZO, .{SSE4_1} ),
// PMINUB / PMINUW
instr(.PMINUB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDA), .RM, .ZO, .{SSE} ),
instr(.PMINUB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xDA), .RM, .ZO, .{MMXEXT} ),
instr(.PMINUB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xDA), .RM, .ZO, .{SSE2} ),
instr(.PMINUW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3A), .RM, .ZO, .{SSE4_1} ),
// PMINUD
instr(.PMINUD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x3B), .RM, .ZO, .{SSE4_1} ),
// PMOVMSKB
instr(.PMOVMSKB, ops2(.reg32, .rm_mm), preOp2(._NP, 0x0F, 0xD7), .RM, .ZO, .{SSE} ),
instr(.PMOVMSKB, ops2(.reg32, .rm_mm), preOp2(._NP, 0x0F, 0xD7), .RM, .ZO, .{MMXEXT} ),
instr(.PMOVMSKB, ops2(.reg64, .rm_mm), preOp2(._NP, 0x0F, 0xD7), .RM, .ZO, .{SSE, No32} ),
instr(.PMOVMSKB, ops2(.reg64, .rm_mm), preOp2(._NP, 0x0F, 0xD7), .RM, .ZO, .{MMXEXT, No32} ),
instr(.PMOVMSKB, ops2(.reg32, .rm_xmml), preOp2(._66, 0x0F, 0xD7), .RM, .ZO, .{SSE} ),
instr(.PMOVMSKB, ops2(.reg64, .rm_xmml), preOp2(._66, 0x0F, 0xD7), .RM, .ZO, .{SSE, No32} ),
// PMOVSX
instr(.PMOVSXBW, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x20), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVSXBD, ops2(.xmml, .xmml_m32), preOp3(._66, 0x0F,0x38,0x21), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVSXBQ, ops2(.xmml, .xmml_m16), preOp3(._66, 0x0F,0x38,0x22), .RM, .ZO, .{SSE4_1} ),
//
instr(.PMOVSXWD, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x23), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVSXWQ, ops2(.xmml, .xmml_m32), preOp3(._66, 0x0F,0x38,0x24), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVSXDQ, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x25), .RM, .ZO, .{SSE4_1} ),
// PMOVZX
instr(.PMOVZXBW, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x30), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVZXBD, ops2(.xmml, .xmml_m32), preOp3(._66, 0x0F,0x38,0x31), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVZXBQ, ops2(.xmml, .xmml_m16), preOp3(._66, 0x0F,0x38,0x32), .RM, .ZO, .{SSE4_1} ),
//
instr(.PMOVZXWD, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x33), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVZXWQ, ops2(.xmml, .xmml_m32), preOp3(._66, 0x0F,0x38,0x34), .RM, .ZO, .{SSE4_1} ),
instr(.PMOVZXDQ, ops2(.xmml, .xmml_m64), preOp3(._66, 0x0F,0x38,0x35), .RM, .ZO, .{SSE4_1} ),
// PMULDQ
instr(.PMULDQ, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x28), .RM, .ZO, .{SSE4_1} ),
// PMULHRSW
instr(.PMULHRSW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x0B), .RM, .ZO, .{SSSE3} ),
instr(.PMULHRSW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x0B), .RM, .ZO, .{SSSE3} ),
// PMULHUW
instr(.PMULHUW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE4), .RM, .ZO, .{SSE} ),
instr(.PMULHUW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE4), .RM, .ZO, .{MMXEXT} ),
instr(.PMULHUW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE4), .RM, .ZO, .{SSE2} ),
// PMULHW
instr(.PMULHW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE5), .RM, .ZO, .{MMX} ),
instr(.PMULHW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE5), .RM, .ZO, .{SSE2} ),
// PMULLD
instr(.PMULLD, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x40), .RM, .ZO, .{SSE4_1} ),
// PMULLW
instr(.PMULLW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD5), .RM, .ZO, .{MMX} ),
instr(.PMULLW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD5), .RM, .ZO, .{SSE2} ),
// PMULUDQ
instr(.PMULUDQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF4), .RM, .ZO, .{SSE2} ),
instr(.PMULUDQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF4), .RM, .ZO, .{SSE2} ),
// POR
instr(.POR, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEB), .RM, .ZO, .{MMX} ),
instr(.POR, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xEB), .RM, .ZO, .{SSE2} ),
// PSADBW
instr(.PSADBW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF6), .RM, .ZO, .{SSE} ),
instr(.PSADBW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF6), .RM, .ZO, .{MMXEXT} ),
instr(.PSADBW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF6), .RM, .ZO, .{SSE2} ),
// PSHUFB
instr(.PSHUFB, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x00), .RM, .ZO, .{SSSE3} ),
instr(.PSHUFB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x00), .RM, .ZO, .{SSSE3} ),
// PSHUFD
instr(.PSHUFD, ops3(.xmml,.xmml_m128,.imm8), preOp2(._66, 0x0F, 0x70), .RMI,.ZO, .{SSE2} ),
// PSHUFHW
instr(.PSHUFHW, ops3(.xmml,.xmml_m128,.imm8), preOp2(._F3, 0x0F, 0x70), .RMI,.ZO, .{SSE2} ),
// PSHUFLW
instr(.PSHUFLW, ops3(.xmml,.xmml_m128,.imm8), preOp2(._F2, 0x0F, 0x70), .RMI,.ZO, .{SSE2} ),
// PSHUFW
instr(.PSHUFW, ops3(.mm, .mm_m64, .imm8), preOp2(._NP, 0x0F, 0x70), .RMI,.ZO, .{SSE} ),
instr(.PSHUFW, ops3(.mm, .mm_m64, .imm8), preOp2(._NP, 0x0F, 0x70), .RMI,.ZO, .{MMXEXT} ),
// PSIGNB / PSIGNW / PSIGND
instr(.PSIGNB, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x08), .RM, .ZO, .{SSSE3} ),
instr(.PSIGNB, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x08), .RM, .ZO, .{SSSE3} ),
//
instr(.PSIGNW, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x09), .RM, .ZO, .{SSSE3} ),
instr(.PSIGNW, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x09), .RM, .ZO, .{SSSE3} ),
//
instr(.PSIGND, ops2(.mm, .mm_m64), preOp3(._NP, 0x0F,0x38,0x0A), .RM, .ZO, .{SSSE3} ),
instr(.PSIGND, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x0A), .RM, .ZO, .{SSSE3} ),
// PSLLDQ
instr(.PSLLDQ, ops2(.rm_xmml, .imm8), preOp2r(._66, 0x0F, 0x73, 7), .MI, .ZO, .{SSE2} ),
// PSLLW / PSLLD / PSLLQ
// PSLLW
instr(.PSLLW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF1), .RM, .ZO, .{MMX} ),
instr(.PSLLW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF1), .RM, .ZO, .{SSE2} ),
//
instr(.PSLLW, ops2(.rm_mm, .imm8), preOp2r(._NP, 0x0F, 0x71, 6), .MI, .ZO, .{MMX} ),
instr(.PSLLW, ops2(.rm_xmml, .imm8), preOp2r(._66, 0x0F, 0x71, 6), .MI, .ZO, .{SSE2} ),
// PSLLD
instr(.PSLLD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF2), .RM, .ZO, .{MMX} ),
instr(.PSLLD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF2), .RM, .ZO, .{SSE2} ),
//
instr(.PSLLD, ops2(.rm_mm, .imm8), preOp2r(._NP, 0x0F, 0x72, 6), .MI, .ZO, .{MMX} ),
instr(.PSLLD, ops2(.rm_xmml, .imm8), preOp2r(._66, 0x0F, 0x72, 6), .MI, .ZO, .{SSE2} ),
// PSLLQ
instr(.PSLLQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF3), .RM, .ZO, .{MMX} ),
instr(.PSLLQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF3), .RM, .ZO, .{SSE2} ),
//
instr(.PSLLQ, ops2(.rm_mm, .imm8), preOp2r(._NP, 0x0F, 0x73, 6), .MI, .ZO, .{MMX} ),
instr(.PSLLQ, ops2(.rm_xmml, .imm8), preOp2r(._66, 0x0F, 0x73, 6), .MI, .ZO, .{SSE2} ),
// PSRAW / PSRAD
// PSRAW
instr(.PSRAW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE1), .RM, .ZO, .{MMX} ),
instr(.PSRAW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE1), .RM, .ZO, .{SSE2} ),
//
instr(.PSRAW, ops2(.mm, .imm8), preOp2r(._NP, 0x0F, 0x71, 4), .MI, .ZO, .{MMX} ),
instr(.PSRAW, ops2(.xmml, .imm8), preOp2r(._66, 0x0F, 0x71, 4), .MI, .ZO, .{SSE2} ),
// PSRAD
instr(.PSRAD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE2), .RM, .ZO, .{MMX} ),
instr(.PSRAD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE2), .RM, .ZO, .{SSE2} ),
//
instr(.PSRAD, ops2(.mm, .imm8), preOp2r(._NP, 0x0F, 0x72, 4), .MI, .ZO, .{MMX} ),
instr(.PSRAD, ops2(.xmml, .imm8), preOp2r(._66, 0x0F, 0x72, 4), .MI, .ZO, .{SSE2} ),
// PSRLDQ
instr(.PSRLDQ, ops2(.rm_xmml, .imm8), preOp2r(._66, 0x0F, 0x73, 3), .MI, .ZO, .{SSE2} ),
// PSRLW / PSRLD / PSRLQ
// PSRLW
instr(.PSRLW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD1), .RM, .ZO, .{MMX} ),
instr(.PSRLW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD1), .RM, .ZO, .{SSE2} ),
//
instr(.PSRLW, ops2(.mm, .imm8), preOp2r(._NP, 0x0F, 0x71, 2), .MI, .ZO, .{MMX} ),
instr(.PSRLW, ops2(.xmml, .imm8), preOp2r(._66, 0x0F, 0x71, 2), .MI, .ZO, .{SSE2} ),
// PSRLD
instr(.PSRLD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD2), .RM, .ZO, .{MMX} ),
instr(.PSRLD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD2), .RM, .ZO, .{SSE2} ),
//
instr(.PSRLD, ops2(.mm, .imm8), preOp2r(._NP, 0x0F, 0x72, 2), .MI, .ZO, .{MMX} ),
instr(.PSRLD, ops2(.xmml, .imm8), preOp2r(._66, 0x0F, 0x72, 2), .MI, .ZO, .{SSE2} ),
// PSRLQ
instr(.PSRLQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD3), .RM, .ZO, .{MMX} ),
instr(.PSRLQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD3), .RM, .ZO, .{SSE2} ),
//
instr(.PSRLQ, ops2(.mm, .imm8), preOp2r(._NP, 0x0F, 0x73, 2), .MI, .ZO, .{MMX} ),
instr(.PSRLQ, ops2(.xmml, .imm8), preOp2r(._66, 0x0F, 0x73, 2), .MI, .ZO, .{SSE2} ),
// PSUBB / PSUBW / PSUBD
// PSUBB
instr(.PSUBB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF8), .RM, .ZO, .{MMX} ),
instr(.PSUBB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF8), .RM, .ZO, .{SSE2} ),
// PSUBW
instr(.PSUBW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xF9), .RM, .ZO, .{MMX} ),
instr(.PSUBW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xF9), .RM, .ZO, .{SSE2} ),
// PSUBD
instr(.PSUBD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xFA), .RM, .ZO, .{MMX} ),
instr(.PSUBD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xFA), .RM, .ZO, .{SSE2} ),
// PSUBQ
instr(.PSUBQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xFB), .RM, .ZO, .{SSE2} ),
instr(.PSUBQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xFB), .RM, .ZO, .{SSE2} ),
// PSUBSB / PSUBSW
// PSUBSB
instr(.PSUBSB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE8), .RM, .ZO, .{MMX} ),
instr(.PSUBSB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE8), .RM, .ZO, .{SSE2} ),
// PSUBSW
instr(.PSUBSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xE9), .RM, .ZO, .{MMX} ),
instr(.PSUBSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xE9), .RM, .ZO, .{SSE2} ),
// PSUBUSB / PSUBUSW
// PSUBUSB
instr(.PSUBUSB, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD8), .RM, .ZO, .{MMX} ),
instr(.PSUBUSB, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD8), .RM, .ZO, .{SSE2} ),
// PSUBUSW
instr(.PSUBUSW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xD9), .RM, .ZO, .{MMX} ),
instr(.PSUBUSW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xD9), .RM, .ZO, .{SSE2} ),
// PTEST
instr(.PTEST, ops2(.xmml, .xmml_m128), preOp3(._66, 0x0F,0x38,0x17), .RM, .ZO, .{SSE4_1} ),
// PUNPCKHBW / PUNPCKHWD / PUNPCKHDQ / PUNPCKHQDQ
instr(.PUNPCKHBW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x68), .RM, .ZO, .{MMX} ),
instr(.PUNPCKHBW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x68), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKHWD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x69), .RM, .ZO, .{MMX} ),
instr(.PUNPCKHWD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x69), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKHDQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x6A), .RM, .ZO, .{MMX} ),
instr(.PUNPCKHDQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x6A), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKHQDQ,ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x6D), .RM, .ZO, .{SSE2} ),
// PUNPCKLBW / PUNPCKLWD / PUNPCKLDQ / PUNPCKLQDQ
instr(.PUNPCKLBW, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x60), .RM, .ZO, .{MMX} ),
instr(.PUNPCKLBW, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x60), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKLWD, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x61), .RM, .ZO, .{MMX} ),
instr(.PUNPCKLWD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x61), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKLDQ, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0x62), .RM, .ZO, .{MMX} ),
instr(.PUNPCKLDQ, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x62), .RM, .ZO, .{SSE2} ),
//
instr(.PUNPCKLQDQ,ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x6C), .RM, .ZO, .{SSE2} ),
// PXOR
instr(.PXOR, ops2(.mm, .mm_m64), preOp2(._NP, 0x0F, 0xEF), .RM, .ZO, .{MMX} ),
instr(.PXOR, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0xEF), .RM, .ZO, .{SSE2} ),
// RCPPS
instr(.RCPPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x53), .RM, .ZO, .{SSE} ),
// RCPSS
instr(.RCPSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x53), .RM, .ZO, .{SSE} ),
// ROUNDPD
instr(.ROUNDPD, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66, 0x0F,0x3A,0x09), .RMI,.ZO, .{SSE4_1} ),
// ROUNDPS
instr(.ROUNDPS, ops3(.xmml,.xmml_m128,.imm8), preOp3(._66, 0x0F,0x3A,0x08), .RMI,.ZO, .{SSE4_1} ),
// ROUNDSD
instr(.ROUNDSD, ops3(.xmml,.xmml_m64,.imm8), preOp3(._66, 0x0F,0x3A,0x0B), .RMI,.ZO, .{SSE4_1} ),
// ROUNDSS
instr(.ROUNDSS, ops3(.xmml,.xmml_m32,.imm8), preOp3(._66, 0x0F,0x3A,0x0A), .RMI,.ZO, .{SSE4_1} ),
// RSQRTPS
instr(.RSQRTPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x52), .RM, .ZO, .{SSE} ),
// RSQRTSS
instr(.RSQRTSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x52), .RM, .ZO, .{SSE} ),
// SHUFPD
instr(.SHUFPD, ops3(.xmml,.xmml_m128,.imm8), preOp2(._66, 0x0F, 0xC6), .RMI,.ZO, .{SSE2} ),
// SHUFPS
instr(.SHUFPS, ops3(.xmml,.xmml_m128,.imm8), preOp2(._NP, 0x0F, 0xC6), .RMI,.ZO, .{SSE} ),
// SQRTPD
instr(.SQRTPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x51), .RM, .ZO, .{SSE2} ),
// SQRTPS
instr(.SQRTPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x51), .RM, .ZO, .{SSE} ),
// SQRTSD
instr(.SQRTSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x51), .RM, .ZO, .{SSE2} ),
// SQRTSS
instr(.SQRTSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x51), .RM, .ZO, .{SSE} ),
// SUBPD
instr(.SUBPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x5C), .RM, .ZO, .{SSE2} ),
// SUBPS
instr(.SUBPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x5C), .RM, .ZO, .{SSE} ),
// SUBSD
instr(.SUBSD, ops2(.xmml, .xmml_m64), preOp2(._F2, 0x0F, 0x5C), .RM, .ZO, .{SSE2} ),
// SUBSS
instr(.SUBSS, ops2(.xmml, .xmml_m32), preOp2(._F3, 0x0F, 0x5C), .RM, .ZO, .{SSE} ),
// UCOMISD
instr(.UCOMISD, ops2(.xmml, .xmml_m64), preOp2(._66, 0x0F, 0x2E), .RM, .ZO, .{SSE2} ),
// UCOMISS
instr(.UCOMISS, ops2(.xmml, .xmml_m32), preOp2(._NP, 0x0F, 0x2E), .RM, .ZO, .{SSE} ),
// UNPCKHPD
instr(.UNPCKHPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x15), .RM, .ZO, .{SSE2} ),
// UNPCKHPS
instr(.UNPCKHPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x15), .RM, .ZO, .{SSE} ),
// UNPCKLPD
instr(.UNPCKLPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x14), .RM, .ZO, .{SSE2} ),
// UNPCKLPS
instr(.UNPCKLPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x14), .RM, .ZO, .{SSE} ),
// XORPD
instr(.XORPD, ops2(.xmml, .xmml_m128), preOp2(._66, 0x0F, 0x57), .RM, .ZO, .{SSE2} ),
// XORPS
instr(.XORPS, ops2(.xmml, .xmml_m128), preOp2(._NP, 0x0F, 0x57), .RM, .ZO, .{SSE} ),
//
// 3DNow!
//
// FEMMS
instr(.FEMMS, ops0(), Op2(0x0F, 0x0E), .RM, .ZO, .{cpu._3DNOW} ),
// PAVGUSB
instr(.PAVGUSB, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xBF), .RM, .ZO, .{cpu._3DNOW} ),
// PF2ID
instr(.PF2ID, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x1D), .RM, .ZO, .{cpu._3DNOW} ),
// PFACC
instr(.PFACC, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xAE), .RM, .ZO, .{cpu._3DNOW} ),
// PFADD
instr(.PFADD, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x9E), .RM, .ZO, .{cpu._3DNOW} ),
// PFCMPEQ
instr(.PFCMPEQ, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xB0), .RM, .ZO, .{cpu._3DNOW} ),
// PFCMPGE
instr(.PFCMPGE, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x90), .RM, .ZO, .{cpu._3DNOW} ),
// PFCMPGT
instr(.PFCMPGT, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xA0), .RM, .ZO, .{cpu._3DNOW} ),
// PFMAX
instr(.PFMAX, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xA4), .RM, .ZO, .{cpu._3DNOW} ),
// PFMIN
instr(.PFMIN, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x94), .RM, .ZO, .{cpu._3DNOW} ),
// PFMUL
instr(.PFMUL, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xB4), .RM, .ZO, .{cpu._3DNOW} ),
// PFRCP
instr(.PFRCP, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x96), .RM, .ZO, .{cpu._3DNOW} ),
// PFRCPIT1
instr(.PFRCPIT1, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xA6), .RM, .ZO, .{cpu._3DNOW} ),
// PFRCPIT2
instr(.PFRCPIT2, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xB6), .RM, .ZO, .{cpu._3DNOW} ),
// PFRSQIT1
instr(.PFRSQIT1, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xA7), .RM, .ZO, .{cpu._3DNOW} ),
// PFRSQRT
instr(.PFRSQRT, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x97), .RM, .ZO, .{cpu._3DNOW} ),
// PFSUB
instr(.PFSUB, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x9A), .RM, .ZO, .{cpu._3DNOW} ),
// PFSUBR
instr(.PFSUBR, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xAA), .RM, .ZO, .{cpu._3DNOW} ),
// PI2FD
instr(.PI2FD, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x0D), .RM, .ZO, .{cpu._3DNOW} ),
// PMULHRW
instr(.PMULHRW, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x0C), .RM, .ZO, .{cpu._3DNOW} ),
instr(.PMULHRW, ops2(.mm, .mm_m64), Op2(0x0F, 0x59), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PREFETCH
// see above
// PREFETCHW
// see above
// PFRCPV
instr(.PFRCPV, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x87), .RM, .ZO, .{cpu._3DNOW, cpu.Cyrix} ),
// PFRSQRTV
instr(.PFRSQRTV, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x86), .RM, .ZO, .{cpu._3DNOW, cpu.Cyrix} ),
//
// 3DNow! Extensions
//
// PF2IW
instr(.PF2IW, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x1C), .RM, .ZO, .{cpu._3DNOWEXT} ),
// PFNACC
instr(.PFNACC, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x8A), .RM, .ZO, .{cpu._3DNOWEXT} ),
// PFPNACC
instr(.PFPNACC, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x8E), .RM, .ZO, .{cpu._3DNOWEXT} ),
// PI2FW
instr(.PI2FW, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0x0C), .RM, .ZO, .{cpu._3DNOWEXT} ),
// PSWAPD
instr(.PSWAPD, ops2(.mm, .mm_m64), Op3DNow(0x0F, 0x0F, 0xBB), .RM, .ZO, .{cpu._3DNOWEXT} ),
//
// SSE4A
//
// EXTRQ
instr(.EXTRQ, ops3(.rm_xmml, .imm8, .imm8), preOp2r(._66, 0x0F, 0x78, 0), .MII, .ZO, .{SSE4A} ),
instr(.EXTRQ, ops2(.xmml, .rm_xmml), preOp2(._66, 0x0F, 0x79), .RM, .ZO, .{SSE4A} ),
// INSERTQ
instr(.INSERTQ, ops4(.xmml,.rm_xmml,.imm8,.imm8), preOp2r(._F2, 0x0F, 0x78, 0), .RMII,.ZO, .{SSE4A} ),
instr(.INSERTQ, ops2(.xmml, .rm_xmml), preOp2(._F2, 0x0F, 0x79), .RM, .ZO, .{SSE4A} ),
// MOVNTSD
instr(.MOVNTSD, ops2(.rm_mem64, .xmml), preOp2(._F2, 0x0F, 0x2B), .MR, .ZO, .{SSE4A} ),
// MOVNTSS
instr(.MOVNTSS, ops2(.rm_mem32, .xmml), preOp2(._F3, 0x0F, 0x2B), .MR, .ZO, .{SSE4A} ),
//
// Cyrix EMMI (Extended Multi-Media Instructions)
//
// PADDSIW
instr(.PADDSIW, ops2(.mm, .mm_m64), Op2(0x0F, 0x51), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PAVEB
instr(.PAVEB, ops2(.mm, .mm_m64), Op2(0x0F, 0x50), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PDISTIB
instr(.PDISTIB, ops2(.mm, .rm_mem64), Op2(0x0F, 0x54), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PMACHRIW
instr(.PMACHRIW, ops2(.mm, .rm_mem64), Op2(0x0F, 0x5E), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PMAGW
instr(.PMAGW, ops2(.mm, .mm_m64), Op2(0x0F, 0x52), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PMULHRW / PMULHRIW
// instr(.PMULHRW, ops2(.mm, .mm_m64), Op2(0x0F, 0x59), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ), // see above
instr(.PMULHRIW, ops2(.mm, .mm_m64), Op2(0x0F, 0x5D), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PMVZB / PMVNZB / PMVLZB / PMVGEZB
instr(.PMVZB, ops2(.mm, .rm_mem64), Op2(0x0F, 0x58), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
instr(.PMVNZB, ops2(.mm, .rm_mem64), Op2(0x0F, 0x5A), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
instr(.PMVLZB, ops2(.mm, .rm_mem64), Op2(0x0F, 0x5B), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
instr(.PMVGEZB, ops2(.mm, .rm_mem64), Op2(0x0F, 0x5C), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
// PSUBSIW
instr(.PSUBSIW, ops2(.mm, .mm_m64), Op2(0x0F, 0x55), .RM, .ZO, .{cpu.EMMI, cpu.Cyrix} ),
//
// SIMD vector instructions (AVX, AVX2, AVX512)
//
// VADDPD
vec(.VADDPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x58, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VADDPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x58, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VADDPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x58, full), .RVM, .{AVX512F} ),
// VADDPS
vec(.VADDPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x58, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VADDPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x58, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VADDPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x58, full), .RVM, .{AVX512F} ),
// VADDSD
vec(.VADDSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDSD, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x58, t1s), .RVM, .{AVX512F} ),
// VADDSS
vec(.VADDSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x58), .RVM, .{AVX} ),
vec(.VADDSS, ops3(.xmm_kz, .xmm, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x58, t1s), .RVM, .{AVX512F} ),
// VADDSUBPD
vec(.VADDSUBPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD0), .RVM, .{AVX} ),
vec(.VADDSUBPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD0), .RVM, .{AVX} ),
// VADDSUBPS
vec(.VADDSUBPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._F2,._0F,.WIG, 0xD0), .RVM, .{AVX} ),
vec(.VADDSUBPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._F2,._0F,.WIG, 0xD0), .RVM, .{AVX} ),
// VANDPD
vec(.VANDPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x54), .RVM, .{AVX} ),
vec(.VANDPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x54), .RVM, .{AVX} ),
vec(.VANDPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x54, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x54, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x54, full), .RVM, .{AVX512DQ} ),
// VANDPS
vec(.VANDPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x54), .RVM, .{AVX} ),
vec(.VANDPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x54), .RVM, .{AVX} ),
vec(.VANDPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x54, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x54, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x54, full), .RVM, .{AVX512DQ} ),
// VANDNPD
vec(.VANDNPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x55), .RVM, .{AVX} ),
vec(.VANDNPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x55), .RVM, .{AVX} ),
vec(.VANDNPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x55, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDNPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x55, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDNPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x55, full), .RVM, .{AVX512DQ} ),
// VANDNPS
vec(.VANDNPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x55), .RVM, .{AVX} ),
vec(.VANDNPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x55), .RVM, .{AVX} ),
vec(.VANDNPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x55, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDNPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x55, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VANDNPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x55, full), .RVM, .{AVX512DQ} ),
// VBLENDPS
vec(.VBLENDPD, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG,0x0D), .RVMI,.{AVX} ),
vec(.VBLENDPD, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG,0x0D), .RVMI,.{AVX} ),
// VBLENDPS
vec(.VBLENDPS, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG,0x0C), .RVMI,.{AVX} ),
vec(.VBLENDPS, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG,0x0C), .RVMI,.{AVX} ),
// VBLENDVPD
vec(.VBLENDVPD, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0,0x4B), .RVMR,.{AVX} ),
vec(.VBLENDVPD, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0,0x4B), .RVMR,.{AVX} ),
// VBLENDVPS
vec(.VBLENDVPS, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0,0x4A), .RVMR,.{AVX} ),
vec(.VBLENDVPS, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0,0x4A), .RVMR,.{AVX} ),
// VCMPPD
vec(.VCMPPD, ops4(.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPPD, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPPD, ops4(.reg_k_k,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F,.W1, 0xC2, full), .RVMI, .{AVX512VL, AVX512F} ),
vec(.VCMPPD, ops4(.reg_k_k,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F,.W1, 0xC2, full), .RVMI, .{AVX512VL, AVX512F} ),
vec(.VCMPPD, ops4(.reg_k_k,.zmm,.zmm_m512_m64bcst_sae,.imm8), evex(.L512,._66,._0F,.W1, 0xC2, full), .RVMI, .{AVX512F} ),
// VCMPPS
vec(.VCMPPS, ops4(.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._NP,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPPS, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._NP,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPPS, ops4(.reg_k_k,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._NP,._0F,.W0, 0xC2, full), .RVMI, .{AVX512VL, AVX512F} ),
vec(.VCMPPS, ops4(.reg_k_k,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._NP,._0F,.W0, 0xC2, full), .RVMI, .{AVX512VL, AVX512F} ),
vec(.VCMPPS, ops4(.reg_k_k,.zmm,.zmm_m512_m32bcst_sae,.imm8), evex(.L512,._NP,._0F,.W0, 0xC2, full), .RVMI, .{AVX512F} ),
// VCMPSD
vec(.VCMPSD, ops4(.xmml,.xmml,.xmml_m64,.imm8), vex(.LIG,._F2,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPSD, ops4(.reg_k_k,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._F2,._0F,.W1, 0xC2, t1s), .RVMI, .{AVX512VL, AVX512F} ),
// VCMPSS
vec(.VCMPSS, ops4(.xmml,.xmml,.xmml_m32,.imm8), vex(.LIG,._F3,._0F,.WIG, 0xC2), .RVMI, .{AVX} ),
vec(.VCMPSS, ops4(.reg_k_k,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._F3,._0F,.W0, 0xC2, t1s), .RVMI, .{AVX512VL, AVX512F} ),
// VCOMISD
vec(.VCOMISD, ops2(.xmml, .xmml_m64), vex(.LIG,._66,._0F,.WIG, 0x2F), .vRM, .{AVX} ),
vec(.VCOMISD, ops2(.xmm, .xmm_m64_sae), evex(.LIG,._66,._0F,.W1, 0x2F, t1s), .vRM, .{AVX512F} ),
// VCOMISS
vec(.VCOMISS, ops2(.xmml, .xmml_m32), vex(.LIG,._NP,._0F,.WIG, 0x2F), .vRM, .{AVX} ),
vec(.VCOMISS, ops2(.xmm, .xmm_m32_sae), evex(.LIG,._NP,._0F,.W0, 0x2F, t1s), .vRM, .{AVX512F} ),
// VCVTDQ2PD
vec(.VCVTDQ2PD, ops2(.xmml, .xmml_m64), vex(.L128,._F3,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTDQ2PD, ops2(.ymml, .xmml_m128), vex(.L256,._F3,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTDQ2PD, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._F3,._0F,.W0, 0xE6, half), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTDQ2PD, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._F3,._0F,.W0, 0xE6, half), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTDQ2PD, ops2(.zmm_kz, .ymm_m256_m32bcst), evex(.L512,._F3,._0F,.W0, 0xE6, half), .vRM, .{AVX512F} ),
// VCVTDQ2PS
vec(.VCVTDQ2PS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTDQ2PS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTDQ2PS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTDQ2PS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTDQ2PS, ops2(.zmm_kz, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x5B, full), .vRM, .{AVX512F} ),
// VCVTPD2DQ
vec(.VCVTPD2DQ, ops2(.xmml, .xmml_m128), vex(.L128,._F2,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTPD2DQ, ops2(.xmml, .ymml_m256), vex(.L256,._F2,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTPD2DQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._F2,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2DQ, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._F2,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2DQ, ops2(.ymm_kz, .zmm_m512_m64bcst_er), evex(.L512,._F2,._0F,.W1, 0xE6, full), .vRM, .{AVX512F} ),
// VCVTPD2PS
vec(.VCVTPD2PS, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5A), .vRM, .{AVX} ),
vec(.VCVTPD2PS, ops2(.xmml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5A), .vRM, .{AVX} ),
vec(.VCVTPD2PS, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x5A, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2PS, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x5A, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2PS, ops2(.ymm_kz, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x5A, full), .vRM, .{AVX512F} ),
// VCVTPS2DQ
vec(.VCVTPS2DQ, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTPS2DQ, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTPS2DQ, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPS2DQ, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPS2DQ, ops2(.zmm_kz, .zmm_m512_m32bcst_er), evex(.L512,._66,._0F,.W0, 0x5B, full), .vRM, .{AVX512F} ),
// VCVTPS2PD
vec(.VCVTPS2PD, ops2(.xmml, .xmml_m64), vex(.L128,._NP,._0F,.WIG, 0x5A), .vRM, .{AVX} ),
vec(.VCVTPS2PD, ops2(.ymml, .xmml_m128), vex(.L256,._NP,._0F,.WIG, 0x5A), .vRM, .{AVX} ),
vec(.VCVTPS2PD, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5A, half), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPS2PD, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5A, half), .vRM, .{AVX512VL} ),
vec(.VCVTPS2PD, ops2(.zmm_kz, .ymm_m256_m32bcst_sae), evex(.L512,._NP,._0F,.W0, 0x5A, half), .vRM, .{AVX512F} ),
// VCVTSD2SI
vec(.VCVTSD2SI, ops2(.reg32, .xmml_m64), vex(.LIG,._F2,._0F,.W0, 0x2D), .vRM, .{AVX} ),
vec(.VCVTSD2SI, ops2(.reg64, .xmml_m64), vex(.LIG,._F2,._0F,.W1, 0x2D), .vRM, .{AVX} ),
vec(.VCVTSD2SI, ops2(.reg32, .xmm_m64_er), evex(.LIG,._F2,._0F,.W0, 0x2D, t1f), .vRM, .{AVX512F} ),
vec(.VCVTSD2SI, ops2(.reg64, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x2D, t1f), .vRM, .{AVX512F} ),
// VCVTSD2SS
vec(.VCVTSD2SS, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x5A), .RVM, .{AVX} ),
vec(.VCVTSD2SS, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x5A, t1s), .RVM, .{AVX512F} ),
// VCVTSI2SD
vec(.VCVTSI2SD, ops3(.xmml, .xmml, .rm32), vex(.LIG,._F2,._0F,.W0, 0x2A), .RVM, .{AVX} ),
vec(.VCVTSI2SD, ops3(.xmml, .xmml, .rm64), vex(.LIG,._F2,._0F,.W1, 0x2A), .RVM, .{AVX, No32} ),
vec(.VCVTSI2SD, ops3(.xmm, .xmm, .rm32), evex(.LIG,._F2,._0F,.W0, 0x2A, t1s), .RVM, .{AVX512F} ),
vec(.VCVTSI2SD, ops3(.xmm, .xmm, .rm64_er), evex(.LIG,._F2,._0F,.W1, 0x2A, t1s), .RVM, .{AVX512F, No32} ),
// VCVTSI2SS
vec(.VCVTSI2SS, ops3(.xmml, .xmml, .rm32), vex(.LIG,._F3,._0F,.W0, 0x2A), .RVM, .{AVX} ),
vec(.VCVTSI2SS, ops3(.xmml, .xmml, .rm64), vex(.LIG,._F3,._0F,.W1, 0x2A), .RVM, .{AVX, No32} ),
vec(.VCVTSI2SS, ops3(.xmm, .xmm, .rm32_er), evex(.LIG,._F3,._0F,.W0, 0x2A, t1s), .RVM, .{AVX512F} ),
vec(.VCVTSI2SS, ops3(.xmm, .xmm, .rm64_er), evex(.LIG,._F3,._0F,.W1, 0x2A, t1s), .RVM, .{AVX512F, No32} ),
// VCVTSS2SD
vec(.VCVTSS2SD, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x5A), .RVM, .{AVX} ),
vec(.VCVTSS2SD, ops3(.xmm_kz, .xmm, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W0, 0x5A, t1s), .RVM, .{AVX512F} ),
// VCVTSS2SI
vec(.VCVTSS2SI, ops2(.reg32, .xmml_m32), vex(.LIG,._F3,._0F,.W0, 0x2D), .vRM, .{AVX} ),
vec(.VCVTSS2SI, ops2(.reg64, .xmml_m32), vex(.LIG,._F3,._0F,.W1, 0x2D), .vRM, .{AVX, No32} ),
vec(.VCVTSS2SI, ops2(.reg32, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x2D, t1f), .vRM, .{AVX512F} ),
vec(.VCVTSS2SI, ops2(.reg64, .xmm_m32_er), evex(.LIG,._F3,._0F,.W1, 0x2D, t1f), .vRM, .{AVX512F, No32} ),
// VCVTTPD2DQ
vec(.VCVTTPD2DQ, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTTPD2DQ, ops2(.xmml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE6), .vRM, .{AVX} ),
vec(.VCVTTPD2DQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPD2DQ, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPD2DQ, ops2(.ymm_kz, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F,.W1, 0xE6, full), .vRM, .{AVX512F} ),
// VCVTTPS2DQ
vec(.VCVTTPS2DQ, ops2(.xmml, .xmml_m128), vex(.L128,._F3,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTTPS2DQ, ops2(.ymml, .ymml_m256), vex(.L256,._F3,._0F,.WIG, 0x5B), .vRM, .{AVX} ),
vec(.VCVTTPS2DQ, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._F3,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPS2DQ, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._F3,._0F,.W0, 0x5B, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPS2DQ, ops2(.zmm_kz, .zmm_m512_m32bcst_sae), evex(.L512,._F3,._0F,.W0, 0x5B, full), .vRM, .{AVX512F} ),
// VCVTTSD2SI
vec(.VCVTTSD2SI, ops2(.reg32, .xmml_m64), vex(.LIG,._F2,._0F,.W0, 0x2C), .vRM, .{AVX} ),
vec(.VCVTTSD2SI, ops2(.reg64, .xmml_m64), vex(.LIG,._F2,._0F,.W1, 0x2C), .vRM, .{AVX, No32} ),
vec(.VCVTTSD2SI, ops2(.reg32, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W0, 0x2C, t1f), .vRM, .{AVX512F} ),
vec(.VCVTTSD2SI, ops2(.reg64, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W1, 0x2C, t1f), .vRM, .{AVX512F, No32} ),
// VCVTTSS2SI
vec(.VCVTTSS2SI, ops2(.reg32, .xmml_m32), vex(.LIG,._F3,._0F,.W0, 0x2C), .vRM, .{AVX} ),
vec(.VCVTTSS2SI, ops2(.reg64, .xmml_m32), vex(.LIG,._F3,._0F,.W1, 0x2C), .vRM, .{AVX, No32} ),
vec(.VCVTTSS2SI, ops2(.reg32, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W0, 0x2C, t1f), .vRM, .{AVX512F} ),
vec(.VCVTTSS2SI, ops2(.reg64, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W1, 0x2C, t1f), .vRM, .{AVX512F, No32} ),
// VDIVPD
vec(.VDIVPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x5E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VDIVPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x5E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VDIVPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x5E, full), .RVM, .{AVX512F} ),
// VDIVPS
vec(.VDIVPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VDIVPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VDIVPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x5E, full), .RVM, .{AVX512F} ),
// VDIVSD
vec(.VDIVSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVSD, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x5E, t1s), .RVM, .{AVX512F} ),
// VDIVSS
vec(.VDIVSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x5E), .RVM, .{AVX} ),
vec(.VDIVSS, ops3(.xmm_kz, .xmm, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x5E, t1s), .RVM, .{AVX512F} ),
// VDPPD
vec(.VDPPD, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x41), .RVMI,.{AVX} ),
// VDPPS
vec(.VDPPS, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x40), .RVMI,.{AVX} ),
vec(.VDPPS, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG, 0x40), .RVMI,.{AVX} ),
// VEXTRACTPS
vec(.VEXTRACTPS, ops3(.rm32, .xmml, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x17), .vMRI,.{AVX} ),
vec(.VEXTRACTPS, ops3(.reg64, .xmml, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x17), .vMRI,.{AVX, No32} ),
vec(.VEXTRACTPS, ops3(.rm32, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x17, t1s), .vMRI,.{AVX512F} ),
vec(.VEXTRACTPS, ops3(.reg64, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x17, t1s), .vMRI,.{AVX512F, No32} ),
// VGF2P8AFFINEINVQB
vec(.VGF2P8AFFINEINVQB, ops4(.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W1, 0xCF), .RVMI,.{AVX, GFNI} ),
vec(.VGF2P8AFFINEINVQB, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0xCF), .RVMI,.{AVX, GFNI} ),
vec(.VGF2P8AFFINEINVQB, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0xCF, full), .RVMI,.{AVX512VL, GFNI} ),
vec(.VGF2P8AFFINEINVQB, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0xCF, full), .RVMI,.{AVX512VL, GFNI} ),
vec(.VGF2P8AFFINEINVQB, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0xCF, full), .RVMI,.{AVX512F, GFNI} ),
// VGF2P8AFFINEQB
vec(.VGF2P8AFFINEQB, ops4(.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W1, 0xCE), .RVMI,.{AVX, GFNI} ),
vec(.VGF2P8AFFINEQB, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0xCE), .RVMI,.{AVX, GFNI} ),
vec(.VGF2P8AFFINEQB, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0xCE, full), .RVMI,.{AVX512VL, GFNI} ),
vec(.VGF2P8AFFINEQB, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0xCE, full), .RVMI,.{AVX512VL, GFNI} ),
vec(.VGF2P8AFFINEQB, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0xCE, full), .RVMI,.{AVX512F, GFNI} ),
// VGF2P8MULB
vec(.VGF2P8MULB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xCF), .RVM, .{AVX, GFNI} ),
vec(.VGF2P8MULB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xCF), .RVM, .{AVX, GFNI} ),
vec(.VGF2P8MULB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0xCF, fmem), .RVM, .{AVX512VL, GFNI} ),
vec(.VGF2P8MULB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0xCF, fmem), .RVM, .{AVX512VL, GFNI} ),
vec(.VGF2P8MULB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0xCF, fmem), .RVM, .{AVX512F, GFNI} ),
// VHADDPD
vec(.VHADDPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x7C), .RVM, .{AVX} ),
vec(.VHADDPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x7C), .RVM, .{AVX} ),
// VHADDPS
vec(.VHADDPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._F2,._0F,.WIG, 0x7C), .RVM, .{AVX} ),
vec(.VHADDPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._F2,._0F,.WIG, 0x7C), .RVM, .{AVX} ),
// VHSUBPD
vec(.VHSUBPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x7D), .RVM, .{AVX} ),
vec(.VHSUBPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x7D), .RVM, .{AVX} ),
// VHSUBPS
vec(.VHSUBPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._F2,._0F,.WIG, 0x7D), .RVM, .{AVX} ),
vec(.VHSUBPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._F2,._0F,.WIG, 0x7D), .RVM, .{AVX} ),
// vecERTPS
vec(.VINSERTPS, ops4(.xmml, .xmml, .xmml_m32, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x21), .RVMI,.{AVX} ),
vec(.VINSERTPS, ops4(.xmm, .xmm, .xmm_m32, .imm8), evex(.L128,._66,._0F3A,.W0, 0x21, t1s), .RVMI,.{AVX512F} ),
// LDDQU
vec(.VLDDQU, ops2(.xmml, .rm_mem128), vex(.L128,._F2,._0F,.WIG, 0xF0), .vRM, .{AVX} ),
vec(.VLDDQU, ops2(.ymml, .rm_mem256), vex(.L256,._F2,._0F,.WIG, 0xF0), .vRM, .{AVX} ),
// VLDMXCSR
vec(.VLDMXCSR, ops1(.rm_mem32), vexr(.LZ,._NP,._0F,.WIG, 0xAE, 2), .vM, .{AVX} ),
// VMASKMOVDQU
vec(.VMASKMOVDQU,ops2(.xmml, .xmml), vex(.L128,._66,._0F,.WIG, 0xF7), .vRM, .{AVX} ),
// VMAXPD
vec(.VMAXPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x5F, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMAXPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x5F, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMAXPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F,.W1, 0x5F, full), .RVM, .{AVX512DQ} ),
// VMAXPS
vec(.VMAXPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5F, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMAXPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5F, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMAXPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_sae), evex(.L512,._NP,._0F,.W0, 0x5F, full), .RVM, .{AVX512DQ} ),
// VMAXSD
vec(.VMAXSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXSD, ops3(.xmm_kz, .xmm, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W1, 0x5F, t1s), .RVM, .{AVX512F} ),
// VMAXSS
vec(.VMAXSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x5F), .RVM, .{AVX} ),
vec(.VMAXSS, ops3(.xmm_kz, .xmm, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W0, 0x5F, t1s), .RVM, .{AVX512F} ),
// VMINPD
vec(.VMINPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x5D, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMINPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x5D, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMINPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F,.W1, 0x5D, full), .RVM, .{AVX512DQ} ),
// VMINPS
vec(.VMINPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5D, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMINPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5D, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VMINPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_sae), evex(.L512,._NP,._0F,.W0, 0x5D, full), .RVM, .{AVX512DQ} ),
// VMINSD
vec(.VMINSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINSD, ops3(.xmm_kz, .xmm, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W1, 0x5D, t1s), .RVM, .{AVX512F} ),
// VMINSS
vec(.VMINSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x5D), .RVM, .{AVX} ),
vec(.VMINSS, ops3(.xmm_kz, .xmm, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W0, 0x5D, t1s), .RVM, .{AVX512F} ),
// VMOVAPD
vec(.VMOVAPD, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x28), .vRM, .{AVX} ),
vec(.VMOVAPD, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x28), .vRM, .{AVX} ),
vec(.VMOVAPD, ops2(.xmml_m128, .xmml), vex(.L128,._66,._0F,.WIG, 0x29), .vMR, .{AVX} ),
vec(.VMOVAPD, ops2(.ymml_m256, .ymml), vex(.L256,._66,._0F,.WIG, 0x29), .vMR, .{AVX} ),
//
vec(.VMOVAPD, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F,.W1, 0x28, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVAPD, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F,.W1, 0x28, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVAPD, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F,.W1, 0x28, fmem), .vRM, .{AVX512F} ),
vec(.VMOVAPD, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F,.W1, 0x29, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVAPD, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F,.W1, 0x29, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVAPD, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F,.W1, 0x29, fmem), .vMR, .{AVX512F} ),
// VMOVAPS
vec(.VMOVAPS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x28), .vRM, .{AVX} ),
vec(.VMOVAPS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x28), .vRM, .{AVX} ),
vec(.VMOVAPS, ops2(.xmml_m128, .xmml), vex(.L128,._NP,._0F,.WIG, 0x29), .vMR, .{AVX} ),
vec(.VMOVAPS, ops2(.ymml_m256, .ymml), vex(.L256,._NP,._0F,.WIG, 0x29), .vMR, .{AVX} ),
//
vec(.VMOVAPS, ops2(.xmm_kz, .xmm_m128), evex(.L128,._NP,._0F,.W0, 0x28, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVAPS, ops2(.ymm_kz, .ymm_m256), evex(.L256,._NP,._0F,.W0, 0x28, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVAPS, ops2(.zmm_kz, .zmm_m512), evex(.L512,._NP,._0F,.W0, 0x28, fmem), .vRM, .{AVX512F} ),
vec(.VMOVAPS, ops2(.xmm_m128_kz, .xmm), evex(.L128,._NP,._0F,.W0, 0x29, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVAPS, ops2(.ymm_m256_kz, .ymm), evex(.L256,._NP,._0F,.W0, 0x29, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVAPS, ops2(.zmm_m512_kz, .zmm), evex(.L512,._NP,._0F,.W0, 0x29, fmem), .vMR, .{AVX512F} ),
// VMOVD
// xmm[0..15]
vec(.VMOVD, ops2(.xmml, .rm32), vex(.L128,._66,._0F,.W0, 0x6E), .vRM, .{AVX} ),
vec(.VMOVD, ops2(.rm32, .xmml), vex(.L128,._66,._0F,.W0, 0x7E), .vMR, .{AVX} ),
vec(.VMOVD, ops2(.xmml, .rm64), vex(.L128,._66,._0F,.W1, 0x6E), .vRM, .{AVX, No32} ),
vec(.VMOVD, ops2(.rm64, .xmml), vex(.L128,._66,._0F,.W1, 0x7E), .vMR, .{AVX, No32} ),
// xmm[0..31]
vec(.VMOVD, ops2(.xmm, .rm32), evex(.L128,._66,._0F,.W0, 0x6E, t1s), .vRM, .{AVX512F} ),
vec(.VMOVD, ops2(.rm32, .xmm), evex(.L128,._66,._0F,.W0, 0x7E, t1s), .vMR, .{AVX512F} ),
vec(.VMOVD, ops2(.xmm, .rm64), evex(.L128,._66,._0F,.W1, 0x6E, t1s), .vRM, .{AVX512F, No32} ),
vec(.VMOVD, ops2(.rm64, .xmm), evex(.L128,._66,._0F,.W1, 0x7E, t1s), .vMR, .{AVX512F, No32} ),
// VMOVQ
// xmm[0..15]
vec(.VMOVQ, ops2(.xmml, .xmml_m64), vex(.L128,._F3,._0F,.WIG,0x7E), .vRM, .{AVX} ),
vec(.VMOVQ, ops2(.xmml_m64, .xmml), vex(.L128,._66,._0F,.WIG,0xD6), .vMR, .{AVX} ),
vec(.VMOVQ, ops2(.xmml, .rm64), vex(.L128,._66,._0F,.W1, 0x6E), .vRM, .{AVX, No32} ),
vec(.VMOVQ, ops2(.rm64, .xmml), vex(.L128,._66,._0F,.W1, 0x7E), .vMR, .{AVX, No32} ),
// xmm[0..31]
vec(.VMOVQ, ops2(.xmm, .xmm_m64), evex(.L128,._F3,._0F,.W1, 0x7E, t1s), .vRM, .{AVX512F} ),
vec(.VMOVQ, ops2(.xmm_m64, .xmm), evex(.L128,._66,._0F,.W1, 0xD6, t1s), .vMR, .{AVX512F} ),
vec(.VMOVQ, ops2(.xmm, .rm64), evex(.L128,._66,._0F,.W1, 0x6E, t1s), .vRM, .{AVX512F, No32} ),
vec(.VMOVQ, ops2(.rm64, .xmm), evex(.L128,._66,._0F,.W1, 0x7E, t1s), .vMR, .{AVX512F, No32} ),
// VMOVDDUP
vec(.VMOVDDUP, ops2(.xmml, .xmml_m64), vex(.L128,._F2,._0F,.WIG, 0x12), .vRM, .{AVX} ),
vec(.VMOVDDUP, ops2(.ymml, .ymml_m256), vex(.L256,._F2,._0F,.WIG, 0x12), .vRM, .{AVX} ),
vec(.VMOVDDUP, ops2(.xmm_kz, .xmm_m64), evex(.L128,._F2,._0F,.W1, 0x12, dup), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDDUP, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F2,._0F,.W1, 0x12, dup), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDDUP, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F2,._0F,.W1, 0x12, dup), .vRM, .{AVX512F} ),
// VMOVDQA / VMOVDQA32 / VMOVDQA64
vec(.VMOVDQA, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x6F), .vRM, .{AVX} ),
vec(.VMOVDQA, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x6F), .vRM, .{AVX} ),
vec(.VMOVDQA, ops2(.xmml_m128, .xmml), vex(.L128,._66,._0F,.WIG, 0x7F), .vMR, .{AVX} ),
vec(.VMOVDQA, ops2(.ymml_m256, .ymml), vex(.L256,._66,._0F,.WIG, 0x7F), .vMR, .{AVX} ),
// VMOVDQA32
vec(.VMOVDQA32, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA32, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA32, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512F} ),
vec(.VMOVDQA32, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA32, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA32, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512F} ),
// VMOVDQA64
vec(.VMOVDQA64, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA64, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA64, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512F} ),
vec(.VMOVDQA64, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA64, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQA64, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512F} ),
// VMOVDQU / VMOVDQU8 / VMOVDQU16 / VMOVDQU32 / VMOVDQU64
vec(.VMOVDQU, ops2(.xmml, .xmml_m128), vex(.L128,._F3,._0F,.WIG, 0x6F), .vRM, .{AVX} ),
vec(.VMOVDQU, ops2(.ymml, .ymml_m256), vex(.L256,._F3,._0F,.WIG, 0x6F), .vRM, .{AVX} ),
vec(.VMOVDQU, ops2(.xmml_m128, .xmml), vex(.L128,._F3,._0F,.WIG, 0x7F), .vMR, .{AVX} ),
vec(.VMOVDQU, ops2(.ymml_m256, .ymml), vex(.L256,._F3,._0F,.WIG, 0x7F), .vMR, .{AVX} ),
// VMOVDQU8
vec(.VMOVDQU8, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F2,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU8, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F2,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU8, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F2,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512BW} ),
vec(.VMOVDQU8, ops2(.xmm_m128_kz, .xmm), evex(.L128,._F2,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU8, ops2(.ymm_m256_kz, .ymm), evex(.L256,._F2,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU8, ops2(.zmm_m512_kz, .zmm), evex(.L512,._F2,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512BW} ),
// VMOVDQU16
vec(.VMOVDQU16, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F2,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU16, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F2,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU16, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F2,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512BW} ),
vec(.VMOVDQU16, ops2(.xmm_m128_kz, .xmm), evex(.L128,._F2,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU16, ops2(.ymm_m256_kz, .ymm), evex(.L256,._F2,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VMOVDQU16, ops2(.zmm_m512_kz, .zmm), evex(.L512,._F2,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512BW} ),
// VMOVDQU32
vec(.VMOVDQU32, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F3,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU32, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F3,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU32, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F3,._0F,.W0, 0x6F, fmem), .vRM, .{AVX512F} ),
vec(.VMOVDQU32, ops2(.xmm_m128_kz, .xmm), evex(.L128,._F3,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU32, ops2(.ymm_m256_kz, .ymm), evex(.L256,._F3,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU32, ops2(.zmm_m512_kz, .zmm), evex(.L512,._F3,._0F,.W0, 0x7F, fmem), .vMR, .{AVX512F} ),
// VMOVDQU64
vec(.VMOVDQU64, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F3,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU64, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F3,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU64, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F3,._0F,.W1, 0x6F, fmem), .vRM, .{AVX512F} ),
vec(.VMOVDQU64, ops2(.xmm_m128_kz, .xmm), evex(.L128,._F3,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU64, ops2(.ymm_m256_kz, .ymm), evex(.L256,._F3,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVDQU64, ops2(.zmm_m512_kz, .zmm), evex(.L512,._F3,._0F,.W1, 0x7F, fmem), .vMR, .{AVX512F} ),
// VMOVHLPS
vec(.VMOVHLPS, ops3(.xmml, .xmml, .xmml), vex(.L128,._NP,._0F,.WIG, 0x12), .RVM, .{AVX} ),
vec(.VMOVHLPS, ops3(.xmm, .xmm, .xmm), evex(.L128,._NP,._0F,.W0, 0x12, nomem), .RVM, .{AVX512F} ),
// VMOVHPD
vec(.VMOVHPD, ops3(.xmml, .xmml, .rm_mem64), vex(.L128,._66,._0F,.WIG, 0x16), .RVM, .{AVX} ),
vec(.VMOVHPD, ops2(.rm_mem64, .xmml), vex(.L128,._66,._0F,.WIG, 0x17), .vMR, .{AVX} ),
vec(.VMOVHPD, ops3(.xmm, .xmm, .rm_mem64), evex(.L128,._66,._0F,.W1, 0x16, t1s), .RVM, .{AVX512F} ),
vec(.VMOVHPD, ops2(.rm_mem64, .xmm), evex(.L128,._66,._0F,.W1, 0x17, t1s), .vMR, .{AVX512F} ),
// VMOVHPS
vec(.VMOVHPS, ops3(.xmml, .xmml, .rm_mem64), vex(.L128,._NP,._0F,.WIG, 0x16), .RVM, .{AVX} ),
vec(.VMOVHPS, ops2(.rm_mem64, .xmml), vex(.L128,._NP,._0F,.WIG, 0x17), .vMR, .{AVX} ),
vec(.VMOVHPS, ops3(.xmm, .xmm, .rm_mem64), evex(.L128,._NP,._0F,.W0, 0x16, tup2), .RVM, .{AVX512F} ),
vec(.VMOVHPS, ops2(.rm_mem64, .xmm), evex(.L128,._NP,._0F,.W0, 0x17, tup2), .vMR, .{AVX512F} ),
// VMOVLHPS
vec(.VMOVLHPS, ops3(.xmml, .xmml, .xmml), vex(.L128,._NP,._0F,.WIG, 0x16), .RVM, .{AVX} ),
vec(.VMOVLHPS, ops3(.xmm, .xmm, .xmm), evex(.L128,._NP,._0F,.W0, 0x16, nomem), .RVM, .{AVX512F} ),
// VMOVLPD
vec(.VMOVLPD, ops3(.xmml, .xmml, .rm_mem64), vex(.L128,._66,._0F,.WIG, 0x12), .RVM, .{AVX} ),
vec(.VMOVLPD, ops2(.rm_mem64, .xmml), vex(.L128,._66,._0F,.WIG, 0x13), .vMR, .{AVX} ),
vec(.VMOVLPD, ops3(.xmm, .xmm, .rm_mem64), evex(.L128,._66,._0F,.W1, 0x12, t1s), .RVM, .{AVX512F} ),
vec(.VMOVLPD, ops2(.rm_mem64, .xmm), evex(.L128,._66,._0F,.W1, 0x13, t1s), .vMR, .{AVX512F} ),
// VMOVLPS
vec(.VMOVLPS, ops3(.xmml, .xmml, .rm_mem64), vex(.L128,._NP,._0F,.WIG, 0x12), .RVM, .{AVX} ),
vec(.VMOVLPS, ops2(.rm_mem64, .xmml), vex(.L128,._NP,._0F,.WIG, 0x13), .vMR, .{AVX} ),
vec(.VMOVLPS, ops3(.xmm, .xmm, .rm_mem64), evex(.L128,._NP,._0F,.W0, 0x12, tup2), .RVM, .{AVX512F} ),
vec(.VMOVLPS, ops2(.rm_mem64, .xmm), evex(.L128,._NP,._0F,.W0, 0x13, tup2), .vMR, .{AVX512F} ),
// VMOVMSKPD
vec(.VMOVMSKPD, ops2(.reg32, .xmml), vex(.L128,._66,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPD, ops2(.reg64, .xmml), vex(.L128,._66,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPD, ops2(.reg32, .ymml), vex(.L256,._66,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPD, ops2(.reg64, .ymml), vex(.L256,._66,._0F,.WIG, 0x50), .vRM, .{AVX} ),
// VMOVMSKPS
vec(.VMOVMSKPS, ops2(.reg32, .xmml), vex(.L128,._NP,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPS, ops2(.reg64, .xmml), vex(.L128,._NP,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPS, ops2(.reg32, .ymml), vex(.L256,._NP,._0F,.WIG, 0x50), .vRM, .{AVX} ),
vec(.VMOVMSKPS, ops2(.reg64, .ymml), vex(.L256,._NP,._0F,.WIG, 0x50), .vRM, .{AVX} ),
// VMOVNTDQA
vec(.VMOVNTDQA, ops2(.xmml, .rm_mem128), vex(.L128,._66,._0F38,.WIG, 0x2A), .vRM, .{AVX} ),
vec(.VMOVNTDQA, ops2(.ymml, .rm_mem256), vex(.L256,._66,._0F38,.WIG, 0x2A), .vRM, .{AVX2} ),
vec(.VMOVNTDQA, ops2(.xmm, .rm_mem128), evex(.L128,._66,._0F38,.W0, 0x2A, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVNTDQA, ops2(.ymm, .rm_mem256), evex(.L256,._66,._0F38,.W0, 0x2A, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVNTDQA, ops2(.zmm, .rm_mem512), evex(.L512,._66,._0F38,.W0, 0x2A, fmem), .vRM, .{AVX512F} ),
// VMOVNTDQ
vec(.VMOVNTDQ, ops2(.rm_mem128, .xmml), vex(.L128,._66,._0F,.WIG, 0xE7), .vMR, .{AVX} ),
vec(.VMOVNTDQ, ops2(.rm_mem256, .ymml), vex(.L256,._66,._0F,.WIG, 0xE7), .vMR, .{AVX} ),
vec(.VMOVNTDQ, ops2(.rm_mem128, .xmm), evex(.L128,._66,._0F,.W0, 0xE7, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTDQ, ops2(.rm_mem256, .ymm), evex(.L256,._66,._0F,.W0, 0xE7, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTDQ, ops2(.rm_mem512, .zmm), evex(.L512,._66,._0F,.W0, 0xE7, fmem), .vMR, .{AVX512F} ),
// VMOVNTPD
vec(.VMOVNTPD, ops2(.rm_mem128, .xmml), vex(.L128,._66,._0F,.WIG, 0x2B), .vMR, .{AVX} ),
vec(.VMOVNTPD, ops2(.rm_mem256, .ymml), vex(.L256,._66,._0F,.WIG, 0x2B), .vMR, .{AVX} ),
vec(.VMOVNTPD, ops2(.rm_mem128, .xmm), evex(.L128,._66,._0F,.W1, 0x2B, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTPD, ops2(.rm_mem256, .ymm), evex(.L256,._66,._0F,.W1, 0x2B, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTPD, ops2(.rm_mem512, .zmm), evex(.L512,._66,._0F,.W1, 0x2B, fmem), .vMR, .{AVX512F} ),
// VMOVNTPS
vec(.VMOVNTPS, ops2(.rm_mem128, .xmml), vex(.L128,._NP,._0F,.WIG, 0x2B), .vMR, .{AVX} ),
vec(.VMOVNTPS, ops2(.rm_mem256, .ymml), vex(.L256,._NP,._0F,.WIG, 0x2B), .vMR, .{AVX} ),
vec(.VMOVNTPS, ops2(.rm_mem128, .xmm), evex(.L128,._NP,._0F,.W0, 0x2B, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTPS, ops2(.rm_mem256, .ymm), evex(.L256,._NP,._0F,.W0, 0x2B, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVNTPS, ops2(.rm_mem512, .zmm), evex(.L512,._NP,._0F,.W0, 0x2B, fmem), .vMR, .{AVX512F} ),
// VMOVSD
vec(.VMOVSD, ops3(.xmml, .xmml, .rm_xmml), vex(.LIG,._F2,._0F,.WIG, 0x10), .RVM, .{AVX} ),
vec(.VMOVSD, ops2(.xmml, .rm_mem64), vex(.LIG,._F2,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVSD, ops3(.rm_xmml, .xmml, .xmml), vex(.LIG,._F2,._0F,.WIG, 0x11), .MVR, .{AVX} ),
vec(.VMOVSD, ops2(.rm_mem64, .xmml), vex(.LIG,._F2,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVSD, ops3(.xmm_kz, .xmm, .rm_xmm), evex(.LIG,._F2,._0F,.W1, 0x10, nomem), .RVM, .{AVX512F} ),
vec(.VMOVSD, ops2(.xmm_kz, .rm_mem64), evex(.LIG,._F2,._0F,.W1, 0x10, t1s), .vRM, .{AVX512F} ),
vec(.VMOVSD, ops3(.rm_xmm_kz, .xmm, .xmm), evex(.LIG,._F2,._0F,.W1, 0x11, nomem), .MVR, .{AVX512F} ),
vec(.VMOVSD, ops2(.rm_mem64_kz, .xmm), evex(.LIG,._F2,._0F,.W1, 0x11, t1s), .vMR, .{AVX512F} ),
// VMOVSHDUP
vec(.VMOVSHDUP, ops2(.xmml, .xmml_m128), vex(.L128,._F3,._0F,.WIG, 0x16), .vRM, .{AVX} ),
vec(.VMOVSHDUP, ops2(.ymml, .ymml_m256), vex(.L256,._F3,._0F,.WIG, 0x16), .vRM, .{AVX} ),
vec(.VMOVSHDUP, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F3,._0F,.W0, 0x16, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVSHDUP, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F3,._0F,.W0, 0x16, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVSHDUP, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F3,._0F,.W0, 0x16, fmem), .vRM, .{AVX512F} ),
// VMOVSLDUP
vec(.VMOVSLDUP, ops2(.xmml, .xmml_m128), vex(.L128,._F3,._0F,.WIG, 0x12), .vRM, .{AVX} ),
vec(.VMOVSLDUP, ops2(.ymml, .ymml_m256), vex(.L256,._F3,._0F,.WIG, 0x12), .vRM, .{AVX} ),
vec(.VMOVSLDUP, ops2(.xmm_kz, .xmm_m128), evex(.L128,._F3,._0F,.W0, 0x12, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVSLDUP, ops2(.ymm_kz, .ymm_m256), evex(.L256,._F3,._0F,.W0, 0x12, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVSLDUP, ops2(.zmm_kz, .zmm_m512), evex(.L512,._F3,._0F,.W0, 0x12, fmem), .vRM, .{AVX512F} ),
// VMOVSS
vec(.VMOVSS, ops3(.xmml, .xmml, .rm_xmml), vex(.LIG,._F3,._0F,.WIG, 0x10), .RVM, .{AVX} ),
vec(.VMOVSS, ops2(.xmml, .rm_mem64), vex(.LIG,._F3,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVSS, ops3(.rm_xmml, .xmml, .xmml), vex(.LIG,._F3,._0F,.WIG, 0x11), .MVR, .{AVX} ),
vec(.VMOVSS, ops2(.rm_mem64, .xmml), vex(.LIG,._F3,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVSS, ops3(.xmm_kz, .xmm, .xmm), evex(.LIG,._F3,._0F,.W0, 0x10, nomem), .RVM, .{AVX512F} ),
vec(.VMOVSS, ops2(.xmm_kz, .rm_mem64), evex(.LIG,._F3,._0F,.W0, 0x10, t1s), .vRM, .{AVX512F} ),
vec(.VMOVSS, ops3(.rm_xmm_kz, .xmm, .xmm), evex(.LIG,._F3,._0F,.W0, 0x11, nomem), .MVR, .{AVX512F} ),
vec(.VMOVSS, ops2(.rm_mem64_kz, .xmm), evex(.LIG,._F3,._0F,.W0, 0x11, t1s), .vMR, .{AVX512F} ),
// VMOVUPD
vec(.VMOVUPD, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVUPD, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVUPD, ops2(.xmml_m128, .xmml), vex(.L128,._66,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVUPD, ops2(.ymml_m256, .ymml), vex(.L256,._66,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVUPD, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F,.W1, 0x10, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVUPD, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F,.W1, 0x10, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVUPD, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F,.W1, 0x10, fmem), .vRM, .{AVX512F} ),
vec(.VMOVUPD, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F,.W1, 0x11, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVUPD, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F,.W1, 0x11, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVUPD, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F,.W1, 0x11, fmem), .vMR, .{AVX512F} ),
// VMOVUPS
vec(.VMOVUPS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVUPS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x10), .vRM, .{AVX} ),
vec(.VMOVUPS, ops2(.xmml_m128, .xmml), vex(.L128,._NP,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVUPS, ops2(.ymml_m256, .ymml), vex(.L256,._NP,._0F,.WIG, 0x11), .vMR, .{AVX} ),
vec(.VMOVUPS, ops2(.xmm_kz, .xmm_m128), evex(.L128,._NP,._0F,.W0, 0x10, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVUPS, ops2(.ymm_kz, .ymm_m256), evex(.L256,._NP,._0F,.W0, 0x10, fmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VMOVUPS, ops2(.zmm_kz, .zmm_m512), evex(.L512,._NP,._0F,.W0, 0x10, fmem), .vRM, .{AVX512F} ),
vec(.VMOVUPS, ops2(.xmm_m128_kz, .xmm), evex(.L128,._NP,._0F,.W0, 0x11, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVUPS, ops2(.ymm_m256_kz, .ymm), evex(.L256,._NP,._0F,.W0, 0x11, fmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VMOVUPS, ops2(.zmm_m512_kz, .zmm), evex(.L512,._NP,._0F,.W0, 0x11, fmem), .vMR, .{AVX512F} ),
// VMPSADBW
vec(.VMPSADBW, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x42), .RVMI,.{AVX} ),
vec(.VMPSADBW, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG, 0x42), .RVMI,.{AVX2} ),
// VMULPD
vec(.VMULPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x59, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VMULPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x59, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VMULPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x59, full), .RVM, .{AVX512F} ),
// VMULPS
vec(.VMULPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x59, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VMULPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x59, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VMULPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x59, full), .RVM, .{AVX512F} ),
// VMULSD
vec(.VMULSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULSD, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x59, t1s), .RVM, .{AVX512F} ),
// VMULSS
vec(.VMULSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x59), .RVM, .{AVX} ),
vec(.VMULSS, ops3(.xmm_kz, .xmm, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x59, t1s), .RVM, .{AVX512F} ),
// VORPD
vec(.VORPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x56), .RVM, .{AVX} ),
vec(.VORPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x56), .RVM, .{AVX} ),
vec(.VORPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x56, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VORPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x56, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VORPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x56, full), .RVM, .{AVX512DQ} ),
// VORPS
vec(.VORPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x56), .RVM, .{AVX} ),
vec(.VORPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x56), .RVM, .{AVX} ),
vec(.VORPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x56, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VORPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x56, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VORPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x56, full), .RVM, .{AVX512DQ} ),
// VPABSB / VPABSW / VPABSD / VPABSQ
vec(.VPABSB, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x1C), .vRM, .{AVX} ),
vec(.VPABSB, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x1C), .vRM, .{AVX2} ),
vec(.VPABSB, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x1C, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPABSB, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x1C, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPABSB, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x1C, fmem), .vRM, .{AVX512BW} ),
// VPABSW
vec(.VPABSW, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x1D), .vRM, .{AVX} ),
vec(.VPABSW, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x1D), .vRM, .{AVX2} ),
vec(.VPABSW, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x1D, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPABSW, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x1D, fmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPABSW, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x1D, fmem), .vRM, .{AVX512BW} ),
// VPABSD
vec(.VPABSD, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x1E), .vRM, .{AVX} ),
vec(.VPABSD, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x1E), .vRM, .{AVX2} ),
vec(.VPABSD, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x1E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPABSD, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x1E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPABSD, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x1E, full), .vRM, .{AVX512F} ),
// VPABSQ
vec(.VPABSQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x1F, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPABSQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x1F, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPABSQ, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x1F, full), .vRM, .{AVX512F} ),
// VPACKSSWB / PACKSSDW
// VPACKSSWB
vec(.VPACKSSWB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG,0x63), .RVM, .{AVX} ),
vec(.VPACKSSWB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG,0x63), .RVM, .{AVX2} ),
vec(.VPACKSSWB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG,0x63, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKSSWB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG,0x63, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKSSWB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG,0x63, fmem), .RVM, .{AVX512BW} ),
// VPACKSSDW
vec(.VPACKSSDW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG,0x6B), .RVM, .{AVX} ),
vec(.VPACKSSDW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG,0x6B), .RVM, .{AVX2} ),
vec(.VPACKSSDW, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0x6B, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKSSDW, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0x6B, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKSSDW, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0x6B, full), .RVM, .{AVX512BW} ),
// VPACKUSWB
vec(.VPACKUSWB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG,0x67), .RVM, .{AVX} ),
vec(.VPACKUSWB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG,0x67), .RVM, .{AVX2} ),
vec(.VPACKUSWB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG,0x67, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKUSWB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG,0x67, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKUSWB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG,0x67, fmem), .RVM, .{AVX512BW} ),
// VPACKUSDW
vec(.VPACKUSDW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG,0x2B), .RVM, .{AVX} ),
vec(.VPACKUSDW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG,0x2B), .RVM, .{AVX2} ),
vec(.VPACKUSDW, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0,0x2B, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKUSDW, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0,0x2B, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPACKUSDW, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0,0x2B, full), .RVM, .{AVX512BW} ),
// VPADDB / PADDW / PADDD / PADDQ
// VPADDB
vec(.VPADDB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xFC), .RVM, .{AVX} ),
vec(.VPADDB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xFC), .RVM, .{AVX2} ),
vec(.VPADDB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xFC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xFC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xFC, fmem), .RVM, .{AVX512BW} ),
// VPADDW
vec(.VPADDW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xFD), .RVM, .{AVX} ),
vec(.VPADDW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xFD), .RVM, .{AVX2} ),
vec(.VPADDW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xFD, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xFD, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xFD, fmem), .RVM, .{AVX512BW} ),
// VPADDD
vec(.VPADDD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xFE), .RVM, .{AVX} ),
vec(.VPADDD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xFE), .RVM, .{AVX2} ),
vec(.VPADDD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xFE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPADDD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xFE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPADDD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xFE, full), .RVM, .{AVX512F} ),
// VPADDQ
vec(.VPADDQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD4), .RVM, .{AVX} ),
vec(.VPADDQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD4), .RVM, .{AVX2} ),
vec(.VPADDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xD4, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPADDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xD4, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPADDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xD4, full), .RVM, .{AVX512F} ),
// VPADDSB / PADDSW
vec(.VPADDSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xEC), .RVM, .{AVX} ),
vec(.VPADDSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xEC), .RVM, .{AVX2} ),
vec(.VPADDSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xEC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xEC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xEC, fmem), .RVM, .{AVX512BW} ),
//
vec(.VPADDSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xED), .RVM, .{AVX} ),
vec(.VPADDSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xED), .RVM, .{AVX2} ),
vec(.VPADDSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xED, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xED, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xED, fmem), .RVM, .{AVX512BW} ),
// VPADDUSB / PADDUSW
vec(.VPADDUSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDC), .RVM, .{AVX} ),
vec(.VPADDUSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDC), .RVM, .{AVX2} ),
vec(.VPADDUSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xDC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDUSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xDC, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDUSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xDC, fmem), .RVM, .{AVX512BW} ),
//
vec(.VPADDUSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDD), .RVM, .{AVX} ),
vec(.VPADDUSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDD), .RVM, .{AVX2} ),
vec(.VPADDUSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xDD, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDUSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xDD, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPADDUSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xDD, fmem), .RVM, .{AVX512BW} ),
// VPALIGNR
vec(.VPALIGNR, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x0F), .RVMI,.{AVX} ),
vec(.VPALIGNR, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG, 0x0F), .RVMI,.{AVX2} ),
vec(.VPALIGNR, ops4(.xmm_kz, .xmm, .xmm_m128, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x0F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPALIGNR, ops4(.ymm_kz, .ymm, .ymm_m256, .imm8), evex(.L256,._66,._0F3A,.WIG, 0x0F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPALIGNR, ops4(.zmm_kz, .zmm, .zmm_m512, .imm8), evex(.L512,._66,._0F3A,.WIG, 0x0F, fmem), .RVMI,.{AVX512BW} ),
// VPAND
vec(.VPAND, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDB), .RVM, .{AVX} ),
vec(.VPAND, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDB), .RVM, .{AVX2} ),
vec(.VPANDD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xDB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xDB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xDB, full), .RVM, .{AVX512F} ),
vec(.VPANDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xDB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xDB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xDB, full), .RVM, .{AVX512F} ),
// VPANDN
vec(.VPANDN, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDF), .RVM, .{AVX} ),
vec(.VPANDN, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDF), .RVM, .{AVX2} ),
vec(.VPANDND, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xDF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDND, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xDF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDND, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xDF, full), .RVM, .{AVX512F} ),
vec(.VPANDNQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xDF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDNQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xDF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPANDNQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xDF, full), .RVM, .{AVX512F} ),
// VPAVGB / VPAVGW
vec(.VPAVGB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE0), .RVM, .{AVX} ),
vec(.VPAVGB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE0), .RVM, .{AVX2} ),
vec(.VPAVGB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE0, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPAVGB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE0, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPAVGB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE0, fmem), .RVM, .{AVX512BW} ),
//
vec(.VPAVGW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE3), .RVM, .{AVX} ),
vec(.VPAVGW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE3), .RVM, .{AVX2} ),
vec(.VPAVGW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE3, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPAVGW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE3, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPAVGW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE3, fmem), .RVM, .{AVX512BW} ),
// VPBLENDVB
vec(.VPBLENDVB, ops4(.xmml, .xmml, .xmml_m128, .xmml), vex(.L128,._66,._0F3A,.W0,0x4C), .RVMR,.{AVX} ),
vec(.VPBLENDVB, ops4(.ymml, .ymml, .ymml_m256, .ymml), vex(.L256,._66,._0F3A,.W0,0x4C), .RVMR,.{AVX2} ),
// VPBLENDDW
vec(.VPBLENDW, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG,0x0E), .RVMI,.{AVX} ),
vec(.VPBLENDW, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG,0x0E), .RVMI,.{AVX2} ),
// VPCLMULQDQ
vec(.VPCLMULQDQ, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG,0x44), .RVMI,.{cpu.PCLMULQDQ, AVX} ),
vec(.VPCLMULQDQ, ops4(.ymml, .ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG,0x44), .RVMI,.{cpu.VPCLMULQDQ} ),
vec(.VPCLMULQDQ, ops4(.xmm, .xmm, .xmm_m128, .imm8), evex(.L128,._66,._0F3A,.WIG,0x44, fmem), .RVMI,.{cpu.VPCLMULQDQ, AVX512VL} ),
vec(.VPCLMULQDQ, ops4(.ymm, .ymm, .ymm_m256, .imm8), evex(.L256,._66,._0F3A,.WIG,0x44, fmem), .RVMI,.{cpu.VPCLMULQDQ, AVX512VL} ),
vec(.VPCLMULQDQ, ops4(.zmm, .zmm, .zmm_m512, .imm8), evex(.L512,._66,._0F3A,.WIG,0x44, fmem), .RVMI,.{cpu.VPCLMULQDQ, AVX512F} ),
// VPCMPEQB / VPCMPEQW / VPCMPEQD
vec(.VPCMPEQB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x74), .RVM, .{AVX} ),
vec(.VPCMPEQB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x74), .RVM, .{AVX2} ),
vec(.VPCMPEQB, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x74, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPEQB, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x74, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPEQB, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x74, fmem), .RVM, .{AVX512BW} ),
// VPCMPEQW
vec(.VPCMPEQW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x75), .RVM, .{AVX} ),
vec(.VPCMPEQW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x75), .RVM, .{AVX2} ),
vec(.VPCMPEQW, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x75, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPEQW, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x75, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPEQW, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x75, fmem), .RVM, .{AVX512BW} ),
// VPCMPEQD
vec(.VPCMPEQD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x76), .RVM, .{AVX} ),
vec(.VPCMPEQD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x76), .RVM, .{AVX2} ),
vec(.VPCMPEQD, ops3(.reg_k_k, .xmm, .xmm_m128_m32bcst),evex(.L128,._66,._0F,.W0, 0x76, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPEQD, ops3(.reg_k_k, .ymm, .ymm_m256_m32bcst),evex(.L256,._66,._0F,.W0, 0x76, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPEQD, ops3(.reg_k_k, .zmm, .zmm_m512_m32bcst),evex(.L512,._66,._0F,.W0, 0x76, full), .RVM, .{AVX512F} ),
// VPCMPEQQ
vec(.VPCMPEQQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x29), .RVM, .{AVX} ),
vec(.VPCMPEQQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x29), .RVM, .{AVX2} ),
vec(.VPCMPEQQ, ops3(.reg_k_k, .xmm, .xmm_m128_m64bcst),evex(.L128,._66,._0F38,.W1, 0x29, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPEQQ, ops3(.reg_k_k, .ymm, .ymm_m256_m64bcst),evex(.L256,._66,._0F38,.W1, 0x29, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPEQQ, ops3(.reg_k_k, .zmm, .zmm_m512_m64bcst),evex(.L512,._66,._0F38,.W1, 0x29, full), .RVM, .{AVX512F} ),
// VPCMPESTRI
vec(.VPCMPESTRI, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.WIG, 0x61), .vRMI,.{AVX} ),
// VPCMPESTRM
vec(.VPCMPESTRM, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.WIG, 0x60), .vRMI,.{AVX} ),
// VPCMPGTB / VPCMPGTW / VPCMPGTD
// VPCMPGTB
vec(.VPCMPGTB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x64), .RVM, .{AVX} ),
vec(.VPCMPGTB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x64), .RVM, .{AVX2} ),
vec(.VPCMPGTB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x64, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPGTB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x64, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPGTB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x64, fmem), .RVM, .{AVX512BW} ),
// VPCMPGTW
vec(.VPCMPGTW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x65), .RVM, .{AVX} ),
vec(.VPCMPGTW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x65), .RVM, .{AVX2} ),
vec(.VPCMPGTW, ops3(.reg_k_k,.xmm,.xmm_m128), evex(.L128,._66,._0F,.WIG, 0x65, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPGTW, ops3(.reg_k_k,.ymm,.ymm_m256), evex(.L256,._66,._0F,.WIG, 0x65, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPCMPGTW, ops3(.reg_k_k,.zmm,.zmm_m512), evex(.L512,._66,._0F,.WIG, 0x65, fmem), .RVM, .{AVX512BW} ),
// VPCMPGTD
vec(.VPCMPGTD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x66), .RVM, .{AVX} ),
vec(.VPCMPGTD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x66), .RVM, .{AVX2} ),
vec(.VPCMPGTD, ops3(.reg_k_k,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0x66, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPGTD, ops3(.reg_k_k,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0x66, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPGTD, ops3(.reg_k_k,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0x66, full), .RVM, .{AVX512F} ),
// VPCMPGTQ
vec(.VPCMPGTQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x37), .RVM, .{AVX} ),
vec(.VPCMPGTQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x37), .RVM, .{AVX2} ),
vec(.VPCMPGTQ, ops3(.reg_k_k,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x37, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPGTQ, ops3(.reg_k_k,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x37, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPCMPGTQ, ops3(.reg_k_k,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x37, full), .RVM, .{AVX512F} ),
// VPCMPISTRI
vec(.VPCMPISTRI, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.WIG, 0x63), .vRMI,.{AVX} ),
// VPCMPISTRM
vec(.VPCMPISTRM, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.WIG, 0x62), .vRMI,.{AVX} ),
// VPEXTRB / VPEXTRD / VPEXTRQ
vec(.VPEXTRB, ops3(.reg32_m8, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x14), .vMRI,.{AVX} ),
vec(.VPEXTRB, ops3(.rm_reg64, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x14), .vMRI,.{AVX, No32} ),
vec(.VPEXTRB, ops3(.reg32_m8, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x14, t1s), .vMRI,.{AVX512BW} ),
vec(.VPEXTRB, ops3(.reg64, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x14, t1s), .vMRI,.{AVX512BW, No32} ),
//
vec(.VPEXTRD, ops3(.rm32, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x16), .vMRI,.{AVX} ),
vec(.VPEXTRD, ops3(.rm32, .xmm, .imm8), evex(.L128,._66,._0F3A,.W0, 0x16, t1s), .vMRI,.{AVX512DQ} ),
//
vec(.VPEXTRQ, ops3(.rm64, .xmml, .imm8), vex(.L128,._66,._0F3A,.W1, 0x16), .vMRI,.{AVX} ),
vec(.VPEXTRQ, ops3(.rm64, .xmm, .imm8), evex(.L128,._66,._0F3A,.W1, 0x16, t1s), .vMRI,.{AVX512DQ} ),
// VPEXTRW
vec(.VPEXTRW, ops3(.reg32, .xmml, .imm8), vex(.L128,._66,._0F,.W0, 0xC5), .vRMI,.{AVX} ),
vec(.VPEXTRW, ops3(.reg64, .xmml, .imm8), vex(.L128,._66,._0F,.W0, 0xC5), .vRMI,.{AVX, No32} ),
vec(.VPEXTRW, ops3(.reg32_m16, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x15), .vMRI,.{AVX} ),
vec(.VPEXTRW, ops3(.rm_reg64, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x15), .vMRI,.{AVX, No32} ),
vec(.VPEXTRW, ops3(.reg32, .xmm, .imm8), evex(.L128,._66,._0F,.WIG, 0xC5, nomem), .vRMI,.{AVX512BW} ),
vec(.VPEXTRW, ops3(.reg64, .xmm, .imm8), evex(.L128,._66,._0F,.WIG, 0xC5, nomem), .vRMI,.{AVX512BW, No32} ),
vec(.VPEXTRW, ops3(.reg32_m16, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x15, t1s), .vMRI,.{AVX512BW} ),
vec(.VPEXTRW, ops3(.rm_reg64, .xmm, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x15, t1s), .vMRI,.{AVX512BW, No32} ),
// VPHADDW / VPHADDD
vec(.VPHADDW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x01), .RVM, .{AVX} ),
vec(.VPHADDW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x01), .RVM, .{AVX2} ),
//
vec(.VPHADDD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x02), .RVM, .{AVX} ),
vec(.VPHADDD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x02), .RVM, .{AVX2} ),
// VPHADDSW
vec(.VPHADDSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x03), .RVM, .{AVX} ),
vec(.VPHADDSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x03), .RVM, .{AVX2} ),
// VPHMINPOSUW
vec(.VPHMINPOSUW,ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x41), .vRM, .{AVX} ),
// VPHSUBW / VPHSUBD
vec(.VPHSUBW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x05), .RVM, .{AVX} ),
vec(.VPHSUBW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x05), .RVM, .{AVX2} ),
//
vec(.VPHSUBD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x06), .RVM, .{AVX} ),
vec(.VPHSUBD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x06), .RVM, .{AVX2} ),
// VPHSUBSW
vec(.VPHSUBSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x07), .RVM, .{AVX} ),
vec(.VPHSUBSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x07), .RVM, .{AVX2} ),
// VPINSRB / VPINSRD / VPINSRQ
vec(.VPINSRB, ops4(.xmml, .xmml, .reg32_m8, .imm8), vex(.L128,._66,._0F3A,.W0, 0x20), .RVMI,.{AVX} ),
vec(.VPINSRB, ops4(.xmm, .xmm, .reg32_m8, .imm8), evex(.L128,._66,._0F3A,.WIG, 0x20, t1s), .RVMI,.{AVX512BW} ),
//
vec(.VPINSRD, ops4(.xmml, .xmml, .rm32, .imm8), vex(.L128,._66,._0F3A,.W0, 0x22), .RVMI,.{AVX} ),
vec(.VPINSRD, ops4(.xmm, .xmm, .rm32, .imm8), evex(.L128,._66,._0F3A,.W0, 0x22, t1s), .RVMI,.{AVX512DQ} ),
//
vec(.VPINSRQ, ops4(.xmml, .xmml, .rm64, .imm8), vex(.L128,._66,._0F3A,.W1, 0x22), .RVMI,.{AVX} ),
vec(.VPINSRQ, ops4(.xmm, .xmm, .rm64, .imm8), evex(.L128,._66,._0F3A,.W1, 0x22, t1s), .RVMI,.{AVX512DQ} ),
// VPINSRW
vec(.VPINSRW, ops4(.xmml, .xmml, .reg32_m16, .imm8), vex(.L128,._66,._0F,.W0, 0xC4), .RVMI,.{AVX} ),
vec(.VPINSRW, ops4(.xmml, .xmml, .rm_reg64, .imm8), vex(.L128,._66,._0F,.W0, 0xC4), .RVMI,.{AVX} ),
vec(.VPINSRW, ops4(.xmm, .xmm, .reg32_m16, .imm8), evex(.L128,._66,._0F,.WIG, 0xC4, t1s), .RVMI,.{AVX512BW} ),
vec(.VPINSRW, ops4(.xmm, .xmm, .rm_reg64, .imm8), evex(.L128,._66,._0F,.WIG, 0xC4, t1s), .RVMI,.{AVX512BW} ),
// VPMADDUBSW
vec(.VPMADDUBSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x04), .RVM, .{AVX} ),
vec(.VPMADDUBSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x04), .RVM, .{AVX2} ),
vec(.VPMADDUBSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x04, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMADDUBSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x04, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMADDUBSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x04, fmem), .RVM, .{AVX512BW} ),
// VPMADDWD
vec(.VPMADDWD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF5), .RVM, .{AVX} ),
vec(.VPMADDWD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xF5), .RVM, .{AVX2} ),
vec(.VPMADDWD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xF5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMADDWD, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xF5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMADDWD, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xF5, fmem), .RVM, .{AVX512BW} ),
// VPMAXSB / VPMAXSW / VPMAXSD / VPMAXSQ
// VPMAXSB
vec(.VPMAXSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3C), .RVM, .{AVX} ),
vec(.VPMAXSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3C), .RVM, .{AVX2} ),
vec(.VPMAXSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x3C, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x3C, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x3C, fmem), .RVM, .{AVX512BW} ),
// VPMAXSW
vec(.VPMAXSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xEE), .RVM, .{AVX} ),
vec(.VPMAXSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xEE), .RVM, .{AVX2} ),
vec(.VPMAXSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xEE, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xEE, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xEE, fmem), .RVM, .{AVX512BW} ),
// VPMAXSD
vec(.VPMAXSD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3D), .RVM, .{AVX} ),
vec(.VPMAXSD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3D), .RVM, .{AVX2} ),
vec(.VPMAXSD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x3D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXSD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x3D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXSD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x3D, full), .RVM, .{AVX512F} ),
// VPMAXSQ
vec(.VPMAXSQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x3D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXSQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x3D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXSQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x3D, full), .RVM, .{AVX512F} ),
// VPMAXUB / VPMAXUW
// VPMAXUB
vec(.VPMAXUB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDE), .RVM, .{AVX} ),
vec(.VPMAXUB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDE), .RVM, .{AVX2} ),
vec(.VPMAXUB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xDE, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXUB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xDE, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXUB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xDE, fmem), .RVM, .{AVX512BW} ),
// VPMAXUW
vec(.VPMAXUW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3E), .RVM, .{AVX} ),
vec(.VPMAXUW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3E), .RVM, .{AVX2} ),
vec(.VPMAXUW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x3E, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXUW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x3E, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMAXUW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x3E, fmem), .RVM, .{AVX512BW} ),
// VPMAXUD / VPMAXUQ
// VPMAXUD
vec(.VPMAXUD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3F), .RVM, .{AVX} ),
vec(.VPMAXUD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3F), .RVM, .{AVX2} ),
vec(.VPMAXUD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x3F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXUD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x3F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXUD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x3F, full), .RVM, .{AVX512F} ),
// VPMAXUQ
vec(.VPMAXUQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x3F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXUQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x3F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMAXUQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x3F, full), .RVM, .{AVX512F} ),
// VPMINSB / VPMINSW
// VPMINSB
vec(.VPMINSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x38), .RVM, .{AVX} ),
vec(.VPMINSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x38), .RVM, .{AVX2} ),
vec(.VPMINSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x38, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x38, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x38, fmem), .RVM, .{AVX512BW} ),
// VPMINSW
vec(.VPMINSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xEA), .RVM, .{AVX} ),
vec(.VPMINSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xEA), .RVM, .{AVX2} ),
vec(.VPMINSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xEA, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xEA, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xEA, fmem), .RVM, .{AVX512BW} ),
// VPMINSD / VPMINSQ
// VPMINSD
vec(.VPMINSD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x39), .RVM, .{AVX} ),
vec(.VPMINSD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x39), .RVM, .{AVX2} ),
vec(.VPMINSD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x39, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINSD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x39, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINSD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x39, full), .RVM, .{AVX512F} ),
// VPMINSQ
vec(.VPMINSQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x39, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINSQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x39, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINSQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x39, full), .RVM, .{AVX512F} ),
// VPMINUB / VPMINUW
// VPMINUB
vec(.VPMINUB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xDA), .RVM, .{AVX} ),
vec(.VPMINUB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xDA), .RVM, .{AVX2} ),
vec(.VPMINUB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xDA, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINUB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xDA, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINUB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xDA, fmem), .RVM, .{AVX512BW} ),
// VPMINUW
vec(.VPMINUW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3A), .RVM, .{AVX} ),
vec(.VPMINUW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3A), .RVM, .{AVX2} ),
vec(.VPMINUW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x3A, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINUW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x3A, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMINUW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x3A, fmem), .RVM, .{AVX512BW} ),
// VPMINUD / VPMINUQ
// VPMINUD
vec(.VPMINUD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x3B), .RVM, .{AVX} ),
vec(.VPMINUD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x3B), .RVM, .{AVX2} ),
vec(.VPMINUD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x3B, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINUD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x3B, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINUD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x3B, full), .RVM, .{AVX512F} ),
// VPMINUQ
vec(.VPMINUQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x3B, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINUQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x3B, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMINUQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x3B, full), .RVM, .{AVX512F} ),
// VPMOVMSKB
vec(.VPMOVMSKB, ops2(.reg32, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD7), .RVM, .{AVX} ),
vec(.VPMOVMSKB, ops2(.reg64, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD7), .RVM, .{AVX} ),
vec(.VPMOVMSKB, ops2(.reg32, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD7), .RVM, .{AVX2} ),
vec(.VPMOVMSKB, ops2(.reg64, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD7), .RVM, .{AVX2} ),
// VPMOVSX
// VPMOVSXBW
vec(.VPMOVSXBW, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x20), .vRM, .{AVX} ),
vec(.VPMOVSXBW, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x20), .vRM, .{AVX2} ),
vec(.VPMOVSXBW, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.WIG, 0x20, hmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVSXBW, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.WIG, 0x20, hmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVSXBW, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.WIG, 0x20, hmem), .vRM, .{AVX512BW} ),
// VPMOVSXBD
vec(.VPMOVSXBD, ops2(.xmml, .xmml_m32), vex(.L128,._66,._0F38,.WIG, 0x21), .vRM, .{AVX} ),
vec(.VPMOVSXBD, ops2(.ymml, .xmml_m64), vex(.L256,._66,._0F38,.WIG, 0x21), .vRM, .{AVX2} ),
vec(.VPMOVSXBD, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.WIG, 0x21, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXBD, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.WIG, 0x21, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXBD, ops2(.zmm_kz, .xmm_m128), evex(.L512,._66,._0F38,.WIG, 0x21, qmem), .vRM, .{AVX512F} ),
// VPMOVSXBQ
vec(.VPMOVSXBQ, ops2(.xmml, .xmml_m16), vex(.L128,._66,._0F38,.WIG, 0x22), .vRM, .{AVX} ),
vec(.VPMOVSXBQ, ops2(.ymml, .xmml_m32), vex(.L256,._66,._0F38,.WIG, 0x22), .vRM, .{AVX2} ),
vec(.VPMOVSXBQ, ops2(.xmm_kz, .xmm_m16), evex(.L128,._66,._0F38,.WIG, 0x22, emem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXBQ, ops2(.ymm_kz, .xmm_m32), evex(.L256,._66,._0F38,.WIG, 0x22, emem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXBQ, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.WIG, 0x22, emem), .vRM, .{AVX512F} ),
// VPMOVSXWD
vec(.VPMOVSXWD, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x23), .vRM, .{AVX} ),
vec(.VPMOVSXWD, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x23), .vRM, .{AVX2} ),
vec(.VPMOVSXWD, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.WIG, 0x23, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXWD, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.WIG, 0x23, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXWD, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.WIG, 0x23, hmem), .vRM, .{AVX512F} ),
// VPMOVSXWQ
vec(.VPMOVSXWQ, ops2(.xmml, .xmml_m32), vex(.L128,._66,._0F38,.WIG, 0x24), .vRM, .{AVX} ),
vec(.VPMOVSXWQ, ops2(.ymml, .xmml_m64), vex(.L256,._66,._0F38,.WIG, 0x24), .vRM, .{AVX2} ),
vec(.VPMOVSXWQ, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.WIG, 0x24, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXWQ, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.WIG, 0x24, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXWQ, ops2(.zmm_kz, .xmm_m128), evex(.L512,._66,._0F38,.WIG, 0x24, qmem), .vRM, .{AVX512F} ),
// VPMOVSXDQ
vec(.VPMOVSXDQ, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x25), .vRM, .{AVX} ),
vec(.VPMOVSXDQ, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x25), .vRM, .{AVX2} ),
vec(.VPMOVSXDQ, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.W0, 0x25, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXDQ, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.W0, 0x25, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVSXDQ, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.W0, 0x25, hmem), .vRM, .{AVX512F} ),
// VPMOVZX
// VPMOVZXBW
vec(.VPMOVZXBW, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x30), .vRM, .{AVX} ),
vec(.VPMOVZXBW, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x30), .vRM, .{AVX2} ),
vec(.VPMOVZXBW, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.WIG, 0x30, hmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVZXBW, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.WIG, 0x30, hmem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVZXBW, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.WIG, 0x30, hmem), .vRM, .{AVX512BW} ),
// VPMOVZXBD
vec(.VPMOVZXBD, ops2(.xmml, .xmml_m32), vex(.L128,._66,._0F38,.WIG, 0x31), .vRM, .{AVX} ),
vec(.VPMOVZXBD, ops2(.ymml, .xmml_m64), vex(.L256,._66,._0F38,.WIG, 0x31), .vRM, .{AVX2} ),
vec(.VPMOVZXBD, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.WIG, 0x31, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXBD, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.WIG, 0x31, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXBD, ops2(.zmm_kz, .xmm_m128), evex(.L512,._66,._0F38,.WIG, 0x31, qmem), .vRM, .{AVX512F} ),
// VPMOVZXBQ
vec(.VPMOVZXBQ, ops2(.xmml, .xmml_m16), vex(.L128,._66,._0F38,.WIG, 0x32), .vRM, .{AVX} ),
vec(.VPMOVZXBQ, ops2(.ymml, .xmml_m32), vex(.L256,._66,._0F38,.WIG, 0x32), .vRM, .{AVX2} ),
vec(.VPMOVZXBQ, ops2(.xmm_kz, .xmm_m16), evex(.L128,._66,._0F38,.WIG, 0x32, emem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXBQ, ops2(.ymm_kz, .xmm_m32), evex(.L256,._66,._0F38,.WIG, 0x32, emem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXBQ, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.WIG, 0x32, emem), .vRM, .{AVX512F} ),
// VPMOVZXWD
vec(.VPMOVZXWD, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x33), .vRM, .{AVX} ),
vec(.VPMOVZXWD, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x33), .vRM, .{AVX2} ),
vec(.VPMOVZXWD, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.WIG, 0x33, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXWD, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.WIG, 0x33, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXWD, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.WIG, 0x33, hmem), .vRM, .{AVX512F} ),
// VPMOVZXWQ
vec(.VPMOVZXWQ, ops2(.xmml, .xmml_m32), vex(.L128,._66,._0F38,.WIG, 0x34), .vRM, .{AVX} ),
vec(.VPMOVZXWQ, ops2(.ymml, .xmml_m64), vex(.L256,._66,._0F38,.WIG, 0x34), .vRM, .{AVX2} ),
vec(.VPMOVZXWQ, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.WIG, 0x34, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXWQ, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.WIG, 0x34, qmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXWQ, ops2(.zmm_kz, .xmm_m128), evex(.L512,._66,._0F38,.WIG, 0x34, qmem), .vRM, .{AVX512F} ),
// VPMOVZXDQ
vec(.VPMOVZXDQ, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.WIG, 0x35), .vRM, .{AVX} ),
vec(.VPMOVZXDQ, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.WIG, 0x35), .vRM, .{AVX2} ),
vec(.VPMOVZXDQ, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.W0, 0x35, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXDQ, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.W0, 0x35, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPMOVZXDQ, ops2(.zmm_kz, .ymm_m256), evex(.L512,._66,._0F38,.W0, 0x35, hmem), .vRM, .{AVX512F} ),
// VPMULDQ
vec(.VPMULDQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x28), .RVM, .{AVX} ),
vec(.VPMULDQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x28), .RVM, .{AVX2} ),
vec(.VPMULDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x28, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x28, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x28, full), .RVM, .{AVX512F} ),
// VPMULHRSW
vec(.VPMULHRSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x0B), .RVM, .{AVX} ),
vec(.VPMULHRSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x0B), .RVM, .{AVX2} ),
vec(.VPMULHRSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x0B, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHRSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x0B, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHRSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x0B, fmem), .RVM, .{AVX512BW} ),
// VPMULHUW
vec(.VPMULHUW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE4), .RVM, .{AVX} ),
vec(.VPMULHUW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE4), .RVM, .{AVX2} ),
vec(.VPMULHUW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE4, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHUW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE4, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHUW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE4, fmem), .RVM, .{AVX512BW} ),
// VPMULHW
vec(.VPMULHW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE5), .RVM, .{AVX} ),
vec(.VPMULHW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE5), .RVM, .{AVX2} ),
vec(.VPMULHW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULHW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE5, fmem), .RVM, .{AVX512BW} ),
// VPMULLD / VPMULLQ
// VPMULLD
vec(.VPMULLD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x40), .RVM, .{AVX} ),
vec(.VPMULLD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x40), .RVM, .{AVX2} ),
vec(.VPMULLD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x40, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULLD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x40, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULLD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x40, full), .RVM, .{AVX512F} ),
// VPMULLQ
vec(.VPMULLQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x40, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VPMULLQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x40, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VPMULLQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x40, full), .RVM, .{AVX512DQ} ),
// VPMULLW
vec(.VPMULLW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD5), .RVM, .{AVX} ),
vec(.VPMULLW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD5), .RVM, .{AVX2} ),
vec(.VPMULLW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xD5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULLW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xD5, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPMULLW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xD5, fmem), .RVM, .{AVX512BW} ),
// VPMULUDQ
vec(.VPMULUDQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF4), .RVM, .{AVX} ),
vec(.VPMULUDQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xF4), .RVM, .{AVX2} ),
vec(.VPMULUDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xF4, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULUDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xF4, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPMULUDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xF4, full), .RVM, .{AVX512F} ),
// VPOR
vec(.VPOR, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xEB), .RVM, .{AVX} ),
vec(.VPOR, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xEB), .RVM, .{AVX2} ),
//
vec(.VPORD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xEB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPORD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xEB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPORD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xEB, full), .RVM, .{AVX512F} ),
//
vec(.VPORQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xEB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPORQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xEB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPORQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xEB, full), .RVM, .{AVX512F} ),
// VPSADBW
vec(.VPSADBW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF6), .RVM, .{AVX} ),
vec(.VPSADBW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xF6), .RVM, .{AVX2} ),
vec(.VPSADBW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xF6, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSADBW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xF6, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSADBW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xF6, fmem), .RVM, .{AVX512BW} ),
// VPSHUFB
vec(.VPSHUFB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x00), .RVM, .{AVX} ),
vec(.VPSHUFB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x00), .RVM, .{AVX2} ),
vec(.VPSHUFB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.WIG, 0x00, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSHUFB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.WIG, 0x00, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSHUFB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.WIG, 0x00, fmem), .RVM, .{AVX512BW} ),
// VPSHUFD
vec(.VPSHUFD, ops3(.xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F,.WIG, 0x70), .vRMI,.{AVX} ),
vec(.VPSHUFD, ops3(.ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F,.WIG, 0x70), .vRMI,.{AVX2} ),
vec(.VPSHUFD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8),evex(.L128,._66,._0F,.W0, 0x70, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPSHUFD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8),evex(.L256,._66,._0F,.W0, 0x70, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPSHUFD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8),evex(.L512,._66,._0F,.W0, 0x70, full), .vRMI,.{AVX512F} ),
// VPSHUFHW
vec(.VPSHUFHW, ops3(.xmml, .xmml_m128, .imm8), vex(.L128,._F3,._0F,.WIG, 0x70), .vRMI,.{AVX} ),
vec(.VPSHUFHW, ops3(.ymml, .ymml_m256, .imm8), vex(.L256,._F3,._0F,.WIG, 0x70), .vRMI,.{AVX2} ),
vec(.VPSHUFHW, ops3(.xmm_kz, .xmm_m128, .imm8), evex(.L128,._F3,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512VL, AVX512BW} ),
vec(.VPSHUFHW, ops3(.ymm_kz, .ymm_m256, .imm8), evex(.L256,._F3,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512VL, AVX512BW} ),
vec(.VPSHUFHW, ops3(.zmm_kz, .zmm_m512, .imm8), evex(.L512,._F3,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512BW} ),
// VPSHUFLW
vec(.VPSHUFLW, ops3(.xmml, .xmml_m128, .imm8), vex(.L128,._F2,._0F,.WIG, 0x70), .vRMI,.{AVX} ),
vec(.VPSHUFLW, ops3(.ymml, .ymml_m256, .imm8), vex(.L256,._F2,._0F,.WIG, 0x70), .vRMI,.{AVX2} ),
vec(.VPSHUFLW, ops3(.xmm_kz, .xmm_m128, .imm8), evex(.L128,._F2,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512VL, AVX512BW} ),
vec(.VPSHUFLW, ops3(.ymm_kz, .ymm_m256, .imm8), evex(.L256,._F2,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512VL, AVX512BW} ),
vec(.VPSHUFLW, ops3(.zmm_kz, .zmm_m512, .imm8), evex(.L512,._F2,._0F,.WIG, 0x70, fmem), .vRMI,.{AVX512BW} ),
// VPSIGNB / VPSIGNW / VPSIGND
// VPSIGNB
vec(.VPSIGNB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x08), .RVM, .{AVX} ),
vec(.VPSIGNB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x08), .RVM, .{AVX2} ),
// VPSIGNW
vec(.VPSIGNW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x09), .RVM, .{AVX} ),
vec(.VPSIGNW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x09), .RVM, .{AVX2} ),
// VPSIGND
vec(.VPSIGND, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x0A), .RVM, .{AVX} ),
vec(.VPSIGND, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x0A), .RVM, .{AVX2} ),
// VPSLLDQ
vec(.VPSLLDQ, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x73, 7), .VMI, .{AVX} ),
vec(.VPSLLDQ, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x73, 7), .VMI, .{AVX2} ),
vec(.VPSLLDQ, ops3(.xmm_kz, .xmm_m128, .imm8), evexr(.L128,._66,._0F,.WIG, 0x73, 7,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSLLDQ, ops3(.ymm_kz, .ymm_m256, .imm8), evexr(.L256,._66,._0F,.WIG, 0x73, 7,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSLLDQ, ops3(.zmm_kz, .zmm_m512, .imm8), evexr(.L512,._66,._0F,.WIG, 0x73, 7,fmem), .VMI, .{AVX512BW} ),
// VPSLLW / VPSLLD / VPSLLQ
// VPSLLW
vec(.VPSLLW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF1), .RVM, .{AVX} ),
vec(.VPSLLW, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x71, 6), .VMI, .{AVX} ),
vec(.VPSLLW, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xF1), .RVM, .{AVX2} ),
vec(.VPSLLW, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x71, 6), .VMI, .{AVX2} ),
vec(.VPSLLW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xF1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSLLW, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.WIG, 0xF1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSLLW, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.WIG, 0xF1, mem128), .RVM, .{AVX512BW} ),
vec(.VPSLLW, ops3(.xmm_kz, .xmm_m128, .imm8), evexr(.L128,._66,._0F,.WIG, 0x71, 6,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSLLW, ops3(.ymm_kz, .ymm_m256, .imm8), evexr(.L256,._66,._0F,.WIG, 0x71, 6,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSLLW, ops3(.zmm_kz, .zmm_m512, .imm8), evexr(.L512,._66,._0F,.WIG, 0x71, 6,fmem), .VMI, .{AVX512BW} ),
// VPSLLD
vec(.VPSLLD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF2), .RVM, .{AVX} ),
vec(.VPSLLD, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x72, 6), .VMI, .{AVX} ),
vec(.VPSLLD, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xF2), .RVM, .{AVX2} ),
vec(.VPSLLD, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x72, 6), .VMI, .{AVX2} ),
vec(.VPSLLD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W0, 0xF2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLD, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W0, 0xF2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLD, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W0, 0xF2, mem128), .RVM, .{AVX512F} ),
vec(.VPSLLD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8),evexr(.L128,._66,._0F,.W0, 0x72, 6,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSLLD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8),evexr(.L256,._66,._0F,.W0, 0x72, 6,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSLLD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8),evexr(.L512,._66,._0F,.W0, 0x72, 6,full), .VMI, .{AVX512F} ),
// VPSLLQ
vec(.VPSLLQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF3), .RVM, .{AVX} ),
vec(.VPSLLQ, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x73, 6), .VMI, .{AVX} ),
vec(.VPSLLQ, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xF3), .RVM, .{AVX2} ),
vec(.VPSLLQ, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x73, 6), .VMI, .{AVX2} ),
vec(.VPSLLQ, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W1, 0xF3, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLQ, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W1, 0xF3, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLQ, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W1, 0xF3, mem128), .RVM, .{AVX512F} ),
vec(.VPSLLQ, ops3(.xmm_kz, .xmm_m128_m64bcst, .imm8),evexr(.L128,._66,._0F,.W1, 0x73, 6,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSLLQ, ops3(.ymm_kz, .ymm_m256_m64bcst, .imm8),evexr(.L256,._66,._0F,.W1, 0x73, 6,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSLLQ, ops3(.zmm_kz, .zmm_m512_m64bcst, .imm8),evexr(.L512,._66,._0F,.W1, 0x73, 6,full), .VMI, .{AVX512F} ),
// VPSRAW / VPSRAD / VPSRAQ
// VPSRAW
vec(.VPSRAW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE1), .RVM, .{AVX} ),
vec(.VPSRAW, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x71, 4), .VMI, .{AVX} ),
vec(.VPSRAW, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xE1), .RVM, .{AVX2} ),
vec(.VPSRAW, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x71, 4), .VMI, .{AVX2} ),
vec(.VPSRAW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRAW, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.WIG, 0xE1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRAW, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.WIG, 0xE1, mem128), .RVM, .{AVX512BW} ),
vec(.VPSRAW, ops3(.xmm_kz, .xmm_m128, .imm8), evexr(.L128,._66,._0F,.WIG, 0x71, 4,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRAW, ops3(.ymm_kz, .ymm_m256, .imm8), evexr(.L256,._66,._0F,.WIG, 0x71, 4,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRAW, ops3(.zmm_kz, .zmm_m512, .imm8), evexr(.L512,._66,._0F,.WIG, 0x71, 4,fmem), .VMI, .{AVX512BW} ),
// VPSRAD
vec(.VPSRAD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE2), .RVM, .{AVX} ),
vec(.VPSRAD, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x72, 4), .VMI, .{AVX} ),
vec(.VPSRAD, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xE2), .RVM, .{AVX2} ),
vec(.VPSRAD, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x72, 4), .VMI, .{AVX2} ),
vec(.VPSRAD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W0, 0xE2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAD, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W0, 0xE2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAD, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W0, 0xE2, mem128), .RVM, .{AVX512F} ),
vec(.VPSRAD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8),evexr(.L128,._66,._0F,.W0, 0x72, 4,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRAD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8),evexr(.L256,._66,._0F,.W0, 0x72, 4,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRAD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8),evexr(.L512,._66,._0F,.W0, 0x72, 4,full), .VMI, .{AVX512F} ),
// VPSRAQ
vec(.VPSRAQ, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W1, 0xE2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAQ, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W1, 0xE2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAQ, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W1, 0xE2, mem128), .RVM, .{AVX512F} ),
vec(.VPSRAQ, ops3(.xmm_kz, .xmm_m128_m64bcst, .imm8),evexr(.L128,._66,._0F,.W1, 0x72, 4,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRAQ, ops3(.ymm_kz, .ymm_m256_m64bcst, .imm8),evexr(.L256,._66,._0F,.W1, 0x72, 4,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRAQ, ops3(.zmm_kz, .zmm_m512_m64bcst, .imm8),evexr(.L512,._66,._0F,.W1, 0x72, 4,full), .VMI, .{AVX512F} ),
// VPSRLDQ
vec(.VPSRLDQ, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x73, 3), .VMI, .{AVX} ),
vec(.VPSRLDQ, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x73, 3), .VMI, .{AVX2} ),
vec(.VPSRLDQ, ops3(.xmm_kz, .xmm_m128, .imm8), evexr(.L128,._66,._0F,.WIG, 0x73, 3,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRLDQ, ops3(.ymm_kz, .ymm_m256, .imm8), evexr(.L256,._66,._0F,.WIG, 0x73, 3,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRLDQ, ops3(.zmm_kz, .zmm_m512, .imm8), evexr(.L512,._66,._0F,.WIG, 0x73, 3,fmem), .VMI, .{AVX512BW} ),
// VPSRLW / VPSRLD / VPSRLQ
// VPSRLW
vec(.VPSRLW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD1), .RVM, .{AVX} ),
vec(.VPSRLW, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x71, 2), .VMI, .{AVX} ),
vec(.VPSRLW, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xD1), .RVM, .{AVX2} ),
vec(.VPSRLW, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x71, 2), .VMI, .{AVX2} ),
vec(.VPSRLW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xD1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRLW, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.WIG, 0xD1, mem128), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRLW, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.WIG, 0xD1, mem128), .RVM, .{AVX512BW} ),
vec(.VPSRLW, ops3(.xmm_kz, .xmm_m128, .imm8), evexr(.L128,._66,._0F,.WIG, 0x71, 2,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRLW, ops3(.ymm_kz, .ymm_m256, .imm8), evexr(.L256,._66,._0F,.WIG, 0x71, 2,fmem), .VMI, .{AVX512VL, AVX512BW} ),
vec(.VPSRLW, ops3(.zmm_kz, .zmm_m512, .imm8), evexr(.L512,._66,._0F,.WIG, 0x71, 2,fmem), .VMI, .{AVX512BW} ),
// VPSRLD
vec(.VPSRLD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD2), .RVM, .{AVX} ),
vec(.VPSRLD, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x72, 2), .VMI, .{AVX} ),
vec(.VPSRLD, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xD2), .RVM, .{AVX2} ),
vec(.VPSRLD, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x72, 2), .VMI, .{AVX2} ),
vec(.VPSRLD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W0, 0xD2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLD, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W0, 0xD2, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLD, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W0, 0xD2, mem128), .RVM, .{AVX512F} ),
vec(.VPSRLD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8),evexr(.L128,._66,._0F,.W0, 0x72, 2,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRLD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8),evexr(.L256,._66,._0F,.W0, 0x72, 2,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRLD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8),evexr(.L512,._66,._0F,.W0, 0x72, 2,full), .VMI, .{AVX512F} ),
// VPSRLQ
vec(.VPSRLQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD3), .RVM, .{AVX} ),
vec(.VPSRLQ, ops3(.xmml, .xmml_m128, .imm8), vexr(.L128,._66,._0F,.WIG, 0x73, 2), .VMI, .{AVX} ),
vec(.VPSRLQ, ops3(.ymml, .ymml, .xmml_m128), vex(.L256,._66,._0F,.WIG, 0xD3), .RVM, .{AVX2} ),
vec(.VPSRLQ, ops3(.ymml, .ymml_m256, .imm8), vexr(.L256,._66,._0F,.WIG, 0x73, 2), .VMI, .{AVX2} ),
vec(.VPSRLQ, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.W1, 0xD3, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLQ, ops3(.ymm_kz, .ymm, .xmm_m128), evex(.L256,._66,._0F,.W1, 0xD3, mem128), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLQ, ops3(.zmm_kz, .zmm, .xmm_m128), evex(.L512,._66,._0F,.W1, 0xD3, mem128), .RVM, .{AVX512F} ),
vec(.VPSRLQ, ops3(.xmm_kz, .xmm_m128_m64bcst, .imm8),evexr(.L128,._66,._0F,.W1, 0x73, 2,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRLQ, ops3(.ymm_kz, .ymm_m256_m64bcst, .imm8),evexr(.L256,._66,._0F,.W1, 0x73, 2,full), .VMI, .{AVX512VL, AVX512F} ),
vec(.VPSRLQ, ops3(.zmm_kz, .zmm_m512_m64bcst, .imm8),evexr(.L512,._66,._0F,.W1, 0x73, 2,full), .VMI, .{AVX512F} ),
// VPSUBB / VPSUBW / VPSUBD
// VPSUBB
vec(.VPSUBB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF8), .RVM, .{AVX} ),
vec(.VPSUBB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xF8), .RVM, .{AVX2} ),
vec(.VPSUBB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xF8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xF8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xF8, fmem), .RVM, .{AVX512BW} ),
// VPSUBW
vec(.VPSUBW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xF9), .RVM, .{AVX} ),
vec(.VPSUBW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xF9), .RVM, .{AVX2} ),
vec(.VPSUBW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xF9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xF9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xF9, fmem), .RVM, .{AVX512BW} ),
// VPSUBD
vec(.VPSUBD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xFA), .RVM, .{AVX} ),
vec(.VPSUBD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xFA), .RVM, .{AVX2} ),
vec(.VPSUBD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xFA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSUBD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xFA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSUBD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xFA, full), .RVM, .{AVX512F} ),
// VPSUBQ
vec(.VPSUBQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xFB), .RVM, .{AVX} ),
vec(.VPSUBQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xFB), .RVM, .{AVX2} ),
vec(.VPSUBQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xFB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSUBQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xFB, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSUBQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xFB, full), .RVM, .{AVX512F} ),
// VPSUBSB / VPSUBSW
vec(.VPSUBSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE8), .RVM, .{AVX} ),
vec(.VPSUBSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE8), .RVM, .{AVX2} ),
vec(.VPSUBSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE8, fmem), .RVM, .{AVX512BW} ),
//
vec(.VPSUBSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xE9), .RVM, .{AVX} ),
vec(.VPSUBSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xE9), .RVM, .{AVX2} ),
vec(.VPSUBSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xE9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xE9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xE9, fmem), .RVM, .{AVX512BW} ),
// VPSUBUSB / VPSUBUSW
vec(.VPSUBUSB, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD8), .RVM, .{AVX} ),
vec(.VPSUBUSB, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD8), .RVM, .{AVX2} ),
vec(.VPSUBUSB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xD8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBUSB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xD8, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBUSB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xD8, fmem), .RVM, .{AVX512BW} ),
//
vec(.VPSUBUSW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xD9), .RVM, .{AVX} ),
vec(.VPSUBUSW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xD9), .RVM, .{AVX2} ),
vec(.VPSUBUSW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0xD9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBUSW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0xD9, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSUBUSW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0xD9, fmem), .RVM, .{AVX512BW} ),
// VPTEST
vec(.VPTEST, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.WIG, 0x17), .vRM, .{AVX} ),
vec(.VPTEST, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.WIG, 0x17), .vRM, .{AVX} ),
// VPUNPCKHBW / VPUNPCKHWD / VPUNPCKHDQ / VPUNPCKHQDQ
// VPUNPCKHBW
vec(.VPUNPCKHBW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x68), .RVM, .{AVX} ),
vec(.VPUNPCKHBW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x68), .RVM, .{AVX2} ),
vec(.VPUNPCKHBW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x68, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKHBW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x68, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKHBW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x68, fmem), .RVM, .{AVX512BW} ),
// VPUNPCKHWD
vec(.VPUNPCKHWD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x69), .RVM, .{AVX} ),
vec(.VPUNPCKHWD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x69), .RVM, .{AVX2} ),
vec(.VPUNPCKHWD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x69, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKHWD, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x69, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKHWD, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x69, fmem), .RVM, .{AVX512BW} ),
// VPUNPCKHDQ
vec(.VPUNPCKHDQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x6A), .RVM, .{AVX} ),
vec(.VPUNPCKHDQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x6A), .RVM, .{AVX2} ),
vec(.VPUNPCKHDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0x6A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKHDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0x6A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKHDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0x6A, full), .RVM, .{AVX512F} ),
// VPUNPCKHQDQ
vec(.VPUNPCKHQDQ,ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x6D), .RVM, .{AVX} ),
vec(.VPUNPCKHQDQ,ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x6D), .RVM, .{AVX2} ),
vec(.VPUNPCKHQDQ,ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x6D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKHQDQ,ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x6D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKHQDQ,ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x6D, full), .RVM, .{AVX512F} ),
// VPUNPCKLBW / VPUNPCKLWD / VPUNPCKLDQ / VPUNPCKLQDQ
// VPUNPCKLBW
vec(.VPUNPCKLBW, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x60), .RVM, .{AVX} ),
vec(.VPUNPCKLBW, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x60), .RVM, .{AVX2} ),
vec(.VPUNPCKLBW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x60, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKLBW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x60, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKLBW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x60, fmem), .RVM, .{AVX512BW} ),
// VPUNPCKLWD
vec(.VPUNPCKLWD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x61), .RVM, .{AVX} ),
vec(.VPUNPCKLWD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x61), .RVM, .{AVX2} ),
vec(.VPUNPCKLWD, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F,.WIG, 0x61, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKLWD, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F,.WIG, 0x61, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPUNPCKLWD, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F,.WIG, 0x61, fmem), .RVM, .{AVX512BW} ),
// VPUNPCKLDQ
vec(.VPUNPCKLDQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x62), .RVM, .{AVX} ),
vec(.VPUNPCKLDQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x62), .RVM, .{AVX2} ),
vec(.VPUNPCKLDQ, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0x62, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKLDQ, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0x62, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKLDQ, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0x62, full), .RVM, .{AVX512F} ),
// VPUNPCKLQDQ
vec(.VPUNPCKLQDQ,ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x6C), .RVM, .{AVX} ),
vec(.VPUNPCKLQDQ,ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x6C), .RVM, .{AVX2} ),
vec(.VPUNPCKLQDQ,ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x6C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKLQDQ,ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x6C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPUNPCKLQDQ,ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x6C, full), .RVM, .{AVX512F} ),
// VPXOR
vec(.VPXOR, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0xEF), .RVM, .{AVX} ),
vec(.VPXOR, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0xEF), .RVM, .{AVX2} ),
//
vec(.VPXORD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F,.W0, 0xEF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPXORD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F,.W0, 0xEF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPXORD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F,.W0, 0xEF, full), .RVM, .{AVX512F} ),
//
vec(.VPXORQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0xEF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPXORQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0xEF, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPXORQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0xEF, full), .RVM, .{AVX512F} ),
// VRCPPS
vec(.VRCPPS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x53), .vRM, .{AVX} ),
vec(.VRCPPS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x53), .vRM, .{AVX} ),
// VRCPSS
vec(.VRCPSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x53), .RVM, .{AVX} ),
// VROUNDPD
vec(.VROUNDPD, ops3(.xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x09), .vRMI,.{AVX} ),
vec(.VROUNDPD, ops3(.ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG, 0x09), .vRMI,.{AVX} ),
// VROUNDPS
vec(.VROUNDPS, ops3(.xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F3A,.WIG, 0x08), .vRMI,.{AVX} ),
vec(.VROUNDPS, ops3(.ymml, .ymml_m256, .imm8), vex(.L256,._66,._0F3A,.WIG, 0x08), .vRMI,.{AVX} ),
// VROUNDSD
vec(.VROUNDSD, ops4(.xmml, .xmml, .xmml_m64, .imm8), vex(.LIG,._66,._0F3A,.WIG, 0x0B), .RVMI,.{AVX} ),
// VROUNDSS
vec(.VROUNDSS, ops4(.xmml, .xmml, .xmml_m32, .imm8), vex(.LIG,._66,._0F3A,.WIG, 0x0A), .RVMI,.{AVX} ),
// VRSQRTPS
vec(.VRSQRTPS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x52), .vRM, .{AVX} ),
vec(.VRSQRTPS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x52), .vRM, .{AVX} ),
// VRSQRTSS
vec(.VRSQRTSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x52), .RVM, .{AVX} ),
// VSHUFPD
vec(.VSHUFPD, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._66,._0F,.WIG,0xC6), .RVMI,.{AVX} ),
vec(.VSHUFPD, ops4(.ymml, .xmml, .ymml_m256, .imm8), vex(.L256,._66,._0F,.WIG,0xC6), .RVMI,.{AVX} ),
vec(.VSHUFPD, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F,.W1, 0xC6, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFPD, ops4(.ymm_kz,.xmm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F,.W1, 0xC6, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFPD, ops4(.zmm_kz,.xmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F,.W1, 0xC6, full), .RVMI,.{AVX512F} ),
// VSHUFPS
vec(.VSHUFPS, ops4(.xmml, .xmml, .xmml_m128, .imm8), vex(.L128,._NP,._0F,.WIG,0xC6), .RVMI,.{AVX} ),
vec(.VSHUFPS, ops4(.ymml, .xmml, .ymml_m256, .imm8), vex(.L256,._NP,._0F,.WIG,0xC6), .RVMI,.{AVX} ),
vec(.VSHUFPS, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._NP,._0F,.W0, 0xC6, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFPS, ops4(.ymm_kz,.xmm,.ymm_m256_m32bcst,.imm8), evex(.L256,._NP,._0F,.W0, 0xC6, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFPS, ops4(.zmm_kz,.xmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._NP,._0F,.W0, 0xC6, full), .RVMI,.{AVX512F} ),
// VSQRTPD
vec(.VSQRTPD, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x51), .vRM, .{AVX} ),
vec(.VSQRTPD, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x51), .vRM, .{AVX} ),
vec(.VSQRTPD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x51, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VSQRTPD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x51, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VSQRTPD, ops2(.zmm_kz, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x51, full), .vRM, .{AVX512F} ),
// VSQRTPS
vec(.VSQRTPS, ops2(.xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x51), .vRM, .{AVX} ),
vec(.VSQRTPS, ops2(.ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x51), .vRM, .{AVX} ),
vec(.VSQRTPS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x51, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VSQRTPS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x51, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VSQRTPS, ops2(.zmm_kz, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x51, full), .vRM, .{AVX512F} ),
// VSQRTSD
vec(.VSQRTSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x51), .RVM, .{AVX} ),
vec(.VSQRTSD, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x51, t1s), .RVM, .{AVX512F} ),
// VSQRTSS
vec(.VSQRTSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x51), .RVM, .{AVX} ),
vec(.VSQRTSS, ops3(.xmm_kz, .xmm, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x51, t1s), .RVM, .{AVX512F} ),
// VSTMXCSR
vec(.VSTMXCSR, ops1(.rm_mem32), vexr(.LZ,._NP,._0F,.WIG, 0xAE, 3), .vM, .{AVX} ),
// VSUBPD
vec(.VSUBPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x5C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VSUBPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x5C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VSUBPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x5C, full), .RVM, .{AVX512F} ),
// VSUBPS
vec(.VSUBPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x5C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VSUBPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x5C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VSUBPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x5C, full), .RVM, .{AVX512F} ),
// VSUBSD
vec(.VSUBSD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._F2,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBSD, ops3(.xmm_kz, .xmm, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x5C, t1s), .RVM, .{AVX512F} ),
// VSUBSS
vec(.VSUBSS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._F3,._0F,.WIG, 0x5C), .RVM, .{AVX} ),
vec(.VSUBSS, ops3(.xmm_kz, .xmm, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x5C, t1s), .RVM, .{AVX512F} ),
// VUCOMISD
vec(.VUCOMISD, ops2(.xmml, .xmml_m64), vex(.LIG,._66,._0F,.WIG, 0x2E), .vRM, .{AVX} ),
vec(.VUCOMISD, ops2(.xmm_kz, .xmm_m64_sae), evex(.LIG,._66,._0F,.W1, 0x2E, t1s), .vRM, .{AVX512F} ),
// VUCOMISS
vec(.VUCOMISS, ops2(.xmml, .xmml_m32), vex(.LIG,._NP,._0F,.WIG, 0x2E), .vRM, .{AVX} ),
vec(.VUCOMISS, ops2(.xmm_kz, .xmm_m32_sae), evex(.LIG,._NP,._0F,.W0, 0x2E, t1s), .vRM, .{AVX512F} ),
// VUNPCKHPD
vec(.VUNPCKHPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x15), .RVM, .{AVX} ),
vec(.VUNPCKHPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x15), .RVM, .{AVX} ),
vec(.VUNPCKHPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKHPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKHPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x15, full), .RVM, .{AVX512F} ),
// VUNPCKHPS
vec(.VUNPCKHPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x15), .RVM, .{AVX} ),
vec(.VUNPCKHPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x15), .RVM, .{AVX} ),
vec(.VUNPCKHPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKHPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKHPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x15, full), .RVM, .{AVX512F} ),
// VUNPCKLPD
vec(.VUNPCKLPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x14), .RVM, .{AVX} ),
vec(.VUNPCKLPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x14), .RVM, .{AVX} ),
vec(.VUNPCKLPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKLPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKLPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x14, full), .RVM, .{AVX512F} ),
// VUNPCKLPS
vec(.VUNPCKLPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x14), .RVM, .{AVX} ),
vec(.VUNPCKLPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x14), .RVM, .{AVX} ),
vec(.VUNPCKLPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKLPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VUNPCKLPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x14, full), .RVM, .{AVX512F} ),
//
// Instructions V-Z
//
// VALIGND / VALIGNQ
// VALIGND
vec(.VALIGND, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x03, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VALIGND, ops4(.ymm_kz,.xmm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x03, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VALIGND, ops4(.zmm_kz,.xmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x03, full), .RVMI,.{AVX512F} ),
// VALIGNQ
vec(.VALIGNQ, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x03, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VALIGNQ, ops4(.ymm_kz,.xmm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x03, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VALIGNQ, ops4(.zmm_kz,.xmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x03, full), .RVMI,.{AVX512F} ),
// VBLENDMPD / VBLENDMPS
// VBLENDMPD
vec(.VBLENDMPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x65, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VBLENDMPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x65, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VBLENDMPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x65, full), .RVM, .{AVX512F} ),
// VBLENDMPS
vec(.VBLENDMPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x65, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VBLENDMPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x65, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VBLENDMPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x65, full), .RVM, .{AVX512F} ),
// VBROADCAST
// VBROADCASTSS
vec(.VBROADCASTSS, ops2(.xmml, .rm_mem32), vex(.L128,._66,._0F38,.W0, 0x18), .vRM, .{AVX} ),
vec(.VBROADCASTSS, ops2(.ymml, .rm_mem32), vex(.L256,._66,._0F38,.W0, 0x18), .vRM, .{AVX} ),
vec(.VBROADCASTSS, ops2(.xmml, .rm_xmml), vex(.L128,._66,._0F38,.W0, 0x18), .vRM, .{AVX2} ),
vec(.VBROADCASTSS, ops2(.ymml, .rm_xmml), vex(.L256,._66,._0F38,.W0, 0x18), .vRM, .{AVX2} ),
vec(.VBROADCASTSS, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.W0, 0x18, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VBROADCASTSS, ops2(.ymm_kz, .xmm_m32), evex(.L256,._66,._0F38,.W0, 0x18, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VBROADCASTSS, ops2(.zmm_kz, .xmm_m32), evex(.L512,._66,._0F38,.W0, 0x18, t1s), .vRM, .{AVX512F} ),
// VBROADCASTSD
vec(.VBROADCASTSD, ops2(.ymml, .rm_mem64), vex(.L256,._66,._0F38,.W0, 0x19), .vRM, .{AVX} ),
vec(.VBROADCASTSD, ops2(.ymml, .rm_xmml), vex(.L256,._66,._0F38,.W0, 0x19), .vRM, .{AVX2} ),
vec(.VBROADCASTSD, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.W1, 0x19, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VBROADCASTSD, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.W1, 0x19, t1s), .vRM, .{AVX512F} ),
// VBROADCASTF128
vec(.VBROADCASTF128, ops2(.ymml, .rm_mem128), vex(.L256,._66,._0F38,.W0, 0x1A), .vRM, .{AVX} ),
// VBROADCASTF32X2
vec(.VBROADCASTF32X2, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.W0, 0x19, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VBROADCASTF32X2, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.W0, 0x19, tup2), .vRM, .{AVX512DQ} ),
// VBROADCASTF32X4
vec(.VBROADCASTF32X4, ops2(.ymm_kz, .rm_mem128), evex(.L256,._66,._0F38,.W0, 0x1A, tup4), .vRM, .{AVX512VL, AVX512F} ),
vec(.VBROADCASTF32X4, ops2(.zmm_kz, .rm_mem128), evex(.L512,._66,._0F38,.W0, 0x1A, tup4), .vRM, .{AVX512F} ),
// VBROADCASTF64X2
vec(.VBROADCASTF64X2, ops2(.ymm_kz, .rm_mem128), evex(.L256,._66,._0F38,.W1, 0x1A, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VBROADCASTF64X2, ops2(.zmm_kz, .rm_mem128), evex(.L512,._66,._0F38,.W1, 0x1A, tup2), .vRM, .{AVX512DQ} ),
// VBROADCASTF32X8
vec(.VBROADCASTF32X8, ops2(.zmm_kz, .rm_mem256), evex(.L512,._66,._0F38,.W0, 0x1B, tup8), .vRM, .{AVX512DQ} ),
// VBROADCASTF64X4
vec(.VBROADCASTF64X4, ops2(.zmm_kz, .rm_mem256), evex(.L512,._66,._0F38,.W1, 0x1B, tup4), .vRM, .{AVX512F} ),
// VCOMPRESSPD
vec(.VCOMPRESSPD, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F38,.W1, 0x8A, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VCOMPRESSPD, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F38,.W1, 0x8A, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VCOMPRESSPD, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F38,.W1, 0x8A, t1s), .vMR, .{AVX512F} ),
// VCOMPRESSPS
vec(.VCOMPRESSPS, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F38,.W0, 0x8A, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VCOMPRESSPS, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F38,.W0, 0x8A, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VCOMPRESSPS, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F38,.W0, 0x8A, t1s), .vMR, .{AVX512F} ),
// VCVTPD2QQ
vec(.VCVTPD2QQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x7B, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPD2QQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x7B, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPD2QQ, ops2(.zmm_kz, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x7B, full), .vRM, .{AVX512DQ} ),
// VCVTPD2UDQ
vec(.VCVTPD2UDQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._NP,._0F,.W1, 0x79, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2UDQ, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._NP,._0F,.W1, 0x79, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPD2UDQ, ops2(.ymm_kz, .zmm_m512_m64bcst_er), evex(.L512,._NP,._0F,.W1, 0x79, full), .vRM, .{AVX512F} ),
// VCVTPD2UQQ
vec(.VCVTPD2UQQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x79, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPD2UQQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x79, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPD2UQQ, ops2(.zmm_kz, .zmm_m512_m64bcst_er), evex(.L512,._66,._0F,.W1, 0x79, full), .vRM, .{AVX512DQ} ),
// VCVTPH2PS
vec(.VCVTPH2PS, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.W0, 0x13), .vRM, .{cpu.F16C} ),
vec(.VCVTPH2PS, ops2(.ymml, .xmml_m128), vex(.L256,._66,._0F38,.W0, 0x13), .vRM, .{cpu.F16C} ),
vec(.VCVTPH2PS, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.W0, 0x13, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPH2PS, ops2(.ymm_kz, .xmm_m128), evex(.L256,._66,._0F38,.W0, 0x13, hmem), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPH2PS, ops2(.zmm_kz, .ymm_m256_sae), evex(.L512,._66,._0F38,.W0, 0x13, hmem), .vRM, .{AVX512F} ),
// VCVTPS2PH
vec(.VCVTPS2PH, ops3(.xmml_m64, .xmml, .imm8), vex(.L128,._66,._0F3A,.W0, 0x1D), .vMRI,.{cpu.F16C} ),
vec(.VCVTPS2PH, ops3(.xmml_m128, .ymml, .imm8), vex(.L256,._66,._0F3A,.W0, 0x1D), .vMRI,.{cpu.F16C} ),
vec(.VCVTPS2PH, ops3(.xmm_m64_kz, .xmm, .imm8), evex(.L128,._66,._0F3A,.W0, 0x1D, hmem), .vMRI,.{AVX512VL, AVX512F} ),
vec(.VCVTPS2PH, ops3(.xmm_m128_kz, .ymm, .imm8), evex(.L256,._66,._0F3A,.W0, 0x1D, hmem), .vMRI,.{AVX512VL, AVX512F} ),
vec(.VCVTPS2PH, ops3(.ymm_m256_kz, .zmm_sae, .imm8), evex(.L512,._66,._0F3A,.W0, 0x1D, hmem), .vMRI,.{AVX512F} ),
// VCVTPS2QQ
vec(.VCVTPS2QQ, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._66,._0F,.W0, 0x7B, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPS2QQ, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._66,._0F,.W0, 0x7B, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPS2QQ, ops2(.zmm_kz, .ymm_m256_m32bcst_er), evex(.L512,._66,._0F,.W0, 0x7B, half), .vRM, .{AVX512DQ} ),
// VCVTPS2UDQ
vec(.VCVTPS2UDQ, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x79, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPS2UDQ, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x79, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTPS2UDQ, ops2(.zmm_kz, .zmm_m512_m32bcst_er), evex(.L512,._NP,._0F,.W0, 0x79, full), .vRM, .{AVX512F} ),
// VCVTPS2UQQ
vec(.VCVTPS2UQQ, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._66,._0F,.W0, 0x79, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPS2UQQ, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._66,._0F,.W0, 0x79, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTPS2UQQ, ops2(.zmm_kz, .ymm_m256_m32bcst_er), evex(.L512,._66,._0F,.W0, 0x79, half), .vRM, .{AVX512DQ} ),
// VCVTQQ2PD
vec(.VCVTQQ2PD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._F3,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTQQ2PD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._F3,._0F,.W1, 0xE6, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTQQ2PD, ops2(.zmm_kz, .zmm_m512_m64bcst_er), evex(.L512,._F3,._0F,.W1, 0xE6, full), .vRM, .{AVX512DQ} ),
// VCVTQQ2PS
vec(.VCVTQQ2PS, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._NP,._0F,.W1, 0x5B, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTQQ2PS, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._NP,._0F,.W1, 0x5B, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTQQ2PS, ops2(.ymm_kz, .zmm_m512_m64bcst_er), evex(.L512,._NP,._0F,.W1, 0x5B, full), .vRM, .{AVX512DQ} ),
// VCVTSD2USI
vec(.VCVTSD2USI, ops2(.reg32, .xmm_m64_er), evex(.LIG,._F2,._0F,.W0, 0x79, t1f), .vRM, .{AVX512F} ),
vec(.VCVTSD2USI, ops2(.reg64, .xmm_m64_er), evex(.LIG,._F2,._0F,.W1, 0x79, t1f), .vRM, .{AVX512F, No32} ),
// VCVTSS2USI
vec(.VCVTSS2USI, ops2(.reg32, .xmm_m32_er), evex(.LIG,._F3,._0F,.W0, 0x79, t1f), .vRM, .{AVX512F} ),
vec(.VCVTSS2USI, ops2(.reg64, .xmm_m32_er), evex(.LIG,._F3,._0F,.W1, 0x79, t1f), .vRM, .{AVX512F, No32} ),
// VCVTTPD2QQ
vec(.VCVTTPD2QQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPD2QQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPD2QQ, ops2(.zmm_kz, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F,.W1, 0x7A, full), .vRM, .{AVX512DQ} ),
// VCVTTPD2UDQ
vec(.VCVTTPD2UDQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._NP,._0F,.W1, 0x78, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPD2UDQ, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._NP,._0F,.W1, 0x78, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPD2UDQ, ops2(.ymm_kz, .zmm_m512_m64bcst_sae), evex(.L512,._NP,._0F,.W1, 0x78, full), .vRM, .{AVX512F} ),
// VCVTTPD2UQQ
vec(.VCVTTPD2UQQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x78, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPD2UQQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x78, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPD2UQQ, ops2(.zmm_kz, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F,.W1, 0x78, full), .vRM, .{AVX512DQ} ),
// VCVTTPS2QQ
vec(.VCVTTPS2QQ, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._66,._0F,.W0, 0x7A, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPS2QQ, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._66,._0F,.W0, 0x7A, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPS2QQ, ops2(.zmm_kz, .ymm_m256_m32bcst_sae), evex(.L512,._66,._0F,.W0, 0x7A, half), .vRM, .{AVX512DQ} ),
// VCVTTPS2UDQ
vec(.VCVTTPS2UDQ, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x78, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPS2UDQ, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x78, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTTPS2UDQ, ops2(.zmm_kz, .zmm_m512_m32bcst_sae), evex(.L512,._NP,._0F,.W0, 0x78, full), .vRM, .{AVX512F} ),
// VCVTTPS2UQQ
vec(.VCVTTPS2UQQ, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._66,._0F,.W0, 0x78, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPS2UQQ, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._66,._0F,.W0, 0x78, half), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTTPS2UQQ, ops2(.zmm_kz, .ymm_m256_m32bcst_sae), evex(.L512,._66,._0F,.W0, 0x78, half), .vRM, .{AVX512DQ} ),
// VCVTTSD2USI
vec(.VCVTTSD2USI, ops2(.reg32, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W0, 0x78, t1f), .vRM, .{AVX512F} ),
vec(.VCVTTSD2USI, ops2(.reg64, .xmm_m64_sae), evex(.LIG,._F2,._0F,.W1, 0x78, t1f), .vRM, .{AVX512F, No32} ),
// VCVTTSS2USI
vec(.VCVTTSS2USI, ops2(.reg32, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W0, 0x78, t1f), .vRM, .{AVX512F} ),
vec(.VCVTTSS2USI, ops2(.reg64, .xmm_m32_sae), evex(.LIG,._F3,._0F,.W1, 0x78, t1f), .vRM, .{AVX512F, No32} ),
// VCVTUDQ2PD
vec(.VCVTUDQ2PD, ops2(.xmm_kz, .xmm_m64_m32bcst), evex(.L128,._F3,._0F,.W0, 0x7A, half), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTUDQ2PD, ops2(.ymm_kz, .xmm_m128_m32bcst), evex(.L256,._F3,._0F,.W0, 0x7A, half), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTUDQ2PD, ops2(.zmm_kz, .ymm_m256_m32bcst), evex(.L512,._F3,._0F,.W0, 0x7A, half), .vRM, .{AVX512F} ),
// VCVTUDQ2PS
vec(.VCVTUDQ2PS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._F2,._0F,.W0, 0x7A, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTUDQ2PS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._F2,._0F,.W0, 0x7A, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VCVTUDQ2PS, ops2(.zmm_kz, .zmm_m512_m32bcst_er), evex(.L512,._F2,._0F,.W0, 0x7A, full), .vRM, .{AVX512F} ),
// VCVTUQQ2PD
vec(.VCVTUQQ2PD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._F3,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTUQQ2PD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._F3,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTUQQ2PD, ops2(.zmm_kz, .zmm_m512_m64bcst_er), evex(.L512,._F3,._0F,.W1, 0x7A, full), .vRM, .{AVX512DQ} ),
// VCVTUQQ2PS
vec(.VCVTUQQ2PS, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._F2,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTUQQ2PS, ops2(.xmm_kz, .ymm_m256_m64bcst), evex(.L256,._F2,._0F,.W1, 0x7A, full), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VCVTUQQ2PS, ops2(.ymm_kz, .zmm_m512_m64bcst_er), evex(.L512,._F2,._0F,.W1, 0x7A, full), .vRM, .{AVX512DQ} ),
// VCVTUSI2SD
vec(.VCVTUSI2SD, ops3(.xmm, .xmm, .rm32), evex(.LIG,._F2,._0F,.W0, 0x7B, t1s), .RVM, .{AVX512F} ),
vec(.VCVTUSI2SD, ops3(.xmm, .xmm, .rm64_er), evex(.LIG,._F2,._0F,.W1, 0x7B, t1s), .RVM, .{AVX512F, No32} ),
// VCVTUSI2SS
vec(.VCVTUSI2SS, ops3(.xmm, .xmm, .rm32_er), evex(.LIG,._F3,._0F,.W0, 0x7B, t1s), .RVM, .{AVX512F} ),
vec(.VCVTUSI2SS, ops3(.xmm, .xmm, .rm64_er), evex(.LIG,._F3,._0F,.W1, 0x7B, t1s), .RVM, .{AVX512F, No32} ),
// VDBPSADBW
vec(.VDBPSADBW, ops4(.xmm_kz,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W0, 0x42, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VDBPSADBW, ops4(.ymm_kz,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W0, 0x42, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VDBPSADBW, ops4(.zmm_kz,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W0, 0x42, fmem), .RVMI,.{AVX512BW} ),
// VEXPANDPD
vec(.VEXPANDPD, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x88, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VEXPANDPD, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x88, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VEXPANDPD, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x88, t1s), .vRM, .{AVX512F} ),
// VEXPANDPS
vec(.VEXPANDPS, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x88, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VEXPANDPS, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x88, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VEXPANDPS, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x88, t1s), .vRM, .{AVX512F} ),
// VEXTRACTF (128, F32x4, 64x2, 32x8, 64x4)
// VEXTRACTF128
vec(.VEXTRACTF128, ops3(.xmml_m128, .ymml, .imm8), vex(.L256,._66,._0F3A,.W0, 0x19), .vMRI,.{AVX} ),
// VEXTRACTF32X4
vec(.VEXTRACTF32X4, ops3(.xmm_m128_kz, .ymm, .imm8), evex(.L256,._66,._0F3A,.W0, 0x19, tup4), .vMRI,.{AVX512VL, AVX512F} ),
vec(.VEXTRACTF32X4, ops3(.xmm_m128_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W0, 0x19, tup4), .vMRI,.{AVX512F} ),
// VEXTRACTF64X2
vec(.VEXTRACTF64X2, ops3(.xmm_m128_kz, .ymm, .imm8), evex(.L256,._66,._0F3A,.W1, 0x19, tup2), .vMRI,.{AVX512VL, AVX512DQ} ),
vec(.VEXTRACTF64X2, ops3(.xmm_m128_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W1, 0x19, tup2), .vMRI,.{AVX512DQ} ),
// VEXTRACTF32X8
vec(.VEXTRACTF32X8, ops3(.ymm_m256_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W0, 0x1B, tup8), .vMRI,.{AVX512DQ} ),
// VEXTRACTF64X4
vec(.VEXTRACTF64X4, ops3(.ymm_m256_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W1, 0x1B, tup4), .vMRI,.{AVX512F} ),
// VEXTRACTI (128, F32x4, 64x2, 32x8, 64x4)
// VEXTRACTI128
vec(.VEXTRACTI128, ops3(.xmml_m128, .ymml, .imm8), vex(.L256,._66,._0F3A,.W0, 0x39), .vMRI,.{AVX2} ),
// VEXTRACTI32X4
vec(.VEXTRACTI32X4, ops3(.xmm_m128_kz, .ymm, .imm8), evex(.L256,._66,._0F3A,.W0, 0x39, tup4), .vMRI,.{AVX512VL, AVX512F} ),
vec(.VEXTRACTI32X4, ops3(.xmm_m128_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W0, 0x39, tup4), .vMRI,.{AVX512F} ),
// VEXTRACTI64X2
vec(.VEXTRACTI64X2, ops3(.xmm_m128_kz, .ymm, .imm8), evex(.L256,._66,._0F3A,.W1, 0x39, tup2), .vMRI,.{AVX512VL, AVX512DQ} ),
vec(.VEXTRACTI64X2, ops3(.xmm_m128_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W1, 0x39, tup2), .vMRI,.{AVX512DQ} ),
// VEXTRACTI32X8
vec(.VEXTRACTI32X8, ops3(.ymm_m256_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W0, 0x3B, tup8), .vMRI,.{AVX512DQ} ),
// VEXTRACTI64X4
vec(.VEXTRACTI64X4, ops3(.ymm_m256_kz, .zmm, .imm8), evex(.L512,._66,._0F3A,.W1, 0x3B, tup4), .vMRI,.{AVX512F} ),
// VFIXUPIMMPD
vec(.VFIXUPIMMPD, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x54, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VFIXUPIMMPD, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x54, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VFIXUPIMMPD, ops4(.zmm_kz,.ymm,.zmm_m512_m64bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W1, 0x54, full), .RVMI,.{AVX512F} ),
// VFIXUPIMMPS
vec(.VFIXUPIMMPS, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x54, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VFIXUPIMMPS, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x54, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VFIXUPIMMPS, ops4(.zmm_kz,.ymm,.zmm_m512_m32bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W0, 0x54, full), .RVMI,.{AVX512F} ),
// VFIXUPIMMSD
vec(.VFIXUPIMMSD, ops4(.xmm_kz,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x55, t1s), .RVMI,.{AVX512VL, AVX512F} ),
// VFIXUPIMMSS
vec(.VFIXUPIMMSS, ops4(.xmm_kz,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x55, t1s), .RVMI,.{AVX512VL, AVX512F} ),
// VFMADD132PD / VFMADD213PD / VFMADD231PD
vec(.VFMADD132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x98), .RVM, .{FMA} ),
vec(.VFMADD132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x98), .RVM, .{FMA} ),
vec(.VFMADD132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x98, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x98, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x98, full), .RVM, .{AVX512F} ),
//
vec(.VFMADD213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xA8), .RVM, .{FMA} ),
vec(.VFMADD213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xA8), .RVM, .{FMA} ),
vec(.VFMADD213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xA8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xA8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xA8, full), .RVM, .{AVX512F} ),
//
vec(.VFMADD231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xB8), .RVM, .{FMA} ),
vec(.VFMADD231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xB8), .RVM, .{FMA} ),
vec(.VFMADD231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xB8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xB8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xB8, full), .RVM, .{AVX512F} ),
// VFMADD132PS / VFMADD213PS / VFMADD231PS
vec(.VFMADD132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x98), .RVM, .{FMA} ),
vec(.VFMADD132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x98), .RVM, .{FMA} ),
vec(.VFMADD132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x98, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x98, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x98, full), .RVM, .{AVX512F} ),
//
vec(.VFMADD213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xA8), .RVM, .{FMA} ),
vec(.VFMADD213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xA8), .RVM, .{FMA} ),
vec(.VFMADD213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xA8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xA8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xA8, full), .RVM, .{AVX512F} ),
//
vec(.VFMADD231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xB8), .RVM, .{FMA} ),
vec(.VFMADD231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xB8), .RVM, .{FMA} ),
vec(.VFMADD231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xB8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xB8, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADD231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xB8, full), .RVM, .{AVX512F} ),
// VFMADD132SD / VFMADD213SD / VFMADD231SD
vec(.VFMADD132SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0x99), .RVM, .{FMA} ),
vec(.VFMADD132SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0x99, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMADD213SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xA9), .RVM, .{FMA} ),
vec(.VFMADD213SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xA9, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMADD231SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xB9), .RVM, .{FMA} ),
vec(.VFMADD231SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xB9, t1s), .RVM, .{AVX512F} ),
// VFMADD132SS / VFMADD213SS / VFMADD231SS
vec(.VFMADD132SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0x99), .RVM, .{FMA} ),
vec(.VFMADD132SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0x99, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMADD213SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xA9), .RVM, .{FMA} ),
vec(.VFMADD213SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xA9, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMADD231SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xB9), .RVM, .{FMA} ),
vec(.VFMADD231SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xB9, t1s), .RVM, .{AVX512F} ),
// VFMADDSUB132PD / VFMADDSUB213PD / VFMADDSUB231PD
vec(.VFMADDSUB132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x96), .RVM, .{FMA} ),
vec(.VFMADDSUB132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x96), .RVM, .{FMA} ),
vec(.VFMADDSUB132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x96, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x96, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x96, full), .RVM, .{AVX512F} ),
//
vec(.VFMADDSUB213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xA6), .RVM, .{FMA} ),
vec(.VFMADDSUB213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xA6), .RVM, .{FMA} ),
vec(.VFMADDSUB213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xA6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xA6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xA6, full), .RVM, .{AVX512F} ),
//
vec(.VFMADDSUB231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xB6), .RVM, .{FMA} ),
vec(.VFMADDSUB231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xB6), .RVM, .{FMA} ),
vec(.VFMADDSUB231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xB6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xB6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xB6, full), .RVM, .{AVX512F} ),
// VFMADDSUB132PS / VFMADDSUB213PS / VFMADDSUB231PS
vec(.VFMADDSUB132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x96), .RVM, .{FMA} ),
vec(.VFMADDSUB132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x96), .RVM, .{FMA} ),
vec(.VFMADDSUB132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x96, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x96, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x96, full), .RVM, .{AVX512F} ),
//
vec(.VFMADDSUB213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xA6), .RVM, .{FMA} ),
vec(.VFMADDSUB213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xA6), .RVM, .{FMA} ),
vec(.VFMADDSUB213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xA6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xA6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xA6, full), .RVM, .{AVX512F} ),
//
vec(.VFMADDSUB231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xB6), .RVM, .{FMA} ),
vec(.VFMADDSUB231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xB6), .RVM, .{FMA} ),
vec(.VFMADDSUB231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xB6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xB6, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMADDSUB231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xB6, full), .RVM, .{AVX512F} ),
// VFMSUBADD132PD / VFMSUBADD213PD / VFMSUBADD231PD
vec(.VFMSUBADD132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x97), .RVM, .{FMA} ),
vec(.VFMSUBADD132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x97), .RVM, .{FMA} ),
vec(.VFMSUBADD132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x97, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x97, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x97, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUBADD213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xA7), .RVM, .{FMA} ),
vec(.VFMSUBADD213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xA7), .RVM, .{FMA} ),
vec(.VFMSUBADD213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xA7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xA7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xA7, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUBADD231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xB7), .RVM, .{FMA} ),
vec(.VFMSUBADD231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xB7), .RVM, .{FMA} ),
vec(.VFMSUBADD231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xB7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xB7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xB7, full), .RVM, .{AVX512F} ),
// VFMSUBADD132PS / VFMSUBADD213PS / VFMSUBADD231PS
vec(.VFMSUBADD132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x97), .RVM, .{FMA} ),
vec(.VFMSUBADD132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x97), .RVM, .{FMA} ),
vec(.VFMSUBADD132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x97, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x97, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x97, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUBADD213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xA7), .RVM, .{FMA} ),
vec(.VFMSUBADD213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xA7), .RVM, .{FMA} ),
vec(.VFMSUBADD213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xA7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xA7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xA7, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUBADD231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xB7), .RVM, .{FMA} ),
vec(.VFMSUBADD231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xB7), .RVM, .{FMA} ),
vec(.VFMSUBADD231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xB7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xB7, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUBADD231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xB7, full), .RVM, .{AVX512F} ),
// VFMSUB132PD / VFMSUB213PD / VFMSUB231PD
vec(.VFMSUB132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x9A), .RVM, .{FMA} ),
vec(.VFMSUB132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x9A), .RVM, .{FMA} ),
vec(.VFMSUB132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x9A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x9A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x9A, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUB213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xAA), .RVM, .{FMA} ),
vec(.VFMSUB213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xAA), .RVM, .{FMA} ),
vec(.VFMSUB213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xAA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xAA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xAA, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUB231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xBA), .RVM, .{FMA} ),
vec(.VFMSUB231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xBA), .RVM, .{FMA} ),
vec(.VFMSUB231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xBA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xBA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xBA, full), .RVM, .{AVX512F} ),
// VFMSUB132PS / VFMSUB213PS / VFMSUB231PS
vec(.VFMSUB132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x9A), .RVM, .{FMA} ),
vec(.VFMSUB132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x9A), .RVM, .{FMA} ),
vec(.VFMSUB132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x9A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x9A, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x9A, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUB213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xAA), .RVM, .{FMA} ),
vec(.VFMSUB213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xAA), .RVM, .{FMA} ),
vec(.VFMSUB213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xAA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xAA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xAA, full), .RVM, .{AVX512F} ),
//
vec(.VFMSUB231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xBA), .RVM, .{FMA} ),
vec(.VFMSUB231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xBA), .RVM, .{FMA} ),
vec(.VFMSUB231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xBA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xBA, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFMSUB231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xBA, full), .RVM, .{AVX512F} ),
// VFMSUB132SD / VFMSUB213SD / VFMSUB231SD
vec(.VFMSUB132SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0x9B), .RVM, .{FMA} ),
vec(.VFMSUB132SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0x9B, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMSUB213SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xAB), .RVM, .{FMA} ),
vec(.VFMSUB213SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xAB, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMSUB231SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xBB), .RVM, .{FMA} ),
vec(.VFMSUB231SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xBB, t1s), .RVM, .{AVX512F} ),
// VFMSUB132SS / VFMSUB213SS / VFMSUB231SS
vec(.VFMSUB132SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0x9B), .RVM, .{FMA} ),
vec(.VFMSUB132SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0x9B, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMSUB213SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xAB), .RVM, .{FMA} ),
vec(.VFMSUB213SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xAB, t1s), .RVM, .{AVX512F} ),
//
vec(.VFMSUB231SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xBB), .RVM, .{FMA} ),
vec(.VFMSUB231SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xBB, t1s), .RVM, .{AVX512F} ),
// VFNMADD132PD / VFNMADD213PD / VFNMADD231PD
vec(.VFNMADD132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x9C), .RVM, .{FMA} ),
vec(.VFNMADD132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x9C), .RVM, .{FMA} ),
vec(.VFNMADD132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x9C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x9C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x9C, full), .RVM, .{AVX512F} ),
//
vec(.VFNMADD213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xAC), .RVM, .{FMA} ),
vec(.VFNMADD213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xAC), .RVM, .{FMA} ),
vec(.VFNMADD213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xAC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xAC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xAC, full), .RVM, .{AVX512F} ),
//
vec(.VFNMADD231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xBC), .RVM, .{FMA} ),
vec(.VFNMADD231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xBC), .RVM, .{FMA} ),
vec(.VFNMADD231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xBC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xBC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xBC, full), .RVM, .{AVX512F} ),
// VFNMADD132PS / VFNMADD213PS / VFNMADD231PS
vec(.VFNMADD132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x9C), .RVM, .{FMA} ),
vec(.VFNMADD132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x9C), .RVM, .{FMA} ),
vec(.VFNMADD132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x9C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x9C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x9C, full), .RVM, .{AVX512F} ),
//
vec(.VFNMADD213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xAC), .RVM, .{FMA} ),
vec(.VFNMADD213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xAC), .RVM, .{FMA} ),
vec(.VFNMADD213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xAC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xAC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xAC, full), .RVM, .{AVX512F} ),
//
vec(.VFNMADD231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xBC), .RVM, .{FMA} ),
vec(.VFNMADD231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xBC), .RVM, .{FMA} ),
vec(.VFNMADD231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xBC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xBC, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMADD231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xBC, full), .RVM, .{AVX512F} ),
// VFNMADD132SD / VFNMADD213SD / VFNMADD231SD
vec(.VFNMADD132SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0x9D), .RVM, .{FMA} ),
vec(.VFNMADD132SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0x9D, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMADD213SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xAD), .RVM, .{FMA} ),
vec(.VFNMADD213SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xAD, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMADD231SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xBD), .RVM, .{FMA} ),
vec(.VFNMADD231SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xBD, t1s), .RVM, .{AVX512F} ),
// VFNMADD132SS / VFNMADD213SS / VFNMADD231SS
vec(.VFNMADD132SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0x9D), .RVM, .{FMA} ),
vec(.VFNMADD132SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0x9D, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMADD213SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xAD), .RVM, .{FMA} ),
vec(.VFNMADD213SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xAD, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMADD231SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xBD), .RVM, .{FMA} ),
vec(.VFNMADD231SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xBD, t1s), .RVM, .{AVX512F} ),
// VFNMSUB132PD / VFNMSUB213PD / VFNMSUB231PD
vec(.VFNMSUB132PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x9E), .RVM, .{FMA} ),
vec(.VFNMSUB132PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x9E), .RVM, .{FMA} ),
vec(.VFNMSUB132PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x9E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB132PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x9E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB132PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x9E, full), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB213PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xAE), .RVM, .{FMA} ),
vec(.VFNMSUB213PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xAE), .RVM, .{FMA} ),
vec(.VFNMSUB213PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xAE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB213PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xAE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB213PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xAE, full), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB231PD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0xBE), .RVM, .{FMA} ),
vec(.VFNMSUB231PD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0xBE), .RVM, .{FMA} ),
vec(.VFNMSUB231PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xBE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB231PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xBE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB231PD, ops3(.zmm_kz,.ymm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0xBE, full), .RVM, .{AVX512F} ),
// VFNMSUB132PS / VFNMSUB213PS / VFNMSUB231PS
vec(.VFNMSUB132PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x9E), .RVM, .{FMA} ),
vec(.VFNMSUB132PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x9E), .RVM, .{FMA} ),
vec(.VFNMSUB132PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x9E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB132PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x9E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB132PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x9E, full), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB213PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xAE), .RVM, .{FMA} ),
vec(.VFNMSUB213PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xAE), .RVM, .{FMA} ),
vec(.VFNMSUB213PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xAE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB213PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xAE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB213PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xAE, full), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB231PS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0xBE), .RVM, .{FMA} ),
vec(.VFNMSUB231PS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0xBE), .RVM, .{FMA} ),
vec(.VFNMSUB231PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xBE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB231PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xBE, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VFNMSUB231PS, ops3(.zmm_kz,.ymm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0xBE, full), .RVM, .{AVX512F} ),
// VFNMSUB132SD / VFNMSUB213SD / VFNMSUB231SD
vec(.VFNMSUB132SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0x9F), .RVM, .{FMA} ),
vec(.VFNMSUB132SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0x9F, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB213SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xAF), .RVM, .{FMA} ),
vec(.VFNMSUB213SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xAF, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB231SD, ops3(.xmml, .xmml, .xmml_m64), vex(.LIG,._66,._0F38,.W1, 0xBF), .RVM, .{FMA} ),
vec(.VFNMSUB231SD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0xBF, t1s), .RVM, .{AVX512F} ),
// VFNMSUB132SS / VFNMSUB213SS / VFNMSUB231SS
vec(.VFNMSUB132SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0x9F), .RVM, .{FMA} ),
vec(.VFNMSUB132SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0x9F, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB213SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xAF), .RVM, .{FMA} ),
vec(.VFNMSUB213SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xAF, t1s), .RVM, .{AVX512F} ),
//
vec(.VFNMSUB231SS, ops3(.xmml, .xmml, .xmml_m32), vex(.LIG,._66,._0F38,.W0, 0xBF), .RVM, .{FMA} ),
vec(.VFNMSUB231SS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0xBF, t1s), .RVM, .{AVX512F} ),
// VFPCLASSPD
vec(.VFPCLASSPD, ops3(.reg_k_k,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x66, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VFPCLASSPD, ops3(.reg_k_k,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x66, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VFPCLASSPD, ops3(.reg_k_k,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x66, full), .vRMI,.{AVX512DQ} ),
// VFPCLASSPS
vec(.VFPCLASSPS, ops3(.reg_k_k,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x66, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VFPCLASSPS, ops3(.reg_k_k,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x66, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VFPCLASSPS, ops3(.reg_k_k,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x66, full), .vRMI,.{AVX512DQ} ),
// VFPCLASSSD
vec(.VFPCLASSSD, ops3(.reg_k_k,.xmm_m64,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x67, t1s), .vRMI,.{AVX512DQ} ),
// VFPCLASSSS
vec(.VFPCLASSSS, ops3(.reg_k_k,.xmm_m32,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x67, t1s), .vRMI,.{AVX512DQ} ),
// VGATHERDPD / VGATHERQPD
vec(.VGATHERDPD, ops3(.xmml, .vm32xl, .xmml), vex(.L128,._66,._0F38,.W1, 0x92), .RMV, .{AVX2} ),
vec(.VGATHERDPD, ops3(.ymml, .vm32xl, .ymml), vex(.L256,._66,._0F38,.W1, 0x92), .RMV, .{AVX2} ),
vec(.VGATHERDPD, ops2(.xmm_kz, .vm32x), evex(.L128,._66,._0F38,.W1, 0x92, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERDPD, ops2(.ymm_kz, .vm32x), evex(.L256,._66,._0F38,.W1, 0x92, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERDPD, ops2(.zmm_kz, .vm32y), evex(.L512,._66,._0F38,.W1, 0x92, t1s), .RMV, .{AVX512F} ),
//
vec(.VGATHERQPD, ops3(.xmml, .vm64xl, .xmml), vex(.L128,._66,._0F38,.W1, 0x93), .RMV, .{AVX2} ),
vec(.VGATHERQPD, ops3(.ymml, .vm64yl, .ymml), vex(.L256,._66,._0F38,.W1, 0x93), .RMV, .{AVX2} ),
vec(.VGATHERQPD, ops2(.xmm_kz, .vm64x), evex(.L128,._66,._0F38,.W1, 0x93, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERQPD, ops2(.ymm_kz, .vm64y), evex(.L256,._66,._0F38,.W1, 0x93, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERQPD, ops2(.zmm_kz, .vm64z), evex(.L512,._66,._0F38,.W1, 0x93, t1s), .RMV, .{AVX512F} ),
// VGATHERDPS / VGATHERQPS
vec(.VGATHERDPS, ops3(.xmml, .vm32xl, .xmml), vex(.L128,._66,._0F38,.W0, 0x92), .RMV, .{AVX2} ),
vec(.VGATHERDPS, ops3(.ymml, .vm32yl, .ymml), vex(.L256,._66,._0F38,.W0, 0x92), .RMV, .{AVX2} ),
vec(.VGATHERDPS, ops2(.xmm_kz, .vm32x), evex(.L128,._66,._0F38,.W0, 0x92, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERDPS, ops2(.ymm_kz, .vm32y), evex(.L256,._66,._0F38,.W0, 0x92, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERDPS, ops2(.zmm_kz, .vm32z), evex(.L512,._66,._0F38,.W0, 0x92, t1s), .RMV, .{AVX512F} ),
//
vec(.VGATHERQPS, ops3(.xmml, .vm64xl, .xmml), vex(.L128,._66,._0F38,.W0, 0x93), .RMV, .{AVX2} ),
vec(.VGATHERQPS, ops3(.xmml, .vm64yl, .xmml), vex(.L256,._66,._0F38,.W0, 0x93), .RMV, .{AVX2} ),
vec(.VGATHERQPS, ops2(.xmm_kz, .vm64x), evex(.L128,._66,._0F38,.W0, 0x93, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERQPS, ops2(.xmm_kz, .vm64y), evex(.L256,._66,._0F38,.W0, 0x93, t1s), .RMV, .{AVX512VL, AVX512F} ),
vec(.VGATHERQPS, ops2(.ymm_kz, .vm64z), evex(.L512,._66,._0F38,.W0, 0x93, t1s), .RMV, .{AVX512F} ),
// VGETEXPPD
vec(.VGETEXPPD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x42, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VGETEXPPD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x42, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VGETEXPPD, ops2(.zmm_kz, .zmm_m512_m64bcst_sae), evex(.L512,._66,._0F38,.W1, 0x42, full), .vRM, .{AVX512F} ),
// VGETEXPPS
vec(.VGETEXPPS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x42, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VGETEXPPS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x42, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VGETEXPPS, ops2(.zmm_kz, .zmm_m512_m32bcst_sae), evex(.L512,._66,._0F38,.W0, 0x42, full), .vRM, .{AVX512F} ),
// VGETEXPSD
vec(.VGETEXPSD, ops3(.xmm_kz, .xmm, .xmm_m64_sae), evex(.LIG,._66,._0F38,.W1, 0x43, t1s), .RVM, .{AVX512F} ),
// VGETEXPSS
vec(.VGETEXPSS, ops3(.xmm_kz, .xmm, .xmm_m32_sae), evex(.LIG,._66,._0F38,.W0, 0x43, t1s), .RVM, .{AVX512F} ),
// VGETMANTPD
vec(.VGETMANTPD, ops3(.xmm_kz,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x26, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VGETMANTPD, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x26, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VGETMANTPD, ops3(.zmm_kz,.zmm_m512_m64bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W1, 0x26, full), .vRMI,.{AVX512F} ),
// VGETMANTPS
vec(.VGETMANTPS, ops3(.xmm_kz,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x26, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VGETMANTPS, ops3(.ymm_kz,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x26, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VGETMANTPS, ops3(.zmm_kz,.zmm_m512_m32bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W0, 0x26, full), .vRMI,.{AVX512F} ),
// VGETMANTSD
vec(.VGETMANTSD, ops4(.xmm_kz,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x27, t1s), .RVMI,.{AVX512F} ),
// VGETMANTSS
vec(.VGETMANTSS, ops4(.xmm_kz,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x27, t1s), .RVMI,.{AVX512F} ),
// vecERTF (128, F32x4, 64x2, 32x8, 64x4)
vec(.VINSERTF128, ops4(.ymml,.ymml,.xmml_m128,.imm8), vex(.L256,._66,._0F3A,.W0, 0x18), .RVMI,.{AVX} ),
// vecERTF32X4
vec(.VINSERTF32X4, ops4(.ymm_kz,.ymm,.xmm_m128,.imm8), evex(.L256,._66,._0F3A,.W0, 0x18, tup4), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VINSERTF32X4, ops4(.zmm_kz,.zmm,.xmm_m128,.imm8), evex(.L512,._66,._0F3A,.W0, 0x18, tup4), .RVMI,.{AVX512F} ),
// vecERTF64X2
vec(.VINSERTF64X2, ops4(.ymm_kz,.ymm,.xmm_m128,.imm8), evex(.L256,._66,._0F3A,.W1, 0x18, tup2), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VINSERTF64X2, ops4(.zmm_kz,.zmm,.xmm_m128,.imm8), evex(.L512,._66,._0F3A,.W1, 0x18, tup2), .RVMI,.{AVX512DQ} ),
// vecERTF32X8
vec(.VINSERTF32X8, ops4(.zmm_kz,.zmm,.ymm_m256,.imm8), evex(.L512,._66,._0F3A,.W0, 0x1A, tup8), .RVMI,.{AVX512DQ} ),
// vecERTF64X4
vec(.VINSERTF64X4, ops4(.zmm_kz,.zmm,.ymm_m256,.imm8), evex(.L512,._66,._0F3A,.W1, 0x1A, tup4), .RVMI,.{AVX512F} ),
// vecERTI (128, F32x4, 64x2, 32x8, 64x4)
vec(.VINSERTI128, ops4(.ymml,.ymml,.xmml_m128,.imm8), vex(.L256,._66,._0F3A,.W0, 0x18), .RVMI,.{AVX} ),
// vecERTI32X4
vec(.VINSERTI32X4, ops4(.ymm_kz,.ymm,.xmm_m128,.imm8), evex(.L256,._66,._0F3A,.W0, 0x18, tup4), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VINSERTI32X4, ops4(.zmm_kz,.zmm,.xmm_m128,.imm8), evex(.L512,._66,._0F3A,.W0, 0x18, tup4), .RVMI,.{AVX512F} ),
// vecERTI64X2
vec(.VINSERTI64X2, ops4(.ymm_kz,.ymm,.xmm_m128,.imm8), evex(.L256,._66,._0F3A,.W1, 0x18, tup2), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VINSERTI64X2, ops4(.zmm_kz,.zmm,.xmm_m128,.imm8), evex(.L512,._66,._0F3A,.W1, 0x18, tup2), .RVMI,.{AVX512DQ} ),
// vecERTI32X8
vec(.VINSERTI32X8, ops4(.zmm_kz,.zmm,.ymm_m256,.imm8), evex(.L512,._66,._0F3A,.W0, 0x1A, tup8), .RVMI,.{AVX512DQ} ),
// vecERTI64X4
vec(.VINSERTI64X4, ops4(.zmm_kz,.zmm,.ymm_m256,.imm8), evex(.L512,._66,._0F3A,.W1, 0x1A, tup4), .RVMI,.{AVX512F} ),
// VMASKMOV
// VMASKMOVPD
vec(.VMASKMOVPD, ops3(.xmml,.xmml,.rm_mem128), vex(.L128,._66,._0F38,.W0, 0x2D), .RVM, .{AVX} ),
vec(.VMASKMOVPD, ops3(.ymml,.ymml,.rm_mem256), vex(.L256,._66,._0F38,.W0, 0x2D), .RVM, .{AVX} ),
vec(.VMASKMOVPD, ops3(.rm_mem128,.xmml,.xmml), vex(.L128,._66,._0F38,.W0, 0x2F), .MVR, .{AVX} ),
vec(.VMASKMOVPD, ops3(.rm_mem256,.ymml,.ymml), vex(.L256,._66,._0F38,.W0, 0x2F), .MVR, .{AVX} ),
// VMASKMOVPS
vec(.VMASKMOVPS, ops3(.xmml,.xmml,.rm_mem128), vex(.L128,._66,._0F38,.W0, 0x2C), .RVM, .{AVX} ),
vec(.VMASKMOVPS, ops3(.ymml,.ymml,.rm_mem256), vex(.L256,._66,._0F38,.W0, 0x2C), .RVM, .{AVX} ),
vec(.VMASKMOVPS, ops3(.rm_mem128,.xmml,.xmml), vex(.L128,._66,._0F38,.W0, 0x2E), .MVR, .{AVX} ),
vec(.VMASKMOVPS, ops3(.rm_mem256,.ymml,.ymml), vex(.L256,._66,._0F38,.W0, 0x2E), .MVR, .{AVX} ),
// VPBLENDD
vec(.VPBLENDD, ops4(.xmml,.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W0, 0x02), .RVMI,.{AVX2} ),
vec(.VPBLENDD, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W0, 0x02), .RVMI,.{AVX2} ),
// VPBLENDMB / VPBLENDMW
// VPBLENDMB
vec(.VPBLENDMB, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x66, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPBLENDMB, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x66, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPBLENDMB, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x66, fmem), .RVM, .{AVX512BW} ),
// VPBLENDMW
vec(.VPBLENDMW, ops3(.xmm_kz, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x66, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPBLENDMW, ops3(.ymm_kz, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x66, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPBLENDMW, ops3(.zmm_kz, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x66, fmem), .RVM, .{AVX512BW} ),
// VPBLENDMD / VPBLENDMQ
// VPBLENDMD
vec(.VPBLENDMD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x64, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPBLENDMD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x64, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPBLENDMD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x64, full), .RVM, .{AVX512F} ),
// VPBLENDMQ
vec(.VPBLENDMQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x64, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPBLENDMQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x64, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPBLENDMQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x64, full), .RVM, .{AVX512F} ),
// VPBROADCASTB / VPBROADCASTW / VPBROADCASTD / VPBROADCASTQ
// VPBROADCASTB
vec(.VPBROADCASTB, ops2(.xmml, .xmml_m8), vex(.L128,._66,._0F38,.W0, 0x78), .vRM, .{AVX2} ),
vec(.VPBROADCASTB, ops2(.ymml, .xmml_m8), vex(.L256,._66,._0F38,.W0, 0x78), .vRM, .{AVX2} ),
vec(.VPBROADCASTB, ops2(.xmm_kz, .xmm_m8), evex(.L128,._66,._0F38,.W0, 0x78, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.ymm_kz, .xmm_m8), evex(.L256,._66,._0F38,.W0, 0x78, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.zmm_kz, .xmm_m8), evex(.L512,._66,._0F38,.W0, 0x78, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTB, ops2(.xmm_kz, .rm_reg8), evex(.L128,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.ymm_kz, .rm_reg8), evex(.L256,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.zmm_kz, .rm_reg8), evex(.L512,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTB, ops2(.xmm_kz, .rm_reg32), evex(.L128,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.ymm_kz, .rm_reg32), evex(.L256,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.zmm_kz, .rm_reg32), evex(.L512,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTB, ops2(.xmm_kz, .rm_reg64), evex(.L128,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.ymm_kz, .rm_reg64), evex(.L256,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTB, ops2(.zmm_kz, .rm_reg64), evex(.L512,._66,._0F38,.W0, 0x7A, t1s), .vRM, .{AVX512BW} ),
// VPBROADCASTW
vec(.VPBROADCASTW, ops2(.xmml, .xmml_m16), vex(.L128,._66,._0F38,.W0, 0x79), .vRM, .{AVX2} ),
vec(.VPBROADCASTW, ops2(.ymml, .xmml_m16), vex(.L256,._66,._0F38,.W0, 0x79), .vRM, .{AVX2} ),
vec(.VPBROADCASTW, ops2(.xmm_kz, .xmm_m16), evex(.L128,._66,._0F38,.W0, 0x79, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.ymm_kz, .xmm_m16), evex(.L256,._66,._0F38,.W0, 0x79, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.zmm_kz, .xmm_m16), evex(.L512,._66,._0F38,.W0, 0x79, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTW, ops2(.xmm_kz, .rm_reg16), evex(.L128,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.ymm_kz, .rm_reg16), evex(.L256,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.zmm_kz, .rm_reg16), evex(.L512,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTW, ops2(.xmm_kz, .rm_reg32), evex(.L128,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.ymm_kz, .rm_reg32), evex(.L256,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.zmm_kz, .rm_reg32), evex(.L512,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512BW} ),
vec(.VPBROADCASTW, ops2(.xmm_kz, .rm_reg64), evex(.L128,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.ymm_kz, .rm_reg64), evex(.L256,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPBROADCASTW, ops2(.zmm_kz, .rm_reg64), evex(.L512,._66,._0F38,.W0, 0x7B, t1s), .vRM, .{AVX512BW} ),
// VPBROADCASTD
vec(.VPBROADCASTD, ops2(.xmml, .xmml_m32), vex(.L128,._66,._0F38,.W0, 0x58), .vRM, .{AVX2} ),
vec(.VPBROADCASTD, ops2(.ymml, .xmml_m32), vex(.L256,._66,._0F38,.W0, 0x58), .vRM, .{AVX2} ),
vec(.VPBROADCASTD, ops2(.xmm_kz, .xmm_m32), evex(.L128,._66,._0F38,.W0, 0x58, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTD, ops2(.ymm_kz, .xmm_m32), evex(.L256,._66,._0F38,.W0, 0x58, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTD, ops2(.zmm_kz, .xmm_m32), evex(.L512,._66,._0F38,.W0, 0x58, t1s), .vRM, .{AVX512F} ),
vec(.VPBROADCASTD, ops2(.xmm_kz, .rm_reg32), evex(.L128,._66,._0F38,.W0, 0x7C, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTD, ops2(.ymm_kz, .rm_reg32), evex(.L256,._66,._0F38,.W0, 0x7C, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTD, ops2(.zmm_kz, .rm_reg32), evex(.L512,._66,._0F38,.W0, 0x7C, t1s), .vRM, .{AVX512F} ),
// VPBROADCASTQ
vec(.VPBROADCASTQ, ops2(.xmml, .xmml_m64), vex(.L128,._66,._0F38,.W0, 0x59), .vRM, .{AVX2} ),
vec(.VPBROADCASTQ, ops2(.ymml, .xmml_m64), vex(.L256,._66,._0F38,.W0, 0x59), .vRM, .{AVX2} ),
vec(.VPBROADCASTQ, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.W1, 0x59, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTQ, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.W1, 0x59, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTQ, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.W1, 0x59, t1s), .vRM, .{AVX512F} ),
vec(.VPBROADCASTQ, ops2(.xmm_kz, .rm_reg64), evex(.L128,._66,._0F38,.W1, 0x7C, t1s), .vRM, .{AVX512VL, AVX512F, No32} ),
vec(.VPBROADCASTQ, ops2(.ymm_kz, .rm_reg64), evex(.L256,._66,._0F38,.W1, 0x7C, t1s), .vRM, .{AVX512VL, AVX512F, No32} ),
vec(.VPBROADCASTQ, ops2(.zmm_kz, .rm_reg64), evex(.L512,._66,._0F38,.W1, 0x7C, t1s), .vRM, .{AVX512F, No32} ),
// VPBROADCASTI32X2
vec(.VPBROADCASTI32X2, ops2(.xmm_kz, .xmm_m64), evex(.L128,._66,._0F38,.W0, 0x59, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPBROADCASTI32X2, ops2(.ymm_kz, .xmm_m64), evex(.L256,._66,._0F38,.W0, 0x59, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPBROADCASTI32X2, ops2(.zmm_kz, .xmm_m64), evex(.L512,._66,._0F38,.W0, 0x59, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
// VPBROADCASTI128
vec(.VPBROADCASTI128, ops2(.ymml, .rm_mem128), vex(.L256,._66,._0F38,.W0, 0x5A), .vRM, .{AVX2} ),
// VPBROADCASTI32X4
vec(.VPBROADCASTI32X4, ops2(.ymm_kz, .rm_mem128), evex(.L256,._66,._0F38,.W0, 0x5A, tup4), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPBROADCASTI32X4, ops2(.zmm_kz, .rm_mem128), evex(.L512,._66,._0F38,.W0, 0x5A, tup4), .vRM, .{AVX512F} ),
// VPBROADCASTI64X2
vec(.VPBROADCASTI64X2, ops2(.ymm_kz, .rm_mem128), evex(.L256,._66,._0F38,.W1, 0x5A, tup2), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPBROADCASTI64X2, ops2(.zmm_kz, .rm_mem128), evex(.L512,._66,._0F38,.W1, 0x5A, tup2), .vRM, .{AVX512DQ} ),
// VPBROADCASTI32X8
vec(.VPBROADCASTI32X8, ops2(.zmm_kz, .rm_mem256), evex(.L512,._66,._0F38,.W0, 0x5B, tup8), .vRM, .{AVX512DQ} ),
// VPBROADCASTI64X4
vec(.VPBROADCASTI64X4, ops2(.zmm_kz, .rm_mem256), evex(.L512,._66,._0F38,.W1, 0x5B, tup4), .vRM, .{AVX512F} ),
// VPBROADCASTM
// VPBROADCASTMB2Q
vec(.VPBROADCASTMB2Q, ops2(.xmm_kz, .rm_k), evex(.L128,._F3,._0F38,.W1, 0x2A, nomem), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPBROADCASTMB2Q, ops2(.ymm_kz, .rm_k), evex(.L256,._F3,._0F38,.W1, 0x2A, nomem), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPBROADCASTMB2Q, ops2(.zmm_kz, .rm_k), evex(.L512,._F3,._0F38,.W1, 0x2A, nomem), .vRM, .{AVX512CD} ),
// VPBROADCASTMW2D
vec(.VPBROADCASTMW2D, ops2(.xmm_kz, .rm_k), evex(.L128,._F3,._0F38,.W0, 0x3A, nomem), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPBROADCASTMW2D, ops2(.ymm_kz, .rm_k), evex(.L256,._F3,._0F38,.W0, 0x3A, nomem), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPBROADCASTMW2D, ops2(.zmm_kz, .rm_k), evex(.L512,._F3,._0F38,.W0, 0x3A, nomem), .vRM, .{AVX512CD} ),
// VPCMPB / VPCMPUB
// VPCMPB
vec(.VPCMPB, ops4(.reg_k_k,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W0, 0x3F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPB, ops4(.reg_k_k,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W0, 0x3F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPB, ops4(.reg_k_k,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W0, 0x3F, fmem), .RVMI,.{AVX512BW} ),
// VPCMPUB
vec(.VPCMPUB, ops4(.reg_k_k,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W0, 0x3E, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPUB, ops4(.reg_k_k,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W0, 0x3E, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPUB, ops4(.reg_k_k,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W0, 0x3E, fmem), .RVMI,.{AVX512BW} ),
// VPCMPD / VPCMPUD
// VPCMPD
vec(.VPCMPD, ops4(.reg_k_k,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x1F, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPD, ops4(.reg_k_k,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x1F, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPD, ops4(.reg_k_k,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x1F, full), .RVMI,.{AVX512F} ),
// VPCMPUD
vec(.VPCMPUD, ops4(.reg_k_k,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x1E, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPUD, ops4(.reg_k_k,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x1E, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPUD, ops4(.reg_k_k,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x1E, full), .RVMI,.{AVX512F} ),
// VPCMPQ / VPCMPUQ
// VPCMPQ
vec(.VPCMPQ, ops4(.reg_k_k,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x1F, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPQ, ops4(.reg_k_k,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x1F, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPQ, ops4(.reg_k_k,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x1F, full), .RVMI,.{AVX512F} ),
// VPCMPUQ
vec(.VPCMPUQ, ops4(.reg_k_k,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x1E, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPUQ, ops4(.reg_k_k,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x1E, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPCMPUQ, ops4(.reg_k_k,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x1E, full), .RVMI,.{AVX512F} ),
// VPCMPW / VPCMPUW
// VPCMPW
vec(.VPCMPW, ops4(.reg_k_k,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W1, 0x3F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPW, ops4(.reg_k_k,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W1, 0x3F, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPW, ops4(.reg_k_k,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W1, 0x3F, fmem), .RVMI,.{AVX512BW} ),
// VPCMPUW
vec(.VPCMPUW, ops4(.reg_k_k,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W1, 0x3E, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPUW, ops4(.reg_k_k,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W1, 0x3E, fmem), .RVMI,.{AVX512VL, AVX512BW} ),
vec(.VPCMPUW, ops4(.reg_k_k,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W1, 0x3E, fmem), .RVMI,.{AVX512BW} ),
// VPCOMPRESSB / VPCOMPRESSW
// VPCOMPRESSB
vec(.VPCOMPRESSB, ops2(.rm_mem128_k, .xmm), evex(.L128,._66,._0F38,.W0, 0x63, t1s), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSB, ops2(.rm_xmm_kz, .xmm), evex(.L128,._66,._0F38,.W0, 0x63, nomem), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSB, ops2(.rm_mem256_k, .ymm), evex(.L256,._66,._0F38,.W0, 0x63, t1s), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSB, ops2(.rm_ymm_kz, .ymm), evex(.L256,._66,._0F38,.W0, 0x63, nomem), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSB, ops2(.rm_mem512_k, .zmm), evex(.L512,._66,._0F38,.W0, 0x63, t1s), .vMR, .{AVX512_VBMI2} ),
vec(.VPCOMPRESSB, ops2(.rm_zmm_kz, .zmm), evex(.L512,._66,._0F38,.W0, 0x63, nomem), .vMR, .{AVX512_VBMI2} ),
// VPCOMPRESSW
vec(.VPCOMPRESSW, ops2(.rm_mem128_k, .xmm), evex(.L128,._66,._0F38,.W1, 0x63, t1s), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSW, ops2(.rm_xmm_kz, .xmm), evex(.L128,._66,._0F38,.W1, 0x63, nomem), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSW, ops2(.rm_mem256_k, .ymm), evex(.L256,._66,._0F38,.W1, 0x63, t1s), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSW, ops2(.rm_ymm_kz, .ymm), evex(.L256,._66,._0F38,.W1, 0x63, nomem), .vMR, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPCOMPRESSW, ops2(.rm_mem512_k, .zmm), evex(.L512,._66,._0F38,.W1, 0x63, t1s), .vMR, .{AVX512_VBMI2} ),
vec(.VPCOMPRESSW, ops2(.rm_zmm_kz, .zmm), evex(.L512,._66,._0F38,.W1, 0x63, nomem), .vMR, .{AVX512_VBMI2} ),
// VPCOMPRESSD
vec(.VPCOMPRESSD, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F38,.W0, 0x8B, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPCOMPRESSD, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F38,.W0, 0x8B, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPCOMPRESSD, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F38,.W0, 0x8B, t1s), .vMR, .{AVX512F} ),
// VPCOMPRESSQ
vec(.VPCOMPRESSQ, ops2(.xmm_m128_kz, .xmm), evex(.L128,._66,._0F38,.W1, 0x8B, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPCOMPRESSQ, ops2(.ymm_m256_kz, .ymm), evex(.L256,._66,._0F38,.W1, 0x8B, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPCOMPRESSQ, ops2(.zmm_m512_kz, .zmm), evex(.L512,._66,._0F38,.W1, 0x8B, t1s), .vMR, .{AVX512F} ),
// VPCONFLICTD / VPCONFLICTQ
// VPCONFLICTD
vec(.VPCONFLICTD, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0xC4, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPCONFLICTD, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0xC4, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPCONFLICTD, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0xC4, full), .vRM, .{AVX512CD} ),
// VPCONFLICTQ
vec(.VPCONFLICTQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xC4, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPCONFLICTQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xC4, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPCONFLICTQ, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0xC4, full), .vRM, .{AVX512CD} ),
// VPDPBUSD
vec(.VPDPBUSD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x50, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPBUSD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x50, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPBUSD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x50, full), .RVM, .{AVX512_VNNI} ),
// VPDPBUSDS
vec(.VPDPBUSDS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x51, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPBUSDS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x51, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPBUSDS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x51, full), .RVM, .{AVX512_VNNI} ),
// VPDPWSSD
vec(.VPDPWSSD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x52, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPWSSD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x52, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPWSSD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x52, full), .RVM, .{AVX512_VNNI} ),
// VPDPWSSDS
vec(.VPDPWSSDS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x53, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPWSSDS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x53, full), .RVM, .{AVX512VL, AVX512_VNNI} ),
vec(.VPDPWSSDS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x53, full), .RVM, .{AVX512_VNNI} ),
// VPERM2F128
vec(.VPERM2F128, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W0, 0x06), .RVMI,.{AVX} ),
// VPERM2I128
vec(.VPERM2I128, ops4(.ymml,.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W0, 0x46), .RVMI,.{AVX2} ),
// VPERMB
vec(.VPERMB, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W0, 0x8D, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMB, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W0, 0x8D, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMB, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W0, 0x8D, fmem), .RVM, .{AVX512_VBMI} ),
// VPERMD / VPERMW
// VPERMD
vec(.VPERMD, ops3(.ymml,.ymml,.ymml_m256), vex(.L256,._66,._0F38,.W0, 0x36), .RVM, .{AVX2} ),
vec(.VPERMD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x36, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x36, full), .RVM, .{AVX512F} ),
// VPERMW
vec(.VPERMW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x8D, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x8D, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x8D, fmem), .RVM, .{AVX512BW} ),
// VPERMI2B
vec(.VPERMI2B, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W0, 0x75, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMI2B, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W0, 0x75, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMI2B, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W0, 0x75, fmem), .RVM, .{AVX512_VBMI} ),
// VPERMI2W / VPERMI2D / VPERMI2Q / VPERMI2PS / VPERMI2PD
// VPERMI2W
vec(.VPERMI2W, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x75, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMI2W, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x75, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMI2W, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x75, fmem), .RVM, .{AVX512BW} ),
// VPERMI2D
vec(.VPERMI2D, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x76, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMI2D, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x76, full), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMI2D, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x76, full), .RVM, .{AVX512BW} ),
// VPERMI2Q
vec(.VPERMI2Q, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x76, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2Q, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x76, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2Q, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x76, full), .RVM, .{AVX512F} ),
// VPERMI2PS
vec(.VPERMI2PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x77, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x77, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2PS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x77, full), .RVM, .{AVX512F} ),
// VPERMI2PD
vec(.VPERMI2PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x77, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x77, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMI2PD, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x77, full), .RVM, .{AVX512F} ),
// VPERMILPD
vec(.VPERMILPD, ops3(.xmml,.xmml,.xmml_m128), vex(.L128,._66,._0F38,.W0, 0x0D), .RVM, .{AVX} ),
vec(.VPERMILPD, ops3(.ymml,.ymml,.ymml_m256), vex(.L256,._66,._0F38,.W0, 0x0D), .RVM, .{AVX} ),
vec(.VPERMILPD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x0D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMILPD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x0D, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMILPD, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x0D, full), .RVM, .{AVX512F} ),
vec(.VPERMILPD, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W0, 0x05), .vRMI,.{AVX} ),
vec(.VPERMILPD, ops3(.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W0, 0x05), .vRMI,.{AVX} ),
vec(.VPERMILPD, ops3(.xmm_kz,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x05, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMILPD, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x05, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMILPD, ops3(.zmm_kz,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x05, full), .vRMI,.{AVX512F} ),
// VPERMILPS
vec(.VPERMILPS, ops3(.xmml,.xmml,.xmml_m128), vex(.L128,._66,._0F38,.W0, 0x0C), .RVM, .{AVX} ),
vec(.VPERMILPS, ops3(.ymml,.ymml,.ymml_m256), vex(.L256,._66,._0F38,.W0, 0x0C), .RVM, .{AVX} ),
vec(.VPERMILPS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x0C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMILPS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x0C, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMILPS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x0C, full), .RVM, .{AVX512F} ),
vec(.VPERMILPS, ops3(.xmml,.xmml_m128,.imm8), vex(.L128,._66,._0F3A,.W0, 0x04), .vRMI,.{AVX} ),
vec(.VPERMILPS, ops3(.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W0, 0x04), .vRMI,.{AVX} ),
vec(.VPERMILPS, ops3(.xmm_kz,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x04, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMILPS, ops3(.ymm_kz,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x04, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMILPS, ops3(.zmm_kz,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x04, full), .vRMI,.{AVX512F} ),
// VPERMPD
vec(.VPERMPD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x16, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMPD, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x16, full), .RVM, .{AVX512F} ),
vec(.VPERMPD, ops3(.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0x01), .vRMI,.{AVX2} ),
vec(.VPERMPD, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x01, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMPD, ops3(.zmm_kz,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x01, full), .vRMI,.{AVX512F} ),
// VPERMPS
vec(.VPERMPS, ops3(.ymml,.ymml,.ymml_m256), vex(.L256,._66,._0F38,.W0, 0x16), .RVM, .{AVX2} ),
vec(.VPERMPS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x16, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMPS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x16, full), .RVM, .{AVX512F} ),
// VPERMQ
vec(.VPERMQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x36, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x36, full), .RVM, .{AVX512F} ),
vec(.VPERMQ, ops3(.ymml,.ymml_m256,.imm8), vex(.L256,._66,._0F3A,.W1, 0x00), .vRMI,.{AVX} ),
vec(.VPERMQ, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x00, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VPERMQ, ops3(.zmm_kz,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x00, full), .vRMI,.{AVX512F} ),
// VPERMT2B
vec(.VPERMT2B, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W0, 0x7D, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMT2B, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W0, 0x7D, fmem), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPERMT2B, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W0, 0x7D, fmem), .RVM, .{AVX512_VBMI} ),
// VPERMT2W / VPERMT2D / VPERMT2Q / VPERMT2PS / VPERMT2PD
// VPERMT2W
vec(.VPERMT2W, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x7D, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMT2W, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x7D, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPERMT2W, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x7D, fmem), .RVM, .{AVX512BW} ),
// VPERMT2D
vec(.VPERMT2D, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x7E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2D, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x7E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2D, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x7E, full), .RVM, .{AVX512F} ),
// VPERMT2Q
vec(.VPERMT2Q, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x7E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2Q, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x7E, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2Q, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x7E, full), .RVM, .{AVX512F} ),
// VPERMT2PS
vec(.VPERMT2PS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x7F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2PS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x7F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2PS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x7F, full), .RVM, .{AVX512F} ),
// VPERMT2PD
vec(.VPERMT2PD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x7F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2PD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x7F, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPERMT2PD, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x7F, full), .RVM, .{AVX512F} ),
// VPEXPANDB / VPEXPANDW
// VPEXPANDB
vec(.VPEXPANDB, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x62, t1s), .vRM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPEXPANDB, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x62, t1s), .vRM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPEXPANDB, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x62, t1s), .vRM, .{AVX512_VBMI2} ),
// VPEXPANDW
vec(.VPEXPANDW, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x62, t1s), .vRM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPEXPANDW, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x62, t1s), .vRM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPEXPANDW, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x62, t1s), .vRM, .{AVX512_VBMI2} ),
// VPEXPANDD
vec(.VPEXPANDD, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x89, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPEXPANDD, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x89, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPEXPANDD, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x89, t1s), .vRM, .{AVX512F} ),
// VPEXPANDQ
vec(.VPEXPANDQ, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x89, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPEXPANDQ, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x89, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPEXPANDQ, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x89, t1s), .vRM, .{AVX512F} ),
// VPGATHERDD / VPGATHERQD / VPGATHERDQ / VPGATHERQQ
// VPGATHERDD
vec(.VPGATHERDD, ops3(.xmml, .vm32xl, .xmml), vex(.L128,._66,._0F38,.W0, 0x90), .RMV, .{AVX2} ),
vec(.VPGATHERDD, ops3(.ymml, .vm32yl, .ymml), vex(.L256,._66,._0F38,.W0, 0x90), .RMV, .{AVX2} ),
vec(.VPGATHERDD, ops2(.xmm_k, .vm32x), evex(.L128,._66,._0F38,.W0, 0x90, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERDD, ops2(.ymm_k, .vm32y), evex(.L256,._66,._0F38,.W0, 0x90, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERDD, ops2(.zmm_k, .vm32z), evex(.L512,._66,._0F38,.W0, 0x90, t1s), .vRM, .{AVX512F} ),
// VPGATHERDQ
vec(.VPGATHERDQ, ops3(.xmml, .vm32xl, .xmml), vex(.L128,._66,._0F38,.W1, 0x90), .RMV, .{AVX2} ),
vec(.VPGATHERDQ, ops3(.ymml, .vm32xl, .ymml), vex(.L256,._66,._0F38,.W1, 0x90), .RMV, .{AVX2} ),
vec(.VPGATHERDQ, ops2(.xmm_k, .vm32x), evex(.L128,._66,._0F38,.W1, 0x90, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERDQ, ops2(.ymm_k, .vm32x), evex(.L256,._66,._0F38,.W1, 0x90, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERDQ, ops2(.zmm_k, .vm32y), evex(.L512,._66,._0F38,.W1, 0x90, t1s), .vRM, .{AVX512F} ),
// VPGATHERQD
vec(.VPGATHERQD, ops3(.xmml, .vm64xl, .xmml), vex(.L128,._66,._0F38,.W0, 0x91), .RMV, .{AVX2} ),
vec(.VPGATHERQD, ops3(.xmml, .vm64yl, .xmml), vex(.L256,._66,._0F38,.W0, 0x91), .RMV, .{AVX2} ),
vec(.VPGATHERQD, ops2(.xmm_k, .vm64x), evex(.L128,._66,._0F38,.W0, 0x91, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERQD, ops2(.xmm_k, .vm64y), evex(.L256,._66,._0F38,.W0, 0x91, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERQD, ops2(.ymm_k, .vm64z), evex(.L512,._66,._0F38,.W0, 0x91, t1s), .vRM, .{AVX512F} ),
// VPGATHERQQ
vec(.VPGATHERQQ, ops3(.xmml, .vm64xl, .xmml), vex(.L128,._66,._0F38,.W1, 0x91), .RMV, .{AVX2} ),
vec(.VPGATHERQQ, ops3(.ymml, .vm64yl, .ymml), vex(.L256,._66,._0F38,.W1, 0x91), .RMV, .{AVX2} ),
vec(.VPGATHERQQ, ops2(.xmm_k, .vm64x), evex(.L128,._66,._0F38,.W1, 0x91, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERQQ, ops2(.ymm_k, .vm64y), evex(.L256,._66,._0F38,.W1, 0x91, t1s), .vRM, .{AVX512VL, AVX512F} ),
vec(.VPGATHERQQ, ops2(.zmm_k, .vm64z), evex(.L512,._66,._0F38,.W1, 0x91, t1s), .vRM, .{AVX512F} ),
// VPLZCNTD / VPLZCNTQ
// VPLZCNTD
vec(.VPLZCNTD, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x44, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPLZCNTD, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x44, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPLZCNTD, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x44, full), .vRM, .{AVX512CD} ),
// VPLZCNTQ
vec(.VPLZCNTQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x44, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPLZCNTQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x44, full), .vRM, .{AVX512VL, AVX512CD} ),
vec(.VPLZCNTQ, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x44, full), .vRM, .{AVX512CD} ),
// VPMADD52HUQ
vec(.VPMADD52HUQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xB5, full), .RVM, .{AVX512VL, AVX512_IFMA} ),
vec(.VPMADD52HUQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xB5, full), .RVM, .{AVX512VL, AVX512_IFMA} ),
vec(.VPMADD52HUQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0xB5, full), .RVM, .{AVX512_IFMA} ),
// VPMADD52LUQ
vec(.VPMADD52LUQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0xB4, full), .RVM, .{AVX512VL, AVX512_IFMA} ),
vec(.VPMADD52LUQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0xB4, full), .RVM, .{AVX512VL, AVX512_IFMA} ),
vec(.VPMADD52LUQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0xB4, full), .RVM, .{AVX512_IFMA} ),
// VPMASKMOV
// VMASKMOVD
vec(.VMASKMOVD, ops3(.xmml, .xmml, .rm_mem128), vex(.L128,._66,._0F38,.W0, 0x8C), .RVM, .{AVX2} ),
vec(.VMASKMOVD, ops3(.ymml, .ymml, .rm_mem256), vex(.L256,._66,._0F38,.W0, 0x8C), .RVM, .{AVX2} ),
vec(.VMASKMOVD, ops3(.rm_mem128, .xmml, .xmml), vex(.L128,._66,._0F38,.W0, 0x8E), .MVR, .{AVX2} ),
vec(.VMASKMOVD, ops3(.rm_mem256, .ymml, .ymml), vex(.L256,._66,._0F38,.W0, 0x8E), .MVR, .{AVX2} ),
// VMASKMOVQ
vec(.VMASKMOVQ, ops3(.xmml, .xmml, .rm_mem128), vex(.L128,._66,._0F38,.W1, 0x8C), .RVM, .{AVX2} ),
vec(.VMASKMOVQ, ops3(.ymml, .ymml, .rm_mem256), vex(.L256,._66,._0F38,.W1, 0x8C), .RVM, .{AVX2} ),
vec(.VMASKMOVQ, ops3(.rm_mem128, .xmml, .xmml), vex(.L128,._66,._0F38,.W1, 0x8E), .MVR, .{AVX2} ),
vec(.VMASKMOVQ, ops3(.rm_mem256, .ymml, .ymml), vex(.L256,._66,._0F38,.W1, 0x8E), .MVR, .{AVX2} ),
// VPMOVB2M / VPMOVW2M / VPMOVD2M / VPMOVQ2M
// VPMOVB2M
vec(.VPMOVB2M, ops2(.reg_k, .rm_xmm), evex(.L128,._F3,._0F38,.W0, 0x29, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVB2M, ops2(.reg_k, .rm_ymm), evex(.L256,._F3,._0F38,.W0, 0x29, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVB2M, ops2(.reg_k, .rm_zmm), evex(.L512,._F3,._0F38,.W0, 0x29, nomem), .vRM, .{AVX512BW} ),
// VPMOVW2M
vec(.VPMOVW2M, ops2(.reg_k, .rm_xmm), evex(.L128,._F3,._0F38,.W1, 0x29, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVW2M, ops2(.reg_k, .rm_ymm), evex(.L256,._F3,._0F38,.W1, 0x29, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVW2M, ops2(.reg_k, .rm_zmm), evex(.L512,._F3,._0F38,.W1, 0x29, nomem), .vRM, .{AVX512BW} ),
// VPMOVD2M
vec(.VPMOVD2M, ops2(.reg_k, .rm_xmm), evex(.L128,._F3,._0F38,.W0, 0x39, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVD2M, ops2(.reg_k, .rm_ymm), evex(.L256,._F3,._0F38,.W0, 0x39, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVD2M, ops2(.reg_k, .rm_zmm), evex(.L512,._F3,._0F38,.W0, 0x39, nomem), .vRM, .{AVX512DQ} ),
// VPMOVQ2M
vec(.VPMOVQ2M, ops2(.reg_k, .rm_xmm), evex(.L128,._F3,._0F38,.W1, 0x39, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVQ2M, ops2(.reg_k, .rm_ymm), evex(.L256,._F3,._0F38,.W1, 0x39, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVQ2M, ops2(.reg_k, .rm_zmm), evex(.L512,._F3,._0F38,.W1, 0x39, nomem), .vRM, .{AVX512DQ} ),
// VPMOVDB / VPMOVSDB / VPMOVUSDB
// VPMOVDB
vec(.VPMOVDB, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x31, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVDB, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x31, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVDB, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x31, qmem), .vMR, .{AVX512F} ),
// VPMOVSDB
vec(.VPMOVSDB, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x21, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSDB, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x21, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSDB, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x21, qmem), .vMR, .{AVX512F} ),
// VPMOVUSDB
vec(.VPMOVUSDB, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x11, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSDB, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x11, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSDB, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x11, qmem), .vMR, .{AVX512F} ),
// VPMOVDW / VPMOVSDB / VPMOVUSDB
// VPMOVDW
vec(.VPMOVDW, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x33, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVDW, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x33, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVDW, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x33, hmem), .vMR, .{AVX512F} ),
// VPMOVSDB
vec(.VPMOVSDW, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x23, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSDW, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x23, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSDW, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x23, hmem), .vMR, .{AVX512F} ),
// VPMOVUSDB
vec(.VPMOVUSDW, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x13, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSDW, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x13, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSDW, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x13, hmem), .vMR, .{AVX512F} ),
// VPMOVM2B / VPMOVM2W / VPMOVM2D / VPMOVM2Q
// VPMOVM2B
vec(.VPMOVM2B, ops2(.xmm, .rm_k), evex(.L128,._F3,._0F38,.W0, 0x28, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVM2B, ops2(.ymm, .rm_k), evex(.L256,._F3,._0F38,.W0, 0x28, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVM2B, ops2(.zmm, .rm_k), evex(.L512,._F3,._0F38,.W0, 0x28, nomem), .vRM, .{AVX512BW} ),
// VPMOVM2W
vec(.VPMOVM2W, ops2(.xmm, .rm_k), evex(.L128,._F3,._0F38,.W1, 0x28, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVM2W, ops2(.ymm, .rm_k), evex(.L256,._F3,._0F38,.W1, 0x28, nomem), .vRM, .{AVX512VL, AVX512BW} ),
vec(.VPMOVM2W, ops2(.zmm, .rm_k), evex(.L512,._F3,._0F38,.W1, 0x28, nomem), .vRM, .{AVX512BW} ),
// VPMOVM2D
vec(.VPMOVM2D, ops2(.xmm, .rm_k), evex(.L128,._F3,._0F38,.W0, 0x38, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVM2D, ops2(.ymm, .rm_k), evex(.L256,._F3,._0F38,.W0, 0x38, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVM2D, ops2(.zmm, .rm_k), evex(.L512,._F3,._0F38,.W0, 0x38, nomem), .vRM, .{AVX512DQ} ),
// VPMOVM2Q
vec(.VPMOVM2Q, ops2(.xmm, .rm_k), evex(.L128,._F3,._0F38,.W1, 0x38, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVM2Q, ops2(.ymm, .rm_k), evex(.L256,._F3,._0F38,.W1, 0x38, nomem), .vRM, .{AVX512VL, AVX512DQ} ),
vec(.VPMOVM2Q, ops2(.zmm, .rm_k), evex(.L512,._F3,._0F38,.W1, 0x38, nomem), .vRM, .{AVX512DQ} ),
// VPMOVQB / VPMOVSQB / VPMOVUSQB
// VPMOVQB
vec(.VPMOVQB, ops2(.xmm_m16_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x32, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQB, ops2(.xmm_m32_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x32, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQB, ops2(.xmm_m64_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x32, emem), .vMR, .{AVX512F} ),
// VPMOVSQB
vec(.VPMOVSQB, ops2(.xmm_m16_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x22, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQB, ops2(.xmm_m32_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x22, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQB, ops2(.xmm_m64_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x22, emem), .vMR, .{AVX512F} ),
// VPMOVUSQB
vec(.VPMOVUSQB, ops2(.xmm_m16_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x12, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQB, ops2(.xmm_m32_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x12, emem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQB, ops2(.xmm_m64_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x12, emem), .vMR, .{AVX512F} ),
// VPMOVQD / VPMOVSQD / VPMOVUSQD
// VPMOVQD
vec(.VPMOVQD, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x35, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQD, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x35, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQD, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x35, hmem), .vMR, .{AVX512F} ),
// VPMOVSQD
vec(.VPMOVSQD, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x25, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQD, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x25, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQD, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x25, hmem), .vMR, .{AVX512F} ),
// VPMOVUSQD
vec(.VPMOVUSQD, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x15, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQD, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x15, hmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQD, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x15, hmem), .vMR, .{AVX512F} ),
// VPMOVQW / VPMOVSQW / VPMOVUSQW
// VPMOVQW
vec(.VPMOVQW, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x34, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQW, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x34, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVQW, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x34, qmem), .vMR, .{AVX512F} ),
// VPMOVSQW
vec(.VPMOVSQW, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x24, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQW, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x24, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVSQW, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x24, qmem), .vMR, .{AVX512F} ),
// VPMOVUSQW
vec(.VPMOVUSQW, ops2(.xmm_m32_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x14, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQW, ops2(.xmm_m64_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x14, qmem), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPMOVUSQW, ops2(.xmm_m128_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x14, qmem), .vMR, .{AVX512F} ),
// VPMOVWB / VPMOVSWB / VPMOVUSWB
// VPMOVWB
vec(.VPMOVWB, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x30, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVWB, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x30, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVWB, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x30, hmem), .vMR, .{AVX512BW} ),
// VPMOVSWB
vec(.VPMOVSWB, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x20, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVSWB, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x20, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVSWB, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x20, hmem), .vMR, .{AVX512BW} ),
// VPMOVUSWB
vec(.VPMOVUSWB, ops2(.xmm_m64_kz, .xmm), evex(.L128,._F3,._0F38,.W0, 0x10, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVUSWB, ops2(.xmm_m128_kz, .ymm), evex(.L256,._F3,._0F38,.W0, 0x10, hmem), .vMR, .{AVX512VL, AVX512BW} ),
vec(.VPMOVUSWB, ops2(.ymm_m256_kz, .zmm), evex(.L512,._F3,._0F38,.W0, 0x10, hmem), .vMR, .{AVX512BW} ),
// VPMULTISHIFTQB
// VPMULTISHIFTQB
vec(.VPMULTISHIFTQB, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x83, full), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPMULTISHIFTQB, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x83, full), .RVM, .{AVX512VL, AVX512_VBMI} ),
vec(.VPMULTISHIFTQB, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x83, full), .RVM, .{AVX512_VBMI} ),
// VPOPCNT
// VPOPCNTB
vec(.VPOPCNTB, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x54, fmem), .vRM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPOPCNTB, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x54, fmem), .vRM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPOPCNTB, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x54, fmem), .vRM, .{AVX512_BITALG} ),
// VPOPCNTW
vec(.VPOPCNTW, ops2(.xmm_kz, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x54, fmem), .vRM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPOPCNTW, ops2(.ymm_kz, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x54, fmem), .vRM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPOPCNTW, ops2(.zmm_kz, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x54, fmem), .vRM, .{AVX512_BITALG} ),
// VPOPCNTD
vec(.VPOPCNTD, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x55, full), .vRM, .{AVX512VL, AVX512_VPOPCNTDQ} ),
vec(.VPOPCNTD, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x55, full), .vRM, .{AVX512VL, AVX512_VPOPCNTDQ} ),
vec(.VPOPCNTD, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x55, full), .vRM, .{AVX512_VPOPCNTDQ} ),
// VPOPCNTQ
vec(.VPOPCNTQ, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x55, full), .vRM, .{AVX512VL, AVX512_VPOPCNTDQ} ),
vec(.VPOPCNTQ, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x55, full), .vRM, .{AVX512VL, AVX512_VPOPCNTDQ} ),
vec(.VPOPCNTQ, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x55, full), .vRM, .{AVX512_VPOPCNTDQ} ),
// VPROLD / VPROLVD / VPROLQ / VPROLVQ
// VPROLD
vec(.VPROLD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8), evexr(.L128,._66,._0F,.W0, 0x72, 1, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPROLD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8), evexr(.L256,._66,._0F,.W0, 0x72, 1, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPROLD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8), evexr(.L512,._66,._0F,.W0, 0x72, 1, full),.VMI, .{AVX512F} ),
// VPROLVD
vec(.VPROLVD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPROLVD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPROLVD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x15, full), .RVM, .{AVX512F} ),
// VPROLQ
vec(.VPROLQ, ops3(.xmm_kz, .xmm_m128_m64bcst, .imm8), evexr(.L128,._66,._0F,.W1, 0x72, 1, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPROLQ, ops3(.ymm_kz, .ymm_m256_m64bcst, .imm8), evexr(.L256,._66,._0F,.W1, 0x72, 1, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPROLQ, ops3(.zmm_kz, .zmm_m512_m64bcst, .imm8), evexr(.L512,._66,._0F,.W1, 0x72, 1, full),.VMI, .{AVX512F} ),
// VPROLVQ
vec(.VPROLVQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPROLVQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x15, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPROLVQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x15, full), .RVM, .{AVX512F} ),
// VPRORD / VPRORVD / VPRORQ / VPRORVQ
// VPRORD
vec(.VPRORD, ops3(.xmm_kz, .xmm_m128_m32bcst, .imm8), evexr(.L128,._66,._0F,.W0, 0x72, 0, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPRORD, ops3(.ymm_kz, .ymm_m256_m32bcst, .imm8), evexr(.L256,._66,._0F,.W0, 0x72, 0, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPRORD, ops3(.zmm_kz, .zmm_m512_m32bcst, .imm8), evexr(.L512,._66,._0F,.W0, 0x72, 0, full),.VMI, .{AVX512F} ),
// VPRORVD
vec(.VPRORVD, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPRORVD, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPRORVD, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x14, full), .RVM, .{AVX512F} ),
// VPRORQ
vec(.VPRORQ, ops3(.xmm_kz, .xmm_m128_m64bcst, .imm8), evexr(.L128,._66,._0F,.W1, 0x72, 0, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPRORQ, ops3(.ymm_kz, .ymm_m256_m64bcst, .imm8), evexr(.L256,._66,._0F,.W1, 0x72, 0, full),.VMI, .{AVX512VL, AVX512F} ),
vec(.VPRORQ, ops3(.zmm_kz, .zmm_m512_m64bcst, .imm8), evexr(.L512,._66,._0F,.W1, 0x72, 0, full),.VMI, .{AVX512F} ),
// VPRORVQ
vec(.VPRORVQ, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPRORVQ, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x14, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPRORVQ, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x14, full), .RVM, .{AVX512F} ),
// VPSCATTERDD / VPSCATTERDQ / VPSCATTERQD / VPSCATTERQQ
// VPSCATTERDD
vec(.VPSCATTERDD, ops2(.vm32x_k, .xmm), evex(.L128,._66,._0F38,.W0, 0xA0, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERDD, ops2(.vm32y_k, .ymm), evex(.L256,._66,._0F38,.W0, 0xA0, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERDD, ops2(.vm32z_k, .zmm), evex(.L512,._66,._0F38,.W0, 0xA0, t1s), .vMR, .{AVX512F} ),
// VPSCATTERDQ
vec(.VPSCATTERDQ, ops2(.vm32x_k, .xmm), evex(.L128,._66,._0F38,.W1, 0xA0, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERDQ, ops2(.vm32x_k, .ymm), evex(.L256,._66,._0F38,.W1, 0xA0, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERDQ, ops2(.vm32y_k, .zmm), evex(.L512,._66,._0F38,.W1, 0xA0, t1s), .vMR, .{AVX512F} ),
// VPSCATTERQD
vec(.VPSCATTERQD, ops2(.vm64x_k, .xmm), evex(.L128,._66,._0F38,.W0, 0xA1, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERQD, ops2(.vm64y_k, .xmm), evex(.L256,._66,._0F38,.W0, 0xA1, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERQD, ops2(.vm64z_k, .ymm), evex(.L512,._66,._0F38,.W0, 0xA1, t1s), .vMR, .{AVX512F} ),
// VPSCATTERQQ
vec(.VPSCATTERQQ, ops2(.vm64x_k, .xmm), evex(.L128,._66,._0F38,.W1, 0xA1, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERQQ, ops2(.vm64y_k, .ymm), evex(.L256,._66,._0F38,.W1, 0xA1, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VPSCATTERQQ, ops2(.vm64z_k, .zmm), evex(.L512,._66,._0F38,.W1, 0xA1, t1s), .vMR, .{AVX512F} ),
// VPSHLD
// VPSHLDW
vec(.VPSHLDW, ops4(.xmm_kz,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W1, 0x70, fmem), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDW, ops4(.ymm_kz,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W1, 0x70, fmem), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDW, ops4(.zmm_kz,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W1, 0x70, fmem), .RVMI,.{AVX512_VBMI2} ),
// VPSHLDD
vec(.VPSHLDD, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x71, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDD, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x71, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDD, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x71, full), .RVMI,.{AVX512_VBMI2} ),
// VPSHLDQ
vec(.VPSHLDQ, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x71, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDQ, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x71, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDQ, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x71, full), .RVMI,.{AVX512_VBMI2} ),
// VPSHLDV
// VPSHLDVW
vec(.VPSHLDVW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x70, fmem), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x70, fmem), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x70, fmem), .RVM, .{AVX512_VBMI2} ),
// VPSHLDVD
vec(.VPSHLDVD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x71, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x71, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x71, full), .RVM, .{AVX512_VBMI2} ),
// VPSHLDVQ
vec(.VPSHLDVQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x71, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x71, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHLDVQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x71, full), .RVM, .{AVX512_VBMI2} ),
// VPSHRD
// VPSHRDW
vec(.VPSHRDW, ops4(.xmm_kz,.xmm,.xmm_m128,.imm8), evex(.L128,._66,._0F3A,.W1, 0x72, fmem), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDW, ops4(.ymm_kz,.ymm,.ymm_m256,.imm8), evex(.L256,._66,._0F3A,.W1, 0x72, fmem), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDW, ops4(.zmm_kz,.zmm,.zmm_m512,.imm8), evex(.L512,._66,._0F3A,.W1, 0x72, fmem), .RVMI,.{AVX512_VBMI2} ),
// VPSHRDD
vec(.VPSHRDD, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x73, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDD, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x73, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDD, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x73, full), .RVMI,.{AVX512_VBMI2} ),
// VPSHRDQ
vec(.VPSHRDQ, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x73, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDQ, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x73, full), .RVMI,.{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDQ, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x73, full), .RVMI,.{AVX512_VBMI2} ),
// VPSHRDV
// VPSHRDVW
vec(.VPSHRDVW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x72, fmem), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x72, fmem), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x72, fmem), .RVM, .{AVX512_VBMI2} ),
// VPSHRDVD
vec(.VPSHRDVD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x73, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x73, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x73, full), .RVM, .{AVX512_VBMI2} ),
// VPSHRDVQ
vec(.VPSHRDVQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x73, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x73, full), .RVM, .{AVX512VL, AVX512_VBMI2} ),
vec(.VPSHRDVQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x73, full), .RVM, .{AVX512_VBMI2} ),
// VPSHUFBITQMB
vec(.VPSHUFBITQMB, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x8F, fmem), .RVM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPSHUFBITQMB, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x8F, fmem), .RVM, .{AVX512VL, AVX512_BITALG} ),
vec(.VPSHUFBITQMB, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x8F, fmem), .RVM, .{AVX512_BITALG} ),
// VPSLLVW / VPSLLVD / VPSLLVQ
// VPSLLVW
vec(.VPSLLVW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x12, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSLLVW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x12, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSLLVW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x12, fmem), .RVM, .{AVX512BW} ),
// VPSLLVD
vec(.VPSLLVD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x47), .RVM, .{AVX2} ),
vec(.VPSLLVD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x47), .RVM, .{AVX2} ),
vec(.VPSLLVD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x47, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLVD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x47, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLVD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x47, full), .RVM, .{AVX512F} ),
// VPSLLVQ
vec(.VPSLLVQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x47), .RVM, .{AVX2} ),
vec(.VPSLLVQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x47), .RVM, .{AVX2} ),
vec(.VPSLLVQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x47, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLVQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x47, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSLLVQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x47, full), .RVM, .{AVX512F} ),
// VPSRAVW / VPSRAVD / VPSRAVQ
// VPSRAVW
vec(.VPSRAVW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x11, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRAVW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x11, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRAVW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x11, fmem), .RVM, .{AVX512BW} ),
// VPSRAVD
vec(.VPSRAVD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x46), .RVM, .{AVX2} ),
vec(.VPSRAVD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x46), .RVM, .{AVX2} ),
vec(.VPSRAVD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x46, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAVD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x46, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAVD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x46, full), .RVM, .{AVX512F} ),
// VPSRAVQ
vec(.VPSRAVQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x46, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAVQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x46, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRAVQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x46, full), .RVM, .{AVX512F} ),
// VPSRLVW / VPSRLVD / VPSRLVQ
// VPSRLVW
vec(.VPSRLVW, ops3(.xmm_kz,.xmm,.xmm_m128), evex(.L128,._66,._0F38,.W1, 0x10, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRLVW, ops3(.ymm_kz,.ymm,.ymm_m256), evex(.L256,._66,._0F38,.W1, 0x10, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPSRLVW, ops3(.zmm_kz,.zmm,.zmm_m512), evex(.L512,._66,._0F38,.W1, 0x10, fmem), .RVM, .{AVX512BW} ),
// VPSRLVD
vec(.VPSRLVD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x45), .RVM, .{AVX2} ),
vec(.VPSRLVD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x45), .RVM, .{AVX2} ),
vec(.VPSRLVD, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x45, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLVD, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x45, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLVD, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x45, full), .RVM, .{AVX512F} ),
// VPSRLVQ
vec(.VPSRLVQ, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F38,.W1, 0x45), .RVM, .{AVX2} ),
vec(.VPSRLVQ, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F38,.W1, 0x45), .RVM, .{AVX2} ),
vec(.VPSRLVQ, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x45, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLVQ, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x45, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPSRLVQ, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x45, full), .RVM, .{AVX512F} ),
// VPTERNLOGD / VPTERNLOGQ
// VPTERNLOGD
vec(.VPTERNLOGD, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x25, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPTERNLOGD, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x25, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPTERNLOGD, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x25, full), .RVMI,.{AVX512F} ),
// VPTERNLOGQ
vec(.VPTERNLOGQ, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x25, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPTERNLOGQ, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x25, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VPTERNLOGQ, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x25, full), .RVMI,.{AVX512F} ),
// VPTESTMB / VPTESTMW / VPTESTMD / VPTESTMQ
// VPTESTMB
vec(.VPTESTMB, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTMB, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTMB, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512BW} ),
// VPTESTMW
vec(.VPTESTMW, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._66,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTMW, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._66,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTMW, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._66,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512BW} ),
// VPTESTMD
vec(.VPTESTMD, ops3(.reg_k_k, .xmm, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTMD, ops3(.reg_k_k, .ymm, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTMD, ops3(.reg_k_k, .zmm, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x27, full), .RVM, .{AVX512F} ),
// VPTESTMQ
vec(.VPTESTMQ, ops3(.reg_k_k, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTMQ, ops3(.reg_k_k, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTMQ, ops3(.reg_k_k, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x27, full), .RVM, .{AVX512F} ),
// VPTESTNMB / VPTESTNMW / VPTESTNMD / VPTESTNMQ
// VPTESTNMB
vec(.VPTESTNMB, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._F3,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTNMB, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._F3,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTNMB, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._F3,._0F38,.W0, 0x26, fmem), .RVM, .{AVX512BW} ),
// VPTESTNMW
vec(.VPTESTNMW, ops3(.reg_k_k, .xmm, .xmm_m128), evex(.L128,._F3,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTNMW, ops3(.reg_k_k, .ymm, .ymm_m256), evex(.L256,._F3,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512VL, AVX512BW} ),
vec(.VPTESTNMW, ops3(.reg_k_k, .zmm, .zmm_m512), evex(.L512,._F3,._0F38,.W1, 0x26, fmem), .RVM, .{AVX512BW} ),
// VPTESTNMD
vec(.VPTESTNMD, ops3(.reg_k_k, .xmm, .xmm_m128_m32bcst), evex(.L128,._F3,._0F38,.W0, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTNMD, ops3(.reg_k_k, .ymm, .ymm_m256_m32bcst), evex(.L256,._F3,._0F38,.W0, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTNMD, ops3(.reg_k_k, .zmm, .zmm_m512_m32bcst), evex(.L512,._F3,._0F38,.W0, 0x27, full), .RVM, .{AVX512F} ),
// VPTESTNMQ
vec(.VPTESTNMQ, ops3(.reg_k_k, .xmm, .xmm_m128_m64bcst), evex(.L128,._F3,._0F38,.W1, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTNMQ, ops3(.reg_k_k, .ymm, .ymm_m256_m64bcst), evex(.L256,._F3,._0F38,.W1, 0x27, full), .RVM, .{AVX512VL, AVX512F} ),
vec(.VPTESTNMQ, ops3(.reg_k_k, .zmm, .zmm_m512_m64bcst), evex(.L512,._F3,._0F38,.W1, 0x27, full), .RVM, .{AVX512F} ),
// VRANGEPD / VRANGEPS / VRANGESD / VRANGESS
// VRANGEPD
vec(.VRANGEPD, ops4(.xmm_kz,.xmm,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x50, full), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VRANGEPD, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x50, full), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VRANGEPD, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst_sae,.imm8),evex(.L512,._66,._0F3A,.W1, 0x50, full), .RVMI,.{AVX512DQ} ),
// VRANGEPS
vec(.VRANGEPS, ops4(.xmm_kz,.xmm,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x50, full), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VRANGEPS, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x50, full), .RVMI,.{AVX512VL, AVX512DQ} ),
vec(.VRANGEPS, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst_sae,.imm8),evex(.L512,._66,._0F3A,.W0, 0x50, full), .RVMI,.{AVX512DQ} ),
// VRANGESD
vec(.VRANGESD, ops4(.xmm_kz,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x51, t1s), .RVMI,.{AVX512DQ} ),
// VRANGESS
vec(.VRANGESS, ops4(.xmm_kz,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x51, t1s), .RVMI,.{AVX512DQ} ),
// VRCP14PD / VRCP14PS / VRCP14SD / VRCP14SS
// VRCP14PD
vec(.VRCP14PD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x4C, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRCP14PD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x4C, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRCP14PD, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x4C, full), .vRM, .{AVX512F} ),
// VRCP14PS
vec(.VRCP14PS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x4C, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRCP14PS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x4C, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRCP14PS, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x4C, full), .vRM, .{AVX512F} ),
// VRCP14SD
vec(.VRCP14SD, ops3(.xmm_kz,.xmm,.xmm_m64), evex(.LIG,._66,._0F38,.W1, 0x4D, t1s), .RVM, .{AVX512F} ),
// VRCP14SS
vec(.VRCP14SS, ops3(.xmm_kz,.xmm,.xmm_m32), evex(.LIG,._66,._0F38,.W0, 0x4D, t1s), .RVM, .{AVX512F} ),
// VREDUCEPD / VREDUCEPS / VREDUCESD / VREDUCESS
// VREDUCEPD
vec(.VREDUCEPD, ops3(.xmm_kz,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x56, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VREDUCEPD, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x56, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VREDUCEPD, ops3(.zmm_kz,.zmm_m512_m64bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W1, 0x56, full), .vRMI,.{AVX512DQ} ),
// VREDUCEPS
vec(.VREDUCEPS, ops3(.xmm_kz,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x56, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VREDUCEPS, ops3(.ymm_kz,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x56, full), .vRMI,.{AVX512VL, AVX512DQ} ),
vec(.VREDUCEPS, ops3(.zmm_kz,.zmm_m512_m32bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W0, 0x56, full), .vRMI,.{AVX512DQ} ),
// VREDUCESD
vec(.VREDUCESD, ops4(.xmm_kz,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x57, t1s), .RVMI,.{AVX512DQ} ),
// VREDUCESS
vec(.VREDUCESS, ops4(.xmm_kz,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x57, t1s), .RVMI,.{AVX512DQ} ),
// VRNDSCALEPD / VRNDSCALEPS / VRNDSCALESD / VRNDSCALESS
// VRNDSCALEPD
vec(.VRNDSCALEPD, ops3(.xmm_kz,.xmm_m128_m64bcst,.imm8), evex(.L128,._66,._0F3A,.W1, 0x09, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VRNDSCALEPD, ops3(.ymm_kz,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x09, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VRNDSCALEPD, ops3(.zmm_kz,.zmm_m512_m64bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W1, 0x09, full), .vRMI,.{AVX512F} ),
// VRNDSCALEPS
vec(.VRNDSCALEPS, ops3(.xmm_kz,.xmm_m128_m32bcst,.imm8), evex(.L128,._66,._0F3A,.W0, 0x08, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VRNDSCALEPS, ops3(.ymm_kz,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x08, full), .vRMI,.{AVX512VL, AVX512F} ),
vec(.VRNDSCALEPS, ops3(.zmm_kz,.zmm_m512_m32bcst_sae,.imm8), evex(.L512,._66,._0F3A,.W0, 0x08, full), .vRMI,.{AVX512F} ),
// VRNDSCALESD
vec(.VRNDSCALESD, ops4(.xmm_kz,.xmm,.xmm_m64_sae,.imm8), evex(.LIG,._66,._0F3A,.W1, 0x0B, t1s), .RVMI,.{AVX512F} ),
// VRNDSCALESS
vec(.VRNDSCALESS, ops4(.xmm_kz,.xmm,.xmm_m32_sae,.imm8), evex(.LIG,._66,._0F3A,.W0, 0x0A, t1s), .RVMI,.{AVX512F} ),
// VRSQRT14PD / VRSQRT14PS / VRSQRT14SD / VRSQRT14SS
// VRSQRT14PD
vec(.VRSQRT14PD, ops2(.xmm_kz, .xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x4E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRSQRT14PD, ops2(.ymm_kz, .ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x4E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRSQRT14PD, ops2(.zmm_kz, .zmm_m512_m64bcst), evex(.L512,._66,._0F38,.W1, 0x4E, full), .vRM, .{AVX512F} ),
// VRSQRT14PS
vec(.VRSQRT14PS, ops2(.xmm_kz, .xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x4E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRSQRT14PS, ops2(.ymm_kz, .ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x4E, full), .vRM, .{AVX512VL, AVX512F} ),
vec(.VRSQRT14PS, ops2(.zmm_kz, .zmm_m512_m32bcst), evex(.L512,._66,._0F38,.W0, 0x4E, full), .vRM, .{AVX512F} ),
// VRSQRT14SD
vec(.VRSQRT14SD, ops3(.xmm_kz,.xmm,.xmm_m64), evex(.LIG,._66,._0F38,.W1, 0x4F, t1s), .RVM, .{AVX512F} ),
// VRSQRT14SS
vec(.VRSQRT14SS, ops3(.xmm_kz,.xmm,.xmm_m32), evex(.LIG,._66,._0F38,.W0, 0x4F, t1s), .RVM, .{AVX512F} ),
// VSCALEFPD / VSCALEFPS / VSCALEFSD / VSCALEFSS
// VSCALEFPD
vec(.VSCALEFPD, ops3(.xmm_kz,.xmm,.xmm_m128_m64bcst), evex(.L128,._66,._0F38,.W1, 0x2C, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSCALEFPD, ops3(.ymm_kz,.ymm,.ymm_m256_m64bcst), evex(.L256,._66,._0F38,.W1, 0x2C, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSCALEFPD, ops3(.zmm_kz,.zmm,.zmm_m512_m64bcst_er), evex(.L512,._66,._0F38,.W1, 0x2C, full), .RVMI,.{AVX512F} ),
// VSCALEFPS
vec(.VSCALEFPS, ops3(.xmm_kz,.xmm,.xmm_m128_m32bcst), evex(.L128,._66,._0F38,.W0, 0x2C, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSCALEFPS, ops3(.ymm_kz,.ymm,.ymm_m256_m32bcst), evex(.L256,._66,._0F38,.W0, 0x2C, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSCALEFPS, ops3(.zmm_kz,.zmm,.zmm_m512_m32bcst_er), evex(.L512,._66,._0F38,.W0, 0x2C, full), .RVMI,.{AVX512F} ),
// VSCALEFSD
vec(.VSCALEFSD, ops3(.xmm_kz,.xmm,.xmm_m64_er), evex(.LIG,._66,._0F38,.W1, 0x2D, t1s), .RVMI,.{AVX512F} ),
// VSCALEFSS
vec(.VSCALEFSS, ops3(.xmm_kz,.xmm,.xmm_m32_er), evex(.LIG,._66,._0F38,.W0, 0x2D, t1s), .RVMI,.{AVX512F} ),
// VSCATTERDPS / VSCATTERDPD / VSCATTERQPS / VSCATTERQPD
// VSCATTERDPS
vec(.VSCATTERDPS, ops2(.vm32x_k, .xmm), evex(.L128,._66,._0F38,.W0, 0xA2, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERDPS, ops2(.vm32y_k, .ymm), evex(.L256,._66,._0F38,.W0, 0xA2, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERDPS, ops2(.vm32z_k, .zmm), evex(.L512,._66,._0F38,.W0, 0xA2, t1s), .vMR, .{AVX512F} ),
// VSCATTERDPD
vec(.VSCATTERDPD, ops2(.vm32x_k, .xmm), evex(.L128,._66,._0F38,.W1, 0xA2, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERDPD, ops2(.vm32x_k, .ymm), evex(.L256,._66,._0F38,.W1, 0xA2, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERDPD, ops2(.vm32y_k, .zmm), evex(.L512,._66,._0F38,.W1, 0xA2, t1s), .vMR, .{AVX512F} ),
// VSCATTERQPS
vec(.VSCATTERQPS, ops2(.vm64x_k, .xmm), evex(.L128,._66,._0F38,.W0, 0xA3, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERQPS, ops2(.vm64y_k, .xmm), evex(.L256,._66,._0F38,.W0, 0xA3, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERQPS, ops2(.vm64z_k, .ymm), evex(.L512,._66,._0F38,.W0, 0xA3, t1s), .vMR, .{AVX512F} ),
// VSCATTERQPD
vec(.VSCATTERQPD, ops2(.vm64x_k, .xmm), evex(.L128,._66,._0F38,.W1, 0xA3, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERQPD, ops2(.vm64y_k, .ymm), evex(.L256,._66,._0F38,.W1, 0xA3, t1s), .vMR, .{AVX512VL, AVX512F} ),
vec(.VSCATTERQPD, ops2(.vm64z_k, .zmm), evex(.L512,._66,._0F38,.W1, 0xA3, t1s), .vMR, .{AVX512F} ),
// VSHUFF32X4 / VSHUFF64X2 / VSHUFI32X4 / VSHUFI64X2
// VSHUFF32X4
vec(.VSHUFF32X4, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x23, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFF32X4, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x23, full), .RVMI,.{AVX512F} ),
// VSHUFF64X2
vec(.VSHUFF64X2, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x23, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFF64X2, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x23, full), .RVMI,.{AVX512F} ),
// VSHUFI32X4
vec(.VSHUFI32X4, ops4(.ymm_kz,.ymm,.ymm_m256_m32bcst,.imm8), evex(.L256,._66,._0F3A,.W0, 0x43, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFI32X4, ops4(.zmm_kz,.zmm,.zmm_m512_m32bcst,.imm8), evex(.L512,._66,._0F3A,.W0, 0x43, full), .RVMI,.{AVX512F} ),
// VSHUFI64X2
vec(.VSHUFI64X2, ops4(.ymm_kz,.ymm,.ymm_m256_m64bcst,.imm8), evex(.L256,._66,._0F3A,.W1, 0x43, full), .RVMI,.{AVX512VL, AVX512F} ),
vec(.VSHUFI64X2, ops4(.zmm_kz,.zmm,.zmm_m512_m64bcst,.imm8), evex(.L512,._66,._0F3A,.W1, 0x43, full), .RVMI,.{AVX512F} ),
// VTESTPD / VTESTPS
// VTESTPS
vec(.VTESTPS, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x0E), .vRM, .{AVX} ),
vec(.VTESTPS, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x0E), .vRM, .{AVX} ),
// VTESTPD
vec(.VTESTPD, ops2(.xmml, .xmml_m128), vex(.L128,._66,._0F38,.W0, 0x0F), .vRM, .{AVX} ),
vec(.VTESTPD, ops2(.ymml, .ymml_m256), vex(.L256,._66,._0F38,.W0, 0x0F), .vRM, .{AVX} ),
// VXORPD
vec(.VXORPD, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._66,._0F,.WIG, 0x57), .RVM, .{AVX} ),
vec(.VXORPD, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._66,._0F,.WIG, 0x57), .RVM, .{AVX} ),
vec(.VXORPD, ops3(.xmm_kz, .xmm, .xmm_m128_m64bcst), evex(.L128,._66,._0F,.W1, 0x57, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VXORPD, ops3(.ymm_kz, .ymm, .ymm_m256_m64bcst), evex(.L256,._66,._0F,.W1, 0x57, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VXORPD, ops3(.zmm_kz, .zmm, .zmm_m512_m64bcst), evex(.L512,._66,._0F,.W1, 0x57, full), .RVM, .{AVX512DQ} ),
// VXXORPS
vec(.VXORPS, ops3(.xmml, .xmml, .xmml_m128), vex(.L128,._NP,._0F,.WIG, 0x57), .RVM, .{AVX} ),
vec(.VXORPS, ops3(.ymml, .ymml, .ymml_m256), vex(.L256,._NP,._0F,.WIG, 0x57), .RVM, .{AVX} ),
vec(.VXORPS, ops3(.xmm_kz, .xmm, .xmm_m128_m32bcst), evex(.L128,._NP,._0F,.W0, 0x57, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VXORPS, ops3(.ymm_kz, .ymm, .ymm_m256_m32bcst), evex(.L256,._NP,._0F,.W0, 0x57, full), .RVM, .{AVX512VL, AVX512DQ} ),
vec(.VXORPS, ops3(.zmm_kz, .zmm, .zmm_m512_m32bcst), evex(.L512,._NP,._0F,.W0, 0x57, full), .RVM, .{AVX512DQ} ),
// VZEROALL
vec(.VZEROALL, ops0(), vex(.L256,._NP,._0F,.WIG, 0x77), .vZO, .{AVX} ),
// VZEROUPPER
vec(.VZEROUPPER, ops0(), vex(.L128,._NP,._0F,.WIG, 0x77), .vZO, .{AVX} ),
//
// AVX512 mask register instructions
//
// KADDW / KADDB / KADDD / KADDQ
vec(.KADDB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x4A), .RVM, .{AVX512DQ} ),
vec(.KADDW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x4A), .RVM, .{AVX512DQ} ),
vec(.KADDD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x4A), .RVM, .{AVX512BW} ),
vec(.KADDQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x4A), .RVM, .{AVX512BW} ),
// KANDW / KANDB / KANDD / KANDQ
vec(.KANDB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x41), .RVM, .{AVX512DQ} ),
vec(.KANDW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x41), .RVM, .{AVX512F} ),
vec(.KANDD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x41), .RVM, .{AVX512BW} ),
vec(.KANDQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x41), .RVM, .{AVX512BW} ),
// KANDNW / KANDNB / KANDND / KANDNQ
vec(.KANDNB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x42), .RVM, .{AVX512DQ} ),
vec(.KANDNW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x42), .RVM, .{AVX512F} ),
vec(.KANDND, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x42), .RVM, .{AVX512BW} ),
vec(.KANDNQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x42), .RVM, .{AVX512BW} ),
// KNOTW / KNOTB / KNOTD / KNOTQ
vec(.KNOTB, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W0, 0x44), .vRM, .{AVX512DQ} ),
vec(.KNOTW, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W0, 0x44), .vRM, .{AVX512F} ),
vec(.KNOTD, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W1, 0x44), .vRM, .{AVX512BW} ),
vec(.KNOTQ, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W1, 0x44), .vRM, .{AVX512BW} ),
// KORW / KORB / KORD / KORQ
vec(.KORB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x45), .RVM, .{AVX512DQ} ),
vec(.KORW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x45), .RVM, .{AVX512F} ),
vec(.KORD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x45), .RVM, .{AVX512BW} ),
vec(.KORQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x45), .RVM, .{AVX512BW} ),
// KORTESTW / KORTESTB / KORTESTD / KORTESTQ
vec(.KORTESTB, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W0, 0x98), .vRM, .{AVX512DQ} ),
vec(.KORTESTW, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W0, 0x98), .vRM, .{AVX512F} ),
vec(.KORTESTD, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W1, 0x98), .vRM, .{AVX512BW} ),
vec(.KORTESTQ, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W1, 0x98), .vRM, .{AVX512BW} ),
// KMOVW / KMOVB / KMOVD / KMOVQ
vec(.KMOVB, ops2(.reg_k, .k_m8), vex(.LZ,._66,._0F,.W0, 0x90), .vRM, .{AVX512DQ} ),
vec(.KMOVB, ops2(.rm_mem8, .reg_k), vex(.LZ,._66,._0F,.W0, 0x91), .vMR, .{AVX512DQ} ),
vec(.KMOVB, ops2(.reg_k, .reg32), vex(.LZ,._66,._0F,.W0, 0x92), .vRM, .{AVX512DQ} ),
vec(.KMOVB, ops2(.reg32, .reg_k), vex(.LZ,._66,._0F,.W0, 0x93), .vRM, .{AVX512DQ} ),
//
vec(.KMOVW, ops2(.reg_k, .k_m16), vex(.LZ,._NP,._0F,.W0, 0x90), .vRM, .{AVX512F} ),
vec(.KMOVW, ops2(.rm_mem16, .reg_k), vex(.LZ,._NP,._0F,.W0, 0x91), .vMR, .{AVX512F} ),
vec(.KMOVW, ops2(.reg_k, .reg32), vex(.LZ,._NP,._0F,.W0, 0x92), .vRM, .{AVX512F} ),
vec(.KMOVW, ops2(.reg32, .reg_k), vex(.LZ,._NP,._0F,.W0, 0x93), .vRM, .{AVX512F} ),
//
vec(.KMOVD, ops2(.reg_k, .k_m32), vex(.LZ,._66,._0F,.W1, 0x90), .vRM, .{AVX512BW} ),
vec(.KMOVD, ops2(.rm_mem32, .reg_k), vex(.LZ,._66,._0F,.W1, 0x91), .vMR, .{AVX512BW} ),
vec(.KMOVD, ops2(.reg_k, .reg32), vex(.LZ,._F2,._0F,.W0, 0x92), .vRM, .{AVX512BW} ),
vec(.KMOVD, ops2(.reg32, .reg_k), vex(.LZ,._F2,._0F,.W0, 0x93), .vRM, .{AVX512BW} ),
//
vec(.KMOVQ, ops2(.reg_k, .k_m64), vex(.LZ,._NP,._0F,.W1, 0x90), .vRM, .{AVX512BW} ),
vec(.KMOVQ, ops2(.rm_mem64, .reg_k), vex(.LZ,._NP,._0F,.W1, 0x91), .vMR, .{AVX512BW} ),
vec(.KMOVQ, ops2(.reg_k, .reg64), vex(.LZ,._F2,._0F,.W1, 0x92), .vRM, .{AVX512BW, No32} ),
vec(.KMOVQ, ops2(.reg64, .reg_k), vex(.LZ,._F2,._0F,.W1, 0x93), .vRM, .{AVX512BW, No32} ),
// KSHIFTLW / KSHIFTLB / KSHIFTLD / KSHIFTLQ
vec(.KSHIFTLB, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W0, 0x32), .vRMI,.{AVX512DQ} ),
vec(.KSHIFTLW, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W1, 0x32), .vRMI,.{AVX512F} ),
vec(.KSHIFTLD, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W0, 0x33), .vRMI,.{AVX512BW} ),
vec(.KSHIFTLQ, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W1, 0x33), .vRMI,.{AVX512BW} ),
// KSHIFTRW / KSHIFTRB / KSHIFTRD / KSHIFTRQ
vec(.KSHIFTRB, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W0, 0x30), .vRMI,.{AVX512DQ} ),
vec(.KSHIFTRW, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W1, 0x30), .vRMI,.{AVX512F} ),
vec(.KSHIFTRD, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W0, 0x31), .vRMI,.{AVX512BW} ),
vec(.KSHIFTRQ, ops3(.reg_k, .reg_k, .imm8), vex(.LZ,._66,._0F3A,.W1, 0x31), .vRMI,.{AVX512BW} ),
// KTESTW / KTESTB / KTESTD / KTESTQ
vec(.KTESTB, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W0, 0x99), .vRM, .{AVX512DQ} ),
vec(.KTESTW, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W0, 0x99), .vRM, .{AVX512DQ} ),
vec(.KTESTD, ops2(.reg_k, .reg_k), vex(.LZ,._66,._0F,.W1, 0x99), .vRM, .{AVX512BW} ),
vec(.KTESTQ, ops2(.reg_k, .reg_k), vex(.LZ,._NP,._0F,.W1, 0x99), .vRM, .{AVX512BW} ),
// KUNPCKBW / KUNPCKWD / KUNPCKDQ
vec(.KUNPCKBW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x4B), .RVM, .{AVX512F} ),
vec(.KUNPCKWD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x4B), .RVM, .{AVX512BW} ),
vec(.KUNPCKDQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x4B), .RVM, .{AVX512BW} ),
// KXNORW / KXNORB / KXNORD / KXNORQ
vec(.KXNORB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x46), .RVM, .{AVX512DQ} ),
vec(.KXNORW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x46), .RVM, .{AVX512F} ),
vec(.KXNORD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x46), .RVM, .{AVX512BW} ),
vec(.KXNORQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x46), .RVM, .{AVX512BW} ),
// KXORW / KXORB / KXORD / KXORQ
vec(.KXORB, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W0, 0x47), .RVM, .{AVX512DQ} ),
vec(.KXORW, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W0, 0x47), .RVM, .{AVX512F} ),
vec(.KXORD, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._66,._0F,.W1, 0x47), .RVM, .{AVX512BW} ),
vec(.KXORQ, ops3(.reg_k, .reg_k, .reg_k), vex(.L1,._NP,._0F,.W1, 0x47), .RVM, .{AVX512BW} ),
//
// Xeon Phi
//
// PREFETCHWT1
instr(.PREFETCHWT1, ops1(.rm_mem8), Op2r(0x0F, 0x0D, 2), .M, .ZO, .{cpu.PREFETCHWT1} ),
//
// Undefined/Reserved Opcodes
//
// Unused opcodes are reserved for future instruction extensions, and most
// encodings will generate (#UD) on earlier processors. However, for
// compatibility with older processors, some reserved opcodes do not generate
// #UD but behave like other instructions or have unique behavior.
//
// SALC
// - Set AL to Cary flag. IF (CF=1), AL=FF, ELSE, AL=0 (#UD in 64-bit mode)
instr(.SALC, ops0(), Op1(0xD6), .ZO, .ZO, .{_8086, No64} ),
//
// Immediate Group 1
//
// Same behavior as corresponding instruction with Opcode Op1r(0x80, x)
//
instr(.RESRV_ADD, ops2(.rm8, .imm8), Op1r(0x82, 0), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_OR, ops2(.rm8, .imm8), Op1r(0x82, 1), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_ADC, ops2(.rm8, .imm8), Op1r(0x82, 2), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_SBB, ops2(.rm8, .imm8), Op1r(0x82, 3), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_AND, ops2(.rm8, .imm8), Op1r(0x82, 4), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_SUB, ops2(.rm8, .imm8), Op1r(0x82, 5), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_XOR, ops2(.rm8, .imm8), Op1r(0x82, 6), .MI, .ZO, .{_8086, No64} ),
instr(.RESRV_CMP, ops2(.rm8, .imm8), Op1r(0x82, 7), .MI, .ZO, .{_8086, No64} ),
//
// Shift Group 2 /6
//
// Same behavior as corresponding instruction with Opcode Op1r(x, 4)
//
instr(.RESRV_SAL, ops2(.rm8, .imm_1), Op1r(0xD0, 6), .M, .ZO, .{_8086} ),
instr(.RESRV_SAL, ops2(.rm8, .reg_cl), Op1r(0xD2, 6), .M, .ZO, .{_8086} ),
instr(.RESRV_SAL, ops2(.rm8, .imm8), Op1r(0xC0, 6), .MI, .ZO, .{_186} ),
instr(.RESRV_SAL, ops2(.rm16, .imm_1), Op1r(0xD1, 6), .M, .Op16, .{_8086} ),
instr(.RESRV_SAL, ops2(.rm32, .imm_1), Op1r(0xD1, 6), .M, .Op32, .{_386} ),
instr(.RESRV_SAL, ops2(.rm64, .imm_1), Op1r(0xD1, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_SAL, ops2(.rm16, .imm8), Op1r(0xC1, 6), .MI, .Op16, .{_186} ),
instr(.RESRV_SAL, ops2(.rm32, .imm8), Op1r(0xC1, 6), .MI, .Op32, .{_386} ),
instr(.RESRV_SAL, ops2(.rm64, .imm8), Op1r(0xC1, 6), .MI, .REX_W, .{x86_64} ),
instr(.RESRV_SAL, ops2(.rm16, .reg_cl), Op1r(0xD3, 6), .M, .Op16, .{_8086} ),
instr(.RESRV_SAL, ops2(.rm32, .reg_cl), Op1r(0xD3, 6), .M, .Op32, .{_386} ),
instr(.RESRV_SAL, ops2(.rm64, .reg_cl), Op1r(0xD3, 6), .M, .REX_W, .{x86_64} ),
//
instr(.RESRV_SHL, ops2(.rm8, .imm_1), Op1r(0xD0, 6), .M, .ZO, .{_8086} ),
instr(.RESRV_SHL, ops2(.rm8, .reg_cl), Op1r(0xD2, 6), .M, .ZO, .{_8086} ),
instr(.RESRV_SHL, ops2(.rm8, .imm8), Op1r(0xC0, 6), .MI, .ZO, .{_186} ),
instr(.RESRV_SHL, ops2(.rm16, .imm_1), Op1r(0xD1, 6), .M, .Op16, .{_8086} ),
instr(.RESRV_SHL, ops2(.rm32, .imm_1), Op1r(0xD1, 6), .M, .Op32, .{_386} ),
instr(.RESRV_SHL, ops2(.rm64, .imm_1), Op1r(0xD1, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_SHL, ops2(.rm16, .imm8), Op1r(0xC1, 6), .MI, .Op16, .{_186} ),
instr(.RESRV_SHL, ops2(.rm32, .imm8), Op1r(0xC1, 6), .MI, .Op32, .{_386} ),
instr(.RESRV_SHL, ops2(.rm64, .imm8), Op1r(0xC1, 6), .MI, .REX_W, .{x86_64} ),
instr(.RESRV_SHL, ops2(.rm16, .reg_cl), Op1r(0xD3, 6), .M, .Op16, .{_8086} ),
instr(.RESRV_SHL, ops2(.rm32, .reg_cl), Op1r(0xD3, 6), .M, .Op32, .{_386} ),
instr(.RESRV_SHL, ops2(.rm64, .reg_cl), Op1r(0xD3, 6), .M, .REX_W, .{x86_64} ),
//
// Unary Group 3 /1
//
instr(.RESRV_TEST, ops2(.rm8, .imm8), Op1r(0xF6, 1), .MI, .ZO, .{_8086} ),
instr(.RESRV_TEST, ops2(.rm16, .imm16), Op1r(0xF7, 1), .MI, .Op16, .{_8086} ),
instr(.RESRV_TEST, ops2(.rm32, .imm32), Op1r(0xF7, 1), .MI, .Op32, .{_386} ),
instr(.RESRV_TEST, ops2(.rm64, .imm32), Op1r(0xF7, 1), .MI, .REX_W, .{x86_64} ),
//
// x87
//
// DCD0 - DCD7 (same as FCOM D8D0-D8D7)
instr(.RESRV_FCOM, ops2(.reg_st0, .reg_st), Op2(0xDC, 0xD0), .O2, .ZO, .{_087} ),
instr(.RESRV_FCOM, ops1(.reg_st), Op2(0xDC, 0xD0), .O, .ZO, .{_087} ),
instr(.RESRV_FCOM, ops0(), Op2(0xDC, 0xD1), .ZO, .ZO, .{_087} ),
// DCD8 - DCDF (same as FCOMP D8D8-D8DF)
instr(.RESRV_FCOMP, ops2(.reg_st0, .reg_st), Op2(0xDC, 0xD8), .O2, .ZO, .{_087} ),
instr(.RESRV_FCOMP, ops1(.reg_st), Op2(0xDC, 0xD8), .O, .ZO, .{_087} ),
instr(.RESRV_FCOMP, ops0(), Op2(0xDC, 0xD9), .ZO, .ZO, .{_087} ),
// DED0 - DED7 (same as FCOMP D8C8-D8DF)
instr(.RESRV_FCOMP2, ops2(.reg_st0, .reg_st), Op2(0xDE, 0xD0), .O2, .ZO, .{_087} ),
instr(.RESRV_FCOMP2, ops1(.reg_st), Op2(0xDE, 0xD0), .O, .ZO, .{_087} ),
instr(.RESRV_FCOMP2, ops0(), Op2(0xDE, 0xD1), .ZO, .ZO, .{_087} ),
// D0C8 - D0CF (same as FXCH D9C8-D9CF)
instr(.RESRV_FXCH, ops2(.reg_st0, .reg_st), Op2(0xD0, 0xC8), .O2, .ZO, .{_087} ),
instr(.RESRV_FXCH, ops1(.reg_st), Op2(0xD0, 0xC8), .O, .ZO, .{_087} ),
instr(.RESRV_FXCH, ops0(), Op2(0xD0, 0xC9), .ZO, .ZO, .{_087} ),
// DFC8 - DFCF (same as FXCH D9C8-D9CF)
instr(.RESRV_FXCH2, ops2(.reg_st0, .reg_st), Op2(0xDF, 0xC8), .O2, .ZO, .{_087} ),
instr(.RESRV_FXCH2, ops1(.reg_st), Op2(0xDF, 0xC8), .O, .ZO, .{_087} ),
instr(.RESRV_FXCH2, ops0(), Op2(0xDF, 0xC9), .ZO, .ZO, .{_087} ),
// DFD0 - DFD7 (same as FSTP DDD8-DDDF)
instr(.RESRV_FSTP, ops1(.reg_st), Op2(0xDF, 0xD0), .O, .ZO, .{_087} ),
instr(.RESRV_FSTP, ops2(.reg_st0, .reg_st), Op2(0xDF, 0xD0), .O2, .ZO, .{_087} ),
// DFD8 - DFDF (same as FSTP DDD8-DDDF)
instr(.RESRV_FSTP2, ops1(.reg_st), Op2(0xDF, 0xD8), .O, .ZO, .{_087} ),
instr(.RESRV_FSTP2, ops2(.reg_st0, .reg_st), Op2(0xDF, 0xD8), .O2, .ZO, .{_087} ),
// D9D8 - D9DF (same as FFREE with addition of an x87 POP)
instr(.FFREEP, ops1(.reg_st), Op2(0xDF, 0xC0), .O, .ZO, .{_287} ),
// DFC0 - DFC7 (same as FSTP DDD8-DDDF but won't cause a stack underflow exception)
instr(.FSTPNOUFLOW, ops1(.reg_st), Op2(0xDD, 0xD8), .O, .ZO, .{_087} ),
instr(.FSTPNOUFLOW, ops2(.reg_st0, .reg_st), Op2(0xDD, 0xD8), .O2, .ZO, .{_087} ),
//
// Reserved NOP
// - Reserved instructions which have no defined impact on existing architectural state.
// - All opcodes `0F 0D` and opcodes in range `0F 18` to `0F 1F` that are not defined above
// NOP - 0F 0D
// PREFETCH Op2r(0x0F, 0x0D, 0)
instr(.RESRV_NOP_0F0D_0, ops1(.rm16), Op2r(0x0F, 0x0D, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_0, ops1(.rm32), Op2r(0x0F, 0x0D, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_0, ops1(.rm64), Op2r(0x0F, 0x0D, 0), .M, .REX_W, .{x86_64} ),
// PREFETCHW Op2r(0x0F, 0x0D, 1)
instr(.RESRV_NOP_0F0D_1, ops1(.rm16), Op2r(0x0F, 0x0D, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_1, ops1(.rm32), Op2r(0x0F, 0x0D, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_1, ops1(.rm64), Op2r(0x0F, 0x0D, 1), .M, .REX_W, .{x86_64} ),
// PREFETCHWT1 Op2r(0x0F, 0x0D, 2)
instr(.RESRV_NOP_0F0D_2, ops1(.rm16), Op2r(0x0F, 0x0D, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_2, ops1(.rm32), Op2r(0x0F, 0x0D, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_2, ops1(.rm64), Op2r(0x0F, 0x0D, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F0D_3, ops1(.rm16), Op2r(0x0F, 0x0D, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_3, ops1(.rm32), Op2r(0x0F, 0x0D, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_3, ops1(.rm64), Op2r(0x0F, 0x0D, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F0D_4, ops1(.rm16), Op2r(0x0F, 0x0D, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_4, ops1(.rm32), Op2r(0x0F, 0x0D, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_4, ops1(.rm64), Op2r(0x0F, 0x0D, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F0D_5, ops1(.rm16), Op2r(0x0F, 0x0D, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_5, ops1(.rm32), Op2r(0x0F, 0x0D, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_5, ops1(.rm64), Op2r(0x0F, 0x0D, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F0D_6, ops1(.rm16), Op2r(0x0F, 0x0D, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_6, ops1(.rm32), Op2r(0x0F, 0x0D, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_6, ops1(.rm64), Op2r(0x0F, 0x0D, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F0D_7, ops1(.rm16), Op2r(0x0F, 0x0D, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F0D_7, ops1(.rm32), Op2r(0x0F, 0x0D, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F0D_7, ops1(.rm64), Op2r(0x0F, 0x0D, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 18
// PREFETCHNTA Op2r(0x0F, 0x18, 0)
instr(.RESRV_NOP_0F18_0, ops1(.rm16), Op2r(0x0F, 0x18, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_0, ops1(.rm32), Op2r(0x0F, 0x18, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_0, ops1(.rm64), Op2r(0x0F, 0x18, 0), .M, .REX_W, .{x86_64} ),
// PREFETCHT0 Op2r(0x0F, 0x18, 1)
instr(.RESRV_NOP_0F18_1, ops1(.rm16), Op2r(0x0F, 0x18, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_1, ops1(.rm32), Op2r(0x0F, 0x18, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_1, ops1(.rm64), Op2r(0x0F, 0x18, 1), .M, .REX_W, .{x86_64} ),
// PREFETCHT1 Op2r(0x0F, 0x18, 2)
instr(.RESRV_NOP_0F18_2, ops1(.rm16), Op2r(0x0F, 0x18, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_2, ops1(.rm32), Op2r(0x0F, 0x18, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_2, ops1(.rm64), Op2r(0x0F, 0x18, 2), .M, .REX_W, .{x86_64} ),
// PREFETCHT2 Op2r(0x0F, 0x18, 3)
instr(.RESRV_NOP_0F18_3, ops1(.rm16), Op2r(0x0F, 0x18, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_3, ops1(.rm32), Op2r(0x0F, 0x18, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_3, ops1(.rm64), Op2r(0x0F, 0x18, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F18_4, ops1(.rm16), Op2r(0x0F, 0x18, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_4, ops1(.rm32), Op2r(0x0F, 0x18, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_4, ops1(.rm64), Op2r(0x0F, 0x18, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F18_5, ops1(.rm16), Op2r(0x0F, 0x18, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_5, ops1(.rm32), Op2r(0x0F, 0x18, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_5, ops1(.rm64), Op2r(0x0F, 0x18, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F18_6, ops1(.rm16), Op2r(0x0F, 0x18, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_6, ops1(.rm32), Op2r(0x0F, 0x18, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_6, ops1(.rm64), Op2r(0x0F, 0x18, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F18_7, ops1(.rm16), Op2r(0x0F, 0x18, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F18_7, ops1(.rm32), Op2r(0x0F, 0x18, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F18_7, ops1(.rm64), Op2r(0x0F, 0x18, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 19
instr(.RESRV_NOP_0F19_0, ops1(.rm16), Op2r(0x0F, 0x19, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_0, ops1(.rm32), Op2r(0x0F, 0x19, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_0, ops1(.rm64), Op2r(0x0F, 0x19, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_1, ops1(.rm16), Op2r(0x0F, 0x19, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_1, ops1(.rm32), Op2r(0x0F, 0x19, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_1, ops1(.rm64), Op2r(0x0F, 0x19, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_2, ops1(.rm16), Op2r(0x0F, 0x19, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_2, ops1(.rm32), Op2r(0x0F, 0x19, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_2, ops1(.rm64), Op2r(0x0F, 0x19, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_3, ops1(.rm16), Op2r(0x0F, 0x19, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_3, ops1(.rm32), Op2r(0x0F, 0x19, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_3, ops1(.rm64), Op2r(0x0F, 0x19, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_4, ops1(.rm16), Op2r(0x0F, 0x19, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_4, ops1(.rm32), Op2r(0x0F, 0x19, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_4, ops1(.rm64), Op2r(0x0F, 0x19, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_5, ops1(.rm16), Op2r(0x0F, 0x19, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_5, ops1(.rm32), Op2r(0x0F, 0x19, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_5, ops1(.rm64), Op2r(0x0F, 0x19, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_6, ops1(.rm16), Op2r(0x0F, 0x19, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_6, ops1(.rm32), Op2r(0x0F, 0x19, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_6, ops1(.rm64), Op2r(0x0F, 0x19, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F19_7, ops1(.rm16), Op2r(0x0F, 0x19, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F19_7, ops1(.rm32), Op2r(0x0F, 0x19, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F19_7, ops1(.rm64), Op2r(0x0F, 0x19, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1A
instr(.RESRV_NOP_0F1A_0, ops1(.rm16), Op2r(0x0F, 0x1A, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_0, ops1(.rm32), Op2r(0x0F, 0x1A, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_0, ops1(.rm64), Op2r(0x0F, 0x1A, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_1, ops1(.rm16), Op2r(0x0F, 0x1A, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_1, ops1(.rm32), Op2r(0x0F, 0x1A, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_1, ops1(.rm64), Op2r(0x0F, 0x1A, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_2, ops1(.rm16), Op2r(0x0F, 0x1A, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_2, ops1(.rm32), Op2r(0x0F, 0x1A, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_2, ops1(.rm64), Op2r(0x0F, 0x1A, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_3, ops1(.rm16), Op2r(0x0F, 0x1A, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_3, ops1(.rm32), Op2r(0x0F, 0x1A, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_3, ops1(.rm64), Op2r(0x0F, 0x1A, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_4, ops1(.rm16), Op2r(0x0F, 0x1A, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_4, ops1(.rm32), Op2r(0x0F, 0x1A, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_4, ops1(.rm64), Op2r(0x0F, 0x1A, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_5, ops1(.rm16), Op2r(0x0F, 0x1A, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_5, ops1(.rm32), Op2r(0x0F, 0x1A, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_5, ops1(.rm64), Op2r(0x0F, 0x1A, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_6, ops1(.rm16), Op2r(0x0F, 0x1A, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_6, ops1(.rm32), Op2r(0x0F, 0x1A, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_6, ops1(.rm64), Op2r(0x0F, 0x1A, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1A_7, ops1(.rm16), Op2r(0x0F, 0x1A, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1A_7, ops1(.rm32), Op2r(0x0F, 0x1A, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1A_7, ops1(.rm64), Op2r(0x0F, 0x1A, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1B
instr(.RESRV_NOP_0F1B_0, ops1(.rm16), Op2r(0x0F, 0x1B, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_0, ops1(.rm32), Op2r(0x0F, 0x1B, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_0, ops1(.rm64), Op2r(0x0F, 0x1B, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_1, ops1(.rm16), Op2r(0x0F, 0x1B, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_1, ops1(.rm32), Op2r(0x0F, 0x1B, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_1, ops1(.rm64), Op2r(0x0F, 0x1B, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_2, ops1(.rm16), Op2r(0x0F, 0x1B, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_2, ops1(.rm32), Op2r(0x0F, 0x1B, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_2, ops1(.rm64), Op2r(0x0F, 0x1B, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_3, ops1(.rm16), Op2r(0x0F, 0x1B, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_3, ops1(.rm32), Op2r(0x0F, 0x1B, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_3, ops1(.rm64), Op2r(0x0F, 0x1B, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_4, ops1(.rm16), Op2r(0x0F, 0x1B, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_4, ops1(.rm32), Op2r(0x0F, 0x1B, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_4, ops1(.rm64), Op2r(0x0F, 0x1B, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_5, ops1(.rm16), Op2r(0x0F, 0x1B, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_5, ops1(.rm32), Op2r(0x0F, 0x1B, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_5, ops1(.rm64), Op2r(0x0F, 0x1B, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_6, ops1(.rm16), Op2r(0x0F, 0x1B, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_6, ops1(.rm32), Op2r(0x0F, 0x1B, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_6, ops1(.rm64), Op2r(0x0F, 0x1B, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1B_7, ops1(.rm16), Op2r(0x0F, 0x1B, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1B_7, ops1(.rm32), Op2r(0x0F, 0x1B, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1B_7, ops1(.rm64), Op2r(0x0F, 0x1B, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1C
// CLDEMOTE preOp2r(._NP, 0x0F, 0x1C, 0)
instr(.RESRV_NOP_0F1C_0, ops1(.rm16), Op2r(0x0F, 0x1C, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_0, ops1(.rm32), Op2r(0x0F, 0x1C, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_0, ops1(.rm64), Op2r(0x0F, 0x1C, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_1, ops1(.rm16), Op2r(0x0F, 0x1C, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_1, ops1(.rm32), Op2r(0x0F, 0x1C, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_1, ops1(.rm64), Op2r(0x0F, 0x1C, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_2, ops1(.rm16), Op2r(0x0F, 0x1C, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_2, ops1(.rm32), Op2r(0x0F, 0x1C, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_2, ops1(.rm64), Op2r(0x0F, 0x1C, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_3, ops1(.rm16), Op2r(0x0F, 0x1C, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_3, ops1(.rm32), Op2r(0x0F, 0x1C, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_3, ops1(.rm64), Op2r(0x0F, 0x1C, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_4, ops1(.rm16), Op2r(0x0F, 0x1C, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_4, ops1(.rm32), Op2r(0x0F, 0x1C, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_4, ops1(.rm64), Op2r(0x0F, 0x1C, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_5, ops1(.rm16), Op2r(0x0F, 0x1C, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_5, ops1(.rm32), Op2r(0x0F, 0x1C, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_5, ops1(.rm64), Op2r(0x0F, 0x1C, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_6, ops1(.rm16), Op2r(0x0F, 0x1C, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_6, ops1(.rm32), Op2r(0x0F, 0x1C, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_6, ops1(.rm64), Op2r(0x0F, 0x1C, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1C_7, ops1(.rm16), Op2r(0x0F, 0x1C, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1C_7, ops1(.rm32), Op2r(0x0F, 0x1C, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1C_7, ops1(.rm64), Op2r(0x0F, 0x1C, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1D
instr(.RESRV_NOP_0F1D_0, ops1(.rm16), Op2r(0x0F, 0x1D, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_0, ops1(.rm32), Op2r(0x0F, 0x1D, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_0, ops1(.rm64), Op2r(0x0F, 0x1D, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_1, ops1(.rm16), Op2r(0x0F, 0x1D, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_1, ops1(.rm32), Op2r(0x0F, 0x1D, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_1, ops1(.rm64), Op2r(0x0F, 0x1D, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_2, ops1(.rm16), Op2r(0x0F, 0x1D, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_2, ops1(.rm32), Op2r(0x0F, 0x1D, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_2, ops1(.rm64), Op2r(0x0F, 0x1D, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_3, ops1(.rm16), Op2r(0x0F, 0x1D, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_3, ops1(.rm32), Op2r(0x0F, 0x1D, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_3, ops1(.rm64), Op2r(0x0F, 0x1D, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_4, ops1(.rm16), Op2r(0x0F, 0x1D, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_4, ops1(.rm32), Op2r(0x0F, 0x1D, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_4, ops1(.rm64), Op2r(0x0F, 0x1D, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_5, ops1(.rm16), Op2r(0x0F, 0x1D, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_5, ops1(.rm32), Op2r(0x0F, 0x1D, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_5, ops1(.rm64), Op2r(0x0F, 0x1D, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_6, ops1(.rm16), Op2r(0x0F, 0x1D, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_6, ops1(.rm32), Op2r(0x0F, 0x1D, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_6, ops1(.rm64), Op2r(0x0F, 0x1D, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1D_7, ops1(.rm16), Op2r(0x0F, 0x1D, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1D_7, ops1(.rm32), Op2r(0x0F, 0x1D, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1D_7, ops1(.rm64), Op2r(0x0F, 0x1D, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1E
instr(.RESRV_NOP_0F1E_0, ops1(.rm16), Op2r(0x0F, 0x1E, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_0, ops1(.rm32), Op2r(0x0F, 0x1E, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_0, ops1(.rm64), Op2r(0x0F, 0x1E, 0), .M, .REX_W, .{x86_64} ),
// RDSSPD preOp2r(._F3, 0x0F, 0x1E, 1)
// RDSSPQ preOp2r(._F3, 0x0F, 0x1E, 1)
instr(.RESRV_NOP_0F1E_1, ops1(.rm16), Op2r(0x0F, 0x1E, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_1, ops1(.rm32), Op2r(0x0F, 0x1E, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_1, ops1(.rm64), Op2r(0x0F, 0x1E, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1E_2, ops1(.rm16), Op2r(0x0F, 0x1E, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_2, ops1(.rm32), Op2r(0x0F, 0x1E, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_2, ops1(.rm64), Op2r(0x0F, 0x1E, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1E_3, ops1(.rm16), Op2r(0x0F, 0x1E, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_3, ops1(.rm32), Op2r(0x0F, 0x1E, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_3, ops1(.rm64), Op2r(0x0F, 0x1E, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1E_4, ops1(.rm16), Op2r(0x0F, 0x1E, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_4, ops1(.rm32), Op2r(0x0F, 0x1E, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_4, ops1(.rm64), Op2r(0x0F, 0x1E, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1E_5, ops1(.rm16), Op2r(0x0F, 0x1E, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_5, ops1(.rm32), Op2r(0x0F, 0x1E, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_5, ops1(.rm64), Op2r(0x0F, 0x1E, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1E_6, ops1(.rm16), Op2r(0x0F, 0x1E, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_6, ops1(.rm32), Op2r(0x0F, 0x1E, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_6, ops1(.rm64), Op2r(0x0F, 0x1E, 6), .M, .REX_W, .{x86_64} ),
// ENDBR32 preOp3(._F3, 0x0F, 0x1E, 0xFB)
// ENDBR64 preOp3(._F3, 0x0F, 0x1E, 0xFA)
instr(.RESRV_NOP_0F1E_7, ops1(.rm16), Op2r(0x0F, 0x1E, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1E_7, ops1(.rm32), Op2r(0x0F, 0x1E, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1E_7, ops1(.rm64), Op2r(0x0F, 0x1E, 7), .M, .REX_W, .{x86_64} ),
// NOP - 0F 1F
instr(.RESRV_NOP_0F1F_0, ops1(.rm16), Op2r(0x0F, 0x1F, 0), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_0, ops1(.rm32), Op2r(0x0F, 0x1F, 0), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_0, ops1(.rm64), Op2r(0x0F, 0x1F, 0), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_1, ops1(.rm16), Op2r(0x0F, 0x1F, 1), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_1, ops1(.rm32), Op2r(0x0F, 0x1F, 1), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_1, ops1(.rm64), Op2r(0x0F, 0x1F, 1), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_2, ops1(.rm16), Op2r(0x0F, 0x1F, 2), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_2, ops1(.rm32), Op2r(0x0F, 0x1F, 2), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_2, ops1(.rm64), Op2r(0x0F, 0x1F, 2), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_3, ops1(.rm16), Op2r(0x0F, 0x1F, 3), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_3, ops1(.rm32), Op2r(0x0F, 0x1F, 3), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_3, ops1(.rm64), Op2r(0x0F, 0x1F, 3), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_4, ops1(.rm16), Op2r(0x0F, 0x1F, 4), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_4, ops1(.rm32), Op2r(0x0F, 0x1F, 4), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_4, ops1(.rm64), Op2r(0x0F, 0x1F, 4), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_5, ops1(.rm16), Op2r(0x0F, 0x1F, 5), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_5, ops1(.rm32), Op2r(0x0F, 0x1F, 5), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_5, ops1(.rm64), Op2r(0x0F, 0x1F, 5), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_6, ops1(.rm16), Op2r(0x0F, 0x1F, 6), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_6, ops1(.rm32), Op2r(0x0F, 0x1F, 6), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_6, ops1(.rm64), Op2r(0x0F, 0x1F, 6), .M, .REX_W, .{x86_64} ),
instr(.RESRV_NOP_0F1F_7, ops1(.rm16), Op2r(0x0F, 0x1F, 7), .M, .Op16, .{P6} ),
instr(.RESRV_NOP_0F1F_7, ops1(.rm32), Op2r(0x0F, 0x1F, 7), .M, .Op32, .{P6} ),
instr(.RESRV_NOP_0F1F_7, ops1(.rm64), Op2r(0x0F, 0x1F, 7), .M, .REX_W, .{x86_64} ),
//
// Legacy, obsolete and undocumented Opcodes
//
// STOREALL
// see: https://web.archive.org/save/http://www.vcfed.org/forum/showthread.php?70386-I-found-the-SAVEALL-opcode/page2
instr(.STOREALL, ops0(), Op2(0x0F, 0x04), .ZO, .ZO, .{cpu._286_Legacy, No64} ),
// LOADALL
instr(.LOADALL, ops0(), Op2(0x0F, 0x05), .ZO, .ZO, .{cpu._286_Legacy, No64} ),
instr(.LOADALL, ops0(), Op2(0x0F, 0x07), .ZO, .ZO, .{cpu._386_Legacy, No64} ),
instr(.LOADALLD, ops0(), Op2(0x0F, 0x07), .ZO, .ZO, .{cpu._386_Legacy, No64} ),
// UMOV
instr(.UMOV, ops2(.rm8, .reg8), Op2(0x0F, 0x10), .MR, .ZO, .{_386_Legacy, No64} ),
instr(.UMOV, ops2(.rm16, .reg16), Op2(0x0F, 0x11), .MR, .Op16, .{_386_Legacy, No64} ),
instr(.UMOV, ops2(.rm32, .reg32), Op2(0x0F, 0x11), .MR, .Op32, .{_386_Legacy, No64} ),
//
instr(.UMOV, ops2(.reg8, .rm8), Op2(0x0F, 0x12), .RM, .ZO, .{_386_Legacy, No64} ),
instr(.UMOV, ops2(.reg16, .rm16), Op2(0x0F, 0x13), .RM, .Op32, .{_386_Legacy, No64} ),
instr(.UMOV, ops2(.reg32, .rm32), Op2(0x0F, 0x13), .RM, .Op32, .{_386_Legacy, No64} ),
//
instr(.UMOV, ops2(.rm8, .reg8), Op2(0x0F, 0x10), .MR, .ZO, .{_486_Legacy, No64} ),
instr(.UMOV, ops2(.rm16, .reg16), Op2(0x0F, 0x11), .MR, .Op16, .{_486_Legacy, No64} ),
instr(.UMOV, ops2(.rm32, .reg32), Op2(0x0F, 0x11), .MR, .Op32, .{_486_Legacy, No64} ),
//
instr(.UMOV, ops2(.reg8, .rm8), Op2(0x0F, 0x12), .RM, .ZO, .{_486_Legacy, No64} ),
instr(.UMOV, ops2(.reg16, .rm16), Op2(0x0F, 0x13), .RM, .Op32, .{_486_Legacy, No64} ),
instr(.UMOV, ops2(.reg32, .rm32), Op2(0x0F, 0x13), .RM, .Op32, .{_486_Legacy, No64} ),
// Dummy sigil value that marks the end of the table, use this to avoid
// extra bounds checking when scanning this table.
instr(._mnemonic_final, ops0(), Opcode{}, .ZO, .ZO, .{} ),
}; | src/x86/database.zig |
const std = @import("std");
test "example" {
const input = @embedFile("11_example.txt");
const result = run(input);
try std.testing.expectEqual(@as(usize, 195), result);
}
pub fn main() void {
const input = @embedFile("11.txt");
const result = run(input);
std.debug.print("{}\n", .{result});
}
const Grid = [10][10]u4;
const BitSet = std.StaticBitSet(100);
fn run(input: []const u8) usize {
var grid = parse(input);
var i: usize = 1;
while (true) : (i += 1) {
if (nextStep(&grid) == 100) return i;
}
}
// returns the number of flashes
fn nextStep(grid: *Grid) usize {
// Inc by 1
for (grid) |*row| {
for (row.*) |*o| {
o.* +|= 1;
}
}
var flashes = BitSet.initEmpty();
// Recursively Flash
for (grid) |row, r| {
for (row) |_, c| {
flash(grid, &flashes, r, c);
}
}
// Reset
for (grid) |*row, r| {
for (row.*) |*o, c| {
if (flashes.isSet(r * 10 + c)) {
o.* = 0;
}
}
}
return flashes.count();
}
fn flash(grid: *Grid, flashes: *BitSet, row: usize, col: usize) void {
const bit_index = row * 10 + col;
if (flashes.isSet(bit_index)) return;
if (grid[row][col] <= 9) return;
// Mark as flashed
flashes.set(bit_index);
const has_top = row > 0;
const has_bottom = row + 1 < 10;
const has_left = col > 0;
const has_right = col + 1 < 10;
// Flash Neighbors
if (has_top) grid[row - 1][col] +|= 1; // Top
if (has_bottom) grid[row + 1][col] +|= 1; // Bottom
if (has_left) grid[row][col - 1] +|= 1; // Left
if (has_right) grid[row][col + 1] +|= 1; // Right
if (has_top and has_left) grid[row - 1][col - 1] +|= 1; // Top Left
if (has_top and has_right) grid[row - 1][col + 1] +|= 1; // Top Right
if (has_bottom and has_left) grid[row + 1][col - 1] +|= 1; // Bottom Left
if (has_bottom and has_right) grid[row + 1][col + 1] +|= 1; // Bottom Right
// Make neigbors flash
if (has_top) flash(grid, flashes, row - 1, col); // Top
if (has_bottom) flash(grid, flashes, row + 1, col); // Bottom
if (has_left) flash(grid, flashes, row, col - 1); // Left
if (has_right) flash(grid, flashes, row, col + 1); // Right
if (has_top and has_left) flash(grid, flashes, row - 1, col - 1); // Top Left
if (has_top and has_right) flash(grid, flashes, row - 1, col + 1); // Top Right
if (has_bottom and has_left) flash(grid, flashes, row + 1, col - 1); // Bottom Left
if (has_bottom and has_right) flash(grid, flashes, row + 1, col + 1); // Bottom Right
}
fn parse(input: []const u8) Grid {
var grid: Grid = undefined;
var row: usize = 0;
var col: usize = 0;
for (input) |c| {
if (c == '\n') {
col = 0;
row += 1;
continue;
}
grid[row][col] = @intCast(u4, c - '0');
col += 1;
}
return grid;
} | shritesh+zig/11b.zig |
const std = @import("std");
const t = std.testing;
pub const base62Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".*;
pub const base = 62;
const zeroString = "000000000000000000000000000";
const offsetUppercase = 10;
const offsetLowercase = 36;
const stringEncodedLength = 27;
pub const Error = error{
InvalidCharacter,
DestTooShort,
};
pub fn fastEncode(dest: *[27]u8, source: *const [20]u8) []const u8 {
const srcBase = 4294967296;
const dstBase = 62;
var parts = [5]u32{
std.mem.readIntBig(u32, source[0..4]),
std.mem.readIntBig(u32, source[4..8]),
std.mem.readIntBig(u32, source[8..12]),
std.mem.readIntBig(u32, source[12..16]),
std.mem.readIntBig(u32, source[16..20]),
};
var n = dest.len;
var bp: []u32 = parts[0..];
var bq = [5]u32{ 0, 0, 0, 0, 0 };
while (bp.len != 0) {
var qidx: usize = 0;
var remainder: u64 = 0;
for (bp) |c| {
var r: u64 = undefined;
_ = @mulWithOverflow(u64, remainder, srcBase, &r);
var value = @intCast(u64, c) + r;
var digit = @divFloor(value, dstBase);
remainder = @mod(value, dstBase);
if (qidx != 0 or digit != 0) {
bq[qidx] = @truncate(u32, digit);
qidx += 1;
}
}
n -= 1;
dest[n] = base62Characters[remainder];
bp = bq[0..qidx];
}
std.mem.copy(u8, dest[0..n], zeroString[0..n]);
return dest[0..27];
}
fn base62Value(digit: u8) !u8 {
return switch (digit) {
'0'...'9' => (digit - '0'),
'A'...'Z' => offsetUppercase + (digit - 'A'),
'a'...'z' => offsetLowercase + (digit - 'a'),
else => error.InvalidCharacter,
};
}
pub fn fastDecode(dest: *[20]u8, source: *const [27]u8) ![]const u8 {
const srcBase = 62;
const dstBase = 4294967296;
var parts: [27]u8 = undefined;
var i: usize = 0;
for (parts) |_| {
parts[i] = try base62Value(source[i]);
i += 1;
}
var n = dest.len;
var bp: []u8 = parts[0..];
var bq: [27]u8 = undefined;
while (bp.len > 0) {
var qidx: usize = 0;
var remainder: u64 = 0;
for (bp) |c| {
var r: u64 = undefined;
_ = @mulWithOverflow(u64, remainder, srcBase, &r);
var value = @intCast(u64, c) + r;
var digit = @divFloor(value, dstBase);
remainder = @mod(value, dstBase);
if (qidx != 0 or digit != 0) {
bq[qidx] = @truncate(u8, digit);
qidx += 1;
}
}
if (n < 4) {
return error.DestTooShort;
}
dest[n - 4] = @truncate(u8, remainder >> 24);
dest[n - 3] = @truncate(u8, remainder >> 16);
dest[n - 2] = @truncate(u8, remainder >> 8);
dest[n - 1] = @truncate(u8, remainder);
n -= 4;
bp = bq[0..qidx];
}
var zero = [_]u8{0} ** 20;
std.mem.copy(u8, dest[0..n], zero[0..n]);
return dest[0..20];
}
test "base62 decode" {
var decoded: [20]u8 = undefined;
const outDec = try fastDecode(&decoded, "0ujtsYcgvSTl8PAuAdqWYSMnLOv");
var outbuf: [27]u8 = undefined;
const expected = try std.fmt.hexToBytes(&outbuf, "0669F7EFB5A1CD34B5F99D1154FB6853345C9735");
//std.debug.print("dec[{s}]\n", .{std.fmt.fmtSliceHexUpper(&decoded)});
try t.expectEqualSlices(u8, expected, outDec);
}
test "base62 encode" {
var outbuf: [27]u8 = undefined;
var toEnc = try std.fmt.hexToBytes(&outbuf, "0669F7EFB5A1CD34B5F99D1154FB6853345C9735");
var outEncBuf: [27]u8 = undefined;
const outEnc = fastEncode(&outEncBuf, toEnc[0..20]);
const expected = "0ujtsYcgvSTl8PAuAdqWYSMnLOv";
//std.debug.print("enc[{s}]\n", .{outEnc});
try t.expectEqualSlices(u8, expected, outEnc);
}
test "invalid" {
var decoded: [20]u8 = undefined;
if (fastDecode(&decoded, "$$$$$$$$$$$$$$$$$$$$$$$$$$$")) |_| {
return error.ExpectedError;
} else |err| if (err != error.InvalidCharacter) {
return err;
}
} | src/base62.zig |
const std = @import("std");
const pike = @import("pike.zig");
const Waker = @import("waker.zig").Waker;
const os = std.os;
const mem = std.mem;
pub const Event = struct {
const Self = @This();
handle: pike.Handle,
readers: Waker = .{},
writers: Waker = .{},
pub fn init() !Self {
return Self{
.handle = .{
.inner = try os.eventfd(0, os.linux.EFD.CLOEXEC | os.linux.EFD.NONBLOCK),
.wake_fn = wake,
},
};
}
pub fn deinit(self: *Self) void {
os.close(self.handle.inner);
if (self.writers.shutdown()) |task| pike.dispatch(task, .{});
if (self.readers.shutdown()) |task| pike.dispatch(task, .{});
}
pub fn registerTo(self: *const Self, notifier: *const pike.Notifier) !void {
try notifier.register(&self.handle, .{ .read = true, .write = true });
}
fn wake(handle: *pike.Handle, batch: *pike.Batch, opts: pike.WakeOptions) void {
const self = @fieldParentPtr(Self, "handle", handle);
if (opts.write_ready) if (self.writers.notify()) |task| batch.push(task);
if (opts.read_ready) if (self.readers.notify()) |task| batch.push(task);
if (opts.shutdown) {
if (self.writers.shutdown()) |task| batch.push(task);
if (self.readers.shutdown()) |task| batch.push(task);
}
}
fn ErrorUnionOf(comptime func: anytype) std.builtin.TypeInfo.ErrorUnion {
return @typeInfo(@typeInfo(@TypeOf(func)).Fn.return_type.?).ErrorUnion;
}
fn call(self: *Self, comptime function: anytype, args: anytype, comptime opts: pike.CallOptions) !ErrorUnionOf(function).payload {
while (true) {
const result = @call(.{ .modifier = .always_inline }, function, args) catch |err| switch (err) {
error.WouldBlock => {
if (comptime opts.write) {
try self.writers.wait(.{ .use_lifo = true });
} else if (comptime opts.read) {
try self.readers.wait(.{});
}
continue;
},
else => return err,
};
return result;
}
}
fn write(self: *Self, amount: u64) callconv(.Async) !void {
const num_bytes = try self.call(os.write, .{
self.handle.inner,
mem.asBytes(&amount),
}, .{ .write = true });
if (num_bytes != @sizeOf(@TypeOf(amount))) {
return error.ShortWrite;
}
}
fn read(self: *Self) callconv(.Async) !void {
var counter: u64 = 0;
const num_bytes = try self.call(os.read, .{
self.handle.inner,
mem.asBytes(&counter),
}, .{ .read = true });
if (num_bytes != @sizeOf(@TypeOf(counter))) {
return error.ShortRead;
}
}
pub fn post(self: *Self) callconv(.Async) !void {
var frame = async self.read();
try self.write(1);
try await frame;
}
}; | event_epoll.zig |
const std = @import("std");
const nvg = @import("nanovg");
const gui = @import("gui.zig");
usingnamespace @import("event.zig");
const Point = @import("geometry.zig").Point;
const Application = @This();
pub const SystemFunctions = struct {
// essential
createWindow: fn ([:0]const u8, u32, u32, gui.Window.CreateOptions, *gui.Window) anyerror!u32,
destroyWindow: fn (u32) void,
setWindowTitle: fn (u32, [:0]const u8) void,
// optional
startTimer: ?fn (*gui.Timer, u32) u32 = null,
cancelTimer: ?fn (u32) void = null,
showCursor: ?fn (bool) void = null,
hasClipboardText: ?fn () bool = null,
getClipboardText: ?fn (std.mem.Allocator) anyerror!?[]const u8 = null,
setClipboardText: ?fn (std.mem.Allocator, []const u8) anyerror!void = null,
};
var system: SystemFunctions = undefined;
allocator: std.mem.Allocator,
windows: std.ArrayList(*gui.Window),
//main_window: ?*gui.Window = null,
const Self = @This();
pub fn init(allocator: std.mem.Allocator, system_functions: SystemFunctions) !*Self {
system = system_functions;
var self = try allocator.create(Application);
self.* = Self{
.allocator = allocator,
.windows = std.ArrayList(*gui.Window).init(allocator),
};
return self;
}
pub fn deinit(self: *Self) void {
for (self.windows.items) |window| {
self.allocator.destroy(window);
}
self.windows.deinit();
self.allocator.destroy(self);
}
pub fn createWindow(self: *Self, title: [:0]const u8, width: f32, height: f32, options: gui.Window.CreateOptions) !*gui.Window {
var window = try gui.Window.init(self.allocator, self);
errdefer self.allocator.destroy(window);
const system_window_id = try system.createWindow(
title,
@floatToInt(u32, width),
@floatToInt(u32, height),
options,
window,
);
window.id = system_window_id;
window.width = width;
window.height = height;
try self.windows.append(window);
return window;
}
pub fn setWindowTitle(window_id: u32, title: [:0]const u8) void {
system.setWindowTitle(window_id, title);
}
pub fn requestWindowClose(self: *Self, window: *gui.Window) void {
if (window.isBlockedByModal()) return;
if (window.onCloseRequestFn) |onCloseRequest| {
if (!onCloseRequest(window.close_request_context)) return; // request denied
}
system.destroyWindow(window.id);
// remove reference from parent
if (window.parent) |parent| {
parent.removeChild(window);
window.parent = null;
}
// NOTE: isBlockedByModal is updated at this point
if (window.onClosedFn) |onClosed| {
onClosed(window.closed_context);
}
if (std.mem.indexOfScalar(*gui.Window, self.windows.items, window)) |i| {
_ = self.windows.swapRemove(i);
window.setMainWidget(null); // also removes reference to this window in main_widget
window.deinit();
}
}
pub fn showCursor(show: bool) void {
if (system.showCursor) |systemShowCursor| {
systemShowCursor(show);
}
}
pub fn hasClipboardText() bool {
if (system.hasClipboardText) |systemHasClipboardText| {
return systemHasClipboardText();
}
return false;
}
pub fn setClipboardText(allocator: std.mem.Allocator, text: []const u8) !void {
if (system.setClipboardText) |systemSetClipboardText| {
try systemSetClipboardText(allocator, text);
}
}
pub fn getClipboardText(allocator: std.mem.Allocator) !?[]const u8 {
if (system.getClipboardText) |systemGetClipboardText| {
return try systemGetClipboardText(allocator);
}
return null;
}
pub fn startTimer(timer: *gui.Timer, interval: u32) u32 {
if (system.startTimer) |systemStartTimer| {
return systemStartTimer(timer, interval);
}
return 0;
}
pub fn cancelTimer(id: u32) void {
if (system.cancelTimer) |systemCancelTimer| {
systemCancelTimer(id);
}
}
pub fn broadcastEvent(self: *Self, event: *gui.Event) void {
for (self.windows.items) |window| {
window.handleEvent(event);
}
} | src/gui/Application.zig |
const c = @cImport({
@cInclude("cfl_enums.h");
});
pub const Color = struct {
pub const ForeGround = 0;
pub const BackGround2 = 7;
pub const Inactive = 8;
pub const Selection = 15;
pub const Gray0 = 32;
pub const Dark3 = 39;
pub const Dark2 = 45;
pub const Dark1 = 47;
pub const BackGround = 49;
pub const Light1 = 50;
pub const Light2 = 52;
pub const Light3 = 54;
pub const Black = 56;
pub const Red = 88;
pub const Green = 63;
pub const Yellow = 95;
pub const Blue = 216;
pub const Magenta = 248;
pub const Cyan = 223;
pub const DarkRed = 72;
pub const DarkGreen = 60;
pub const DarkYellow = 76;
pub const DarkBlue = 136;
pub const DarkMagenta = 152;
pub const DarkCyan = 140;
pub const White = 255;
};
pub const Align = struct {
pub const Center = 0;
pub const Top = 1;
pub const Bottom = 2;
pub const Left = 4;
pub const Right = 8;
pub const Inside = 16;
pub const TextOverImage = 20;
pub const Clip = 40;
pub const Wrap = 80;
pub const ImageNextToText = 100;
pub const TextNextToImage = 120;
pub const ImageBackdrop = 200;
pub const TopLeft = 1 | 4;
pub const TopRight = 1 | 8;
pub const BottomLeft = 2 | 4;
pub const BottomRight = 2 | 8;
pub const LeftTop = 7;
pub const RightTop = 11;
pub const LeftBottom = 13;
pub const RightBottom = 14;
pub const PositionMask = 15;
pub const ImageMask = 320;
};
pub const LabelType = enum(i32) {
Normal = 0,
None,
Shadow,
Engraved,
Embossed,
Multi,
Icon,
Image,
FreeType,
};
pub const BoxType = enum(i32) {
NoBox = 0,
FlatBox,
UpBox,
DownBox,
UpFrame,
DownFrame,
ThinUpBox,
ThinDownBox,
ThinUpFrame,
ThinDownFrame,
EngraveBox,
EmbossedBox,
EngravedFrame,
EmbossedFrame,
BorderBox,
ShadowBox,
BorderFrame,
ShadowFrame,
RoundedBox,
RShadowBox,
RoundedFrame,
RFlatBox,
RoundUpBox,
RoundDownBox,
DiamondUpBox,
DiamondDownBox,
OvalBox,
OShadowBox,
OvalFrame,
OFlatFrame,
PlasticUpBox,
PlasticDownBox,
PlasticUpFrame,
PlasticDownFrame,
PlasticThinUpBox,
PlasticThinDownBox,
PlasticRoundUpBox,
PlasticRoundDownBox,
GtkUpBox,
GtkDownBox,
GtkUpFrame,
GtkDownFrame,
GtkThinUpBox,
GtkThinDownBox,
GtkThinUpFrame,
GtkThinDownFrame,
GtkRoundUpFrame,
GtkRoundDownFrame,
GleamUpBox,
GleamDownBox,
GleamUpFrame,
GleamDownFrame,
GleamThinUpBox,
GleamThinDownBox,
GleamRoundUpBox,
GleamRoundDownBox,
FreeBoxType,
};
pub const BrowserScrollbar = enum(i32) {
BrowserScrollbarNone = 0,
BrowserScrollbarHorizontal = 1,
BrowserScrollbarVertical = 2,
BrowserScrollbarBoth = 3,
BrowserScrollbarAlwaysOn = 4,
BrowserScrollbarHorizontalAlways = 5,
BrowserScrollbarVerticalAlways = 6,
BrowserScrollbarBothAlways = 7,
};
pub const Event = enum(i32) {
NoEvent = 0,
Push,
Released,
Enter,
Leave,
Drag,
Focus,
Unfocus,
KeyDown,
KeyUp,
Close,
Move,
Shortcut,
Deactivate,
Activate,
Hide,
Show,
Paste,
SelectionClear,
MouseWheel,
DndEnter,
DndDrag,
DndLeave,
DndRelease,
ScreenConfigChanged,
Fullscreen,
ZoomGesture,
ZoomEvent,
};
pub const Font = enum(i32) {
Helvetica = 0,
HelveticaBold = 1,
HelveticaItalic = 2,
HelveticaBoldItalic = 3,
Courier = 4,
CourierBold = 5,
CourierItalic = 6,
CourierBoldItalic = 7,
Times = 8,
TimesBold = 9,
TimesItalic = 10,
TimesBoldItalic = 11,
Symbol = 12,
Screen = 13,
ScreenBold = 14,
Zapfdingbats = 15,
};
pub const Key = struct {
pub const None = 0;
pub const Button = 0xfee8;
pub const BackSpace = 0xff08;
pub const Tab = 0xff09;
pub const IsoKey = 0xff0c;
pub const Enter = 0xff0d;
pub const Pause = 0xff13;
pub const ScrollLock = 0xff14;
pub const Escape = 0xff1b;
pub const Kana = 0xff2e;
pub const Eisu = 0xff2f;
pub const Yen = 0xff30;
pub const JISUnderscore = 0xff31;
pub const Home = 0xff50;
pub const Left = 0xff51;
pub const Up = 0xff52;
pub const Right = 0xff53;
pub const Down = 0xff54;
pub const PageUp = 0xff55;
pub const PageDown = 0xff56;
pub const End = 0xff57;
pub const Print = 0xff61;
pub const Insert = 0xff63;
pub const Menu = 0xff67;
pub const Help = 0xff68;
pub const NumLock = 0xff7f;
pub const KP = 0xff80;
pub const KPEnter = 0xff8d;
pub const KPLast = 0xffbd;
pub const FLast = 0xffe0;
pub const ShiftL = 0xffe1;
pub const ShiftR = 0xffe2;
pub const ControlL = 0xffe3;
pub const ControlR = 0xffe4;
pub const CapsLock = 0xffe5;
pub const MetaL = 0xffe7;
pub const MetaR = 0xffe8;
pub const AltL = 0xffe9;
pub const AltR = 0xffea;
pub const Delete = 0xffff;
};
pub const Shortcut = struct {
pub const None = 0;
pub const Shift = 0x00010000;
pub const CapsLock = 0x00020000;
pub const Ctrl = 0x00040000;
pub const Alt = 0x00080000;
};
pub const CallbackTrigger = struct {
pub const Never = 0;
pub const Changed = 1;
pub const NotChanged = 2;
pub const Release = 4;
pub const ReleaseAlways = 6;
pub const EnterKey = 8;
pub const EnterKeyAlways = 10;
pub const EnterKeyChanged = 11;
};
pub const Cursor = enum(i32) {
Default = 0,
Arrow = 35,
Cross = 66,
Wait = 76,
Insert = 77,
Hand = 31,
Help = 47,
Move = 27,
NS = 78,
WE = 79,
NWSE = 80,
NESW = 81,
N = 70,
NE = 69,
E = 49,
SE = 8,
S = 9,
SW = 7,
W = 36,
NW = 68,
None = 255,
};
pub const TextCursor = enum(u8) {
Normal,
Caret,
Dim,
Block,
Heavy,
Simple,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/enums.zig |
const std = @import("std");
const builtin = @import("builtin");
const mem = @import("gc.zig");
const target = @import("builtin").target;
const is_windows = target.os.tag == .windows;
const linenoise = @cImport({
if (!is_windows) {
@cInclude("stddef.h");
@cInclude("linenoise.h");
}
});
/// Linenoise wrapper with a Reader interface
const Linenoise = struct {
line: ?[:0]u8 = null,
index: usize = 0,
remaining: usize = 0,
eof_next: bool = false,
prompt: []const u8 = "",
fn init() Linenoise {
return .{};
}
pub fn hidePrompt(self: *Linenoise) void {
self.prompt = "";
}
/// Prints the REPL prompt. On nix* systems this is done by linenoise in readFn.
pub fn printPrompt(self: *Linenoise, prompt: []const u8) !void {
self.prompt = prompt;
if (is_windows and self.prompt.len > 0) {
try std.io.getStdOut().writer().print("{s}", .{self.prompt});
}
}
/// Add the given entry to the REPL history
pub fn addToHistory(_: *Linenoise, entry: []const u8) !void {
if (!is_windows and entry.len > 0) {
const duped = try mem.allocator.dupeZ(u8, entry);
defer mem.allocator.free(duped);
// Linenoise takes a copy
_ = linenoise.linenoiseHistoryAdd(duped);
}
}
/// This satisfies the Reader interface. The first call will cause
/// linenoise to be invoked with an optional prompt. The returned line
/// is then consumed, after which EndOfStream is returned. Rinse and
/// repeat. For Windows, we simply delegate to stdin.
fn readFn(self: *@This(), dest: []u8) anyerror!usize {
var copy_count: usize = 0;
if (!is_windows) {
if (self.eof_next) {
self.eof_next = false;
return error.EndOfStream;
}
if (self.remaining == 0) {
// This gives us a [*c]u8...
const c_line = linenoise.linenoise(self.prompt.ptr);
if (c_line == null) {
return error.EndOfStream;
}
// ...which we convert to a [:0]u8
self.line = std.mem.span(c_line);
self.remaining = self.line.?.len;
self.index = 0;
}
copy_count = std.math.min(self.remaining, dest.len);
if (copy_count > 0) std.mem.copy(u8, dest, self.line.?[self.index .. self.index + copy_count]);
self.remaining -= copy_count;
self.index += copy_count;
if (self.remaining == 0) {
self.eof_next = true;
std.heap.c_allocator.free(self.line.?);
}
return copy_count;
} else {
return std.io.getStdIn().reader().read(dest);
}
}
pub const Reader = std.io.Reader(*@This(), anyerror, readFn);
pub fn reader(self: *@This()) Reader {
return .{ .context = self };
}
};
pub var linenoise_wrapper = Linenoise.init();
pub var linenoise_reader = linenoise_wrapper.reader(); | src/linereader.zig |
const std = @import("std");
const builtin = @import("builtin");
const sdl = @import("sdl");
const c = @cImport({
@cInclude("vulkan/vulkan.h");
});
const use_rt_funcs = builtin.os.tag == .macos or builtin.os.tag == .windows;
pub usingnamespace c;
pub inline fn createInstance(pCreateInfo: [*c]const c.VkInstanceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pInstance: [*c]c.VkInstance) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateInstance(pCreateInfo, pAllocator, pInstance);
} else {
return c.vkCreateInstance(pCreateInfo, pAllocator, pInstance);
}
}
pub inline fn enumeratePhysicalDevices(instance: c.VkInstance, pPhysicalDeviceCount: [*c]u32, pPhysicalDevices: [*c]c.VkPhysicalDevice) c.VkResult {
if (use_rt_funcs) {
return rtVkEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices);
} else {
return c.vkEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices);
}
}
pub inline fn getPhysicalDeviceQueueFamilyProperties(physicalDevice: c.VkPhysicalDevice, pQueueFamilyPropertyCount: [*c]u32, pQueueFamilyProperties: [*c]c.VkQueueFamilyProperties) void {
if (use_rt_funcs) {
rtVkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties);
} else {
c.vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties);
}
}
pub inline fn getPhysicalDeviceSurfaceSupportKHR(physicalDevice: c.VkPhysicalDevice, queueFamilyIndex: u32, surface: c.VkSurfaceKHR, pSupported: [*c]c.VkBool32) c.VkResult {
if (use_rt_funcs) {
return rtVkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, pSupported);
} else {
return c.vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, pSupported);
}
}
pub inline fn enumerateDeviceExtensionProperties(physicalDevice: c.VkPhysicalDevice, pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]c.VkExtensionProperties) c.VkResult {
if (use_rt_funcs) {
return rtVkEnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pPropertyCount, pProperties);
} else {
return c.vkEnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pPropertyCount, pProperties);
}
}
pub inline fn getPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pSurfaceCapabilities: [*c]c.VkSurfaceCapabilitiesKHR) c.VkResult {
if (use_rt_funcs) {
return rtVkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, pSurfaceCapabilities);
} else {
return c.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, pSurfaceCapabilities);
}
}
pub inline fn getPhysicalDeviceSurfacePresentModesKHR(physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pPresentModeCount: [*c]u32, pPresentModes: [*c]c.VkPresentModeKHR) c.VkResult {
if (use_rt_funcs) {
return rtVkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, pPresentModeCount, pPresentModes);
} else {
return c.vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, pPresentModeCount, pPresentModes);
}
}
pub inline fn getPhysicalDeviceSurfaceFormatsKHR(physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pSurfaceFormatCount: [*c]u32, pSurfaceFormats: [*c]c.VkSurfaceFormatKHR) c.VkResult {
if (use_rt_funcs) {
return rtVkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, pSurfaceFormatCount, pSurfaceFormats);
} else {
return c.vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, pSurfaceFormatCount, pSurfaceFormats);
}
}
pub inline fn createDevice(physicalDevice: c.VkPhysicalDevice, pCreateInfo: [*c]const c.VkDeviceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pDevice: [*c]c.VkDevice) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
} else {
return c.vkCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
}
}
pub inline fn getDeviceQueue(device: c.VkDevice, queueFamilyIndex: u32, queueIndex: u32, pQueue: [*c]c.VkQueue) void {
if (use_rt_funcs) {
rtVkGetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue);
} else {
c.vkGetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue);
}
}
pub inline fn createSwapchainKHR(device: c.VkDevice, pCreateInfo: [*c]const c.VkSwapchainCreateInfoKHR, pAllocator: [*c]const c.VkAllocationCallbacks, pSwapchain: [*c]c.VkSwapchainKHR) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
} else {
return c.vkCreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
}
}
pub inline fn getSwapchainImagesKHR(device: c.VkDevice, swapchain: c.VkSwapchainKHR, pSwapchainImageCount: [*c]u32, pSwapchainImages: [*c]c.VkImage) c.VkResult {
if (use_rt_funcs) {
return rtVkGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, pSwapchainImages);
} else {
return c.vkGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, pSwapchainImages);
}
}
pub inline fn createImageView(device: c.VkDevice, pCreateInfo: [*c]const c.VkImageViewCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pView: [*c]c.VkImageView) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateImageView(device, pCreateInfo, pAllocator, pView);
} else {
return c.vkCreateImageView(device, pCreateInfo, pAllocator, pView);
}
}
pub inline fn createRenderPass(device: c.VkDevice, pCreateInfo: [*c]const c.VkRenderPassCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pRenderPass: [*c]c.VkRenderPass) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateRenderPass(device, pCreateInfo, pAllocator, pRenderPass);
} else {
return c.vkCreateRenderPass(device, pCreateInfo, pAllocator, pRenderPass);
}
}
pub inline fn createPipelineLayout(device: c.VkDevice, pCreateInfo: [*c]const c.VkPipelineLayoutCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pPipelineLayout: [*c]c.VkPipelineLayout) c.VkResult {
if (use_rt_funcs) {
return rtVkCreatePipelineLayout(device, pCreateInfo, pAllocator, pPipelineLayout);
} else {
return c.vkCreatePipelineLayout(device, pCreateInfo, pAllocator, pPipelineLayout);
}
}
pub inline fn createShaderModule(device: c.VkDevice, pCreateInfo: [*c]const c.VkShaderModuleCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pShaderModule: [*c]c.VkShaderModule) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateShaderModule(device, pCreateInfo, pAllocator, pShaderModule);
} else {
return c.vkCreateShaderModule(device, pCreateInfo, pAllocator, pShaderModule);
}
}
pub inline fn createGraphicsPipelines(device: c.VkDevice, pipelineCache: c.VkPipelineCache, createInfoCount: u32, pCreateInfos: [*c]const c.VkGraphicsPipelineCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pPipelines: [*c]c.VkPipeline) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
} else {
return c.vkCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
}
pub inline fn destroyShaderModule(device: c.VkDevice, shaderModule: c.VkShaderModule, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyShaderModule(device, shaderModule, pAllocator);
} else {
c.vkDestroyShaderModule(device, shaderModule, pAllocator);
}
}
pub inline fn createFramebuffer(device: c.VkDevice, pCreateInfo: [*c]const c.VkFramebufferCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pFramebuffer: [*c]c.VkFramebuffer) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateFramebuffer(device, pCreateInfo, pAllocator, pFramebuffer);
} else {
return c.vkCreateFramebuffer(device, pCreateInfo, pAllocator, pFramebuffer);
}
}
pub inline fn createCommandPool(device: c.VkDevice, pCreateInfo: [*c]const c.VkCommandPoolCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pCommandPool: [*c]c.VkCommandPool) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateCommandPool(device, pCreateInfo, pAllocator, pCommandPool);
} else {
return c.vkCreateCommandPool(device, pCreateInfo, pAllocator, pCommandPool);
}
}
pub inline fn allocateCommandBuffers(device: c.VkDevice, pAllocateInfo: [*c]const c.VkCommandBufferAllocateInfo, pCommandBuffers: [*c]c.VkCommandBuffer) c.VkResult {
if (use_rt_funcs) {
return rtVkAllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
} else {
return c.vkAllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
}
}
pub inline fn beginCommandBuffer(commandBuffer: c.VkCommandBuffer, pBeginInfo: [*c]const c.VkCommandBufferBeginInfo) c.VkResult {
if (use_rt_funcs) {
return rtVkBeginCommandBuffer(commandBuffer, pBeginInfo);
} else {
return c.vkBeginCommandBuffer(commandBuffer, pBeginInfo);
}
}
pub inline fn cmdBeginRenderPass(commandBuffer: c.VkCommandBuffer, pRenderPassBegin: [*c]const c.VkRenderPassBeginInfo, contents: c.VkSubpassContents) void {
if (use_rt_funcs) {
rtVkCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
} else {
c.vkCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
}
}
pub inline fn cmdBindPipeline(commandBuffer: c.VkCommandBuffer, pipelineBindPoint: c.VkPipelineBindPoint, pipeline: c.VkPipeline) void {
if (use_rt_funcs) {
rtVkCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
} else {
c.vkCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
}
}
pub inline fn cmdDraw(commandBuffer: c.VkCommandBuffer, vertexCount: u32, instanceCount: u32, firstVertex: u32, firstInstance: u32) void {
if (use_rt_funcs) {
rtVkCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
} else {
c.vkCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
}
}
pub inline fn cmdEndRenderPass(commandBuffer: c.VkCommandBuffer) void {
if (use_rt_funcs) {
rtVkCmdEndRenderPass(commandBuffer);
} else {
c.vkCmdEndRenderPass(commandBuffer);
}
}
pub inline fn endCommandBuffer(commandBuffer: c.VkCommandBuffer) c.VkResult {
if (use_rt_funcs) {
return rtVkEndCommandBuffer(commandBuffer);
} else {
return c.vkEndCommandBuffer(commandBuffer);
}
}
pub inline fn createSemaphore(device: c.VkDevice, pCreateInfo: [*c]const c.VkSemaphoreCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSemaphore: [*c]c.VkSemaphore) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateSemaphore(device, pCreateInfo, pAllocator, pSemaphore);
} else {
return c.vkCreateSemaphore(device, pCreateInfo, pAllocator, pSemaphore);
}
}
pub inline fn createFence(device: c.VkDevice, pCreateInfo: [*c]const c.VkFenceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pFence: [*c]c.VkFence) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateFence(device, pCreateInfo, pAllocator, pFence);
} else {
return c.vkCreateFence(device, pCreateInfo, pAllocator, pFence);
}
}
pub inline fn enumerateInstanceLayerProperties(pPropertyCount: [*c]u32, pProperties: [*c]c.VkLayerProperties) c.VkResult {
if (use_rt_funcs) {
return rtVkEnumerateInstanceLayerProperties(pPropertyCount, pProperties);
} else {
return c.vkEnumerateInstanceLayerProperties(pPropertyCount, pProperties);
}
}
pub inline fn mapMemory(device: c.VkDevice, memory: c.VkDeviceMemory, offset: c.VkDeviceSize, size: c.VkDeviceSize, flags: c.VkMemoryMapFlags, ppData: [*c]?*anyopaque) c.VkResult {
if (use_rt_funcs) {
return rtVkMapMemory(device, memory, offset, size, flags, ppData);
} else {
return c.vkMapMemory(device, memory, offset, size, flags, ppData);
}
}
pub inline fn unmapMemory(device: c.VkDevice, memory: c.VkDeviceMemory) void {
if (use_rt_funcs) {
rtVkUnmapMemory(device, memory);
} else {
c.vkUnmapMemory(device, memory);
}
}
pub inline fn createBuffer(device: c.VkDevice, pCreateInfo: [*c]const c.VkBufferCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pBuffer: [*c]c.VkBuffer) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
} else {
return c.vkCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
}
}
pub inline fn getBufferMemoryRequirements(device: c.VkDevice, buffer: c.VkBuffer, pMemoryRequirements: [*c]c.VkMemoryRequirements) void {
if (use_rt_funcs) {
rtVkGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
} else {
c.vkGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
}
}
pub inline fn allocateMemory(device: c.VkDevice, pAllocateInfo: [*c]const c.VkMemoryAllocateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pMemory: [*c]c.VkDeviceMemory) c.VkResult {
if (use_rt_funcs) {
return rtVkAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
} else {
return c.vkAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
}
}
pub inline fn bindBufferMemory(device: c.VkDevice, buffer: c.VkBuffer, memory: c.VkDeviceMemory, memoryOffset: c.VkDeviceSize) c.VkResult {
if (use_rt_funcs) {
return rtVkBindBufferMemory(device, buffer, memory, memoryOffset);
} else {
return c.vkBindBufferMemory(device, buffer, memory, memoryOffset);
}
}
pub inline fn createImage(device: c.VkDevice, pCreateInfo: [*c]const c.VkImageCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pImage: [*c]c.VkImage) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateImage(device, pCreateInfo, pAllocator, pImage);
} else {
return c.vkCreateImage(device, pCreateInfo, pAllocator, pImage);
}
}
pub inline fn getImageMemoryRequirements(device: c.VkDevice, image: c.VkImage, pMemoryRequirements: [*c]c.VkMemoryRequirements) void {
if (use_rt_funcs) {
rtVkGetImageMemoryRequirements(device, image, pMemoryRequirements);
} else {
c.vkGetImageMemoryRequirements(device, image, pMemoryRequirements);
}
}
pub inline fn bindImageMemory(device: c.VkDevice, image: c.VkImage, memory: c.VkDeviceMemory, memoryOffset: c.VkDeviceSize) c.VkResult {
if (use_rt_funcs) {
return rtVkBindImageMemory(device, image, memory, memoryOffset);
} else {
return c.vkBindImageMemory(device, image, memory, memoryOffset);
}
}
pub inline fn cmdPipelineBarrier(commandBuffer: c.VkCommandBuffer, srcStageMask: c.VkPipelineStageFlags, dstStageMask: c.VkPipelineStageFlags,
dependencyFlags: c.VkDependencyFlags, memoryBarrierCount: u32, pMemoryBarriers: [*c]const c.VkMemoryBarrier, bufferMemoryBarrierCount: u32,
pBufferMemoryBarriers: [*c]const c.VkBufferMemoryBarrier, imageMemoryBarrierCount: u32, pImageMemoryBarriers: [*c]const c.VkImageMemoryBarrier
) void {
if (use_rt_funcs) {
rtVkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
} else {
c.vkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
}
}
pub inline fn cmdCopyBufferToImage(commandBuffer: c.VkCommandBuffer, srcBuffer: c.VkBuffer, dstImage: c.VkImage, dstImageLayout: c.VkImageLayout, regionCount: u32, pRegions: [*c]const c.VkBufferImageCopy) void {
if (use_rt_funcs) {
rtVkCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
} else {
c.vkCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
}
}
pub inline fn getPhysicalDeviceMemoryProperties(physicalDevice: c.VkPhysicalDevice, pMemoryProperties: [*c]c.VkPhysicalDeviceMemoryProperties) void {
if (use_rt_funcs) {
rtVkGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
} else {
c.vkGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
}
}
pub inline fn queueSubmit(queue: c.VkQueue, submitCount: u32, pSubmits: [*c]const c.VkSubmitInfo, fence: c.VkFence) c.VkResult {
if (use_rt_funcs) {
return rtVkQueueSubmit(queue, submitCount, pSubmits, fence);
} else {
return c.vkQueueSubmit(queue, submitCount, pSubmits, fence);
}
}
pub inline fn queueWaitIdle(queue: c.VkQueue) c.VkResult {
if (use_rt_funcs) {
return rtVkQueueWaitIdle(queue);
} else {
return c.vkQueueWaitIdle(queue);
}
}
pub inline fn freeCommandBuffers(device: c.VkDevice, commandPool: c.VkCommandPool, commandBufferCount: u32, pCommandBuffers: [*c]const c.VkCommandBuffer) void {
if (use_rt_funcs) {
return rtVkFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
} else {
return c.vkFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
}
}
pub inline fn enumerateInstanceExtensionProperties(pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]c.VkExtensionProperties) c.VkResult {
if (use_rt_funcs) {
return rtVkEnumerateInstanceExtensionProperties(pLayerName, pPropertyCount, pProperties);
} else {
return c.vkEnumerateInstanceExtensionProperties(pLayerName, pPropertyCount, pProperties);
}
}
pub inline fn destroyBuffer(device: c.VkDevice, buffer: c.VkBuffer, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyBuffer(device, buffer, pAllocator);
} else {
c.vkDestroyBuffer(device, buffer, pAllocator);
}
}
pub inline fn freeMemory(device: c.VkDevice, memory: c.VkDeviceMemory, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkFreeMemory(device, memory, pAllocator);
} else {
c.vkFreeMemory(device, memory, pAllocator);
}
}
pub inline fn destroyImage(device: c.VkDevice, image: c.VkImage, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyImage(device, image, pAllocator);
} else {
c.vkDestroyImage(device, image, pAllocator);
}
}
pub inline fn destroyImageView(device: c.VkDevice, imageView: c.VkImageView, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyImageView(device, imageView, pAllocator);
} else {
c.vkDestroyImageView(device, imageView, pAllocator);
}
}
pub inline fn createDescriptorSetLayout(device: c.VkDevice, pCreateInfo: [*c]const c.VkDescriptorSetLayoutCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSetLayout: [*c]c.VkDescriptorSetLayout) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateDescriptorSetLayout(device, pCreateInfo, pAllocator, pSetLayout);
} else {
return c.vkCreateDescriptorSetLayout(device, pCreateInfo, pAllocator, pSetLayout);
}
}
pub inline fn createSampler(device: c.VkDevice, pCreateInfo: [*c]const c.VkSamplerCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSampler: [*c]c.VkSampler) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateSampler(device, pCreateInfo, pAllocator, pSampler);
} else {
return c.vkCreateSampler(device, pCreateInfo, pAllocator, pSampler);
}
}
pub inline fn waitForFences(device: c.VkDevice, fenceCount: u32, pFences: [*c]const c.VkFence, waitAll: c.VkBool32, timeout: u64) c.VkResult {
if (use_rt_funcs) {
return rtVkWaitForFences(device, fenceCount, pFences, waitAll, timeout);
} else {
return c.vkWaitForFences(device, fenceCount, pFences, waitAll, timeout);
}
}
pub inline fn resetFences(device: c.VkDevice, fenceCount: u32, pFences: [*c]const c.VkFence) c.VkResult {
if (use_rt_funcs) {
return rtVkResetFences(device, fenceCount, pFences);
} else {
return c.vkResetFences(device, fenceCount, pFences);
}
}
pub inline fn acquireNextImageKHR(device: c.VkDevice, swapchain: c.VkSwapchainKHR, timeout: u64, semaphore: c.VkSemaphore, fence: c.VkFence, pImageIndex: [*c]u32) c.VkResult {
if (use_rt_funcs) {
return rtVkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, pImageIndex);
} else {
return c.vkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, pImageIndex);
}
}
pub inline fn queuePresentKHR(queue: c.VkQueue, pPresentInfo: [*c]const c.VkPresentInfoKHR) c.VkResult {
if (use_rt_funcs) {
return rtVkQueuePresentKHR(queue, pPresentInfo);
} else {
return c.vkQueuePresentKHR(queue, pPresentInfo);
}
}
pub inline fn cmdBindVertexBuffers(commandBuffer: c.VkCommandBuffer, firstBinding: u32, bindingCount: u32, pBuffers: [*c]const c.VkBuffer, pOffsets: [*c]const c.VkDeviceSize) void {
if (use_rt_funcs) {
rtVkCmdBindVertexBuffers(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets);
} else {
c.vkCmdBindVertexBuffers(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets);
}
}
pub inline fn cmdBindIndexBuffer(commandBuffer: c.VkCommandBuffer, buffer: c.VkBuffer, offset: c.VkDeviceSize, indexType: c.VkIndexType) void {
if (use_rt_funcs) {
rtVkCmdBindIndexBuffer(commandBuffer, buffer, offset, indexType);
} else {
c.vkCmdBindIndexBuffer(commandBuffer, buffer, offset, indexType);
}
}
pub inline fn cmdDrawIndexed(commandBuffer: c.VkCommandBuffer, indexCount: u32, instanceCount: u32, firstIndex: u32, vertexOffset: i32, firstInstance: u32) void {
if (use_rt_funcs) {
rtVkCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
} else {
c.vkCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
}
}
pub inline fn cmdPushConstants(commandBuffer: c.VkCommandBuffer, layout: c.VkPipelineLayout, stageFlags: c.VkShaderStageFlags, offset: u32, size: u32, pValues: ?*const anyopaque) void {
if (use_rt_funcs) {
rtVkCmdPushConstants(commandBuffer, layout, stageFlags, offset, size, pValues);
} else {
c.vkCmdPushConstants(commandBuffer, layout, stageFlags, offset, size, pValues);
}
}
pub inline fn cmdBindDescriptorSets(commandBuffer: c.VkCommandBuffer, pipelineBindPoint: c.VkPipelineBindPoint, layout: c.VkPipelineLayout, firstSet: u32, descriptorSetCount: u32, pDescriptorSets: [*c]const c.VkDescriptorSet, dynamicOffsetCount: u32, pDynamicOffsets: [*c]const u32) void {
if (use_rt_funcs) {
rtVkCmdBindDescriptorSets(commandBuffer, pipelineBindPoint, layout, firstSet, descriptorSetCount, pDescriptorSets, dynamicOffsetCount, pDynamicOffsets);
} else {
c.vkCmdBindDescriptorSets(commandBuffer, pipelineBindPoint, layout, firstSet, descriptorSetCount, pDescriptorSets, dynamicOffsetCount, pDynamicOffsets);
}
}
pub inline fn createDescriptorPool(device: c.VkDevice, pCreateInfo: [*c]const c.VkDescriptorPoolCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pDescriptorPool: [*c]c.VkDescriptorPool) c.VkResult {
if (use_rt_funcs) {
return rtVkCreateDescriptorPool(device, pCreateInfo, pAllocator, pDescriptorPool);
} else {
return c.vkCreateDescriptorPool(device, pCreateInfo, pAllocator, pDescriptorPool);
}
}
pub inline fn allocateDescriptorSets(device: c.VkDevice, pAllocateInfo: [*c]const c.VkDescriptorSetAllocateInfo, pDescriptorSets: [*c]c.VkDescriptorSet) c.VkResult {
if (use_rt_funcs) {
return rtVkAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets);
} else {
return c.vkAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets);
}
}
pub inline fn updateDescriptorSets(device: c.VkDevice, descriptorWriteCount: u32, pDescriptorWrites: [*c]const c.VkWriteDescriptorSet, descriptorCopyCount: u32, pDescriptorCopies: [*c]const c.VkCopyDescriptorSet) void {
if (use_rt_funcs) {
return rtVkUpdateDescriptorSets(device, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies);
} else {
return c.vkUpdateDescriptorSets(device, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies);
}
}
pub inline fn getPhysicalDeviceFeatures(physicalDevice: c.VkPhysicalDevice, pFeatures: [*c]c.VkPhysicalDeviceFeatures) void {
if (use_rt_funcs) {
rtVkGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
} else {
c.vkGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
}
}
pub inline fn destroyInstance(instance: c.VkInstance, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyInstance(instance, pAllocator);
} else {
c.vkDestroyInstance(instance, pAllocator);
}
}
pub inline fn destroyDevice(device: c.VkDevice, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyDevice(device, pAllocator);
} else {
c.vkDestroyDevice(device, pAllocator);
}
}
pub inline fn destroySurfaceKHR(instance: c.VkInstance, surface: c.VkSurfaceKHR, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroySurfaceKHR(instance, surface, pAllocator);
} else {
c.vkDestroySurfaceKHR(instance, surface, pAllocator);
}
}
pub inline fn destroySemaphore(device: c.VkDevice, semaphore: c.VkSemaphore, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroySemaphore(device, semaphore, pAllocator);
} else {
c.vkDestroySemaphore(device, semaphore, pAllocator);
}
}
pub inline fn destroyFence(device: c.VkDevice, fence: c.VkFence, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyFence(device, fence, pAllocator);
} else {
c.vkDestroyFence(device, fence, pAllocator);
}
}
pub inline fn destroyPipeline(device: c.VkDevice, pipeline: c.VkPipeline, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyPipeline(device, pipeline, pAllocator);
} else {
c.vkDestroyPipeline(device, pipeline, pAllocator);
}
}
pub inline fn destroyPipelineLayout(device: c.VkDevice, pipelineLayout: c.VkPipelineLayout, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyPipelineLayout(device, pipelineLayout, pAllocator);
} else {
c.vkDestroyPipelineLayout(device, pipelineLayout, pAllocator);
}
}
pub inline fn destroySwapchainKHR(device: c.VkDevice, swapchain: c.VkSwapchainKHR, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroySwapchainKHR(device, swapchain, pAllocator);
} else {
c.vkDestroySwapchainKHR(device, swapchain, pAllocator);
}
}
pub inline fn destroyFramebuffer(device: c.VkDevice, framebuffer: c.VkFramebuffer, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyFramebuffer(device, framebuffer, pAllocator);
} else {
c.vkDestroyFramebuffer(device, framebuffer, pAllocator);
}
}
pub inline fn destroyDescriptorSetLayout(device: c.VkDevice, descriptorSetLayout: c.VkDescriptorSetLayout, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyDescriptorSetLayout(device, descriptorSetLayout, pAllocator);
} else {
c.vkDestroyDescriptorSetLayout(device, descriptorSetLayout, pAllocator);
}
}
pub inline fn destroyDescriptorPool(device: c.VkDevice, descriptorPool: c.VkDescriptorPool, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyDescriptorPool(device, descriptorPool, pAllocator);
} else {
c.vkDestroyDescriptorPool(device, descriptorPool, pAllocator);
}
}
pub inline fn destroySampler(device: c.VkDevice, sampler: c.VkSampler, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroySampler(device, sampler, pAllocator);
} else {
c.vkDestroySampler(device, sampler, pAllocator);
}
}
pub inline fn destroyRenderPass(device: c.VkDevice, renderPass: c.VkRenderPass, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyRenderPass(device, renderPass, pAllocator);
} else {
c.vkDestroyRenderPass(device, renderPass, pAllocator);
}
}
pub inline fn destroyCommandPool(device: c.VkDevice, commandPool: c.VkCommandPool, pAllocator: [*c]const c.VkAllocationCallbacks) void {
if (use_rt_funcs) {
rtVkDestroyCommandPool(device, commandPool, pAllocator);
} else {
c.vkDestroyCommandPool(device, commandPool, pAllocator);
}
}
pub inline fn cmdSetScissor(commandBuffer: c.VkCommandBuffer, firstScissor: u32, scissorCount: u32, pScissors: [*c]const c.VkRect2D) void {
if (use_rt_funcs) {
rtVkCmdSetScissor(commandBuffer, firstScissor, scissorCount, pScissors);
} else {
c.vkCmdSetScissor(commandBuffer, firstScissor, scissorCount, pScissors);
}
}
var rtVkGetInstanceProcAddr: fn (instance: c.VkInstance, pName: [*c]const u8) c.PFN_vkVoidFunction = undefined;
var rtVkCreateInstance: fn (pCreateInfo: [*c]const c.VkInstanceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pInstance: [*c]c.VkInstance) c.VkResult = undefined;
var rtVkEnumeratePhysicalDevices: fn (instance: c.VkInstance, pPhysicalDeviceCount: [*c]u32, pPhysicalDevices: [*c]c.VkPhysicalDevice) c.VkResult = undefined;
var rtVkGetPhysicalDeviceQueueFamilyProperties: fn (physicalDevice: c.VkPhysicalDevice, pQueueFamilyPropertyCount: [*c]u32, pQueueFamilyProperties: [*c]c.VkQueueFamilyProperties) void = undefined;
var rtVkGetPhysicalDeviceSurfaceSupportKHR: fn (physicalDevice: c.VkPhysicalDevice, queueFamilyIndex: u32, surface: c.VkSurfaceKHR, pSupported: [*c]c.VkBool32) c.VkResult = undefined;
var rtVkEnumerateDeviceExtensionProperties: fn (physicalDevice: c.VkPhysicalDevice, pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]c.VkExtensionProperties) c.VkResult = undefined;
var rtVkGetPhysicalDeviceSurfaceCapabilitiesKHR: fn (physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pSurfaceCapabilities: [*c]c.VkSurfaceCapabilitiesKHR) c.VkResult = undefined;
var rtVkGetPhysicalDeviceSurfacePresentModesKHR: fn (physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pPresentModeCount: [*c]u32, pPresentModes: [*c]c.VkPresentModeKHR) c.VkResult = undefined;
var rtVkGetPhysicalDeviceSurfaceFormatsKHR: fn (physicalDevice: c.VkPhysicalDevice, surface: c.VkSurfaceKHR, pSurfaceFormatCount: [*c]u32, pSurfaceFormats: [*c]c.VkSurfaceFormatKHR) c.VkResult = undefined;
var rtVkCreateDevice: fn (physicalDevice: c.VkPhysicalDevice, pCreateInfo: [*c]const c.VkDeviceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pDevice: [*c]c.VkDevice) c.VkResult = undefined;
var rtVkGetDeviceQueue: fn (device: c.VkDevice, queueFamilyIndex: u32, queueIndex: u32, pQueue: [*c]c.VkQueue) void = undefined;
var rtVkCreateSwapchainKHR: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkSwapchainCreateInfoKHR, pAllocator: [*c]const c.VkAllocationCallbacks, pSwapchain: [*c]c.VkSwapchainKHR) c.VkResult = undefined;
var rtVkGetSwapchainImagesKHR: fn (device: c.VkDevice, swapchain: c.VkSwapchainKHR, pSwapchainImageCount: [*c]u32, pSwapchainImages: [*c]c.VkImage) c.VkResult = undefined;
var rtVkCreateImageView: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkImageViewCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pView: [*c]c.VkImageView) c.VkResult = undefined;
var rtVkCreateRenderPass: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkRenderPassCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pRenderPass: [*c]c.VkRenderPass) c.VkResult = undefined;
var rtVkCreatePipelineLayout: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkPipelineLayoutCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pPipelineLayout: [*c]c.VkPipelineLayout) c.VkResult = undefined;
var rtVkCreateShaderModule: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkShaderModuleCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pShaderModule: [*c]c.VkShaderModule) c.VkResult = undefined;
var rtVkCreateGraphicsPipelines: fn (device: c.VkDevice, pipelineCache: c.VkPipelineCache, createInfoCount: u32, pCreateInfos: [*c]const c.VkGraphicsPipelineCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pPipelines: [*c]c.VkPipeline) c.VkResult = undefined;
var rtVkDestroyShaderModule: fn (device: c.VkDevice, shaderModule: c.VkShaderModule, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkCreateFramebuffer: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkFramebufferCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pFramebuffer: [*c]c.VkFramebuffer) c.VkResult = undefined;
var rtVkCreateCommandPool: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkCommandPoolCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pCommandPool: [*c]c.VkCommandPool) c.VkResult = undefined;
var rtVkAllocateCommandBuffers: fn (device: c.VkDevice, pAllocateInfo: [*c]const c.VkCommandBufferAllocateInfo, pCommandBuffers: [*c]c.VkCommandBuffer) c.VkResult = undefined;
var rtVkBeginCommandBuffer: fn (commandBuffer: c.VkCommandBuffer, pBeginInfo: [*c]const c.VkCommandBufferBeginInfo) c.VkResult = undefined;
var rtVkCmdBeginRenderPass: fn (commandBuffer: c.VkCommandBuffer, pRenderPassBegin: [*c]const c.VkRenderPassBeginInfo, contents: c.VkSubpassContents) void = undefined;
var rtVkCmdBindPipeline: fn (commandBuffer: c.VkCommandBuffer, pipelineBindPoint: c.VkPipelineBindPoint, pipeline: c.VkPipeline) void = undefined;
var rtVkCmdDraw: fn (commandBuffer: c.VkCommandBuffer, vertexCount: u32, instanceCount: u32, firstVertex: u32, firstInstance: u32) void = undefined;
var rtVkCmdEndRenderPass: fn (commandBuffer: c.VkCommandBuffer) void = undefined;
var rtVkEndCommandBuffer: fn (commandBuffer: c.VkCommandBuffer) c.VkResult = undefined;
var rtVkCreateSemaphore: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkSemaphoreCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSemaphore: [*c]c.VkSemaphore) c.VkResult = undefined;
var rtVkCreateFence: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkFenceCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pFence: [*c]c.VkFence) c.VkResult = undefined;
var rtVkEnumerateInstanceLayerProperties: fn (pPropertyCount: [*c]u32, pProperties: [*c]c.VkLayerProperties) c.VkResult = undefined;
var rtVkMapMemory: fn (device: c.VkDevice, memory: c.VkDeviceMemory, offset: c.VkDeviceSize, size: c.VkDeviceSize, flags: c.VkMemoryMapFlags, ppData: [*c]?*anyopaque) c.VkResult = undefined;
var rtVkUnmapMemory: fn (device: c.VkDevice, memory: c.VkDeviceMemory) void = undefined;
var rtVkCreateBuffer: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkBufferCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pBuffer: [*c]c.VkBuffer) c.VkResult = undefined;
var rtVkGetBufferMemoryRequirements: fn (device: c.VkDevice, buffer: c.VkBuffer, pMemoryRequirements: [*c]c.VkMemoryRequirements) void = undefined;
var rtVkAllocateMemory: fn (device: c.VkDevice, pAllocateInfo: [*c]const c.VkMemoryAllocateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pMemory: [*c]c.VkDeviceMemory) c.VkResult = undefined;
var rtVkBindBufferMemory: fn (device: c.VkDevice, buffer: c.VkBuffer, memory: c.VkDeviceMemory, memoryOffset: c.VkDeviceSize) c.VkResult = undefined;
var rtVkCreateImage: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkImageCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pImage: [*c]c.VkImage) c.VkResult = undefined;
var rtVkGetImageMemoryRequirements: fn (device: c.VkDevice, image: c.VkImage, pMemoryRequirements: [*c]c.VkMemoryRequirements) void = undefined;
var rtVkBindImageMemory: fn (device: c.VkDevice, image: c.VkImage, memory: c.VkDeviceMemory, memoryOffset: c.VkDeviceSize) c.VkResult = undefined;
var rtVkCmdPipelineBarrier: fn (commandBuffer: c.VkCommandBuffer, srcStageMask: c.VkPipelineStageFlags, dstStageMask: c.VkPipelineStageFlags, dependencyFlags: c.VkDependencyFlags, memoryBarrierCount: u32, pMemoryBarriers: [*c]const c.VkMemoryBarrier, bufferMemoryBarrierCount: u32, pBufferMemoryBarriers: [*c]const c.VkBufferMemoryBarrier, imageMemoryBarrierCount: u32, pImageMemoryBarriers: [*c]const c.VkImageMemoryBarrier) void = undefined;
var rtVkCmdCopyBufferToImage: fn (commandBuffer: c.VkCommandBuffer, srcBuffer: c.VkBuffer, dstImage: c.VkImage, dstImageLayout: c.VkImageLayout, regionCount: u32, pRegions: [*c]const c.VkBufferImageCopy) void = undefined;
var rtVkGetPhysicalDeviceMemoryProperties: fn (physicalDevice: c.VkPhysicalDevice, pMemoryProperties: [*c]c.VkPhysicalDeviceMemoryProperties) void = undefined;
var rtVkQueueSubmit: fn (queue: c.VkQueue, submitCount: u32, pSubmits: [*c]const c.VkSubmitInfo, fence: c.VkFence) c.VkResult = undefined;
var rtVkQueueWaitIdle: fn (queue: c.VkQueue) c.VkResult = undefined;
var rtVkFreeCommandBuffers: fn (device: c.VkDevice, commandPool: c.VkCommandPool, commandBufferCount: u32, pCommandBuffers: [*c]const c.VkCommandBuffer) void = undefined;
var rtVkEnumerateInstanceExtensionProperties: fn (pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]c.VkExtensionProperties) c.VkResult = undefined;
var rtVkDestroyBuffer: fn (device: c.VkDevice, buffer: c.VkBuffer, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkFreeMemory: fn (device: c.VkDevice, memory: c.VkDeviceMemory, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyImage: fn (device: c.VkDevice, image: c.VkImage, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyImageView: fn (device: c.VkDevice, imageView: c.VkImageView, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkCreateDescriptorSetLayout: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkDescriptorSetLayoutCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSetLayout: [*c]c.VkDescriptorSetLayout) c.VkResult = undefined;
var rtVkCreateSampler: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkSamplerCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pSampler: [*c]c.VkSampler) c.VkResult = undefined;
var rtVkWaitForFences: fn (device: c.VkDevice, fenceCount: u32, pFences: [*c]const c.VkFence, waitAll: c.VkBool32, timeout: u64) c.VkResult = undefined;
var rtVkResetFences: fn (device: c.VkDevice, fenceCount: u32, pFences: [*c]const c.VkFence) c.VkResult = undefined;
var rtVkAcquireNextImageKHR: fn (device: c.VkDevice, swapchain: c.VkSwapchainKHR, timeout: u64, semaphore: c.VkSemaphore, fence: c.VkFence, pImageIndex: [*c]u32) c.VkResult = undefined;
var rtVkQueuePresentKHR: fn (queue: c.VkQueue, pPresentInfo: [*c]const c.VkPresentInfoKHR) c.VkResult = undefined;
var rtVkCmdBindVertexBuffers: fn (commandBuffer: c.VkCommandBuffer, firstBinding: u32, bindingCount: u32, pBuffers: [*c]const c.VkBuffer, pOffsets: [*c]const c.VkDeviceSize) void = undefined;
var rtVkCmdBindIndexBuffer: fn (commandBuffer: c.VkCommandBuffer, buffer: c.VkBuffer, offset: c.VkDeviceSize, indexType: c.VkIndexType) void = undefined;
var rtVkCmdDrawIndexed: fn (commandBuffer: c.VkCommandBuffer, indexCount: u32, instanceCount: u32, firstIndex: u32, vertexOffset: i32, firstInstance: u32) void = undefined;
var rtVkCmdPushConstants: fn (commandBuffer: c.VkCommandBuffer, layout: c.VkPipelineLayout, stageFlags: c.VkShaderStageFlags, offset: u32, size: u32, pValues: ?*const anyopaque) void = undefined;
var rtVkCmdBindDescriptorSets: fn (commandBuffer: c.VkCommandBuffer, pipelineBindPoint: c.VkPipelineBindPoint, layout: c.VkPipelineLayout, firstSet: u32, descriptorSetCount: u32, pDescriptorSets: [*c]const c.VkDescriptorSet, dynamicOffsetCount: u32, pDynamicOffsets: [*c]const u32) void = undefined;
var rtVkCreateDescriptorPool: fn (device: c.VkDevice, pCreateInfo: [*c]const c.VkDescriptorPoolCreateInfo, pAllocator: [*c]const c.VkAllocationCallbacks, pDescriptorPool: [*c]c.VkDescriptorPool) c.VkResult = undefined;
var rtVkAllocateDescriptorSets: fn (device: c.VkDevice, pAllocateInfo: [*c]const c.VkDescriptorSetAllocateInfo, pDescriptorSets: [*c]c.VkDescriptorSet) c.VkResult = undefined;
var rtVkUpdateDescriptorSets: fn (device: c.VkDevice, descriptorWriteCount: u32, pDescriptorWrites: [*c]const c.VkWriteDescriptorSet, descriptorCopyCount: u32, pDescriptorCopies: [*c]const c.VkCopyDescriptorSet) void = undefined;
var rtVkGetPhysicalDeviceFeatures: fn (physicalDevice: c.VkPhysicalDevice, pFeatures: [*c]c.VkPhysicalDeviceFeatures) void = undefined;
var rtVkDestroyInstance: fn (instance: c.VkInstance, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyDevice: fn (device: c.VkDevice, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroySurfaceKHR: fn (instance: c.VkInstance, surface: c.VkSurfaceKHR, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroySemaphore: fn (device: c.VkDevice, semaphore: c.VkSemaphore, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyFence: fn (device: c.VkDevice, fence: c.VkFence, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyPipeline: fn (device: c.VkDevice, pipeline: c.VkPipeline, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyPipelineLayout: fn (device: c.VkDevice, pipelineLayout: c.VkPipelineLayout, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroySwapchainKHR: fn (device: c.VkDevice, swapchain: c.VkSwapchainKHR, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyFramebuffer: fn (device: c.VkDevice, framebuffer: c.VkFramebuffer, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyDescriptorSetLayout: fn (device: c.VkDevice, descriptorSetLayout: c.VkDescriptorSetLayout, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyDescriptorPool: fn (device: c.VkDevice, descriptorPool: c.VkDescriptorPool, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroySampler: fn (device: c.VkDevice, sampler: c.VkSampler, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyRenderPass: fn (device: c.VkDevice, renderPass: c.VkRenderPass, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkDestroyCommandPool: fn (device: c.VkDevice, commandPool: c.VkCommandPool, pAllocator: [*c]const c.VkAllocationCallbacks) void = undefined;
var rtVkCmdSetScissor: fn (commandBuffer: c.VkCommandBuffer, firstScissor: u32, scissorCount: u32, pScissors: [*c]const c.VkRect2D) void = undefined;
/// Vulkan is translated to Metal on macOS through MoltenVK. After SDL_Vulkan_LoadLibrary or creating a sdl window with SDL_WINDOW_VULKAN,
/// this should be invoked to bind the vk functions at runtime.
pub fn initMacVkInstanceFuncs() void {
rtVkGetInstanceProcAddr = @ptrCast(@TypeOf(rtVkGetInstanceProcAddr), sdl.SDL_Vulkan_GetVkGetInstanceProcAddr());
loadVkFunc(&rtVkCreateInstance, null, "vkCreateInstance");
loadVkFunc(&rtVkEnumerateInstanceLayerProperties, null, "vkEnumerateInstanceLayerProperties");
loadVkFunc(&rtVkEnumerateInstanceExtensionProperties, null, "vkEnumerateInstanceExtensionProperties");
}
pub fn initMacVkFunctions(instance: c.VkInstance) void {
loadVkFunc(&rtVkEnumeratePhysicalDevices, instance, "vkEnumeratePhysicalDevices");
loadVkFunc(&rtVkGetPhysicalDeviceQueueFamilyProperties, instance, "vkGetPhysicalDeviceQueueFamilyProperties");
loadVkFunc(&rtVkGetPhysicalDeviceSurfaceSupportKHR, instance, "vkGetPhysicalDeviceSurfaceSupportKHR");
loadVkFunc(&rtVkEnumerateDeviceExtensionProperties, instance, "vkEnumerateDeviceExtensionProperties");
loadVkFunc(&rtVkGetPhysicalDeviceSurfaceCapabilitiesKHR, instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
loadVkFunc(&rtVkGetPhysicalDeviceSurfacePresentModesKHR, instance, "vkGetPhysicalDeviceSurfacePresentModesKHR");
loadVkFunc(&rtVkGetPhysicalDeviceSurfaceFormatsKHR, instance, "vkGetPhysicalDeviceSurfaceFormatsKHR");
loadVkFunc(&rtVkCreateDevice, instance, "vkCreateDevice");
loadVkFunc(&rtVkGetDeviceQueue, instance, "vkGetDeviceQueue");
loadVkFunc(&rtVkCreateSwapchainKHR, instance, "vkCreateSwapchainKHR");
loadVkFunc(&rtVkGetSwapchainImagesKHR, instance, "vkGetSwapchainImagesKHR");
loadVkFunc(&rtVkCreateImageView, instance, "vkCreateImageView");
loadVkFunc(&rtVkCreateRenderPass, instance, "vkCreateRenderPass");
loadVkFunc(&rtVkCreatePipelineLayout, instance, "vkCreatePipelineLayout");
loadVkFunc(&rtVkCreateShaderModule, instance, "vkCreateShaderModule");
loadVkFunc(&rtVkCreateGraphicsPipelines, instance, "vkCreateGraphicsPipelines");
loadVkFunc(&rtVkDestroyShaderModule, instance, "vkDestroyShaderModule");
loadVkFunc(&rtVkCreateFramebuffer, instance, "vkCreateFramebuffer");
loadVkFunc(&rtVkCreateCommandPool, instance, "vkCreateCommandPool");
loadVkFunc(&rtVkAllocateCommandBuffers, instance, "vkAllocateCommandBuffers");
loadVkFunc(&rtVkBeginCommandBuffer, instance, "vkBeginCommandBuffer");
loadVkFunc(&rtVkCmdBeginRenderPass, instance, "vkCmdBeginRenderPass");
loadVkFunc(&rtVkCmdBindPipeline, instance, "vkCmdBindPipeline");
loadVkFunc(&rtVkCmdDraw, instance, "vkCmdDraw");
loadVkFunc(&rtVkCmdEndRenderPass, instance, "vkCmdEndRenderPass");
loadVkFunc(&rtVkEndCommandBuffer, instance, "vkEndCommandBuffer");
loadVkFunc(&rtVkCreateSemaphore, instance, "vkCreateSemaphore");
loadVkFunc(&rtVkCreateFence, instance, "vkCreateFence");
loadVkFunc(&rtVkEnumerateDeviceExtensionProperties, instance, "vkEnumerateDeviceExtensionProperties");
loadVkFunc(&rtVkMapMemory, instance, "vkMapMemory");
loadVkFunc(&rtVkUnmapMemory, instance, "vkUnmapMemory");
loadVkFunc(&rtVkCreateBuffer, instance, "vkCreateBuffer");
loadVkFunc(&rtVkGetBufferMemoryRequirements, instance, "vkGetBufferMemoryRequirements");
loadVkFunc(&rtVkAllocateMemory, instance, "vkAllocateMemory");
loadVkFunc(&rtVkBindBufferMemory, instance, "vkBindBufferMemory");
loadVkFunc(&rtVkCreateImage, instance, "vkCreateImage");
loadVkFunc(&rtVkGetImageMemoryRequirements, instance, "vkGetImageMemoryRequirements");
loadVkFunc(&rtVkBindImageMemory, instance, "vkBindImageMemory");
loadVkFunc(&rtVkCmdPipelineBarrier, instance, "vkCmdPipelineBarrier");
loadVkFunc(&rtVkCmdCopyBufferToImage, instance, "vkCmdCopyBufferToImage");
loadVkFunc(&rtVkGetPhysicalDeviceMemoryProperties, instance, "vkGetPhysicalDeviceMemoryProperties");
loadVkFunc(&rtVkQueueSubmit, instance, "vkQueueSubmit");
loadVkFunc(&rtVkQueueWaitIdle, instance, "vkQueueWaitIdle");
loadVkFunc(&rtVkFreeCommandBuffers, instance, "vkFreeCommandBuffers");
loadVkFunc(&rtVkDestroyBuffer, instance, "vkDestroyBuffer");
loadVkFunc(&rtVkFreeMemory, instance, "vkFreeMemory");
loadVkFunc(&rtVkDestroyImage, instance, "vkDestroyImage");
loadVkFunc(&rtVkDestroyImageView, instance, "vkDestroyImageView");
loadVkFunc(&rtVkCreateDescriptorSetLayout, instance, "vkCreateDescriptorSetLayout");
loadVkFunc(&rtVkCreateSampler, instance, "vkCreateSampler");
loadVkFunc(&rtVkWaitForFences, instance, "vkWaitForFences");
loadVkFunc(&rtVkResetFences, instance, "vkResetFences");
loadVkFunc(&rtVkAcquireNextImageKHR, instance, "vkAcquireNextImageKHR");
loadVkFunc(&rtVkQueuePresentKHR, instance, "vkQueuePresentKHR");
loadVkFunc(&rtVkCmdBindVertexBuffers, instance, "vkCmdBindVertexBuffers");
loadVkFunc(&rtVkCmdBindIndexBuffer, instance, "vkCmdBindIndexBuffer");
loadVkFunc(&rtVkCmdDrawIndexed, instance, "vkCmdDrawIndexed");
loadVkFunc(&rtVkCmdPushConstants, instance, "vkCmdPushConstants");
loadVkFunc(&rtVkCmdBindDescriptorSets, instance, "vkCmdBindDescriptorSets");
loadVkFunc(&rtVkCreateDescriptorPool, instance, "vkCreateDescriptorPool");
loadVkFunc(&rtVkAllocateDescriptorSets, instance, "vkAllocateDescriptorSets");
loadVkFunc(&rtVkUpdateDescriptorSets, instance, "vkUpdateDescriptorSets");
loadVkFunc(&rtVkGetPhysicalDeviceFeatures, instance, "vkGetPhysicalDeviceFeatures");
loadVkFunc(&rtVkDestroyInstance, instance, "vkDestroyInstance");
loadVkFunc(&rtVkDestroyDevice, instance, "vkDestroyDevice");
loadVkFunc(&rtVkDestroySurfaceKHR, instance, "vkDestroySurfaceKHR");
loadVkFunc(&rtVkDestroySemaphore, instance, "vkDestroySemaphore");
loadVkFunc(&rtVkDestroyFence, instance, "vkDestroyFence");
loadVkFunc(&rtVkDestroyPipeline, instance, "vkDestroyPipeline");
loadVkFunc(&rtVkDestroyPipelineLayout, instance, "vkDestroyPipelineLayout");
loadVkFunc(&rtVkDestroySwapchainKHR, instance, "vkDestroySwapchainKHR");
loadVkFunc(&rtVkDestroyFramebuffer, instance, "vkDestroyFramebuffer");
loadVkFunc(&rtVkDestroyDescriptorSetLayout, instance, "vkDestroyDescriptorSetLayout");
loadVkFunc(&rtVkDestroyDescriptorPool, instance, "vkDestroyDescriptorPool");
loadVkFunc(&rtVkDestroySampler, instance, "vkDestroySampler");
loadVkFunc(&rtVkDestroyRenderPass, instance, "vkDestroyRenderPass");
loadVkFunc(&rtVkDestroyCommandPool, instance, "vkDestroyCommandPool");
loadVkFunc(&rtVkCmdSetScissor, instance, "vkCmdSetScissor");
}
fn loadVkFunc(ptr_to_fn: anytype, instance: c.VkInstance, name: [:0]const u8) void {
if (rtVkGetInstanceProcAddr(instance, name)) |ptr| {
const Ptr = std.meta.Child(@TypeOf(ptr_to_fn));
ptr_to_fn.* = @ptrCast(Ptr, ptr);
} else {
std.debug.panic("Failed to load: {s}", .{name});
}
}
pub fn assertSuccess(res: c.VkResult) void {
if (res != c.VK_SUCCESS) {
@panic("expected success");
}
}
pub fn fromBool(b: bool) c.VkBool32 {
if (b) {
return c.VK_TRUE;
} else {
return c.VK_FALSE;
}
} | lib/vk/vk.zig |
const zupnp = @import("../lib.zig");
const c = @import("../c.zig");
const ChunkedDeinitFn = fn(*anyopaque)void;
const ChunkedGetChunkFn = fn(*anyopaque, []u8, usize)usize;
/// HTTP response to send back to the client.
pub const ServerResponse = union(enum) {
pub const ContentsParameters = struct {
/// Extra headers to send to the client.
headers: ?zupnp.web.Headers = null,
/// Content type.
content_type: [:0]const u8 = "",
/// Contents
contents: []const u8 = "",
};
pub const ChunkedParameters = struct {
/// Extra headers to send to the client.
headers: ?zupnp.web.Headers = null,
/// Content type.
content_type: [:0]const u8 = "",
};
pub const ContentsInternal = struct {
headers: ?zupnp.web.Headers,
content_type: [:0]const u8,
contents: []const u8,
};
pub const ChunkedInternal = struct {
pub const Handler = struct {
instance: *anyopaque,
deinitFn: ?ChunkedDeinitFn,
getChunkFn: ChunkedGetChunkFn,
};
headers: ?zupnp.web.Headers,
content_type: [:0]const u8,
handler: Handler,
};
NotFound: void,
Forbidden: void,
Contents: ContentsInternal,
Chunked: ChunkedInternal,
/// Create a 404 Not Found response.
pub fn notFound() ServerResponse {
return .{ .NotFound = {} };
}
/// Create a 403 Fobidden response.
pub fn forbidden() ServerResponse {
return .{ .Forbidden = {} };
}
/// Create a 200 OK response with contents.
pub fn contents(parameters: ContentsParameters) ServerResponse {
return .{ .Contents = .{
.headers = parameters.headers,
.content_type = parameters.content_type,
.contents = parameters.contents,
} };
}
/// Create a 200 OK response with chunked (i.e. streaming) contents.
pub fn chunked(parameters: ChunkedParameters, handler: anytype) ServerResponse {
const HandlerType = @typeInfo(@TypeOf(handler)).Pointer.child;
return .{ .Chunked = .{
.headers = parameters.headers,
.content_type = parameters.content_type,
.handler = .{
.instance = handler,
.deinitFn = c.mutateCallback(HandlerType, "deinit", ChunkedDeinitFn),
.getChunkFn = c.mutateCallback(HandlerType, "getChunk", ChunkedGetChunkFn).?,
},
} };
}
}; | src/web/server_response.zig |
const std = @import("std");
const expect = std.testing.expect;
const builtin = @import("builtin");
test "@byteSwap integers" {
const ByteSwapIntTest = struct {
fn run() void {
t(u0, 0, 0);
t(u8, 0x12, 0x12);
t(u16, 0x1234, 0x3412);
t(u24, 0x123456, 0x563412);
t(u32, 0x12345678, 0x78563412);
t(u40, 0x123456789a, 0x9a78563412);
t(i48, 0x123456789abc, @bitCast(i48, u48(0xbc9a78563412)));
t(u56, 0x123456789abcde, 0xdebc9a78563412);
t(u64, 0x123456789abcdef1, 0xf1debc9a78563412);
t(u128, 0x123456789abcdef11121314151617181, 0x8171615141312111f1debc9a78563412);
t(u0, u0(0), 0);
t(i8, i8(-50), -50);
t(i16, @bitCast(i16, u16(0x1234)), @bitCast(i16, u16(0x3412)));
t(i24, @bitCast(i24, u24(0x123456)), @bitCast(i24, u24(0x563412)));
t(i32, @bitCast(i32, u32(0x12345678)), @bitCast(i32, u32(0x78563412)));
t(u40, @bitCast(i40, u40(0x123456789a)), u40(0x9a78563412));
t(i48, @bitCast(i48, u48(0x123456789abc)), @bitCast(i48, u48(0xbc9a78563412)));
t(i56, @bitCast(i56, u56(0x123456789abcde)), @bitCast(i56, u56(0xdebc9a78563412)));
t(i64, @bitCast(i64, u64(0x123456789abcdef1)), @bitCast(i64, u64(0xf1debc9a78563412)));
t(
i128,
@bitCast(i128, u128(0x123456789abcdef11121314151617181)),
@bitCast(i128, u128(0x8171615141312111f1debc9a78563412)),
);
}
fn t(comptime I: type, input: I, expected_output: I) void {
std.testing.expectEqual(expected_output, @byteSwap(I, input));
}
};
comptime ByteSwapIntTest.run();
ByteSwapIntTest.run();
}
test "@byteSwap vectors" {
// https://github.com/ziglang/zig/issues/3563
if (builtin.os == .dragonfly) return error.SkipZigTest;
// https://github.com/ziglang/zig/issues/3317
if (builtin.arch == .mipsel) return error.SkipZigTest;
const ByteSwapVectorTest = struct {
fn run() void {
t(u8, 2, [_]u8{ 0x12, 0x13 }, [_]u8{ 0x12, 0x13 });
t(u16, 2, [_]u16{ 0x1234, 0x2345 }, [_]u16{ 0x3412, 0x4523 });
t(u24, 2, [_]u24{ 0x123456, 0x234567 }, [_]u24{ 0x563412, 0x674523 });
}
fn t(
comptime I: type,
comptime n: comptime_int,
input: @Vector(n, I),
expected_vector: @Vector(n, I),
) void {
const actual_output: [n]I = @byteSwap(I, input);
const expected_output: [n]I = expected_vector;
std.testing.expectEqual(expected_output, actual_output);
}
};
comptime ByteSwapVectorTest.run();
ByteSwapVectorTest.run();
} | test/stage1/behavior/byteswap.zig |
/// Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693.
///
/// BLAKE2b is able to produce hash values up to 64 bytes. If you aren't sure
/// which function you need, use the `blake2b` function. If you wish to gain
/// more control of how the algorithm works, use the `Context.init`,
/// `Context.update`, and `Context.final` functions.
const std = @import("std");
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const sigma = [_][]const u8{
&[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
&[_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
&[_]u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
&[_]u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
&[_]u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
&[_]u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
&[_]u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
&[_]u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
&[_]u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
&[_]u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
};
const IV = [_]u64{
0x6a09e667f3bcc908, 0xbb67ae8584caa73b,
0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
0x510e527fade682d1, 0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
};
const IV_type = @TypeOf(IV);
const IV_mem_type = @TypeOf(IV[0]);
const word = 64;
const round = 12;
const block = 128;
const bit_size = u128;
const R0 = 32;
const R1 = 24;
const R2 = 16;
const R3 = 63;
const max_hash_length = 64;
const max_key_size = max_hash_length;
/// Produces a hash value from `input` and writes it to `output`.
///
/// `input` may be an empty data. If an optional `key` is supplied, it must
/// be no larger than 64 bytes. `output` must be between 1 and 64 bytes
/// long, as its size determines the resulting hash length. For instances, if
/// the `output` size is 64 bytes, it returns a BLAKE2b-512 hash.
pub fn blake2b(input: []const u8, output: []u8, key: ?[]const u8) !void {
var blake2b_context = try Context.init(output.len, key);
blake2b_context.update(input);
blake2b_context.final(output) catch unreachable;
}
test "blake2b" {
var buf0: [64]u8 = undefined;
var buf1: [48]u8 = undefined;
var buf2: [32]u8 = undefined;
const text = "hash slinging slasher";
// BLAKE2b-512("hash slinging slasher")
blake2b(text, &buf0, null) catch unreachable;
testing.expectEqualSlices(@TypeOf(buf0[0]), &buf0, &[_]u8{
0x37, 0x98, 0x1d, 0xb4, 0xc7, 0x5a, 0xf4, 0x0f,
0x56, 0xdb, 0xa6, 0x44, 0x40, 0x3e, 0x22, 0x3e,
0x31, 0xfe, 0x8e, 0xba, 0x2e, 0x92, 0xc2, 0x1a,
0xc0, 0x64, 0x80, 0x82, 0x0d, 0x22, 0x50, 0xe9,
0x22, 0xa1, 0x37, 0x6c, 0x40, 0x56, 0x01, 0x72,
0xb8, 0x46, 0xef, 0xc6, 0xfd, 0x17, 0xb4, 0x4a,
0xd4, 0x28, 0x91, 0x3b, 0xa5, 0x82, 0x47, 0x29,
0x9d, 0xc7, 0xc4, 0x6d, 0x3a, 0x14, 0x3b, 0x0c,
});
// BLAKE2b-384("hash slinging slasher")
blake2b(text, &buf1, null) catch unreachable;
testing.expectEqualSlices(@TypeOf(buf1[0]), &buf1, &[_]u8{
0xcc, 0x3e, 0x36, 0x90, 0xb2, 0x27, 0x1f, 0x19,
0xa9, 0xdf, 0x99, 0xca, 0xa1, 0x15, 0x29, 0x4f,
0x7c, 0x0d, 0xd6, 0xa9, 0x96, 0x0a, 0x53, 0xb4,
0x8f, 0x06, 0x70, 0xc8, 0x80, 0x4b, 0x7d, 0xa2,
0xd2, 0x2a, 0xb9, 0xb3, 0x7a, 0x7e, 0xd3, 0x0f,
0x01, 0xfa, 0xe0, 0xe4, 0xb4, 0xff, 0x02, 0x8c,
});
// BLAKE2b-256("hash slinging slasher")
blake2b(text, &buf2, null) catch unreachable;
testing.expectEqualSlices(@TypeOf(buf2[0]), &buf2, &[_]u8{
0xa0, 0xbd, 0x94, 0x69, 0x32, 0xdd, 0xd9, 0x3c,
0xd1, 0x57, 0x80, 0xa3, 0x86, 0xa8, 0xfd, 0x2e,
0x1c, 0x65, 0x50, 0xd3, 0x65, 0x97, 0x9b, 0xa0,
0x4f, 0xf8, 0xdd, 0x42, 0x95, 0x81, 0xb3, 0xcf,
});
}
pub const Context = struct {
h: IV_type = IV,
chunk: [block]u8 = [_]u8{0} ** block,
counter: usize = 0,
bytes_compressed: bit_size = 0,
hash_length: usize,
pub fn init(output_length: usize, key: ?[]const u8) !@This() {
var context = @This() {
.hash_length = output_length,
};
errdefer mem.secureZero(@TypeOf(context.h[0]), &context.h);
if (context.hash_length == 0) return error.LengthIsZero;
if (context.hash_length > max_hash_length) return error.LengthOverflow;
const key_length = if (key) |_| key.?.len else 0;
if (key_length > max_key_size) return error.KeyOverflow;
context.h[0] ^= @intCast(IV_mem_type, 0x01010000 ^ @shlExact(key_length, 8) ^ context.hash_length);
if (key_length > 0) {
var pad_the_key_with_zeroes = [_]u8{0} ** block;
mem.copy(u8, &pad_the_key_with_zeroes, key.?[0..]);
context.update(&pad_the_key_with_zeroes);
context.counter = block;
}
return context;
}
pub fn update(self: *@This(), input: []const u8) void {
const bytes_remaining = input.len;
var i: usize = 0;
while (i < bytes_remaining) : (i += 1) {
if (self.counter == block) {
self.bytes_compressed += block;
self.compress(false);
self.counter = 0;
}
self.chunk[self.counter] = input[i];
self.counter += 1;
}
}
pub fn final(self: *@This(), output: []u8) !void {
defer mem.secureZero(@TypeOf(self.h[0]), &self.h);
if (output.len != self.hash_length) return error.WrongSize;
self.bytes_compressed += self.counter;
mem.set(u8, self.chunk[self.counter..], 0);
self.compress(true);
var result = [_]u8{0} ** word;
for (self.h) |val, i| {
const x: usize = i * (word / 8);
const y: usize = (i + 1) * (word / 8);
mem.writeIntSliceLittle(IV_mem_type, result[x..y], val);
}
mem.secureZero(u8, output);
mem.copy(u8, output, result[0..output.len]);
}
fn compress(self: *@This(), is_last_block: bool) void {
var i: usize = 0;
var v: [16]IV_mem_type = undefined;
while (i < (v.len / 2)) : (i += 1) {
v[i] = self.h[i];
v[i + (v.len / 2)] = IV[i];
}
i = 0;
{
var c: [@sizeOf(@TypeOf(self.bytes_compressed))]u8 = undefined;
mem.writeIntLittle(@TypeOf(self.bytes_compressed), &c, self.bytes_compressed);
const d = c[0..c.len / 2];
const e = c[c.len / 2..c.len];
const f = mem.readIntSliceLittle(IV_mem_type, d[0..]);
const g = mem.readIntSliceLittle(IV_mem_type, e[0..]);
v[12] = v[12] ^ f;
v[13] = v[13] ^ g;
}
if (is_last_block) v[14] = ~v[14];
var m: [16]IV_mem_type = undefined;
for (m) |*val, index| {
val.* = divideChunk(self.chunk, index);
}
while (i < round) : (i += 1) {
var s = sigma[i % 10];
mix(&v, 0, 4, 8, 12, m[s[ 0]], m[s[ 1]]);
mix(&v, 1, 5, 9, 13, m[s[ 2]], m[s[ 3]]);
mix(&v, 2, 6, 10, 14, m[s[ 4]], m[s[ 5]]);
mix(&v, 3, 7, 11, 15, m[s[ 6]], m[s[ 7]]);
mix(&v, 0, 5, 10, 15, m[s[ 8]], m[s[ 9]]);
mix(&v, 1, 6, 11, 12, m[s[10]], m[s[11]]);
mix(&v, 2, 7, 8, 13, m[s[12]], m[s[13]]);
mix(&v, 3, 4, 9, 14, m[s[14]], m[s[15]]);
}
i = 0;
while (i < self.h.len) : (i += 1) {
self.h[i] ^= v[i] ^ v[i + self.h.len];
}
}
};
inline fn divideChunk(chunk: [block]u8, count: usize) IV_mem_type {
const f = block / 16;
var g: [f]u8 = undefined;
var i: usize = 0;
while (i < f) : (i += 1) {
g[i] = chunk[(f * count) + i];
}
return mem.readIntSliceLittle(IV_mem_type, &g);
}
inline fn mix(
v: *[16]IV_mem_type,
comptime a: usize,
comptime b: usize,
comptime c: usize,
comptime d: usize,
x: IV_mem_type,
y: IV_mem_type) void {
v[a] +%= v[b] +% x;
v[d] = math.rotr(IV_mem_type, (v[d] ^ v[a]), @as(usize, R0));
v[c] +%= v[d];
v[b] = math.rotr(IV_mem_type, (v[b] ^ v[c]), @as(usize, R1));
v[a] +%= v[b] +% y;
v[d] = math.rotr(IV_mem_type, (v[d] ^ v[a]), @as(usize, R2));
v[c] +%= v[d];
v[b] = math.rotr(IV_mem_type, (v[b] ^ v[c]), @as(usize, R3));
} | src/blake2b.zig |
const c = @import("c.zig");
const std = @import("std");
const Allocator = std.mem.Allocator;
const DeviceHandle = @import("device_handle.zig").DeviceHandle;
const err = @import("error.zig");
/// WIP
pub fn Transfer(comptime T: type) type {
return struct {
const Self = @This();
const libusb_transfer = extern struct {
dev_handle: *c.libusb_device_handle,
flags: u8,
endpoint: u8,
@"type": u8,
timeout: c_uint,
status: c.libusb_transfer_status,
length: c_int,
actual_length: c_int,
callback: fn (*libusb_transfer) callconv(.C) void,
user_data: ?*anyopaque,
buffer: [*c]u8,
num_iso_packets: c_int,
iso_packet_desc: [0]c.libusb_iso_packet_descriptor, // TODO: Variable Length Array
};
allocator: *Allocator,
transfer: *libusb_transfer,
user_data: T,
callback: fn (*Self) void,
pub fn deinit(self: *const Self) void {
c.libusb_free_transfer(@ptrCast(*c.libusb_transfer, self.transfer));
self.allocator.destroy(self);
}
pub fn submit(self: *Self) err.Error!void {
self.transfer.user_data = self;
try err.failable(c.libusb_submit_transfer(@ptrCast(*c.libusb_transfer, self.transfer)));
}
pub fn cancel(self: *Self) err.Error!void {
try err.failable(c.libusb_cancel_transfer(@ptrCast(*c.libusb_transfer, self.transfer)));
}
pub fn buffer(self: Self) []u8 {
const length = std.math.cast(usize, self.transfer.length) catch @panic("Buffer length too large");
return self.transfer.buffer[0..length];
}
pub fn fillInterrupt(
allocator: *Allocator,
handle: *DeviceHandle,
endpoint: u8,
buf: []u8,
callback: fn (*Self) void,
user_data: T,
timeout: u64,
) (Allocator.err.Error || err.Error)!*Self {
const opt_transfer = @intToPtr(?*libusb_transfer, @ptrToInt(c.libusb_alloc_transfer(0)));
if (opt_transfer) |transfer| {
transfer.*.dev_handle = handle.handle;
transfer.*.endpoint = endpoint;
transfer.*.@"type" = c.LIBUSB_TRANSFER_TYPE_INTERRUPT;
transfer.*.timeout = std.math.cast(c_uint, timeout) catch @panic("Timeout too large");
transfer.*.buffer = buf.ptr;
transfer.*.length = std.math.cast(c_int, buf.len) catch @panic("Length too large");
transfer.*.callback = callbackRaw;
var self = try allocator.create(Self);
self.* = Self{
.allocator = allocator,
.transfer = transfer,
.user_data = user_data,
.callback = callback,
};
return self;
} else {
return error.OutOfMemory;
}
}
export fn callbackRaw(transfer: *libusb_transfer) void {
const self = @intToPtr(*Self, @ptrToInt(transfer.user_data.?));
self.callback(self);
}
};
} | src/transfer.zig |
const std = @import("std");
const tallocator = std.testing.allocator;
const warn = std.debug.warn;
const assertEqual = std.testing.expectEqual;
pub fn sweep(allocat: *std.mem.Allocator, bits: u128, r: u128) !*std.ArrayList(u128){
var i: u128 = 0;
var index: usize = 0;
var collect = std.ArrayList(u128).init(allocat);
errdefer collect.deinit();
var omasks: []u128 = allocat.alloc(u128, @intCast(usize, r)) catch unreachable;
defer allocat.free(omasks);
var mask: u128 = 0;
while ( i < r ) : (i += 1) {
mask |= @intCast(u128, 1) << @truncate(std.math.Log2Int(u128), i);
}
var omask = mask;
var u: u128 = i-1;
var ind: usize = 0;
while ( u > 0 ) : ( u-=1 ) {
omask &= ~( @intCast(u128, 1) << @truncate(std.math.Log2Int(u128), i) );
omasks[ind] = omask;
ind += 1;
}
var j: usize = 0;
var z: u128 = i-j;
while ( j < r-1) : ( j+= 1) {
z = i-j;
mask = omasks[j];
var k: usize = j;
while ( k > 0 ) : ( k-=1 ) {
mask |= @intCast(u128, 1) << @truncate(std.math.Log2Int(u128), (bits-1)-k);
}
while ( z < ((bits-1)-j) ) : ( z += 1 ) {
mask |= @intCast(u128, 1) << @truncate(std.math.Log2Int(u128), z);
try collect.append(mask);
index += 1;
mask &= ~(@intCast(u128, 1) << @truncate(std.math.Log2Int(u128), z));
}
}
mask = collect.items[index-1] & ~@intCast(u128, 1) << @truncate(std.math.Log2Int(u128), 0);
var v: u8 = 1;
while( v < ( (bits-1) - (r-1) ) ) : ( v += 1){
mask |= @intCast(u128, 1) << @truncate(std.math.Log2Int(u128), v);
try collect.append(mask);
index += 1;
mask &= ~(@intCast(u128, 1) << @truncate(std.math.Log2Int(u128), v));
}
return &collect;
}
test "sweep" {
var res = sweep(tallocator, 128, 5) catch unreachable;
defer res.deinit();
var idx: usize = 0;
while (idx < res.items.len) : (idx += 1) {
warn("mask: {b}\r\n", .{res.items[idx]});
}
} | src/main.zig |
const std = @import("std");
const tools = @import("tools");
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 Component = [2]u32;
const Bridge = struct {
strength: u32,
length: u32,
};
fn recurse(components: []Component, depth: u32, con: u32, strength: u32) Bridge {
if (depth > 0) {
assert(components[depth - 1][0] == con or components[depth - 1][1] == con);
} else {
assert(con == 0);
}
var best: ?Bridge = null;
var exhausted = true;
var i = depth;
while (i < components.len) : (i += 1) {
const c = components[i];
var nextcon: u32 = undefined;
if (c[0] == con) {
nextcon = c[1];
} else if (c[1] == con) {
nextcon = c[0];
} else {
continue;
}
exhausted = false;
components[i] = components[depth];
components[depth] = c;
const s = recurse(components, depth + 1, nextcon, strength + (c[0] + c[1]));
if (best == null or s.length > best.?.length or (s.length == best.?.length and s.strength > best.?.strength))
best = s;
components[depth] = components[i];
components[i] = c;
}
if (exhausted) {
trace("found: {} @ depth={}\n", .{ strength, depth });
return .{ .strength = strength, .length = depth };
} else {
return best.?;
}
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
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, "day24.txt", limit);
defer allocator.free(text);
var components_buf: [5000]Component = undefined;
const components = blk: {
var len: usize = 0;
var it = std.mem.tokenize(u8, text, "\n");
while (it.next()) |line| {
if (tools.match_pattern("{}/{}", line)) |vals| {
components_buf[len] = Component{ @intCast(u32, vals[0].imm), @intCast(u32, vals[1].imm) };
len += 1;
} else {
trace("skipping {}\n", .{line});
}
}
break :blk components_buf[0..len];
};
try stdout.print("components = {}\n", .{components.len});
const before = blk: {
var sum: u32 = 0;
for (components) |c| {
sum += c[0] + 1000 * c[1];
}
break :blk sum;
};
try stdout.print("strongest = {}\n", .{recurse(components, 0, 0, 0)});
const after = blk: {
var sum: u32 = 0;
for (components) |c| {
sum += c[0] + 1000 * c[1];
}
break :blk sum;
};
assert(before == after);
} | 2017/day24.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const bssl = @import("bearssl");
const crt = bssl.crt;
const localhost = @import("localhost.zig");
const Params = struct {
pemData: []const u8,
numCerts: usize,
};
const params = [_]Params {
.{
.pemData = @embedFile("five_certs.pem"),
.numCerts = 5,
},
.{
.pemData = @embedFile("many_certs.pem"),
.numCerts = 132,
},
};
fn compareRsaPublicKey(
expected: bssl.c.br_rsa_public_key,
actual: bssl.c.br_rsa_public_key) !void
{
try expectEqualSlices(u8, expected.n[0..expected.nlen], actual.n[0..actual.nlen]);
try expectEqualSlices(u8, expected.e[0..expected.elen], actual.e[0..actual.elen]);
}
fn comparePublicKey(
expected: bssl.c.br_x509_pkey,
actual: bssl.c.br_x509_pkey) !void
{
try expectEqual(expected.key_type, actual.key_type);
try expectEqual(bssl.c.BR_KEYTYPE_RSA, actual.key_type); // only cover RSA for now
try compareRsaPublicKey(expected.key.rsa, actual.key.rsa);
}
fn compareAnchors(
expected: []const bssl.c.br_x509_trust_anchor,
actual: []const bssl.c.br_x509_trust_anchor) !void
{
try expectEqual(expected.len, actual.len);
for (expected) |_, i| {
const dnSliceExpected = expected[i].dn.data[0..expected[i].dn.len];
const dnSliceActual = actual[i].dn.data[0..actual[i].dn.len];
try expectEqualSlices(u8, dnSliceExpected, dnSliceActual);
try expectEqual(expected[i].flags, actual[i].flags);
try comparePublicKey(expected[i].pkey, actual[i].pkey);
}
}
test "cert anchors (single)"
{
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch |err| std.log.err("{}", .{err});
var allocator = gpa.allocator();
const pemData = @embedFile("localhost.crt");
var anchors = try crt.Anchors.init(pemData, allocator);
defer anchors.deinit(allocator);
const rawAnchors = try anchors.getRawAnchors(allocator);
defer allocator.free(rawAnchors);
try compareAnchors(&localhost.TAs, rawAnchors);
}
test "cert anchors (multiple, no compare for now)"
{
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch |err| std.log.err("{}", .{err});
var allocator = gpa.allocator();
for (params) |param| {
var anchors = try crt.Anchors.init(param.pemData, allocator);
defer anchors.deinit(allocator);
try expectEqual(param.numCerts, anchors.anchors.len);
const rawAnchors = try anchors.getRawAnchors(allocator);
defer allocator.free(rawAnchors);
try expectEqual(param.numCerts, rawAnchors.len);
}
}
fn compareChain(
expected: []const bssl.c.br_x509_certificate,
actual: []const bssl.c.br_x509_certificate) !void
{
try expectEqual(expected.len, actual.len);
for (expected) |_, i| {
const sliceExpected = expected[i].data[0..expected[i].data_len];
const sliceActual = actual[i].data[0..actual[i].data_len];
try expectEqualSlices(u8, sliceExpected, sliceActual);
}
}
test "cert chain (single)"
{
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch |err| std.log.err("{}", .{err});
var allocator = gpa.allocator();
const pemData = @embedFile("localhost.crt");
var chain = try crt.Chain.init(pemData, allocator);
defer chain.deinit(allocator);
try compareChain(&localhost.CHAIN, chain.chain);
}
test "cert chain (multiple, no compare for now)"
{
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch |err| std.log.err("{}", .{err});
var allocator = gpa.allocator();
for (params) |param| {
var chain = try crt.Chain.init(param.pemData, allocator);
defer chain.deinit(allocator);
try expectEqual(param.numCerts, chain.chain.len);
}
} | test/test_crt.zig |
const memory = @import("memory.zig");
/// Map implemented using a simple binary tree.
///
/// TODO: Replace with Balancing Tree
///
/// For Reference See:
/// https://en.wikipedia.org/wiki/Binary_search_tree
pub fn Map(comptime KeyType: type, comptime ValueType: type,
comptime eql: fn(a: KeyType, b: KeyType) bool,
comptime cmp: fn(a: KeyType, b: KeyType) bool) type {
return struct {
const Self = @This();
pub const Node = struct {
left: ?*Node,
right: ?*Node,
parent: ?*Node,
key: KeyType,
value: ValueType,
pub fn replace_child(self: *Node, current_child: *Node, new_child: ?*Node) void {
if (self.left == current_child) {
self.left = new_child;
} else if (self.right == current_child) {
self.right = new_child;
} else {
@panic("Map.replace_child: Not a child of node!");
}
if (new_child) |node| node.parent = self;
}
pub fn get_child(self: *const Node, right: bool) ?*Node {
return if (right) self.right else self.left;
}
};
alloc: *memory.Allocator,
root: ?*Node = null,
len: usize = 0,
const FindParentResult = struct {
parent: *Node,
leaf: *?*Node,
};
fn find_parent(self: *Self, key: KeyType, start_node: *Node) FindParentResult {
_ = self;
var i = start_node;
while (true) {
if (cmp(key, i.key)) {
if (i.right == null or eql(key, i.right.?.key)) {
return FindParentResult{.parent = i, .leaf = &i.right};
} else {
i = i.right.?;
}
} else {
if (i.left == null or eql(key, i.left.?.key)) {
return FindParentResult{.parent = i, .leaf = &i.left};
} else {
i = i.left.?;
}
}
}
}
pub fn insert_node(self: *Self, node: *Node) void {
if (self.root == null) {
node.parent = null;
self.root = node;
} else {
const r = self.find_parent(node.key, self.root.?);
node.parent = r.parent;
r.leaf.* = node;
}
self.len += 1;
}
pub fn insert(self: *Self, key: KeyType, value: ValueType) memory.MemoryError!*Node {
const node = try self.alloc.alloc(Node);
node.left = null;
node.right = null;
node.key = key;
node.value = value;
self.insert_node(node);
return node;
}
pub fn find_node(self: *Self, key: KeyType) ?*Node {
if (self.root == null) {
return null;
}
if (eql(key, self.root.?.key)) {
return self.root;
}
return self.find_parent(key, self.root.?).leaf.*;
}
pub fn find(self: *Self, key: KeyType) ?ValueType {
if (self.find_node(key)) |node| {
return node.value;
}
return null;
}
fn replace_node(self: *Self, current: *Node, new: ?*Node) void {
if (current == self.root) {
self.root = new;
} else {
current.parent.?.replace_child(current, new);
}
}
pub fn remove_node(self: *Self, node: *Node) void {
const right_null = node.right == null;
const left_null = node.left == null;
if (right_null and left_null) {
self.replace_node(node, null);
} else if (right_null and !left_null) {
self.replace_node(node, node.left);
} else if (!right_null and left_null) {
self.replace_node(node, node.right);
} else {
const replacement = node.left.?;
const reattach = node.right.?;
self.replace_node(node, replacement);
const r = self.find_parent(reattach.key, replacement);
reattach.parent = r.parent;
r.leaf.* = reattach;
}
self.len -= 1;
}
pub fn dump_node(self: *Self, node: ?*Node) void {
if (node == null) {
@import("std").debug.warn("null");
} else {
@import("std").debug.warn("({} (", node.?.key);
if (node.?.parent == null) {
@import("std").debug.warn("null): ");
} else {
@import("std").debug.warn("{}): ", node.?.parent.?.key);
}
self.dump_node(node.?.left);
@import("std").debug.warn(", ");
self.dump_node(node.?.right);
@import("std").debug.warn(")");
}
}
pub fn dump(self: *Self) void {
self.dump_node(self.root);
}
pub fn remove(self: *Self, key: KeyType) memory.MemoryError!bool {
if (self.find_node(key)) |node| {
self.remove_node(node);
try self.alloc.free(node);
return true;
}
return false;
}
/// Iterator that uses Morris Traversal
pub const Iterator = struct {
next_node: ?*Node = null,
pub fn init(self: *Iterator, root: ?*Node) void {
if (root == null) return;
self.next_node = root;
while (self.next_node.?.left) |node| {
self.next_node = node;
}
}
pub fn next(self: *Iterator) ?*Node {
if (self.next_node == null) {
return null;
}
const rv = self.next_node.?;
if (rv.right != null) {
self.next_node = rv.right;
while (self.next_node.?.left) |node| {
self.next_node = node;
}
return rv;
}
while (true) {
const node = self.next_node.?;
if (node.parent) |parent| {
defer self.next_node = parent;
if (parent.left == self.next_node) break;
} else {
self.next_node = null;
break;
}
}
return rv;
}
};
pub fn iterate(self: *Self) Iterator {
var rv = Iterator{};
rv.init(self.root);
return rv;
}
};
}
fn usize_eql(a: usize, b: usize) bool {
return a == b;
}
fn usize_cmp(a: usize, b: usize) bool {
return a > b;
}
test "Map" {
const std = @import("std");
var alloc = memory.UnitTestAllocator{};
const equal = std.testing.expectEqual;
alloc.init();
defer alloc.done();
const UsizeUsizeMap = Map(usize, usize, usize_eql, usize_cmp);
var map = UsizeUsizeMap{.alloc = &alloc.allocator};
const nil: ?usize = null;
const niln: ?*UsizeUsizeMap.Node = null;
// Empty
try equal(@as(usize, 0), map.len);
try equal(nil, map.find(45));
// Insert Some Values
_ = try map.insert(4, 65);
try equal(@as(usize, 1), map.len);
_ = try map.insert(1, 44);
_ = try map.insert(10, 12345);
_ = try map.insert(23, 5678);
_ = try map.insert(7, 53);
try equal(@as(usize, 5), map.len);
// Find Them
try equal(@as(usize, 12345), map.find(10).?);
try equal(@as(usize, 44), map.find(1).?);
try equal(@as(usize, 5678), map.find(23).?);
try equal(@as(usize, 65), map.find(4).?);
try equal(@as(usize, 53), map.find(7).?);
var it = map.iterate();
try equal(@as(usize, 1), it.next().?.key);
try equal(@as(usize, 4), it.next().?.key);
try equal(@as(usize, 7), it.next().?.key);
try equal(@as(usize, 10), it.next().?.key);
try equal(@as(usize, 23), it.next().?.key);
try equal(niln, it.next());
// Try to Find Non-Existent Key
try equal(nil, map.find(45));
try equal(false, try map.remove(45));
// Remove Node with Two Children
try equal(true, try map.remove(10));
try equal(@as(usize, 4), map.len);
try equal(@as(usize, 4), map.find_node(7).?.parent.?.key);
// Remove the Rest
try equal(true, try map.remove(1));
try equal(true, try map.remove(23));
try equal(true, try map.remove(4));
try equal(true, try map.remove(7));
try equal(@as(usize, 0), map.len);
// Try to Find Keys That Once Existed
try equal(nil, map.find(1));
try equal(nil, map.find(4));
} | kernel/map.zig |
const std = @import("std");
const assert = std.debug.assert;
const ExecError = error{InvalidOpcode};
fn exec(intcode: []i32) !void {
var pos: usize = 0;
while (true) {
switch (intcode[pos]) {
99 => break,
1 => {
const pos_x = @intCast(usize, intcode[pos + 1]);
const pos_y = @intCast(usize, intcode[pos + 2]);
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = intcode[pos_x] + intcode[pos_y];
pos += 4;
},
2 => {
const pos_x = @intCast(usize, intcode[pos + 1]);
const pos_y = @intCast(usize, intcode[pos + 2]);
const pos_result = @intCast(usize, intcode[pos + 3]);
intcode[pos_result] = intcode[pos_x] * intcode[pos_y];
pos += 4;
},
else => return error.InvalidOpcode,
}
}
}
test "test exec 1" {
var intcode = [_]i32{ 1, 0, 0, 0, 99 };
try exec(intcode[0..]);
assert(intcode[0] == 2);
}
test "test exec 2" {
var intcode = [_]i32{ 2, 3, 0, 3, 99 };
try exec(intcode[0..]);
assert(intcode[3] == 6);
}
test "test exec 3" {
var intcode = [_]i32{ 2, 4, 4, 5, 99, 0 };
try exec(intcode[0..]);
assert(intcode[5] == 9801);
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const stdin = std.io.getStdIn();
var stdreader = stdin.reader();
var buf: [1024]u8 = undefined;
var ints = std.ArrayList(i32).init(allocator);
// read everything into an int arraylist
while (try stdreader.readUntilDelimiterOrEof(&buf, ',')) |item| {
try ints.append(try std.fmt.parseInt(i32, item, 10));
}
ints.items[1] = 12;
ints.items[2] = 2;
try exec(ints.items);
// output entry at position 0
std.debug.warn("value at position 0: {}\n", .{ints.items[0]});
} | zig/02.zig |
const std = @import("std");
const assert = std.debug.assert;
const ArgError = @import("main.zig").ArgError;
pub const ImageFormat = enum(u8) {
Pbm = 0,
Pgm = 1,
Ppm = 2,
pub fn parse(fmt_str_user: []const u8) ArgError!ImageFormat {
const fmts = [_][]const u8{ "pbm", "pgm", "ppm" };
var fmt_idx: u8 = 0;
for (fmts) |fmt_str| {
if (std.mem.eql(u8, fmt_str, fmt_str_user)) {
return @intToEnum(ImageFormat, fmt_idx);
}
fmt_idx += 1;
}
return ArgError.FormatInvalid;
}
};
fn savePbm(bytes: []const u8, file: *const std.fs.File, width: u16, height: u16) !void {
const signaure = "P1\n";
try file.writeAll(signaure);
try file.writer().print("{d} {d}\n", .{ width, height });
var line_width: u16 = 0;
for (bytes) |byte, byte_idx| {
if (line_width + 2 + 1 >= 70) {
try file.writer().writeByte('\n');
line_width = 0;
}
_ = try file.writer().write(&.{'0' + byte});
line_width += 1;
}
}
fn savePgm(bytes: []const u8, file: *const std.fs.File, width: u16, height: u16) !void {
const signaure = "P2\n";
try file.writeAll(signaure);
try file.writer().print("{d} {d}\n255\n", .{ width, height });
var line_width: u16 = 0;
for (bytes) |byte, byte_idx| {
if (line_width + 2 + 1 >= 70) {
try file.writer().writeByte('\n');
line_width = 0;
}
const pos_pre = try file.getPos();
try file.writer().print("{d} ", .{byte});
const pos_post = try file.getPos();
line_width += @intCast(u16, pos_post - pos_pre);
}
}
fn savePpm(bytes: []const u8, file: *const std.fs.File, width: u16, height: u16) !void {
const signaure = "P3\n";
try file.writeAll(signaure);
try file.writer().print("{d} {d}\n255\n", .{ width, height });
var line_width: u16 = 0;
for (bytes) |byte, byte_idx| {
if (line_width + 2 + 1 >= 70) {
try file.writer().writeByte('\n');
line_width = 0;
}
const pos_pre = try file.getPos();
try file.writer().print("{d} ", .{byte});
const pos_post = try file.getPos();
line_width += @intCast(u16, pos_post - pos_pre);
}
}
pub fn saveFile(file: *const std.fs.File, bytes: []const u8, format: ImageFormat, width: u16, height: u16) !void {
return switch (format) {
ImageFormat.Pbm => savePbm(bytes, file, width, height),
ImageFormat.Pgm => savePgm(bytes, file, width, height),
ImageFormat.Ppm => savePpm(bytes, file, width, height),
};
} | src/image.zig |
const std = @import("std");
const array = @import("array.zig");
const Array = array.Array;
const tensor = @import("tensor.zig");
const Tensor = tensor.Tensor;
const expr = tensor.expr;
pub fn relu(alc: *std.mem.Allocator, x: Tensor) !Tensor {
return try expr(alc, "max(0, x)", .{ .x = x });
}
pub fn logSoftmax(alc: *std.mem.Allocator, x: Tensor, dims: []const u64) !Tensor {
var dims_tensor = Tensor.flatFromBuffer(u64, @bitCast([]u64, dims));
// https://github.com/google/jax/pull/2260
var x_shifted = try expr(alc, "x - detach(keep_max(x, dims))", .{ .x = x, .dims = dims_tensor });
defer x_shifted.release();
return try expr(alc, "x_shifted - log(keep_sum(exp(x_shifted), dims))", .{ .x_shifted = x_shifted, .dims = dims_tensor });
}
test "logSoftmax" {
var input = try Tensor.allocWithString(f32, std.testing.allocator, "[[1, 2, 3], [1, 20, 300], [0, -1, 1000], [0, -1, 1000]]", tensor.REQUIRES_GRAD);
defer input.release();
var dims = [_]u64{1};
var output = try logSoftmax(std.testing.allocator, input, &dims);
defer output.release();
var expected_output = try Array.allocWithString(f32, std.testing.allocator, "[[-2.4076e+00, -1.4076e+00, -4.0761e-01], [-2.9900e+02, -2.8000e+02, 0.0000e+00], [-1.0000e+03, -1.0010e+03, 0.0000e+00], [-1.0000e+03, -1.0010e+03, 0.0000e+00]]");
defer expected_output.release();
std.testing.expect(array.allclose(output.data, expected_output, 1e-5, 1e-8));
var grad_output = try tensor.onesLikeAlloc(std.testing.allocator, output, tensor.NO_FLAGS);
defer grad_output.release();
try tensor.backwardAlloc(std.testing.allocator, output, grad_output);
var expected_grad_input = try Array.allocWithString(f32, std.testing.allocator, "[[ 0.7299, 0.2658, -0.9957], [ 1.0000, 1.0000, -2.0000], [1.0000, 1.0000, -2.0000], [1.0000, 1.0000, -2.0000]]");
defer expected_grad_input.release();
std.testing.expect(array.allclose(input.grad.?, expected_grad_input, 1e-5, 1e-3));
}
pub fn nllLoss(alc: *std.mem.Allocator, input: Tensor, target: Tensor) !Tensor {
if (input.data.ndim != 2) {
@panic("Input has wrong number of dimensions");
}
if (target.data.ndim != 1) {
@panic("Target has wrong number of dimensions");
}
if (!array.dtypeIsInteger(target.data.dtype)) {
@panic("Target dtype must be int");
}
var target_expanded = target.reshapeView(&[_]u64{target.data.numel, 1});
var dims = [_]u64{0,1};
return try expr(alc, "reduce_mean(-gather(input, 1, target), dims)", .{.input=input, .target=target_expanded, .dims=Tensor.flatFromBuffer(u64, &dims)});
}
test "nllLoss" {
var input = try Tensor.allocWithString(f32, std.testing.allocator, "[[1, 2, 3], [1, 20, 300], [0, 1, 1000]]", tensor.REQUIRES_GRAD);
defer input.release();
var target = try Tensor.allocWithString(u64, std.testing.allocator, "[0, 1, 2]", tensor.NO_FLAGS);
defer target.release();
var output = try nllLoss(std.testing.allocator, input, target);
defer output.release();
var expected_output = try array.scalarAlloc(std.testing.allocator, .f32, -340.3333);
defer expected_output.release();
std.testing.expect(array.allclose(output.data, expected_output, 1e-05, 1e-08));
}
/// Kaiming init for fan_in init with gain set for ReLU
/// https://arxiv.org/abs/1502.01852
pub fn kaimingUniform(alc: *std.mem.Allocator, dst: Array, r: *std.rand.Random) !void {
var high = try array.expr(alc, "(3.0 .^ 0.5) .* ((2.0 .^ 0.5) ./ (fan .^ 0.5))", .{.fan=dst.getShape()[0]});
defer high.release();
var low = try array.uminusAlloc(alc, high);
defer low.release();
array.fillUniform(dst, r, low, high);
} | src/funcs.zig |
const std = @import("std");
const reg = @import("registry.zig");
const id_render = @import("../id_render.zig");
const cparse = @import("c_parse.zig");
const mem = std.mem;
const Allocator = mem.Allocator;
const CaseStyle = id_render.CaseStyle;
const IdRenderer = id_render.IdRenderer;
const preamble =
\\
\\// This file is generated from the Khronos OpenXR XML API registry
\\
\\const std = @import("std");
\\const builtin = @import("builtin");
\\const root = @import("root");
\\pub const openxr_call_conv: builtin.CallingConvention = if (builtin.os.tag == .windows and builtin.cpu.arch == .i386)
\\ .Stdcall
\\ else if (builtin.abi == .android and (builtin.cpu.arch.isARM() or builtin.cpu.arch.isThumb()) and builtin.Target.arm.featureSetHas(builtin.cpu.features, .has_v7) and builtin.cpu.arch.ptrBitWidth() == 32)
\\ // On Android 32-bit ARM targets, OpenXR functions use the "hardfloat"
\\ // calling convention, i.e. float parameters are passed in registers. This
\\ // is true even if the rest of the application passes floats on the stack,
\\ // as it does by default when compiling for the armeabi-v7a NDK ABI.
\\ .AAPCSVFP
\\ else
\\ .C;
\\pub fn FlagsMixin(comptime FlagsType: type) type {
\\ return struct {
\\ pub const IntType = Flags64;
\\ pub fn toInt(self: FlagsType) IntType {
\\ return @bitCast(IntType, self);
\\ }
\\ pub fn fromInt(flags: IntType) FlagsType {
\\ return @bitCast(FlagsType, flags);
\\ }
\\ pub fn merge(lhs: FlagsType, rhs: FlagsType) FlagsType {
\\ return fromInt(toInt(lhs) | toInt(rhs));
\\ }
\\ pub fn intersect(lhs: FlagsType, rhs: FlagsType) FlagsType {
\\ return fromInt(toInt(lhs) & toInt(rhs));
\\ }
\\ pub fn complement(self: FlagsType) FlagsType {
\\ return fromInt(~toInt(lhs));
\\ }
\\ pub fn subtract(lhs: FlagsType, rhs: FlagsType) FlagsType {
\\ return fromInt(toInt(lhs) & toInt(rhs.complement()));
\\ }
\\ pub fn contains(lhs: FlagsType, rhs: FlagsType) bool {
\\ return toInt(intersect(lhs, rhs)) == toInt(rhs);
\\ }
\\ };
\\}
\\pub fn makeVersion(major: u16, minor: u16, patch: u32) u64 {
\\ return (@as(u64, major) << 48) | (@as(u64, minor) << 32) | patch;
\\}
\\pub fn versionMajor(version: u64) u16 {
\\ return @truncate(u16, version >> 48);
\\}
\\pub fn versionMinor(version: u16) u10 {
\\ return @truncate(u16, version >> 32);
\\}
\\pub fn versionPatch(version: u64) u32 {
\\ return @truncate(u32, version);
\\}
\\
;
const builtin_types = std.ComptimeStringMap([]const u8, .{
.{ "void", @typeName(void) },
.{ "char", @typeName(u8) },
.{ "float", @typeName(f32) },
.{ "double", @typeName(f64) },
.{ "uint8_t", @typeName(u8) },
.{ "uint16_t", @typeName(u16) },
.{ "uint32_t", @typeName(u32) },
.{ "uint64_t", @typeName(u64) },
.{ "int32_t", @typeName(i32) },
.{ "int64_t", @typeName(i64) },
.{ "size_t", @typeName(usize) },
.{ "int", @typeName(c_int) },
});
const foreign_types = std.ComptimeStringMap([]const u8, .{
.{ "Display", "opaque {}" },
.{ "VisualID", @typeName(c_uint) },
.{ "Window", @typeName(c_ulong) },
.{ "xcb_glx_fbconfig_t", "opaque {}" },
.{ "xcb_glx_drawable_t", "opaque {}" },
.{ "xcb_glx_context_t", "opaque {}" },
.{ "xcb_connection_t", "opaque {}" },
.{ "xcb_visualid_t", @typeName(u32) },
.{ "xcb_window_t", @typeName(u32) },
.{ "VkAllocationCallbacks", "@import(\"vulkan\").AllocationCallbacks" },
.{ "VkDevice", "@import(\"vulkan\").Device" },
.{ "VkDeviceCreateInfo", "@import(\"vulkan\").DeviceCreateInfo" },
.{ "VkFormat", "@import(\"vulkan\").Format" },
.{ "VkImage", "@import(\"vulkan\").Image" },
.{ "VkInstance", "@import(\"vulkan\").Instance" },
.{ "VkInstanceCreateInfo", "@import(\"vulkan\").InstanceCreateInfo" },
.{ "VkPhysicalDevice", "@import(\"vulkan\").PhysicalDevice" },
.{ "VkResult", "@import(\"vulkan\").Result" },
.{ "PFN_vkGetInstanceProcAddr", "@import(\"vulkan\").PfnGetInstanceProcAddr" },
});
const initialized_types = std.ComptimeStringMap([]const u8, .{
.{ "XrVector2f", "0" },
.{ "XrVector3f", "0" },
.{ "XrVector4f", "0" },
.{ "XrColor4f", "0" },
.{ "XrQuaternionf", "0" },
.{ "XrPosef", ".{}" },
.{ "XrOffset2Df", "0" },
.{ "XrExtent2Df", "0" },
.{ "XrRect2Df", ".{}" },
.{ "XrOffset2Di", "0" },
.{ "XrExtent2Di", "0" },
.{ "XrRect2Di", ".{}" },
});
fn eqlIgnoreCase(lhs: []const u8, rhs: []const u8) bool {
if (lhs.len != rhs.len) {
return false;
}
for (lhs) |c, i| {
if (std.ascii.toLower(c) != std.ascii.toLower(rhs[i])) {
return false;
}
}
return true;
}
pub fn trimXrNamespace(id: []const u8) []const u8 {
const prefixes = [_][]const u8{ "XR_", "xr", "Xr", "PFN_xr" };
for (prefixes) |prefix| {
if (mem.startsWith(u8, id, prefix)) {
return id[prefix.len..];
}
}
return id;
}
fn Renderer(comptime WriterType: type) type {
return struct {
const Self = @This();
const WriteError = WriterType.Error;
const RenderTypeInfoError = WriteError || error{OutOfMemory};
const BitflagName = struct {
/// Name without FlagBits, so XrSurfaceTransformFlagBitsKHR
/// becomes XrSurfaceTransform
base_name: []const u8,
/// Optional tag of the flag
tag: ?[]const u8,
};
const ParamType = enum {
in_pointer,
out_pointer,
in_out_pointer,
bitflags,
mut_buffer_len,
buffer_len,
other,
};
const ReturnValue = struct {
name: []const u8,
return_value_type: reg.TypeInfo,
origin: enum {
parameter,
inner_return_value,
},
};
const CommandDispatchType = enum {
base,
instance,
};
writer: WriterType,
allocator: *Allocator,
registry: *const reg.Registry,
id_renderer: *IdRenderer,
declarations_by_name: std.StringHashMap(*const reg.DeclarationType),
fn init(writer: WriterType, allocator: *Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !Self {
const tags = try allocator.alloc([]const u8, registry.tags.len);
errdefer allocator.free(tags);
for (tags) |*tag, i| tag.* = registry.tags[i].name;
var declarations_by_name = std.StringHashMap(*const reg.DeclarationType).init(allocator);
errdefer declarations_by_name.deinit();
for (registry.decls) |*decl| {
const result = try declarations_by_name.getOrPut(decl.name);
if (result.found_existing) {
return error.InvalidRegistry;
}
result.entry.value = &decl.decl_type;
}
return Self{
.writer = writer,
.allocator = allocator,
.registry = registry,
.id_renderer = id_renderer,
.declarations_by_name = declarations_by_name,
};
}
fn deinit(self: *Self) void {
self.declarations_by_name.deinit();
self.allocator.free(self.id_renderer.tags);
self.id_renderer.deinit();
}
fn writeIdentifier(self: Self, id: []const u8) !void {
try self.id_renderer.render(self.writer, id);
}
fn writeIdentifierWithCase(self: *Self, case: CaseStyle, id: []const u8) !void {
try self.id_renderer.renderWithCase(self.writer, case, id);
}
fn writeIdentifierFmt(self: *Self, comptime fmt: []const u8, args: anytype) !void {
try self.id_renderer.renderFmt(self.writer, fmt, args);
}
fn extractEnumFieldName(self: Self, enum_name: []const u8, field_name: []const u8) ![]const u8 {
const adjusted_enum_name = if (mem.eql(u8, enum_name, "XrStructureType"))
"XrType"
else
self.id_renderer.stripAuthorTag(enum_name);
var enum_it = id_render.SegmentIterator.init(adjusted_enum_name);
var field_it = id_render.SegmentIterator.init(field_name);
while (true) {
const rest = field_it.rest();
const enum_segment = enum_it.next() orelse return rest;
const field_segment = field_it.next() orelse return error.FieldNameEqualsEnumName;
if (!eqlIgnoreCase(enum_segment, field_segment)) {
return rest;
}
}
}
fn extractBitflagName(self: Self, name: []const u8) ?BitflagName {
const tag = self.id_renderer.getAuthorTag(name);
const base_name = if (tag) |tag_name| name[0 .. name.len - tag_name.len] else name;
if (!mem.endsWith(u8, base_name, "FlagBits")) {
return null;
}
return BitflagName{
.base_name = base_name[0 .. base_name.len - "FlagBits".len],
.tag = tag,
};
}
fn isFlags(self: Self, name: []const u8) bool {
const tag = self.id_renderer.getAuthorTag(name);
const base_name = if (tag) |tag_name| name[0 .. name.len - tag_name.len] else name;
return mem.endsWith(u8, base_name, "Flags64");
}
fn containerHasField(self: Self, container: *const reg.Container, field_name: []const u8) bool {
for (container.fields) |field| {
if (mem.eql(u8, field, field_name)) {
return true;
}
}
return false;
}
fn isInOutPointer(self: Self, ptr: reg.Pointer) !bool {
if (ptr.child.* != .name) {
return false;
}
var name = ptr.child.name;
const decl = while (true) {
const decl = self.declarations_by_name.get(name) orelse return error.InvalidRegistry;
if (decl.* != .alias) {
break decl;
}
name = decl.alias.name;
} else unreachable;
if (decl.* != .container) {
return false;
}
const container = decl.container;
if (container.is_union) {
return false;
}
for (container.fields) |field| {
if (mem.eql(u8, field.name, "next")) {
return true;
}
}
return false;
}
fn classifyParam(self: Self, param: reg.Command.Param) !ParamType {
switch (param.param_type) {
.pointer => |ptr| {
if (param.is_buffer_len) {
if (ptr.is_const or ptr.is_optional) {
return error.InvalidRegistry;
}
return .mut_buffer_len;
}
if (ptr.child.* == .name) {
const child_name = ptr.child.name;
if (mem.eql(u8, child_name, "void")) {
return .other;
} else if (builtin_types.get(child_name) == null and trimXrNamespace(child_name).ptr == child_name.ptr) {
return .other; // External type
}
}
if (ptr.size == .one and !ptr.is_optional) {
// Sometimes, a mutable pointer to a struct is taken, even though
// OpenXR expects this struct to be initialized. This is particularly the case
// for getting structs which include next chains.
if (ptr.is_const) {
return .in_pointer;
} else if (try self.isInOutPointer(ptr)) {
return .in_out_pointer;
} else {
return .out_pointer;
}
}
},
.name => |name| {
if (self.extractBitflagName(param.param_type.name) != null or self.isFlags(param.param_type.name)) {
return .bitflags;
}
},
else => {},
}
if (param.is_buffer_len) {
return .buffer_len;
}
return .other;
}
fn classifyCommandDispatch(self: Self, name: []const u8, command: reg.Command) CommandDispatchType {
const override_functions = std.ComptimeStringMap(CommandDispatchType, .{
.{ "xrGetInstanceProcAddr", .base },
.{ "xrCreateInstance", .base },
.{ "xrEnumerateApiLayerProperties", .base },
.{ "xrEnumerateInstanceExtensionProperties", .base },
});
const dispatch_types = std.ComptimeStringMap(CommandDispatchType, .{
.{ "XrInstance", .instance },
});
if (override_functions.get(name)) |dispatch_type| {
return dispatch_type;
}
return switch (command.params[0].param_type) {
.name => .instance,
else => return .base,
};
}
fn render(self: *Self) !void {
try self.renderCopyright();
try self.writer.writeAll(preamble);
for (self.registry.api_constants) |api_constant| {
try self.renderApiConstant(api_constant);
}
for (self.registry.decls) |decl| {
try self.renderDecl(decl);
}
try self.renderCommandPtrs();
try self.renderExtensionInfo();
try self.renderWrappers();
}
fn renderCopyright(self: *Self) !void {
var it = mem.split(self.registry.copyright, "\n");
while (it.next()) |line| {
try self.writer.print("// {s}\n", .{line});
}
}
fn renderApiConstant(self: *Self, api_constant: reg.ApiConstant) !void {
try self.writer.writeAll("pub const ");
try self.renderName(api_constant.name);
try self.writer.writeAll(" = ");
switch (api_constant.value) {
.expr => |expr| try self.renderApiConstantExpr(expr),
.version => |version| {
try self.writer.writeAll("makeVersion(");
for (version) |part, i| {
if (i != 0) {
try self.writer.writeAll(", ");
}
try self.renderApiConstantExpr(part);
}
try self.writer.writeAll(")");
},
}
try self.writer.writeAll(";\n");
}
fn renderApiConstantExpr(self: *Self, expr: []const u8) !void {
const adjusted_expr = if (expr.len > 2 and expr[0] == '(' and expr[expr.len - 1] == ')')
expr[1 .. expr.len - 1]
else
expr;
var tokenizer = cparse.CTokenizer{ .source = adjusted_expr };
var peeked: ?cparse.Token = null;
while (true) {
const tok = peeked orelse (try tokenizer.next()) orelse break;
peeked = null;
switch (tok.kind) {
.lparen, .rparen, .tilde, .minus => {
try self.writer.writeAll(tok.text);
continue;
},
.id => {
try self.renderName(tok.text);
continue;
},
.int => {},
else => return error.InvalidApiConstant,
}
const suffix = (try tokenizer.next()) orelse {
try self.writer.writeAll(tok.text);
break;
};
switch (suffix.kind) {
.id => {
if (mem.eql(u8, suffix.text, "ULL")) {
try self.writer.print("@as(u64, {s})", .{tok.text});
} else if (mem.eql(u8, suffix.text, "U")) {
try self.writer.print("@as(u32, {s})", .{tok.text});
} else {
return error.InvalidApiConstant;
}
},
.dot => {
const decimal = (try tokenizer.next()) orelse return error.InvalidConstantExpr;
try self.writer.print("@as(f32, {s}.{s})", .{ tok.text, decimal.text });
const f = (try tokenizer.next()) orelse return error.InvalidConstantExpr;
if (f.kind != .id or !mem.eql(u8, f.text, "f")) {
return error.InvalidApiConstant;
}
},
else => {
try self.writer.writeAll(tok.text);
peeked = suffix;
},
}
}
}
fn renderTypeInfo(self: *Self, type_info: reg.TypeInfo) RenderTypeInfoError!void {
switch (type_info) {
.name => |name| try self.renderName(name),
.command_ptr => |command_ptr| try self.renderCommandPtr(command_ptr, true),
.pointer => |pointer| try self.renderPointer(pointer),
.array => |array| try self.renderArray(array),
}
}
fn renderName(self: *Self, name: []const u8) !void {
if (builtin_types.get(name)) |zig_name| {
try self.writer.writeAll(zig_name);
return;
} else if (self.extractBitflagName(name)) |bitflag_name| {
try self.writeIdentifierFmt("{s}Flags{s}", .{
trimXrNamespace(bitflag_name.base_name),
@as([]const u8, if (bitflag_name.tag) |tag| tag else ""),
});
return;
} else if (mem.startsWith(u8, name, "xr")) {
// Function type, always render with the exact same text for linking purposes.
try self.writeIdentifier(name);
return;
} else if (mem.startsWith(u8, name, "Xr")) {
// Type, strip namespace and write, as they are alreay in title case.
try self.writeIdentifier(name[2..]);
return;
} else if (mem.startsWith(u8, name, "PFN_xr")) {
// Function pointer type, strip off the PFN_xr part and replace it with Pfn. Note that
// this function is only called to render the typedeffed function pointers like xrVoidFunction
try self.writeIdentifierFmt("Pfn{s}", .{name[6..]});
return;
} else if (mem.startsWith(u8, name, "XR_")) {
// Constants
try self.writeIdentifier(name[3..]);
return;
}
try self.writeIdentifier(name);
}
fn renderCommandPtr(self: *Self, command_ptr: reg.Command, optional: bool) !void {
if (optional) {
try self.writer.writeByte('?');
}
try self.writer.writeAll("fn(");
for (command_ptr.params) |param| {
try self.writeIdentifierWithCase(.snake, param.name);
try self.writer.writeAll(": ");
blk: {
if (param.param_type == .name) {
if (self.extractBitflagName(param.param_type.name)) |bitflag_name| {
try self.writeIdentifierFmt("{s}Flags{s}", .{
trimXrNamespace(bitflag_name.base_name),
@as([]const u8, if (bitflag_name.tag) |tag| tag else ""),
});
try self.writer.writeAll(".IntType");
break :blk;
} else if (self.isFlags(param.param_type.name)) {
try self.renderTypeInfo(param.param_type);
try self.writer.writeAll(".IntType");
break :blk;
}
}
try self.renderTypeInfo(param.param_type);
}
try self.writer.writeAll(", ");
}
try self.writer.writeAll(") callconv(openxr_call_conv)");
try self.renderTypeInfo(command_ptr.return_type.*);
}
fn renderPointer(self: *Self, pointer: reg.Pointer) !void {
const child_is_void = pointer.child.* == .name and mem.eql(u8, pointer.child.name, "void");
if (pointer.is_optional) {
try self.writer.writeByte('?');
}
const size = if (child_is_void) .one else pointer.size;
switch (size) {
.one => try self.writer.writeByte('*'),
.many, .other_field => try self.writer.writeAll("[*]"),
.zero_terminated => try self.writer.writeAll("[*:0]"),
}
if (pointer.is_const) {
try self.writer.writeAll("const ");
}
if (child_is_void) {
try self.writer.writeAll("c_void");
} else {
try self.renderTypeInfo(pointer.child.*);
}
}
fn renderArray(self: *Self, array: reg.Array) !void {
try self.writer.writeByte('[');
switch (array.size) {
.int => |size| try self.writer.print("{}", .{size}),
.alias => |alias| try self.renderName(alias),
}
try self.writer.writeByte(']');
try self.renderTypeInfo(array.child.*);
}
fn renderDecl(self: *Self, decl: reg.Declaration) !void {
switch (decl.decl_type) {
.container => |container| try self.renderContainer(decl.name, container),
.enumeration => |enumeration| try self.renderEnumeration(decl.name, enumeration),
.handle => |handle| try self.renderHandle(decl.name, handle),
.alias => |alias| try self.renderAlias(decl.name, alias),
.foreign => |foreign| try self.renderForeign(decl.name, foreign),
.typedef => |type_info| try self.renderTypedef(decl.name, type_info),
.external => try self.renderExternal(decl.name),
.command, .bitmask => {},
}
}
fn renderContainer(self: *Self, name: []const u8, container: reg.Container) !void {
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = ");
for (container.fields) |field| {
if (field.bits != null) {
try self.writer.writeAll("packed ");
break;
}
} else {
try self.writer.writeAll("extern ");
}
if (container.is_union) {
try self.writer.writeAll("union {");
} else {
try self.writer.writeAll("struct {");
}
for (container.fields) |field| {
try self.writeIdentifierWithCase(.snake, field.name);
try self.writer.writeAll(": ");
if (field.bits) |bits| {
try self.writer.print(" u{},", .{bits});
if (field.field_type != .name or builtin_types.get(field.field_type.name) == null) {
try self.writer.writeAll("// ");
try self.renderTypeInfo(field.field_type);
try self.writer.writeByte('\n');
}
} else {
try self.renderTypeInfo(field.field_type);
try self.renderContainerDefaultField(container, name, field);
try self.writer.writeAll(", ");
}
}
if (!container.is_union) {
try self.writer.writeAll(
\\ pub fn empty() @This() {
\\ var value: @This() = undefined;
);
for (container.fields) |field| {
if (mem.eql(u8, field.name, "next") or mem.eql(u8, field.name, "type")) {
try self.writer.writeAll("value.");
try self.writeIdentifierWithCase(.snake, field.name);
try self.renderContainerDefaultField(container, name, field);
try self.writer.writeAll(";\n");
}
}
try self.writer.writeAll(
\\ return value;
\\ }
);
}
try self.writer.writeAll("};\n");
}
fn renderContainerDefaultField(self: *Self, container: reg.Container, container_name: []const u8, field: reg.Container.Field) !void {
if (mem.eql(u8, field.name, "next")) {
try self.writer.writeAll(" = null");
} else if (mem.eql(u8, field.name, "type")) {
if (container.stype == null) {
return;
}
const stype = container.stype.?;
if (!mem.startsWith(u8, stype, "XR_TYPE_")) {
return error.InvalidRegistry;
}
try self.writer.writeAll(" = .");
try self.writeIdentifierWithCase(.snake, stype["XR_TYPE_".len..]);
} else if (mem.eql(u8, field.name, "w") and mem.eql(u8, container_name, "XrQuaternionf")) {
try self.writer.writeAll(" = 1");
} else if (initialized_types.get(container_name)) |value| {
try self.writer.writeAll(" = ");
try self.writer.writeAll(value);
}
}
fn renderEnumFieldName(self: *Self, name: []const u8, field_name: []const u8) !void {
try self.writeIdentifierWithCase(.snake, try self.extractEnumFieldName(name, field_name));
}
fn renderEnumerationValue(self: *Self, enum_name: []const u8, enumeration: reg.Enum, value: reg.Enum.Value) !void {
var current_value = value;
var maybe_alias_of: ?[]const u8 = null;
while (true) {
switch (current_value) {
.int => |int| try self.writer.print(" = {}, ", .{int}),
.bitpos => |pos| try self.writer.print(" = 1 << {}, ", .{pos}),
.bit_vector => |bv| try self.writer.print("= 0x{X}, ", .{bv}),
.alias => |alias| {
// Find the alias
current_value = for (enumeration.fields) |field| {
if (mem.eql(u8, field.name, alias.name)) {
maybe_alias_of = field.name;
break field.value;
}
} else return error.InvalidRegistry; // There is no alias
continue;
},
}
break;
}
if (maybe_alias_of) |alias_of| {
try self.writer.writeAll("// alias of ");
try self.renderEnumFieldName(enum_name, alias_of);
try self.writer.writeByte('\n');
}
}
fn renderEnumeration(self: *Self, name: []const u8, enumeration: reg.Enum) !void {
if (enumeration.is_bitmask) {
try self.renderBitmaskBits(name, enumeration);
return;
}
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = extern enum(i32) {");
for (enumeration.fields) |field| {
if (field.value == .alias and field.value.alias.is_compat_alias)
continue;
try self.renderEnumFieldName(name, field.name);
try self.renderEnumerationValue(name, enumeration, field.value);
}
try self.writer.writeAll("_,};\n");
}
fn renderBitmaskBits(self: *Self, name: []const u8, bits: reg.Enum) !void {
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = packed struct {");
if (bits.fields.len == 0) {
try self.writer.writeAll("_reserved_bits: Flags64 = 0,");
} else {
var flags_by_bitpos = [_]?[]const u8{null} ** 64;
for (bits.fields) |field| {
if (field.value == .bitpos) {
flags_by_bitpos[field.value.bitpos] = field.name;
}
}
for (flags_by_bitpos) |opt_flag_name, bitpos| {
if (opt_flag_name) |flag_name| {
try self.renderEnumFieldName(name, flag_name);
} else {
try self.writer.print("_reserved_bit_{}", .{bitpos});
}
try self.writer.writeAll(": bool ");
if (bitpos == 0) { // Force alignment to integer boundaries
try self.writer.writeAll("align(@alignOf(Flags64)) ");
}
try self.writer.writeAll("= false, ");
}
}
try self.writer.writeAll("pub usingnamespace FlagsMixin(");
try self.renderName(name);
try self.writer.writeAll(");\n};\n");
}
fn renderHandle(self: *Self, name: []const u8, handle: reg.Handle) !void {
const backing_type: []const u8 = if (handle.is_dispatchable) "usize" else "u64";
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.print(" = extern enum({s}) {{null_handle = 0, _}};\n", .{backing_type});
}
fn renderAlias(self: *Self, name: []const u8, alias: reg.Alias) !void {
if (alias.target == .other_command) {
return;
} else if (self.extractBitflagName(name) != null) {
// Don't make aliases of the bitflag names, as those are replaced by just the flags type
return;
}
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = ");
try self.renderName(alias.name);
try self.writer.writeAll(";\n");
}
fn renderExternal(self: *Self, name: []const u8) !void {
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = opaque {};\n");
}
fn renderForeign(self: *Self, name: []const u8, foreign: reg.Foreign) !void {
if (mem.eql(u8, foreign.depends, "openxr_platform_defines")) {
return; // Skip built-in types, they are handled differently
}
try self.writer.writeAll("pub const ");
try self.writeIdentifier(name);
try self.writer.print(" = if (@hasDecl(root, \"{s}\")) root.", .{name});
try self.writeIdentifier(name);
try self.writer.writeAll(" else ");
if (foreign_types.get(name)) |default| {
try self.writer.writeAll(default);
try self.writer.writeAll(";\n");
} else {
try self.writer.print("@compileError(\"Missing type definition of '{s}'\");\n", .{name});
}
}
fn renderTypedef(self: *Self, name: []const u8, type_info: reg.TypeInfo) !void {
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = ");
try self.renderTypeInfo(type_info);
try self.writer.writeAll(";\n");
}
fn renderCommandPtrName(self: *Self, name: []const u8) !void {
try self.writeIdentifierFmt("Pfn{s}", .{trimXrNamespace(name)});
}
fn renderCommandPtrs(self: *Self) !void {
for (self.registry.decls) |decl| {
if (decl.decl_type != .command) {
continue;
}
try self.writer.writeAll("pub const ");
try self.renderCommandPtrName(decl.name);
try self.writer.writeAll(" = ");
try self.renderCommandPtr(decl.decl_type.command, false);
try self.writer.writeAll(";\n");
}
}
fn renderExtensionInfo(self: *Self) !void {
try self.writer.writeAll(
\\pub const extension_info = struct {
\\ const Info = struct {
\\ name: [:0]const u8,
\\ version: u32,
\\ };
);
for (self.registry.extensions) |ext| {
try self.writer.writeAll("pub const ");
try self.writeIdentifierWithCase(.snake, trimXrNamespace(ext.name));
try self.writer.writeAll("= Info {\n");
try self.writer.print(".name = \"{s}\", .version = {},", .{ ext.name, ext.version });
try self.writer.writeAll("};\n");
}
try self.writer.writeAll("};\n");
}
fn renderWrappers(self: *Self) !void {
try self.renderWrappersOfDispatchType("BaseWrapper", .base);
try self.renderWrappersOfDispatchType("InstanceWrapper", .instance);
}
fn renderWrappersOfDispatchType(self: *Self, name: []const u8, dispatch_type: CommandDispatchType) !void {
try self.writer.print(
\\pub fn {s}(comptime Self: type) type {{
\\ return struct {{
\\
, .{name});
try self.renderWrapperLoader(dispatch_type);
for (self.registry.decls) |decl| {
if (decl.decl_type == .command) {
const command = decl.decl_type.command;
if (self.classifyCommandDispatch(decl.name, command) == dispatch_type) {
try self.renderWrapper(decl.name, decl.decl_type.command);
}
}
}
try self.writer.writeAll("};}\n");
}
fn renderWrapperLoader(self: *Self, dispatch_type: CommandDispatchType) !void {
const params = switch (dispatch_type) {
.base => "loader: anytype",
.instance => "instance: Instance, loader: anytype",
};
const loader_first_param = switch (dispatch_type) {
.base => ".null_handle, ",
.instance => "instance, ",
};
@setEvalBranchQuota(2000);
try self.writer.print(
\\pub fn load({s}) !Self {{
\\ var self: Self = undefined;
\\ inline for (std.meta.fields(Self)) |field| {{
\\ const name = @ptrCast([*:0]const u8, field.name ++ "\x00");
\\ const cmd_ptr = (try loader({s}name)) orelse return error.InvalidCommand;
\\ @field(self, field.name) = @ptrCast(field.field_type, cmd_ptr);
\\ }}
\\ return self;
\\}}
\\
, .{ params, loader_first_param });
}
fn derefName(name: []const u8) []const u8 {
var it = id_render.SegmentIterator.init(name);
return if (mem.eql(u8, it.next().?, "p"))
name[1..]
else
name;
}
fn renderWrapperPrototype(self: *Self, name: []const u8, command: reg.Command, returns: []const ReturnValue) !void {
try self.writer.writeAll("pub fn ");
try self.writeIdentifierWithCase(.camel, trimXrNamespace(name));
try self.writer.writeAll("(self: Self, ");
for (command.params) |param| {
switch (try self.classifyParam(param)) {
.in_pointer => {
// Remove one pointer level
try self.writeIdentifierWithCase(.snake, derefName(param.name));
try self.writer.writeAll(": ");
try self.renderTypeInfo(param.param_type.pointer.child.*);
},
.out_pointer => continue, // Return value
.in_out_pointer, .bitflags, // Special stuff handled in renderWrapperCall
.buffer_len, .mut_buffer_len, .other => {
try self.writeIdentifierWithCase(.snake, param.name);
try self.writer.writeAll(": ");
try self.renderTypeInfo(param.param_type);
},
}
try self.writer.writeAll(", ");
}
try self.writer.writeAll(") ");
if (command.return_type.* == .name and mem.eql(u8, command.return_type.name, "XrResult")) {
try self.renderErrorSet(command.error_codes);
try self.writer.writeByte('!');
}
if (returns.len == 1) {
try self.renderTypeInfo(returns[0].return_value_type);
} else if (returns.len > 1) {
try self.renderReturnStructName(name);
} else {
try self.writer.writeAll("void");
}
}
fn renderWrapperCall(self: *Self, name: []const u8, command: reg.Command, returns: []const ReturnValue) !void {
try self.writer.writeAll("self.");
try self.writeIdentifier(name);
try self.writer.writeAll("(");
for (command.params) |param| {
switch (try self.classifyParam(param)) {
.in_pointer => {
try self.writer.writeByte('&');
try self.writeIdentifierWithCase(.snake, derefName(param.name));
},
.out_pointer => {
try self.writer.writeByte('&');
if (returns.len > 1) {
try self.writer.writeAll("return_values.");
}
try self.writeIdentifierWithCase(.snake, derefName(param.name));
},
.bitflags => {
try self.writeIdentifierWithCase(.snake, param.name);
try self.writer.writeAll(".toInt()");
},
.in_out_pointer, .buffer_len, .mut_buffer_len, .other => {
try self.writeIdentifierWithCase(.snake, param.name);
},
}
try self.writer.writeAll(", ");
}
try self.writer.writeAll(")");
}
fn extractReturns(self: *Self, command: reg.Command) ![]const ReturnValue {
var returns = std.ArrayList(ReturnValue).init(self.allocator);
if (command.return_type.* == .name) {
const return_name = command.return_type.name;
if (!mem.eql(u8, return_name, "void") and !mem.eql(u8, return_name, "XrResult")) {
try returns.append(.{
.name = "return_value",
.return_value_type = command.return_type.*,
.origin = .inner_return_value,
});
}
}
if (command.success_codes.len > 1) {
if (command.return_type.* != .name or !mem.eql(u8, command.return_type.name, "XrResult")) {
return error.InvalidRegistry;
}
try returns.append(.{
.name = "result",
.return_value_type = command.return_type.*,
.origin = .inner_return_value,
});
} else if (command.success_codes.len == 1 and !mem.eql(u8, command.success_codes[0], "XR_SUCCESS")) {
return error.InvalidRegistry;
}
for (command.params) |param| {
if ((try self.classifyParam(param)) == .out_pointer) {
try returns.append(.{
.name = derefName(param.name),
.return_value_type = param.param_type.pointer.child.*,
.origin = .parameter,
});
}
}
return returns.toOwnedSlice();
}
fn renderReturnStructName(self: *Self, command_name: []const u8) !void {
try self.writeIdentifierFmt("{s}Result", .{trimXrNamespace(command_name)});
}
fn renderReturnStruct(self: *Self, command_name: []const u8, returns: []const ReturnValue) !void {
try self.writer.writeAll("pub const ");
try self.renderReturnStructName(command_name);
try self.writer.writeAll(" = struct {\n");
for (returns) |ret| {
try self.writeIdentifierWithCase(.snake, ret.name);
try self.writer.writeAll(": ");
try self.renderTypeInfo(ret.return_value_type);
try self.writer.writeAll(", ");
}
try self.writer.writeAll("};\n");
}
fn renderWrapper(self: *Self, name: []const u8, command: reg.Command) !void {
const returns_xr_result = command.return_type.* == .name and mem.eql(u8, command.return_type.name, "XrResult");
const returns_void = command.return_type.* == .name and mem.eql(u8, command.return_type.name, "void");
const returns = try self.extractReturns(command);
if (returns.len > 1) {
try self.renderReturnStruct(name, returns);
}
try self.renderWrapperPrototype(name, command, returns);
if (returns.len == 1 and returns[0].origin == .inner_return_value) {
try self.writer.writeAll("{\n\n");
if (returns_xr_result) {
try self.writer.writeAll("const result = ");
try self.renderWrapperCall(name, command, returns);
try self.writer.writeAll(";\n");
try self.renderErrorSwitch("result", command);
try self.writer.writeAll("return result;\n");
} else {
try self.writer.writeAll("return ");
try self.renderWrapperCall(name, command, returns);
try self.writer.writeAll(";\n");
}
try self.writer.writeAll("\n}\n");
return;
}
try self.writer.writeAll("{\n");
if (returns.len == 1) {
try self.writer.writeAll("var ");
try self.writeIdentifierWithCase(.snake, returns[0].name);
try self.writer.writeAll(": ");
try self.renderTypeInfo(returns[0].return_value_type);
try self.writer.writeAll(" = undefined;\n");
} else if (returns.len > 1) {
try self.writer.writeAll("var return_values: ");
try self.renderReturnStructName(name);
try self.writer.writeAll(" = undefined;\n");
}
if (returns_xr_result) {
try self.writer.writeAll("const result = ");
try self.renderWrapperCall(name, command, returns);
try self.writer.writeAll(";\n");
try self.renderErrorSwitch("result", command);
if (command.success_codes.len > 1) {
try self.writer.writeAll("return_values.result = result;\n");
}
} else {
if (!returns_void) {
try self.writer.writeAll("return_values.return_value = ");
}
try self.renderWrapperCall(name, command, returns);
try self.writer.writeAll(";\n");
}
if (returns.len == 1) {
try self.writer.writeAll("return ");
try self.writeIdentifierWithCase(.snake, returns[0].name);
try self.writer.writeAll(";\n");
} else if (returns.len > 1) {
try self.writer.writeAll("return return_values;\n");
}
try self.writer.writeAll("}\n");
}
fn renderErrorSwitch(self: *Self, result_var: []const u8, command: reg.Command) !void {
try self.writer.writeAll("switch (");
try self.writeIdentifier(result_var);
try self.writer.writeAll(") {\n");
for (command.success_codes) |success| {
try self.writer.writeByte('.');
try self.renderEnumFieldName("XrResult", success);
try self.writer.writeAll(" => {},");
}
for (command.error_codes) |err| {
try self.writer.writeByte('.');
try self.renderEnumFieldName("XrResult", err);
try self.writer.writeAll(" => return error.");
try self.renderResultAsErrorName(err);
try self.writer.writeAll(", ");
}
try self.writer.writeAll("else => return error.Unknown,}\n");
}
fn renderErrorSet(self: *Self, errors: []const []const u8) !void {
try self.writer.writeAll("error{");
for (errors) |name| {
try self.renderResultAsErrorName(name);
try self.writer.writeAll(", ");
}
try self.writer.writeAll("Unknown, }");
}
fn renderResultAsErrorName(self: *Self, name: []const u8) !void {
const error_prefix = "XR_ERROR_";
if (mem.startsWith(u8, name, error_prefix)) {
try self.writeIdentifierWithCase(.title, name[error_prefix.len..]);
} else {
// Apparently some commands (XrAcquireProfilingLockInfoKHR) return
// success codes as error...
try self.writeIdentifierWithCase(.title, trimXrNamespace(name));
}
}
};
}
pub fn render(writer: anytype, allocator: *Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !void {
var renderer = try Renderer(@TypeOf(writer)).init(writer, allocator, registry, id_renderer);
defer renderer.deinit();
try renderer.render();
} | generator/openxr/render.zig |
pub fn Register(comptime R: type) type {
return RegisterRW(R, R);
}
pub fn RegisterRW(comptime Read: type, comptime Write: type) type {
return struct {
raw_ptr: *volatile u32,
const Self = @This();
pub fn init(address: usize) Self {
return Self{ .raw_ptr = @intToPtr(*volatile u32, address) };
}
pub fn initRange(address: usize, comptime dim_increment: usize, comptime num_registers: usize) [num_registers]Self {
var registers: [num_registers]Self = undefined;
var i: usize = 0;
while (i < num_registers) : (i += 1) {
registers[i] = Self.init(address + (i * dim_increment));
}
return registers;
}
pub fn read(self: Self) Read {
return @bitCast(Read, self.raw_ptr.*);
}
pub fn write(self: Self, value: Write) void {
self.raw_ptr.* = @bitCast(u32, value);
}
pub fn modify(self: Self, new_value: anytype) void {
if (Read != Write) {
@compileError("Can't modify because read and write types for this register aren't the same.");
}
var old_value = self.read();
const info = @typeInfo(@TypeOf(new_value));
inline for (info.Struct.fields) |field| {
@field(old_value, field.name) = @field(new_value, field.name);
}
self.write(old_value);
}
pub fn read_raw(self: Self) u32 {
return self.raw_ptr.*;
}
pub fn write_raw(self: Self, value: u32) void {
self.raw_ptr.* = value;
}
pub fn default_read_value(self: Self) Read {
return Read{};
}
pub fn default_write_value(self: Self) Write {
return Write{};
}
};
}
pub fn RepeatedFields(comptime num_fields: usize, comptime field_name: []const u8, comptime T: type) type {
var info = @typeInfo(packed struct { f: T });
var fields: [num_fields]std.builtin.TypeInfo.StructField = undefined;
var field_ix: usize = 0;
while (field_ix < num_fields) : (field_ix += 1) {
var field = info.Struct.fields[0];
// awkward workaround for lack of comptime allocator
@setEvalBranchQuota(100000);
var field_ix_buffer: [field_name.len + 16]u8 = undefined;
var stream = std.io.FixedBufferStream([]u8){ .buffer = &field_ix_buffer, .pos = 0 };
std.fmt.format(stream.writer(), "{}{}", .{ field_name, field_ix }) catch unreachable;
field.name = stream.getWritten();
field.default_value = T.default_value;
fields[field_ix] = field;
}
// TODO this might not be safe to set
info.Struct.is_tuple = true;
info.Struct.fields = &fields;
return @Type(info);
}
///cyclic redundancy check calculation
///unit
pub const crc = struct {
//////////////////////////
///DR
const dr_val = packed struct {
///DR [0:31]
///Data register bits
dr: u32 = 4294967295,
};
///Data register
pub const dr = Register(dr_val).init(0x40023000 + 0x0);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR [0:7]
///General-purpose 8-bit data register
///bits
idr: u8 = 0,
_unused8: u24 = 0,
};
///Independent data register
pub const idr = Register(idr_val).init(0x40023000 + 0x4);
//////////////////////////
///CR
const cr_val = packed struct {
///RESET [0:0]
///reset bit
reset: u1 = 0,
_unused1: u2 = 0,
///POLYSIZE [3:4]
///Polynomial size
polysize: packed enum(u2) {
///32-bit polynomial
polysize32 = 0,
///16-bit polynomial
polysize16 = 1,
///8-bit polynomial
polysize8 = 2,
///7-bit polynomial
polysize7 = 3,
} = .polysize32,
///REV_IN [5:6]
///Reverse input data
rev_in: packed enum(u2) {
///Bit order not affected
normal = 0,
///Bit reversal done by byte
byte = 1,
///Bit reversal done by half-word
half_word = 2,
///Bit reversal done by word
word = 3,
} = .normal,
///REV_OUT [7:7]
///Reverse output data
rev_out: packed enum(u1) {
///Bit order not affected
normal = 0,
///Bit reversed output
reversed = 1,
} = .normal,
_unused8: u24 = 0,
};
///Control register
pub const cr = Register(cr_val).init(0x40023000 + 0x8);
//////////////////////////
///INIT
const init_val = packed struct {
///INIT [0:31]
///Programmable initial CRC
///value
init: u32 = 4294967295,
};
///Initial CRC value
pub const init = Register(init_val).init(0x40023000 + 0x10);
//////////////////////////
///DR8
const dr8_val = packed struct {
///DR8 [0:7]
///Data register bits
dr8: u8 = 85,
_unused8: u24 = 0,
};
///Data register - byte sized
pub const dr8 = Register(dr8_val).init(0x40023000 + 0);
//////////////////////////
///DR16
const dr16_val = packed struct {
///DR16 [0:15]
///Data register bits
dr16: u16 = 21813,
_unused16: u16 = 0,
};
///Data register - half-word sized
pub const dr16 = Register(dr16_val).init(0x40023000 + 0);
};
///General-purpose I/Os
pub const gpiof = struct {
//////////////////////////
///MODER
const moder_val = packed struct {
///MODER0 [0:1]
///Port x configuration bits (y =
///0..15)
moder0: u2 = 0,
///MODER1 [2:3]
///Port x configuration bits (y =
///0..15)
moder1: u2 = 0,
///MODER2 [4:5]
///Port x configuration bits (y =
///0..15)
moder2: u2 = 0,
///MODER3 [6:7]
///Port x configuration bits (y =
///0..15)
moder3: u2 = 0,
///MODER4 [8:9]
///Port x configuration bits (y =
///0..15)
moder4: u2 = 0,
///MODER5 [10:11]
///Port x configuration bits (y =
///0..15)
moder5: u2 = 0,
///MODER6 [12:13]
///Port x configuration bits (y =
///0..15)
moder6: u2 = 0,
///MODER7 [14:15]
///Port x configuration bits (y =
///0..15)
moder7: u2 = 0,
///MODER8 [16:17]
///Port x configuration bits (y =
///0..15)
moder8: u2 = 0,
///MODER9 [18:19]
///Port x configuration bits (y =
///0..15)
moder9: u2 = 0,
///MODER10 [20:21]
///Port x configuration bits (y =
///0..15)
moder10: u2 = 0,
///MODER11 [22:23]
///Port x configuration bits (y =
///0..15)
moder11: u2 = 0,
///MODER12 [24:25]
///Port x configuration bits (y =
///0..15)
moder12: u2 = 0,
///MODER13 [26:27]
///Port x configuration bits (y =
///0..15)
moder13: u2 = 0,
///MODER14 [28:29]
///Port x configuration bits (y =
///0..15)
moder14: u2 = 0,
///MODER15 [30:31]
///Port x configuration bits (y =
///0..15)
moder15: packed enum(u2) {
///Input mode (reset state)
input = 0,
///General purpose output mode
output = 1,
///Alternate function mode
alternate = 2,
///Analog mode
analog = 3,
} = .input,
};
///GPIO port mode register
pub const moder = Register(moder_val).init(0x48001400 + 0x0);
//////////////////////////
///OTYPER
const otyper_val = packed struct {
///OT0 [0:0]
///Port x configuration bit 0
ot0: u1 = 0,
///OT1 [1:1]
///Port x configuration bit 1
ot1: u1 = 0,
///OT2 [2:2]
///Port x configuration bit 2
ot2: u1 = 0,
///OT3 [3:3]
///Port x configuration bit 3
ot3: u1 = 0,
///OT4 [4:4]
///Port x configuration bit 4
ot4: u1 = 0,
///OT5 [5:5]
///Port x configuration bit 5
ot5: u1 = 0,
///OT6 [6:6]
///Port x configuration bit 6
ot6: u1 = 0,
///OT7 [7:7]
///Port x configuration bit 7
ot7: u1 = 0,
///OT8 [8:8]
///Port x configuration bit 8
ot8: u1 = 0,
///OT9 [9:9]
///Port x configuration bit 9
ot9: u1 = 0,
///OT10 [10:10]
///Port x configuration bit
///10
ot10: u1 = 0,
///OT11 [11:11]
///Port x configuration bit
///11
ot11: u1 = 0,
///OT12 [12:12]
///Port x configuration bit
///12
ot12: u1 = 0,
///OT13 [13:13]
///Port x configuration bit
///13
ot13: u1 = 0,
///OT14 [14:14]
///Port x configuration bit
///14
ot14: u1 = 0,
///OT15 [15:15]
///Port x configuration bit
///15
ot15: packed enum(u1) {
///Output push-pull (reset state)
push_pull = 0,
///Output open-drain
open_drain = 1,
} = .push_pull,
_unused16: u16 = 0,
};
///GPIO port output type register
pub const otyper = Register(otyper_val).init(0x48001400 + 0x4);
//////////////////////////
///OSPEEDR
const ospeedr_val = packed struct {
///OSPEEDR0 [0:1]
///Port x configuration bits (y =
///0..15)
ospeedr0: u2 = 0,
///OSPEEDR1 [2:3]
///Port x configuration bits (y =
///0..15)
ospeedr1: u2 = 0,
///OSPEEDR2 [4:5]
///Port x configuration bits (y =
///0..15)
ospeedr2: u2 = 0,
///OSPEEDR3 [6:7]
///Port x configuration bits (y =
///0..15)
ospeedr3: u2 = 0,
///OSPEEDR4 [8:9]
///Port x configuration bits (y =
///0..15)
ospeedr4: u2 = 0,
///OSPEEDR5 [10:11]
///Port x configuration bits (y =
///0..15)
ospeedr5: u2 = 0,
///OSPEEDR6 [12:13]
///Port x configuration bits (y =
///0..15)
ospeedr6: u2 = 0,
///OSPEEDR7 [14:15]
///Port x configuration bits (y =
///0..15)
ospeedr7: u2 = 0,
///OSPEEDR8 [16:17]
///Port x configuration bits (y =
///0..15)
ospeedr8: u2 = 0,
///OSPEEDR9 [18:19]
///Port x configuration bits (y =
///0..15)
ospeedr9: u2 = 0,
///OSPEEDR10 [20:21]
///Port x configuration bits (y =
///0..15)
ospeedr10: u2 = 0,
///OSPEEDR11 [22:23]
///Port x configuration bits (y =
///0..15)
ospeedr11: u2 = 0,
///OSPEEDR12 [24:25]
///Port x configuration bits (y =
///0..15)
ospeedr12: u2 = 0,
///OSPEEDR13 [26:27]
///Port x configuration bits (y =
///0..15)
ospeedr13: u2 = 0,
///OSPEEDR14 [28:29]
///Port x configuration bits (y =
///0..15)
ospeedr14: u2 = 0,
///OSPEEDR15 [30:31]
///Port x configuration bits (y =
///0..15)
ospeedr15: packed enum(u2) {
///Low speed
low_speed = 0,
///Medium speed
medium_speed = 1,
///High speed
high_speed = 2,
///Very high speed
very_high_speed = 3,
} = .low_speed,
};
///GPIO port output speed
///register
pub const ospeedr = Register(ospeedr_val).init(0x48001400 + 0x8);
//////////////////////////
///PUPDR
const pupdr_val = packed struct {
///PUPDR0 [0:1]
///Port x configuration bits (y =
///0..15)
pupdr0: u2 = 0,
///PUPDR1 [2:3]
///Port x configuration bits (y =
///0..15)
pupdr1: u2 = 0,
///PUPDR2 [4:5]
///Port x configuration bits (y =
///0..15)
pupdr2: u2 = 0,
///PUPDR3 [6:7]
///Port x configuration bits (y =
///0..15)
pupdr3: u2 = 0,
///PUPDR4 [8:9]
///Port x configuration bits (y =
///0..15)
pupdr4: u2 = 0,
///PUPDR5 [10:11]
///Port x configuration bits (y =
///0..15)
pupdr5: u2 = 0,
///PUPDR6 [12:13]
///Port x configuration bits (y =
///0..15)
pupdr6: u2 = 0,
///PUPDR7 [14:15]
///Port x configuration bits (y =
///0..15)
pupdr7: u2 = 0,
///PUPDR8 [16:17]
///Port x configuration bits (y =
///0..15)
pupdr8: u2 = 0,
///PUPDR9 [18:19]
///Port x configuration bits (y =
///0..15)
pupdr9: u2 = 0,
///PUPDR10 [20:21]
///Port x configuration bits (y =
///0..15)
pupdr10: u2 = 0,
///PUPDR11 [22:23]
///Port x configuration bits (y =
///0..15)
pupdr11: u2 = 0,
///PUPDR12 [24:25]
///Port x configuration bits (y =
///0..15)
pupdr12: u2 = 0,
///PUPDR13 [26:27]
///Port x configuration bits (y =
///0..15)
pupdr13: u2 = 0,
///PUPDR14 [28:29]
///Port x configuration bits (y =
///0..15)
pupdr14: u2 = 0,
///PUPDR15 [30:31]
///Port x configuration bits (y =
///0..15)
pupdr15: packed enum(u2) {
///No pull-up, pull-down
floating = 0,
///Pull-up
pull_up = 1,
///Pull-down
pull_down = 2,
} = .floating,
};
///GPIO port pull-up/pull-down
///register
pub const pupdr = Register(pupdr_val).init(0x48001400 + 0xC);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR0 [0:0]
///Port input data (y =
///0..15)
idr0: u1 = 0,
///IDR1 [1:1]
///Port input data (y =
///0..15)
idr1: u1 = 0,
///IDR2 [2:2]
///Port input data (y =
///0..15)
idr2: u1 = 0,
///IDR3 [3:3]
///Port input data (y =
///0..15)
idr3: u1 = 0,
///IDR4 [4:4]
///Port input data (y =
///0..15)
idr4: u1 = 0,
///IDR5 [5:5]
///Port input data (y =
///0..15)
idr5: u1 = 0,
///IDR6 [6:6]
///Port input data (y =
///0..15)
idr6: u1 = 0,
///IDR7 [7:7]
///Port input data (y =
///0..15)
idr7: u1 = 0,
///IDR8 [8:8]
///Port input data (y =
///0..15)
idr8: u1 = 0,
///IDR9 [9:9]
///Port input data (y =
///0..15)
idr9: u1 = 0,
///IDR10 [10:10]
///Port input data (y =
///0..15)
idr10: u1 = 0,
///IDR11 [11:11]
///Port input data (y =
///0..15)
idr11: u1 = 0,
///IDR12 [12:12]
///Port input data (y =
///0..15)
idr12: u1 = 0,
///IDR13 [13:13]
///Port input data (y =
///0..15)
idr13: u1 = 0,
///IDR14 [14:14]
///Port input data (y =
///0..15)
idr14: u1 = 0,
///IDR15 [15:15]
///Port input data (y =
///0..15)
idr15: packed enum(u1) {
///Input is logic high
high = 1,
///Input is logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port input data register
pub const idr = RegisterRW(idr_val, void).init(0x48001400 + 0x10);
//////////////////////////
///ODR
const odr_val = packed struct {
///ODR0 [0:0]
///Port output data (y =
///0..15)
odr0: u1 = 0,
///ODR1 [1:1]
///Port output data (y =
///0..15)
odr1: u1 = 0,
///ODR2 [2:2]
///Port output data (y =
///0..15)
odr2: u1 = 0,
///ODR3 [3:3]
///Port output data (y =
///0..15)
odr3: u1 = 0,
///ODR4 [4:4]
///Port output data (y =
///0..15)
odr4: u1 = 0,
///ODR5 [5:5]
///Port output data (y =
///0..15)
odr5: u1 = 0,
///ODR6 [6:6]
///Port output data (y =
///0..15)
odr6: u1 = 0,
///ODR7 [7:7]
///Port output data (y =
///0..15)
odr7: u1 = 0,
///ODR8 [8:8]
///Port output data (y =
///0..15)
odr8: u1 = 0,
///ODR9 [9:9]
///Port output data (y =
///0..15)
odr9: u1 = 0,
///ODR10 [10:10]
///Port output data (y =
///0..15)
odr10: u1 = 0,
///ODR11 [11:11]
///Port output data (y =
///0..15)
odr11: u1 = 0,
///ODR12 [12:12]
///Port output data (y =
///0..15)
odr12: u1 = 0,
///ODR13 [13:13]
///Port output data (y =
///0..15)
odr13: u1 = 0,
///ODR14 [14:14]
///Port output data (y =
///0..15)
odr14: u1 = 0,
///ODR15 [15:15]
///Port output data (y =
///0..15)
odr15: packed enum(u1) {
///Set output to logic high
high = 1,
///Set output to logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port output data register
pub const odr = Register(odr_val).init(0x48001400 + 0x14);
//////////////////////////
///BSRR
const bsrr_val = packed struct {
///BS0 [0:0]
///Port x set bit y (y=
///0..15)
bs0: u1 = 0,
///BS1 [1:1]
///Port x set bit y (y=
///0..15)
bs1: u1 = 0,
///BS2 [2:2]
///Port x set bit y (y=
///0..15)
bs2: u1 = 0,
///BS3 [3:3]
///Port x set bit y (y=
///0..15)
bs3: u1 = 0,
///BS4 [4:4]
///Port x set bit y (y=
///0..15)
bs4: u1 = 0,
///BS5 [5:5]
///Port x set bit y (y=
///0..15)
bs5: u1 = 0,
///BS6 [6:6]
///Port x set bit y (y=
///0..15)
bs6: u1 = 0,
///BS7 [7:7]
///Port x set bit y (y=
///0..15)
bs7: u1 = 0,
///BS8 [8:8]
///Port x set bit y (y=
///0..15)
bs8: u1 = 0,
///BS9 [9:9]
///Port x set bit y (y=
///0..15)
bs9: u1 = 0,
///BS10 [10:10]
///Port x set bit y (y=
///0..15)
bs10: u1 = 0,
///BS11 [11:11]
///Port x set bit y (y=
///0..15)
bs11: u1 = 0,
///BS12 [12:12]
///Port x set bit y (y=
///0..15)
bs12: u1 = 0,
///BS13 [13:13]
///Port x set bit y (y=
///0..15)
bs13: u1 = 0,
///BS14 [14:14]
///Port x set bit y (y=
///0..15)
bs14: u1 = 0,
///BS15 [15:15]
///Port x set bit y (y=
///0..15)
bs15: u1 = 0,
///BR0 [16:16]
///Port x set bit y (y=
///0..15)
br0: u1 = 0,
///BR1 [17:17]
///Port x reset bit y (y =
///0..15)
br1: u1 = 0,
///BR2 [18:18]
///Port x reset bit y (y =
///0..15)
br2: u1 = 0,
///BR3 [19:19]
///Port x reset bit y (y =
///0..15)
br3: u1 = 0,
///BR4 [20:20]
///Port x reset bit y (y =
///0..15)
br4: u1 = 0,
///BR5 [21:21]
///Port x reset bit y (y =
///0..15)
br5: u1 = 0,
///BR6 [22:22]
///Port x reset bit y (y =
///0..15)
br6: u1 = 0,
///BR7 [23:23]
///Port x reset bit y (y =
///0..15)
br7: u1 = 0,
///BR8 [24:24]
///Port x reset bit y (y =
///0..15)
br8: u1 = 0,
///BR9 [25:25]
///Port x reset bit y (y =
///0..15)
br9: u1 = 0,
///BR10 [26:26]
///Port x reset bit y (y =
///0..15)
br10: u1 = 0,
///BR11 [27:27]
///Port x reset bit y (y =
///0..15)
br11: u1 = 0,
///BR12 [28:28]
///Port x reset bit y (y =
///0..15)
br12: u1 = 0,
///BR13 [29:29]
///Port x reset bit y (y =
///0..15)
br13: u1 = 0,
///BR14 [30:30]
///Port x reset bit y (y =
///0..15)
br14: u1 = 0,
///BR15 [31:31]
///Port x reset bit y (y =
///0..15)
br15: u1 = 0,
};
///GPIO port bit set/reset
///register
pub const bsrr = RegisterRW(void, bsrr_val).init(0x48001400 + 0x18);
//////////////////////////
///LCKR
const lckr_val = packed struct {
///LCK0 [0:0]
///Port x lock bit y (y=
///0..15)
lck0: u1 = 0,
///LCK1 [1:1]
///Port x lock bit y (y=
///0..15)
lck1: u1 = 0,
///LCK2 [2:2]
///Port x lock bit y (y=
///0..15)
lck2: u1 = 0,
///LCK3 [3:3]
///Port x lock bit y (y=
///0..15)
lck3: u1 = 0,
///LCK4 [4:4]
///Port x lock bit y (y=
///0..15)
lck4: u1 = 0,
///LCK5 [5:5]
///Port x lock bit y (y=
///0..15)
lck5: u1 = 0,
///LCK6 [6:6]
///Port x lock bit y (y=
///0..15)
lck6: u1 = 0,
///LCK7 [7:7]
///Port x lock bit y (y=
///0..15)
lck7: u1 = 0,
///LCK8 [8:8]
///Port x lock bit y (y=
///0..15)
lck8: u1 = 0,
///LCK9 [9:9]
///Port x lock bit y (y=
///0..15)
lck9: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCK10 [10:10]
///Port x lock bit y (y=
///0..15)
lck10: u1 = 0,
///LCK11 [11:11]
///Port x lock bit y (y=
///0..15)
lck11: u1 = 0,
///LCK12 [12:12]
///Port x lock bit y (y=
///0..15)
lck12: u1 = 0,
///LCK13 [13:13]
///Port x lock bit y (y=
///0..15)
lck13: u1 = 0,
///LCK14 [14:14]
///Port x lock bit y (y=
///0..15)
lck14: u1 = 0,
///LCK15 [15:15]
///Port x lock bit y (y=
///0..15)
lck15: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCKK [16:16]
///Port x lock bit y
lckk: packed enum(u1) {
///Port configuration lock key not active
not_active = 0,
///Port configuration lock key active
active = 1,
} = .not_active,
_unused17: u15 = 0,
};
///GPIO port configuration lock
///register
pub const lckr = Register(lckr_val).init(0x48001400 + 0x1C);
//////////////////////////
///AFRL
const afrl_val = packed struct {
///AFRL0 [0:3]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl0: u4 = 0,
///AFRL1 [4:7]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl1: u4 = 0,
///AFRL2 [8:11]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl2: u4 = 0,
///AFRL3 [12:15]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl3: u4 = 0,
///AFRL4 [16:19]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl4: u4 = 0,
///AFRL5 [20:23]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl5: u4 = 0,
///AFRL6 [24:27]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl6: u4 = 0,
///AFRL7 [28:31]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl7: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function low
///register
pub const afrl = Register(afrl_val).init(0x48001400 + 0x20);
//////////////////////////
///AFRH
const afrh_val = packed struct {
///AFRH8 [0:3]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh8: u4 = 0,
///AFRH9 [4:7]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh9: u4 = 0,
///AFRH10 [8:11]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh10: u4 = 0,
///AFRH11 [12:15]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh11: u4 = 0,
///AFRH12 [16:19]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh12: u4 = 0,
///AFRH13 [20:23]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh13: u4 = 0,
///AFRH14 [24:27]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh14: u4 = 0,
///AFRH15 [28:31]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh15: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function high
///register
pub const afrh = Register(afrh_val).init(0x48001400 + 0x24);
//////////////////////////
///BRR
const brr_val = packed struct {
///BR0 [0:0]
///Port x Reset bit y
br0: u1 = 0,
///BR1 [1:1]
///Port x Reset bit y
br1: u1 = 0,
///BR2 [2:2]
///Port x Reset bit y
br2: u1 = 0,
///BR3 [3:3]
///Port x Reset bit y
br3: u1 = 0,
///BR4 [4:4]
///Port x Reset bit y
br4: u1 = 0,
///BR5 [5:5]
///Port x Reset bit y
br5: u1 = 0,
///BR6 [6:6]
///Port x Reset bit y
br6: u1 = 0,
///BR7 [7:7]
///Port x Reset bit y
br7: u1 = 0,
///BR8 [8:8]
///Port x Reset bit y
br8: u1 = 0,
///BR9 [9:9]
///Port x Reset bit y
br9: u1 = 0,
///BR10 [10:10]
///Port x Reset bit y
br10: u1 = 0,
///BR11 [11:11]
///Port x Reset bit y
br11: u1 = 0,
///BR12 [12:12]
///Port x Reset bit y
br12: u1 = 0,
///BR13 [13:13]
///Port x Reset bit y
br13: u1 = 0,
///BR14 [14:14]
///Port x Reset bit y
br14: u1 = 0,
///BR15 [15:15]
///Port x Reset bit y
br15: u1 = 0,
_unused16: u16 = 0,
};
///Port bit reset register
pub const brr = RegisterRW(void, brr_val).init(0x48001400 + 0x28);
};
///General-purpose I/Os
pub const gpiod = struct {
//////////////////////////
///MODER
const moder_val = packed struct {
///MODER0 [0:1]
///Port x configuration bits (y =
///0..15)
moder0: u2 = 0,
///MODER1 [2:3]
///Port x configuration bits (y =
///0..15)
moder1: u2 = 0,
///MODER2 [4:5]
///Port x configuration bits (y =
///0..15)
moder2: u2 = 0,
///MODER3 [6:7]
///Port x configuration bits (y =
///0..15)
moder3: u2 = 0,
///MODER4 [8:9]
///Port x configuration bits (y =
///0..15)
moder4: u2 = 0,
///MODER5 [10:11]
///Port x configuration bits (y =
///0..15)
moder5: u2 = 0,
///MODER6 [12:13]
///Port x configuration bits (y =
///0..15)
moder6: u2 = 0,
///MODER7 [14:15]
///Port x configuration bits (y =
///0..15)
moder7: u2 = 0,
///MODER8 [16:17]
///Port x configuration bits (y =
///0..15)
moder8: u2 = 0,
///MODER9 [18:19]
///Port x configuration bits (y =
///0..15)
moder9: u2 = 0,
///MODER10 [20:21]
///Port x configuration bits (y =
///0..15)
moder10: u2 = 0,
///MODER11 [22:23]
///Port x configuration bits (y =
///0..15)
moder11: u2 = 0,
///MODER12 [24:25]
///Port x configuration bits (y =
///0..15)
moder12: u2 = 0,
///MODER13 [26:27]
///Port x configuration bits (y =
///0..15)
moder13: u2 = 0,
///MODER14 [28:29]
///Port x configuration bits (y =
///0..15)
moder14: u2 = 0,
///MODER15 [30:31]
///Port x configuration bits (y =
///0..15)
moder15: packed enum(u2) {
///Input mode (reset state)
input = 0,
///General purpose output mode
output = 1,
///Alternate function mode
alternate = 2,
///Analog mode
analog = 3,
} = .input,
};
///GPIO port mode register
pub const moder = Register(moder_val).init(0x48000C00 + 0x0);
//////////////////////////
///OTYPER
const otyper_val = packed struct {
///OT0 [0:0]
///Port x configuration bit 0
ot0: u1 = 0,
///OT1 [1:1]
///Port x configuration bit 1
ot1: u1 = 0,
///OT2 [2:2]
///Port x configuration bit 2
ot2: u1 = 0,
///OT3 [3:3]
///Port x configuration bit 3
ot3: u1 = 0,
///OT4 [4:4]
///Port x configuration bit 4
ot4: u1 = 0,
///OT5 [5:5]
///Port x configuration bit 5
ot5: u1 = 0,
///OT6 [6:6]
///Port x configuration bit 6
ot6: u1 = 0,
///OT7 [7:7]
///Port x configuration bit 7
ot7: u1 = 0,
///OT8 [8:8]
///Port x configuration bit 8
ot8: u1 = 0,
///OT9 [9:9]
///Port x configuration bit 9
ot9: u1 = 0,
///OT10 [10:10]
///Port x configuration bit
///10
ot10: u1 = 0,
///OT11 [11:11]
///Port x configuration bit
///11
ot11: u1 = 0,
///OT12 [12:12]
///Port x configuration bit
///12
ot12: u1 = 0,
///OT13 [13:13]
///Port x configuration bit
///13
ot13: u1 = 0,
///OT14 [14:14]
///Port x configuration bit
///14
ot14: u1 = 0,
///OT15 [15:15]
///Port x configuration bit
///15
ot15: packed enum(u1) {
///Output push-pull (reset state)
push_pull = 0,
///Output open-drain
open_drain = 1,
} = .push_pull,
_unused16: u16 = 0,
};
///GPIO port output type register
pub const otyper = Register(otyper_val).init(0x48000C00 + 0x4);
//////////////////////////
///OSPEEDR
const ospeedr_val = packed struct {
///OSPEEDR0 [0:1]
///Port x configuration bits (y =
///0..15)
ospeedr0: u2 = 0,
///OSPEEDR1 [2:3]
///Port x configuration bits (y =
///0..15)
ospeedr1: u2 = 0,
///OSPEEDR2 [4:5]
///Port x configuration bits (y =
///0..15)
ospeedr2: u2 = 0,
///OSPEEDR3 [6:7]
///Port x configuration bits (y =
///0..15)
ospeedr3: u2 = 0,
///OSPEEDR4 [8:9]
///Port x configuration bits (y =
///0..15)
ospeedr4: u2 = 0,
///OSPEEDR5 [10:11]
///Port x configuration bits (y =
///0..15)
ospeedr5: u2 = 0,
///OSPEEDR6 [12:13]
///Port x configuration bits (y =
///0..15)
ospeedr6: u2 = 0,
///OSPEEDR7 [14:15]
///Port x configuration bits (y =
///0..15)
ospeedr7: u2 = 0,
///OSPEEDR8 [16:17]
///Port x configuration bits (y =
///0..15)
ospeedr8: u2 = 0,
///OSPEEDR9 [18:19]
///Port x configuration bits (y =
///0..15)
ospeedr9: u2 = 0,
///OSPEEDR10 [20:21]
///Port x configuration bits (y =
///0..15)
ospeedr10: u2 = 0,
///OSPEEDR11 [22:23]
///Port x configuration bits (y =
///0..15)
ospeedr11: u2 = 0,
///OSPEEDR12 [24:25]
///Port x configuration bits (y =
///0..15)
ospeedr12: u2 = 0,
///OSPEEDR13 [26:27]
///Port x configuration bits (y =
///0..15)
ospeedr13: u2 = 0,
///OSPEEDR14 [28:29]
///Port x configuration bits (y =
///0..15)
ospeedr14: u2 = 0,
///OSPEEDR15 [30:31]
///Port x configuration bits (y =
///0..15)
ospeedr15: packed enum(u2) {
///Low speed
low_speed = 0,
///Medium speed
medium_speed = 1,
///High speed
high_speed = 2,
///Very high speed
very_high_speed = 3,
} = .low_speed,
};
///GPIO port output speed
///register
pub const ospeedr = Register(ospeedr_val).init(0x48000C00 + 0x8);
//////////////////////////
///PUPDR
const pupdr_val = packed struct {
///PUPDR0 [0:1]
///Port x configuration bits (y =
///0..15)
pupdr0: u2 = 0,
///PUPDR1 [2:3]
///Port x configuration bits (y =
///0..15)
pupdr1: u2 = 0,
///PUPDR2 [4:5]
///Port x configuration bits (y =
///0..15)
pupdr2: u2 = 0,
///PUPDR3 [6:7]
///Port x configuration bits (y =
///0..15)
pupdr3: u2 = 0,
///PUPDR4 [8:9]
///Port x configuration bits (y =
///0..15)
pupdr4: u2 = 0,
///PUPDR5 [10:11]
///Port x configuration bits (y =
///0..15)
pupdr5: u2 = 0,
///PUPDR6 [12:13]
///Port x configuration bits (y =
///0..15)
pupdr6: u2 = 0,
///PUPDR7 [14:15]
///Port x configuration bits (y =
///0..15)
pupdr7: u2 = 0,
///PUPDR8 [16:17]
///Port x configuration bits (y =
///0..15)
pupdr8: u2 = 0,
///PUPDR9 [18:19]
///Port x configuration bits (y =
///0..15)
pupdr9: u2 = 0,
///PUPDR10 [20:21]
///Port x configuration bits (y =
///0..15)
pupdr10: u2 = 0,
///PUPDR11 [22:23]
///Port x configuration bits (y =
///0..15)
pupdr11: u2 = 0,
///PUPDR12 [24:25]
///Port x configuration bits (y =
///0..15)
pupdr12: u2 = 0,
///PUPDR13 [26:27]
///Port x configuration bits (y =
///0..15)
pupdr13: u2 = 0,
///PUPDR14 [28:29]
///Port x configuration bits (y =
///0..15)
pupdr14: u2 = 0,
///PUPDR15 [30:31]
///Port x configuration bits (y =
///0..15)
pupdr15: packed enum(u2) {
///No pull-up, pull-down
floating = 0,
///Pull-up
pull_up = 1,
///Pull-down
pull_down = 2,
} = .floating,
};
///GPIO port pull-up/pull-down
///register
pub const pupdr = Register(pupdr_val).init(0x48000C00 + 0xC);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR0 [0:0]
///Port input data (y =
///0..15)
idr0: u1 = 0,
///IDR1 [1:1]
///Port input data (y =
///0..15)
idr1: u1 = 0,
///IDR2 [2:2]
///Port input data (y =
///0..15)
idr2: u1 = 0,
///IDR3 [3:3]
///Port input data (y =
///0..15)
idr3: u1 = 0,
///IDR4 [4:4]
///Port input data (y =
///0..15)
idr4: u1 = 0,
///IDR5 [5:5]
///Port input data (y =
///0..15)
idr5: u1 = 0,
///IDR6 [6:6]
///Port input data (y =
///0..15)
idr6: u1 = 0,
///IDR7 [7:7]
///Port input data (y =
///0..15)
idr7: u1 = 0,
///IDR8 [8:8]
///Port input data (y =
///0..15)
idr8: u1 = 0,
///IDR9 [9:9]
///Port input data (y =
///0..15)
idr9: u1 = 0,
///IDR10 [10:10]
///Port input data (y =
///0..15)
idr10: u1 = 0,
///IDR11 [11:11]
///Port input data (y =
///0..15)
idr11: u1 = 0,
///IDR12 [12:12]
///Port input data (y =
///0..15)
idr12: u1 = 0,
///IDR13 [13:13]
///Port input data (y =
///0..15)
idr13: u1 = 0,
///IDR14 [14:14]
///Port input data (y =
///0..15)
idr14: u1 = 0,
///IDR15 [15:15]
///Port input data (y =
///0..15)
idr15: packed enum(u1) {
///Input is logic high
high = 1,
///Input is logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port input data register
pub const idr = RegisterRW(idr_val, void).init(0x48000C00 + 0x10);
//////////////////////////
///ODR
const odr_val = packed struct {
///ODR0 [0:0]
///Port output data (y =
///0..15)
odr0: u1 = 0,
///ODR1 [1:1]
///Port output data (y =
///0..15)
odr1: u1 = 0,
///ODR2 [2:2]
///Port output data (y =
///0..15)
odr2: u1 = 0,
///ODR3 [3:3]
///Port output data (y =
///0..15)
odr3: u1 = 0,
///ODR4 [4:4]
///Port output data (y =
///0..15)
odr4: u1 = 0,
///ODR5 [5:5]
///Port output data (y =
///0..15)
odr5: u1 = 0,
///ODR6 [6:6]
///Port output data (y =
///0..15)
odr6: u1 = 0,
///ODR7 [7:7]
///Port output data (y =
///0..15)
odr7: u1 = 0,
///ODR8 [8:8]
///Port output data (y =
///0..15)
odr8: u1 = 0,
///ODR9 [9:9]
///Port output data (y =
///0..15)
odr9: u1 = 0,
///ODR10 [10:10]
///Port output data (y =
///0..15)
odr10: u1 = 0,
///ODR11 [11:11]
///Port output data (y =
///0..15)
odr11: u1 = 0,
///ODR12 [12:12]
///Port output data (y =
///0..15)
odr12: u1 = 0,
///ODR13 [13:13]
///Port output data (y =
///0..15)
odr13: u1 = 0,
///ODR14 [14:14]
///Port output data (y =
///0..15)
odr14: u1 = 0,
///ODR15 [15:15]
///Port output data (y =
///0..15)
odr15: packed enum(u1) {
///Set output to logic high
high = 1,
///Set output to logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port output data register
pub const odr = Register(odr_val).init(0x48000C00 + 0x14);
//////////////////////////
///BSRR
const bsrr_val = packed struct {
///BS0 [0:0]
///Port x set bit y (y=
///0..15)
bs0: u1 = 0,
///BS1 [1:1]
///Port x set bit y (y=
///0..15)
bs1: u1 = 0,
///BS2 [2:2]
///Port x set bit y (y=
///0..15)
bs2: u1 = 0,
///BS3 [3:3]
///Port x set bit y (y=
///0..15)
bs3: u1 = 0,
///BS4 [4:4]
///Port x set bit y (y=
///0..15)
bs4: u1 = 0,
///BS5 [5:5]
///Port x set bit y (y=
///0..15)
bs5: u1 = 0,
///BS6 [6:6]
///Port x set bit y (y=
///0..15)
bs6: u1 = 0,
///BS7 [7:7]
///Port x set bit y (y=
///0..15)
bs7: u1 = 0,
///BS8 [8:8]
///Port x set bit y (y=
///0..15)
bs8: u1 = 0,
///BS9 [9:9]
///Port x set bit y (y=
///0..15)
bs9: u1 = 0,
///BS10 [10:10]
///Port x set bit y (y=
///0..15)
bs10: u1 = 0,
///BS11 [11:11]
///Port x set bit y (y=
///0..15)
bs11: u1 = 0,
///BS12 [12:12]
///Port x set bit y (y=
///0..15)
bs12: u1 = 0,
///BS13 [13:13]
///Port x set bit y (y=
///0..15)
bs13: u1 = 0,
///BS14 [14:14]
///Port x set bit y (y=
///0..15)
bs14: u1 = 0,
///BS15 [15:15]
///Port x set bit y (y=
///0..15)
bs15: u1 = 0,
///BR0 [16:16]
///Port x set bit y (y=
///0..15)
br0: u1 = 0,
///BR1 [17:17]
///Port x reset bit y (y =
///0..15)
br1: u1 = 0,
///BR2 [18:18]
///Port x reset bit y (y =
///0..15)
br2: u1 = 0,
///BR3 [19:19]
///Port x reset bit y (y =
///0..15)
br3: u1 = 0,
///BR4 [20:20]
///Port x reset bit y (y =
///0..15)
br4: u1 = 0,
///BR5 [21:21]
///Port x reset bit y (y =
///0..15)
br5: u1 = 0,
///BR6 [22:22]
///Port x reset bit y (y =
///0..15)
br6: u1 = 0,
///BR7 [23:23]
///Port x reset bit y (y =
///0..15)
br7: u1 = 0,
///BR8 [24:24]
///Port x reset bit y (y =
///0..15)
br8: u1 = 0,
///BR9 [25:25]
///Port x reset bit y (y =
///0..15)
br9: u1 = 0,
///BR10 [26:26]
///Port x reset bit y (y =
///0..15)
br10: u1 = 0,
///BR11 [27:27]
///Port x reset bit y (y =
///0..15)
br11: u1 = 0,
///BR12 [28:28]
///Port x reset bit y (y =
///0..15)
br12: u1 = 0,
///BR13 [29:29]
///Port x reset bit y (y =
///0..15)
br13: u1 = 0,
///BR14 [30:30]
///Port x reset bit y (y =
///0..15)
br14: u1 = 0,
///BR15 [31:31]
///Port x reset bit y (y =
///0..15)
br15: u1 = 0,
};
///GPIO port bit set/reset
///register
pub const bsrr = RegisterRW(void, bsrr_val).init(0x48000C00 + 0x18);
//////////////////////////
///LCKR
const lckr_val = packed struct {
///LCK0 [0:0]
///Port x lock bit y (y=
///0..15)
lck0: u1 = 0,
///LCK1 [1:1]
///Port x lock bit y (y=
///0..15)
lck1: u1 = 0,
///LCK2 [2:2]
///Port x lock bit y (y=
///0..15)
lck2: u1 = 0,
///LCK3 [3:3]
///Port x lock bit y (y=
///0..15)
lck3: u1 = 0,
///LCK4 [4:4]
///Port x lock bit y (y=
///0..15)
lck4: u1 = 0,
///LCK5 [5:5]
///Port x lock bit y (y=
///0..15)
lck5: u1 = 0,
///LCK6 [6:6]
///Port x lock bit y (y=
///0..15)
lck6: u1 = 0,
///LCK7 [7:7]
///Port x lock bit y (y=
///0..15)
lck7: u1 = 0,
///LCK8 [8:8]
///Port x lock bit y (y=
///0..15)
lck8: u1 = 0,
///LCK9 [9:9]
///Port x lock bit y (y=
///0..15)
lck9: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCK10 [10:10]
///Port x lock bit y (y=
///0..15)
lck10: u1 = 0,
///LCK11 [11:11]
///Port x lock bit y (y=
///0..15)
lck11: u1 = 0,
///LCK12 [12:12]
///Port x lock bit y (y=
///0..15)
lck12: u1 = 0,
///LCK13 [13:13]
///Port x lock bit y (y=
///0..15)
lck13: u1 = 0,
///LCK14 [14:14]
///Port x lock bit y (y=
///0..15)
lck14: u1 = 0,
///LCK15 [15:15]
///Port x lock bit y (y=
///0..15)
lck15: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCKK [16:16]
///Port x lock bit y
lckk: packed enum(u1) {
///Port configuration lock key not active
not_active = 0,
///Port configuration lock key active
active = 1,
} = .not_active,
_unused17: u15 = 0,
};
///GPIO port configuration lock
///register
pub const lckr = Register(lckr_val).init(0x48000C00 + 0x1C);
//////////////////////////
///AFRL
const afrl_val = packed struct {
///AFRL0 [0:3]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl0: u4 = 0,
///AFRL1 [4:7]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl1: u4 = 0,
///AFRL2 [8:11]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl2: u4 = 0,
///AFRL3 [12:15]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl3: u4 = 0,
///AFRL4 [16:19]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl4: u4 = 0,
///AFRL5 [20:23]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl5: u4 = 0,
///AFRL6 [24:27]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl6: u4 = 0,
///AFRL7 [28:31]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl7: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function low
///register
pub const afrl = Register(afrl_val).init(0x48000C00 + 0x20);
//////////////////////////
///AFRH
const afrh_val = packed struct {
///AFRH8 [0:3]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh8: u4 = 0,
///AFRH9 [4:7]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh9: u4 = 0,
///AFRH10 [8:11]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh10: u4 = 0,
///AFRH11 [12:15]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh11: u4 = 0,
///AFRH12 [16:19]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh12: u4 = 0,
///AFRH13 [20:23]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh13: u4 = 0,
///AFRH14 [24:27]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh14: u4 = 0,
///AFRH15 [28:31]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh15: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function high
///register
pub const afrh = Register(afrh_val).init(0x48000C00 + 0x24);
//////////////////////////
///BRR
const brr_val = packed struct {
///BR0 [0:0]
///Port x Reset bit y
br0: u1 = 0,
///BR1 [1:1]
///Port x Reset bit y
br1: u1 = 0,
///BR2 [2:2]
///Port x Reset bit y
br2: u1 = 0,
///BR3 [3:3]
///Port x Reset bit y
br3: u1 = 0,
///BR4 [4:4]
///Port x Reset bit y
br4: u1 = 0,
///BR5 [5:5]
///Port x Reset bit y
br5: u1 = 0,
///BR6 [6:6]
///Port x Reset bit y
br6: u1 = 0,
///BR7 [7:7]
///Port x Reset bit y
br7: u1 = 0,
///BR8 [8:8]
///Port x Reset bit y
br8: u1 = 0,
///BR9 [9:9]
///Port x Reset bit y
br9: u1 = 0,
///BR10 [10:10]
///Port x Reset bit y
br10: u1 = 0,
///BR11 [11:11]
///Port x Reset bit y
br11: u1 = 0,
///BR12 [12:12]
///Port x Reset bit y
br12: u1 = 0,
///BR13 [13:13]
///Port x Reset bit y
br13: u1 = 0,
///BR14 [14:14]
///Port x Reset bit y
br14: u1 = 0,
///BR15 [15:15]
///Port x Reset bit y
br15: u1 = 0,
_unused16: u16 = 0,
};
///Port bit reset register
pub const brr = RegisterRW(void, brr_val).init(0x48000C00 + 0x28);
};
///General-purpose I/Os
pub const gpioc = struct {
//////////////////////////
///MODER
const moder_val = packed struct {
///MODER0 [0:1]
///Port x configuration bits (y =
///0..15)
moder0: u2 = 0,
///MODER1 [2:3]
///Port x configuration bits (y =
///0..15)
moder1: u2 = 0,
///MODER2 [4:5]
///Port x configuration bits (y =
///0..15)
moder2: u2 = 0,
///MODER3 [6:7]
///Port x configuration bits (y =
///0..15)
moder3: u2 = 0,
///MODER4 [8:9]
///Port x configuration bits (y =
///0..15)
moder4: u2 = 0,
///MODER5 [10:11]
///Port x configuration bits (y =
///0..15)
moder5: u2 = 0,
///MODER6 [12:13]
///Port x configuration bits (y =
///0..15)
moder6: u2 = 0,
///MODER7 [14:15]
///Port x configuration bits (y =
///0..15)
moder7: u2 = 0,
///MODER8 [16:17]
///Port x configuration bits (y =
///0..15)
moder8: u2 = 0,
///MODER9 [18:19]
///Port x configuration bits (y =
///0..15)
moder9: u2 = 0,
///MODER10 [20:21]
///Port x configuration bits (y =
///0..15)
moder10: u2 = 0,
///MODER11 [22:23]
///Port x configuration bits (y =
///0..15)
moder11: u2 = 0,
///MODER12 [24:25]
///Port x configuration bits (y =
///0..15)
moder12: u2 = 0,
///MODER13 [26:27]
///Port x configuration bits (y =
///0..15)
moder13: u2 = 0,
///MODER14 [28:29]
///Port x configuration bits (y =
///0..15)
moder14: u2 = 0,
///MODER15 [30:31]
///Port x configuration bits (y =
///0..15)
moder15: packed enum(u2) {
///Input mode (reset state)
input = 0,
///General purpose output mode
output = 1,
///Alternate function mode
alternate = 2,
///Analog mode
analog = 3,
} = .input,
};
///GPIO port mode register
pub const moder = Register(moder_val).init(0x48000800 + 0x0);
//////////////////////////
///OTYPER
const otyper_val = packed struct {
///OT0 [0:0]
///Port x configuration bit 0
ot0: u1 = 0,
///OT1 [1:1]
///Port x configuration bit 1
ot1: u1 = 0,
///OT2 [2:2]
///Port x configuration bit 2
ot2: u1 = 0,
///OT3 [3:3]
///Port x configuration bit 3
ot3: u1 = 0,
///OT4 [4:4]
///Port x configuration bit 4
ot4: u1 = 0,
///OT5 [5:5]
///Port x configuration bit 5
ot5: u1 = 0,
///OT6 [6:6]
///Port x configuration bit 6
ot6: u1 = 0,
///OT7 [7:7]
///Port x configuration bit 7
ot7: u1 = 0,
///OT8 [8:8]
///Port x configuration bit 8
ot8: u1 = 0,
///OT9 [9:9]
///Port x configuration bit 9
ot9: u1 = 0,
///OT10 [10:10]
///Port x configuration bit
///10
ot10: u1 = 0,
///OT11 [11:11]
///Port x configuration bit
///11
ot11: u1 = 0,
///OT12 [12:12]
///Port x configuration bit
///12
ot12: u1 = 0,
///OT13 [13:13]
///Port x configuration bit
///13
ot13: u1 = 0,
///OT14 [14:14]
///Port x configuration bit
///14
ot14: u1 = 0,
///OT15 [15:15]
///Port x configuration bit
///15
ot15: packed enum(u1) {
///Output push-pull (reset state)
push_pull = 0,
///Output open-drain
open_drain = 1,
} = .push_pull,
_unused16: u16 = 0,
};
///GPIO port output type register
pub const otyper = Register(otyper_val).init(0x48000800 + 0x4);
//////////////////////////
///OSPEEDR
const ospeedr_val = packed struct {
///OSPEEDR0 [0:1]
///Port x configuration bits (y =
///0..15)
ospeedr0: u2 = 0,
///OSPEEDR1 [2:3]
///Port x configuration bits (y =
///0..15)
ospeedr1: u2 = 0,
///OSPEEDR2 [4:5]
///Port x configuration bits (y =
///0..15)
ospeedr2: u2 = 0,
///OSPEEDR3 [6:7]
///Port x configuration bits (y =
///0..15)
ospeedr3: u2 = 0,
///OSPEEDR4 [8:9]
///Port x configuration bits (y =
///0..15)
ospeedr4: u2 = 0,
///OSPEEDR5 [10:11]
///Port x configuration bits (y =
///0..15)
ospeedr5: u2 = 0,
///OSPEEDR6 [12:13]
///Port x configuration bits (y =
///0..15)
ospeedr6: u2 = 0,
///OSPEEDR7 [14:15]
///Port x configuration bits (y =
///0..15)
ospeedr7: u2 = 0,
///OSPEEDR8 [16:17]
///Port x configuration bits (y =
///0..15)
ospeedr8: u2 = 0,
///OSPEEDR9 [18:19]
///Port x configuration bits (y =
///0..15)
ospeedr9: u2 = 0,
///OSPEEDR10 [20:21]
///Port x configuration bits (y =
///0..15)
ospeedr10: u2 = 0,
///OSPEEDR11 [22:23]
///Port x configuration bits (y =
///0..15)
ospeedr11: u2 = 0,
///OSPEEDR12 [24:25]
///Port x configuration bits (y =
///0..15)
ospeedr12: u2 = 0,
///OSPEEDR13 [26:27]
///Port x configuration bits (y =
///0..15)
ospeedr13: u2 = 0,
///OSPEEDR14 [28:29]
///Port x configuration bits (y =
///0..15)
ospeedr14: u2 = 0,
///OSPEEDR15 [30:31]
///Port x configuration bits (y =
///0..15)
ospeedr15: packed enum(u2) {
///Low speed
low_speed = 0,
///Medium speed
medium_speed = 1,
///High speed
high_speed = 2,
///Very high speed
very_high_speed = 3,
} = .low_speed,
};
///GPIO port output speed
///register
pub const ospeedr = Register(ospeedr_val).init(0x48000800 + 0x8);
//////////////////////////
///PUPDR
const pupdr_val = packed struct {
///PUPDR0 [0:1]
///Port x configuration bits (y =
///0..15)
pupdr0: u2 = 0,
///PUPDR1 [2:3]
///Port x configuration bits (y =
///0..15)
pupdr1: u2 = 0,
///PUPDR2 [4:5]
///Port x configuration bits (y =
///0..15)
pupdr2: u2 = 0,
///PUPDR3 [6:7]
///Port x configuration bits (y =
///0..15)
pupdr3: u2 = 0,
///PUPDR4 [8:9]
///Port x configuration bits (y =
///0..15)
pupdr4: u2 = 0,
///PUPDR5 [10:11]
///Port x configuration bits (y =
///0..15)
pupdr5: u2 = 0,
///PUPDR6 [12:13]
///Port x configuration bits (y =
///0..15)
pupdr6: u2 = 0,
///PUPDR7 [14:15]
///Port x configuration bits (y =
///0..15)
pupdr7: u2 = 0,
///PUPDR8 [16:17]
///Port x configuration bits (y =
///0..15)
pupdr8: u2 = 0,
///PUPDR9 [18:19]
///Port x configuration bits (y =
///0..15)
pupdr9: u2 = 0,
///PUPDR10 [20:21]
///Port x configuration bits (y =
///0..15)
pupdr10: u2 = 0,
///PUPDR11 [22:23]
///Port x configuration bits (y =
///0..15)
pupdr11: u2 = 0,
///PUPDR12 [24:25]
///Port x configuration bits (y =
///0..15)
pupdr12: u2 = 0,
///PUPDR13 [26:27]
///Port x configuration bits (y =
///0..15)
pupdr13: u2 = 0,
///PUPDR14 [28:29]
///Port x configuration bits (y =
///0..15)
pupdr14: u2 = 0,
///PUPDR15 [30:31]
///Port x configuration bits (y =
///0..15)
pupdr15: packed enum(u2) {
///No pull-up, pull-down
floating = 0,
///Pull-up
pull_up = 1,
///Pull-down
pull_down = 2,
} = .floating,
};
///GPIO port pull-up/pull-down
///register
pub const pupdr = Register(pupdr_val).init(0x48000800 + 0xC);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR0 [0:0]
///Port input data (y =
///0..15)
idr0: u1 = 0,
///IDR1 [1:1]
///Port input data (y =
///0..15)
idr1: u1 = 0,
///IDR2 [2:2]
///Port input data (y =
///0..15)
idr2: u1 = 0,
///IDR3 [3:3]
///Port input data (y =
///0..15)
idr3: u1 = 0,
///IDR4 [4:4]
///Port input data (y =
///0..15)
idr4: u1 = 0,
///IDR5 [5:5]
///Port input data (y =
///0..15)
idr5: u1 = 0,
///IDR6 [6:6]
///Port input data (y =
///0..15)
idr6: u1 = 0,
///IDR7 [7:7]
///Port input data (y =
///0..15)
idr7: u1 = 0,
///IDR8 [8:8]
///Port input data (y =
///0..15)
idr8: u1 = 0,
///IDR9 [9:9]
///Port input data (y =
///0..15)
idr9: u1 = 0,
///IDR10 [10:10]
///Port input data (y =
///0..15)
idr10: u1 = 0,
///IDR11 [11:11]
///Port input data (y =
///0..15)
idr11: u1 = 0,
///IDR12 [12:12]
///Port input data (y =
///0..15)
idr12: u1 = 0,
///IDR13 [13:13]
///Port input data (y =
///0..15)
idr13: u1 = 0,
///IDR14 [14:14]
///Port input data (y =
///0..15)
idr14: u1 = 0,
///IDR15 [15:15]
///Port input data (y =
///0..15)
idr15: packed enum(u1) {
///Input is logic high
high = 1,
///Input is logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port input data register
pub const idr = RegisterRW(idr_val, void).init(0x48000800 + 0x10);
//////////////////////////
///ODR
const odr_val = packed struct {
///ODR0 [0:0]
///Port output data (y =
///0..15)
odr0: u1 = 0,
///ODR1 [1:1]
///Port output data (y =
///0..15)
odr1: u1 = 0,
///ODR2 [2:2]
///Port output data (y =
///0..15)
odr2: u1 = 0,
///ODR3 [3:3]
///Port output data (y =
///0..15)
odr3: u1 = 0,
///ODR4 [4:4]
///Port output data (y =
///0..15)
odr4: u1 = 0,
///ODR5 [5:5]
///Port output data (y =
///0..15)
odr5: u1 = 0,
///ODR6 [6:6]
///Port output data (y =
///0..15)
odr6: u1 = 0,
///ODR7 [7:7]
///Port output data (y =
///0..15)
odr7: u1 = 0,
///ODR8 [8:8]
///Port output data (y =
///0..15)
odr8: u1 = 0,
///ODR9 [9:9]
///Port output data (y =
///0..15)
odr9: u1 = 0,
///ODR10 [10:10]
///Port output data (y =
///0..15)
odr10: u1 = 0,
///ODR11 [11:11]
///Port output data (y =
///0..15)
odr11: u1 = 0,
///ODR12 [12:12]
///Port output data (y =
///0..15)
odr12: u1 = 0,
///ODR13 [13:13]
///Port output data (y =
///0..15)
odr13: u1 = 0,
///ODR14 [14:14]
///Port output data (y =
///0..15)
odr14: u1 = 0,
///ODR15 [15:15]
///Port output data (y =
///0..15)
odr15: packed enum(u1) {
///Set output to logic high
high = 1,
///Set output to logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port output data register
pub const odr = Register(odr_val).init(0x48000800 + 0x14);
//////////////////////////
///BSRR
const bsrr_val = packed struct {
///BS0 [0:0]
///Port x set bit y (y=
///0..15)
bs0: u1 = 0,
///BS1 [1:1]
///Port x set bit y (y=
///0..15)
bs1: u1 = 0,
///BS2 [2:2]
///Port x set bit y (y=
///0..15)
bs2: u1 = 0,
///BS3 [3:3]
///Port x set bit y (y=
///0..15)
bs3: u1 = 0,
///BS4 [4:4]
///Port x set bit y (y=
///0..15)
bs4: u1 = 0,
///BS5 [5:5]
///Port x set bit y (y=
///0..15)
bs5: u1 = 0,
///BS6 [6:6]
///Port x set bit y (y=
///0..15)
bs6: u1 = 0,
///BS7 [7:7]
///Port x set bit y (y=
///0..15)
bs7: u1 = 0,
///BS8 [8:8]
///Port x set bit y (y=
///0..15)
bs8: u1 = 0,
///BS9 [9:9]
///Port x set bit y (y=
///0..15)
bs9: u1 = 0,
///BS10 [10:10]
///Port x set bit y (y=
///0..15)
bs10: u1 = 0,
///BS11 [11:11]
///Port x set bit y (y=
///0..15)
bs11: u1 = 0,
///BS12 [12:12]
///Port x set bit y (y=
///0..15)
bs12: u1 = 0,
///BS13 [13:13]
///Port x set bit y (y=
///0..15)
bs13: u1 = 0,
///BS14 [14:14]
///Port x set bit y (y=
///0..15)
bs14: u1 = 0,
///BS15 [15:15]
///Port x set bit y (y=
///0..15)
bs15: u1 = 0,
///BR0 [16:16]
///Port x set bit y (y=
///0..15)
br0: u1 = 0,
///BR1 [17:17]
///Port x reset bit y (y =
///0..15)
br1: u1 = 0,
///BR2 [18:18]
///Port x reset bit y (y =
///0..15)
br2: u1 = 0,
///BR3 [19:19]
///Port x reset bit y (y =
///0..15)
br3: u1 = 0,
///BR4 [20:20]
///Port x reset bit y (y =
///0..15)
br4: u1 = 0,
///BR5 [21:21]
///Port x reset bit y (y =
///0..15)
br5: u1 = 0,
///BR6 [22:22]
///Port x reset bit y (y =
///0..15)
br6: u1 = 0,
///BR7 [23:23]
///Port x reset bit y (y =
///0..15)
br7: u1 = 0,
///BR8 [24:24]
///Port x reset bit y (y =
///0..15)
br8: u1 = 0,
///BR9 [25:25]
///Port x reset bit y (y =
///0..15)
br9: u1 = 0,
///BR10 [26:26]
///Port x reset bit y (y =
///0..15)
br10: u1 = 0,
///BR11 [27:27]
///Port x reset bit y (y =
///0..15)
br11: u1 = 0,
///BR12 [28:28]
///Port x reset bit y (y =
///0..15)
br12: u1 = 0,
///BR13 [29:29]
///Port x reset bit y (y =
///0..15)
br13: u1 = 0,
///BR14 [30:30]
///Port x reset bit y (y =
///0..15)
br14: u1 = 0,
///BR15 [31:31]
///Port x reset bit y (y =
///0..15)
br15: u1 = 0,
};
///GPIO port bit set/reset
///register
pub const bsrr = RegisterRW(void, bsrr_val).init(0x48000800 + 0x18);
//////////////////////////
///LCKR
const lckr_val = packed struct {
///LCK0 [0:0]
///Port x lock bit y (y=
///0..15)
lck0: u1 = 0,
///LCK1 [1:1]
///Port x lock bit y (y=
///0..15)
lck1: u1 = 0,
///LCK2 [2:2]
///Port x lock bit y (y=
///0..15)
lck2: u1 = 0,
///LCK3 [3:3]
///Port x lock bit y (y=
///0..15)
lck3: u1 = 0,
///LCK4 [4:4]
///Port x lock bit y (y=
///0..15)
lck4: u1 = 0,
///LCK5 [5:5]
///Port x lock bit y (y=
///0..15)
lck5: u1 = 0,
///LCK6 [6:6]
///Port x lock bit y (y=
///0..15)
lck6: u1 = 0,
///LCK7 [7:7]
///Port x lock bit y (y=
///0..15)
lck7: u1 = 0,
///LCK8 [8:8]
///Port x lock bit y (y=
///0..15)
lck8: u1 = 0,
///LCK9 [9:9]
///Port x lock bit y (y=
///0..15)
lck9: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCK10 [10:10]
///Port x lock bit y (y=
///0..15)
lck10: u1 = 0,
///LCK11 [11:11]
///Port x lock bit y (y=
///0..15)
lck11: u1 = 0,
///LCK12 [12:12]
///Port x lock bit y (y=
///0..15)
lck12: u1 = 0,
///LCK13 [13:13]
///Port x lock bit y (y=
///0..15)
lck13: u1 = 0,
///LCK14 [14:14]
///Port x lock bit y (y=
///0..15)
lck14: u1 = 0,
///LCK15 [15:15]
///Port x lock bit y (y=
///0..15)
lck15: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCKK [16:16]
///Port x lock bit y
lckk: packed enum(u1) {
///Port configuration lock key not active
not_active = 0,
///Port configuration lock key active
active = 1,
} = .not_active,
_unused17: u15 = 0,
};
///GPIO port configuration lock
///register
pub const lckr = Register(lckr_val).init(0x48000800 + 0x1C);
//////////////////////////
///AFRL
const afrl_val = packed struct {
///AFRL0 [0:3]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl0: u4 = 0,
///AFRL1 [4:7]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl1: u4 = 0,
///AFRL2 [8:11]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl2: u4 = 0,
///AFRL3 [12:15]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl3: u4 = 0,
///AFRL4 [16:19]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl4: u4 = 0,
///AFRL5 [20:23]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl5: u4 = 0,
///AFRL6 [24:27]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl6: u4 = 0,
///AFRL7 [28:31]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl7: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function low
///register
pub const afrl = Register(afrl_val).init(0x48000800 + 0x20);
//////////////////////////
///AFRH
const afrh_val = packed struct {
///AFRH8 [0:3]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh8: u4 = 0,
///AFRH9 [4:7]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh9: u4 = 0,
///AFRH10 [8:11]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh10: u4 = 0,
///AFRH11 [12:15]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh11: u4 = 0,
///AFRH12 [16:19]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh12: u4 = 0,
///AFRH13 [20:23]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh13: u4 = 0,
///AFRH14 [24:27]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh14: u4 = 0,
///AFRH15 [28:31]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh15: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function high
///register
pub const afrh = Register(afrh_val).init(0x48000800 + 0x24);
//////////////////////////
///BRR
const brr_val = packed struct {
///BR0 [0:0]
///Port x Reset bit y
br0: u1 = 0,
///BR1 [1:1]
///Port x Reset bit y
br1: u1 = 0,
///BR2 [2:2]
///Port x Reset bit y
br2: u1 = 0,
///BR3 [3:3]
///Port x Reset bit y
br3: u1 = 0,
///BR4 [4:4]
///Port x Reset bit y
br4: u1 = 0,
///BR5 [5:5]
///Port x Reset bit y
br5: u1 = 0,
///BR6 [6:6]
///Port x Reset bit y
br6: u1 = 0,
///BR7 [7:7]
///Port x Reset bit y
br7: u1 = 0,
///BR8 [8:8]
///Port x Reset bit y
br8: u1 = 0,
///BR9 [9:9]
///Port x Reset bit y
br9: u1 = 0,
///BR10 [10:10]
///Port x Reset bit y
br10: u1 = 0,
///BR11 [11:11]
///Port x Reset bit y
br11: u1 = 0,
///BR12 [12:12]
///Port x Reset bit y
br12: u1 = 0,
///BR13 [13:13]
///Port x Reset bit y
br13: u1 = 0,
///BR14 [14:14]
///Port x Reset bit y
br14: u1 = 0,
///BR15 [15:15]
///Port x Reset bit y
br15: u1 = 0,
_unused16: u16 = 0,
};
///Port bit reset register
pub const brr = RegisterRW(void, brr_val).init(0x48000800 + 0x28);
};
///General-purpose I/Os
pub const gpiob = struct {
//////////////////////////
///MODER
const moder_val = packed struct {
///MODER0 [0:1]
///Port x configuration bits (y =
///0..15)
moder0: u2 = 0,
///MODER1 [2:3]
///Port x configuration bits (y =
///0..15)
moder1: u2 = 0,
///MODER2 [4:5]
///Port x configuration bits (y =
///0..15)
moder2: u2 = 0,
///MODER3 [6:7]
///Port x configuration bits (y =
///0..15)
moder3: u2 = 0,
///MODER4 [8:9]
///Port x configuration bits (y =
///0..15)
moder4: u2 = 0,
///MODER5 [10:11]
///Port x configuration bits (y =
///0..15)
moder5: u2 = 0,
///MODER6 [12:13]
///Port x configuration bits (y =
///0..15)
moder6: u2 = 0,
///MODER7 [14:15]
///Port x configuration bits (y =
///0..15)
moder7: u2 = 0,
///MODER8 [16:17]
///Port x configuration bits (y =
///0..15)
moder8: u2 = 0,
///MODER9 [18:19]
///Port x configuration bits (y =
///0..15)
moder9: u2 = 0,
///MODER10 [20:21]
///Port x configuration bits (y =
///0..15)
moder10: u2 = 0,
///MODER11 [22:23]
///Port x configuration bits (y =
///0..15)
moder11: u2 = 0,
///MODER12 [24:25]
///Port x configuration bits (y =
///0..15)
moder12: u2 = 0,
///MODER13 [26:27]
///Port x configuration bits (y =
///0..15)
moder13: u2 = 0,
///MODER14 [28:29]
///Port x configuration bits (y =
///0..15)
moder14: u2 = 0,
///MODER15 [30:31]
///Port x configuration bits (y =
///0..15)
moder15: packed enum(u2) {
///Input mode (reset state)
input = 0,
///General purpose output mode
output = 1,
///Alternate function mode
alternate = 2,
///Analog mode
analog = 3,
} = .input,
};
///GPIO port mode register
pub const moder = Register(moder_val).init(0x48000400 + 0x0);
//////////////////////////
///OTYPER
const otyper_val = packed struct {
///OT0 [0:0]
///Port x configuration bit 0
ot0: u1 = 0,
///OT1 [1:1]
///Port x configuration bit 1
ot1: u1 = 0,
///OT2 [2:2]
///Port x configuration bit 2
ot2: u1 = 0,
///OT3 [3:3]
///Port x configuration bit 3
ot3: u1 = 0,
///OT4 [4:4]
///Port x configuration bit 4
ot4: u1 = 0,
///OT5 [5:5]
///Port x configuration bit 5
ot5: u1 = 0,
///OT6 [6:6]
///Port x configuration bit 6
ot6: u1 = 0,
///OT7 [7:7]
///Port x configuration bit 7
ot7: u1 = 0,
///OT8 [8:8]
///Port x configuration bit 8
ot8: u1 = 0,
///OT9 [9:9]
///Port x configuration bit 9
ot9: u1 = 0,
///OT10 [10:10]
///Port x configuration bit
///10
ot10: u1 = 0,
///OT11 [11:11]
///Port x configuration bit
///11
ot11: u1 = 0,
///OT12 [12:12]
///Port x configuration bit
///12
ot12: u1 = 0,
///OT13 [13:13]
///Port x configuration bit
///13
ot13: u1 = 0,
///OT14 [14:14]
///Port x configuration bit
///14
ot14: u1 = 0,
///OT15 [15:15]
///Port x configuration bit
///15
ot15: packed enum(u1) {
///Output push-pull (reset state)
push_pull = 0,
///Output open-drain
open_drain = 1,
} = .push_pull,
_unused16: u16 = 0,
};
///GPIO port output type register
pub const otyper = Register(otyper_val).init(0x48000400 + 0x4);
//////////////////////////
///OSPEEDR
const ospeedr_val = packed struct {
///OSPEEDR0 [0:1]
///Port x configuration bits (y =
///0..15)
ospeedr0: u2 = 0,
///OSPEEDR1 [2:3]
///Port x configuration bits (y =
///0..15)
ospeedr1: u2 = 0,
///OSPEEDR2 [4:5]
///Port x configuration bits (y =
///0..15)
ospeedr2: u2 = 0,
///OSPEEDR3 [6:7]
///Port x configuration bits (y =
///0..15)
ospeedr3: u2 = 0,
///OSPEEDR4 [8:9]
///Port x configuration bits (y =
///0..15)
ospeedr4: u2 = 0,
///OSPEEDR5 [10:11]
///Port x configuration bits (y =
///0..15)
ospeedr5: u2 = 0,
///OSPEEDR6 [12:13]
///Port x configuration bits (y =
///0..15)
ospeedr6: u2 = 0,
///OSPEEDR7 [14:15]
///Port x configuration bits (y =
///0..15)
ospeedr7: u2 = 0,
///OSPEEDR8 [16:17]
///Port x configuration bits (y =
///0..15)
ospeedr8: u2 = 0,
///OSPEEDR9 [18:19]
///Port x configuration bits (y =
///0..15)
ospeedr9: u2 = 0,
///OSPEEDR10 [20:21]
///Port x configuration bits (y =
///0..15)
ospeedr10: u2 = 0,
///OSPEEDR11 [22:23]
///Port x configuration bits (y =
///0..15)
ospeedr11: u2 = 0,
///OSPEEDR12 [24:25]
///Port x configuration bits (y =
///0..15)
ospeedr12: u2 = 0,
///OSPEEDR13 [26:27]
///Port x configuration bits (y =
///0..15)
ospeedr13: u2 = 0,
///OSPEEDR14 [28:29]
///Port x configuration bits (y =
///0..15)
ospeedr14: u2 = 0,
///OSPEEDR15 [30:31]
///Port x configuration bits (y =
///0..15)
ospeedr15: packed enum(u2) {
///Low speed
low_speed = 0,
///Medium speed
medium_speed = 1,
///High speed
high_speed = 2,
///Very high speed
very_high_speed = 3,
} = .low_speed,
};
///GPIO port output speed
///register
pub const ospeedr = Register(ospeedr_val).init(0x48000400 + 0x8);
//////////////////////////
///PUPDR
const pupdr_val = packed struct {
///PUPDR0 [0:1]
///Port x configuration bits (y =
///0..15)
pupdr0: u2 = 0,
///PUPDR1 [2:3]
///Port x configuration bits (y =
///0..15)
pupdr1: u2 = 0,
///PUPDR2 [4:5]
///Port x configuration bits (y =
///0..15)
pupdr2: u2 = 0,
///PUPDR3 [6:7]
///Port x configuration bits (y =
///0..15)
pupdr3: u2 = 0,
///PUPDR4 [8:9]
///Port x configuration bits (y =
///0..15)
pupdr4: u2 = 0,
///PUPDR5 [10:11]
///Port x configuration bits (y =
///0..15)
pupdr5: u2 = 0,
///PUPDR6 [12:13]
///Port x configuration bits (y =
///0..15)
pupdr6: u2 = 0,
///PUPDR7 [14:15]
///Port x configuration bits (y =
///0..15)
pupdr7: u2 = 0,
///PUPDR8 [16:17]
///Port x configuration bits (y =
///0..15)
pupdr8: u2 = 0,
///PUPDR9 [18:19]
///Port x configuration bits (y =
///0..15)
pupdr9: u2 = 0,
///PUPDR10 [20:21]
///Port x configuration bits (y =
///0..15)
pupdr10: u2 = 0,
///PUPDR11 [22:23]
///Port x configuration bits (y =
///0..15)
pupdr11: u2 = 0,
///PUPDR12 [24:25]
///Port x configuration bits (y =
///0..15)
pupdr12: u2 = 0,
///PUPDR13 [26:27]
///Port x configuration bits (y =
///0..15)
pupdr13: u2 = 0,
///PUPDR14 [28:29]
///Port x configuration bits (y =
///0..15)
pupdr14: u2 = 0,
///PUPDR15 [30:31]
///Port x configuration bits (y =
///0..15)
pupdr15: packed enum(u2) {
///No pull-up, pull-down
floating = 0,
///Pull-up
pull_up = 1,
///Pull-down
pull_down = 2,
} = .floating,
};
///GPIO port pull-up/pull-down
///register
pub const pupdr = Register(pupdr_val).init(0x48000400 + 0xC);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR0 [0:0]
///Port input data (y =
///0..15)
idr0: u1 = 0,
///IDR1 [1:1]
///Port input data (y =
///0..15)
idr1: u1 = 0,
///IDR2 [2:2]
///Port input data (y =
///0..15)
idr2: u1 = 0,
///IDR3 [3:3]
///Port input data (y =
///0..15)
idr3: u1 = 0,
///IDR4 [4:4]
///Port input data (y =
///0..15)
idr4: u1 = 0,
///IDR5 [5:5]
///Port input data (y =
///0..15)
idr5: u1 = 0,
///IDR6 [6:6]
///Port input data (y =
///0..15)
idr6: u1 = 0,
///IDR7 [7:7]
///Port input data (y =
///0..15)
idr7: u1 = 0,
///IDR8 [8:8]
///Port input data (y =
///0..15)
idr8: u1 = 0,
///IDR9 [9:9]
///Port input data (y =
///0..15)
idr9: u1 = 0,
///IDR10 [10:10]
///Port input data (y =
///0..15)
idr10: u1 = 0,
///IDR11 [11:11]
///Port input data (y =
///0..15)
idr11: u1 = 0,
///IDR12 [12:12]
///Port input data (y =
///0..15)
idr12: u1 = 0,
///IDR13 [13:13]
///Port input data (y =
///0..15)
idr13: u1 = 0,
///IDR14 [14:14]
///Port input data (y =
///0..15)
idr14: u1 = 0,
///IDR15 [15:15]
///Port input data (y =
///0..15)
idr15: packed enum(u1) {
///Input is logic high
high = 1,
///Input is logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port input data register
pub const idr = RegisterRW(idr_val, void).init(0x48000400 + 0x10);
//////////////////////////
///ODR
const odr_val = packed struct {
///ODR0 [0:0]
///Port output data (y =
///0..15)
odr0: u1 = 0,
///ODR1 [1:1]
///Port output data (y =
///0..15)
odr1: u1 = 0,
///ODR2 [2:2]
///Port output data (y =
///0..15)
odr2: u1 = 0,
///ODR3 [3:3]
///Port output data (y =
///0..15)
odr3: u1 = 0,
///ODR4 [4:4]
///Port output data (y =
///0..15)
odr4: u1 = 0,
///ODR5 [5:5]
///Port output data (y =
///0..15)
odr5: u1 = 0,
///ODR6 [6:6]
///Port output data (y =
///0..15)
odr6: u1 = 0,
///ODR7 [7:7]
///Port output data (y =
///0..15)
odr7: u1 = 0,
///ODR8 [8:8]
///Port output data (y =
///0..15)
odr8: u1 = 0,
///ODR9 [9:9]
///Port output data (y =
///0..15)
odr9: u1 = 0,
///ODR10 [10:10]
///Port output data (y =
///0..15)
odr10: u1 = 0,
///ODR11 [11:11]
///Port output data (y =
///0..15)
odr11: u1 = 0,
///ODR12 [12:12]
///Port output data (y =
///0..15)
odr12: u1 = 0,
///ODR13 [13:13]
///Port output data (y =
///0..15)
odr13: u1 = 0,
///ODR14 [14:14]
///Port output data (y =
///0..15)
odr14: u1 = 0,
///ODR15 [15:15]
///Port output data (y =
///0..15)
odr15: packed enum(u1) {
///Set output to logic high
high = 1,
///Set output to logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port output data register
pub const odr = Register(odr_val).init(0x48000400 + 0x14);
//////////////////////////
///BSRR
const bsrr_val = packed struct {
///BS0 [0:0]
///Port x set bit y (y=
///0..15)
bs0: u1 = 0,
///BS1 [1:1]
///Port x set bit y (y=
///0..15)
bs1: u1 = 0,
///BS2 [2:2]
///Port x set bit y (y=
///0..15)
bs2: u1 = 0,
///BS3 [3:3]
///Port x set bit y (y=
///0..15)
bs3: u1 = 0,
///BS4 [4:4]
///Port x set bit y (y=
///0..15)
bs4: u1 = 0,
///BS5 [5:5]
///Port x set bit y (y=
///0..15)
bs5: u1 = 0,
///BS6 [6:6]
///Port x set bit y (y=
///0..15)
bs6: u1 = 0,
///BS7 [7:7]
///Port x set bit y (y=
///0..15)
bs7: u1 = 0,
///BS8 [8:8]
///Port x set bit y (y=
///0..15)
bs8: u1 = 0,
///BS9 [9:9]
///Port x set bit y (y=
///0..15)
bs9: u1 = 0,
///BS10 [10:10]
///Port x set bit y (y=
///0..15)
bs10: u1 = 0,
///BS11 [11:11]
///Port x set bit y (y=
///0..15)
bs11: u1 = 0,
///BS12 [12:12]
///Port x set bit y (y=
///0..15)
bs12: u1 = 0,
///BS13 [13:13]
///Port x set bit y (y=
///0..15)
bs13: u1 = 0,
///BS14 [14:14]
///Port x set bit y (y=
///0..15)
bs14: u1 = 0,
///BS15 [15:15]
///Port x set bit y (y=
///0..15)
bs15: u1 = 0,
///BR0 [16:16]
///Port x set bit y (y=
///0..15)
br0: u1 = 0,
///BR1 [17:17]
///Port x reset bit y (y =
///0..15)
br1: u1 = 0,
///BR2 [18:18]
///Port x reset bit y (y =
///0..15)
br2: u1 = 0,
///BR3 [19:19]
///Port x reset bit y (y =
///0..15)
br3: u1 = 0,
///BR4 [20:20]
///Port x reset bit y (y =
///0..15)
br4: u1 = 0,
///BR5 [21:21]
///Port x reset bit y (y =
///0..15)
br5: u1 = 0,
///BR6 [22:22]
///Port x reset bit y (y =
///0..15)
br6: u1 = 0,
///BR7 [23:23]
///Port x reset bit y (y =
///0..15)
br7: u1 = 0,
///BR8 [24:24]
///Port x reset bit y (y =
///0..15)
br8: u1 = 0,
///BR9 [25:25]
///Port x reset bit y (y =
///0..15)
br9: u1 = 0,
///BR10 [26:26]
///Port x reset bit y (y =
///0..15)
br10: u1 = 0,
///BR11 [27:27]
///Port x reset bit y (y =
///0..15)
br11: u1 = 0,
///BR12 [28:28]
///Port x reset bit y (y =
///0..15)
br12: u1 = 0,
///BR13 [29:29]
///Port x reset bit y (y =
///0..15)
br13: u1 = 0,
///BR14 [30:30]
///Port x reset bit y (y =
///0..15)
br14: u1 = 0,
///BR15 [31:31]
///Port x reset bit y (y =
///0..15)
br15: u1 = 0,
};
///GPIO port bit set/reset
///register
pub const bsrr = RegisterRW(void, bsrr_val).init(0x48000400 + 0x18);
//////////////////////////
///LCKR
const lckr_val = packed struct {
///LCK0 [0:0]
///Port x lock bit y (y=
///0..15)
lck0: u1 = 0,
///LCK1 [1:1]
///Port x lock bit y (y=
///0..15)
lck1: u1 = 0,
///LCK2 [2:2]
///Port x lock bit y (y=
///0..15)
lck2: u1 = 0,
///LCK3 [3:3]
///Port x lock bit y (y=
///0..15)
lck3: u1 = 0,
///LCK4 [4:4]
///Port x lock bit y (y=
///0..15)
lck4: u1 = 0,
///LCK5 [5:5]
///Port x lock bit y (y=
///0..15)
lck5: u1 = 0,
///LCK6 [6:6]
///Port x lock bit y (y=
///0..15)
lck6: u1 = 0,
///LCK7 [7:7]
///Port x lock bit y (y=
///0..15)
lck7: u1 = 0,
///LCK8 [8:8]
///Port x lock bit y (y=
///0..15)
lck8: u1 = 0,
///LCK9 [9:9]
///Port x lock bit y (y=
///0..15)
lck9: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCK10 [10:10]
///Port x lock bit y (y=
///0..15)
lck10: u1 = 0,
///LCK11 [11:11]
///Port x lock bit y (y=
///0..15)
lck11: u1 = 0,
///LCK12 [12:12]
///Port x lock bit y (y=
///0..15)
lck12: u1 = 0,
///LCK13 [13:13]
///Port x lock bit y (y=
///0..15)
lck13: u1 = 0,
///LCK14 [14:14]
///Port x lock bit y (y=
///0..15)
lck14: u1 = 0,
///LCK15 [15:15]
///Port x lock bit y (y=
///0..15)
lck15: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCKK [16:16]
///Port x lock bit y
lckk: packed enum(u1) {
///Port configuration lock key not active
not_active = 0,
///Port configuration lock key active
active = 1,
} = .not_active,
_unused17: u15 = 0,
};
///GPIO port configuration lock
///register
pub const lckr = Register(lckr_val).init(0x48000400 + 0x1C);
//////////////////////////
///AFRL
const afrl_val = packed struct {
///AFRL0 [0:3]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl0: u4 = 0,
///AFRL1 [4:7]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl1: u4 = 0,
///AFRL2 [8:11]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl2: u4 = 0,
///AFRL3 [12:15]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl3: u4 = 0,
///AFRL4 [16:19]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl4: u4 = 0,
///AFRL5 [20:23]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl5: u4 = 0,
///AFRL6 [24:27]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl6: u4 = 0,
///AFRL7 [28:31]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl7: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function low
///register
pub const afrl = Register(afrl_val).init(0x48000400 + 0x20);
//////////////////////////
///AFRH
const afrh_val = packed struct {
///AFRH8 [0:3]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh8: u4 = 0,
///AFRH9 [4:7]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh9: u4 = 0,
///AFRH10 [8:11]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh10: u4 = 0,
///AFRH11 [12:15]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh11: u4 = 0,
///AFRH12 [16:19]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh12: u4 = 0,
///AFRH13 [20:23]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh13: u4 = 0,
///AFRH14 [24:27]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh14: u4 = 0,
///AFRH15 [28:31]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh15: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function high
///register
pub const afrh = Register(afrh_val).init(0x48000400 + 0x24);
//////////////////////////
///BRR
const brr_val = packed struct {
///BR0 [0:0]
///Port x Reset bit y
br0: u1 = 0,
///BR1 [1:1]
///Port x Reset bit y
br1: u1 = 0,
///BR2 [2:2]
///Port x Reset bit y
br2: u1 = 0,
///BR3 [3:3]
///Port x Reset bit y
br3: u1 = 0,
///BR4 [4:4]
///Port x Reset bit y
br4: u1 = 0,
///BR5 [5:5]
///Port x Reset bit y
br5: u1 = 0,
///BR6 [6:6]
///Port x Reset bit y
br6: u1 = 0,
///BR7 [7:7]
///Port x Reset bit y
br7: u1 = 0,
///BR8 [8:8]
///Port x Reset bit y
br8: u1 = 0,
///BR9 [9:9]
///Port x Reset bit y
br9: u1 = 0,
///BR10 [10:10]
///Port x Reset bit y
br10: u1 = 0,
///BR11 [11:11]
///Port x Reset bit y
br11: u1 = 0,
///BR12 [12:12]
///Port x Reset bit y
br12: u1 = 0,
///BR13 [13:13]
///Port x Reset bit y
br13: u1 = 0,
///BR14 [14:14]
///Port x Reset bit y
br14: u1 = 0,
///BR15 [15:15]
///Port x Reset bit y
br15: u1 = 0,
_unused16: u16 = 0,
};
///Port bit reset register
pub const brr = RegisterRW(void, brr_val).init(0x48000400 + 0x28);
};
///General-purpose I/Os
pub const gpioa = struct {
//////////////////////////
///MODER
const moder_val = packed struct {
///MODER0 [0:1]
///Port x configuration bits (y =
///0..15)
moder0: u2 = 0,
///MODER1 [2:3]
///Port x configuration bits (y =
///0..15)
moder1: u2 = 0,
///MODER2 [4:5]
///Port x configuration bits (y =
///0..15)
moder2: u2 = 0,
///MODER3 [6:7]
///Port x configuration bits (y =
///0..15)
moder3: u2 = 0,
///MODER4 [8:9]
///Port x configuration bits (y =
///0..15)
moder4: u2 = 0,
///MODER5 [10:11]
///Port x configuration bits (y =
///0..15)
moder5: u2 = 0,
///MODER6 [12:13]
///Port x configuration bits (y =
///0..15)
moder6: u2 = 0,
///MODER7 [14:15]
///Port x configuration bits (y =
///0..15)
moder7: u2 = 0,
///MODER8 [16:17]
///Port x configuration bits (y =
///0..15)
moder8: u2 = 0,
///MODER9 [18:19]
///Port x configuration bits (y =
///0..15)
moder9: u2 = 0,
///MODER10 [20:21]
///Port x configuration bits (y =
///0..15)
moder10: u2 = 0,
///MODER11 [22:23]
///Port x configuration bits (y =
///0..15)
moder11: u2 = 0,
///MODER12 [24:25]
///Port x configuration bits (y =
///0..15)
moder12: u2 = 0,
///MODER13 [26:27]
///Port x configuration bits (y =
///0..15)
moder13: u2 = 2,
///MODER14 [28:29]
///Port x configuration bits (y =
///0..15)
moder14: u2 = 2,
///MODER15 [30:31]
///Port x configuration bits (y =
///0..15)
moder15: packed enum(u2) {
///Input mode (reset state)
input = 0,
///General purpose output mode
output = 1,
///Alternate function mode
alternate = 2,
///Analog mode
analog = 3,
} = .input,
};
///GPIO port mode register
pub const moder = Register(moder_val).init(0x48000000 + 0x0);
//////////////////////////
///OTYPER
const otyper_val = packed struct {
///OT0 [0:0]
///Port x configuration bits (y =
///0..15)
ot0: u1 = 0,
///OT1 [1:1]
///Port x configuration bits (y =
///0..15)
ot1: u1 = 0,
///OT2 [2:2]
///Port x configuration bits (y =
///0..15)
ot2: u1 = 0,
///OT3 [3:3]
///Port x configuration bits (y =
///0..15)
ot3: u1 = 0,
///OT4 [4:4]
///Port x configuration bits (y =
///0..15)
ot4: u1 = 0,
///OT5 [5:5]
///Port x configuration bits (y =
///0..15)
ot5: u1 = 0,
///OT6 [6:6]
///Port x configuration bits (y =
///0..15)
ot6: u1 = 0,
///OT7 [7:7]
///Port x configuration bits (y =
///0..15)
ot7: u1 = 0,
///OT8 [8:8]
///Port x configuration bits (y =
///0..15)
ot8: u1 = 0,
///OT9 [9:9]
///Port x configuration bits (y =
///0..15)
ot9: u1 = 0,
///OT10 [10:10]
///Port x configuration bits (y =
///0..15)
ot10: u1 = 0,
///OT11 [11:11]
///Port x configuration bits (y =
///0..15)
ot11: u1 = 0,
///OT12 [12:12]
///Port x configuration bits (y =
///0..15)
ot12: u1 = 0,
///OT13 [13:13]
///Port x configuration bits (y =
///0..15)
ot13: u1 = 0,
///OT14 [14:14]
///Port x configuration bits (y =
///0..15)
ot14: u1 = 0,
///OT15 [15:15]
///Port x configuration bits (y =
///0..15)
ot15: packed enum(u1) {
///Output push-pull (reset state)
push_pull = 0,
///Output open-drain
open_drain = 1,
} = .push_pull,
_unused16: u16 = 0,
};
///GPIO port output type register
pub const otyper = Register(otyper_val).init(0x48000000 + 0x4);
//////////////////////////
///OSPEEDR
const ospeedr_val = packed struct {
///OSPEEDR0 [0:1]
///Port x configuration bits (y =
///0..15)
ospeedr0: u2 = 0,
///OSPEEDR1 [2:3]
///Port x configuration bits (y =
///0..15)
ospeedr1: u2 = 0,
///OSPEEDR2 [4:5]
///Port x configuration bits (y =
///0..15)
ospeedr2: u2 = 0,
///OSPEEDR3 [6:7]
///Port x configuration bits (y =
///0..15)
ospeedr3: u2 = 0,
///OSPEEDR4 [8:9]
///Port x configuration bits (y =
///0..15)
ospeedr4: u2 = 0,
///OSPEEDR5 [10:11]
///Port x configuration bits (y =
///0..15)
ospeedr5: u2 = 0,
///OSPEEDR6 [12:13]
///Port x configuration bits (y =
///0..15)
ospeedr6: u2 = 0,
///OSPEEDR7 [14:15]
///Port x configuration bits (y =
///0..15)
ospeedr7: u2 = 0,
///OSPEEDR8 [16:17]
///Port x configuration bits (y =
///0..15)
ospeedr8: u2 = 0,
///OSPEEDR9 [18:19]
///Port x configuration bits (y =
///0..15)
ospeedr9: u2 = 0,
///OSPEEDR10 [20:21]
///Port x configuration bits (y =
///0..15)
ospeedr10: u2 = 0,
///OSPEEDR11 [22:23]
///Port x configuration bits (y =
///0..15)
ospeedr11: u2 = 0,
///OSPEEDR12 [24:25]
///Port x configuration bits (y =
///0..15)
ospeedr12: u2 = 0,
///OSPEEDR13 [26:27]
///Port x configuration bits (y =
///0..15)
ospeedr13: u2 = 0,
///OSPEEDR14 [28:29]
///Port x configuration bits (y =
///0..15)
ospeedr14: u2 = 0,
///OSPEEDR15 [30:31]
///Port x configuration bits (y =
///0..15)
ospeedr15: packed enum(u2) {
///Low speed
low_speed = 0,
///Medium speed
medium_speed = 1,
///High speed
high_speed = 2,
///Very high speed
very_high_speed = 3,
} = .low_speed,
};
///GPIO port output speed
///register
pub const ospeedr = Register(ospeedr_val).init(0x48000000 + 0x8);
//////////////////////////
///PUPDR
const pupdr_val = packed struct {
///PUPDR0 [0:1]
///Port x configuration bits (y =
///0..15)
pupdr0: u2 = 0,
///PUPDR1 [2:3]
///Port x configuration bits (y =
///0..15)
pupdr1: u2 = 0,
///PUPDR2 [4:5]
///Port x configuration bits (y =
///0..15)
pupdr2: u2 = 0,
///PUPDR3 [6:7]
///Port x configuration bits (y =
///0..15)
pupdr3: u2 = 0,
///PUPDR4 [8:9]
///Port x configuration bits (y =
///0..15)
pupdr4: u2 = 0,
///PUPDR5 [10:11]
///Port x configuration bits (y =
///0..15)
pupdr5: u2 = 0,
///PUPDR6 [12:13]
///Port x configuration bits (y =
///0..15)
pupdr6: u2 = 0,
///PUPDR7 [14:15]
///Port x configuration bits (y =
///0..15)
pupdr7: u2 = 0,
///PUPDR8 [16:17]
///Port x configuration bits (y =
///0..15)
pupdr8: u2 = 0,
///PUPDR9 [18:19]
///Port x configuration bits (y =
///0..15)
pupdr9: u2 = 0,
///PUPDR10 [20:21]
///Port x configuration bits (y =
///0..15)
pupdr10: u2 = 0,
///PUPDR11 [22:23]
///Port x configuration bits (y =
///0..15)
pupdr11: u2 = 0,
///PUPDR12 [24:25]
///Port x configuration bits (y =
///0..15)
pupdr12: u2 = 0,
///PUPDR13 [26:27]
///Port x configuration bits (y =
///0..15)
pupdr13: u2 = 1,
///PUPDR14 [28:29]
///Port x configuration bits (y =
///0..15)
pupdr14: u2 = 2,
///PUPDR15 [30:31]
///Port x configuration bits (y =
///0..15)
pupdr15: packed enum(u2) {
///No pull-up, pull-down
floating = 0,
///Pull-up
pull_up = 1,
///Pull-down
pull_down = 2,
} = .floating,
};
///GPIO port pull-up/pull-down
///register
pub const pupdr = Register(pupdr_val).init(0x48000000 + 0xC);
//////////////////////////
///IDR
const idr_val = packed struct {
///IDR0 [0:0]
///Port input data (y =
///0..15)
idr0: u1 = 0,
///IDR1 [1:1]
///Port input data (y =
///0..15)
idr1: u1 = 0,
///IDR2 [2:2]
///Port input data (y =
///0..15)
idr2: u1 = 0,
///IDR3 [3:3]
///Port input data (y =
///0..15)
idr3: u1 = 0,
///IDR4 [4:4]
///Port input data (y =
///0..15)
idr4: u1 = 0,
///IDR5 [5:5]
///Port input data (y =
///0..15)
idr5: u1 = 0,
///IDR6 [6:6]
///Port input data (y =
///0..15)
idr6: u1 = 0,
///IDR7 [7:7]
///Port input data (y =
///0..15)
idr7: u1 = 0,
///IDR8 [8:8]
///Port input data (y =
///0..15)
idr8: u1 = 0,
///IDR9 [9:9]
///Port input data (y =
///0..15)
idr9: u1 = 0,
///IDR10 [10:10]
///Port input data (y =
///0..15)
idr10: u1 = 0,
///IDR11 [11:11]
///Port input data (y =
///0..15)
idr11: u1 = 0,
///IDR12 [12:12]
///Port input data (y =
///0..15)
idr12: u1 = 0,
///IDR13 [13:13]
///Port input data (y =
///0..15)
idr13: u1 = 0,
///IDR14 [14:14]
///Port input data (y =
///0..15)
idr14: u1 = 0,
///IDR15 [15:15]
///Port input data (y =
///0..15)
idr15: packed enum(u1) {
///Input is logic high
high = 1,
///Input is logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port input data register
pub const idr = RegisterRW(idr_val, void).init(0x48000000 + 0x10);
//////////////////////////
///ODR
const odr_val = packed struct {
///ODR0 [0:0]
///Port output data (y =
///0..15)
odr0: u1 = 0,
///ODR1 [1:1]
///Port output data (y =
///0..15)
odr1: u1 = 0,
///ODR2 [2:2]
///Port output data (y =
///0..15)
odr2: u1 = 0,
///ODR3 [3:3]
///Port output data (y =
///0..15)
odr3: u1 = 0,
///ODR4 [4:4]
///Port output data (y =
///0..15)
odr4: u1 = 0,
///ODR5 [5:5]
///Port output data (y =
///0..15)
odr5: u1 = 0,
///ODR6 [6:6]
///Port output data (y =
///0..15)
odr6: u1 = 0,
///ODR7 [7:7]
///Port output data (y =
///0..15)
odr7: u1 = 0,
///ODR8 [8:8]
///Port output data (y =
///0..15)
odr8: u1 = 0,
///ODR9 [9:9]
///Port output data (y =
///0..15)
odr9: u1 = 0,
///ODR10 [10:10]
///Port output data (y =
///0..15)
odr10: u1 = 0,
///ODR11 [11:11]
///Port output data (y =
///0..15)
odr11: u1 = 0,
///ODR12 [12:12]
///Port output data (y =
///0..15)
odr12: u1 = 0,
///ODR13 [13:13]
///Port output data (y =
///0..15)
odr13: u1 = 0,
///ODR14 [14:14]
///Port output data (y =
///0..15)
odr14: u1 = 0,
///ODR15 [15:15]
///Port output data (y =
///0..15)
odr15: packed enum(u1) {
///Set output to logic high
high = 1,
///Set output to logic low
low = 0,
} = .low,
_unused16: u16 = 0,
};
///GPIO port output data register
pub const odr = Register(odr_val).init(0x48000000 + 0x14);
//////////////////////////
///BSRR
const bsrr_val = packed struct {
///BS0 [0:0]
///Port x set bit y (y=
///0..15)
bs0: u1 = 0,
///BS1 [1:1]
///Port x set bit y (y=
///0..15)
bs1: u1 = 0,
///BS2 [2:2]
///Port x set bit y (y=
///0..15)
bs2: u1 = 0,
///BS3 [3:3]
///Port x set bit y (y=
///0..15)
bs3: u1 = 0,
///BS4 [4:4]
///Port x set bit y (y=
///0..15)
bs4: u1 = 0,
///BS5 [5:5]
///Port x set bit y (y=
///0..15)
bs5: u1 = 0,
///BS6 [6:6]
///Port x set bit y (y=
///0..15)
bs6: u1 = 0,
///BS7 [7:7]
///Port x set bit y (y=
///0..15)
bs7: u1 = 0,
///BS8 [8:8]
///Port x set bit y (y=
///0..15)
bs8: u1 = 0,
///BS9 [9:9]
///Port x set bit y (y=
///0..15)
bs9: u1 = 0,
///BS10 [10:10]
///Port x set bit y (y=
///0..15)
bs10: u1 = 0,
///BS11 [11:11]
///Port x set bit y (y=
///0..15)
bs11: u1 = 0,
///BS12 [12:12]
///Port x set bit y (y=
///0..15)
bs12: u1 = 0,
///BS13 [13:13]
///Port x set bit y (y=
///0..15)
bs13: u1 = 0,
///BS14 [14:14]
///Port x set bit y (y=
///0..15)
bs14: u1 = 0,
///BS15 [15:15]
///Port x set bit y (y=
///0..15)
bs15: u1 = 0,
///BR0 [16:16]
///Port x set bit y (y=
///0..15)
br0: u1 = 0,
///BR1 [17:17]
///Port x reset bit y (y =
///0..15)
br1: u1 = 0,
///BR2 [18:18]
///Port x reset bit y (y =
///0..15)
br2: u1 = 0,
///BR3 [19:19]
///Port x reset bit y (y =
///0..15)
br3: u1 = 0,
///BR4 [20:20]
///Port x reset bit y (y =
///0..15)
br4: u1 = 0,
///BR5 [21:21]
///Port x reset bit y (y =
///0..15)
br5: u1 = 0,
///BR6 [22:22]
///Port x reset bit y (y =
///0..15)
br6: u1 = 0,
///BR7 [23:23]
///Port x reset bit y (y =
///0..15)
br7: u1 = 0,
///BR8 [24:24]
///Port x reset bit y (y =
///0..15)
br8: u1 = 0,
///BR9 [25:25]
///Port x reset bit y (y =
///0..15)
br9: u1 = 0,
///BR10 [26:26]
///Port x reset bit y (y =
///0..15)
br10: u1 = 0,
///BR11 [27:27]
///Port x reset bit y (y =
///0..15)
br11: u1 = 0,
///BR12 [28:28]
///Port x reset bit y (y =
///0..15)
br12: u1 = 0,
///BR13 [29:29]
///Port x reset bit y (y =
///0..15)
br13: u1 = 0,
///BR14 [30:30]
///Port x reset bit y (y =
///0..15)
br14: u1 = 0,
///BR15 [31:31]
///Port x reset bit y (y =
///0..15)
br15: u1 = 0,
};
///GPIO port bit set/reset
///register
pub const bsrr = RegisterRW(void, bsrr_val).init(0x48000000 + 0x18);
//////////////////////////
///LCKR
const lckr_val = packed struct {
///LCK0 [0:0]
///Port x lock bit y (y=
///0..15)
lck0: u1 = 0,
///LCK1 [1:1]
///Port x lock bit y (y=
///0..15)
lck1: u1 = 0,
///LCK2 [2:2]
///Port x lock bit y (y=
///0..15)
lck2: u1 = 0,
///LCK3 [3:3]
///Port x lock bit y (y=
///0..15)
lck3: u1 = 0,
///LCK4 [4:4]
///Port x lock bit y (y=
///0..15)
lck4: u1 = 0,
///LCK5 [5:5]
///Port x lock bit y (y=
///0..15)
lck5: u1 = 0,
///LCK6 [6:6]
///Port x lock bit y (y=
///0..15)
lck6: u1 = 0,
///LCK7 [7:7]
///Port x lock bit y (y=
///0..15)
lck7: u1 = 0,
///LCK8 [8:8]
///Port x lock bit y (y=
///0..15)
lck8: u1 = 0,
///LCK9 [9:9]
///Port x lock bit y (y=
///0..15)
lck9: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCK10 [10:10]
///Port x lock bit y (y=
///0..15)
lck10: u1 = 0,
///LCK11 [11:11]
///Port x lock bit y (y=
///0..15)
lck11: u1 = 0,
///LCK12 [12:12]
///Port x lock bit y (y=
///0..15)
lck12: u1 = 0,
///LCK13 [13:13]
///Port x lock bit y (y=
///0..15)
lck13: u1 = 0,
///LCK14 [14:14]
///Port x lock bit y (y=
///0..15)
lck14: u1 = 0,
///LCK15 [15:15]
///Port x lock bit y (y=
///0..15)
lck15: packed enum(u1) {
///Port configuration not locked
unlocked = 0,
///Port configuration locked
locked = 1,
} = .unlocked,
///LCKK [16:16]
///Port x lock bit y (y=
///0..15)
lckk: packed enum(u1) {
///Port configuration lock key not active
not_active = 0,
///Port configuration lock key active
active = 1,
} = .not_active,
_unused17: u15 = 0,
};
///GPIO port configuration lock
///register
pub const lckr = Register(lckr_val).init(0x48000000 + 0x1C);
//////////////////////////
///AFRL
const afrl_val = packed struct {
///AFRL0 [0:3]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl0: u4 = 0,
///AFRL1 [4:7]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl1: u4 = 0,
///AFRL2 [8:11]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl2: u4 = 0,
///AFRL3 [12:15]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl3: u4 = 0,
///AFRL4 [16:19]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl4: u4 = 0,
///AFRL5 [20:23]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl5: u4 = 0,
///AFRL6 [24:27]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl6: u4 = 0,
///AFRL7 [28:31]
///Alternate function selection for port x
///bit y (y = 0..7)
afrl7: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function low
///register
pub const afrl = Register(afrl_val).init(0x48000000 + 0x20);
//////////////////////////
///AFRH
const afrh_val = packed struct {
///AFRH8 [0:3]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh8: u4 = 0,
///AFRH9 [4:7]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh9: u4 = 0,
///AFRH10 [8:11]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh10: u4 = 0,
///AFRH11 [12:15]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh11: u4 = 0,
///AFRH12 [16:19]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh12: u4 = 0,
///AFRH13 [20:23]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh13: u4 = 0,
///AFRH14 [24:27]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh14: u4 = 0,
///AFRH15 [28:31]
///Alternate function selection for port x
///bit y (y = 8..15)
afrh15: packed enum(u4) {
///AF0
af0 = 0,
///AF1
af1 = 1,
///AF2
af2 = 2,
///AF3
af3 = 3,
///AF4
af4 = 4,
///AF5
af5 = 5,
///AF6
af6 = 6,
///AF7
af7 = 7,
///AF8
af8 = 8,
///AF9
af9 = 9,
///AF10
af10 = 10,
///AF11
af11 = 11,
///AF12
af12 = 12,
///AF13
af13 = 13,
///AF14
af14 = 14,
///AF15
af15 = 15,
} = .af0,
};
///GPIO alternate function high
///register
pub const afrh = Register(afrh_val).init(0x48000000 + 0x24);
//////////////////////////
///BRR
const brr_val = packed struct {
///BR0 [0:0]
///Port x Reset bit y
br0: u1 = 0,
///BR1 [1:1]
///Port x Reset bit y
br1: u1 = 0,
///BR2 [2:2]
///Port x Reset bit y
br2: u1 = 0,
///BR3 [3:3]
///Port x Reset bit y
br3: u1 = 0,
///BR4 [4:4]
///Port x Reset bit y
br4: u1 = 0,
///BR5 [5:5]
///Port x Reset bit y
br5: u1 = 0,
///BR6 [6:6]
///Port x Reset bit y
br6: u1 = 0,
///BR7 [7:7]
///Port x Reset bit y
br7: u1 = 0,
///BR8 [8:8]
///Port x Reset bit y
br8: u1 = 0,
///BR9 [9:9]
///Port x Reset bit y
br9: u1 = 0,
///BR10 [10:10]
///Port x Reset bit y
br10: u1 = 0,
///BR11 [11:11]
///Port x Reset bit y
br11: u1 = 0,
///BR12 [12:12]
///Port x Reset bit y
br12: u1 = 0,
///BR13 [13:13]
///Port x Reset bit y
br13: u1 = 0,
///BR14 [14:14]
///Port x Reset bit y
br14: u1 = 0,
///BR15 [15:15]
///Port x Reset bit y
br15: u1 = 0,
_unused16: u16 = 0,
};
///Port bit reset register
pub const brr = RegisterRW(void, brr_val).init(0x48000000 + 0x28);
};
///Serial peripheral interface
pub const spi1 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CPHA [0:0]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first_edge = 0,
///The second clock transition is the first data capture edge
second_edge = 1,
} = .first_edge,
///CPOL [1:1]
///Clock polarity
cpol: packed enum(u1) {
///CK to 0 when idle
idle_low = 0,
///CK to 1 when idle
idle_high = 1,
} = .idle_low,
///MSTR [2:2]
///Master selection
mstr: packed enum(u1) {
///Slave configuration
slave = 0,
///Master configuration
master = 1,
} = .slave,
///BR [3:5]
///Baud rate control
br: packed enum(u3) {
///f_PCLK / 2
div2 = 0,
///f_PCLK / 4
div4 = 1,
///f_PCLK / 8
div8 = 2,
///f_PCLK / 16
div16 = 3,
///f_PCLK / 32
div32 = 4,
///f_PCLK / 64
div64 = 5,
///f_PCLK / 128
div128 = 6,
///f_PCLK / 256
div256 = 7,
} = .div2,
///SPE [6:6]
///SPI enable
spe: packed enum(u1) {
///Peripheral disabled
disabled = 0,
///Peripheral enabled
enabled = 1,
} = .disabled,
///LSBFIRST [7:7]
///Frame format
lsbfirst: packed enum(u1) {
///Data is transmitted/received with the MSB first
msbfirst = 0,
///Data is transmitted/received with the LSB first
lsbfirst = 1,
} = .msbfirst,
///SSI [8:8]
///Internal slave select
ssi: packed enum(u1) {
///0 is forced onto the NSS pin and the I/O value of the NSS pin is ignored
slave_selected = 0,
///1 is forced onto the NSS pin and the I/O value of the NSS pin is ignored
slave_not_selected = 1,
} = .slave_selected,
///SSM [9:9]
///Software slave management
ssm: packed enum(u1) {
///Software slave management disabled
disabled = 0,
///Software slave management enabled
enabled = 1,
} = .disabled,
///RXONLY [10:10]
///Receive only
rxonly: packed enum(u1) {
///Full duplex (Transmit and receive)
full_duplex = 0,
///Output disabled (Receive-only mode)
output_disabled = 1,
} = .full_duplex,
///CRCL [11:11]
///CRC length
crcl: packed enum(u1) {
///8-bit CRC length
eight_bit = 0,
///16-bit CRC length
sixteen_bit = 1,
} = .eight_bit,
///CRCNEXT [12:12]
///CRC transfer next
crcnext: packed enum(u1) {
///Next transmit value is from Tx buffer
tx_buffer = 0,
///Next transmit value is from Tx CRC register
crc = 1,
} = .tx_buffer,
///CRCEN [13:13]
///Hardware CRC calculation
///enable
crcen: packed enum(u1) {
///CRC calculation disabled
disabled = 0,
///CRC calculation enabled
enabled = 1,
} = .disabled,
///BIDIOE [14:14]
///Output enable in bidirectional
///mode
bidioe: packed enum(u1) {
///Output disabled (receive-only mode)
output_disabled = 0,
///Output enabled (transmit-only mode)
output_enabled = 1,
} = .output_disabled,
///BIDIMODE [15:15]
///Bidirectional data mode
///enable
bidimode: packed enum(u1) {
///2-line unidirectional data mode selected
unidirectional = 0,
///1-line bidirectional data mode selected
bidirectional = 1,
} = .unidirectional,
_unused16: u16 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40013000 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///RXDMAEN [0:0]
///Rx buffer DMA enable
rxdmaen: packed enum(u1) {
///Rx buffer DMA disabled
disabled = 0,
///Rx buffer DMA enabled
enabled = 1,
} = .disabled,
///TXDMAEN [1:1]
///Tx buffer DMA enable
txdmaen: packed enum(u1) {
///Tx buffer DMA disabled
disabled = 0,
///Tx buffer DMA enabled
enabled = 1,
} = .disabled,
///SSOE [2:2]
///SS output enable
ssoe: packed enum(u1) {
///SS output is disabled in master mode
disabled = 0,
///SS output is enabled in master mode
enabled = 1,
} = .disabled,
///NSSP [3:3]
///NSS pulse management
nssp: packed enum(u1) {
///No NSS pulse
no_pulse = 0,
///NSS pulse generated
pulse_generated = 1,
} = .no_pulse,
///FRF [4:4]
///Frame format
frf: packed enum(u1) {
///SPI Motorola mode
motorola = 0,
///SPI TI mode
ti = 1,
} = .motorola,
///ERRIE [5:5]
///Error interrupt enable
errie: packed enum(u1) {
///Error interrupt masked
masked = 0,
///Error interrupt not masked
not_masked = 1,
} = .masked,
///RXNEIE [6:6]
///RX buffer not empty interrupt
///enable
rxneie: packed enum(u1) {
///RXE interrupt masked
masked = 0,
///RXE interrupt not masked
not_masked = 1,
} = .masked,
///TXEIE [7:7]
///Tx buffer empty interrupt
///enable
txeie: packed enum(u1) {
///TXE interrupt masked
masked = 0,
///TXE interrupt not masked
not_masked = 1,
} = .masked,
///DS [8:11]
///Data size
ds: packed enum(u4) {
///4-bit
four_bit = 3,
///5-bit
five_bit = 4,
///6-bit
six_bit = 5,
///7-bit
seven_bit = 6,
///8-bit
eight_bit = 7,
///9-bit
nine_bit = 8,
///10-bit
ten_bit = 9,
///11-bit
eleven_bit = 10,
///12-bit
twelve_bit = 11,
///13-bit
thirteen_bit = 12,
///14-bit
fourteen_bit = 13,
///15-bit
fifteen_bit = 14,
///16-bit
sixteen_bit = 15,
_zero = 0,
} = ._zero,
///FRXTH [12:12]
///FIFO reception threshold
frxth: packed enum(u1) {
///RXNE event is generated if the FIFO level is greater than or equal to 1/2 (16-bit)
half = 0,
///RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit)
quarter = 1,
} = .half,
///LDMA_RX [13:13]
///Last DMA transfer for
///reception
ldma_rx: packed enum(u1) {
///Number of data to transfer for receive is even
even = 0,
///Number of data to transfer for receive is odd
odd = 1,
} = .even,
///LDMA_TX [14:14]
///Last DMA transfer for
///transmission
ldma_tx: packed enum(u1) {
///Number of data to transfer for transmit is even
even = 0,
///Number of data to transfer for transmit is odd
odd = 1,
} = .even,
_unused15: u17 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40013000 + 0x4);
//////////////////////////
///SR
const sr_val_read = packed struct {
///RXNE [0:0]
///Receive buffer not empty
rxne: u1 = 0,
///TXE [1:1]
///Transmit buffer empty
txe: u1 = 1,
_unused2: u2 = 0,
///CRCERR [4:4]
///CRC error flag
crcerr: u1 = 0,
///MODF [5:5]
///Mode fault
modf: packed enum(u1) {
///No mode fault occurred
no_fault = 0,
///Mode fault occurred
fault = 1,
} = .no_fault,
///OVR [6:6]
///Overrun flag
ovr: packed enum(u1) {
///No overrun occurred
no_overrun = 0,
///Overrun occurred
overrun = 1,
} = .no_overrun,
///BSY [7:7]
///Busy flag
bsy: packed enum(u1) {
///SPI not busy
not_busy = 0,
///SPI busy
busy = 1,
} = .not_busy,
///FRE [8:8]
///Frame format error
fre: packed enum(u1) {
///No frame format error
no_error = 0,
///A frame format error occurred
_error = 1,
} = .no_error,
///FRLVL [9:10]
///FIFO reception level
frlvl: packed enum(u2) {
///Rx FIFO Empty
empty = 0,
///Rx 1/4 FIFO
quarter = 1,
///Rx 1/2 FIFO
half = 2,
///Rx FIFO full
full = 3,
} = .empty,
///FTLVL [11:12]
///FIFO transmission level
ftlvl: packed enum(u2) {
///Tx FIFO Empty
empty = 0,
///Tx 1/4 FIFO
quarter = 1,
///Tx 1/2 FIFO
half = 2,
///Tx FIFO full
full = 3,
} = .empty,
_unused13: u19 = 0,
};
const sr_val_write = packed struct {
///RXNE [0:0]
///Receive buffer not empty
rxne: u1 = 0,
///TXE [1:1]
///Transmit buffer empty
txe: u1 = 1,
_unused2: u2 = 0,
///CRCERR [4:4]
///CRC error flag
crcerr: u1 = 0,
///MODF [5:5]
///Mode fault
modf: u1 = 0,
///OVR [6:6]
///Overrun flag
ovr: u1 = 0,
///BSY [7:7]
///Busy flag
bsy: u1 = 0,
///FRE [8:8]
///Frame format error
fre: u1 = 0,
///FRLVL [9:10]
///FIFO reception level
frlvl: u2 = 0,
///FTLVL [11:12]
///FIFO transmission level
ftlvl: u2 = 0,
_unused13: u19 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40013000 + 0x8);
//////////////////////////
///DR
const dr_val = packed struct {
///DR [0:15]
///Data register
dr: u16 = 0,
_unused16: u16 = 0,
};
///data register
pub const dr = Register(dr_val).init(0x40013000 + 0xC);
//////////////////////////
///CRCPR
const crcpr_val = packed struct {
///CRCPOLY [0:15]
///CRC polynomial register
crcpoly: u16 = 7,
_unused16: u16 = 0,
};
///CRC polynomial register
pub const crcpr = Register(crcpr_val).init(0x40013000 + 0x10);
//////////////////////////
///RXCRCR
const rxcrcr_val = packed struct {
///RxCRC [0:15]
///Rx CRC register
rx_crc: u16 = 0,
_unused16: u16 = 0,
};
///RX CRC register
pub const rxcrcr = RegisterRW(rxcrcr_val, void).init(0x40013000 + 0x14);
//////////////////////////
///TXCRCR
const txcrcr_val = packed struct {
///TxCRC [0:15]
///Tx CRC register
tx_crc: u16 = 0,
_unused16: u16 = 0,
};
///TX CRC register
pub const txcrcr = RegisterRW(txcrcr_val, void).init(0x40013000 + 0x18);
//////////////////////////
///I2SCFGR
const i2scfgr_val = packed struct {
///CHLEN [0:0]
///Channel length (number of bits per audio
///channel)
chlen: packed enum(u1) {
///16-bit wide
sixteen_bit = 0,
///32-bit wide
thirty_two_bit = 1,
} = .sixteen_bit,
///DATLEN [1:2]
///Data length to be
///transferred
datlen: packed enum(u2) {
///16-bit data length
sixteen_bit = 0,
///24-bit data length
twenty_four_bit = 1,
///32-bit data length
thirty_two_bit = 2,
} = .sixteen_bit,
///CKPOL [3:3]
///Steady state clock
///polarity
ckpol: packed enum(u1) {
///I2S clock inactive state is low level
idle_low = 0,
///I2S clock inactive state is high level
idle_high = 1,
} = .idle_low,
///I2SSTD [4:5]
///I2S standard selection
i2sstd: packed enum(u2) {
///I2S Philips standard
philips = 0,
///MSB justified standard
msb = 1,
///LSB justified standard
lsb = 2,
///PCM standard
pcm = 3,
} = .philips,
_unused6: u1 = 0,
///PCMSYNC [7:7]
///PCM frame synchronization
pcmsync: packed enum(u1) {
///Short frame synchronisation
short = 0,
///Long frame synchronisation
long = 1,
} = .short,
///I2SCFG [8:9]
///I2S configuration mode
i2scfg: packed enum(u2) {
///Slave - transmit
slave_tx = 0,
///Slave - receive
slave_rx = 1,
///Master - transmit
master_tx = 2,
///Master - receive
master_rx = 3,
} = .slave_tx,
///I2SE [10:10]
///I2S Enable
i2se: packed enum(u1) {
///I2S peripheral is disabled
disabled = 0,
///I2S peripheral is enabled
enabled = 1,
} = .disabled,
///I2SMOD [11:11]
///I2S mode selection
i2smod: packed enum(u1) {
///SPI mode is selected
spimode = 0,
///I2S mode is selected
i2smode = 1,
} = .spimode,
_unused12: u20 = 0,
};
///I2S configuration register
pub const i2scfgr = Register(i2scfgr_val).init(0x40013000 + 0x1C);
//////////////////////////
///I2SPR
const i2spr_val = packed struct {
///I2SDIV [0:7]
///I2S Linear prescaler
i2sdiv: u8 = 16,
///ODD [8:8]
///Odd factor for the
///prescaler
odd: packed enum(u1) {
///Real divider value is I2SDIV * 2
even = 0,
///Real divider value is (I2SDIV * 2) + 1
odd = 1,
} = .even,
///MCKOE [9:9]
///Master clock output enable
mckoe: packed enum(u1) {
///Master clock output is disabled
disabled = 0,
///Master clock output is enabled
enabled = 1,
} = .disabled,
_unused10: u22 = 0,
};
///I2S prescaler register
pub const i2spr = Register(i2spr_val).init(0x40013000 + 0x20);
};
///Serial peripheral interface
pub const spi2 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CPHA [0:0]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first_edge = 0,
///The second clock transition is the first data capture edge
second_edge = 1,
} = .first_edge,
///CPOL [1:1]
///Clock polarity
cpol: packed enum(u1) {
///CK to 0 when idle
idle_low = 0,
///CK to 1 when idle
idle_high = 1,
} = .idle_low,
///MSTR [2:2]
///Master selection
mstr: packed enum(u1) {
///Slave configuration
slave = 0,
///Master configuration
master = 1,
} = .slave,
///BR [3:5]
///Baud rate control
br: packed enum(u3) {
///f_PCLK / 2
div2 = 0,
///f_PCLK / 4
div4 = 1,
///f_PCLK / 8
div8 = 2,
///f_PCLK / 16
div16 = 3,
///f_PCLK / 32
div32 = 4,
///f_PCLK / 64
div64 = 5,
///f_PCLK / 128
div128 = 6,
///f_PCLK / 256
div256 = 7,
} = .div2,
///SPE [6:6]
///SPI enable
spe: packed enum(u1) {
///Peripheral disabled
disabled = 0,
///Peripheral enabled
enabled = 1,
} = .disabled,
///LSBFIRST [7:7]
///Frame format
lsbfirst: packed enum(u1) {
///Data is transmitted/received with the MSB first
msbfirst = 0,
///Data is transmitted/received with the LSB first
lsbfirst = 1,
} = .msbfirst,
///SSI [8:8]
///Internal slave select
ssi: packed enum(u1) {
///0 is forced onto the NSS pin and the I/O value of the NSS pin is ignored
slave_selected = 0,
///1 is forced onto the NSS pin and the I/O value of the NSS pin is ignored
slave_not_selected = 1,
} = .slave_selected,
///SSM [9:9]
///Software slave management
ssm: packed enum(u1) {
///Software slave management disabled
disabled = 0,
///Software slave management enabled
enabled = 1,
} = .disabled,
///RXONLY [10:10]
///Receive only
rxonly: packed enum(u1) {
///Full duplex (Transmit and receive)
full_duplex = 0,
///Output disabled (Receive-only mode)
output_disabled = 1,
} = .full_duplex,
///CRCL [11:11]
///CRC length
crcl: packed enum(u1) {
///8-bit CRC length
eight_bit = 0,
///16-bit CRC length
sixteen_bit = 1,
} = .eight_bit,
///CRCNEXT [12:12]
///CRC transfer next
crcnext: packed enum(u1) {
///Next transmit value is from Tx buffer
tx_buffer = 0,
///Next transmit value is from Tx CRC register
crc = 1,
} = .tx_buffer,
///CRCEN [13:13]
///Hardware CRC calculation
///enable
crcen: packed enum(u1) {
///CRC calculation disabled
disabled = 0,
///CRC calculation enabled
enabled = 1,
} = .disabled,
///BIDIOE [14:14]
///Output enable in bidirectional
///mode
bidioe: packed enum(u1) {
///Output disabled (receive-only mode)
output_disabled = 0,
///Output enabled (transmit-only mode)
output_enabled = 1,
} = .output_disabled,
///BIDIMODE [15:15]
///Bidirectional data mode
///enable
bidimode: packed enum(u1) {
///2-line unidirectional data mode selected
unidirectional = 0,
///1-line bidirectional data mode selected
bidirectional = 1,
} = .unidirectional,
_unused16: u16 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40003800 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///RXDMAEN [0:0]
///Rx buffer DMA enable
rxdmaen: packed enum(u1) {
///Rx buffer DMA disabled
disabled = 0,
///Rx buffer DMA enabled
enabled = 1,
} = .disabled,
///TXDMAEN [1:1]
///Tx buffer DMA enable
txdmaen: packed enum(u1) {
///Tx buffer DMA disabled
disabled = 0,
///Tx buffer DMA enabled
enabled = 1,
} = .disabled,
///SSOE [2:2]
///SS output enable
ssoe: packed enum(u1) {
///SS output is disabled in master mode
disabled = 0,
///SS output is enabled in master mode
enabled = 1,
} = .disabled,
///NSSP [3:3]
///NSS pulse management
nssp: packed enum(u1) {
///No NSS pulse
no_pulse = 0,
///NSS pulse generated
pulse_generated = 1,
} = .no_pulse,
///FRF [4:4]
///Frame format
frf: packed enum(u1) {
///SPI Motorola mode
motorola = 0,
///SPI TI mode
ti = 1,
} = .motorola,
///ERRIE [5:5]
///Error interrupt enable
errie: packed enum(u1) {
///Error interrupt masked
masked = 0,
///Error interrupt not masked
not_masked = 1,
} = .masked,
///RXNEIE [6:6]
///RX buffer not empty interrupt
///enable
rxneie: packed enum(u1) {
///RXE interrupt masked
masked = 0,
///RXE interrupt not masked
not_masked = 1,
} = .masked,
///TXEIE [7:7]
///Tx buffer empty interrupt
///enable
txeie: packed enum(u1) {
///TXE interrupt masked
masked = 0,
///TXE interrupt not masked
not_masked = 1,
} = .masked,
///DS [8:11]
///Data size
ds: packed enum(u4) {
///4-bit
four_bit = 3,
///5-bit
five_bit = 4,
///6-bit
six_bit = 5,
///7-bit
seven_bit = 6,
///8-bit
eight_bit = 7,
///9-bit
nine_bit = 8,
///10-bit
ten_bit = 9,
///11-bit
eleven_bit = 10,
///12-bit
twelve_bit = 11,
///13-bit
thirteen_bit = 12,
///14-bit
fourteen_bit = 13,
///15-bit
fifteen_bit = 14,
///16-bit
sixteen_bit = 15,
_zero = 0,
} = ._zero,
///FRXTH [12:12]
///FIFO reception threshold
frxth: packed enum(u1) {
///RXNE event is generated if the FIFO level is greater than or equal to 1/2 (16-bit)
half = 0,
///RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit)
quarter = 1,
} = .half,
///LDMA_RX [13:13]
///Last DMA transfer for
///reception
ldma_rx: packed enum(u1) {
///Number of data to transfer for receive is even
even = 0,
///Number of data to transfer for receive is odd
odd = 1,
} = .even,
///LDMA_TX [14:14]
///Last DMA transfer for
///transmission
ldma_tx: packed enum(u1) {
///Number of data to transfer for transmit is even
even = 0,
///Number of data to transfer for transmit is odd
odd = 1,
} = .even,
_unused15: u17 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40003800 + 0x4);
//////////////////////////
///SR
const sr_val_read = packed struct {
///RXNE [0:0]
///Receive buffer not empty
rxne: u1 = 0,
///TXE [1:1]
///Transmit buffer empty
txe: u1 = 1,
_unused2: u2 = 0,
///CRCERR [4:4]
///CRC error flag
crcerr: u1 = 0,
///MODF [5:5]
///Mode fault
modf: packed enum(u1) {
///No mode fault occurred
no_fault = 0,
///Mode fault occurred
fault = 1,
} = .no_fault,
///OVR [6:6]
///Overrun flag
ovr: packed enum(u1) {
///No overrun occurred
no_overrun = 0,
///Overrun occurred
overrun = 1,
} = .no_overrun,
///BSY [7:7]
///Busy flag
bsy: packed enum(u1) {
///SPI not busy
not_busy = 0,
///SPI busy
busy = 1,
} = .not_busy,
///FRE [8:8]
///Frame format error
fre: packed enum(u1) {
///No frame format error
no_error = 0,
///A frame format error occurred
_error = 1,
} = .no_error,
///FRLVL [9:10]
///FIFO reception level
frlvl: packed enum(u2) {
///Rx FIFO Empty
empty = 0,
///Rx 1/4 FIFO
quarter = 1,
///Rx 1/2 FIFO
half = 2,
///Rx FIFO full
full = 3,
} = .empty,
///FTLVL [11:12]
///FIFO transmission level
ftlvl: packed enum(u2) {
///Tx FIFO Empty
empty = 0,
///Tx 1/4 FIFO
quarter = 1,
///Tx 1/2 FIFO
half = 2,
///Tx FIFO full
full = 3,
} = .empty,
_unused13: u19 = 0,
};
const sr_val_write = packed struct {
///RXNE [0:0]
///Receive buffer not empty
rxne: u1 = 0,
///TXE [1:1]
///Transmit buffer empty
txe: u1 = 1,
_unused2: u2 = 0,
///CRCERR [4:4]
///CRC error flag
crcerr: u1 = 0,
///MODF [5:5]
///Mode fault
modf: u1 = 0,
///OVR [6:6]
///Overrun flag
ovr: u1 = 0,
///BSY [7:7]
///Busy flag
bsy: u1 = 0,
///FRE [8:8]
///Frame format error
fre: u1 = 0,
///FRLVL [9:10]
///FIFO reception level
frlvl: u2 = 0,
///FTLVL [11:12]
///FIFO transmission level
ftlvl: u2 = 0,
_unused13: u19 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40003800 + 0x8);
//////////////////////////
///DR
const dr_val = packed struct {
///DR [0:15]
///Data register
dr: u16 = 0,
_unused16: u16 = 0,
};
///data register
pub const dr = Register(dr_val).init(0x40003800 + 0xC);
//////////////////////////
///CRCPR
const crcpr_val = packed struct {
///CRCPOLY [0:15]
///CRC polynomial register
crcpoly: u16 = 7,
_unused16: u16 = 0,
};
///CRC polynomial register
pub const crcpr = Register(crcpr_val).init(0x40003800 + 0x10);
//////////////////////////
///RXCRCR
const rxcrcr_val = packed struct {
///RxCRC [0:15]
///Rx CRC register
rx_crc: u16 = 0,
_unused16: u16 = 0,
};
///RX CRC register
pub const rxcrcr = RegisterRW(rxcrcr_val, void).init(0x40003800 + 0x14);
//////////////////////////
///TXCRCR
const txcrcr_val = packed struct {
///TxCRC [0:15]
///Tx CRC register
tx_crc: u16 = 0,
_unused16: u16 = 0,
};
///TX CRC register
pub const txcrcr = RegisterRW(txcrcr_val, void).init(0x40003800 + 0x18);
//////////////////////////
///I2SCFGR
const i2scfgr_val = packed struct {
///CHLEN [0:0]
///Channel length (number of bits per audio
///channel)
chlen: packed enum(u1) {
///16-bit wide
sixteen_bit = 0,
///32-bit wide
thirty_two_bit = 1,
} = .sixteen_bit,
///DATLEN [1:2]
///Data length to be
///transferred
datlen: packed enum(u2) {
///16-bit data length
sixteen_bit = 0,
///24-bit data length
twenty_four_bit = 1,
///32-bit data length
thirty_two_bit = 2,
} = .sixteen_bit,
///CKPOL [3:3]
///Steady state clock
///polarity
ckpol: packed enum(u1) {
///I2S clock inactive state is low level
idle_low = 0,
///I2S clock inactive state is high level
idle_high = 1,
} = .idle_low,
///I2SSTD [4:5]
///I2S standard selection
i2sstd: packed enum(u2) {
///I2S Philips standard
philips = 0,
///MSB justified standard
msb = 1,
///LSB justified standard
lsb = 2,
///PCM standard
pcm = 3,
} = .philips,
_unused6: u1 = 0,
///PCMSYNC [7:7]
///PCM frame synchronization
pcmsync: packed enum(u1) {
///Short frame synchronisation
short = 0,
///Long frame synchronisation
long = 1,
} = .short,
///I2SCFG [8:9]
///I2S configuration mode
i2scfg: packed enum(u2) {
///Slave - transmit
slave_tx = 0,
///Slave - receive
slave_rx = 1,
///Master - transmit
master_tx = 2,
///Master - receive
master_rx = 3,
} = .slave_tx,
///I2SE [10:10]
///I2S Enable
i2se: packed enum(u1) {
///I2S peripheral is disabled
disabled = 0,
///I2S peripheral is enabled
enabled = 1,
} = .disabled,
///I2SMOD [11:11]
///I2S mode selection
i2smod: packed enum(u1) {
///SPI mode is selected
spimode = 0,
///I2S mode is selected
i2smode = 1,
} = .spimode,
_unused12: u20 = 0,
};
///I2S configuration register
pub const i2scfgr = Register(i2scfgr_val).init(0x40003800 + 0x1C);
//////////////////////////
///I2SPR
const i2spr_val = packed struct {
///I2SDIV [0:7]
///I2S Linear prescaler
i2sdiv: u8 = 16,
///ODD [8:8]
///Odd factor for the
///prescaler
odd: packed enum(u1) {
///Real divider value is I2SDIV * 2
even = 0,
///Real divider value is (I2SDIV * 2) + 1
odd = 1,
} = .even,
///MCKOE [9:9]
///Master clock output enable
mckoe: packed enum(u1) {
///Master clock output is disabled
disabled = 0,
///Master clock output is enabled
enabled = 1,
} = .disabled,
_unused10: u22 = 0,
};
///I2S prescaler register
pub const i2spr = Register(i2spr_val).init(0x40003800 + 0x20);
};
///Power control
pub const pwr = struct {
//////////////////////////
///CR
const cr_val = packed struct {
///LPDS [0:0]
///Low-power deep sleep
lpds: u1 = 0,
///PDDS [1:1]
///Power down deepsleep
pdds: packed enum(u1) {
///Enter Stop mode when the CPU enters deepsleep
stop_mode = 0,
///Enter Standby mode when the CPU enters deepsleep
standby_mode = 1,
} = .stop_mode,
///CWUF [2:2]
///Clear wakeup flag
cwuf: u1 = 0,
///CSBF [3:3]
///Clear standby flag
csbf: u1 = 0,
_unused4: u4 = 0,
///DBP [8:8]
///Disable backup domain write
///protection
dbp: u1 = 0,
_unused9: u23 = 0,
};
///power control register
pub const cr = Register(cr_val).init(0x40007000 + 0x0);
//////////////////////////
///CSR
const csr_val = packed struct {
///WUF [0:0]
///Wakeup flag
wuf: u1 = 0,
///SBF [1:1]
///Standby flag
sbf: u1 = 0,
_unused2: u6 = 0,
///EWUP1 [8:8]
///Enable WKUP pin 1
ewup1: u1 = 0,
///EWUP2 [9:9]
///Enable WKUP pin 2
ewup2: u1 = 0,
_unused10: u1 = 0,
///EWUP4 [11:11]
///Enable WKUP pin 4
ewup4: u1 = 0,
///EWUP5 [12:12]
///Enable WKUP pin 5
ewup5: u1 = 0,
///EWUP6 [13:13]
///Enable WKUP pin 6
ewup6: u1 = 0,
///EWUP7 [14:14]
///Enable WKUP pin 7
ewup7: u1 = 0,
_unused15: u17 = 0,
};
///power control/status register
pub const csr = Register(csr_val).init(0x40007000 + 0x4);
};
///Inter-integrated circuit
pub const i2c1 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///PE [0:0]
///Peripheral enable
pe: packed enum(u1) {
///Peripheral disabled
disabled = 0,
///Peripheral enabled
enabled = 1,
} = .disabled,
///TXIE [1:1]
///TX Interrupt enable
txie: packed enum(u1) {
///Transmit (TXIS) interrupt disabled
disabled = 0,
///Transmit (TXIS) interrupt enabled
enabled = 1,
} = .disabled,
///RXIE [2:2]
///RX Interrupt enable
rxie: packed enum(u1) {
///Receive (RXNE) interrupt disabled
disabled = 0,
///Receive (RXNE) interrupt enabled
enabled = 1,
} = .disabled,
///ADDRIE [3:3]
///Address match interrupt enable (slave
///only)
addrie: packed enum(u1) {
///Address match (ADDR) interrupts disabled
disabled = 0,
///Address match (ADDR) interrupts enabled
enabled = 1,
} = .disabled,
///NACKIE [4:4]
///Not acknowledge received interrupt
///enable
nackie: packed enum(u1) {
///Not acknowledge (NACKF) received interrupts disabled
disabled = 0,
///Not acknowledge (NACKF) received interrupts enabled
enabled = 1,
} = .disabled,
///STOPIE [5:5]
///STOP detection Interrupt
///enable
stopie: packed enum(u1) {
///Stop detection (STOPF) interrupt disabled
disabled = 0,
///Stop detection (STOPF) interrupt enabled
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transfer Complete interrupt
///enable
tcie: packed enum(u1) {
///Transfer Complete interrupt disabled
disabled = 0,
///Transfer Complete interrupt enabled
enabled = 1,
} = .disabled,
///ERRIE [7:7]
///Error interrupts enable
errie: packed enum(u1) {
///Error detection interrupts disabled
disabled = 0,
///Error detection interrupts enabled
enabled = 1,
} = .disabled,
///DNF [8:11]
///Digital noise filter
dnf: packed enum(u4) {
///Digital filter disabled
no_filter = 0,
///Digital filter enabled and filtering capability up to 1 tI2CCLK
filter1 = 1,
///Digital filter enabled and filtering capability up to 2 tI2CCLK
filter2 = 2,
///Digital filter enabled and filtering capability up to 3 tI2CCLK
filter3 = 3,
///Digital filter enabled and filtering capability up to 4 tI2CCLK
filter4 = 4,
///Digital filter enabled and filtering capability up to 5 tI2CCLK
filter5 = 5,
///Digital filter enabled and filtering capability up to 6 tI2CCLK
filter6 = 6,
///Digital filter enabled and filtering capability up to 7 tI2CCLK
filter7 = 7,
///Digital filter enabled and filtering capability up to 8 tI2CCLK
filter8 = 8,
///Digital filter enabled and filtering capability up to 9 tI2CCLK
filter9 = 9,
///Digital filter enabled and filtering capability up to 10 tI2CCLK
filter10 = 10,
///Digital filter enabled and filtering capability up to 11 tI2CCLK
filter11 = 11,
///Digital filter enabled and filtering capability up to 12 tI2CCLK
filter12 = 12,
///Digital filter enabled and filtering capability up to 13 tI2CCLK
filter13 = 13,
///Digital filter enabled and filtering capability up to 14 tI2CCLK
filter14 = 14,
///Digital filter enabled and filtering capability up to 15 tI2CCLK
filter15 = 15,
} = .no_filter,
///ANFOFF [12:12]
///Analog noise filter OFF
anfoff: packed enum(u1) {
///Analog noise filter enabled
enabled = 0,
///Analog noise filter disabled
disabled = 1,
} = .enabled,
///SWRST [13:13]
///Software reset
swrst: u1 = 0,
///TXDMAEN [14:14]
///DMA transmission requests
///enable
txdmaen: packed enum(u1) {
///DMA mode disabled for transmission
disabled = 0,
///DMA mode enabled for transmission
enabled = 1,
} = .disabled,
///RXDMAEN [15:15]
///DMA reception requests
///enable
rxdmaen: packed enum(u1) {
///DMA mode disabled for reception
disabled = 0,
///DMA mode enabled for reception
enabled = 1,
} = .disabled,
///SBC [16:16]
///Slave byte control
sbc: packed enum(u1) {
///Slave byte control disabled
disabled = 0,
///Slave byte control enabled
enabled = 1,
} = .disabled,
///NOSTRETCH [17:17]
///Clock stretching disable
nostretch: packed enum(u1) {
///Clock stretching enabled
enabled = 0,
///Clock stretching disabled
disabled = 1,
} = .enabled,
///WUPEN [18:18]
///Wakeup from STOP enable
wupen: packed enum(u1) {
///Wakeup from Stop mode disabled
disabled = 0,
///Wakeup from Stop mode enabled
enabled = 1,
} = .disabled,
///GCEN [19:19]
///General call enable
gcen: packed enum(u1) {
///General call disabled. Address 0b00000000 is NACKed
disabled = 0,
///General call enabled. Address 0b00000000 is ACKed
enabled = 1,
} = .disabled,
///SMBHEN [20:20]
///SMBus Host address enable
smbhen: packed enum(u1) {
///Host address disabled. Address 0b0001000x is NACKed
disabled = 0,
///Host address enabled. Address 0b0001000x is ACKed
enabled = 1,
} = .disabled,
///SMBDEN [21:21]
///SMBus Device Default address
///enable
smbden: packed enum(u1) {
///Device default address disabled. Address 0b1100001x is NACKed
disabled = 0,
///Device default address enabled. Address 0b1100001x is ACKed
enabled = 1,
} = .disabled,
///ALERTEN [22:22]
///SMBUS alert enable
alerten: packed enum(u1) {
///In device mode (SMBHEN=Disabled) Releases SMBA pin high and Alert Response Address Header disabled (0001100x) followed by NACK. In host mode (SMBHEN=Enabled) SMBus Alert pin (SMBA) not supported
disabled = 0,
///In device mode (SMBHEN=Disabled) Drives SMBA pin low and Alert Response Address Header enabled (0001100x) followed by ACK.In host mode (SMBHEN=Enabled) SMBus Alert pin (SMBA) supported
enabled = 1,
} = .disabled,
///PECEN [23:23]
///PEC enable
pecen: packed enum(u1) {
///PEC calculation disabled
disabled = 0,
///PEC calculation enabled
enabled = 1,
} = .disabled,
_unused24: u8 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40005400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///SADD [0:9]
///Slave address bit 9:8 (master
///mode)
sadd: u10 = 0,
///RD_WRN [10:10]
///Transfer direction (master
///mode)
rd_wrn: packed enum(u1) {
///Master requests a write transfer
write = 0,
///Master requests a read transfer
read = 1,
} = .write,
///ADD10 [11:11]
///10-bit addressing mode (master
///mode)
add10: packed enum(u1) {
///The master operates in 7-bit addressing mode
bit7 = 0,
///The master operates in 10-bit addressing mode
bit10 = 1,
} = .bit7,
///HEAD10R [12:12]
///10-bit address header only read
///direction (master receiver mode)
head10r: packed enum(u1) {
///The master sends the complete 10 bit slave address read sequence
complete = 0,
///The master only sends the 1st 7 bits of the 10 bit address, followed by Read direction
partial = 1,
} = .complete,
///START [13:13]
///Start generation
start: packed enum(u1) {
///No Start generation
no_start = 0,
///Restart/Start generation
start = 1,
} = .no_start,
///STOP [14:14]
///Stop generation (master
///mode)
stop: packed enum(u1) {
///No Stop generation
no_stop = 0,
///Stop generation after current byte transfer
stop = 1,
} = .no_stop,
///NACK [15:15]
///NACK generation (slave
///mode)
nack: packed enum(u1) {
///an ACK is sent after current received byte
ack = 0,
///a NACK is sent after current received byte
nack = 1,
} = .ack,
///NBYTES [16:23]
///Number of bytes
nbytes: u8 = 0,
///RELOAD [24:24]
///NBYTES reload mode
reload: packed enum(u1) {
///The transfer is completed after the NBYTES data transfer (STOP or RESTART will follow)
completed = 0,
///The transfer is not completed after the NBYTES data transfer (NBYTES will be reloaded)
not_completed = 1,
} = .completed,
///AUTOEND [25:25]
///Automatic end mode (master
///mode)
autoend: packed enum(u1) {
///Software end mode: TC flag is set when NBYTES data are transferred, stretching SCL low
software = 0,
///Automatic end mode: a STOP condition is automatically sent when NBYTES data are transferred
automatic = 1,
} = .software,
///PECBYTE [26:26]
///Packet error checking byte
pecbyte: packed enum(u1) {
///No PEC transfer
no_pec = 0,
///PEC transmission/reception is requested
pec = 1,
} = .no_pec,
_unused27: u5 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40005400 + 0x4);
//////////////////////////
///OAR1
const oar1_val = packed struct {
///OA1 [0:9]
///Interface address
oa1: u10 = 0,
///OA1MODE [10:10]
///Own Address 1 10-bit mode
oa1mode: packed enum(u1) {
///Own address 1 is a 7-bit address
bit7 = 0,
///Own address 1 is a 10-bit address
bit10 = 1,
} = .bit7,
_unused11: u4 = 0,
///OA1EN [15:15]
///Own Address 1 enable
oa1en: packed enum(u1) {
///Own address 1 disabled. The received slave address OA1 is NACKed
disabled = 0,
///Own address 1 enabled. The received slave address OA1 is ACKed
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///Own address register 1
pub const oar1 = Register(oar1_val).init(0x40005400 + 0x8);
//////////////////////////
///OAR2
const oar2_val = packed struct {
_unused0: u1 = 0,
///OA2 [1:7]
///Interface address
oa2: u7 = 0,
///OA2MSK [8:10]
///Own Address 2 masks
oa2msk: packed enum(u3) {
///No mask
no_mask = 0,
///OA2[1] is masked and don’t care. Only OA2[7:2] are compared
mask1 = 1,
///OA2[2:1] are masked and don’t care. Only OA2[7:3] are compared
mask2 = 2,
///OA2[3:1] are masked and don’t care. Only OA2[7:4] are compared
mask3 = 3,
///OA2[4:1] are masked and don’t care. Only OA2[7:5] are compared
mask4 = 4,
///OA2[5:1] are masked and don’t care. Only OA2[7:6] are compared
mask5 = 5,
///OA2[6:1] are masked and don’t care. Only OA2[7] is compared.
mask6 = 6,
///OA2[7:1] are masked and don’t care. No comparison is done, and all (except reserved) 7-bit received addresses are acknowledged
mask7 = 7,
} = .no_mask,
_unused11: u4 = 0,
///OA2EN [15:15]
///Own Address 2 enable
oa2en: packed enum(u1) {
///Own address 2 disabled. The received slave address OA2 is NACKed
disabled = 0,
///Own address 2 enabled. The received slave address OA2 is ACKed
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///Own address register 2
pub const oar2 = Register(oar2_val).init(0x40005400 + 0xC);
//////////////////////////
///TIMINGR
const timingr_val = packed struct {
///SCLL [0:7]
///SCL low period (master
///mode)
scll: u8 = 0,
///SCLH [8:15]
///SCL high period (master
///mode)
sclh: u8 = 0,
///SDADEL [16:19]
///Data hold time
sdadel: u4 = 0,
///SCLDEL [20:23]
///Data setup time
scldel: u4 = 0,
_unused24: u4 = 0,
///PRESC [28:31]
///Timing prescaler
presc: u4 = 0,
};
///Timing register
pub const timingr = Register(timingr_val).init(0x40005400 + 0x10);
//////////////////////////
///TIMEOUTR
const timeoutr_val = packed struct {
///TIMEOUTA [0:11]
///Bus timeout A
timeouta: u12 = 0,
///TIDLE [12:12]
///Idle clock timeout
///detection
tidle: packed enum(u1) {
///TIMEOUTA is used to detect SCL low timeout
disabled = 0,
///TIMEOUTA is used to detect both SCL and SDA high timeout (bus idle condition)
enabled = 1,
} = .disabled,
_unused13: u2 = 0,
///TIMOUTEN [15:15]
///Clock timeout enable
timouten: packed enum(u1) {
///SCL timeout detection is disabled
disabled = 0,
///SCL timeout detection is enabled
enabled = 1,
} = .disabled,
///TIMEOUTB [16:27]
///Bus timeout B
timeoutb: u12 = 0,
_unused28: u3 = 0,
///TEXTEN [31:31]
///Extended clock timeout
///enable
texten: packed enum(u1) {
///Extended clock timeout detection is disabled
disabled = 0,
///Extended clock timeout detection is enabled
enabled = 1,
} = .disabled,
};
///Status register 1
pub const timeoutr = Register(timeoutr_val).init(0x40005400 + 0x14);
//////////////////////////
///ISR
const isr_val = packed struct {
///TXE [0:0]
///Transmit data register empty
///(transmitters)
txe: packed enum(u1) {
///TXDR register not empty
not_empty = 0,
///TXDR register empty
empty = 1,
} = .empty,
///TXIS [1:1]
///Transmit interrupt status
///(transmitters)
txis: packed enum(u1) {
///The TXDR register is not empty
not_empty = 0,
///The TXDR register is empty and the data to be transmitted must be written in the TXDR register
empty = 1,
} = .not_empty,
///RXNE [2:2]
///Receive data register not empty
///(receivers)
rxne: packed enum(u1) {
///The RXDR register is empty
empty = 0,
///Received data is copied into the RXDR register, and is ready to be read
not_empty = 1,
} = .empty,
///ADDR [3:3]
///Address matched (slave
///mode)
addr: packed enum(u1) {
///Adress mismatched or not received
not_match = 0,
///Received slave address matched with one of the enabled slave addresses
match = 1,
} = .not_match,
///NACKF [4:4]
///Not acknowledge received
///flag
nackf: packed enum(u1) {
///No NACK has been received
no_nack = 0,
///NACK has been received
nack = 1,
} = .no_nack,
///STOPF [5:5]
///Stop detection flag
stopf: packed enum(u1) {
///No Stop condition detected
no_stop = 0,
///Stop condition detected
stop = 1,
} = .no_stop,
///TC [6:6]
///Transfer Complete (master
///mode)
tc: packed enum(u1) {
///Transfer is not complete
not_complete = 0,
///NBYTES has been transfered
complete = 1,
} = .not_complete,
///TCR [7:7]
///Transfer Complete Reload
tcr: packed enum(u1) {
///Transfer is not complete
not_complete = 0,
///NBYTES has been transfered
complete = 1,
} = .not_complete,
///BERR [8:8]
///Bus error
berr: packed enum(u1) {
///No bus error
no_error = 0,
///Misplaced Start and Stop condition is detected
_error = 1,
} = .no_error,
///ARLO [9:9]
///Arbitration lost
arlo: packed enum(u1) {
///No arbitration lost
not_lost = 0,
///Arbitration lost
lost = 1,
} = .not_lost,
///OVR [10:10]
///Overrun/Underrun (slave
///mode)
ovr: packed enum(u1) {
///No overrun/underrun error occurs
no_overrun = 0,
///slave mode with NOSTRETCH=1, when an overrun/underrun error occurs
overrun = 1,
} = .no_overrun,
///PECERR [11:11]
///PEC Error in reception
pecerr: packed enum(u1) {
///Received PEC does match with PEC register
match = 0,
///Received PEC does not match with PEC register
no_match = 1,
} = .match,
///TIMEOUT [12:12]
///Timeout or t_low detection
///flag
timeout: packed enum(u1) {
///No timeout occured
no_timeout = 0,
///Timeout occured
timeout = 1,
} = .no_timeout,
///ALERT [13:13]
///SMBus alert
alert: packed enum(u1) {
///SMBA alert is not detected
no_alert = 0,
///SMBA alert event is detected on SMBA pin
alert = 1,
} = .no_alert,
_unused14: u1 = 0,
///BUSY [15:15]
///Bus busy
busy: packed enum(u1) {
///No communication is in progress on the bus
not_busy = 0,
///A communication is in progress on the bus
busy = 1,
} = .not_busy,
///DIR [16:16]
///Transfer direction (Slave
///mode)
dir: packed enum(u1) {
///Write transfer, slave enters receiver mode
write = 0,
///Read transfer, slave enters transmitter mode
read = 1,
} = .write,
///ADDCODE [17:23]
///Address match code (Slave
///mode)
addcode: u7 = 0,
_unused24: u8 = 0,
};
///Interrupt and Status register
pub const isr = Register(isr_val).init(0x40005400 + 0x18);
//////////////////////////
///ICR
const icr_val = packed struct {
_unused0: u3 = 0,
///ADDRCF [3:3]
///Address Matched flag clear
addrcf: packed enum(u1) {
///Clears the ADDR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NACKCF [4:4]
///Not Acknowledge flag clear
nackcf: packed enum(u1) {
///Clears the NACK flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///STOPCF [5:5]
///Stop detection flag clear
stopcf: packed enum(u1) {
///Clears the STOP flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused6: u2 = 0,
///BERRCF [8:8]
///Bus error flag clear
berrcf: packed enum(u1) {
///Clears the BERR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ARLOCF [9:9]
///Arbitration lost flag
///clear
arlocf: packed enum(u1) {
///Clears the ARLO flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///OVRCF [10:10]
///Overrun/Underrun flag
///clear
ovrcf: packed enum(u1) {
///Clears the OVR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///PECCF [11:11]
///PEC Error flag clear
peccf: packed enum(u1) {
///Clears the PEC flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///TIMOUTCF [12:12]
///Timeout detection flag
///clear
timoutcf: packed enum(u1) {
///Clears the TIMOUT flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ALERTCF [13:13]
///Alert flag clear
alertcf: packed enum(u1) {
///Clears the ALERT flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused14: u18 = 0,
};
///Interrupt clear register
pub const icr = RegisterRW(void, icr_val).init(0x40005400 + 0x1C);
//////////////////////////
///PECR
const pecr_val = packed struct {
///PEC [0:7]
///Packet error checking
///register
pec: u8 = 0,
_unused8: u24 = 0,
};
///PEC register
pub const pecr = RegisterRW(pecr_val, void).init(0x40005400 + 0x20);
//////////////////////////
///RXDR
const rxdr_val = packed struct {
///RXDATA [0:7]
///8-bit receive data
rxdata: u8 = 0,
_unused8: u24 = 0,
};
///Receive data register
pub const rxdr = RegisterRW(rxdr_val, void).init(0x40005400 + 0x24);
//////////////////////////
///TXDR
const txdr_val = packed struct {
///TXDATA [0:7]
///8-bit transmit data
txdata: u8 = 0,
_unused8: u24 = 0,
};
///Transmit data register
pub const txdr = Register(txdr_val).init(0x40005400 + 0x28);
};
///Inter-integrated circuit
pub const i2c2 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///PE [0:0]
///Peripheral enable
pe: packed enum(u1) {
///Peripheral disabled
disabled = 0,
///Peripheral enabled
enabled = 1,
} = .disabled,
///TXIE [1:1]
///TX Interrupt enable
txie: packed enum(u1) {
///Transmit (TXIS) interrupt disabled
disabled = 0,
///Transmit (TXIS) interrupt enabled
enabled = 1,
} = .disabled,
///RXIE [2:2]
///RX Interrupt enable
rxie: packed enum(u1) {
///Receive (RXNE) interrupt disabled
disabled = 0,
///Receive (RXNE) interrupt enabled
enabled = 1,
} = .disabled,
///ADDRIE [3:3]
///Address match interrupt enable (slave
///only)
addrie: packed enum(u1) {
///Address match (ADDR) interrupts disabled
disabled = 0,
///Address match (ADDR) interrupts enabled
enabled = 1,
} = .disabled,
///NACKIE [4:4]
///Not acknowledge received interrupt
///enable
nackie: packed enum(u1) {
///Not acknowledge (NACKF) received interrupts disabled
disabled = 0,
///Not acknowledge (NACKF) received interrupts enabled
enabled = 1,
} = .disabled,
///STOPIE [5:5]
///STOP detection Interrupt
///enable
stopie: packed enum(u1) {
///Stop detection (STOPF) interrupt disabled
disabled = 0,
///Stop detection (STOPF) interrupt enabled
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transfer Complete interrupt
///enable
tcie: packed enum(u1) {
///Transfer Complete interrupt disabled
disabled = 0,
///Transfer Complete interrupt enabled
enabled = 1,
} = .disabled,
///ERRIE [7:7]
///Error interrupts enable
errie: packed enum(u1) {
///Error detection interrupts disabled
disabled = 0,
///Error detection interrupts enabled
enabled = 1,
} = .disabled,
///DNF [8:11]
///Digital noise filter
dnf: packed enum(u4) {
///Digital filter disabled
no_filter = 0,
///Digital filter enabled and filtering capability up to 1 tI2CCLK
filter1 = 1,
///Digital filter enabled and filtering capability up to 2 tI2CCLK
filter2 = 2,
///Digital filter enabled and filtering capability up to 3 tI2CCLK
filter3 = 3,
///Digital filter enabled and filtering capability up to 4 tI2CCLK
filter4 = 4,
///Digital filter enabled and filtering capability up to 5 tI2CCLK
filter5 = 5,
///Digital filter enabled and filtering capability up to 6 tI2CCLK
filter6 = 6,
///Digital filter enabled and filtering capability up to 7 tI2CCLK
filter7 = 7,
///Digital filter enabled and filtering capability up to 8 tI2CCLK
filter8 = 8,
///Digital filter enabled and filtering capability up to 9 tI2CCLK
filter9 = 9,
///Digital filter enabled and filtering capability up to 10 tI2CCLK
filter10 = 10,
///Digital filter enabled and filtering capability up to 11 tI2CCLK
filter11 = 11,
///Digital filter enabled and filtering capability up to 12 tI2CCLK
filter12 = 12,
///Digital filter enabled and filtering capability up to 13 tI2CCLK
filter13 = 13,
///Digital filter enabled and filtering capability up to 14 tI2CCLK
filter14 = 14,
///Digital filter enabled and filtering capability up to 15 tI2CCLK
filter15 = 15,
} = .no_filter,
///ANFOFF [12:12]
///Analog noise filter OFF
anfoff: packed enum(u1) {
///Analog noise filter enabled
enabled = 0,
///Analog noise filter disabled
disabled = 1,
} = .enabled,
///SWRST [13:13]
///Software reset
swrst: u1 = 0,
///TXDMAEN [14:14]
///DMA transmission requests
///enable
txdmaen: packed enum(u1) {
///DMA mode disabled for transmission
disabled = 0,
///DMA mode enabled for transmission
enabled = 1,
} = .disabled,
///RXDMAEN [15:15]
///DMA reception requests
///enable
rxdmaen: packed enum(u1) {
///DMA mode disabled for reception
disabled = 0,
///DMA mode enabled for reception
enabled = 1,
} = .disabled,
///SBC [16:16]
///Slave byte control
sbc: packed enum(u1) {
///Slave byte control disabled
disabled = 0,
///Slave byte control enabled
enabled = 1,
} = .disabled,
///NOSTRETCH [17:17]
///Clock stretching disable
nostretch: packed enum(u1) {
///Clock stretching enabled
enabled = 0,
///Clock stretching disabled
disabled = 1,
} = .enabled,
///WUPEN [18:18]
///Wakeup from STOP enable
wupen: packed enum(u1) {
///Wakeup from Stop mode disabled
disabled = 0,
///Wakeup from Stop mode enabled
enabled = 1,
} = .disabled,
///GCEN [19:19]
///General call enable
gcen: packed enum(u1) {
///General call disabled. Address 0b00000000 is NACKed
disabled = 0,
///General call enabled. Address 0b00000000 is ACKed
enabled = 1,
} = .disabled,
///SMBHEN [20:20]
///SMBus Host address enable
smbhen: packed enum(u1) {
///Host address disabled. Address 0b0001000x is NACKed
disabled = 0,
///Host address enabled. Address 0b0001000x is ACKed
enabled = 1,
} = .disabled,
///SMBDEN [21:21]
///SMBus Device Default address
///enable
smbden: packed enum(u1) {
///Device default address disabled. Address 0b1100001x is NACKed
disabled = 0,
///Device default address enabled. Address 0b1100001x is ACKed
enabled = 1,
} = .disabled,
///ALERTEN [22:22]
///SMBUS alert enable
alerten: packed enum(u1) {
///In device mode (SMBHEN=Disabled) Releases SMBA pin high and Alert Response Address Header disabled (0001100x) followed by NACK. In host mode (SMBHEN=Enabled) SMBus Alert pin (SMBA) not supported
disabled = 0,
///In device mode (SMBHEN=Disabled) Drives SMBA pin low and Alert Response Address Header enabled (0001100x) followed by ACK.In host mode (SMBHEN=Enabled) SMBus Alert pin (SMBA) supported
enabled = 1,
} = .disabled,
///PECEN [23:23]
///PEC enable
pecen: packed enum(u1) {
///PEC calculation disabled
disabled = 0,
///PEC calculation enabled
enabled = 1,
} = .disabled,
_unused24: u8 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40005800 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///SADD [0:9]
///Slave address bit 9:8 (master
///mode)
sadd: u10 = 0,
///RD_WRN [10:10]
///Transfer direction (master
///mode)
rd_wrn: packed enum(u1) {
///Master requests a write transfer
write = 0,
///Master requests a read transfer
read = 1,
} = .write,
///ADD10 [11:11]
///10-bit addressing mode (master
///mode)
add10: packed enum(u1) {
///The master operates in 7-bit addressing mode
bit7 = 0,
///The master operates in 10-bit addressing mode
bit10 = 1,
} = .bit7,
///HEAD10R [12:12]
///10-bit address header only read
///direction (master receiver mode)
head10r: packed enum(u1) {
///The master sends the complete 10 bit slave address read sequence
complete = 0,
///The master only sends the 1st 7 bits of the 10 bit address, followed by Read direction
partial = 1,
} = .complete,
///START [13:13]
///Start generation
start: packed enum(u1) {
///No Start generation
no_start = 0,
///Restart/Start generation
start = 1,
} = .no_start,
///STOP [14:14]
///Stop generation (master
///mode)
stop: packed enum(u1) {
///No Stop generation
no_stop = 0,
///Stop generation after current byte transfer
stop = 1,
} = .no_stop,
///NACK [15:15]
///NACK generation (slave
///mode)
nack: packed enum(u1) {
///an ACK is sent after current received byte
ack = 0,
///a NACK is sent after current received byte
nack = 1,
} = .ack,
///NBYTES [16:23]
///Number of bytes
nbytes: u8 = 0,
///RELOAD [24:24]
///NBYTES reload mode
reload: packed enum(u1) {
///The transfer is completed after the NBYTES data transfer (STOP or RESTART will follow)
completed = 0,
///The transfer is not completed after the NBYTES data transfer (NBYTES will be reloaded)
not_completed = 1,
} = .completed,
///AUTOEND [25:25]
///Automatic end mode (master
///mode)
autoend: packed enum(u1) {
///Software end mode: TC flag is set when NBYTES data are transferred, stretching SCL low
software = 0,
///Automatic end mode: a STOP condition is automatically sent when NBYTES data are transferred
automatic = 1,
} = .software,
///PECBYTE [26:26]
///Packet error checking byte
pecbyte: packed enum(u1) {
///No PEC transfer
no_pec = 0,
///PEC transmission/reception is requested
pec = 1,
} = .no_pec,
_unused27: u5 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40005800 + 0x4);
//////////////////////////
///OAR1
const oar1_val = packed struct {
///OA1 [0:9]
///Interface address
oa1: u10 = 0,
///OA1MODE [10:10]
///Own Address 1 10-bit mode
oa1mode: packed enum(u1) {
///Own address 1 is a 7-bit address
bit7 = 0,
///Own address 1 is a 10-bit address
bit10 = 1,
} = .bit7,
_unused11: u4 = 0,
///OA1EN [15:15]
///Own Address 1 enable
oa1en: packed enum(u1) {
///Own address 1 disabled. The received slave address OA1 is NACKed
disabled = 0,
///Own address 1 enabled. The received slave address OA1 is ACKed
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///Own address register 1
pub const oar1 = Register(oar1_val).init(0x40005800 + 0x8);
//////////////////////////
///OAR2
const oar2_val = packed struct {
_unused0: u1 = 0,
///OA2 [1:7]
///Interface address
oa2: u7 = 0,
///OA2MSK [8:10]
///Own Address 2 masks
oa2msk: packed enum(u3) {
///No mask
no_mask = 0,
///OA2[1] is masked and don’t care. Only OA2[7:2] are compared
mask1 = 1,
///OA2[2:1] are masked and don’t care. Only OA2[7:3] are compared
mask2 = 2,
///OA2[3:1] are masked and don’t care. Only OA2[7:4] are compared
mask3 = 3,
///OA2[4:1] are masked and don’t care. Only OA2[7:5] are compared
mask4 = 4,
///OA2[5:1] are masked and don’t care. Only OA2[7:6] are compared
mask5 = 5,
///OA2[6:1] are masked and don’t care. Only OA2[7] is compared.
mask6 = 6,
///OA2[7:1] are masked and don’t care. No comparison is done, and all (except reserved) 7-bit received addresses are acknowledged
mask7 = 7,
} = .no_mask,
_unused11: u4 = 0,
///OA2EN [15:15]
///Own Address 2 enable
oa2en: packed enum(u1) {
///Own address 2 disabled. The received slave address OA2 is NACKed
disabled = 0,
///Own address 2 enabled. The received slave address OA2 is ACKed
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///Own address register 2
pub const oar2 = Register(oar2_val).init(0x40005800 + 0xC);
//////////////////////////
///TIMINGR
const timingr_val = packed struct {
///SCLL [0:7]
///SCL low period (master
///mode)
scll: u8 = 0,
///SCLH [8:15]
///SCL high period (master
///mode)
sclh: u8 = 0,
///SDADEL [16:19]
///Data hold time
sdadel: u4 = 0,
///SCLDEL [20:23]
///Data setup time
scldel: u4 = 0,
_unused24: u4 = 0,
///PRESC [28:31]
///Timing prescaler
presc: u4 = 0,
};
///Timing register
pub const timingr = Register(timingr_val).init(0x40005800 + 0x10);
//////////////////////////
///TIMEOUTR
const timeoutr_val = packed struct {
///TIMEOUTA [0:11]
///Bus timeout A
timeouta: u12 = 0,
///TIDLE [12:12]
///Idle clock timeout
///detection
tidle: packed enum(u1) {
///TIMEOUTA is used to detect SCL low timeout
disabled = 0,
///TIMEOUTA is used to detect both SCL and SDA high timeout (bus idle condition)
enabled = 1,
} = .disabled,
_unused13: u2 = 0,
///TIMOUTEN [15:15]
///Clock timeout enable
timouten: packed enum(u1) {
///SCL timeout detection is disabled
disabled = 0,
///SCL timeout detection is enabled
enabled = 1,
} = .disabled,
///TIMEOUTB [16:27]
///Bus timeout B
timeoutb: u12 = 0,
_unused28: u3 = 0,
///TEXTEN [31:31]
///Extended clock timeout
///enable
texten: packed enum(u1) {
///Extended clock timeout detection is disabled
disabled = 0,
///Extended clock timeout detection is enabled
enabled = 1,
} = .disabled,
};
///Status register 1
pub const timeoutr = Register(timeoutr_val).init(0x40005800 + 0x14);
//////////////////////////
///ISR
const isr_val = packed struct {
///TXE [0:0]
///Transmit data register empty
///(transmitters)
txe: packed enum(u1) {
///TXDR register not empty
not_empty = 0,
///TXDR register empty
empty = 1,
} = .empty,
///TXIS [1:1]
///Transmit interrupt status
///(transmitters)
txis: packed enum(u1) {
///The TXDR register is not empty
not_empty = 0,
///The TXDR register is empty and the data to be transmitted must be written in the TXDR register
empty = 1,
} = .not_empty,
///RXNE [2:2]
///Receive data register not empty
///(receivers)
rxne: packed enum(u1) {
///The RXDR register is empty
empty = 0,
///Received data is copied into the RXDR register, and is ready to be read
not_empty = 1,
} = .empty,
///ADDR [3:3]
///Address matched (slave
///mode)
addr: packed enum(u1) {
///Adress mismatched or not received
not_match = 0,
///Received slave address matched with one of the enabled slave addresses
match = 1,
} = .not_match,
///NACKF [4:4]
///Not acknowledge received
///flag
nackf: packed enum(u1) {
///No NACK has been received
no_nack = 0,
///NACK has been received
nack = 1,
} = .no_nack,
///STOPF [5:5]
///Stop detection flag
stopf: packed enum(u1) {
///No Stop condition detected
no_stop = 0,
///Stop condition detected
stop = 1,
} = .no_stop,
///TC [6:6]
///Transfer Complete (master
///mode)
tc: packed enum(u1) {
///Transfer is not complete
not_complete = 0,
///NBYTES has been transfered
complete = 1,
} = .not_complete,
///TCR [7:7]
///Transfer Complete Reload
tcr: packed enum(u1) {
///Transfer is not complete
not_complete = 0,
///NBYTES has been transfered
complete = 1,
} = .not_complete,
///BERR [8:8]
///Bus error
berr: packed enum(u1) {
///No bus error
no_error = 0,
///Misplaced Start and Stop condition is detected
_error = 1,
} = .no_error,
///ARLO [9:9]
///Arbitration lost
arlo: packed enum(u1) {
///No arbitration lost
not_lost = 0,
///Arbitration lost
lost = 1,
} = .not_lost,
///OVR [10:10]
///Overrun/Underrun (slave
///mode)
ovr: packed enum(u1) {
///No overrun/underrun error occurs
no_overrun = 0,
///slave mode with NOSTRETCH=1, when an overrun/underrun error occurs
overrun = 1,
} = .no_overrun,
///PECERR [11:11]
///PEC Error in reception
pecerr: packed enum(u1) {
///Received PEC does match with PEC register
match = 0,
///Received PEC does not match with PEC register
no_match = 1,
} = .match,
///TIMEOUT [12:12]
///Timeout or t_low detection
///flag
timeout: packed enum(u1) {
///No timeout occured
no_timeout = 0,
///Timeout occured
timeout = 1,
} = .no_timeout,
///ALERT [13:13]
///SMBus alert
alert: packed enum(u1) {
///SMBA alert is not detected
no_alert = 0,
///SMBA alert event is detected on SMBA pin
alert = 1,
} = .no_alert,
_unused14: u1 = 0,
///BUSY [15:15]
///Bus busy
busy: packed enum(u1) {
///No communication is in progress on the bus
not_busy = 0,
///A communication is in progress on the bus
busy = 1,
} = .not_busy,
///DIR [16:16]
///Transfer direction (Slave
///mode)
dir: packed enum(u1) {
///Write transfer, slave enters receiver mode
write = 0,
///Read transfer, slave enters transmitter mode
read = 1,
} = .write,
///ADDCODE [17:23]
///Address match code (Slave
///mode)
addcode: u7 = 0,
_unused24: u8 = 0,
};
///Interrupt and Status register
pub const isr = Register(isr_val).init(0x40005800 + 0x18);
//////////////////////////
///ICR
const icr_val = packed struct {
_unused0: u3 = 0,
///ADDRCF [3:3]
///Address Matched flag clear
addrcf: packed enum(u1) {
///Clears the ADDR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NACKCF [4:4]
///Not Acknowledge flag clear
nackcf: packed enum(u1) {
///Clears the NACK flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///STOPCF [5:5]
///Stop detection flag clear
stopcf: packed enum(u1) {
///Clears the STOP flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused6: u2 = 0,
///BERRCF [8:8]
///Bus error flag clear
berrcf: packed enum(u1) {
///Clears the BERR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ARLOCF [9:9]
///Arbitration lost flag
///clear
arlocf: packed enum(u1) {
///Clears the ARLO flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///OVRCF [10:10]
///Overrun/Underrun flag
///clear
ovrcf: packed enum(u1) {
///Clears the OVR flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///PECCF [11:11]
///PEC Error flag clear
peccf: packed enum(u1) {
///Clears the PEC flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///TIMOUTCF [12:12]
///Timeout detection flag
///clear
timoutcf: packed enum(u1) {
///Clears the TIMOUT flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ALERTCF [13:13]
///Alert flag clear
alertcf: packed enum(u1) {
///Clears the ALERT flag in ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused14: u18 = 0,
};
///Interrupt clear register
pub const icr = RegisterRW(void, icr_val).init(0x40005800 + 0x1C);
//////////////////////////
///PECR
const pecr_val = packed struct {
///PEC [0:7]
///Packet error checking
///register
pec: u8 = 0,
_unused8: u24 = 0,
};
///PEC register
pub const pecr = RegisterRW(pecr_val, void).init(0x40005800 + 0x20);
//////////////////////////
///RXDR
const rxdr_val = packed struct {
///RXDATA [0:7]
///8-bit receive data
rxdata: u8 = 0,
_unused8: u24 = 0,
};
///Receive data register
pub const rxdr = RegisterRW(rxdr_val, void).init(0x40005800 + 0x24);
//////////////////////////
///TXDR
const txdr_val = packed struct {
///TXDATA [0:7]
///8-bit transmit data
txdata: u8 = 0,
_unused8: u24 = 0,
};
///Transmit data register
pub const txdr = Register(txdr_val).init(0x40005800 + 0x28);
};
///Independent watchdog
pub const iwdg = struct {
//////////////////////////
///KR
const kr_val = packed struct {
///KEY [0:15]
///Key value
key: packed enum(u16) {
///Enable access to PR, RLR and WINR registers (0x5555)
enable = 21845,
///Reset the watchdog value (0xAAAA)
reset = 43690,
///Start the watchdog (0xCCCC)
start = 52428,
_zero = 0,
} = ._zero,
_unused16: u16 = 0,
};
///Key register
pub const kr = RegisterRW(void, kr_val).init(0x40003000 + 0x0);
//////////////////////////
///PR
const pr_val = packed struct {
///PR [0:2]
///Prescaler divider
pr: packed enum(u3) {
///Divider /4
divide_by4 = 0,
///Divider /8
divide_by8 = 1,
///Divider /16
divide_by16 = 2,
///Divider /32
divide_by32 = 3,
///Divider /64
divide_by64 = 4,
///Divider /128
divide_by128 = 5,
///Divider /256
divide_by256 = 6,
///Divider /256
divide_by256bis = 7,
} = .divide_by4,
_unused3: u29 = 0,
};
///Prescaler register
pub const pr = Register(pr_val).init(0x40003000 + 0x4);
//////////////////////////
///RLR
const rlr_val = packed struct {
///RL [0:11]
///Watchdog counter reload
///value
rl: u12 = 4095,
_unused12: u20 = 0,
};
///Reload register
pub const rlr = Register(rlr_val).init(0x40003000 + 0x8);
//////////////////////////
///SR
const sr_val = packed struct {
///PVU [0:0]
///Watchdog prescaler value
///update
pvu: u1 = 0,
///RVU [1:1]
///Watchdog counter reload value
///update
rvu: u1 = 0,
///WVU [2:2]
///Watchdog counter window value
///update
wvu: u1 = 0,
_unused3: u29 = 0,
};
///Status register
pub const sr = RegisterRW(sr_val, void).init(0x40003000 + 0xC);
//////////////////////////
///WINR
const winr_val = packed struct {
///WIN [0:11]
///Watchdog counter window
///value
win: u12 = 4095,
_unused12: u20 = 0,
};
///Window register
pub const winr = Register(winr_val).init(0x40003000 + 0x10);
};
///Window watchdog
pub const wwdg = struct {
//////////////////////////
///CR
const cr_val = packed struct {
///T [0:6]
///7-bit counter
t: u7 = 127,
///WDGA [7:7]
///Activation bit
wdga: packed enum(u1) {
///Watchdog disabled
disabled = 0,
///Watchdog enabled
enabled = 1,
} = .disabled,
_unused8: u24 = 0,
};
///Control register
pub const cr = Register(cr_val).init(0x40002C00 + 0x0);
//////////////////////////
///CFR
const cfr_val = packed struct {
///W [0:6]
///7-bit window value
w: u7 = 127,
///WDGTB [7:8]
///Timer base
wdgtb: packed enum(u2) {
///Counter clock (PCLK1 div 4096) div 1
div1 = 0,
///Counter clock (PCLK1 div 4096) div 2
div2 = 1,
///Counter clock (PCLK1 div 4096) div 4
div4 = 2,
///Counter clock (PCLK1 div 4096) div 8
div8 = 3,
} = .div1,
///EWI [9:9]
///Early wakeup interrupt
ewi: u1 = 0,
_unused10: u22 = 0,
};
///Configuration register
pub const cfr = Register(cfr_val).init(0x40002C00 + 0x4);
//////////////////////////
///SR
const sr_val_read = packed struct {
///EWIF [0:0]
///Early wakeup interrupt
///flag
ewif: packed enum(u1) {
///The EWI Interrupt Service Routine has been triggered
pending = 1,
///The EWI Interrupt Service Routine has been serviced
finished = 0,
} = .finished,
_unused1: u31 = 0,
};
const sr_val_write = packed struct {
///EWIF [0:0]
///Early wakeup interrupt
///flag
ewif: packed enum(u1) {
///The EWI Interrupt Service Routine has been serviced
finished = 0,
} = .finished,
_unused1: u31 = 0,
};
///Status register
pub const sr = RegisterRW(sr_val_read, sr_val_write).init(0x40002C00 + 0x8);
};
///Advanced-timers
pub const tim1 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Counter is not stopped at update event
disabled = 0,
///Counter stops counting at the next update event (clearing the CEN bit)
enabled = 1,
} = .disabled,
///DIR [4:4]
///Direction
dir: packed enum(u1) {
///Counter used as upcounter
up = 0,
///Counter used as downcounter
down = 1,
} = .up,
///CMS [5:6]
///Center-aligned mode
///selection
cms: packed enum(u2) {
///The counter counts up or down depending on the direction bit
edge_aligned = 0,
///The counter counts up and down alternatively. Output compare interrupt flags are set only when the counter is counting down.
center_aligned1 = 1,
///The counter counts up and down alternatively. Output compare interrupt flags are set only when the counter is counting up.
center_aligned2 = 2,
///The counter counts up and down alternatively. Output compare interrupt flags are set both when the counter is counting up or down.
center_aligned3 = 3,
} = .edge_aligned,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40012C00 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///CCPC [0:0]
///Capture/compare preloaded
///control
ccpc: u1 = 0,
_unused1: u1 = 0,
///CCUS [2:2]
///Capture/compare control update
///selection
ccus: u1 = 0,
///CCDS [3:3]
///Capture/compare DMA
///selection
ccds: packed enum(u1) {
///CCx DMA request sent when CCx event occurs
on_compare = 0,
///CCx DMA request sent when update event occurs
on_update = 1,
} = .on_compare,
///MMS [4:6]
///Master mode selection
mms: packed enum(u3) {
///The UG bit from the TIMx_EGR register is used as trigger output
reset = 0,
///The counter enable signal, CNT_EN, is used as trigger output
enable = 1,
///The update event is selected as trigger output
update = 2,
///The trigger output send a positive pulse when the CC1IF flag it to be set, as soon as a capture or a compare match occurred
compare_pulse = 3,
///OC1REF signal is used as trigger output
compare_oc1 = 4,
///OC2REF signal is used as trigger output
compare_oc2 = 5,
///OC3REF signal is used as trigger output
compare_oc3 = 6,
///OC4REF signal is used as trigger output
compare_oc4 = 7,
} = .reset,
///TI1S [7:7]
///TI1 selection
ti1s: packed enum(u1) {
///The TIMx_CH1 pin is connected to TI1 input
normal = 0,
///The TIMx_CH1, CH2, CH3 pins are connected to TI1 input
xor = 1,
} = .normal,
///OIS1 [8:8]
///Output Idle state 1
ois1: u1 = 0,
///OIS1N [9:9]
///Output Idle state 1
ois1n: u1 = 0,
///OIS2 [10:10]
///Output Idle state 2
ois2: u1 = 0,
///OIS2N [11:11]
///Output Idle state 2
ois2n: u1 = 0,
///OIS3 [12:12]
///Output Idle state 3
ois3: u1 = 0,
///OIS3N [13:13]
///Output Idle state 3
ois3n: u1 = 0,
///OIS4 [14:14]
///Output Idle state 4
ois4: u1 = 0,
_unused15: u17 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40012C00 + 0x4);
//////////////////////////
///SMCR
const smcr_val = packed struct {
///SMS [0:2]
///Slave mode selection
sms: packed enum(u3) {
///Slave mode disabled - if CEN = ‘1 then the prescaler is clocked directly by the internal clock.
disabled = 0,
///Encoder mode 1 - Counter counts up/down on TI2FP1 edge depending on TI1FP2 level.
encoder_mode_1 = 1,
///Encoder mode 2 - Counter counts up/down on TI1FP2 edge depending on TI2FP1 level.
encoder_mode_2 = 2,
///Encoder mode 3 - Counter counts up/down on both TI1FP1 and TI2FP2 edges depending on the level of the other input.
encoder_mode_3 = 3,
///Reset Mode - Rising edge of the selected trigger input (TRGI) reinitializes the counter and generates an update of the registers.
reset_mode = 4,
///Gated Mode - The counter clock is enabled when the trigger input (TRGI) is high. The counter stops (but is not reset) as soon as the trigger becomes low. Both start and stop of the counter are controlled.
gated_mode = 5,
///Trigger Mode - The counter starts at a rising edge of the trigger TRGI (but it is not reset). Only the start of the counter is controlled.
trigger_mode = 6,
///External Clock Mode 1 - Rising edges of the selected trigger (TRGI) clock the counter.
ext_clock_mode = 7,
} = .disabled,
_unused3: u1 = 0,
///TS [4:6]
///Trigger selection
ts: packed enum(u3) {
///Internal Trigger 0 (ITR0)
itr0 = 0,
///Internal Trigger 1 (ITR1)
itr1 = 1,
///Internal Trigger 2 (ITR2)
itr2 = 2,
///TI1 Edge Detector (TI1F_ED)
ti1f_ed = 4,
///Filtered Timer Input 1 (TI1FP1)
ti1fp1 = 5,
///Filtered Timer Input 2 (TI2FP2)
ti2fp2 = 6,
///External Trigger input (ETRF)
etrf = 7,
} = .itr0,
///MSM [7:7]
///Master/Slave mode
msm: packed enum(u1) {
///No action
no_sync = 0,
///The effect of an event on the trigger input (TRGI) is delayed to allow a perfect synchronization between the current timer and its slaves (through TRGO). It is useful if we want to synchronize several timers on a single external event.
sync = 1,
} = .no_sync,
///ETF [8:11]
///External trigger filter
etf: packed enum(u4) {
///No filter, sampling is done at fDTS
no_filter = 0,
///fSAMPLING=fCK_INT, N=2
fck_int_n2 = 1,
///fSAMPLING=fCK_INT, N=4
fck_int_n4 = 2,
///fSAMPLING=fCK_INT, N=8
fck_int_n8 = 3,
///fSAMPLING=fDTS/2, N=6
fdts_div2_n6 = 4,
///fSAMPLING=fDTS/2, N=8
fdts_div2_n8 = 5,
///fSAMPLING=fDTS/4, N=6
fdts_div4_n6 = 6,
///fSAMPLING=fDTS/4, N=8
fdts_div4_n8 = 7,
///fSAMPLING=fDTS/8, N=6
fdts_div8_n6 = 8,
///fSAMPLING=fDTS/8, N=8
fdts_div8_n8 = 9,
///fSAMPLING=fDTS/16, N=5
fdts_div16_n5 = 10,
///fSAMPLING=fDTS/16, N=6
fdts_div16_n6 = 11,
///fSAMPLING=fDTS/16, N=8
fdts_div16_n8 = 12,
///fSAMPLING=fDTS/32, N=5
fdts_div32_n5 = 13,
///fSAMPLING=fDTS/32, N=6
fdts_div32_n6 = 14,
///fSAMPLING=fDTS/32, N=8
fdts_div32_n8 = 15,
} = .no_filter,
///ETPS [12:13]
///External trigger prescaler
etps: packed enum(u2) {
///Prescaler OFF
div1 = 0,
///ETRP frequency divided by 2
div2 = 1,
///ETRP frequency divided by 4
div4 = 2,
///ETRP frequency divided by 8
div8 = 3,
} = .div1,
///ECE [14:14]
///External clock enable
ece: packed enum(u1) {
///External clock mode 2 disabled
disabled = 0,
///External clock mode 2 enabled. The counter is clocked by any active edge on the ETRF signal.
enabled = 1,
} = .disabled,
///ETP [15:15]
///External trigger polarity
etp: packed enum(u1) {
///ETR is noninverted, active at high level or rising edge
not_inverted = 0,
///ETR is inverted, active at low level or falling edge
inverted = 1,
} = .not_inverted,
_unused16: u16 = 0,
};
///slave mode control register
pub const smcr = Register(smcr_val).init(0x40012C00 + 0x8);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: u1 = 0,
///CC2IE [2:2]
///Capture/Compare 2 interrupt
///enable
cc2ie: u1 = 0,
///CC3IE [3:3]
///Capture/Compare 3 interrupt
///enable
cc3ie: u1 = 0,
///CC4IE [4:4]
///Capture/Compare 4 interrupt
///enable
cc4ie: packed enum(u1) {
///CCx interrupt disabled
disabled = 0,
///CCx interrupt enabled
enabled = 1,
} = .disabled,
///COMIE [5:5]
///COM interrupt enable
comie: u1 = 0,
///TIE [6:6]
///Trigger interrupt enable
tie: packed enum(u1) {
///Trigger interrupt disabled
disabled = 0,
///Trigger interrupt enabled
enabled = 1,
} = .disabled,
///BIE [7:7]
///Break interrupt enable
bie: u1 = 0,
///UDE [8:8]
///Update DMA request enable
ude: packed enum(u1) {
///Update DMA request disabled
disabled = 0,
///Update DMA request enabled
enabled = 1,
} = .disabled,
///CC1DE [9:9]
///Capture/Compare 1 DMA request
///enable
cc1de: u1 = 0,
///CC2DE [10:10]
///Capture/Compare 2 DMA request
///enable
cc2de: u1 = 0,
///CC3DE [11:11]
///Capture/Compare 3 DMA request
///enable
cc3de: u1 = 0,
///CC4DE [12:12]
///Capture/Compare 4 DMA request
///enable
cc4de: packed enum(u1) {
///CCx DMA request disabled
disabled = 0,
///CCx DMA request enabled
enabled = 1,
} = .disabled,
///COMDE [13:13]
///COM DMA request enable
comde: u1 = 0,
///TDE [14:14]
///Trigger DMA request enable
tde: packed enum(u1) {
///Trigger DMA request disabled
disabled = 0,
///Trigger DMA request enabled
enabled = 1,
} = .disabled,
_unused15: u17 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40012C00 + 0xC);
//////////////////////////
///SR
const sr_val_read = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: u1 = 0,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
///CC2IF [2:2]
///Capture/Compare 2 interrupt
///flag
cc2if: u1 = 0,
///CC3IF [3:3]
///Capture/Compare 3 interrupt
///flag
cc3if: u1 = 0,
///CC4IF [4:4]
///Capture/Compare 4 interrupt
///flag
cc4if: packed enum(u1) {
///If CC1 is an output: The content of the counter TIMx_CNT matches the content of the TIMx_CCR1 register. If CC1 is an input: The counter value has been captured in TIMx_CCR1 register.
match = 1,
_zero = 0,
} = ._zero,
///COMIF [5:5]
///COM interrupt flag
comif: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: packed enum(u1) {
///No trigger event occurred
no_trigger = 0,
///Trigger interrupt pending
trigger = 1,
} = .no_trigger,
///BIF [7:7]
///Break interrupt flag
bif: u1 = 0,
_unused8: u1 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
///CC2OF [10:10]
///Capture/compare 2 overcapture
///flag
cc2of: u1 = 0,
///CC3OF [11:11]
///Capture/Compare 3 overcapture
///flag
cc3of: u1 = 0,
///CC4OF [12:12]
///Capture/Compare 4 overcapture
///flag
cc4of: packed enum(u1) {
///The counter value has been captured in TIMx_CCRx register while CCxIF flag was already set
overcapture = 1,
_zero = 0,
} = ._zero,
_unused13: u19 = 0,
};
const sr_val_write = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: u1 = 0,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
///CC2IF [2:2]
///Capture/Compare 2 interrupt
///flag
cc2if: u1 = 0,
///CC3IF [3:3]
///Capture/Compare 3 interrupt
///flag
cc3if: u1 = 0,
///CC4IF [4:4]
///Capture/Compare 4 interrupt
///flag
cc4if: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
///COMIF [5:5]
///COM interrupt flag
comif: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
///BIF [7:7]
///Break interrupt flag
bif: u1 = 0,
_unused8: u1 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
///CC2OF [10:10]
///Capture/compare 2 overcapture
///flag
cc2of: u1 = 0,
///CC3OF [11:11]
///Capture/Compare 3 overcapture
///flag
cc3of: u1 = 0,
///CC4OF [12:12]
///Capture/Compare 4 overcapture
///flag
cc4of: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
_unused13: u19 = 0,
};
///status register
pub const sr = RegisterRW(sr_val_read, sr_val_write).init(0x40012C00 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
///CC2G [2:2]
///Capture/compare 2
///generation
cc2g: u1 = 0,
///CC3G [3:3]
///Capture/compare 3
///generation
cc3g: u1 = 0,
///CC4G [4:4]
///Capture/compare 4
///generation
cc4g: u1 = 0,
///COMG [5:5]
///Capture/Compare control update
///generation
comg: u1 = 0,
///TG [6:6]
///Trigger generation
tg: u1 = 0,
///BG [7:7]
///Break generation
bg: u1 = 0,
_unused8: u24 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40012C00 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: packed enum(u2) {
///CC1 channel is configured as output
output = 0,
} = .output,
///OC1FE [2:2]
///Output Compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output Compare 1 preload
///enable
oc1pe: packed enum(u1) {
///Preload register on CCR1 disabled. New values written to CCR1 are taken into account immediately
disabled = 0,
///Preload register on CCR1 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC1M [4:6]
///Output Compare 1 mode
oc1m: u3 = 0,
///OC1CE [7:7]
///Output Compare 1 clear
///enable
oc1ce: u1 = 0,
///CC2S [8:9]
///Capture/Compare 2
///selection
cc2s: packed enum(u2) {
///CC2 channel is configured as output
output = 0,
} = .output,
///OC2FE [10:10]
///Output Compare 2 fast
///enable
oc2fe: u1 = 0,
///OC2PE [11:11]
///Output Compare 2 preload
///enable
oc2pe: packed enum(u1) {
///Preload register on CCR2 disabled. New values written to CCR2 are taken into account immediately
disabled = 0,
///Preload register on CCR2 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC2M [12:14]
///Output Compare 2 mode
oc2m: packed enum(u3) {
///The comparison between the output compare register TIMx_CCRy and the counter TIMx_CNT has no effect on the outputs
frozen = 0,
///Set channel to active level on match. OCyREF signal is forced high when the counter matches the capture/compare register
active_on_match = 1,
///Set channel to inactive level on match. OCyREF signal is forced low when the counter matches the capture/compare register
inactive_on_match = 2,
///OCyREF toggles when TIMx_CNT=TIMx_CCRy
toggle = 3,
///OCyREF is forced low
force_inactive = 4,
///OCyREF is forced high
force_active = 5,
///In upcounting, channel is active as long as TIMx_CNT<TIMx_CCRy else inactive. In downcounting, channel is inactive as long as TIMx_CNT>TIMx_CCRy else active
pwm_mode1 = 6,
///Inversely to PwmMode1
pwm_mode2 = 7,
} = .frozen,
///OC2CE [15:15]
///Output Compare 2 clear
///enable
oc2ce: u1 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40012C00 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: packed enum(u2) {
///CC1 channel is configured as input, IC1 is mapped on TI1
ti1 = 1,
///CC1 channel is configured as input, IC1 is mapped on TI2
ti2 = 2,
///CC1 channel is configured as input, IC1 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: packed enum(u4) {
///No filter, sampling is done at fDTS
no_filter = 0,
///fSAMPLING=fCK_INT, N=2
fck_int_n2 = 1,
///fSAMPLING=fCK_INT, N=4
fck_int_n4 = 2,
///fSAMPLING=fCK_INT, N=8
fck_int_n8 = 3,
///fSAMPLING=fDTS/2, N=6
fdts_div2_n6 = 4,
///fSAMPLING=fDTS/2, N=8
fdts_div2_n8 = 5,
///fSAMPLING=fDTS/4, N=6
fdts_div4_n6 = 6,
///fSAMPLING=fDTS/4, N=8
fdts_div4_n8 = 7,
///fSAMPLING=fDTS/8, N=6
fdts_div8_n6 = 8,
///fSAMPLING=fDTS/8, N=8
fdts_div8_n8 = 9,
///fSAMPLING=fDTS/16, N=5
fdts_div16_n5 = 10,
///fSAMPLING=fDTS/16, N=6
fdts_div16_n6 = 11,
///fSAMPLING=fDTS/16, N=8
fdts_div16_n8 = 12,
///fSAMPLING=fDTS/32, N=5
fdts_div32_n5 = 13,
///fSAMPLING=fDTS/32, N=6
fdts_div32_n6 = 14,
///fSAMPLING=fDTS/32, N=8
fdts_div32_n8 = 15,
} = .no_filter,
///CC2S [8:9]
///Capture/Compare 2
///selection
cc2s: packed enum(u2) {
///CC2 channel is configured as input, IC2 is mapped on TI2
ti2 = 1,
///CC2 channel is configured as input, IC2 is mapped on TI1
ti1 = 2,
///CC2 channel is configured as input, IC2 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC2PSC [10:11]
///Input capture 2 prescaler
ic2psc: u2 = 0,
///IC2F [12:15]
///Input capture 2 filter
ic2f: u4 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 1 (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40012C00 + 0x18);
//////////////////////////
///CCMR2_Output
const ccmr2_output_val = packed struct {
///CC3S [0:1]
///Capture/Compare 3
///selection
cc3s: packed enum(u2) {
///CC3 channel is configured as output
output = 0,
} = .output,
///OC3FE [2:2]
///Output compare 3 fast
///enable
oc3fe: u1 = 0,
///OC3PE [3:3]
///Output compare 3 preload
///enable
oc3pe: packed enum(u1) {
///Preload register on CCR3 disabled. New values written to CCR3 are taken into account immediately
disabled = 0,
///Preload register on CCR3 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC3M [4:6]
///Output compare 3 mode
oc3m: u3 = 0,
///OC3CE [7:7]
///Output compare 3 clear
///enable
oc3ce: u1 = 0,
///CC4S [8:9]
///Capture/Compare 4
///selection
cc4s: packed enum(u2) {
///CC4 channel is configured as output
output = 0,
} = .output,
///OC4FE [10:10]
///Output compare 4 fast
///enable
oc4fe: u1 = 0,
///OC4PE [11:11]
///Output compare 4 preload
///enable
oc4pe: packed enum(u1) {
///Preload register on CCR4 disabled. New values written to CCR4 are taken into account immediately
disabled = 0,
///Preload register on CCR4 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC4M [12:14]
///Output compare 4 mode
oc4m: packed enum(u3) {
///The comparison between the output compare register TIMx_CCRy and the counter TIMx_CNT has no effect on the outputs
frozen = 0,
///Set channel to active level on match. OCyREF signal is forced high when the counter matches the capture/compare register
active_on_match = 1,
///Set channel to inactive level on match. OCyREF signal is forced low when the counter matches the capture/compare register
inactive_on_match = 2,
///OCyREF toggles when TIMx_CNT=TIMx_CCRy
toggle = 3,
///OCyREF is forced low
force_inactive = 4,
///OCyREF is forced high
force_active = 5,
///In upcounting, channel is active as long as TIMx_CNT<TIMx_CCRy else inactive. In downcounting, channel is inactive as long as TIMx_CNT>TIMx_CCRy else active
pwm_mode1 = 6,
///Inversely to PwmMode1
pwm_mode2 = 7,
} = .frozen,
///OC4CE [15:15]
///Output compare 4 clear
///enable
oc4ce: u1 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr2_output = Register(ccmr2_output_val).init(0x40012C00 + 0x1C);
//////////////////////////
///CCMR2_Input
const ccmr2_input_val = packed struct {
///CC3S [0:1]
///Capture/compare 3
///selection
cc3s: packed enum(u2) {
///CC3 channel is configured as input, IC3 is mapped on TI3
ti3 = 1,
///CC3 channel is configured as input, IC3 is mapped on TI4
ti4 = 2,
///CC3 channel is configured as input, IC3 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC3PSC [2:3]
///Input capture 3 prescaler
ic3psc: u2 = 0,
///IC3F [4:7]
///Input capture 3 filter
ic3f: u4 = 0,
///CC4S [8:9]
///Capture/Compare 4
///selection
cc4s: packed enum(u2) {
///CC4 channel is configured as input, IC4 is mapped on TI4
ti4 = 1,
///CC4 channel is configured as input, IC4 is mapped on TI3
ti3 = 2,
///CC4 channel is configured as input, IC4 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC4PSC [10:11]
///Input capture 4 prescaler
ic4psc: u2 = 0,
///IC4F [12:15]
///Input capture 4 filter
ic4f: u4 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 2 (input
///mode)
pub const ccmr2_input = Register(ccmr2_input_val).init(0x40012C00 + 0x1C);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
///CC1NE [2:2]
///Capture/Compare 1 complementary output
///enable
cc1ne: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
///CC2E [4:4]
///Capture/Compare 2 output
///enable
cc2e: u1 = 0,
///CC2P [5:5]
///Capture/Compare 2 output
///Polarity
cc2p: u1 = 0,
///CC2NE [6:6]
///Capture/Compare 2 complementary output
///enable
cc2ne: u1 = 0,
///CC2NP [7:7]
///Capture/Compare 2 output
///Polarity
cc2np: u1 = 0,
///CC3E [8:8]
///Capture/Compare 3 output
///enable
cc3e: u1 = 0,
///CC3P [9:9]
///Capture/Compare 3 output
///Polarity
cc3p: u1 = 0,
///CC3NE [10:10]
///Capture/Compare 3 complementary output
///enable
cc3ne: u1 = 0,
///CC3NP [11:11]
///Capture/Compare 3 output
///Polarity
cc3np: u1 = 0,
///CC4E [12:12]
///Capture/Compare 4 output
///enable
cc4e: u1 = 0,
///CC4P [13:13]
///Capture/Compare 3 output
///Polarity
cc4p: u1 = 0,
_unused14: u18 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40012C00 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40012C00 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40012C00 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40012C00 + 0x2C);
//////////////////////////
///RCR
const rcr_val = packed struct {
///REP [0:7]
///Repetition counter value
rep: u8 = 0,
_unused8: u24 = 0,
};
///repetition counter register
pub const rcr = Register(rcr_val).init(0x40012C00 + 0x30);
//////////////////////////
///CCR%s
const ccr_val = packed struct {
///CCR [0:15]
///Capture/Compare 1 value
ccr: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 1
pub const ccr = Register(ccr_val).initRange(0x40012C00 + 0x34, 4, 4);
//////////////////////////
///BDTR
const bdtr_val = packed struct {
///DTG [0:7]
///Dead-time generator setup
dtg: u8 = 0,
///LOCK [8:9]
///Lock configuration
lock: u2 = 0,
///OSSI [10:10]
///Off-state selection for Idle
///mode
ossi: u1 = 0,
///OSSR [11:11]
///Off-state selection for Run
///mode
ossr: u1 = 0,
///BKE [12:12]
///Break enable
bke: u1 = 0,
///BKP [13:13]
///Break polarity
bkp: u1 = 0,
///AOE [14:14]
///Automatic output enable
aoe: u1 = 0,
///MOE [15:15]
///Main output enable
moe: u1 = 0,
_unused16: u16 = 0,
};
///break and dead-time register
pub const bdtr = Register(bdtr_val).init(0x40012C00 + 0x44);
//////////////////////////
///DCR
const dcr_val = packed struct {
///DBA [0:4]
///DMA base address
dba: u5 = 0,
_unused5: u3 = 0,
///DBL [8:12]
///DMA burst length
dbl: u5 = 0,
_unused13: u19 = 0,
};
///DMA control register
pub const dcr = Register(dcr_val).init(0x40012C00 + 0x48);
//////////////////////////
///DMAR
const dmar_val = packed struct {
///DMAB [0:15]
///DMA register for burst
///accesses
dmab: u16 = 0,
_unused16: u16 = 0,
};
///DMA address for full transfer
pub const dmar = Register(dmar_val).init(0x40012C00 + 0x4C);
};
///General-purpose-timers
pub const tim3 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Counter is not stopped at update event
disabled = 0,
///Counter stops counting at the next update event (clearing the CEN bit)
enabled = 1,
} = .disabled,
///DIR [4:4]
///Direction
dir: packed enum(u1) {
///Counter used as upcounter
up = 0,
///Counter used as downcounter
down = 1,
} = .up,
///CMS [5:6]
///Center-aligned mode
///selection
cms: packed enum(u2) {
///The counter counts up or down depending on the direction bit
edge_aligned = 0,
///The counter counts up and down alternatively. Output compare interrupt flags are set only when the counter is counting down.
center_aligned1 = 1,
///The counter counts up and down alternatively. Output compare interrupt flags are set only when the counter is counting up.
center_aligned2 = 2,
///The counter counts up and down alternatively. Output compare interrupt flags are set both when the counter is counting up or down.
center_aligned3 = 3,
} = .edge_aligned,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40000400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u3 = 0,
///CCDS [3:3]
///Capture/compare DMA
///selection
ccds: packed enum(u1) {
///CCx DMA request sent when CCx event occurs
on_compare = 0,
///CCx DMA request sent when update event occurs
on_update = 1,
} = .on_compare,
///MMS [4:6]
///Master mode selection
mms: packed enum(u3) {
///The UG bit from the TIMx_EGR register is used as trigger output
reset = 0,
///The counter enable signal, CNT_EN, is used as trigger output
enable = 1,
///The update event is selected as trigger output
update = 2,
///The trigger output send a positive pulse when the CC1IF flag it to be set, as soon as a capture or a compare match occurred
compare_pulse = 3,
///OC1REF signal is used as trigger output
compare_oc1 = 4,
///OC2REF signal is used as trigger output
compare_oc2 = 5,
///OC3REF signal is used as trigger output
compare_oc3 = 6,
///OC4REF signal is used as trigger output
compare_oc4 = 7,
} = .reset,
///TI1S [7:7]
///TI1 selection
ti1s: packed enum(u1) {
///The TIMx_CH1 pin is connected to TI1 input
normal = 0,
///The TIMx_CH1, CH2, CH3 pins are connected to TI1 input
xor = 1,
} = .normal,
_unused8: u24 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40000400 + 0x4);
//////////////////////////
///SMCR
const smcr_val = packed struct {
///SMS [0:2]
///Slave mode selection
sms: packed enum(u3) {
///Slave mode disabled - if CEN = ‘1 then the prescaler is clocked directly by the internal clock.
disabled = 0,
///Encoder mode 1 - Counter counts up/down on TI2FP1 edge depending on TI1FP2 level.
encoder_mode_1 = 1,
///Encoder mode 2 - Counter counts up/down on TI1FP2 edge depending on TI2FP1 level.
encoder_mode_2 = 2,
///Encoder mode 3 - Counter counts up/down on both TI1FP1 and TI2FP2 edges depending on the level of the other input.
encoder_mode_3 = 3,
///Reset Mode - Rising edge of the selected trigger input (TRGI) reinitializes the counter and generates an update of the registers.
reset_mode = 4,
///Gated Mode - The counter clock is enabled when the trigger input (TRGI) is high. The counter stops (but is not reset) as soon as the trigger becomes low. Both start and stop of the counter are controlled.
gated_mode = 5,
///Trigger Mode - The counter starts at a rising edge of the trigger TRGI (but it is not reset). Only the start of the counter is controlled.
trigger_mode = 6,
///External Clock Mode 1 - Rising edges of the selected trigger (TRGI) clock the counter.
ext_clock_mode = 7,
} = .disabled,
_unused3: u1 = 0,
///TS [4:6]
///Trigger selection
ts: packed enum(u3) {
///Internal Trigger 0 (ITR0)
itr0 = 0,
///Internal Trigger 1 (ITR1)
itr1 = 1,
///Internal Trigger 2 (ITR2)
itr2 = 2,
///TI1 Edge Detector (TI1F_ED)
ti1f_ed = 4,
///Filtered Timer Input 1 (TI1FP1)
ti1fp1 = 5,
///Filtered Timer Input 2 (TI2FP2)
ti2fp2 = 6,
///External Trigger input (ETRF)
etrf = 7,
} = .itr0,
///MSM [7:7]
///Master/Slave mode
msm: packed enum(u1) {
///No action
no_sync = 0,
///The effect of an event on the trigger input (TRGI) is delayed to allow a perfect synchronization between the current timer and its slaves (through TRGO). It is useful if we want to synchronize several timers on a single external event.
sync = 1,
} = .no_sync,
///ETF [8:11]
///External trigger filter
etf: packed enum(u4) {
///No filter, sampling is done at fDTS
no_filter = 0,
///fSAMPLING=fCK_INT, N=2
fck_int_n2 = 1,
///fSAMPLING=fCK_INT, N=4
fck_int_n4 = 2,
///fSAMPLING=fCK_INT, N=8
fck_int_n8 = 3,
///fSAMPLING=fDTS/2, N=6
fdts_div2_n6 = 4,
///fSAMPLING=fDTS/2, N=8
fdts_div2_n8 = 5,
///fSAMPLING=fDTS/4, N=6
fdts_div4_n6 = 6,
///fSAMPLING=fDTS/4, N=8
fdts_div4_n8 = 7,
///fSAMPLING=fDTS/8, N=6
fdts_div8_n6 = 8,
///fSAMPLING=fDTS/8, N=8
fdts_div8_n8 = 9,
///fSAMPLING=fDTS/16, N=5
fdts_div16_n5 = 10,
///fSAMPLING=fDTS/16, N=6
fdts_div16_n6 = 11,
///fSAMPLING=fDTS/16, N=8
fdts_div16_n8 = 12,
///fSAMPLING=fDTS/32, N=5
fdts_div32_n5 = 13,
///fSAMPLING=fDTS/32, N=6
fdts_div32_n6 = 14,
///fSAMPLING=fDTS/32, N=8
fdts_div32_n8 = 15,
} = .no_filter,
///ETPS [12:13]
///External trigger prescaler
etps: packed enum(u2) {
///Prescaler OFF
div1 = 0,
///ETRP frequency divided by 2
div2 = 1,
///ETRP frequency divided by 4
div4 = 2,
///ETRP frequency divided by 8
div8 = 3,
} = .div1,
///ECE [14:14]
///External clock enable
ece: packed enum(u1) {
///External clock mode 2 disabled
disabled = 0,
///External clock mode 2 enabled. The counter is clocked by any active edge on the ETRF signal.
enabled = 1,
} = .disabled,
///ETP [15:15]
///External trigger polarity
etp: packed enum(u1) {
///ETR is noninverted, active at high level or rising edge
not_inverted = 0,
///ETR is inverted, active at low level or falling edge
inverted = 1,
} = .not_inverted,
_unused16: u16 = 0,
};
///slave mode control register
pub const smcr = Register(smcr_val).init(0x40000400 + 0x8);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: u1 = 0,
///CC2IE [2:2]
///Capture/Compare 2 interrupt
///enable
cc2ie: u1 = 0,
///CC3IE [3:3]
///Capture/Compare 3 interrupt
///enable
cc3ie: u1 = 0,
///CC4IE [4:4]
///Capture/Compare 4 interrupt
///enable
cc4ie: packed enum(u1) {
///CCx interrupt disabled
disabled = 0,
///CCx interrupt enabled
enabled = 1,
} = .disabled,
_unused5: u1 = 0,
///TIE [6:6]
///Trigger interrupt enable
tie: packed enum(u1) {
///Trigger interrupt disabled
disabled = 0,
///Trigger interrupt enabled
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///UDE [8:8]
///Update DMA request enable
ude: packed enum(u1) {
///Update DMA request disabled
disabled = 0,
///Update DMA request enabled
enabled = 1,
} = .disabled,
///CC1DE [9:9]
///Capture/Compare 1 DMA request
///enable
cc1de: u1 = 0,
///CC2DE [10:10]
///Capture/Compare 2 DMA request
///enable
cc2de: u1 = 0,
///CC3DE [11:11]
///Capture/Compare 3 DMA request
///enable
cc3de: u1 = 0,
///CC4DE [12:12]
///Capture/Compare 4 DMA request
///enable
cc4de: packed enum(u1) {
///CCx DMA request disabled
disabled = 0,
///CCx DMA request enabled
enabled = 1,
} = .disabled,
///COMDE [13:13]
///COM DMA request enable
comde: u1 = 0,
///TDE [14:14]
///Trigger DMA request enable
tde: packed enum(u1) {
///Trigger DMA request disabled
disabled = 0,
///Trigger DMA request enabled
enabled = 1,
} = .disabled,
_unused15: u17 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40000400 + 0xC);
//////////////////////////
///SR
const sr_val_read = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: u1 = 0,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
///CC2IF [2:2]
///Capture/Compare 2 interrupt
///flag
cc2if: u1 = 0,
///CC3IF [3:3]
///Capture/Compare 3 interrupt
///flag
cc3if: u1 = 0,
///CC4IF [4:4]
///Capture/Compare 4 interrupt
///flag
cc4if: packed enum(u1) {
///If CC1 is an output: The content of the counter TIMx_CNT matches the content of the TIMx_CCR1 register. If CC1 is an input: The counter value has been captured in TIMx_CCR1 register.
match = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: packed enum(u1) {
///No trigger event occurred
no_trigger = 0,
///Trigger interrupt pending
trigger = 1,
} = .no_trigger,
_unused7: u2 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
///CC2OF [10:10]
///Capture/compare 2 overcapture
///flag
cc2of: u1 = 0,
///CC3OF [11:11]
///Capture/Compare 3 overcapture
///flag
cc3of: u1 = 0,
///CC4OF [12:12]
///Capture/Compare 4 overcapture
///flag
cc4of: packed enum(u1) {
///The counter value has been captured in TIMx_CCRx register while CCxIF flag was already set
overcapture = 1,
_zero = 0,
} = ._zero,
_unused13: u19 = 0,
};
const sr_val_write = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: u1 = 0,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
///CC2IF [2:2]
///Capture/Compare 2 interrupt
///flag
cc2if: u1 = 0,
///CC3IF [3:3]
///Capture/Compare 3 interrupt
///flag
cc3if: u1 = 0,
///CC4IF [4:4]
///Capture/Compare 4 interrupt
///flag
cc4if: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
_unused5: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
_unused7: u2 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
///CC2OF [10:10]
///Capture/compare 2 overcapture
///flag
cc2of: u1 = 0,
///CC3OF [11:11]
///Capture/Compare 3 overcapture
///flag
cc3of: u1 = 0,
///CC4OF [12:12]
///Capture/Compare 4 overcapture
///flag
cc4of: packed enum(u1) {
///Clear flag
clear = 0,
} = .clear,
_unused13: u19 = 0,
};
///status register
pub const sr = RegisterRW(sr_val_read, sr_val_write).init(0x40000400 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
///CC2G [2:2]
///Capture/compare 2
///generation
cc2g: u1 = 0,
///CC3G [3:3]
///Capture/compare 3
///generation
cc3g: u1 = 0,
///CC4G [4:4]
///Capture/compare 4
///generation
cc4g: u1 = 0,
_unused5: u1 = 0,
///TG [6:6]
///Trigger generation
tg: u1 = 0,
_unused7: u25 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40000400 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: packed enum(u2) {
///CC1 channel is configured as output
output = 0,
} = .output,
///OC1FE [2:2]
///Output compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output compare 1 preload
///enable
oc1pe: packed enum(u1) {
///Preload register on CCR1 disabled. New values written to CCR1 are taken into account immediately
disabled = 0,
///Preload register on CCR1 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC1M [4:6]
///Output compare 1 mode
oc1m: u3 = 0,
///OC1CE [7:7]
///Output compare 1 clear
///enable
oc1ce: u1 = 0,
///CC2S [8:9]
///Capture/Compare 2
///selection
cc2s: packed enum(u2) {
///CC2 channel is configured as output
output = 0,
} = .output,
///OC2FE [10:10]
///Output compare 2 fast
///enable
oc2fe: u1 = 0,
///OC2PE [11:11]
///Output compare 2 preload
///enable
oc2pe: packed enum(u1) {
///Preload register on CCR2 disabled. New values written to CCR2 are taken into account immediately
disabled = 0,
///Preload register on CCR2 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC2M [12:14]
///Output compare 2 mode
oc2m: packed enum(u3) {
///The comparison between the output compare register TIMx_CCRy and the counter TIMx_CNT has no effect on the outputs
frozen = 0,
///Set channel to active level on match. OCyREF signal is forced high when the counter matches the capture/compare register
active_on_match = 1,
///Set channel to inactive level on match. OCyREF signal is forced low when the counter matches the capture/compare register
inactive_on_match = 2,
///OCyREF toggles when TIMx_CNT=TIMx_CCRy
toggle = 3,
///OCyREF is forced low
force_inactive = 4,
///OCyREF is forced high
force_active = 5,
///In upcounting, channel is active as long as TIMx_CNT<TIMx_CCRy else inactive. In downcounting, channel is inactive as long as TIMx_CNT>TIMx_CCRy else active
pwm_mode1 = 6,
///Inversely to PwmMode1
pwm_mode2 = 7,
} = .frozen,
///OC2CE [15:15]
///Output compare 2 clear
///enable
oc2ce: u1 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 1 (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40000400 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: packed enum(u2) {
///CC1 channel is configured as input, IC1 is mapped on TI1
ti1 = 1,
///CC1 channel is configured as input, IC1 is mapped on TI2
ti2 = 2,
///CC1 channel is configured as input, IC1 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: packed enum(u4) {
///No filter, sampling is done at fDTS
no_filter = 0,
///fSAMPLING=fCK_INT, N=2
fck_int_n2 = 1,
///fSAMPLING=fCK_INT, N=4
fck_int_n4 = 2,
///fSAMPLING=fCK_INT, N=8
fck_int_n8 = 3,
///fSAMPLING=fDTS/2, N=6
fdts_div2_n6 = 4,
///fSAMPLING=fDTS/2, N=8
fdts_div2_n8 = 5,
///fSAMPLING=fDTS/4, N=6
fdts_div4_n6 = 6,
///fSAMPLING=fDTS/4, N=8
fdts_div4_n8 = 7,
///fSAMPLING=fDTS/8, N=6
fdts_div8_n6 = 8,
///fSAMPLING=fDTS/8, N=8
fdts_div8_n8 = 9,
///fSAMPLING=fDTS/16, N=5
fdts_div16_n5 = 10,
///fSAMPLING=fDTS/16, N=6
fdts_div16_n6 = 11,
///fSAMPLING=fDTS/16, N=8
fdts_div16_n8 = 12,
///fSAMPLING=fDTS/32, N=5
fdts_div32_n5 = 13,
///fSAMPLING=fDTS/32, N=6
fdts_div32_n6 = 14,
///fSAMPLING=fDTS/32, N=8
fdts_div32_n8 = 15,
} = .no_filter,
///CC2S [8:9]
///Capture/compare 2
///selection
cc2s: packed enum(u2) {
///CC2 channel is configured as input, IC2 is mapped on TI2
ti2 = 1,
///CC2 channel is configured as input, IC2 is mapped on TI1
ti1 = 2,
///CC2 channel is configured as input, IC2 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC2PSC [10:11]
///Input capture 2 prescaler
ic2psc: u2 = 0,
///IC2F [12:15]
///Input capture 2 filter
ic2f: u4 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 1 (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40000400 + 0x18);
//////////////////////////
///CCMR2_Output
const ccmr2_output_val = packed struct {
///CC3S [0:1]
///Capture/Compare 3
///selection
cc3s: packed enum(u2) {
///CC3 channel is configured as output
output = 0,
} = .output,
///OC3FE [2:2]
///Output compare 3 fast
///enable
oc3fe: u1 = 0,
///OC3PE [3:3]
///Output compare 3 preload
///enable
oc3pe: packed enum(u1) {
///Preload register on CCR3 disabled. New values written to CCR3 are taken into account immediately
disabled = 0,
///Preload register on CCR3 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC3M [4:6]
///Output compare 3 mode
oc3m: u3 = 0,
///OC3CE [7:7]
///Output compare 3 clear
///enable
oc3ce: u1 = 0,
///CC4S [8:9]
///Capture/Compare 4
///selection
cc4s: packed enum(u2) {
///CC4 channel is configured as output
output = 0,
} = .output,
///OC4FE [10:10]
///Output compare 4 fast
///enable
oc4fe: u1 = 0,
///OC4PE [11:11]
///Output compare 4 preload
///enable
oc4pe: packed enum(u1) {
///Preload register on CCR4 disabled. New values written to CCR4 are taken into account immediately
disabled = 0,
///Preload register on CCR4 enabled. Preload value is loaded into active register on each update event
enabled = 1,
} = .disabled,
///OC4M [12:14]
///Output compare 4 mode
oc4m: packed enum(u3) {
///The comparison between the output compare register TIMx_CCRy and the counter TIMx_CNT has no effect on the outputs
frozen = 0,
///Set channel to active level on match. OCyREF signal is forced high when the counter matches the capture/compare register
active_on_match = 1,
///Set channel to inactive level on match. OCyREF signal is forced low when the counter matches the capture/compare register
inactive_on_match = 2,
///OCyREF toggles when TIMx_CNT=TIMx_CCRy
toggle = 3,
///OCyREF is forced low
force_inactive = 4,
///OCyREF is forced high
force_active = 5,
///In upcounting, channel is active as long as TIMx_CNT<TIMx_CCRy else inactive. In downcounting, channel is inactive as long as TIMx_CNT>TIMx_CCRy else active
pwm_mode1 = 6,
///Inversely to PwmMode1
pwm_mode2 = 7,
} = .frozen,
///OC4CE [15:15]
///Output compare 4 clear
///enable
oc4ce: u1 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 2 (output
///mode)
pub const ccmr2_output = Register(ccmr2_output_val).init(0x40000400 + 0x1C);
//////////////////////////
///CCMR2_Input
const ccmr2_input_val = packed struct {
///CC3S [0:1]
///Capture/Compare 3
///selection
cc3s: packed enum(u2) {
///CC3 channel is configured as input, IC3 is mapped on TI3
ti3 = 1,
///CC3 channel is configured as input, IC3 is mapped on TI4
ti4 = 2,
///CC3 channel is configured as input, IC3 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC3PSC [2:3]
///Input capture 3 prescaler
ic3psc: u2 = 0,
///IC3F [4:7]
///Input capture 3 filter
ic3f: u4 = 0,
///CC4S [8:9]
///Capture/Compare 4
///selection
cc4s: packed enum(u2) {
///CC4 channel is configured as input, IC4 is mapped on TI4
ti4 = 1,
///CC4 channel is configured as input, IC4 is mapped on TI3
ti3 = 2,
///CC4 channel is configured as input, IC4 is mapped on TRC
trc = 3,
_zero = 0,
} = ._zero,
///IC4PSC [10:11]
///Input capture 4 prescaler
ic4psc: u2 = 0,
///IC4F [12:15]
///Input capture 4 filter
ic4f: u4 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 2 (input
///mode)
pub const ccmr2_input = Register(ccmr2_input_val).init(0x40000400 + 0x1C);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
_unused2: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
///CC2E [4:4]
///Capture/Compare 2 output
///enable
cc2e: u1 = 0,
///CC2P [5:5]
///Capture/Compare 2 output
///Polarity
cc2p: u1 = 0,
_unused6: u1 = 0,
///CC2NP [7:7]
///Capture/Compare 2 output
///Polarity
cc2np: u1 = 0,
///CC3E [8:8]
///Capture/Compare 3 output
///enable
cc3e: u1 = 0,
///CC3P [9:9]
///Capture/Compare 3 output
///Polarity
cc3p: u1 = 0,
_unused10: u1 = 0,
///CC3NP [11:11]
///Capture/Compare 3 output
///Polarity
cc3np: u1 = 0,
///CC4E [12:12]
///Capture/Compare 4 output
///enable
cc4e: u1 = 0,
///CC4P [13:13]
///Capture/Compare 3 output
///Polarity
cc4p: u1 = 0,
_unused14: u1 = 0,
///CC4NP [15:15]
///Capture/Compare 4 output
///Polarity
cc4np: u1 = 0,
_unused16: u16 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40000400 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///Counter value
cnt: u16 = 0,
///CNT_H [16:31]
///High counter value (TIM2
///only)
cnt_h: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40000400 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40000400 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
///ARR_H [16:31]
///High Auto-reload value (TIM2
///only)
arr_h: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40000400 + 0x2C);
//////////////////////////
///CCR%s
const ccr_val = packed struct {
///CCR [0:15]
///Capture/Compare 1 value
ccr: u16 = 0,
///CCR1_H [16:31]
///High Capture/Compare 1 value (TIM2
///only)
ccr1_h: u16 = 0,
};
///capture/compare register 1
pub const ccr = Register(ccr_val).initRange(0x40000400 + 0x34, 4, 4);
//////////////////////////
///DCR
const dcr_val = packed struct {
///DBA [0:4]
///DMA base address
dba: u5 = 0,
_unused5: u3 = 0,
///DBL [8:12]
///DMA burst length
dbl: u5 = 0,
_unused13: u19 = 0,
};
///DMA control register
pub const dcr = Register(dcr_val).init(0x40000400 + 0x48);
//////////////////////////
///DMAR
const dmar_val = packed struct {
///DMAR [0:15]
///DMA register for burst
///accesses
dmar: u16 = 0,
_unused16: u16 = 0,
};
///DMA address for full transfer
pub const dmar = Register(dmar_val).init(0x40000400 + 0x4C);
};
///General-purpose-timers
pub const tim14 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
_unused3: u4 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40002000 + 0x0);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: u1 = 0,
_unused2: u30 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40002000 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
_unused2: u7 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
_unused10: u22 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40002000 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
_unused2: u30 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40002000 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///OC1FE [2:2]
///Output compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output Compare 1 preload
///enable
oc1pe: u1 = 0,
///OC1M [4:6]
///Output Compare 1 mode
oc1m: u3 = 0,
_unused7: u25 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40002000 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: u4 = 0,
_unused8: u24 = 0,
};
///capture/compare mode register (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40002000 + 0x18);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
_unused2: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
_unused4: u28 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40002000 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40002000 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40002000 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40002000 + 0x2C);
//////////////////////////
///CCR%s
const ccr_val = packed struct {
///CCR [0:15]
///Capture/Compare 1 value
ccr: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 1
pub const ccr = Register(ccr_val).initRange(0x40002000 + 0x34, 0, 1);
//////////////////////////
///OR
const _or_val = packed struct {
///RMP [0:1]
///Timer input 1 remap
rmp: u2 = 0,
_unused2: u30 = 0,
};
///option register
pub const _or = Register(_or_val).init(0x40002000 + 0x50);
};
///Basic-timers
pub const tim6 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Counter is not stopped at update event
disabled = 0,
///Counter stops counting at the next update event (clearing the CEN bit)
enabled = 1,
} = .disabled,
_unused4: u3 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
_unused8: u24 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40001000 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///MMS [4:6]
///Master mode selection
mms: packed enum(u3) {
///Use UG bit from TIMx_EGR register
reset = 0,
///Use CNT bit from TIMx_CEN register
enable = 1,
///Use the update event
update = 2,
} = .reset,
_unused7: u25 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40001000 + 0x4);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
_unused1: u7 = 0,
///UDE [8:8]
///Update DMA request enable
ude: packed enum(u1) {
///Update DMA request disabled
disabled = 0,
///Update DMA request enabled
enabled = 1,
} = .disabled,
_unused9: u23 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40001000 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
_unused1: u31 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40001000 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
_unused1: u31 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40001000 + 0x14);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///Low counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40001000 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40001000 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Low Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40001000 + 0x2C);
};
///Basic-timers
pub const tim7 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Counter is not stopped at update event
disabled = 0,
///Counter stops counting at the next update event (clearing the CEN bit)
enabled = 1,
} = .disabled,
_unused4: u3 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
_unused8: u24 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40001400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///MMS [4:6]
///Master mode selection
mms: packed enum(u3) {
///Use UG bit from TIMx_EGR register
reset = 0,
///Use CNT bit from TIMx_CEN register
enable = 1,
///Use the update event
update = 2,
} = .reset,
_unused7: u25 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40001400 + 0x4);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
_unused1: u7 = 0,
///UDE [8:8]
///Update DMA request enable
ude: packed enum(u1) {
///Update DMA request disabled
disabled = 0,
///Update DMA request enabled
enabled = 1,
} = .disabled,
_unused9: u23 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40001400 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
_unused1: u31 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40001400 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
_unused1: u31 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40001400 + 0x14);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///Low counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40001400 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40001400 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Low Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40001400 + 0x2C);
};
///External interrupt/event
///controller
pub const exti = struct {
//////////////////////////
///IMR
const imr_val = packed struct {
///MR0 [0:0]
///Interrupt Mask on line 0
mr0: packed enum(u1) {
///Interrupt request line is masked
masked = 0,
///Interrupt request line is unmasked
unmasked = 1,
} = .masked,
///MR1 [1:1]
///Interrupt Mask on line 1
mr1: u1 = 0,
///MR2 [2:2]
///Interrupt Mask on line 2
mr2: u1 = 0,
///MR3 [3:3]
///Interrupt Mask on line 3
mr3: u1 = 0,
///MR4 [4:4]
///Interrupt Mask on line 4
mr4: u1 = 0,
///MR5 [5:5]
///Interrupt Mask on line 5
mr5: u1 = 0,
///MR6 [6:6]
///Interrupt Mask on line 6
mr6: u1 = 0,
///MR7 [7:7]
///Interrupt Mask on line 7
mr7: u1 = 0,
///MR8 [8:8]
///Interrupt Mask on line 8
mr8: u1 = 0,
///MR9 [9:9]
///Interrupt Mask on line 9
mr9: u1 = 0,
///MR10 [10:10]
///Interrupt Mask on line 10
mr10: u1 = 0,
///MR11 [11:11]
///Interrupt Mask on line 11
mr11: u1 = 0,
///MR12 [12:12]
///Interrupt Mask on line 12
mr12: u1 = 0,
///MR13 [13:13]
///Interrupt Mask on line 13
mr13: u1 = 0,
///MR14 [14:14]
///Interrupt Mask on line 14
mr14: u1 = 0,
///MR15 [15:15]
///Interrupt Mask on line 15
mr15: u1 = 0,
///MR16 [16:16]
///Interrupt Mask on line 16
mr16: u1 = 0,
///MR17 [17:17]
///Interrupt Mask on line 17
mr17: u1 = 0,
///MR18 [18:18]
///Interrupt Mask on line 18
mr18: u1 = 1,
///MR19 [19:19]
///Interrupt Mask on line 19
mr19: u1 = 0,
///MR20 [20:20]
///Interrupt Mask on line 20
mr20: u1 = 1,
///MR21 [21:21]
///Interrupt Mask on line 21
mr21: u1 = 0,
///MR22 [22:22]
///Interrupt Mask on line 22
mr22: u1 = 0,
///MR23 [23:23]
///Interrupt Mask on line 23
mr23: u1 = 1,
///MR24 [24:24]
///Interrupt Mask on line 24
mr24: u1 = 1,
///MR25 [25:25]
///Interrupt Mask on line 25
mr25: u1 = 1,
///MR26 [26:26]
///Interrupt Mask on line 26
mr26: u1 = 1,
///MR27 [27:27]
///Interrupt Mask on line 27
mr27: u1 = 1,
_unused28: u4 = 0,
};
///Interrupt mask register
///(EXTI_IMR)
pub const imr = Register(imr_val).init(0x40010400 + 0x0);
//////////////////////////
///EMR
const emr_val = packed struct {
///MR0 [0:0]
///Event Mask on line 0
mr0: packed enum(u1) {
///Interrupt request line is masked
masked = 0,
///Interrupt request line is unmasked
unmasked = 1,
} = .masked,
///MR1 [1:1]
///Event Mask on line 1
mr1: u1 = 0,
///MR2 [2:2]
///Event Mask on line 2
mr2: u1 = 0,
///MR3 [3:3]
///Event Mask on line 3
mr3: u1 = 0,
///MR4 [4:4]
///Event Mask on line 4
mr4: u1 = 0,
///MR5 [5:5]
///Event Mask on line 5
mr5: u1 = 0,
///MR6 [6:6]
///Event Mask on line 6
mr6: u1 = 0,
///MR7 [7:7]
///Event Mask on line 7
mr7: u1 = 0,
///MR8 [8:8]
///Event Mask on line 8
mr8: u1 = 0,
///MR9 [9:9]
///Event Mask on line 9
mr9: u1 = 0,
///MR10 [10:10]
///Event Mask on line 10
mr10: u1 = 0,
///MR11 [11:11]
///Event Mask on line 11
mr11: u1 = 0,
///MR12 [12:12]
///Event Mask on line 12
mr12: u1 = 0,
///MR13 [13:13]
///Event Mask on line 13
mr13: u1 = 0,
///MR14 [14:14]
///Event Mask on line 14
mr14: u1 = 0,
///MR15 [15:15]
///Event Mask on line 15
mr15: u1 = 0,
///MR16 [16:16]
///Event Mask on line 16
mr16: u1 = 0,
///MR17 [17:17]
///Event Mask on line 17
mr17: u1 = 0,
///MR18 [18:18]
///Event Mask on line 18
mr18: u1 = 0,
///MR19 [19:19]
///Event Mask on line 19
mr19: u1 = 0,
///MR20 [20:20]
///Event Mask on line 20
mr20: u1 = 0,
///MR21 [21:21]
///Event Mask on line 21
mr21: u1 = 0,
///MR22 [22:22]
///Event Mask on line 22
mr22: u1 = 0,
///MR23 [23:23]
///Event Mask on line 23
mr23: u1 = 0,
///MR24 [24:24]
///Event Mask on line 24
mr24: u1 = 0,
///MR25 [25:25]
///Event Mask on line 25
mr25: u1 = 0,
///MR26 [26:26]
///Event Mask on line 26
mr26: u1 = 0,
///MR27 [27:27]
///Event Mask on line 27
mr27: u1 = 0,
_unused28: u4 = 0,
};
///Event mask register (EXTI_EMR)
pub const emr = Register(emr_val).init(0x40010400 + 0x4);
//////////////////////////
///RTSR
const rtsr_val = packed struct {
///TR0 [0:0]
///Rising trigger event configuration of
///line 0
tr0: packed enum(u1) {
///Rising edge trigger is disabled
disabled = 0,
///Rising edge trigger is enabled
enabled = 1,
} = .disabled,
///TR1 [1:1]
///Rising trigger event configuration of
///line 1
tr1: u1 = 0,
///TR2 [2:2]
///Rising trigger event configuration of
///line 2
tr2: u1 = 0,
///TR3 [3:3]
///Rising trigger event configuration of
///line 3
tr3: u1 = 0,
///TR4 [4:4]
///Rising trigger event configuration of
///line 4
tr4: u1 = 0,
///TR5 [5:5]
///Rising trigger event configuration of
///line 5
tr5: u1 = 0,
///TR6 [6:6]
///Rising trigger event configuration of
///line 6
tr6: u1 = 0,
///TR7 [7:7]
///Rising trigger event configuration of
///line 7
tr7: u1 = 0,
///TR8 [8:8]
///Rising trigger event configuration of
///line 8
tr8: u1 = 0,
///TR9 [9:9]
///Rising trigger event configuration of
///line 9
tr9: u1 = 0,
///TR10 [10:10]
///Rising trigger event configuration of
///line 10
tr10: u1 = 0,
///TR11 [11:11]
///Rising trigger event configuration of
///line 11
tr11: u1 = 0,
///TR12 [12:12]
///Rising trigger event configuration of
///line 12
tr12: u1 = 0,
///TR13 [13:13]
///Rising trigger event configuration of
///line 13
tr13: u1 = 0,
///TR14 [14:14]
///Rising trigger event configuration of
///line 14
tr14: u1 = 0,
///TR15 [15:15]
///Rising trigger event configuration of
///line 15
tr15: u1 = 0,
///TR16 [16:16]
///Rising trigger event configuration of
///line 16
tr16: u1 = 0,
///TR17 [17:17]
///Rising trigger event configuration of
///line 17
tr17: u1 = 0,
_unused18: u1 = 0,
///TR19 [19:19]
///Rising trigger event configuration of
///line 19
tr19: u1 = 0,
_unused20: u12 = 0,
};
///Rising Trigger selection register
///(EXTI_RTSR)
pub const rtsr = Register(rtsr_val).init(0x40010400 + 0x8);
//////////////////////////
///FTSR
const ftsr_val = packed struct {
///TR0 [0:0]
///Falling trigger event configuration of
///line 0
tr0: packed enum(u1) {
///Falling edge trigger is disabled
disabled = 0,
///Falling edge trigger is enabled
enabled = 1,
} = .disabled,
///TR1 [1:1]
///Falling trigger event configuration of
///line 1
tr1: u1 = 0,
///TR2 [2:2]
///Falling trigger event configuration of
///line 2
tr2: u1 = 0,
///TR3 [3:3]
///Falling trigger event configuration of
///line 3
tr3: u1 = 0,
///TR4 [4:4]
///Falling trigger event configuration of
///line 4
tr4: u1 = 0,
///TR5 [5:5]
///Falling trigger event configuration of
///line 5
tr5: u1 = 0,
///TR6 [6:6]
///Falling trigger event configuration of
///line 6
tr6: u1 = 0,
///TR7 [7:7]
///Falling trigger event configuration of
///line 7
tr7: u1 = 0,
///TR8 [8:8]
///Falling trigger event configuration of
///line 8
tr8: u1 = 0,
///TR9 [9:9]
///Falling trigger event configuration of
///line 9
tr9: u1 = 0,
///TR10 [10:10]
///Falling trigger event configuration of
///line 10
tr10: u1 = 0,
///TR11 [11:11]
///Falling trigger event configuration of
///line 11
tr11: u1 = 0,
///TR12 [12:12]
///Falling trigger event configuration of
///line 12
tr12: u1 = 0,
///TR13 [13:13]
///Falling trigger event configuration of
///line 13
tr13: u1 = 0,
///TR14 [14:14]
///Falling trigger event configuration of
///line 14
tr14: u1 = 0,
///TR15 [15:15]
///Falling trigger event configuration of
///line 15
tr15: u1 = 0,
///TR16 [16:16]
///Falling trigger event configuration of
///line 16
tr16: u1 = 0,
///TR17 [17:17]
///Falling trigger event configuration of
///line 17
tr17: u1 = 0,
_unused18: u1 = 0,
///TR19 [19:19]
///Falling trigger event configuration of
///line 19
tr19: u1 = 0,
_unused20: u12 = 0,
};
///Falling Trigger selection register
///(EXTI_FTSR)
pub const ftsr = Register(ftsr_val).init(0x40010400 + 0xC);
//////////////////////////
///SWIER
const swier_val = packed struct {
///SWIER0 [0:0]
///Software Interrupt on line
///0
swier0: u1 = 0,
///SWIER1 [1:1]
///Software Interrupt on line
///1
swier1: u1 = 0,
///SWIER2 [2:2]
///Software Interrupt on line
///2
swier2: u1 = 0,
///SWIER3 [3:3]
///Software Interrupt on line
///3
swier3: u1 = 0,
///SWIER4 [4:4]
///Software Interrupt on line
///4
swier4: u1 = 0,
///SWIER5 [5:5]
///Software Interrupt on line
///5
swier5: u1 = 0,
///SWIER6 [6:6]
///Software Interrupt on line
///6
swier6: u1 = 0,
///SWIER7 [7:7]
///Software Interrupt on line
///7
swier7: u1 = 0,
///SWIER8 [8:8]
///Software Interrupt on line
///8
swier8: u1 = 0,
///SWIER9 [9:9]
///Software Interrupt on line
///9
swier9: u1 = 0,
///SWIER10 [10:10]
///Software Interrupt on line
///10
swier10: u1 = 0,
///SWIER11 [11:11]
///Software Interrupt on line
///11
swier11: u1 = 0,
///SWIER12 [12:12]
///Software Interrupt on line
///12
swier12: u1 = 0,
///SWIER13 [13:13]
///Software Interrupt on line
///13
swier13: u1 = 0,
///SWIER14 [14:14]
///Software Interrupt on line
///14
swier14: u1 = 0,
///SWIER15 [15:15]
///Software Interrupt on line
///15
swier15: u1 = 0,
///SWIER16 [16:16]
///Software Interrupt on line
///16
swier16: u1 = 0,
///SWIER17 [17:17]
///Software Interrupt on line
///17
swier17: u1 = 0,
_unused18: u1 = 0,
///SWIER19 [19:19]
///Software Interrupt on line
///19
swier19: u1 = 0,
_unused20: u12 = 0,
};
///Software interrupt event register
///(EXTI_SWIER)
pub const swier = Register(swier_val).init(0x40010400 + 0x10);
//////////////////////////
///PR
const pr_val_read = packed struct {
///PR0 [0:0]
///Pending bit 0
pr0: packed enum(u1) {
///No trigger request occurred
not_pending = 0,
///Selected trigger request occurred
pending = 1,
} = .not_pending,
///PR1 [1:1]
///Pending bit 1
pr1: u1 = 0,
///PR2 [2:2]
///Pending bit 2
pr2: u1 = 0,
///PR3 [3:3]
///Pending bit 3
pr3: u1 = 0,
///PR4 [4:4]
///Pending bit 4
pr4: u1 = 0,
///PR5 [5:5]
///Pending bit 5
pr5: u1 = 0,
///PR6 [6:6]
///Pending bit 6
pr6: u1 = 0,
///PR7 [7:7]
///Pending bit 7
pr7: u1 = 0,
///PR8 [8:8]
///Pending bit 8
pr8: u1 = 0,
///PR9 [9:9]
///Pending bit 9
pr9: u1 = 0,
///PR10 [10:10]
///Pending bit 10
pr10: u1 = 0,
///PR11 [11:11]
///Pending bit 11
pr11: u1 = 0,
///PR12 [12:12]
///Pending bit 12
pr12: u1 = 0,
///PR13 [13:13]
///Pending bit 13
pr13: u1 = 0,
///PR14 [14:14]
///Pending bit 14
pr14: u1 = 0,
///PR15 [15:15]
///Pending bit 15
pr15: u1 = 0,
///PR16 [16:16]
///Pending bit 16
pr16: u1 = 0,
///PR17 [17:17]
///Pending bit 17
pr17: u1 = 0,
_unused18: u1 = 0,
///PR19 [19:19]
///Pending bit 19
pr19: u1 = 0,
_unused20: u12 = 0,
};
const pr_val_write = packed struct {
///PR0 [0:0]
///Pending bit 0
pr0: packed enum(u1) {
///Clears pending bit
clear = 1,
_zero = 0,
} = ._zero,
///PR1 [1:1]
///Pending bit 1
pr1: u1 = 0,
///PR2 [2:2]
///Pending bit 2
pr2: u1 = 0,
///PR3 [3:3]
///Pending bit 3
pr3: u1 = 0,
///PR4 [4:4]
///Pending bit 4
pr4: u1 = 0,
///PR5 [5:5]
///Pending bit 5
pr5: u1 = 0,
///PR6 [6:6]
///Pending bit 6
pr6: u1 = 0,
///PR7 [7:7]
///Pending bit 7
pr7: u1 = 0,
///PR8 [8:8]
///Pending bit 8
pr8: u1 = 0,
///PR9 [9:9]
///Pending bit 9
pr9: u1 = 0,
///PR10 [10:10]
///Pending bit 10
pr10: u1 = 0,
///PR11 [11:11]
///Pending bit 11
pr11: u1 = 0,
///PR12 [12:12]
///Pending bit 12
pr12: u1 = 0,
///PR13 [13:13]
///Pending bit 13
pr13: u1 = 0,
///PR14 [14:14]
///Pending bit 14
pr14: u1 = 0,
///PR15 [15:15]
///Pending bit 15
pr15: u1 = 0,
///PR16 [16:16]
///Pending bit 16
pr16: u1 = 0,
///PR17 [17:17]
///Pending bit 17
pr17: u1 = 0,
_unused18: u1 = 0,
///PR19 [19:19]
///Pending bit 19
pr19: u1 = 0,
_unused20: u12 = 0,
};
///Pending register (EXTI_PR)
pub const pr = RegisterRW(pr_val_read, pr_val_write).init(0x40010400 + 0x14);
};
///Nested Vectored Interrupt
///Controller
pub const nvic = struct {
//////////////////////////
///ISER
const iser_val = packed struct {
///SETENA [0:31]
///SETENA
setena: u32 = 0,
};
///Interrupt Set Enable Register
pub const iser = Register(iser_val).init(0xE000E100 + 0x0);
//////////////////////////
///ICER
const icer_val = packed struct {
///CLRENA [0:31]
///CLRENA
clrena: u32 = 0,
};
///Interrupt Clear Enable
///Register
pub const icer = Register(icer_val).init(0xE000E100 + 0x80);
//////////////////////////
///ISPR
const ispr_val = packed struct {
///SETPEND [0:31]
///SETPEND
setpend: u32 = 0,
};
///Interrupt Set-Pending Register
pub const ispr = Register(ispr_val).init(0xE000E100 + 0x100);
//////////////////////////
///ICPR
const icpr_val = packed struct {
///CLRPEND [0:31]
///CLRPEND
clrpend: u32 = 0,
};
///Interrupt Clear-Pending
///Register
pub const icpr = Register(icpr_val).init(0xE000E100 + 0x180);
//////////////////////////
///IPR0
const ipr0_val = packed struct {
_unused0: u6 = 0,
///PRI_00 [6:7]
///PRI_00
pri_00: u2 = 0,
_unused8: u6 = 0,
///PRI_01 [14:15]
///PRI_01
pri_01: u2 = 0,
_unused16: u6 = 0,
///PRI_02 [22:23]
///PRI_02
pri_02: u2 = 0,
_unused24: u6 = 0,
///PRI_03 [30:31]
///PRI_03
pri_03: u2 = 0,
};
///Interrupt Priority Register 0
pub const ipr0 = Register(ipr0_val).init(0xE000E100 + 0x300);
//////////////////////////
///IPR1
const ipr1_val = packed struct {
_unused0: u6 = 0,
///PRI_40 [6:7]
///PRI_40
pri_40: u2 = 0,
_unused8: u6 = 0,
///PRI_41 [14:15]
///PRI_41
pri_41: u2 = 0,
_unused16: u6 = 0,
///PRI_42 [22:23]
///PRI_42
pri_42: u2 = 0,
_unused24: u6 = 0,
///PRI_43 [30:31]
///PRI_43
pri_43: u2 = 0,
};
///Interrupt Priority Register 1
pub const ipr1 = Register(ipr1_val).init(0xE000E100 + 0x304);
//////////////////////////
///IPR2
const ipr2_val = packed struct {
_unused0: u6 = 0,
///PRI_80 [6:7]
///PRI_80
pri_80: u2 = 0,
_unused8: u6 = 0,
///PRI_81 [14:15]
///PRI_81
pri_81: u2 = 0,
_unused16: u6 = 0,
///PRI_82 [22:23]
///PRI_82
pri_82: u2 = 0,
_unused24: u6 = 0,
///PRI_83 [30:31]
///PRI_83
pri_83: u2 = 0,
};
///Interrupt Priority Register 2
pub const ipr2 = Register(ipr2_val).init(0xE000E100 + 0x308);
//////////////////////////
///IPR3
const ipr3_val = packed struct {
_unused0: u6 = 0,
///PRI_120 [6:7]
///PRI_120
pri_120: u2 = 0,
_unused8: u6 = 0,
///PRI_121 [14:15]
///PRI_121
pri_121: u2 = 0,
_unused16: u6 = 0,
///PRI_122 [22:23]
///PRI_122
pri_122: u2 = 0,
_unused24: u6 = 0,
///PRI_123 [30:31]
///PRI_123
pri_123: u2 = 0,
};
///Interrupt Priority Register 3
pub const ipr3 = Register(ipr3_val).init(0xE000E100 + 0x30C);
//////////////////////////
///IPR4
const ipr4_val = packed struct {
_unused0: u6 = 0,
///PRI_160 [6:7]
///PRI_160
pri_160: u2 = 0,
_unused8: u6 = 0,
///PRI_161 [14:15]
///PRI_161
pri_161: u2 = 0,
_unused16: u6 = 0,
///PRI_162 [22:23]
///PRI_162
pri_162: u2 = 0,
_unused24: u6 = 0,
///PRI_163 [30:31]
///PRI_163
pri_163: u2 = 0,
};
///Interrupt Priority Register 4
pub const ipr4 = Register(ipr4_val).init(0xE000E100 + 0x310);
//////////////////////////
///IPR5
const ipr5_val = packed struct {
_unused0: u6 = 0,
///PRI_200 [6:7]
///PRI_200
pri_200: u2 = 0,
_unused8: u6 = 0,
///PRI_201 [14:15]
///PRI_201
pri_201: u2 = 0,
_unused16: u6 = 0,
///PRI_202 [22:23]
///PRI_202
pri_202: u2 = 0,
_unused24: u6 = 0,
///PRI_203 [30:31]
///PRI_203
pri_203: u2 = 0,
};
///Interrupt Priority Register 5
pub const ipr5 = Register(ipr5_val).init(0xE000E100 + 0x314);
//////////////////////////
///IPR6
const ipr6_val = packed struct {
_unused0: u6 = 0,
///PRI_240 [6:7]
///PRI_240
pri_240: u2 = 0,
_unused8: u6 = 0,
///PRI_241 [14:15]
///PRI_241
pri_241: u2 = 0,
_unused16: u6 = 0,
///PRI_242 [22:23]
///PRI_242
pri_242: u2 = 0,
_unused24: u6 = 0,
///PRI_243 [30:31]
///PRI_243
pri_243: u2 = 0,
};
///Interrupt Priority Register 6
pub const ipr6 = Register(ipr6_val).init(0xE000E100 + 0x318);
//////////////////////////
///IPR7
const ipr7_val = packed struct {
_unused0: u6 = 0,
///PRI_280 [6:7]
///PRI_280
pri_280: u2 = 0,
_unused8: u6 = 0,
///PRI_281 [14:15]
///PRI_281
pri_281: u2 = 0,
_unused16: u6 = 0,
///PRI_282 [22:23]
///PRI_282
pri_282: u2 = 0,
_unused24: u6 = 0,
///PRI_283 [30:31]
///PRI_283
pri_283: u2 = 0,
};
///Interrupt Priority Register 7
pub const ipr7 = Register(ipr7_val).init(0xE000E100 + 0x31C);
};
///DMA controller
pub const dma1 = struct {
//////////////////////////
///ISR
const isr_val = packed struct {
///GIF1 [0:0]
///Channel 1 Global interrupt
///flag
gif1: packed enum(u1) {
///No transfer error, half event, complete event
no_event = 0,
///A transfer error, half event or complete event has occured
event = 1,
} = .no_event,
///TCIF1 [1:1]
///Channel 1 Transfer Complete
///flag
tcif1: packed enum(u1) {
///No transfer complete event
not_complete = 0,
///A transfer complete event has occured
complete = 1,
} = .not_complete,
///HTIF1 [2:2]
///Channel 1 Half Transfer Complete
///flag
htif1: packed enum(u1) {
///No half transfer event
not_half = 0,
///A half transfer event has occured
half = 1,
} = .not_half,
///TEIF1 [3:3]
///Channel 1 Transfer Error
///flag
teif1: packed enum(u1) {
///No transfer error
no_error = 0,
///A transfer error has occured
_error = 1,
} = .no_error,
///GIF2 [4:4]
///Channel 2 Global interrupt
///flag
gif2: u1 = 0,
///TCIF2 [5:5]
///Channel 2 Transfer Complete
///flag
tcif2: u1 = 0,
///HTIF2 [6:6]
///Channel 2 Half Transfer Complete
///flag
htif2: u1 = 0,
///TEIF2 [7:7]
///Channel 2 Transfer Error
///flag
teif2: u1 = 0,
///GIF3 [8:8]
///Channel 3 Global interrupt
///flag
gif3: u1 = 0,
///TCIF3 [9:9]
///Channel 3 Transfer Complete
///flag
tcif3: u1 = 0,
///HTIF3 [10:10]
///Channel 3 Half Transfer Complete
///flag
htif3: u1 = 0,
///TEIF3 [11:11]
///Channel 3 Transfer Error
///flag
teif3: u1 = 0,
///GIF4 [12:12]
///Channel 4 Global interrupt
///flag
gif4: u1 = 0,
///TCIF4 [13:13]
///Channel 4 Transfer Complete
///flag
tcif4: u1 = 0,
///HTIF4 [14:14]
///Channel 4 Half Transfer Complete
///flag
htif4: u1 = 0,
///TEIF4 [15:15]
///Channel 4 Transfer Error
///flag
teif4: u1 = 0,
///GIF5 [16:16]
///Channel 5 Global interrupt
///flag
gif5: u1 = 0,
///TCIF5 [17:17]
///Channel 5 Transfer Complete
///flag
tcif5: u1 = 0,
///HTIF5 [18:18]
///Channel 5 Half Transfer Complete
///flag
htif5: u1 = 0,
///TEIF5 [19:19]
///Channel 5 Transfer Error
///flag
teif5: u1 = 0,
///GIF6 [20:20]
///Channel 6 Global interrupt
///flag
gif6: u1 = 0,
///TCIF6 [21:21]
///Channel 6 Transfer Complete
///flag
tcif6: u1 = 0,
///HTIF6 [22:22]
///Channel 6 Half Transfer Complete
///flag
htif6: u1 = 0,
///TEIF6 [23:23]
///Channel 6 Transfer Error
///flag
teif6: u1 = 0,
///GIF7 [24:24]
///Channel 7 Global interrupt
///flag
gif7: u1 = 0,
///TCIF7 [25:25]
///Channel 7 Transfer Complete
///flag
tcif7: u1 = 0,
///HTIF7 [26:26]
///Channel 7 Half Transfer Complete
///flag
htif7: u1 = 0,
///TEIF7 [27:27]
///Channel 7 Transfer Error
///flag
teif7: u1 = 0,
_unused28: u4 = 0,
};
///DMA interrupt status register
///(DMA_ISR)
pub const isr = RegisterRW(isr_val, void).init(0x40020000 + 0x0);
//////////////////////////
///IFCR
const ifcr_val = packed struct {
///CGIF1 [0:0]
///Channel 1 Global interrupt
///clear
cgif1: packed enum(u1) {
///Clears the GIF, TEIF, HTIF, TCIF flags in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTCIF1 [1:1]
///Channel 1 Transfer Complete
///clear
ctcif1: packed enum(u1) {
///Clears the TCIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CHTIF1 [2:2]
///Channel 1 Half Transfer
///clear
chtif1: packed enum(u1) {
///Clears the HTIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTEIF1 [3:3]
///Channel 1 Transfer Error
///clear
cteif1: packed enum(u1) {
///Clears the TEIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CGIF2 [4:4]
///Channel 2 Global interrupt
///clear
cgif2: u1 = 0,
///CTCIF2 [5:5]
///Channel 2 Transfer Complete
///clear
ctcif2: u1 = 0,
///CHTIF2 [6:6]
///Channel 2 Half Transfer
///clear
chtif2: u1 = 0,
///CTEIF2 [7:7]
///Channel 2 Transfer Error
///clear
cteif2: u1 = 0,
///CGIF3 [8:8]
///Channel 3 Global interrupt
///clear
cgif3: u1 = 0,
///CTCIF3 [9:9]
///Channel 3 Transfer Complete
///clear
ctcif3: u1 = 0,
///CHTIF3 [10:10]
///Channel 3 Half Transfer
///clear
chtif3: u1 = 0,
///CTEIF3 [11:11]
///Channel 3 Transfer Error
///clear
cteif3: u1 = 0,
///CGIF4 [12:12]
///Channel 4 Global interrupt
///clear
cgif4: u1 = 0,
///CTCIF4 [13:13]
///Channel 4 Transfer Complete
///clear
ctcif4: u1 = 0,
///CHTIF4 [14:14]
///Channel 4 Half Transfer
///clear
chtif4: u1 = 0,
///CTEIF4 [15:15]
///Channel 4 Transfer Error
///clear
cteif4: u1 = 0,
///CGIF5 [16:16]
///Channel 5 Global interrupt
///clear
cgif5: u1 = 0,
///CTCIF5 [17:17]
///Channel 5 Transfer Complete
///clear
ctcif5: u1 = 0,
///CHTIF5 [18:18]
///Channel 5 Half Transfer
///clear
chtif5: u1 = 0,
///CTEIF5 [19:19]
///Channel 5 Transfer Error
///clear
cteif5: u1 = 0,
///CGIF6 [20:20]
///Channel 6 Global interrupt
///clear
cgif6: u1 = 0,
///CTCIF6 [21:21]
///Channel 6 Transfer Complete
///clear
ctcif6: u1 = 0,
///CHTIF6 [22:22]
///Channel 6 Half Transfer
///clear
chtif6: u1 = 0,
///CTEIF6 [23:23]
///Channel 6 Transfer Error
///clear
cteif6: u1 = 0,
///CGIF7 [24:24]
///Channel 7 Global interrupt
///clear
cgif7: u1 = 0,
///CTCIF7 [25:25]
///Channel 7 Transfer Complete
///clear
ctcif7: u1 = 0,
///CHTIF7 [26:26]
///Channel 7 Half Transfer
///clear
chtif7: u1 = 0,
///CTEIF7 [27:27]
///Channel 7 Transfer Error
///clear
cteif7: u1 = 0,
_unused28: u4 = 0,
};
///DMA interrupt flag clear register
///(DMA_IFCR)
pub const ifcr = RegisterRW(void, ifcr_val).init(0x40020000 + 0x4);
};
///Reset and clock control
pub const rcc = struct {
//////////////////////////
///CR
const cr_val_read = packed struct {
///HSION [0:0]
///Internal High Speed clock
///enable
hsion: u1 = 1,
///HSIRDY [1:1]
///Internal High Speed clock ready
///flag
hsirdy: packed enum(u1) {
///Clock not ready
not_ready = 0,
///Clock ready
ready = 1,
} = .ready,
_unused2: u1 = 0,
///HSITRIM [3:7]
///Internal High Speed clock
///trimming
hsitrim: u5 = 16,
///HSICAL [8:15]
///Internal High Speed clock
///Calibration
hsical: u8 = 0,
///HSEON [16:16]
///External High Speed clock
///enable
hseon: u1 = 0,
///HSERDY [17:17]
///External High Speed clock ready
///flag
hserdy: u1 = 0,
///HSEBYP [18:18]
///External High Speed clock
///Bypass
hsebyp: u1 = 0,
///CSSON [19:19]
///Clock Security System
///enable
csson: u1 = 0,
_unused20: u4 = 0,
///PLLON [24:24]
///PLL enable
pllon: u1 = 0,
///PLLRDY [25:25]
///PLL clock ready flag
pllrdy: u1 = 0,
_unused26: u6 = 0,
};
const cr_val_write = packed struct {
///HSION [0:0]
///Internal High Speed clock
///enable
hsion: u1 = 1,
///HSIRDY [1:1]
///Internal High Speed clock ready
///flag
hsirdy: u1 = 1,
_unused2: u1 = 0,
///HSITRIM [3:7]
///Internal High Speed clock
///trimming
hsitrim: u5 = 16,
///HSICAL [8:15]
///Internal High Speed clock
///Calibration
hsical: u8 = 0,
///HSEON [16:16]
///External High Speed clock
///enable
hseon: u1 = 0,
///HSERDY [17:17]
///External High Speed clock ready
///flag
hserdy: u1 = 0,
///HSEBYP [18:18]
///External High Speed clock
///Bypass
hsebyp: u1 = 0,
///CSSON [19:19]
///Clock Security System
///enable
csson: u1 = 0,
_unused20: u4 = 0,
///PLLON [24:24]
///PLL enable
pllon: u1 = 0,
///PLLRDY [25:25]
///PLL clock ready flag
pllrdy: u1 = 0,
_unused26: u6 = 0,
};
///Clock control register
pub const cr = Register(cr_val).init(0x40021000 + 0x0);
//////////////////////////
///CFGR
const cfgr_val_read = packed struct {
///SW [0:1]
///System clock Switch
sw: u2 = 0,
///SWS [2:3]
///System Clock Switch Status
sws: packed enum(u2) {
///HSI48 used as system clock (when avaiable)
hsi48 = 3,
///HSI oscillator used as system clock
hsi = 0,
///HSE oscillator used as system clock
hse = 1,
///PLL used as system clock
pll = 2,
} = .hsi,
///HPRE [4:7]
///AHB prescaler
hpre: u4 = 0,
///PPRE [8:10]
///APB Low speed prescaler
///(APB1)
ppre: u3 = 0,
_unused11: u3 = 0,
///ADCPRE [14:14]
///APCPRE is deprecated. See ADC field in CFGR2 register.
adcpre: u1 = 0,
_unused15: u1 = 0,
///PLLSRC [16:16]
///PLL input clock source
pllsrc: u1 = 0,
///PLLXTPRE [17:17]
///HSE divider for PLL entry. Same bit as PREDIC[0] from CFGR2 register. Refer to it for its meaning
pllxtpre: u1 = 0,
///PLLMUL [18:21]
///PLL Multiplication Factor
pllmul: u4 = 0,
_unused22: u2 = 0,
///MCO [24:26]
///Microcontroller clock
///output
mco: u3 = 0,
_unused27: u1 = 0,
///MCOPRE [28:30]
///Microcontroller Clock Output
///Prescaler
mcopre: u3 = 0,
///PLLNODIV [31:31]
///PLL clock not divided for
///MCO
pllnodiv: u1 = 0,
};
const cfgr_val_write = packed struct {
///SW [0:1]
///System clock Switch
sw: u2 = 0,
///SWS [2:3]
///System Clock Switch Status
sws: u2 = 0,
///HPRE [4:7]
///AHB prescaler
hpre: u4 = 0,
///PPRE [8:10]
///APB Low speed prescaler
///(APB1)
ppre: u3 = 0,
_unused11: u3 = 0,
///ADCPRE [14:14]
///APCPRE is deprecated. See ADC field in CFGR2 register.
adcpre: u1 = 0,
_unused15: u1 = 0,
///PLLSRC [16:16]
///PLL input clock source
pllsrc: u1 = 0,
///PLLXTPRE [17:17]
///HSE divider for PLL entry. Same bit as PREDIC[0] from CFGR2 register. Refer to it for its meaning
pllxtpre: u1 = 0,
///PLLMUL [18:21]
///PLL Multiplication Factor
pllmul: u4 = 0,
_unused22: u2 = 0,
///MCO [24:26]
///Microcontroller clock
///output
mco: u3 = 0,
_unused27: u1 = 0,
///MCOPRE [28:30]
///Microcontroller Clock Output
///Prescaler
mcopre: u3 = 0,
///PLLNODIV [31:31]
///PLL clock not divided for
///MCO
pllnodiv: u1 = 0,
};
///Clock configuration register
///(RCC_CFGR)
pub const cfgr = Register(cfgr_val).init(0x40021000 + 0x4);
//////////////////////////
///CIR
const cir_val_read = packed struct {
///LSIRDYF [0:0]
///LSI Ready Interrupt flag
lsirdyf: packed enum(u1) {
///No clock ready interrupt
not_interrupted = 0,
///Clock ready interrupt
interrupted = 1,
} = .not_interrupted,
///LSERDYF [1:1]
///LSE Ready Interrupt flag
lserdyf: u1 = 0,
///HSIRDYF [2:2]
///HSI Ready Interrupt flag
hsirdyf: u1 = 0,
///HSERDYF [3:3]
///HSE Ready Interrupt flag
hserdyf: u1 = 0,
///PLLRDYF [4:4]
///PLL Ready Interrupt flag
pllrdyf: u1 = 0,
///HSI14RDYF [5:5]
///HSI14 ready interrupt flag
hsi14rdyf: u1 = 0,
///HSI48RDYF [6:6]
///HSI48 ready interrupt flag
hsi48rdyf: u1 = 0,
///CSSF [7:7]
///Clock Security System Interrupt
///flag
cssf: packed enum(u1) {
///No clock security interrupt caused by HSE clock failure
not_interrupted = 0,
///Clock security interrupt caused by HSE clock failure
interrupted = 1,
} = .not_interrupted,
///LSIRDYIE [8:8]
///LSI Ready Interrupt Enable
lsirdyie: u1 = 0,
///LSERDYIE [9:9]
///LSE Ready Interrupt Enable
lserdyie: u1 = 0,
///HSIRDYIE [10:10]
///HSI Ready Interrupt Enable
hsirdyie: u1 = 0,
///HSERDYIE [11:11]
///HSE Ready Interrupt Enable
hserdyie: u1 = 0,
///PLLRDYIE [12:12]
///PLL Ready Interrupt Enable
pllrdyie: u1 = 0,
///HSI14RDYIE [13:13]
///HSI14 ready interrupt
///enable
hsi14rdyie: u1 = 0,
///HSI48RDYIE [14:14]
///HSI48 ready interrupt
///enable
hsi48rdyie: u1 = 0,
_unused15: u1 = 0,
///LSIRDYC [16:16]
///LSI Ready Interrupt Clear
lsirdyc: u1 = 0,
///LSERDYC [17:17]
///LSE Ready Interrupt Clear
lserdyc: u1 = 0,
///HSIRDYC [18:18]
///HSI Ready Interrupt Clear
hsirdyc: u1 = 0,
///HSERDYC [19:19]
///HSE Ready Interrupt Clear
hserdyc: u1 = 0,
///PLLRDYC [20:20]
///PLL Ready Interrupt Clear
pllrdyc: u1 = 0,
///HSI14RDYC [21:21]
///HSI 14 MHz Ready Interrupt
///Clear
hsi14rdyc: u1 = 0,
///HSI48RDYC [22:22]
///HSI48 Ready Interrupt
///Clear
hsi48rdyc: u1 = 0,
///CSSC [23:23]
///Clock security system interrupt
///clear
cssc: u1 = 0,
_unused24: u8 = 0,
};
const cir_val_write = packed struct {
///LSIRDYF [0:0]
///LSI Ready Interrupt flag
lsirdyf: u1 = 0,
///LSERDYF [1:1]
///LSE Ready Interrupt flag
lserdyf: u1 = 0,
///HSIRDYF [2:2]
///HSI Ready Interrupt flag
hsirdyf: u1 = 0,
///HSERDYF [3:3]
///HSE Ready Interrupt flag
hserdyf: u1 = 0,
///PLLRDYF [4:4]
///PLL Ready Interrupt flag
pllrdyf: u1 = 0,
///HSI14RDYF [5:5]
///HSI14 ready interrupt flag
hsi14rdyf: u1 = 0,
///HSI48RDYF [6:6]
///HSI48 ready interrupt flag
hsi48rdyf: u1 = 0,
///CSSF [7:7]
///Clock Security System Interrupt
///flag
cssf: u1 = 0,
///LSIRDYIE [8:8]
///LSI Ready Interrupt Enable
lsirdyie: u1 = 0,
///LSERDYIE [9:9]
///LSE Ready Interrupt Enable
lserdyie: u1 = 0,
///HSIRDYIE [10:10]
///HSI Ready Interrupt Enable
hsirdyie: u1 = 0,
///HSERDYIE [11:11]
///HSE Ready Interrupt Enable
hserdyie: u1 = 0,
///PLLRDYIE [12:12]
///PLL Ready Interrupt Enable
pllrdyie: u1 = 0,
///HSI14RDYIE [13:13]
///HSI14 ready interrupt
///enable
hsi14rdyie: u1 = 0,
///HSI48RDYIE [14:14]
///HSI48 ready interrupt
///enable
hsi48rdyie: u1 = 0,
_unused15: u1 = 0,
///LSIRDYC [16:16]
///LSI Ready Interrupt Clear
lsirdyc: packed enum(u1) {
///Clear interrupt flag
clear = 1,
_zero = 0,
} = ._zero,
///LSERDYC [17:17]
///LSE Ready Interrupt Clear
lserdyc: u1 = 0,
///HSIRDYC [18:18]
///HSI Ready Interrupt Clear
hsirdyc: u1 = 0,
///HSERDYC [19:19]
///HSE Ready Interrupt Clear
hserdyc: u1 = 0,
///PLLRDYC [20:20]
///PLL Ready Interrupt Clear
pllrdyc: u1 = 0,
///HSI14RDYC [21:21]
///HSI 14 MHz Ready Interrupt
///Clear
hsi14rdyc: u1 = 0,
///HSI48RDYC [22:22]
///HSI48 Ready Interrupt
///Clear
hsi48rdyc: u1 = 0,
///CSSC [23:23]
///Clock security system interrupt
///clear
cssc: packed enum(u1) {
///Clear CSSF flag
clear = 1,
_zero = 0,
} = ._zero,
_unused24: u8 = 0,
};
///Clock interrupt register
///(RCC_CIR)
pub const cir = Register(cir_val).init(0x40021000 + 0x8);
//////////////////////////
///APB2RSTR
const apb2rstr_val = packed struct {
///SYSCFGRST [0:0]
///SYSCFG and COMP reset
syscfgrst: packed enum(u1) {
///Reset the selected module
reset = 1,
_zero = 0,
} = ._zero,
_unused1: u4 = 0,
///USART6RST [5:5]
///USART6 reset
usart6rst: u1 = 0,
_unused6: u3 = 0,
///ADCRST [9:9]
///ADC interface reset
adcrst: u1 = 0,
_unused10: u1 = 0,
///TIM1RST [11:11]
///TIM1 timer reset
tim1rst: u1 = 0,
///SPI1RST [12:12]
///SPI 1 reset
spi1rst: u1 = 0,
_unused13: u1 = 0,
///USART1RST [14:14]
///USART1 reset
usart1rst: u1 = 0,
_unused15: u1 = 0,
///TIM15RST [16:16]
///TIM15 timer reset
tim15rst: u1 = 0,
///TIM16RST [17:17]
///TIM16 timer reset
tim16rst: u1 = 0,
///TIM17RST [18:18]
///TIM17 timer reset
tim17rst: u1 = 0,
_unused19: u3 = 0,
///DBGMCURST [22:22]
///Debug MCU reset
dbgmcurst: u1 = 0,
_unused23: u9 = 0,
};
///APB2 peripheral reset register
///(RCC_APB2RSTR)
pub const apb2rstr = Register(apb2rstr_val).init(0x40021000 + 0xC);
//////////////////////////
///APB1RSTR
const apb1rstr_val = packed struct {
_unused0: u1 = 0,
///TIM3RST [1:1]
///Timer 3 reset
tim3rst: packed enum(u1) {
///Reset the selected module
reset = 1,
_zero = 0,
} = ._zero,
_unused2: u2 = 0,
///TIM6RST [4:4]
///Timer 6 reset
tim6rst: u1 = 0,
///TIM7RST [5:5]
///TIM7 timer reset
tim7rst: u1 = 0,
_unused6: u2 = 0,
///TIM14RST [8:8]
///Timer 14 reset
tim14rst: u1 = 0,
_unused9: u2 = 0,
///WWDGRST [11:11]
///Window watchdog reset
wwdgrst: u1 = 0,
_unused12: u2 = 0,
///SPI2RST [14:14]
///SPI2 reset
spi2rst: u1 = 0,
_unused15: u2 = 0,
///USART2RST [17:17]
///USART 2 reset
usart2rst: u1 = 0,
///USART3RST [18:18]
///USART3 reset
usart3rst: u1 = 0,
///USART4RST [19:19]
///USART4 reset
usart4rst: u1 = 0,
///USART5RST [20:20]
///USART5 reset
usart5rst: u1 = 0,
///I2C1RST [21:21]
///I2C1 reset
i2c1rst: u1 = 0,
///I2C2RST [22:22]
///I2C2 reset
i2c2rst: u1 = 0,
///USBRST [23:23]
///USB interface reset
usbrst: u1 = 0,
_unused24: u4 = 0,
///PWRRST [28:28]
///Power interface reset
pwrrst: u1 = 0,
_unused29: u3 = 0,
};
///APB1 peripheral reset register
///(RCC_APB1RSTR)
pub const apb1rstr = Register(apb1rstr_val).init(0x40021000 + 0x10);
//////////////////////////
///AHBENR
const ahbenr_val = packed struct {
///DMAEN [0:0]
///DMA clock enable
dmaen: packed enum(u1) {
///The selected clock is disabled
disabled = 0,
///The selected clock is enabled
enabled = 1,
} = .disabled,
_unused1: u1 = 0,
///SRAMEN [2:2]
///SRAM interface clock
///enable
sramen: u1 = 1,
_unused3: u1 = 0,
///FLITFEN [4:4]
///FLITF clock enable
flitfen: u1 = 1,
_unused5: u1 = 0,
///CRCEN [6:6]
///CRC clock enable
crcen: u1 = 0,
_unused7: u10 = 0,
///IOPAEN [17:17]
///I/O port A clock enable
iopaen: u1 = 0,
///IOPBEN [18:18]
///I/O port B clock enable
iopben: u1 = 0,
///IOPCEN [19:19]
///I/O port C clock enable
iopcen: u1 = 0,
///IOPDEN [20:20]
///I/O port D clock enable
iopden: u1 = 0,
_unused21: u1 = 0,
///IOPFEN [22:22]
///I/O port F clock enable
iopfen: u1 = 0,
_unused23: u9 = 0,
};
///AHB Peripheral Clock enable register
///(RCC_AHBENR)
pub const ahbenr = Register(ahbenr_val).init(0x40021000 + 0x14);
//////////////////////////
///APB2ENR
const apb2enr_val = packed struct {
///SYSCFGEN [0:0]
///SYSCFG clock enable
syscfgen: packed enum(u1) {
///The selected clock is disabled
disabled = 0,
///The selected clock is enabled
enabled = 1,
} = .disabled,
_unused1: u4 = 0,
///USART6EN [5:5]
///USART6 clock enable
usart6en: u1 = 0,
_unused6: u3 = 0,
///ADCEN [9:9]
///ADC 1 interface clock
///enable
adcen: u1 = 0,
_unused10: u1 = 0,
///TIM1EN [11:11]
///TIM1 Timer clock enable
tim1en: u1 = 0,
///SPI1EN [12:12]
///SPI 1 clock enable
spi1en: u1 = 0,
_unused13: u1 = 0,
///USART1EN [14:14]
///USART1 clock enable
usart1en: u1 = 0,
_unused15: u1 = 0,
///TIM15EN [16:16]
///TIM15 timer clock enable
tim15en: u1 = 0,
///TIM16EN [17:17]
///TIM16 timer clock enable
tim16en: u1 = 0,
///TIM17EN [18:18]
///TIM17 timer clock enable
tim17en: u1 = 0,
_unused19: u3 = 0,
///DBGMCUEN [22:22]
///MCU debug module clock
///enable
dbgmcuen: u1 = 0,
_unused23: u9 = 0,
};
///APB2 peripheral clock enable register
///(RCC_APB2ENR)
pub const apb2enr = Register(apb2enr_val).init(0x40021000 + 0x18);
//////////////////////////
///APB1ENR
const apb1enr_val = packed struct {
_unused0: u1 = 0,
///TIM3EN [1:1]
///Timer 3 clock enable
tim3en: packed enum(u1) {
///The selected clock is disabled
disabled = 0,
///The selected clock is enabled
enabled = 1,
} = .disabled,
_unused2: u2 = 0,
///TIM6EN [4:4]
///Timer 6 clock enable
tim6en: u1 = 0,
///TIM7EN [5:5]
///TIM7 timer clock enable
tim7en: u1 = 0,
_unused6: u2 = 0,
///TIM14EN [8:8]
///Timer 14 clock enable
tim14en: u1 = 0,
_unused9: u2 = 0,
///WWDGEN [11:11]
///Window watchdog clock
///enable
wwdgen: u1 = 0,
_unused12: u2 = 0,
///SPI2EN [14:14]
///SPI 2 clock enable
spi2en: u1 = 0,
_unused15: u2 = 0,
///USART2EN [17:17]
///USART 2 clock enable
usart2en: u1 = 0,
///USART3EN [18:18]
///USART3 clock enable
usart3en: u1 = 0,
///USART4EN [19:19]
///USART4 clock enable
usart4en: u1 = 0,
///USART5EN [20:20]
///USART5 clock enable
usart5en: u1 = 0,
///I2C1EN [21:21]
///I2C 1 clock enable
i2c1en: u1 = 0,
///I2C2EN [22:22]
///I2C 2 clock enable
i2c2en: u1 = 0,
///USBEN [23:23]
///USB interface clock enable
usben: u1 = 0,
_unused24: u4 = 0,
///PWREN [28:28]
///Power interface clock
///enable
pwren: u1 = 0,
_unused29: u3 = 0,
};
///APB1 peripheral clock enable register
///(RCC_APB1ENR)
pub const apb1enr = Register(apb1enr_val).init(0x40021000 + 0x1C);
//////////////////////////
///BDCR
const bdcr_val_read = packed struct {
///LSEON [0:0]
///External Low Speed oscillator
///enable
lseon: u1 = 0,
///LSERDY [1:1]
///External Low Speed oscillator
///ready
lserdy: packed enum(u1) {
///LSE oscillator not ready
not_ready = 0,
///LSE oscillator ready
ready = 1,
} = .not_ready,
///LSEBYP [2:2]
///External Low Speed oscillator
///bypass
lsebyp: u1 = 0,
///LSEDRV [3:4]
///LSE oscillator drive
///capability
lsedrv: u2 = 0,
_unused5: u3 = 0,
///RTCSEL [8:9]
///RTC clock source selection
rtcsel: u2 = 0,
_unused10: u5 = 0,
///RTCEN [15:15]
///RTC clock enable
rtcen: u1 = 0,
///BDRST [16:16]
///Backup domain software
///reset
bdrst: u1 = 0,
_unused17: u15 = 0,
};
const bdcr_val_write = packed struct {
///LSEON [0:0]
///External Low Speed oscillator
///enable
lseon: u1 = 0,
///LSERDY [1:1]
///External Low Speed oscillator
///ready
lserdy: u1 = 0,
///LSEBYP [2:2]
///External Low Speed oscillator
///bypass
lsebyp: u1 = 0,
///LSEDRV [3:4]
///LSE oscillator drive
///capability
lsedrv: u2 = 0,
_unused5: u3 = 0,
///RTCSEL [8:9]
///RTC clock source selection
rtcsel: u2 = 0,
_unused10: u5 = 0,
///RTCEN [15:15]
///RTC clock enable
rtcen: u1 = 0,
///BDRST [16:16]
///Backup domain software
///reset
bdrst: u1 = 0,
_unused17: u15 = 0,
};
///Backup domain control register
///(RCC_BDCR)
pub const bdcr = Register(bdcr_val).init(0x40021000 + 0x20);
//////////////////////////
///CSR
const csr_val_read = packed struct {
///LSION [0:0]
///Internal low speed oscillator
///enable
lsion: u1 = 0,
///LSIRDY [1:1]
///Internal low speed oscillator
///ready
lsirdy: packed enum(u1) {
///LSI oscillator not ready
not_ready = 0,
///LSI oscillator ready
ready = 1,
} = .not_ready,
_unused2: u21 = 0,
///V18PWRRSTF [23:23]
///1.8 V domain reset flag
v18pwrrstf: u1 = 0,
///RMVF [24:24]
///Remove reset flag
rmvf: u1 = 0,
///OBLRSTF [25:25]
///Option byte loader reset
///flag
oblrstf: packed enum(u1) {
///No reset has occured
no_reset = 0,
///A reset has occured
reset = 1,
} = .no_reset,
///PINRSTF [26:26]
///PIN reset flag
pinrstf: u1 = 1,
///PORRSTF [27:27]
///POR/PDR reset flag
porrstf: u1 = 1,
///SFTRSTF [28:28]
///Software reset flag
sftrstf: u1 = 0,
///IWDGRSTF [29:29]
///Independent watchdog reset
///flag
iwdgrstf: u1 = 0,
///WWDGRSTF [30:30]
///Window watchdog reset flag
wwdgrstf: u1 = 0,
///LPWRRSTF [31:31]
///Low-power reset flag
lpwrrstf: u1 = 0,
};
const csr_val_write = packed struct {
///LSION [0:0]
///Internal low speed oscillator
///enable
lsion: u1 = 0,
///LSIRDY [1:1]
///Internal low speed oscillator
///ready
lsirdy: u1 = 0,
_unused2: u21 = 0,
///V18PWRRSTF [23:23]
///1.8 V domain reset flag
v18pwrrstf: u1 = 0,
///RMVF [24:24]
///Remove reset flag
rmvf: packed enum(u1) {
///Clears the reset flag
clear = 1,
_zero = 0,
} = ._zero,
///OBLRSTF [25:25]
///Option byte loader reset
///flag
oblrstf: u1 = 0,
///PINRSTF [26:26]
///PIN reset flag
pinrstf: u1 = 1,
///PORRSTF [27:27]
///POR/PDR reset flag
porrstf: u1 = 1,
///SFTRSTF [28:28]
///Software reset flag
sftrstf: u1 = 0,
///IWDGRSTF [29:29]
///Independent watchdog reset
///flag
iwdgrstf: u1 = 0,
///WWDGRSTF [30:30]
///Window watchdog reset flag
wwdgrstf: u1 = 0,
///LPWRRSTF [31:31]
///Low-power reset flag
lpwrrstf: u1 = 0,
};
///Control/status register
///(RCC_CSR)
pub const csr = Register(csr_val).init(0x40021000 + 0x24);
//////////////////////////
///AHBRSTR
const ahbrstr_val = packed struct {
_unused0: u17 = 0,
///IOPARST [17:17]
///I/O port A reset
ioparst: packed enum(u1) {
///Reset the selected module
reset = 1,
_zero = 0,
} = ._zero,
///IOPBRST [18:18]
///I/O port B reset
iopbrst: u1 = 0,
///IOPCRST [19:19]
///I/O port C reset
iopcrst: u1 = 0,
///IOPDRST [20:20]
///I/O port D reset
iopdrst: u1 = 0,
_unused21: u1 = 0,
///IOPFRST [22:22]
///I/O port F reset
iopfrst: u1 = 0,
_unused23: u9 = 0,
};
///AHB peripheral reset register
pub const ahbrstr = Register(ahbrstr_val).init(0x40021000 + 0x28);
//////////////////////////
///CFGR2
const cfgr2_val = packed struct {
///PREDIV [0:3]
///PREDIV division factor
prediv: packed enum(u4) {
///PREDIV input clock not divided
div1 = 0,
///PREDIV input clock divided by 2
div2 = 1,
///PREDIV input clock divided by 3
div3 = 2,
///PREDIV input clock divided by 4
div4 = 3,
///PREDIV input clock divided by 5
div5 = 4,
///PREDIV input clock divided by 6
div6 = 5,
///PREDIV input clock divided by 7
div7 = 6,
///PREDIV input clock divided by 8
div8 = 7,
///PREDIV input clock divided by 9
div9 = 8,
///PREDIV input clock divided by 10
div10 = 9,
///PREDIV input clock divided by 11
div11 = 10,
///PREDIV input clock divided by 12
div12 = 11,
///PREDIV input clock divided by 13
div13 = 12,
///PREDIV input clock divided by 14
div14 = 13,
///PREDIV input clock divided by 15
div15 = 14,
///PREDIV input clock divided by 16
div16 = 15,
} = .div1,
_unused4: u28 = 0,
};
///Clock configuration register 2
pub const cfgr2 = Register(cfgr2_val).init(0x40021000 + 0x2C);
//////////////////////////
///CFGR3
const cfgr3_val = packed struct {
///USART1SW [0:1]
///USART1 clock source
///selection
usart1sw: packed enum(u2) {
///PCLK selected as USART clock source
pclk = 0,
///SYSCLK selected as USART clock source
sysclk = 1,
///LSE selected as USART clock source
lse = 2,
///HSI selected as USART clock source
hsi = 3,
} = .pclk,
_unused2: u2 = 0,
///I2C1SW [4:4]
///I2C1 clock source
///selection
i2c1sw: packed enum(u1) {
///HSI clock selected as I2C clock source
hsi = 0,
///SYSCLK clock selected as I2C clock source
sysclk = 1,
} = .hsi,
_unused5: u2 = 0,
///USBSW [7:7]
///USB clock source selection
usbsw: packed enum(u1) {
///USB clock disabled
disabled = 0,
///PLL clock selected as USB clock source
pllclk = 1,
} = .disabled,
///ADCSW [8:8]
///ADCSW is deprecated. See ADC field in CFGR2 register.
adcsw: u1 = 0,
_unused9: u7 = 0,
///USART2SW [16:17]
///USART2 clock source
///selection
usart2sw: u2 = 0,
///USART3SW [18:19]
///USART3 clock source
usart3sw: u2 = 0,
_unused20: u12 = 0,
};
///Clock configuration register 3
pub const cfgr3 = Register(cfgr3_val).init(0x40021000 + 0x30);
//////////////////////////
///CR2
const cr2_val_read = packed struct {
///HSI14ON [0:0]
///HSI14 clock enable
hsi14on: u1 = 0,
///HSI14RDY [1:1]
///HR14 clock ready flag
hsi14rdy: packed enum(u1) {
///HSI14 oscillator not ready
not_ready = 0,
///HSI14 oscillator ready
ready = 1,
} = .not_ready,
///HSI14DIS [2:2]
///HSI14 clock request from ADC
///disable
hsi14dis: u1 = 0,
///HSI14TRIM [3:7]
///HSI14 clock trimming
hsi14trim: u5 = 16,
///HSI14CAL [8:15]
///HSI14 clock calibration
hsi14cal: u8 = 0,
///HSI48ON [16:16]
///HSI48 clock enable
hsi48on: u1 = 0,
///HSI48RDY [17:17]
///HSI48 clock ready flag
hsi48rdy: packed enum(u1) {
///HSI48 oscillator ready
not_ready = 0,
///HSI48 oscillator ready
ready = 1,
} = .not_ready,
_unused18: u6 = 0,
///HSI48CAL [24:31]
///HSI48 factory clock
///calibration
hsi48cal: u8 = 0,
};
const cr2_val_write = packed struct {
///HSI14ON [0:0]
///HSI14 clock enable
hsi14on: u1 = 0,
///HSI14RDY [1:1]
///HR14 clock ready flag
hsi14rdy: u1 = 0,
///HSI14DIS [2:2]
///HSI14 clock request from ADC
///disable
hsi14dis: u1 = 0,
///HSI14TRIM [3:7]
///HSI14 clock trimming
hsi14trim: u5 = 16,
///HSI14CAL [8:15]
///HSI14 clock calibration
hsi14cal: u8 = 0,
///HSI48ON [16:16]
///HSI48 clock enable
hsi48on: u1 = 0,
///HSI48RDY [17:17]
///HSI48 clock ready flag
hsi48rdy: u1 = 0,
_unused18: u6 = 0,
///HSI48CAL [24:31]
///HSI48 factory clock
///calibration
hsi48cal: u8 = 0,
};
///Clock control register 2
pub const cr2 = Register(cr2_val).init(0x40021000 + 0x34);
};
///System configuration controller
pub const syscfg = struct {
//////////////////////////
///CFGR1
const cfgr1_val = packed struct {
///MEM_MODE [0:1]
///Memory mapping selection
///bits
mem_mode: packed enum(u2) {
///Main Flash memory mapped at 0x0000_0000
main_flash = 0,
///System Flash memory mapped at 0x0000_0000
system_flash = 1,
///Main Flash memory mapped at 0x0000_0000
main_flash2 = 2,
///Embedded SRAM mapped at 0x0000_0000
sram = 3,
} = .main_flash,
_unused2: u2 = 0,
///PA11_PA12_RMP [4:4]
///PA11 and PA12 remapping bit for small packages (28 and 20 pins)
pa11_pa12_rmp: packed enum(u1) {
///Pin pair PA9/PA10 mapped on the pins
not_remapped = 0,
///Pin pair PA11/PA12 mapped instead of PA9/PA10
remapped = 1,
} = .not_remapped,
_unused5: u3 = 0,
///ADC_DMA_RMP [8:8]
///ADC DMA remapping bit
adc_dma_rmp: packed enum(u1) {
///ADC DMA request mapped on DMA channel 1
not_remapped = 0,
///ADC DMA request mapped on DMA channel 2
remapped = 1,
} = .not_remapped,
///USART1_TX_DMA_RMP [9:9]
///USART1_TX DMA remapping
///bit
usart1_tx_dma_rmp: packed enum(u1) {
///USART1_TX DMA request mapped on DMA channel 2
not_remapped = 0,
///USART1_TX DMA request mapped on DMA channel 4
remapped = 1,
} = .not_remapped,
///USART1_RX_DMA_RMP [10:10]
///USART1_RX DMA request remapping
///bit
usart1_rx_dma_rmp: packed enum(u1) {
///USART1_RX DMA request mapped on DMA channel 3
not_remapped = 0,
///USART1_RX DMA request mapped on DMA channel 5
remapped = 1,
} = .not_remapped,
///TIM16_DMA_RMP [11:11]
///TIM16 DMA request remapping
///bit
tim16_dma_rmp: packed enum(u1) {
///TIM16_CH1 and TIM16_UP DMA request mapped on DMA channel 3
not_remapped = 0,
///TIM16_CH1 and TIM16_UP DMA request mapped on DMA channel 4
remapped = 1,
} = .not_remapped,
///TIM17_DMA_RMP [12:12]
///TIM17 DMA request remapping
///bit
tim17_dma_rmp: packed enum(u1) {
///TIM17_CH1 and TIM17_UP DMA request mapped on DMA channel 1
not_remapped = 0,
///TIM17_CH1 and TIM17_UP DMA request mapped on DMA channel 2
remapped = 1,
} = .not_remapped,
_unused13: u3 = 0,
///I2C_PB6_FMP [16:16]
///Fast Mode Plus (FM plus) driving
///capability activation bits.
i2c_pb6_fmp: packed enum(u1) {
///PB6 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PB6 and the Speed control is bypassed
fmp = 1,
} = .standard,
///I2C_PB7_FMP [17:17]
///Fast Mode Plus (FM+) driving capability
///activation bits.
i2c_pb7_fmp: packed enum(u1) {
///PB7 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PB7 and the Speed control is bypassed
fmp = 1,
} = .standard,
///I2C_PB8_FMP [18:18]
///Fast Mode Plus (FM+) driving capability
///activation bits.
i2c_pb8_fmp: packed enum(u1) {
///PB8 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PB8 and the Speed control is bypassed
fmp = 1,
} = .standard,
///I2C_PB9_FMP [19:19]
///Fast Mode Plus (FM+) driving capability
///activation bits.
i2c_pb9_fmp: packed enum(u1) {
///PB9 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PB9 and the Speed control is bypassed
fmp = 1,
} = .standard,
///I2C1_FMP [20:20]
///FM+ driving capability activation for
///I2C1
i2c1_fmp: packed enum(u1) {
///FM+ mode is controlled by I2C_Pxx_FMP bits only
standard = 0,
///FM+ mode is enabled on all I2C1 pins selected through selection bits in GPIOx_AFR registers
fmp = 1,
} = .standard,
_unused21: u1 = 0,
///I2C_PA9_FMP [22:22]
///Fast Mode Plus (FM+) driving capability activation bits
i2c_pa9_fmp: packed enum(u1) {
///PA9 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PA9 and the Speed control is bypassed
fmp = 1,
} = .standard,
///I2C_PA10_FMP [23:23]
///Fast Mode Plus (FM+) driving capability activation bits
i2c_pa10_fmp: packed enum(u1) {
///PA10 pin operate in standard mode
standard = 0,
///I2C FM+ mode enabled on PA10 and the Speed control is bypassed
fmp = 1,
} = .standard,
_unused24: u2 = 0,
///USART3_DMA_RMP [26:26]
///USART3 DMA request remapping
///bit
usart3_dma_rmp: packed enum(u1) {
///USART3_RX and USART3_TX DMA requests mapped on DMA channel 6 and 7 respectively (or simply disabled on STM32F0x0)
not_remapped = 0,
///USART3_RX and USART3_TX DMA requests mapped on DMA channel 3 and 2 respectively
remapped = 1,
} = .not_remapped,
_unused27: u5 = 0,
};
///configuration register 1
pub const cfgr1 = Register(cfgr1_val).init(0x40010000 + 0x0);
//////////////////////////
///EXTICR1
const exticr1_val = packed struct {
///EXTI0 [0:3]
///EXTI 0 configuration bits
exti0: packed enum(u4) {
///Select PA0 as the source input for the EXTI0 external interrupt
pa0 = 0,
///Select PB0 as the source input for the EXTI0 external interrupt
pb0 = 1,
///Select PC0 as the source input for the EXTI0 external interrupt
pc0 = 2,
///Select PD0 as the source input for the EXTI0 external interrupt
pd0 = 3,
///Select PF0 as the source input for the EXTI0 external interrupt
pf0 = 5,
} = .pa0,
///EXTI1 [4:7]
///EXTI 1 configuration bits
exti1: packed enum(u4) {
///Select PA1 as the source input for the EXTI1 external interrupt
pa1 = 0,
///Select PB1 as the source input for the EXTI1 external interrupt
pb1 = 1,
///Select PC1 as the source input for the EXTI1 external interrupt
pc1 = 2,
///Select PD1 as the source input for the EXTI1 external interrupt
pd1 = 3,
///Select PF1 as the source input for the EXTI1 external interrupt
pf1 = 5,
} = .pa1,
///EXTI2 [8:11]
///EXTI 2 configuration bits
exti2: packed enum(u4) {
///Select PA2 as the source input for the EXTI2 external interrupt
pa2 = 0,
///Select PB2 as the source input for the EXTI2 external interrupt
pb2 = 1,
///Select PC2 as the source input for the EXTI2 external interrupt
pc2 = 2,
///Select PD2 as the source input for the EXTI2 external interrupt
pd2 = 3,
///Select PF2 as the source input for the EXTI2 external interrupt
pf2 = 5,
} = .pa2,
///EXTI3 [12:15]
///EXTI 3 configuration bits
exti3: packed enum(u4) {
///Select PA3 as the source input for the EXTI3 external interrupt
pa3 = 0,
///Select PB3 as the source input for the EXTI3 external interrupt
pb3 = 1,
///Select PC3 as the source input for the EXTI3 external interrupt
pc3 = 2,
///Select PD3 as the source input for the EXTI3 external interrupt
pd3 = 3,
///Select PF3 as the source input for the EXTI3 external interrupt
pf3 = 5,
} = .pa3,
_unused16: u16 = 0,
};
///external interrupt configuration register
///1
pub const exticr1 = Register(exticr1_val).init(0x40010000 + 0x8);
//////////////////////////
///EXTICR2
const exticr2_val = packed struct {
///EXTI4 [0:3]
///EXTI 4 configuration bits
exti4: packed enum(u4) {
///Select PA4 as the source input for the EXTI4 external interrupt
pa4 = 0,
///Select PB4 as the source input for the EXTI4 external interrupt
pb4 = 1,
///Select PC4 as the source input for the EXTI4 external interrupt
pc4 = 2,
///Select PD4 as the source input for the EXTI4 external interrupt
pd4 = 3,
///Select PF4 as the source input for the EXTI4 external interrupt
pf4 = 5,
} = .pa4,
///EXTI5 [4:7]
///EXTI 5 configuration bits
exti5: packed enum(u4) {
///Select PA5 as the source input for the EXTI5 external interrupt
pa5 = 0,
///Select PB5 as the source input for the EXTI5 external interrupt
pb5 = 1,
///Select PC5 as the source input for the EXTI5 external interrupt
pc5 = 2,
///Select PD5 as the source input for the EXTI5 external interrupt
pd5 = 3,
///Select PF5 as the source input for the EXTI5 external interrupt
pf5 = 5,
} = .pa5,
///EXTI6 [8:11]
///EXTI 6 configuration bits
exti6: packed enum(u4) {
///Select PA6 as the source input for the EXTI6 external interrupt
pa6 = 0,
///Select PB6 as the source input for the EXTI6 external interrupt
pb6 = 1,
///Select PC6 as the source input for the EXTI6 external interrupt
pc6 = 2,
///Select PD6 as the source input for the EXTI6 external interrupt
pd6 = 3,
///Select PF6 as the source input for the EXTI6 external interrupt
pf6 = 5,
} = .pa6,
///EXTI7 [12:15]
///EXTI 7 configuration bits
exti7: packed enum(u4) {
///Select PA7 as the source input for the EXTI7 external interrupt
pa7 = 0,
///Select PB7 as the source input for the EXTI7 external interrupt
pb7 = 1,
///Select PC7 as the source input for the EXTI7 external interrupt
pc7 = 2,
///Select PD7 as the source input for the EXTI7 external interrupt
pd7 = 3,
///Select PF7 as the source input for the EXTI7 external interrupt
pf7 = 5,
} = .pa7,
_unused16: u16 = 0,
};
///external interrupt configuration register
///2
pub const exticr2 = Register(exticr2_val).init(0x40010000 + 0xC);
//////////////////////////
///EXTICR3
const exticr3_val = packed struct {
///EXTI8 [0:3]
///EXTI 8 configuration bits
exti8: packed enum(u4) {
///Select PA8 as the source input for the EXTI8 external interrupt
pa8 = 0,
///Select PB8 as the source input for the EXTI8 external interrupt
pb8 = 1,
///Select PC8 as the source input for the EXTI8 external interrupt
pc8 = 2,
///Select PD8 as the source input for the EXTI8 external interrupt
pd8 = 3,
///Select PF8 as the source input for the EXTI8 external interrupt
pf8 = 5,
} = .pa8,
///EXTI9 [4:7]
///EXTI 9 configuration bits
exti9: packed enum(u4) {
///Select PA9 as the source input for the EXTI9 external interrupt
pa9 = 0,
///Select PB9 as the source input for the EXTI9 external interrupt
pb9 = 1,
///Select PC9 as the source input for the EXTI9 external interrupt
pc9 = 2,
///Select PD9 as the source input for the EXTI9 external interrupt
pd9 = 3,
///Select PF9 as the source input for the EXTI9 external interrupt
pf9 = 5,
} = .pa9,
///EXTI10 [8:11]
///EXTI 10 configuration bits
exti10: packed enum(u4) {
///Select PA10 as the source input for the EXTI10 external interrupt
pa10 = 0,
///Select PB10 as the source input for the EXTI10 external interrupt
pb10 = 1,
///Select PC10 as the source input for the EXTI10 external interrupt
pc10 = 2,
///Select PD10 as the source input for the EXTI10 external interrupt
pd10 = 3,
///Select PF10 as the source input for the EXTI10 external interrupt
pf10 = 5,
} = .pa10,
///EXTI11 [12:15]
///EXTI 11 configuration bits
exti11: packed enum(u4) {
///Select PA11 as the source input for the EXTI11 external interrupt
pa11 = 0,
///Select PB11 as the source input for the EXTI11 external interrupt
pb11 = 1,
///Select PC11 as the source input for the EXTI11 external interrupt
pc11 = 2,
///Select PD11 as the source input for the EXTI11 external interrupt
pd11 = 3,
///Select PF11 as the source input for the EXTI11 external interrupt
pf11 = 5,
} = .pa11,
_unused16: u16 = 0,
};
///external interrupt configuration register
///3
pub const exticr3 = Register(exticr3_val).init(0x40010000 + 0x10);
//////////////////////////
///EXTICR4
const exticr4_val = packed struct {
///EXTI12 [0:3]
///EXTI 12 configuration bits
exti12: packed enum(u4) {
///Select PA12 as the source input for the EXTI12 external interrupt
pa12 = 0,
///Select PB12 as the source input for the EXTI12 external interrupt
pb12 = 1,
///Select PC12 as the source input for the EXTI12 external interrupt
pc12 = 2,
///Select PD12 as the source input for the EXTI12 external interrupt
pd12 = 3,
///Select PF12 as the source input for the EXTI12 external interrupt
pf12 = 5,
} = .pa12,
///EXTI13 [4:7]
///EXTI 13 configuration bits
exti13: packed enum(u4) {
///Select PA13 as the source input for the EXTI13 external interrupt
pa13 = 0,
///Select PB13 as the source input for the EXTI13 external interrupt
pb13 = 1,
///Select PC13 as the source input for the EXTI13 external interrupt
pc13 = 2,
///Select PD13 as the source input for the EXTI13 external interrupt
pd13 = 3,
///Select PF13 as the source input for the EXTI13 external interrupt
pf13 = 5,
} = .pa13,
///EXTI14 [8:11]
///EXTI 14 configuration bits
exti14: packed enum(u4) {
///Select PA14 as the source input for the EXTI14 external interrupt
pa14 = 0,
///Select PB14 as the source input for the EXTI14 external interrupt
pb14 = 1,
///Select PC14 as the source input for the EXTI14 external interrupt
pc14 = 2,
///Select PD14 as the source input for the EXTI14 external interrupt
pd14 = 3,
///Select PF14 as the source input for the EXTI14 external interrupt
pf14 = 5,
} = .pa14,
///EXTI15 [12:15]
///EXTI 15 configuration bits
exti15: packed enum(u4) {
///Select PA15 as the source input for the EXTI15 external interrupt
pa15 = 0,
///Select PB15 as the source input for the EXTI15 external interrupt
pb15 = 1,
///Select PC15 as the source input for the EXTI15 external interrupt
pc15 = 2,
///Select PD15 as the source input for the EXTI15 external interrupt
pd15 = 3,
///Select PF15 as the source input for the EXTI15 external interrupt
pf15 = 5,
} = .pa15,
_unused16: u16 = 0,
};
///external interrupt configuration register
///4
pub const exticr4 = Register(exticr4_val).init(0x40010000 + 0x14);
//////////////////////////
///CFGR2
const cfgr2_val_read = packed struct {
///LOCKUP_LOCK [0:0]
///Cortex-M0 LOCKUP bit enable
///bit
lockup_lock: u1 = 0,
///SRAM_PARITY_LOCK [1:1]
///SRAM parity lock bit
sram_parity_lock: u1 = 0,
_unused2: u6 = 0,
///SRAM_PEF [8:8]
///SRAM parity flag
sram_pef: packed enum(u1) {
///No SRAM parity error detected
no_parity_error = 0,
///SRAM parity error detected
parity_error_detected = 1,
} = .no_parity_error,
_unused9: u23 = 0,
};
const cfgr2_val_write = packed struct {
///LOCKUP_LOCK [0:0]
///Cortex-M0 LOCKUP bit enable
///bit
lockup_lock: u1 = 0,
///SRAM_PARITY_LOCK [1:1]
///SRAM parity lock bit
sram_parity_lock: u1 = 0,
_unused2: u6 = 0,
///SRAM_PEF [8:8]
///SRAM parity flag
sram_pef: packed enum(u1) {
///Clear SRAM parity error flag
clear = 1,
_zero = 0,
} = ._zero,
_unused9: u23 = 0,
};
///configuration register 2
pub const cfgr2 = RegisterRW(cfgr2_val_read, cfgr2_val_write).init(0x40010000 + 0x18);
};
///Analog-to-digital converter
pub const adc = struct {
//////////////////////////
///ISR
const isr_val_read = packed struct {
///ADRDY [0:0]
///ADC ready
adrdy: packed enum(u1) {
///ADC not yet ready to start conversion
not_ready = 0,
///ADC ready to start conversion
ready = 1,
} = .not_ready,
///EOSMP [1:1]
///End of sampling flag
eosmp: packed enum(u1) {
///Not at the end of the samplings phase
not_at_end = 0,
///End of sampling phase reached
at_end = 1,
} = .not_at_end,
///EOC [2:2]
///End of conversion flag
eoc: packed enum(u1) {
///Channel conversion is not complete
not_complete = 0,
///Channel conversion complete
complete = 1,
} = .not_complete,
///EOSEQ [3:3]
///End of sequence flag
eoseq: packed enum(u1) {
///Conversion sequence is not complete
not_complete = 0,
///Conversion sequence complete
complete = 1,
} = .not_complete,
///OVR [4:4]
///ADC overrun
ovr: packed enum(u1) {
///No overrun occurred
no_overrun = 0,
///Overrun occurred
overrun = 1,
} = .no_overrun,
_unused5: u2 = 0,
///AWD [7:7]
///Analog watchdog flag
awd: packed enum(u1) {
///No analog watchdog event occurred
no_event = 0,
///Analog watchdog event occurred
event = 1,
} = .no_event,
_unused8: u24 = 0,
};
const isr_val_write = packed struct {
///ADRDY [0:0]
///ADC ready
adrdy: packed enum(u1) {
///Clear the ADC ready flag
clear = 1,
_zero = 0,
} = ._zero,
///EOSMP [1:1]
///End of sampling flag
eosmp: packed enum(u1) {
///Clear the sampling phase flag
clear = 1,
_zero = 0,
} = ._zero,
///EOC [2:2]
///End of conversion flag
eoc: packed enum(u1) {
///Clear the channel conversion flag
clear = 1,
_zero = 0,
} = ._zero,
///EOSEQ [3:3]
///End of sequence flag
eoseq: packed enum(u1) {
///Clear the conversion sequence flag
clear = 1,
_zero = 0,
} = ._zero,
///OVR [4:4]
///ADC overrun
ovr: packed enum(u1) {
///Clear the overrun flag
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u2 = 0,
///AWD [7:7]
///Analog watchdog flag
awd: packed enum(u1) {
///Clear the analog watchdog event flag
clear = 1,
_zero = 0,
} = ._zero,
_unused8: u24 = 0,
};
///interrupt and status register
pub const isr = RegisterRW(isr_val_read, isr_val_write).init(0x40012400 + 0x0);
//////////////////////////
///IER
const ier_val = packed struct {
///ADRDYIE [0:0]
///ADC ready interrupt enable
adrdyie: packed enum(u1) {
///ADC ready interrupt disabled
disabled = 0,
///ADC ready interrupt enabled
enabled = 1,
} = .disabled,
///EOSMPIE [1:1]
///End of sampling flag interrupt
///enable
eosmpie: packed enum(u1) {
///End of sampling interrupt disabled
disabled = 0,
///End of sampling interrupt enabled
enabled = 1,
} = .disabled,
///EOCIE [2:2]
///End of conversion interrupt
///enable
eocie: packed enum(u1) {
///End of conversion interrupt disabled
disabled = 0,
///End of conversion interrupt enabled
enabled = 1,
} = .disabled,
///EOSEQIE [3:3]
///End of conversion sequence interrupt
///enable
eoseqie: packed enum(u1) {
///End of conversion sequence interrupt disabled
disabled = 0,
///End of conversion sequence interrupt enabled
enabled = 1,
} = .disabled,
///OVRIE [4:4]
///Overrun interrupt enable
ovrie: packed enum(u1) {
///Overrun interrupt disabled
disabled = 0,
///Overrun interrupt enabled
enabled = 1,
} = .disabled,
_unused5: u2 = 0,
///AWDIE [7:7]
///Analog watchdog interrupt
///enable
awdie: packed enum(u1) {
///Analog watchdog interrupt disabled
disabled = 0,
///Analog watchdog interrupt enabled
enabled = 1,
} = .disabled,
_unused8: u24 = 0,
};
///interrupt enable register
pub const ier = Register(ier_val).init(0x40012400 + 0x4);
//////////////////////////
///CR
const cr_val_read = packed struct {
///ADEN [0:0]
///ADC enable command
aden: packed enum(u1) {
///ADC disabled
disabled = 0,
///ADC enabled
enabled = 1,
} = .disabled,
///ADDIS [1:1]
///ADC disable command
addis: packed enum(u1) {
///No disable command active
not_disabling = 0,
///ADC disabling
disabling = 1,
} = .not_disabling,
///ADSTART [2:2]
///ADC start conversion
///command
adstart: packed enum(u1) {
///No conversion ongoing
not_active = 0,
///ADC operating and may be converting
active = 1,
} = .not_active,
_unused3: u1 = 0,
///ADSTP [4:4]
///ADC stop conversion
///command
adstp: packed enum(u1) {
///No stop command active
not_stopping = 0,
///ADC stopping conversion
stopping = 1,
} = .not_stopping,
_unused5: u26 = 0,
///ADCAL [31:31]
///ADC calibration
adcal: packed enum(u1) {
///ADC calibration either not yet performed or completed
not_calibrating = 0,
///ADC calibration in progress
calibrating = 1,
} = .not_calibrating,
};
const cr_val_write = packed struct {
///ADEN [0:0]
///ADC enable command
aden: packed enum(u1) {
///Enable the ADC
enabled = 1,
_zero = 0,
} = ._zero,
///ADDIS [1:1]
///ADC disable command
addis: packed enum(u1) {
///Disable the ADC
disable = 1,
_zero = 0,
} = ._zero,
///ADSTART [2:2]
///ADC start conversion
///command
adstart: packed enum(u1) {
///Start the ADC conversion (may be delayed for hardware triggers)
start_conversion = 1,
_zero = 0,
} = ._zero,
_unused3: u1 = 0,
///ADSTP [4:4]
///ADC stop conversion
///command
adstp: packed enum(u1) {
///Stop the active conversion
stop_conversion = 1,
_zero = 0,
} = ._zero,
_unused5: u26 = 0,
///ADCAL [31:31]
///ADC calibration
adcal: packed enum(u1) {
///Start the ADC calibration sequence
start_calibration = 1,
_zero = 0,
} = ._zero,
};
///control register
pub const cr = RegisterRW(cr_val_read, cr_val_write).init(0x40012400 + 0x8);
//////////////////////////
///CFGR1
const cfgr1_val = packed struct {
///DMAEN [0:0]
///Direct memory access
///enable
dmaen: packed enum(u1) {
///DMA mode disabled
disabled = 0,
///DMA mode enabled
enabled = 1,
} = .disabled,
///DMACFG [1:1]
///Direct memery access
///configuration
dmacfg: packed enum(u1) {
///DMA one shot mode
one_shot = 0,
///DMA circular mode
circular = 1,
} = .one_shot,
///SCANDIR [2:2]
///Scan sequence direction
scandir: packed enum(u1) {
///Upward scan (from CHSEL0 to CHSEL18)
upward = 0,
///Backward scan (from CHSEL18 to CHSEL0)
backward = 1,
} = .upward,
///RES [3:4]
///Data resolution
res: packed enum(u2) {
///12-bit (14 ADCCLK cycles)
twelve_bit = 0,
///10-bit (13 ADCCLK cycles)
ten_bit = 1,
///8-bit (11 ADCCLK cycles)
eight_bit = 2,
///6-bit (9 ADCCLK cycles)
six_bit = 3,
} = .twelve_bit,
///ALIGN [5:5]
///Data alignment
_align: packed enum(u1) {
///Right alignment
right = 0,
///Left alignment
left = 1,
} = .right,
///EXTSEL [6:8]
///External trigger selection
extsel: packed enum(u3) {
///Timer 1 TRGO Event
tim1_trgo = 0,
///Timer 1 CC4 event
tim1_cc4 = 1,
///Timer 3 TRGO event
tim3_trgo = 3,
///Timer 15 TRGO event
tim15_trgo = 4,
} = .tim1_trgo,
_unused9: u1 = 0,
///EXTEN [10:11]
///External trigger enable and polarity
///selection
exten: packed enum(u2) {
///Trigger detection disabled
disabled = 0,
///Trigger detection on the rising edge
rising_edge = 1,
///Trigger detection on the falling edge
falling_edge = 2,
///Trigger detection on both the rising and falling edges
both_edges = 3,
} = .disabled,
///OVRMOD [12:12]
///Overrun management mode
ovrmod: packed enum(u1) {
///ADC_DR register is preserved with the old data when an overrun is detected
preserved = 0,
///ADC_DR register is overwritten with the last conversion result when an overrun is detected
overwritten = 1,
} = .preserved,
///CONT [13:13]
///Single / continuous conversion
///mode
cont: packed enum(u1) {
///Single conversion mode
single = 0,
///Continuous conversion mode
continuous = 1,
} = .single,
///WAIT [14:14]
///Wait conversion mode
wait: packed enum(u1) {
///Wait conversion mode off
disabled = 0,
///Wait conversion mode on
enabled = 1,
} = .disabled,
///AUTOFF [15:15]
///Auto-off mode
autoff: packed enum(u1) {
///Auto-off mode disabled
disabled = 0,
///Auto-off mode enabled
enabled = 1,
} = .disabled,
///DISCEN [16:16]
///Discontinuous mode
discen: packed enum(u1) {
///Discontinuous mode on regular channels disabled
disabled = 0,
///Discontinuous mode on regular channels enabled
enabled = 1,
} = .disabled,
_unused17: u5 = 0,
///AWDSGL [22:22]
///Enable the watchdog on a single channel
///or on all channels
awdsgl: packed enum(u1) {
///Analog watchdog enabled on all channels
all_channels = 0,
///Analog watchdog enabled on a single channel
single_channel = 1,
} = .all_channels,
///AWDEN [23:23]
///Analog watchdog enable
awden: packed enum(u1) {
///Analog watchdog disabled on regular channels
disabled = 0,
///Analog watchdog enabled on regular channels
enabled = 1,
} = .disabled,
_unused24: u2 = 0,
///AWDCH [26:30]
///Analog watchdog channel
///selection
awdch: u5 = 0,
_unused31: u1 = 0,
};
///configuration register 1
pub const cfgr1 = Register(cfgr1_val).init(0x40012400 + 0xC);
//////////////////////////
///CFGR2
const cfgr2_val = packed struct {
_unused0: u30 = 0,
///CKMODE [30:31]
///ADC clock mode
ckmode: packed enum(u2) {
///Asynchronous clock mode
adcclk = 0,
///Synchronous clock mode (PCLK/2)
pclk_div2 = 1,
///Sychronous clock mode (PCLK/4)
pclk_div4 = 2,
} = .adcclk,
};
///configuration register 2
pub const cfgr2 = Register(cfgr2_val).init(0x40012400 + 0x10);
//////////////////////////
///SMPR
const smpr_val = packed struct {
///SMP [0:2]
///Sampling time selection
smp: packed enum(u3) {
///1.5 cycles
cycles1_5 = 0,
///7.5 cycles
cycles7_5 = 1,
///13.5 cycles
cycles13_5 = 2,
///28.5 cycles
cycles28_5 = 3,
///41.5 cycles
cycles41_5 = 4,
///55.5 cycles
cycles55_5 = 5,
///71.5 cycles
cycles71_5 = 6,
///239.5 cycles
cycles239_5 = 7,
} = .cycles1_5,
_unused3: u29 = 0,
};
///sampling time register
pub const smpr = Register(smpr_val).init(0x40012400 + 0x14);
//////////////////////////
///TR
const tr_val = packed struct {
///LT [0:11]
///Analog watchdog lower
///threshold
lt: u12 = 4095,
_unused12: u4 = 0,
///HT [16:27]
///Analog watchdog higher
///threshold
ht: u12 = 0,
_unused28: u4 = 0,
};
///watchdog threshold register
pub const tr = Register(tr_val).init(0x40012400 + 0x20);
//////////////////////////
///CHSELR
const chselr_val = packed struct {
///CHSEL0 [0:0]
///Channel-x selection
chsel0: u1 = 0,
///CHSEL1 [1:1]
///Channel-x selection
chsel1: u1 = 0,
///CHSEL2 [2:2]
///Channel-x selection
chsel2: u1 = 0,
///CHSEL3 [3:3]
///Channel-x selection
chsel3: u1 = 0,
///CHSEL4 [4:4]
///Channel-x selection
chsel4: u1 = 0,
///CHSEL5 [5:5]
///Channel-x selection
chsel5: u1 = 0,
///CHSEL6 [6:6]
///Channel-x selection
chsel6: u1 = 0,
///CHSEL7 [7:7]
///Channel-x selection
chsel7: u1 = 0,
///CHSEL8 [8:8]
///Channel-x selection
chsel8: u1 = 0,
///CHSEL9 [9:9]
///Channel-x selection
chsel9: u1 = 0,
///CHSEL10 [10:10]
///Channel-x selection
chsel10: u1 = 0,
///CHSEL11 [11:11]
///Channel-x selection
chsel11: u1 = 0,
///CHSEL12 [12:12]
///Channel-x selection
chsel12: u1 = 0,
///CHSEL13 [13:13]
///Channel-x selection
chsel13: u1 = 0,
///CHSEL14 [14:14]
///Channel-x selection
chsel14: u1 = 0,
///CHSEL15 [15:15]
///Channel-x selection
chsel15: u1 = 0,
///CHSEL16 [16:16]
///Channel-x selection
chsel16: u1 = 0,
///CHSEL17 [17:17]
///Channel-x selection
chsel17: u1 = 0,
///CHSEL18 [18:18]
///Channel-x selection
chsel18: packed enum(u1) {
///Input Channel is not selected for conversion
not_selected = 0,
///Input Channel is selected for conversion
selected = 1,
} = .not_selected,
_unused19: u13 = 0,
};
///channel selection register
pub const chselr = Register(chselr_val).init(0x40012400 + 0x28);
//////////////////////////
///DR
const dr_val = packed struct {
///DATA [0:15]
///Converted data
data: u16 = 0,
_unused16: u16 = 0,
};
///data register
pub const dr = RegisterRW(dr_val, void).init(0x40012400 + 0x40);
//////////////////////////
///CCR
const ccr_val = packed struct {
_unused0: u22 = 0,
///VREFEN [22:22]
///Temperature sensor and VREFINT
///enable
vrefen: packed enum(u1) {
///V_REFINT channel disabled
disabled = 0,
///V_REFINT channel enabled
enabled = 1,
} = .disabled,
///TSEN [23:23]
///Temperature sensor enable
tsen: packed enum(u1) {
///Temperature sensor disabled
disabled = 0,
///Temperature sensor enabled
enabled = 1,
} = .disabled,
_unused24: u8 = 0,
};
///common configuration register
pub const ccr = Register(ccr_val).init(0x40012400 + 0x308);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart1 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40013800 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40013800 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40013800 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40013800 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40013800 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40013800 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40013800 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40013800 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40013800 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40013800 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40013800 + 0x28);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart2 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40004400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40004400 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40004400 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40004400 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40004400 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40004400 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40004400 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40004400 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40004400 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40004400 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40004400 + 0x28);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart3 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40004800 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40004800 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40004800 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40004800 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40004800 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40004800 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40004800 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40004800 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40004800 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40004800 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40004800 + 0x28);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart4 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40004C00 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40004C00 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40004C00 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40004C00 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40004C00 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40004C00 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40004C00 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40004C00 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40004C00 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40004C00 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40004C00 + 0x28);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart6 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40011400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40011400 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40011400 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40011400 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40011400 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40011400 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40011400 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40011400 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40011400 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40011400 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40011400 + 0x28);
};
///Universal synchronous asynchronous receiver
///transmitter
pub const usart5 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///UE [0:0]
///USART enable
ue: packed enum(u1) {
///UART is disabled
disabled = 0,
///UART is enabled
enabled = 1,
} = .disabled,
///UESM [1:1]
///USART enable in Stop mode
uesm: packed enum(u1) {
///USART not able to wake up the MCU from Stop mode
disabled = 0,
///USART able to wake up the MCU from Stop mode
enabled = 1,
} = .disabled,
///RE [2:2]
///Receiver enable
re: packed enum(u1) {
///Receiver is disabled
disabled = 0,
///Receiver is enabled
enabled = 1,
} = .disabled,
///TE [3:3]
///Transmitter enable
te: packed enum(u1) {
///Transmitter is disabled
disabled = 0,
///Transmitter is enabled
enabled = 1,
} = .disabled,
///IDLEIE [4:4]
///IDLE interrupt enable
idleie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever IDLE=1 in the ISR register
enabled = 1,
} = .disabled,
///RXNEIE [5:5]
///RXNE interrupt enable
rxneie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever ORE=1 or RXNE=1 in the ISR register
enabled = 1,
} = .disabled,
///TCIE [6:6]
///Transmission complete interrupt
///enable
tcie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TC=1 in the ISR register
enabled = 1,
} = .disabled,
///TXEIE [7:7]
///interrupt enable
txeie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever TXE=1 in the ISR register
enabled = 1,
} = .disabled,
///PEIE [8:8]
///PE interrupt enable
peie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated whenever PE=1 in the ISR register
enabled = 1,
} = .disabled,
///PS [9:9]
///Parity selection
ps: packed enum(u1) {
///Even parity
even = 0,
///Odd parity
odd = 1,
} = .even,
///PCE [10:10]
///Parity control enable
pce: packed enum(u1) {
///Parity control disabled
disabled = 0,
///Parity control enabled
enabled = 1,
} = .disabled,
///WAKE [11:11]
///Receiver wakeup method
wake: packed enum(u1) {
///Idle line
idle = 0,
///Address mask
address = 1,
} = .idle,
///M0 [12:12]
///Word length
m0: packed enum(u1) {
///1 start bit, 8 data bits, n stop bits
bit8 = 0,
///1 start bit, 9 data bits, n stop bits
bit9 = 1,
} = .bit8,
///MME [13:13]
///Mute mode enable
mme: packed enum(u1) {
///Receiver in active mode permanently
disabled = 0,
///Receiver can switch between mute mode and active mode
enabled = 1,
} = .disabled,
///CMIE [14:14]
///Character match interrupt
///enable
cmie: packed enum(u1) {
///Interrupt is disabled
disabled = 0,
///Interrupt is generated when the CMF bit is set in the ISR register
enabled = 1,
} = .disabled,
///OVER8 [15:15]
///Oversampling mode
over8: packed enum(u1) {
///Oversampling by 16
oversampling16 = 0,
///Oversampling by 8
oversampling8 = 1,
} = .oversampling16,
///DEDT [16:20]
///Driver Enable deassertion
///time
dedt: u5 = 0,
///DEAT [21:25]
///Driver Enable assertion
///time
deat: u5 = 0,
///RTOIE [26:26]
///Receiver timeout interrupt
///enable
rtoie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated when the RTOF bit is set in the ISR register
enabled = 1,
} = .disabled,
///EOBIE [27:27]
///End of Block interrupt
///enable
eobie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///A USART interrupt is generated when the EOBF flag is set in the ISR register
enabled = 1,
} = .disabled,
///M1 [28:28]
///Word length
m1: packed enum(u1) {
///Use M0 to set the data bits
m0 = 0,
///1 start bit, 7 data bits, n stop bits
bit7 = 1,
} = .m0,
_unused29: u3 = 0,
};
///Control register 1
pub const cr1 = Register(cr1_val).init(0x40005000 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
_unused0: u4 = 0,
///ADDM7 [4:4]
///7-bit Address Detection/4-bit Address
///Detection
addm7: packed enum(u1) {
///4-bit address detection
bit4 = 0,
///7-bit address detection
bit7 = 1,
} = .bit4,
///LBDL [5:5]
///LIN break detection length
lbdl: packed enum(u1) {
///10-bit break detection
bit10 = 0,
///11-bit break detection
bit11 = 1,
} = .bit10,
///LBDIE [6:6]
///LIN break detection interrupt
///enable
lbdie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever LBDF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused7: u1 = 0,
///LBCL [8:8]
///Last bit clock pulse
lbcl: packed enum(u1) {
///The clock pulse of the last data bit is not output to the CK pin
not_output = 0,
///The clock pulse of the last data bit is output to the CK pin
output = 1,
} = .not_output,
///CPHA [9:9]
///Clock phase
cpha: packed enum(u1) {
///The first clock transition is the first data capture edge
first = 0,
///The second clock transition is the first data capture edge
second = 1,
} = .first,
///CPOL [10:10]
///Clock polarity
cpol: packed enum(u1) {
///Steady low value on CK pin outside transmission window
low = 0,
///Steady high value on CK pin outside transmission window
high = 1,
} = .low,
///CLKEN [11:11]
///Clock enable
clken: packed enum(u1) {
///CK pin disabled
disabled = 0,
///CK pin enabled
enabled = 1,
} = .disabled,
///STOP [12:13]
///STOP bits
stop: packed enum(u2) {
///1 stop bit
stop1 = 0,
///0.5 stop bit
stop0p5 = 1,
///2 stop bit
stop2 = 2,
///1.5 stop bit
stop1p5 = 3,
} = .stop1,
///LINEN [14:14]
///LIN mode enable
linen: packed enum(u1) {
///LIN mode disabled
disabled = 0,
///LIN mode enabled
enabled = 1,
} = .disabled,
///SWAP [15:15]
///Swap TX/RX pins
swap: packed enum(u1) {
///TX/RX pins are used as defined in standard pinout
standard = 0,
///The TX and RX pins functions are swapped
swapped = 1,
} = .standard,
///RXINV [16:16]
///RX pin active level
///inversion
rxinv: packed enum(u1) {
///RX pin signal works using the standard logic levels
standard = 0,
///RX pin signal values are inverted
inverted = 1,
} = .standard,
///TXINV [17:17]
///TX pin active level
///inversion
txinv: packed enum(u1) {
///TX pin signal works using the standard logic levels
standard = 0,
///TX pin signal values are inverted
inverted = 1,
} = .standard,
///DATAINV [18:18]
///Binary data inversion
datainv: packed enum(u1) {
///Logical data from the data register are send/received in positive/direct logic
positive = 0,
///Logical data from the data register are send/received in negative/inverse logic
negative = 1,
} = .positive,
///MSBFIRST [19:19]
///Most significant bit first
msbfirst: packed enum(u1) {
///data is transmitted/received with data bit 0 first, following the start bit
lsb = 0,
///data is transmitted/received with MSB (bit 7/8/9) first, following the start bit
msb = 1,
} = .lsb,
///ABREN [20:20]
///Auto baud rate enable
abren: packed enum(u1) {
///Auto baud rate detection is disabled
disabled = 0,
///Auto baud rate detection is enabled
enabled = 1,
} = .disabled,
///ABRMOD [21:22]
///Auto baud rate mode
abrmod: packed enum(u2) {
///Measurement of the start bit is used to detect the baud rate
start = 0,
///Falling edge to falling edge measurement
edge = 1,
///0x7F frame detection
frame7f = 2,
///0x55 frame detection
frame55 = 3,
} = .start,
///RTOEN [23:23]
///Receiver timeout enable
rtoen: packed enum(u1) {
///Receiver timeout feature disabled
disabled = 0,
///Receiver timeout feature enabled
enabled = 1,
} = .disabled,
///ADD [24:31]
///Address of the USART node
add: u8 = 0,
};
///Control register 2
pub const cr2 = Register(cr2_val).init(0x40005000 + 0x4);
//////////////////////////
///CR3
const cr3_val = packed struct {
///EIE [0:0]
///Error interrupt enable
eie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated when FE=1 or ORE=1 or NF=1 in the ISR register
enabled = 1,
} = .disabled,
///IREN [1:1]
///IrDA mode enable
iren: packed enum(u1) {
///IrDA disabled
disabled = 0,
///IrDA enabled
enabled = 1,
} = .disabled,
///IRLP [2:2]
///IrDA low-power
irlp: packed enum(u1) {
///Normal mode
normal = 0,
///Low-power mode
low_power = 1,
} = .normal,
///HDSEL [3:3]
///Half-duplex selection
hdsel: packed enum(u1) {
///Half duplex mode is not selected
not_selected = 0,
///Half duplex mode is selected
selected = 1,
} = .not_selected,
///NACK [4:4]
///Smartcard NACK enable
nack: packed enum(u1) {
///NACK transmission in case of parity error is disabled
disabled = 0,
///NACK transmission during parity error is enabled
enabled = 1,
} = .disabled,
///SCEN [5:5]
///Smartcard mode enable
scen: packed enum(u1) {
///Smartcard Mode disabled
disabled = 0,
///Smartcard Mode enabled
enabled = 1,
} = .disabled,
///DMAR [6:6]
///DMA enable receiver
dmar: packed enum(u1) {
///DMA mode is disabled for reception
disabled = 0,
///DMA mode is enabled for reception
enabled = 1,
} = .disabled,
///DMAT [7:7]
///DMA enable transmitter
dmat: packed enum(u1) {
///DMA mode is disabled for transmission
disabled = 0,
///DMA mode is enabled for transmission
enabled = 1,
} = .disabled,
///RTSE [8:8]
///RTS enable
rtse: packed enum(u1) {
///RTS hardware flow control disabled
disabled = 0,
///RTS output enabled, data is only requested when there is space in the receive buffer
enabled = 1,
} = .disabled,
///CTSE [9:9]
///CTS enable
ctse: packed enum(u1) {
///CTS hardware flow control disabled
disabled = 0,
///CTS mode enabled, data is only transmitted when the CTS input is asserted
enabled = 1,
} = .disabled,
///CTSIE [10:10]
///CTS interrupt enable
ctsie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An interrupt is generated whenever CTSIF=1 in the ISR register
enabled = 1,
} = .disabled,
///ONEBIT [11:11]
///One sample bit method
///enable
onebit: packed enum(u1) {
///Three sample bit method
sample3 = 0,
///One sample bit method
sample1 = 1,
} = .sample3,
///OVRDIS [12:12]
///Overrun Disable
ovrdis: packed enum(u1) {
///Overrun Error Flag, ORE, is set when received data is not read before receiving new data
enabled = 0,
///Overrun functionality is disabled. If new data is received while the RXNE flag is still set the ORE flag is not set and the new received data overwrites the previous content of the RDR register
disabled = 1,
} = .enabled,
///DDRE [13:13]
///DMA Disable on Reception
///Error
ddre: packed enum(u1) {
///DMA is not disabled in case of reception error
not_disabled = 0,
///DMA is disabled following a reception error
disabled = 1,
} = .not_disabled,
///DEM [14:14]
///Driver enable mode
dem: packed enum(u1) {
///DE function is disabled
disabled = 0,
///The DE signal is output on the RTS pin
enabled = 1,
} = .disabled,
///DEP [15:15]
///Driver enable polarity
///selection
dep: packed enum(u1) {
///DE signal is active high
high = 0,
///DE signal is active low
low = 1,
} = .high,
_unused16: u1 = 0,
///SCARCNT [17:19]
///Smartcard auto-retry count
scarcnt: u3 = 0,
///WUS [20:21]
///Wakeup from Stop mode interrupt flag
///selection
wus: packed enum(u2) {
///WUF active on address match
address = 0,
///WuF active on Start bit detection
start = 2,
///WUF active on RXNE
rxne = 3,
} = .address,
///WUFIE [22:22]
///Wakeup from Stop mode interrupt
///enable
wufie: packed enum(u1) {
///Interrupt is inhibited
disabled = 0,
///An USART interrupt is generated whenever WUF=1 in the ISR register
enabled = 1,
} = .disabled,
_unused23: u9 = 0,
};
///Control register 3
pub const cr3 = Register(cr3_val).init(0x40005000 + 0x8);
//////////////////////////
///BRR
const brr_val = packed struct {
///BRR [0:15]
///mantissa of USARTDIV
brr: u16 = 0,
_unused16: u16 = 0,
};
///Baud rate register
pub const brr = Register(brr_val).init(0x40005000 + 0xC);
//////////////////////////
///GTPR
const gtpr_val = packed struct {
///PSC [0:7]
///Prescaler value
psc: u8 = 0,
///GT [8:15]
///Guard time value
gt: u8 = 0,
_unused16: u16 = 0,
};
///Guard time and prescaler
///register
pub const gtpr = Register(gtpr_val).init(0x40005000 + 0x10);
//////////////////////////
///RTOR
const rtor_val = packed struct {
///RTO [0:23]
///Receiver timeout value
rto: u24 = 0,
///BLEN [24:31]
///Block Length
blen: u8 = 0,
};
///Receiver timeout register
pub const rtor = Register(rtor_val).init(0x40005000 + 0x14);
//////////////////////////
///RQR
const rqr_val = packed struct {
///ABRRQ [0:0]
///Auto baud rate request
abrrq: packed enum(u1) {
///resets the ABRF flag in the USART_ISR and request an automatic baud rate measurement on the next received data frame
request = 1,
_zero = 0,
} = ._zero,
///SBKRQ [1:1]
///Send break request
sbkrq: packed enum(u1) {
///sets the SBKF flag and request to send a BREAK on the line, as soon as the transmit machine is available
_break = 1,
_zero = 0,
} = ._zero,
///MMRQ [2:2]
///Mute mode request
mmrq: packed enum(u1) {
///Puts the USART in mute mode and sets the RWU flag
mute = 1,
_zero = 0,
} = ._zero,
///RXFRQ [3:3]
///Receive data flush request
rxfrq: packed enum(u1) {
///clears the RXNE flag. This allows to discard the received data without reading it, and avoid an overrun condition
discard = 1,
_zero = 0,
} = ._zero,
///TXFRQ [4:4]
///Transmit data flush
///request
txfrq: packed enum(u1) {
///Set the TXE flags. This allows to discard the transmit data
discard = 1,
_zero = 0,
} = ._zero,
_unused5: u27 = 0,
};
///Request register
pub const rqr = Register(rqr_val).init(0x40005000 + 0x18);
//////////////////////////
///ISR
const isr_val = packed struct {
///PE [0:0]
///Parity error
pe: u1 = 0,
///FE [1:1]
///Framing error
fe: u1 = 0,
///NF [2:2]
///Noise detected flag
nf: u1 = 0,
///ORE [3:3]
///Overrun error
ore: u1 = 0,
///IDLE [4:4]
///Idle line detected
idle: u1 = 0,
///RXNE [5:5]
///Read data register not
///empty
rxne: u1 = 0,
///TC [6:6]
///Transmission complete
tc: u1 = 1,
///TXE [7:7]
///Transmit data register
///empty
txe: u1 = 1,
///LBDF [8:8]
///LIN break detection flag
lbdf: u1 = 0,
///CTSIF [9:9]
///CTS interrupt flag
ctsif: u1 = 0,
///CTS [10:10]
///CTS flag
cts: u1 = 0,
///RTOF [11:11]
///Receiver timeout
rtof: u1 = 0,
///EOBF [12:12]
///End of block flag
eobf: u1 = 0,
_unused13: u1 = 0,
///ABRE [14:14]
///Auto baud rate error
abre: u1 = 0,
///ABRF [15:15]
///Auto baud rate flag
abrf: u1 = 0,
///BUSY [16:16]
///Busy flag
busy: u1 = 0,
///CMF [17:17]
///character match flag
cmf: u1 = 0,
///SBKF [18:18]
///Send break flag
sbkf: u1 = 0,
///RWU [19:19]
///Receiver wakeup from Mute
///mode
rwu: u1 = 0,
///WUF [20:20]
///Wakeup from Stop mode flag
wuf: u1 = 0,
///TEACK [21:21]
///Transmit enable acknowledge
///flag
teack: u1 = 0,
///REACK [22:22]
///Receive enable acknowledge
///flag
reack: u1 = 0,
_unused23: u9 = 0,
};
///Interrupt & status
///register
pub const isr = RegisterRW(isr_val, void).init(0x40005000 + 0x1C);
//////////////////////////
///ICR
const icr_val = packed struct {
///PECF [0:0]
///Parity error clear flag
pecf: packed enum(u1) {
///Clears the PE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///FECF [1:1]
///Framing error clear flag
fecf: packed enum(u1) {
///Clears the FE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///NCF [2:2]
///Noise detected clear flag
ncf: packed enum(u1) {
///Clears the NF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///ORECF [3:3]
///Overrun error clear flag
orecf: packed enum(u1) {
///Clears the ORE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///IDLECF [4:4]
///Idle line detected clear
///flag
idlecf: packed enum(u1) {
///Clears the IDLE flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused5: u1 = 0,
///TCCF [6:6]
///Transmission complete clear
///flag
tccf: packed enum(u1) {
///Clears the TC flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused7: u1 = 0,
///LBDCF [8:8]
///LIN break detection clear
///flag
lbdcf: packed enum(u1) {
///Clears the LBDF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///CTSCF [9:9]
///CTS clear flag
ctscf: packed enum(u1) {
///Clears the CTSIF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused10: u1 = 0,
///RTOCF [11:11]
///Receiver timeout clear
///flag
rtocf: packed enum(u1) {
///Clears the RTOF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
///EOBCF [12:12]
///End of timeout clear flag
eobcf: packed enum(u1) {
///Clears the EOBF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused13: u4 = 0,
///CMCF [17:17]
///Character match clear flag
cmcf: packed enum(u1) {
///Clears the CMF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused18: u2 = 0,
///WUCF [20:20]
///Wakeup from Stop mode clear
///flag
wucf: packed enum(u1) {
///Clears the WUF flag in the ISR register
clear = 1,
_zero = 0,
} = ._zero,
_unused21: u11 = 0,
};
///Interrupt flag clear register
pub const icr = Register(icr_val).init(0x40005000 + 0x20);
//////////////////////////
///RDR
const rdr_val = packed struct {
///RDR [0:8]
///Receive data value
rdr: u9 = 0,
_unused9: u23 = 0,
};
///Receive data register
pub const rdr = RegisterRW(rdr_val, void).init(0x40005000 + 0x24);
//////////////////////////
///TDR
const tdr_val = packed struct {
///TDR [0:8]
///Transmit data value
tdr: u9 = 0,
_unused9: u23 = 0,
};
///Transmit data register
pub const tdr = Register(tdr_val).init(0x40005000 + 0x28);
};
///Real-time clock
pub const rtc = struct {
//////////////////////////
///TR
const tr_val = packed struct {
///SU [0:3]
///Second units in BCD format
su: u4 = 0,
///ST [4:6]
///Second tens in BCD format
st: u3 = 0,
_unused7: u1 = 0,
///MNU [8:11]
///Minute units in BCD format
mnu: u4 = 0,
///MNT [12:14]
///Minute tens in BCD format
mnt: u3 = 0,
_unused15: u1 = 0,
///HU [16:19]
///Hour units in BCD format
hu: u4 = 0,
///HT [20:21]
///Hour tens in BCD format
ht: u2 = 0,
///PM [22:22]
///AM/PM notation
pm: u1 = 0,
_unused23: u9 = 0,
};
///time register
pub const tr = Register(tr_val).init(0x40002800 + 0x0);
//////////////////////////
///DR
const dr_val = packed struct {
///DU [0:3]
///Date units in BCD format
du: u4 = 1,
///DT [4:5]
///Date tens in BCD format
dt: u2 = 0,
_unused6: u2 = 0,
///MU [8:11]
///Month units in BCD format
mu: u4 = 1,
///MT [12:12]
///Month tens in BCD format
mt: u1 = 0,
///WDU [13:15]
///Week day units
wdu: u3 = 1,
///YU [16:19]
///Year units in BCD format
yu: u4 = 0,
///YT [20:23]
///Year tens in BCD format
yt: u4 = 0,
_unused24: u8 = 0,
};
///date register
pub const dr = Register(dr_val).init(0x40002800 + 0x4);
//////////////////////////
///CR
const cr_val = packed struct {
_unused0: u3 = 0,
///TSEDGE [3:3]
///Time-stamp event active
///edge
tsedge: u1 = 0,
///REFCKON [4:4]
///RTC_REFIN reference clock detection
///enable (50 or 60 Hz)
refckon: u1 = 0,
///BYPSHAD [5:5]
///Bypass the shadow
///registers
bypshad: u1 = 0,
///FMT [6:6]
///Hour format
fmt: u1 = 0,
_unused7: u1 = 0,
///ALRAE [8:8]
///Alarm A enable
alrae: u1 = 0,
_unused9: u2 = 0,
///TSE [11:11]
///timestamp enable
tse: u1 = 0,
///ALRAIE [12:12]
///Alarm A interrupt enable
alraie: u1 = 0,
_unused13: u2 = 0,
///TSIE [15:15]
///Time-stamp interrupt
///enable
tsie: u1 = 0,
///ADD1H [16:16]
///Add 1 hour (summer time
///change)
add1h: u1 = 0,
///SUB1H [17:17]
///Subtract 1 hour (winter time
///change)
sub1h: u1 = 0,
///BKP [18:18]
///Backup
bkp: u1 = 0,
///COSEL [19:19]
///Calibration output
///selection
cosel: u1 = 0,
///POL [20:20]
///Output polarity
pol: u1 = 0,
///OSEL [21:22]
///Output selection
osel: u2 = 0,
///COE [23:23]
///Calibration output enable
coe: u1 = 0,
_unused24: u8 = 0,
};
///control register
pub const cr = Register(cr_val).init(0x40002800 + 0x8);
//////////////////////////
///ISR
const isr_val = packed struct {
///ALRAWF [0:0]
///Alarm A write flag
alrawf: u1 = 1,
_unused1: u2 = 0,
///SHPF [3:3]
///Shift operation pending
shpf: u1 = 0,
///INITS [4:4]
///Initialization status flag
inits: u1 = 0,
///RSF [5:5]
///Registers synchronization
///flag
rsf: u1 = 0,
///INITF [6:6]
///Initialization flag
initf: u1 = 0,
///INIT [7:7]
///Initialization mode
init: u1 = 0,
///ALRAF [8:8]
///Alarm A flag
alraf: u1 = 0,
_unused9: u2 = 0,
///TSF [11:11]
///Time-stamp flag
tsf: u1 = 0,
///TSOVF [12:12]
///Time-stamp overflow flag
tsovf: u1 = 0,
///TAMP1F [13:13]
///RTC_TAMP1 detection flag
tamp1f: u1 = 0,
///TAMP2F [14:14]
///RTC_TAMP2 detection flag
tamp2f: u1 = 0,
_unused15: u1 = 0,
///RECALPF [16:16]
///Recalibration pending Flag
recalpf: u1 = 0,
_unused17: u15 = 0,
};
///initialization and status
///register
pub const isr = Register(isr_val).init(0x40002800 + 0xC);
//////////////////////////
///PRER
const prer_val = packed struct {
///PREDIV_S [0:14]
///Synchronous prescaler
///factor
prediv_s: u15 = 255,
_unused15: u1 = 0,
///PREDIV_A [16:22]
///Asynchronous prescaler
///factor
prediv_a: u7 = 127,
_unused23: u9 = 0,
};
///prescaler register
pub const prer = Register(prer_val).init(0x40002800 + 0x10);
//////////////////////////
///ALRMAR
const alrmar_val = packed struct {
///SU [0:3]
///Second units in BCD
///format.
su: u4 = 0,
///ST [4:6]
///Second tens in BCD format.
st: u3 = 0,
///MSK1 [7:7]
///Alarm A seconds mask
msk1: u1 = 0,
///MNU [8:11]
///Minute units in BCD
///format.
mnu: u4 = 0,
///MNT [12:14]
///Minute tens in BCD format.
mnt: u3 = 0,
///MSK2 [15:15]
///Alarm A minutes mask
msk2: u1 = 0,
///HU [16:19]
///Hour units in BCD format.
hu: u4 = 0,
///HT [20:21]
///Hour tens in BCD format.
ht: u2 = 0,
///PM [22:22]
///AM/PM notation
pm: u1 = 0,
///MSK3 [23:23]
///Alarm A hours mask
msk3: u1 = 0,
///DU [24:27]
///Date units or day in BCD
///format.
du: u4 = 0,
///DT [28:29]
///Date tens in BCD format.
dt: u2 = 0,
///WDSEL [30:30]
///Week day selection
wdsel: u1 = 0,
///MSK4 [31:31]
///Alarm A date mask
msk4: u1 = 0,
};
///alarm A register
pub const alrmar = Register(alrmar_val).init(0x40002800 + 0x1C);
//////////////////////////
///WPR
const wpr_val = packed struct {
///KEY [0:7]
///Write protection key
key: u8 = 0,
_unused8: u24 = 0,
};
///write protection register
pub const wpr = RegisterRW(void, wpr_val).init(0x40002800 + 0x24);
//////////////////////////
///SSR
const ssr_val = packed struct {
///SS [0:15]
///Sub second value
ss: u16 = 0,
_unused16: u16 = 0,
};
///sub second register
pub const ssr = RegisterRW(ssr_val, void).init(0x40002800 + 0x28);
//////////////////////////
///SHIFTR
const shiftr_val = packed struct {
///SUBFS [0:14]
///Subtract a fraction of a
///second
subfs: u15 = 0,
_unused15: u16 = 0,
///ADD1S [31:31]
///Add one second
add1s: u1 = 0,
};
///shift control register
pub const shiftr = RegisterRW(void, shiftr_val).init(0x40002800 + 0x2C);
//////////////////////////
///TSTR
const tstr_val = packed struct {
///SU [0:3]
///Second units in BCD
///format.
su: u4 = 0,
///ST [4:6]
///Second tens in BCD format.
st: u3 = 0,
_unused7: u1 = 0,
///MNU [8:11]
///Minute units in BCD
///format.
mnu: u4 = 0,
///MNT [12:14]
///Minute tens in BCD format.
mnt: u3 = 0,
_unused15: u1 = 0,
///HU [16:19]
///Hour units in BCD format.
hu: u4 = 0,
///HT [20:21]
///Hour tens in BCD format.
ht: u2 = 0,
///PM [22:22]
///AM/PM notation
pm: u1 = 0,
_unused23: u9 = 0,
};
///timestamp time register
pub const tstr = RegisterRW(tstr_val, void).init(0x40002800 + 0x30);
//////////////////////////
///TSDR
const tsdr_val = packed struct {
///DU [0:3]
///Date units in BCD format
du: u4 = 0,
///DT [4:5]
///Date tens in BCD format
dt: u2 = 0,
_unused6: u2 = 0,
///MU [8:11]
///Month units in BCD format
mu: u4 = 0,
///MT [12:12]
///Month tens in BCD format
mt: u1 = 0,
///WDU [13:15]
///Week day units
wdu: u3 = 0,
_unused16: u16 = 0,
};
///timestamp date register
pub const tsdr = RegisterRW(tsdr_val, void).init(0x40002800 + 0x34);
//////////////////////////
///TSSSR
const tsssr_val = packed struct {
///SS [0:15]
///Sub second value
ss: u16 = 0,
_unused16: u16 = 0,
};
///time-stamp sub second register
pub const tsssr = RegisterRW(tsssr_val, void).init(0x40002800 + 0x38);
//////////////////////////
///CALR
const calr_val = packed struct {
///CALM [0:8]
///Calibration minus
calm: u9 = 0,
_unused9: u4 = 0,
///CALW16 [13:13]
///Use a 16-second calibration cycle
///period
calw16: u1 = 0,
///CALW8 [14:14]
///Use a 16-second calibration cycle
///period
calw8: u1 = 0,
///CALP [15:15]
///Use an 8-second calibration cycle
///period
calp: u1 = 0,
_unused16: u16 = 0,
};
///calibration register
pub const calr = Register(calr_val).init(0x40002800 + 0x3C);
//////////////////////////
///TAFCR
const tafcr_val = packed struct {
///TAMP1E [0:0]
///RTC_TAMP1 input detection
///enable
tamp1e: u1 = 0,
///TAMP1TRG [1:1]
///Active level for RTC_TAMP1
///input
tamp1trg: u1 = 0,
///TAMPIE [2:2]
///Tamper interrupt enable
tampie: u1 = 0,
///TAMP2E [3:3]
///RTC_TAMP2 input detection
///enable
tamp2e: u1 = 0,
///TAMP2_TRG [4:4]
///Active level for RTC_TAMP2
///input
tamp2_trg: u1 = 0,
_unused5: u2 = 0,
///TAMPTS [7:7]
///Activate timestamp on tamper detection
///event
tampts: u1 = 0,
///TAMPFREQ [8:10]
///Tamper sampling frequency
tampfreq: u3 = 0,
///TAMPFLT [11:12]
///RTC_TAMPx filter count
tampflt: u2 = 0,
///TAMP_PRCH [13:14]
///RTC_TAMPx precharge
///duration
tamp_prch: u2 = 0,
///TAMP_PUDIS [15:15]
///RTC_TAMPx pull-up disable
tamp_pudis: u1 = 0,
_unused16: u2 = 0,
///PC13VALUE [18:18]
///RTC_ALARM output type/PC13
///value
pc13value: u1 = 0,
///PC13MODE [19:19]
///PC13 mode
pc13mode: u1 = 0,
///PC14VALUE [20:20]
///PC14 value
pc14value: u1 = 0,
///PC14MODE [21:21]
///PC14 mode
pc14mode: u1 = 0,
///PC15VALUE [22:22]
///PC15 value
pc15value: u1 = 0,
///PC15MODE [23:23]
///PC15 mode
pc15mode: u1 = 0,
_unused24: u8 = 0,
};
///tamper and alternate function configuration
///register
pub const tafcr = Register(tafcr_val).init(0x40002800 + 0x40);
//////////////////////////
///ALRMASSR
const alrmassr_val = packed struct {
///SS [0:14]
///Sub seconds value
ss: u15 = 0,
_unused15: u9 = 0,
///MASKSS [24:27]
///Mask the most-significant bits starting
///at this bit
maskss: u4 = 0,
_unused28: u4 = 0,
};
///alarm A sub second register
pub const alrmassr = Register(alrmassr_val).init(0x40002800 + 0x44);
//////////////////////////
///BKP%sR
const bkpr_val = packed struct {
///BKP [0:31]
///BKP
bkp: u32 = 0,
};
///backup register
pub const bkpr = Register(bkpr_val).initRange(0x40002800 + 0x50, 4, 5);
};
///General-purpose-timers
pub const tim15 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: u1 = 0,
_unused4: u3 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40014000 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///CCPC [0:0]
///Capture/compare preloaded
///control
ccpc: u1 = 0,
_unused1: u1 = 0,
///CCUS [2:2]
///Capture/compare control update
///selection
ccus: u1 = 0,
///CCDS [3:3]
///Capture/compare DMA
///selection
ccds: u1 = 0,
///MMS [4:6]
///Master mode selection
mms: u3 = 0,
_unused7: u1 = 0,
///OIS1 [8:8]
///Output Idle state 1
ois1: u1 = 0,
///OIS1N [9:9]
///Output Idle state 1
ois1n: u1 = 0,
///OIS2 [10:10]
///Output Idle state 2
ois2: u1 = 0,
_unused11: u21 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40014000 + 0x4);
//////////////////////////
///SMCR
const smcr_val = packed struct {
///SMS [0:2]
///Slave mode selection
sms: u3 = 0,
_unused3: u1 = 0,
///TS [4:6]
///Trigger selection
ts: u3 = 0,
///MSM [7:7]
///Master/Slave mode
msm: u1 = 0,
_unused8: u24 = 0,
};
///slave mode control register
pub const smcr = Register(smcr_val).init(0x40014000 + 0x8);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: u1 = 0,
///CC2IE [2:2]
///Capture/Compare 2 interrupt
///enable
cc2ie: u1 = 0,
_unused3: u2 = 0,
///COMIE [5:5]
///COM interrupt enable
comie: u1 = 0,
///TIE [6:6]
///Trigger interrupt enable
tie: u1 = 0,
///BIE [7:7]
///Break interrupt enable
bie: u1 = 0,
///UDE [8:8]
///Update DMA request enable
ude: u1 = 0,
///CC1DE [9:9]
///Capture/Compare 1 DMA request
///enable
cc1de: u1 = 0,
///CC2DE [10:10]
///Capture/Compare 2 DMA request
///enable
cc2de: u1 = 0,
_unused11: u3 = 0,
///TDE [14:14]
///Trigger DMA request enable
tde: u1 = 0,
_unused15: u17 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40014000 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
///CC2IF [2:2]
///Capture/Compare 2 interrupt
///flag
cc2if: u1 = 0,
_unused3: u2 = 0,
///COMIF [5:5]
///COM interrupt flag
comif: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: u1 = 0,
///BIF [7:7]
///Break interrupt flag
bif: u1 = 0,
_unused8: u1 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
///CC2OF [10:10]
///Capture/compare 2 overcapture
///flag
cc2of: u1 = 0,
_unused11: u21 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40014000 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
///CC2G [2:2]
///Capture/compare 2
///generation
cc2g: u1 = 0,
_unused3: u2 = 0,
///COMG [5:5]
///Capture/Compare control update
///generation
comg: u1 = 0,
///TG [6:6]
///Trigger generation
tg: u1 = 0,
///BG [7:7]
///Break generation
bg: u1 = 0,
_unused8: u24 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40014000 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///OC1FE [2:2]
///Output Compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output Compare 1 preload
///enable
oc1pe: u1 = 0,
///OC1M [4:6]
///Output Compare 1 mode
oc1m: u3 = 0,
_unused7: u1 = 0,
///CC2S [8:9]
///Capture/Compare 2
///selection
cc2s: u2 = 0,
///OC2FE [10:10]
///Output Compare 2 fast
///enable
oc2fe: u1 = 0,
///OC2PE [11:11]
///Output Compare 2 preload
///enable
oc2pe: u1 = 0,
///OC2M [12:14]
///Output Compare 2 mode
oc2m: u3 = 0,
_unused15: u17 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40014000 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: u4 = 0,
///CC2S [8:9]
///Capture/Compare 2
///selection
cc2s: u2 = 0,
///IC2PSC [10:11]
///Input capture 2 prescaler
ic2psc: u2 = 0,
///IC2F [12:15]
///Input capture 2 filter
ic2f: u4 = 0,
_unused16: u16 = 0,
};
///capture/compare mode register 1 (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40014000 + 0x18);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
///CC1NE [2:2]
///Capture/Compare 1 complementary output
///enable
cc1ne: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
///CC2E [4:4]
///Capture/Compare 2 output
///enable
cc2e: u1 = 0,
///CC2P [5:5]
///Capture/Compare 2 output
///Polarity
cc2p: u1 = 0,
_unused6: u1 = 0,
///CC2NP [7:7]
///Capture/Compare 2 output
///Polarity
cc2np: u1 = 0,
_unused8: u24 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40014000 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40014000 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40014000 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40014000 + 0x2C);
//////////////////////////
///RCR
const rcr_val = packed struct {
///REP [0:7]
///Repetition counter value
rep: u8 = 0,
_unused8: u24 = 0,
};
///repetition counter register
pub const rcr = Register(rcr_val).init(0x40014000 + 0x30);
//////////////////////////
///CCR1
const ccr1_val = packed struct {
///CCR1 [0:15]
///Capture/Compare 1 value
ccr1: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 1
pub const ccr1 = Register(ccr1_val).init(0x40014000 + 0x34);
//////////////////////////
///CCR2
const ccr2_val = packed struct {
///CCR2 [0:15]
///Capture/Compare 2 value
ccr2: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 2
pub const ccr2 = Register(ccr2_val).init(0x40014000 + 0x38);
//////////////////////////
///BDTR
const bdtr_val = packed struct {
///DTG [0:7]
///Dead-time generator setup
dtg: u8 = 0,
///LOCK [8:9]
///Lock configuration
lock: u2 = 0,
///OSSI [10:10]
///Off-state selection for Idle
///mode
ossi: u1 = 0,
///OSSR [11:11]
///Off-state selection for Run
///mode
ossr: u1 = 0,
///BKE [12:12]
///Break enable
bke: u1 = 0,
///BKP [13:13]
///Break polarity
bkp: u1 = 0,
///AOE [14:14]
///Automatic output enable
aoe: u1 = 0,
///MOE [15:15]
///Main output enable
moe: u1 = 0,
_unused16: u16 = 0,
};
///break and dead-time register
pub const bdtr = Register(bdtr_val).init(0x40014000 + 0x44);
//////////////////////////
///DCR
const dcr_val = packed struct {
///DBA [0:4]
///DMA base address
dba: u5 = 0,
_unused5: u3 = 0,
///DBL [8:12]
///DMA burst length
dbl: u5 = 0,
_unused13: u19 = 0,
};
///DMA control register
pub const dcr = Register(dcr_val).init(0x40014000 + 0x48);
//////////////////////////
///DMAR
const dmar_val = packed struct {
///DMAB [0:15]
///DMA register for burst
///accesses
dmab: u16 = 0,
_unused16: u16 = 0,
};
///DMA address for full transfer
pub const dmar = Register(dmar_val).init(0x40014000 + 0x4C);
};
///General-purpose-timers
pub const tim16 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Not stopped at update event
not_stopped = 0,
///Counter stops counting at next update event
stopped = 1,
} = .not_stopped,
_unused4: u3 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40014400 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///CCPC [0:0]
///Capture/compare preloaded
///control
ccpc: packed enum(u1) {
///CCxE, CCxNE and OCxM bits are not preloaded
not_preloaded = 0,
///CCxE, CCxNE and OCxM bits are preloaded
preloaded = 1,
} = .not_preloaded,
_unused1: u1 = 0,
///CCUS [2:2]
///Capture/compare control update
///selection
ccus: packed enum(u1) {
///Capture/compare are updated only by setting the COMG bit
default = 0,
///Capture/compare are updated by setting the COMG bit or when an rising edge occurs on TRGI
with_rising_edge = 1,
} = .default,
///CCDS [3:3]
///Capture/compare DMA
///selection
ccds: packed enum(u1) {
///CCx DMA request sent when CCx event occurs
on_compare = 0,
///CCx DMA request sent when update event occurs
on_update = 1,
} = .on_compare,
_unused4: u4 = 0,
///OIS1 [8:8]
///Output Idle state 1
ois1: packed enum(u1) {
///OC1=0 (after a dead-time if OC1N is implemented) when MOE=0
low = 0,
///OC1=1 (after a dead-time if OC1N is implemented) when MOE=0
high = 1,
} = .low,
///OIS1N [9:9]
///Output Idle state 1
ois1n: packed enum(u1) {
///OC1N=0 after a dead-time when MOE=0
low = 0,
///OC1N=1 after a dead-time when MOE=0
high = 1,
} = .low,
_unused10: u22 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40014400 + 0x4);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: packed enum(u1) {
///CC1 interrupt disabled
disabled = 0,
///CC1 interrupt enabled
enabled = 1,
} = .disabled,
_unused2: u3 = 0,
///COMIE [5:5]
///COM interrupt enable
comie: packed enum(u1) {
///COM interrupt disabled
disabled = 0,
///COM interrupt enabled
enabled = 1,
} = .disabled,
///TIE [6:6]
///Trigger interrupt enable
tie: u1 = 0,
///BIE [7:7]
///Break interrupt enable
bie: packed enum(u1) {
///Break interrupt disabled
disabled = 0,
///Break interrupt enabled
enabled = 1,
} = .disabled,
///UDE [8:8]
///Update DMA request enable
ude: u1 = 0,
///CC1DE [9:9]
///Capture/Compare 1 DMA request
///enable
cc1de: packed enum(u1) {
///CC1 DMA request disabled
disabled = 0,
///CC1 DMA request enabled
enabled = 1,
} = .disabled,
_unused10: u4 = 0,
///TDE [14:14]
///Trigger DMA request enable
tde: u1 = 0,
_unused15: u17 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40014400 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
_unused2: u3 = 0,
///COMIF [5:5]
///COM interrupt flag
comif: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: u1 = 0,
///BIF [7:7]
///Break interrupt flag
bif: u1 = 0,
_unused8: u1 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
_unused10: u22 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40014400 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
_unused2: u3 = 0,
///COMG [5:5]
///Capture/Compare control update
///generation
comg: u1 = 0,
///TG [6:6]
///Trigger generation
tg: u1 = 0,
///BG [7:7]
///Break generation
bg: u1 = 0,
_unused8: u24 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40014400 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///OC1FE [2:2]
///Output Compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output Compare 1 preload
///enable
oc1pe: u1 = 0,
///OC1M [4:6]
///Output Compare 1 mode
oc1m: u3 = 0,
_unused7: u25 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40014400 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: u4 = 0,
_unused8: u24 = 0,
};
///capture/compare mode register 1 (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40014400 + 0x18);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
///CC1NE [2:2]
///Capture/Compare 1 complementary output
///enable
cc1ne: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
_unused4: u28 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40014400 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40014400 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40014400 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40014400 + 0x2C);
//////////////////////////
///RCR
const rcr_val = packed struct {
///REP [0:7]
///Repetition counter value
rep: u8 = 0,
_unused8: u24 = 0,
};
///repetition counter register
pub const rcr = Register(rcr_val).init(0x40014400 + 0x30);
//////////////////////////
///CCR1
const ccr1_val = packed struct {
///CCR1 [0:15]
///Capture/Compare 1 value
ccr1: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 1
pub const ccr1 = Register(ccr1_val).init(0x40014400 + 0x34);
//////////////////////////
///BDTR
const bdtr_val = packed struct {
///DTG [0:7]
///Dead-time generator setup
dtg: u8 = 0,
///LOCK [8:9]
///Lock configuration
lock: u2 = 0,
///OSSI [10:10]
///Off-state selection for Idle
///mode
ossi: u1 = 0,
///OSSR [11:11]
///Off-state selection for Run
///mode
ossr: u1 = 0,
///BKE [12:12]
///Break enable
bke: u1 = 0,
///BKP [13:13]
///Break polarity
bkp: u1 = 0,
///AOE [14:14]
///Automatic output enable
aoe: u1 = 0,
///MOE [15:15]
///Main output enable
moe: u1 = 0,
_unused16: u16 = 0,
};
///break and dead-time register
pub const bdtr = Register(bdtr_val).init(0x40014400 + 0x44);
//////////////////////////
///DCR
const dcr_val = packed struct {
///DBA [0:4]
///DMA base address
dba: u5 = 0,
_unused5: u3 = 0,
///DBL [8:12]
///DMA burst length
dbl: u5 = 0,
_unused13: u19 = 0,
};
///DMA control register
pub const dcr = Register(dcr_val).init(0x40014400 + 0x48);
//////////////////////////
///DMAR
const dmar_val = packed struct {
///DMAB [0:15]
///DMA register for burst
///accesses
dmab: u16 = 0,
_unused16: u16 = 0,
};
///DMA address for full transfer
pub const dmar = Register(dmar_val).init(0x40014400 + 0x4C);
};
///General-purpose-timers
pub const tim17 = struct {
//////////////////////////
///CR1
const cr1_val = packed struct {
///CEN [0:0]
///Counter enable
cen: packed enum(u1) {
///Counter disabled
disabled = 0,
///Counter enabled
enabled = 1,
} = .disabled,
///UDIS [1:1]
///Update disable
udis: packed enum(u1) {
///Update event enabled
enabled = 0,
///Update event disabled
disabled = 1,
} = .enabled,
///URS [2:2]
///Update request source
urs: packed enum(u1) {
///Any of counter overflow/underflow, setting UG, or update through slave mode, generates an update interrupt or DMA request
any_event = 0,
///Only counter overflow/underflow generates an update interrupt or DMA request
counter_only = 1,
} = .any_event,
///OPM [3:3]
///One-pulse mode
opm: packed enum(u1) {
///Not stopped at update event
not_stopped = 0,
///Counter stops counting at next update event
stopped = 1,
} = .not_stopped,
_unused4: u3 = 0,
///ARPE [7:7]
///Auto-reload preload enable
arpe: packed enum(u1) {
///TIMx_APRR register is not buffered
disabled = 0,
///TIMx_APRR register is buffered
enabled = 1,
} = .disabled,
///CKD [8:9]
///Clock division
ckd: packed enum(u2) {
///t_DTS = t_CK_INT
div1 = 0,
///t_DTS = 2 × t_CK_INT
div2 = 1,
///t_DTS = 4 × t_CK_INT
div4 = 2,
} = .div1,
_unused10: u22 = 0,
};
///control register 1
pub const cr1 = Register(cr1_val).init(0x40014800 + 0x0);
//////////////////////////
///CR2
const cr2_val = packed struct {
///CCPC [0:0]
///Capture/compare preloaded
///control
ccpc: packed enum(u1) {
///CCxE, CCxNE and OCxM bits are not preloaded
not_preloaded = 0,
///CCxE, CCxNE and OCxM bits are preloaded
preloaded = 1,
} = .not_preloaded,
_unused1: u1 = 0,
///CCUS [2:2]
///Capture/compare control update
///selection
ccus: packed enum(u1) {
///Capture/compare are updated only by setting the COMG bit
default = 0,
///Capture/compare are updated by setting the COMG bit or when an rising edge occurs on TRGI
with_rising_edge = 1,
} = .default,
///CCDS [3:3]
///Capture/compare DMA
///selection
ccds: packed enum(u1) {
///CCx DMA request sent when CCx event occurs
on_compare = 0,
///CCx DMA request sent when update event occurs
on_update = 1,
} = .on_compare,
_unused4: u4 = 0,
///OIS1 [8:8]
///Output Idle state 1
ois1: packed enum(u1) {
///OC1=0 (after a dead-time if OC1N is implemented) when MOE=0
low = 0,
///OC1=1 (after a dead-time if OC1N is implemented) when MOE=0
high = 1,
} = .low,
///OIS1N [9:9]
///Output Idle state 1
ois1n: packed enum(u1) {
///OC1N=0 after a dead-time when MOE=0
low = 0,
///OC1N=1 after a dead-time when MOE=0
high = 1,
} = .low,
_unused10: u22 = 0,
};
///control register 2
pub const cr2 = Register(cr2_val).init(0x40014800 + 0x4);
//////////////////////////
///DIER
const dier_val = packed struct {
///UIE [0:0]
///Update interrupt enable
uie: packed enum(u1) {
///Update interrupt disabled
disabled = 0,
///Update interrupt enabled
enabled = 1,
} = .disabled,
///CC1IE [1:1]
///Capture/Compare 1 interrupt
///enable
cc1ie: packed enum(u1) {
///CC1 interrupt disabled
disabled = 0,
///CC1 interrupt enabled
enabled = 1,
} = .disabled,
_unused2: u3 = 0,
///COMIE [5:5]
///COM interrupt enable
comie: packed enum(u1) {
///COM interrupt disabled
disabled = 0,
///COM interrupt enabled
enabled = 1,
} = .disabled,
///TIE [6:6]
///Trigger interrupt enable
tie: u1 = 0,
///BIE [7:7]
///Break interrupt enable
bie: packed enum(u1) {
///Break interrupt disabled
disabled = 0,
///Break interrupt enabled
enabled = 1,
} = .disabled,
///UDE [8:8]
///Update DMA request enable
ude: u1 = 0,
///CC1DE [9:9]
///Capture/Compare 1 DMA request
///enable
cc1de: packed enum(u1) {
///CC1 DMA request disabled
disabled = 0,
///CC1 DMA request enabled
enabled = 1,
} = .disabled,
_unused10: u4 = 0,
///TDE [14:14]
///Trigger DMA request enable
tde: u1 = 0,
_unused15: u17 = 0,
};
///DMA/Interrupt enable register
pub const dier = Register(dier_val).init(0x40014800 + 0xC);
//////////////////////////
///SR
const sr_val = packed struct {
///UIF [0:0]
///Update interrupt flag
uif: packed enum(u1) {
///No update occurred
clear = 0,
///Update interrupt pending.
update_pending = 1,
} = .clear,
///CC1IF [1:1]
///Capture/compare 1 interrupt
///flag
cc1if: u1 = 0,
_unused2: u3 = 0,
///COMIF [5:5]
///COM interrupt flag
comif: u1 = 0,
///TIF [6:6]
///Trigger interrupt flag
tif: u1 = 0,
///BIF [7:7]
///Break interrupt flag
bif: u1 = 0,
_unused8: u1 = 0,
///CC1OF [9:9]
///Capture/Compare 1 overcapture
///flag
cc1of: u1 = 0,
_unused10: u22 = 0,
};
///status register
pub const sr = Register(sr_val).init(0x40014800 + 0x10);
//////////////////////////
///EGR
const egr_val = packed struct {
///UG [0:0]
///Update generation
ug: packed enum(u1) {
///Re-initializes the timer counter and generates an update of the registers.
update = 1,
_zero = 0,
} = ._zero,
///CC1G [1:1]
///Capture/compare 1
///generation
cc1g: u1 = 0,
_unused2: u3 = 0,
///COMG [5:5]
///Capture/Compare control update
///generation
comg: u1 = 0,
///TG [6:6]
///Trigger generation
tg: u1 = 0,
///BG [7:7]
///Break generation
bg: u1 = 0,
_unused8: u24 = 0,
};
///event generation register
pub const egr = RegisterRW(void, egr_val).init(0x40014800 + 0x14);
//////////////////////////
///CCMR1_Output
const ccmr1_output_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///OC1FE [2:2]
///Output Compare 1 fast
///enable
oc1fe: u1 = 0,
///OC1PE [3:3]
///Output Compare 1 preload
///enable
oc1pe: u1 = 0,
///OC1M [4:6]
///Output Compare 1 mode
oc1m: u3 = 0,
_unused7: u25 = 0,
};
///capture/compare mode register (output
///mode)
pub const ccmr1_output = Register(ccmr1_output_val).init(0x40014800 + 0x18);
//////////////////////////
///CCMR1_Input
const ccmr1_input_val = packed struct {
///CC1S [0:1]
///Capture/Compare 1
///selection
cc1s: u2 = 0,
///IC1PSC [2:3]
///Input capture 1 prescaler
ic1psc: u2 = 0,
///IC1F [4:7]
///Input capture 1 filter
ic1f: u4 = 0,
_unused8: u24 = 0,
};
///capture/compare mode register 1 (input
///mode)
pub const ccmr1_input = Register(ccmr1_input_val).init(0x40014800 + 0x18);
//////////////////////////
///CCER
const ccer_val = packed struct {
///CC1E [0:0]
///Capture/Compare 1 output
///enable
cc1e: u1 = 0,
///CC1P [1:1]
///Capture/Compare 1 output
///Polarity
cc1p: u1 = 0,
///CC1NE [2:2]
///Capture/Compare 1 complementary output
///enable
cc1ne: u1 = 0,
///CC1NP [3:3]
///Capture/Compare 1 output
///Polarity
cc1np: u1 = 0,
_unused4: u28 = 0,
};
///capture/compare enable
///register
pub const ccer = Register(ccer_val).init(0x40014800 + 0x20);
//////////////////////////
///CNT
const cnt_val = packed struct {
///CNT [0:15]
///counter value
cnt: u16 = 0,
_unused16: u16 = 0,
};
///counter
pub const cnt = Register(cnt_val).init(0x40014800 + 0x24);
//////////////////////////
///PSC
const psc_val = packed struct {
///PSC [0:15]
///Prescaler value
psc: u16 = 0,
_unused16: u16 = 0,
};
///prescaler
pub const psc = Register(psc_val).init(0x40014800 + 0x28);
//////////////////////////
///ARR
const arr_val = packed struct {
///ARR [0:15]
///Auto-reload value
arr: u16 = 0,
_unused16: u16 = 0,
};
///auto-reload register
pub const arr = Register(arr_val).init(0x40014800 + 0x2C);
//////////////////////////
///RCR
const rcr_val = packed struct {
///REP [0:7]
///Repetition counter value
rep: u8 = 0,
_unused8: u24 = 0,
};
///repetition counter register
pub const rcr = Register(rcr_val).init(0x40014800 + 0x30);
//////////////////////////
///CCR1
const ccr1_val = packed struct {
///CCR1 [0:15]
///Capture/Compare 1 value
ccr1: u16 = 0,
_unused16: u16 = 0,
};
///capture/compare register 1
pub const ccr1 = Register(ccr1_val).init(0x40014800 + 0x34);
//////////////////////////
///BDTR
const bdtr_val = packed struct {
///DTG [0:7]
///Dead-time generator setup
dtg: u8 = 0,
///LOCK [8:9]
///Lock configuration
lock: u2 = 0,
///OSSI [10:10]
///Off-state selection for Idle
///mode
ossi: u1 = 0,
///OSSR [11:11]
///Off-state selection for Run
///mode
ossr: u1 = 0,
///BKE [12:12]
///Break enable
bke: u1 = 0,
///BKP [13:13]
///Break polarity
bkp: u1 = 0,
///AOE [14:14]
///Automatic output enable
aoe: u1 = 0,
///MOE [15:15]
///Main output enable
moe: u1 = 0,
_unused16: u16 = 0,
};
///break and dead-time register
pub const bdtr = Register(bdtr_val).init(0x40014800 + 0x44);
//////////////////////////
///DCR
const dcr_val = packed struct {
///DBA [0:4]
///DMA base address
dba: u5 = 0,
_unused5: u3 = 0,
///DBL [8:12]
///DMA burst length
dbl: u5 = 0,
_unused13: u19 = 0,
};
///DMA control register
pub const dcr = Register(dcr_val).init(0x40014800 + 0x48);
//////////////////////////
///DMAR
const dmar_val = packed struct {
///DMAB [0:15]
///DMA register for burst
///accesses
dmab: u16 = 0,
_unused16: u16 = 0,
};
///DMA address for full transfer
pub const dmar = Register(dmar_val).init(0x40014800 + 0x4C);
};
///Flash
pub const flash = struct {
//////////////////////////
///ACR
const acr_val_read = packed struct {
///LATENCY [0:2]
///LATENCY
latency: u3 = 0,
_unused3: u1 = 0,
///PRFTBE [4:4]
///PRFTBE
prftbe: u1 = 1,
///PRFTBS [5:5]
///PRFTBS
prftbs: packed enum(u1) {
///Prefetch buffer is disabled
disabled = 0,
///Prefetch buffer is enabled
enabled = 1,
} = .enabled,
_unused6: u26 = 0,
};
const acr_val_write = packed struct {
///LATENCY [0:2]
///LATENCY
latency: u3 = 0,
_unused3: u1 = 0,
///PRFTBE [4:4]
///PRFTBE
prftbe: u1 = 1,
///PRFTBS [5:5]
///PRFTBS
prftbs: u1 = 1,
_unused6: u26 = 0,
};
///Flash access control register
pub const acr = Register(acr_val).init(0x40022000 + 0x0);
//////////////////////////
///KEYR
const keyr_val = packed struct {
///FKEYR [0:31]
///Flash Key
fkeyr: u32 = 0,
};
///Flash key register
pub const keyr = RegisterRW(void, keyr_val).init(0x40022000 + 0x4);
//////////////////////////
///OPTKEYR
const optkeyr_val = packed struct {
///OPTKEYR [0:31]
///Option byte key
optkeyr: u32 = 0,
};
///Flash option key register
pub const optkeyr = RegisterRW(void, optkeyr_val).init(0x40022000 + 0x8);
//////////////////////////
///SR
const sr_val_read = packed struct {
///BSY [0:0]
///Busy
bsy: packed enum(u1) {
///No write/erase operation is in progress
inactive = 0,
///A write/erase operation is in progress
active = 1,
} = .inactive,
_unused1: u1 = 0,
///PGERR [2:2]
///Programming error
pgerr: u1 = 0,
_unused3: u1 = 0,
///WRPRT [4:4]
///Write protection error
wrprt: u1 = 0,
///EOP [5:5]
///End of operation
eop: u1 = 0,
_unused6: u26 = 0,
};
const sr_val_write = packed struct {
///BSY [0:0]
///Busy
bsy: u1 = 0,
_unused1: u1 = 0,
///PGERR [2:2]
///Programming error
pgerr: u1 = 0,
_unused3: u1 = 0,
///WRPRT [4:4]
///Write protection error
wrprt: u1 = 0,
///EOP [5:5]
///End of operation
eop: u1 = 0,
_unused6: u26 = 0,
};
///Flash status register
pub const sr = Register(sr_val).init(0x40022000 + 0xC);
//////////////////////////
///CR
const cr_val = packed struct {
///PG [0:0]
///Programming
pg: packed enum(u1) {
///Flash programming activated
program = 1,
_zero = 0,
} = ._zero,
///PER [1:1]
///Page erase
per: packed enum(u1) {
///Erase activated for selected page
page_erase = 1,
_zero = 0,
} = ._zero,
///MER [2:2]
///Mass erase
mer: packed enum(u1) {
///Erase activated for all user sectors
mass_erase = 1,
_zero = 0,
} = ._zero,
_unused3: u1 = 0,
///OPTPG [4:4]
///Option byte programming
optpg: packed enum(u1) {
///Program option byte activated
option_byte_programming = 1,
_zero = 0,
} = ._zero,
///OPTER [5:5]
///Option byte erase
opter: packed enum(u1) {
///Erase option byte activated
option_byte_erase = 1,
_zero = 0,
} = ._zero,
///STRT [6:6]
///Start
strt: packed enum(u1) {
///Trigger an erase operation
start = 1,
_zero = 0,
} = ._zero,
///LOCK [7:7]
///Lock
lock: packed enum(u1) {
///FLASH_CR register is unlocked
unlocked = 0,
///FLASH_CR register is locked
locked = 1,
} = .locked,
_unused8: u1 = 0,
///OPTWRE [9:9]
///Option bytes write enable
optwre: packed enum(u1) {
///Option byte write disabled
disabled = 0,
///Option byte write enabled
enabled = 1,
} = .disabled,
///ERRIE [10:10]
///Error interrupt enable
errie: packed enum(u1) {
///Error interrupt generation disabled
disabled = 0,
///Error interrupt generation enabled
enabled = 1,
} = .disabled,
_unused11: u1 = 0,
///EOPIE [12:12]
///End of operation interrupt
///enable
eopie: packed enum(u1) {
///End of operation interrupt disabled
disabled = 0,
///End of operation interrupt enabled
enabled = 1,
} = .disabled,
///FORCE_OPTLOAD [13:13]
///Force option byte loading
force_optload: packed enum(u1) {
///Force option byte loading inactive
inactive = 0,
///Force option byte loading active
active = 1,
} = .inactive,
_unused14: u18 = 0,
};
///Flash control register
pub const cr = Register(cr_val).init(0x40022000 + 0x10);
//////////////////////////
///AR
const ar_val = packed struct {
///FAR [0:31]
///Flash address
far: u32 = 0,
};
///Flash address register
pub const ar = RegisterRW(void, ar_val).init(0x40022000 + 0x14);
//////////////////////////
///OBR
const obr_val = packed struct {
///OPTERR [0:0]
///Option byte error
opterr: packed enum(u1) {
///The loaded option byte and its complement do not match
option_byte_error = 1,
_zero = 0,
} = ._zero,
///RDPRT [1:2]
///Read protection level
///status
rdprt: packed enum(u2) {
///Level 0
level0 = 0,
///Level 1
level1 = 1,
///Level 2
level2 = 3,
} = .level1,
_unused3: u5 = 0,
///WDG_SW [8:8]
///WDG_SW
wdg_sw: packed enum(u1) {
///Hardware watchdog
hardware = 0,
///Software watchdog
software = 1,
} = .software,
///nRST_STOP [9:9]
///nRST_STOP
n_rst_stop: packed enum(u1) {
///Reset generated when entering Stop mode
reset = 0,
///No reset generated
no_reset = 1,
} = .no_reset,
///nRST_STDBY [10:10]
///nRST_STDBY
n_rst_stdby: packed enum(u1) {
///Reset generated when entering Standby mode
reset = 0,
///No reset generated
no_reset = 1,
} = .no_reset,
_unused11: u1 = 0,
///nBOOT1 [12:12]
///BOOT1
n_boot1: packed enum(u1) {
///Together with BOOT0, select the device boot mode
disabled = 0,
///Together with BOOT0, select the device boot mode
enabled = 1,
} = .enabled,
///VDDA_MONITOR [13:13]
///VDDA_MONITOR
vdda_monitor: packed enum(u1) {
///VDDA power supply supervisor disabled
disabled = 0,
///VDDA power supply supervisor enabled
enabled = 1,
} = .enabled,
///RAM_PARITY_CHECK [14:14]
///RAM_PARITY_CHECK
ram_parity_check: packed enum(u1) {
///RAM parity check disabled
disabled = 1,
///RAM parity check enabled
enabled = 0,
} = .disabled,
_unused15: u1 = 0,
///Data0 [16:23]
///Data0
data0: u8 = 255,
///Data1 [24:31]
///Data1
data1: u8 = 3,
};
///Option byte register
pub const obr = RegisterRW(obr_val, void).init(0x40022000 + 0x1C);
//////////////////////////
///WRPR
const wrpr_val = packed struct {
///WRP [0:31]
///Write protect
wrp: u32 = 4294967295,
};
///Write protection register
pub const wrpr = RegisterRW(wrpr_val, void).init(0x40022000 + 0x20);
};
///Debug support
pub const dbgmcu = struct {
//////////////////////////
///IDCODE
const idcode_val = packed struct {
///DEV_ID [0:11]
///Device Identifier
dev_id: u12 = 0,
///DIV_ID [12:15]
///Division Identifier
div_id: u4 = 0,
///REV_ID [16:31]
///Revision Identifier
rev_id: u16 = 0,
};
///MCU Device ID Code Register
pub const idcode = RegisterRW(idcode_val, void).init(0x40015800 + 0x0);
//////////////////////////
///CR
const cr_val = packed struct {
_unused0: u1 = 0,
///DBG_STOP [1:1]
///Debug Stop Mode
dbg_stop: u1 = 0,
///DBG_STANDBY [2:2]
///Debug Standby Mode
dbg_standby: u1 = 0,
_unused3: u29 = 0,
};
///Debug MCU Configuration
///Register
pub const cr = Register(cr_val).init(0x40015800 + 0x4);
//////////////////////////
///APB1_FZ
const apb1_fz_val = packed struct {
_unused0: u1 = 0,
///DBG_TIM3_STOP [1:1]
///TIM3 counter stopped when core is
///halted
dbg_tim3_stop: u1 = 0,
_unused2: u2 = 0,
///DBG_TIM6_STOP [4:4]
///TIM6 counter stopped when core is
///halted
dbg_tim6_stop: u1 = 0,
///DBG_TIM7_STOP [5:5]
///TIM7 counter stopped when core is
///halted
dbg_tim7_stop: u1 = 0,
_unused6: u2 = 0,
///DBG_TIM14_STOP [8:8]
///TIM14 counter stopped when core is
///halted
dbg_tim14_stop: u1 = 0,
_unused9: u2 = 0,
///DBG_WWDG_STOP [11:11]
///Debug window watchdog stopped when core
///is halted
dbg_wwdg_stop: u1 = 0,
///DBG_IWDG_STOP [12:12]
///Debug independent watchdog stopped when
///core is halted
dbg_iwdg_stop: u1 = 0,
_unused13: u8 = 0,
///DBG_I2C1_SMBUS_TIMEOUT [21:21]
///SMBUS timeout mode stopped when core is
///halted
dbg_i2c1_smbus_timeout: u1 = 0,
_unused22: u10 = 0,
};
///Debug MCU APB1 freeze register
pub const apb1_fz = Register(apb1_fz_val).init(0x40015800 + 0x8);
//////////////////////////
///APB2_FZ
const apb2_fz_val = packed struct {
_unused0: u11 = 0,
///DBG_TIM1_STOP [11:11]
///TIM1 counter stopped when core is
///halted
dbg_tim1_stop: u1 = 0,
_unused12: u4 = 0,
///DBG_TIM15_STOP [16:16]
///TIM15 counter stopped when core is
///halted
dbg_tim15_stop: u1 = 0,
///DBG_TIM16_STOP [17:17]
///TIM16 counter stopped when core is
///halted
dbg_tim16_stop: u1 = 0,
///DBG_TIM17_STOP [18:18]
///TIM17 counter stopped when core is
///halted
dbg_tim17_stop: u1 = 0,
_unused19: u13 = 0,
};
///Debug MCU APB2 freeze register
pub const apb2_fz = Register(apb2_fz_val).init(0x40015800 + 0xC);
};
///Universal serial bus full-speed device
///interface
pub const usb = struct {
//////////////////////////
///EP0R
const ep0r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 0 register
pub const ep0r = Register(ep0r_val).init(0x40005C00 + 0x0);
//////////////////////////
///EP1R
const ep1r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 1 register
pub const ep1r = Register(ep1r_val).init(0x40005C00 + 0x4);
//////////////////////////
///EP2R
const ep2r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 2 register
pub const ep2r = Register(ep2r_val).init(0x40005C00 + 0x8);
//////////////////////////
///EP3R
const ep3r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 3 register
pub const ep3r = Register(ep3r_val).init(0x40005C00 + 0xC);
//////////////////////////
///EP4R
const ep4r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 4 register
pub const ep4r = Register(ep4r_val).init(0x40005C00 + 0x10);
//////////////////////////
///EP5R
const ep5r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 5 register
pub const ep5r = Register(ep5r_val).init(0x40005C00 + 0x14);
//////////////////////////
///EP6R
const ep6r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 6 register
pub const ep6r = Register(ep6r_val).init(0x40005C00 + 0x18);
//////////////////////////
///EP7R
const ep7r_val = packed struct {
///EA [0:3]
///Endpoint address
ea: u4 = 0,
///STAT_TX [4:5]
///Status bits, for transmission
///transfers
stat_tx: packed enum(u2) {
///all transmission requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all transmission requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all transmission requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for transmission
valid = 3,
} = .disabled,
///DTOG_TX [6:6]
///Data Toggle, for transmission
///transfers
dtog_tx: u1 = 0,
///CTR_TX [7:7]
///Correct Transfer for
///transmission
ctr_tx: u1 = 0,
///EP_KIND [8:8]
///Endpoint kind
ep_kind: u1 = 0,
///EP_TYPE [9:10]
///Endpoint type
ep_type: packed enum(u2) {
///Bulk endpoint
bulk = 0,
///Control endpoint
control = 1,
///Iso endpoint
iso = 2,
///Interrupt endpoint
interrupt = 3,
} = .bulk,
///SETUP [11:11]
///Setup transaction
///completed
setup: u1 = 0,
///STAT_RX [12:13]
///Status bits, for reception
///transfers
stat_rx: packed enum(u2) {
///all reception requests addressed to this endpoint are ignored
disabled = 0,
///the endpoint is stalled and all reception requests result in a STALL handshake
stall = 1,
///the endpoint is naked and all reception requests result in a NAK handshake
nak = 2,
///this endpoint is enabled for reception
valid = 3,
} = .disabled,
///DTOG_RX [14:14]
///Data Toggle, for reception
///transfers
dtog_rx: u1 = 0,
///CTR_RX [15:15]
///Correct transfer for
///reception
ctr_rx: u1 = 0,
_unused16: u16 = 0,
};
///endpoint 7 register
pub const ep7r = Register(ep7r_val).init(0x40005C00 + 0x1C);
//////////////////////////
///CNTR
const cntr_val = packed struct {
///FRES [0:0]
///Force USB Reset
fres: packed enum(u1) {
///Clear USB reset
no_reset = 0,
///Force a reset of the USB peripheral, exactly like a RESET signaling on the USB
reset = 1,
} = .reset,
///PDWN [1:1]
///Power down
pdwn: packed enum(u1) {
///No power down
disabled = 0,
///Enter power down mode
enabled = 1,
} = .enabled,
///LPMODE [2:2]
///Low-power mode
lpmode: packed enum(u1) {
///No low-power mode
disabled = 0,
///Enter low-power mode
enabled = 1,
} = .disabled,
///FSUSP [3:3]
///Force suspend
fsusp: packed enum(u1) {
///No effect
no_effect = 0,
///Enter suspend mode. Clocks and static power dissipation in the analog transceiver are left unaffected
_suspend = 1,
} = .no_effect,
///RESUME [4:4]
///Resume request
_resume: packed enum(u1) {
///Resume requested
requested = 1,
_zero = 0,
} = ._zero,
///L1RESUME [5:5]
///LPM L1 Resume request
l1resume: packed enum(u1) {
///LPM L1 request requested
requested = 1,
_zero = 0,
} = ._zero,
_unused6: u1 = 0,
///L1REQM [7:7]
///LPM L1 state request interrupt
///mask
l1reqm: packed enum(u1) {
///L1REQ Interrupt disabled
disabled = 0,
///L1REQ Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///ESOFM [8:8]
///Expected start of frame interrupt
///mask
esofm: packed enum(u1) {
///ESOF Interrupt disabled
disabled = 0,
///ESOF Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///SOFM [9:9]
///Start of frame interrupt
///mask
sofm: packed enum(u1) {
///SOF Interrupt disabled
disabled = 0,
///SOF Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///RESETM [10:10]
///USB reset interrupt mask
resetm: packed enum(u1) {
///RESET Interrupt disabled
disabled = 0,
///RESET Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///SUSPM [11:11]
///Suspend mode interrupt
///mask
suspm: packed enum(u1) {
///Suspend Mode Request SUSP Interrupt disabled
disabled = 0,
///SUSP Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///WKUPM [12:12]
///Wakeup interrupt mask
wkupm: packed enum(u1) {
///WKUP Interrupt disabled
disabled = 0,
///WKUP Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///ERRM [13:13]
///Error interrupt mask
errm: packed enum(u1) {
///ERR Interrupt disabled
disabled = 0,
///ERR Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///PMAOVRM [14:14]
///Packet memory area over / underrun
///interrupt mask
pmaovrm: packed enum(u1) {
///PMAOVR Interrupt disabled
disabled = 0,
///PMAOVR Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
///CTRM [15:15]
///Correct transfer interrupt
///mask
ctrm: packed enum(u1) {
///Correct Transfer (CTR) Interrupt disabled
disabled = 0,
///CTR Interrupt enabled, an interrupt request is generated when the corresponding bit in the USB_ISTR register is set
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///control register
pub const cntr = Register(cntr_val).init(0x40005C00 + 0x40);
//////////////////////////
///ISTR
const istr_val = packed struct {
///EP_ID [0:3]
///Endpoint Identifier
ep_id: u4 = 0,
///DIR [4:4]
///Direction of transaction
dir: packed enum(u1) {
///data transmitted by the USB peripheral to the host PC
to = 0,
///data received by the USB peripheral from the host PC
from = 1,
} = .to,
_unused5: u2 = 0,
///L1REQ [7:7]
///LPM L1 state request
l1req: packed enum(u1) {
///LPM command to enter the L1 state is successfully received and acknowledged
received = 1,
_zero = 0,
} = ._zero,
///ESOF [8:8]
///Expected start frame
esof: packed enum(u1) {
///an SOF packet is expected but not received
expected_start_of_frame = 1,
_zero = 0,
} = ._zero,
///SOF [9:9]
///start of frame
sof: packed enum(u1) {
///beginning of a new USB frame and it is set when a SOF packet arrives through the USB bus
start_of_frame = 1,
_zero = 0,
} = ._zero,
///RESET [10:10]
///reset request
reset: packed enum(u1) {
///peripheral detects an active USB RESET signal at its inputs
reset = 1,
_zero = 0,
} = ._zero,
///SUSP [11:11]
///Suspend mode request
susp: packed enum(u1) {
///no traffic has been received for 3 ms, indicating a suspend mode request from the USB bus
_suspend = 1,
_zero = 0,
} = ._zero,
///WKUP [12:12]
///Wakeup
wkup: packed enum(u1) {
///activity is detected that wakes up the USB peripheral
wakeup = 1,
_zero = 0,
} = ._zero,
///ERR [13:13]
///Error
err: packed enum(u1) {
///One of No ANSwer, Cyclic Redundancy Check, Bit Stuffing or Framing format Violation error occurred
_error = 1,
_zero = 0,
} = ._zero,
///PMAOVR [14:14]
///Packet memory area over /
///underrun
pmaovr: packed enum(u1) {
///microcontroller has not been able to respond in time to an USB memory request
overrun = 1,
_zero = 0,
} = ._zero,
///CTR [15:15]
///Correct transfer
ctr: packed enum(u1) {
///endpoint has successfully completed a transaction
completed = 1,
_zero = 0,
} = ._zero,
_unused16: u16 = 0,
};
///interrupt status register
pub const istr = Register(istr_val).init(0x40005C00 + 0x44);
//////////////////////////
///FNR
const fnr_val = packed struct {
///FN [0:10]
///Frame number
_fn: u11 = 0,
///LSOF [11:12]
///Lost SOF
lsof: u2 = 0,
///LCK [13:13]
///Locked
lck: packed enum(u1) {
///the frame timer remains in this state until an USB reset or USB suspend event occurs
locked = 1,
_zero = 0,
} = ._zero,
///RXDM [14:14]
///Receive data - line status
rxdm: packed enum(u1) {
///received data minus upstream port data line
received = 1,
_zero = 0,
} = ._zero,
///RXDP [15:15]
///Receive data + line status
rxdp: packed enum(u1) {
///received data plus upstream port data line
received = 1,
_zero = 0,
} = ._zero,
_unused16: u16 = 0,
};
///frame number register
pub const fnr = RegisterRW(fnr_val, void).init(0x40005C00 + 0x48);
//////////////////////////
///DADDR
const daddr_val = packed struct {
///ADD [0:6]
///Device address
add: u7 = 0,
///EF [7:7]
///Enable function
ef: packed enum(u1) {
///USB device disabled
disabled = 0,
///USB device enabled
enabled = 1,
} = .disabled,
_unused8: u24 = 0,
};
///device address
pub const daddr = Register(daddr_val).init(0x40005C00 + 0x4C);
//////////////////////////
///BTABLE
const btable_val = packed struct {
_unused0: u3 = 0,
///BTABLE [3:15]
///Buffer table
btable: u13 = 0,
_unused16: u16 = 0,
};
///Buffer table address
pub const btable = Register(btable_val).init(0x40005C00 + 0x50);
//////////////////////////
///LPMCSR
const lpmcsr_val = packed struct {
///LPMEN [0:0]
///LPM support enable
lpmen: packed enum(u1) {
///enable the LPM support within the USB device
disabled = 0,
///no LPM transactions are handled
enabled = 1,
} = .disabled,
///LPMACK [1:1]
///LPM Token acknowledge
///enable
lpmack: packed enum(u1) {
///the valid LPM Token will be NYET
nyet = 0,
///the valid LPM Token will be ACK
ack = 1,
} = .nyet,
_unused2: u1 = 0,
///REMWAKE [3:3]
///bRemoteWake value
remwake: u1 = 0,
///BESL [4:7]
///BESL value
besl: u4 = 0,
_unused8: u24 = 0,
};
///LPM control and status
///register
pub const lpmcsr = Register(lpmcsr_val).init(0x40005C00 + 0x54);
//////////////////////////
///BCDR
const bcdr_val = packed struct {
///BCDEN [0:0]
///Battery charging detector (BCD)
///enable
bcden: packed enum(u1) {
///disable the BCD support
disabled = 0,
///enable the BCD support within the USB device
enabled = 1,
} = .disabled,
///DCDEN [1:1]
///Data contact detection (DCD) mode
///enable
dcden: packed enum(u1) {
///Data contact detection (DCD) mode disabled
disabled = 0,
///Data contact detection (DCD) mode enabled
enabled = 1,
} = .disabled,
///PDEN [2:2]
///Primary detection (PD) mode
///enable
pden: packed enum(u1) {
///Primary detection (PD) mode disabled
disabled = 0,
///Primary detection (PD) mode enabled
enabled = 1,
} = .disabled,
///SDEN [3:3]
///Secondary detection (SD) mode
///enable
sden: packed enum(u1) {
///Secondary detection (SD) mode disabled
disabled = 0,
///Secondary detection (SD) mode enabled
enabled = 1,
} = .disabled,
///DCDET [4:4]
///Data contact detection (DCD)
///status
dcdet: packed enum(u1) {
///data lines contact not detected
not_detected = 0,
///data lines contact detected
detected = 1,
} = .not_detected,
///PDET [5:5]
///Primary detection (PD)
///status
pdet: packed enum(u1) {
///no BCD support detected
no_bcd = 0,
///BCD support detected
bcd = 1,
} = .no_bcd,
///SDET [6:6]
///Secondary detection (SD)
///status
sdet: packed enum(u1) {
///CDP detected
cdp = 0,
///DCP detected
dcp = 1,
} = .cdp,
///PS2DET [7:7]
///DM pull-up detection
///status
ps2det: packed enum(u1) {
///Normal port detected
normal = 0,
///PS2 port or proprietary charger detected
ps2 = 1,
} = .normal,
_unused8: u7 = 0,
///DPPU [15:15]
///DP pull-up control
dppu: packed enum(u1) {
///signalize disconnect to the host when needed by the user software
disabled = 0,
///enable the embedded pull-up on the DP line
enabled = 1,
} = .disabled,
_unused16: u16 = 0,
};
///Battery charging detector
pub const bcdr = Register(bcdr_val).init(0x40005C00 + 0x58);
};
///System control block
pub const scb = struct {
//////////////////////////
///CPUID
const cpuid_val = packed struct {
///Revision [0:3]
///Revision number
revision: u4 = 1,
///PartNo [4:15]
///Part number of the
///processor
part_no: u12 = 3108,
///Constant [16:19]
///Reads as 0xF
constant: u4 = 15,
///Variant [20:23]
///Variant number
variant: u4 = 0,
///Implementer [24:31]
///Implementer code
implementer: u8 = 65,
};
///CPUID base register
pub const cpuid = RegisterRW(cpuid_val, void).init(0xE000ED00 + 0x0);
//////////////////////////
///ICSR
const icsr_val = packed struct {
///VECTACTIVE [0:5]
///Active vector
vectactive: u6 = 0,
_unused6: u6 = 0,
///VECTPENDING [12:17]
///Pending vector
vectpending: u6 = 0,
_unused18: u4 = 0,
///ISRPENDING [22:22]
///Interrupt pending flag
isrpending: u1 = 0,
_unused23: u2 = 0,
///PENDSTCLR [25:25]
///SysTick exception clear-pending
///bit
pendstclr: u1 = 0,
///PENDSTSET [26:26]
///SysTick exception set-pending
///bit
pendstset: u1 = 0,
///PENDSVCLR [27:27]
///PendSV clear-pending bit
pendsvclr: u1 = 0,
///PENDSVSET [28:28]
///PendSV set-pending bit
pendsvset: u1 = 0,
_unused29: u2 = 0,
///NMIPENDSET [31:31]
///NMI set-pending bit.
nmipendset: u1 = 0,
};
///Interrupt control and state
///register
pub const icsr = Register(icsr_val).init(0xE000ED00 + 0x4);
//////////////////////////
///AIRCR
const aircr_val = packed struct {
_unused0: u1 = 0,
///VECTCLRACTIVE [1:1]
///VECTCLRACTIVE
vectclractive: u1 = 0,
///SYSRESETREQ [2:2]
///SYSRESETREQ
sysresetreq: u1 = 0,
_unused3: u12 = 0,
///ENDIANESS [15:15]
///ENDIANESS
endianess: u1 = 0,
///VECTKEYSTAT [16:31]
///Register key
vectkeystat: u16 = 0,
};
///Application interrupt and reset control
///register
pub const aircr = Register(aircr_val).init(0xE000ED00 + 0xC);
//////////////////////////
///SCR
const scr_val = packed struct {
_unused0: u1 = 0,
///SLEEPONEXIT [1:1]
///SLEEPONEXIT
sleeponexit: u1 = 0,
///SLEEPDEEP [2:2]
///SLEEPDEEP
sleepdeep: u1 = 0,
_unused3: u1 = 0,
///SEVEONPEND [4:4]
///Send Event on Pending bit
seveonpend: u1 = 0,
_unused5: u27 = 0,
};
///System control register
pub const scr = Register(scr_val).init(0xE000ED00 + 0x10);
//////////////////////////
///CCR
const ccr_val = packed struct {
_unused0: u3 = 0,
///UNALIGN__TRP [3:3]
///UNALIGN_ TRP
unalign__trp: u1 = 0,
_unused4: u5 = 0,
///STKALIGN [9:9]
///STKALIGN
stkalign: u1 = 0,
_unused10: u22 = 0,
};
///Configuration and control
///register
pub const ccr = Register(ccr_val).init(0xE000ED00 + 0x14);
//////////////////////////
///SHPR2
const shpr2_val = packed struct {
_unused0: u24 = 0,
///PRI_11 [24:31]
///Priority of system handler
///11
pri_11: u8 = 0,
};
///System handler priority
///registers
pub const shpr2 = Register(shpr2_val).init(0xE000ED00 + 0x1C);
//////////////////////////
///SHPR3
const shpr3_val = packed struct {
_unused0: u16 = 0,
///PRI_14 [16:23]
///Priority of system handler
///14
pri_14: u8 = 0,
///PRI_15 [24:31]
///Priority of system handler
///15
pri_15: u8 = 0,
};
///System handler priority
///registers
pub const shpr3 = Register(shpr3_val).init(0xE000ED00 + 0x20);
};
///SysTick timer
pub const stk = struct {
//////////////////////////
///CSR
const csr_val = packed struct {
///ENABLE [0:0]
///Counter enable
enable: u1 = 0,
///TICKINT [1:1]
///SysTick exception request
///enable
tickint: u1 = 0,
///CLKSOURCE [2:2]
///Clock source selection
clksource: u1 = 0,
_unused3: u13 = 0,
///COUNTFLAG [16:16]
///COUNTFLAG
countflag: u1 = 0,
_unused17: u15 = 0,
};
///SysTick control and status
///register
pub const csr = Register(csr_val).init(0xE000E010 + 0x0);
//////////////////////////
///RVR
const rvr_val = packed struct {
///RELOAD [0:23]
///RELOAD value
reload: u24 = 0,
_unused24: u8 = 0,
};
///SysTick reload value register
pub const rvr = Register(rvr_val).init(0xE000E010 + 0x4);
//////////////////////////
///CVR
const cvr_val = packed struct {
///CURRENT [0:23]
///Current counter value
current: u24 = 0,
_unused24: u8 = 0,
};
///SysTick current value register
pub const cvr = Register(cvr_val).init(0xE000E010 + 0x8);
//////////////////////////
///CALIB
const calib_val = packed struct {
///TENMS [0:23]
///Calibration value
tenms: u24 = 0,
_unused24: u6 = 0,
///SKEW [30:30]
///SKEW flag: Indicates whether the TENMS
///value is exact
skew: u1 = 0,
///NOREF [31:31]
///NOREF flag. Reads as zero
noref: u1 = 0,
};
///SysTick calibration value
///register
pub const calib = Register(calib_val).init(0xE000E010 + 0xC);
}; | target/stm32f0x0.zig |
const std = @import("std");
/// Creates a new parser core that provides the core functions for a recursive descent
/// parser.
/// `TokenizerT` is the type of the tokenizer to use.
/// `ignore_list` is a array of token types that will be ignored by this parser core.
/// This is useful to filter out comments and non-significant whitespace.
pub fn ParserCore(comptime TokenizerT: type, comptime ignore_list: anytype) type {
const ignore_array: [ignore_list.len]TokenizerT.TokenType = ignore_list;
return struct {
const Self = @This();
const Tokenizer = TokenizerT;
const TokenType = Tokenizer.TokenType;
const Token = Tokenizer.Token;
pub const Rule = fn (TokenType) bool;
pub const State = Tokenizer.State;
pub const Error = AcceptError || Tokenizer.Error;
tokenizer: *Tokenizer,
/// Create a new parser core based on the tokenizer given.
/// The core will only reference the Tokenizer and will modify
/// it's state.
pub fn init(tokenizer: *Tokenizer) Self {
return Self{
.tokenizer = tokenizer,
};
}
/// Yields the next unfiltered token
fn nextToken(self: *Self) !?Token {
while (try self.tokenizer.next()) |tok| {
if (std.mem.indexOfScalar(TokenType, &ignore_array, tok.type) == null)
return tok;
}
return null;
}
/// Saves the state of the parser. Can be later restored with `restoreState`.
pub fn saveState(self: Self) State {
return self.tokenizer.saveState();
}
/// Restores a previously saved state. This will rewind any parsing done
/// since the
pub fn restoreState(self: *Self, state: State) void {
self.tokenizer.restoreState(state);
}
pub const AcceptError = error{ EndOfStream, UnexpectedToken } || Tokenizer.NextError;
/// Accepts a token that matches `rule`. Otherwise returns
/// - `error.EndOfStream` when no tokens are available
/// - `error.UnexpectedToken` when an invalid token was encountered
pub fn accept(self: *Self, comptime rule: Rule) AcceptError!Token {
const state = self.saveState();
errdefer self.restoreState(state);
const token = (try self.nextToken()) orelse return error.EndOfStream;
if (rule(token.type))
return token;
return error.UnexpectedToken;
}
/// Returns the next token if any, but doesn't modify the state of the parser.
pub fn peek(self: *Self) Tokenizer.NextError!?Token {
const state = self.saveState();
defer self.restoreState(state);
return try self.nextToken();
}
};
}
/// Provides generic rules to match tokens.
pub fn RuleSet(comptime TokenType: type) type {
return struct {
const Rule = fn (TokenType) bool;
/// Returns a rule that matches one of the given token types.
/// Usage: `expect(oneOf(.{ .foo, .bar }))`
pub fn oneOf(types: anytype) Rule {
const types_array: [types.len]TokenType = types;
return struct {
fn f(t: TokenType) bool {
return (std.mem.indexOfScalar(TokenType, &types_array, t) != null);
}
}.f;
}
/// Returns a rule that matches the `expected` token type and nothing else.
pub fn is(comptime expected: TokenType) Rule {
return struct {
fn f(t: TokenType) bool {
return (t == expected);
}
}.f;
}
/// A rule that matches *any* token.
pub fn any(_: TokenType) bool {
return true;
}
};
} | src/parser_core.zig |
const math = @import("std").math;
usingnamespace @import("MathUtil.zig");
const Quat = @import("Quat.zig").Quat;
pub const zero = Vec3{};
pub const one = Vec3{ .x = 1.0, .y = 1.0, .z = 1.0 };
pub const xAxis = Vec3{ .x = 1.0, .y = 0.0, .z = 0.0 };
pub const yAxis = Vec3{ .x = 0.0, .y = 1.0, .z = 0.0 };
pub const zAxis = Vec3{ .x = 0.0, .y = 0.0, .z = 1.0 };
pub const Vec3 = packed struct {
x: f32 = 0.0,
y: f32 = 0.0,
z: f32 = 0.0,
pub fn Scale(self: *Vec3, scalar: f32) void {
self.x *= scalar;
self.y *= scalar;
self.z *= scalar;
}
pub fn GetScaled(self: *const Vec3, scalar: f32) Vec3 {
return Vec3{
.x = self.x * scalar,
.y = self.y * scalar,
.z = self.z * scalar,
};
}
pub fn Add(self: *const Vec3, rhs: Vec3) Vec3 {
return Vec3{
.x = self.x + rhs.x,
.y = self.y + rhs.y,
.z = self.z + rhs.z,
};
}
pub fn Sub(self: *const Vec3, rhs: Vec3) Vec3 {
return Vec3{
.x = self.x - rhs.x,
.y = self.y - rhs.y,
.z = self.z - rhs.z,
};
}
pub fn Dot(self: *const Vec3, rhs: Vec3) Vec3 {
return Vec3{
.x = self.x * rhs.x,
.y = self.y * rhs.y,
.z = self.z * rhs.z,
};
}
pub fn Cross(self: *const Vec3, rhs: Vec3) Vec3 {
return Vec3{
.x = self.y * rhs.z - self.z * rhs.y,
.y = self.z * rhs.x - self.x * rhs.z,
.z = self.x * rhs.y - self.y * rhs.x,
};
}
// equals with a default tolerance of f32_epsilon
pub fn Equals(self: *const Vec3, rhs: Vec3) bool {
return self.EqualsT(rhs, math.f32_epsilon);
}
pub fn EqualsT(self: *const Vec3, rhs: Vec3, tolerance: f32) bool {
return EqualWithinTolerance(f32, self.x, rhs.x, tolerance) and
EqualWithinTolerance(f32, self.y, rhs.y, tolerance) and
EqualWithinTolerance(f32, self.z, rhs.z, tolerance);
}
pub fn LengthSqrd(self: *const Vec3) f32 {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
pub fn Length(self: *const Vec3) f32 {
return math.sqrt(self.LengthSqrd());
}
pub fn DistSqrd(self: *const Vec3, rhs: Vec3) f32 {
return self.Sub(rhs).LengthSqrd();
}
pub fn Dist(self: *const Vec3, rhs: Vec3) f32 {
return self.Sub(rhs).Length();
}
//TODO panics in debug build only maybe?
pub fn ClampToMinSize(self: *Vec3, size: f32) void {
const lengthSqrd = self.LengthSqrd();
const sizeSqrd = size * size;
if (lengthSqrd < sizeSqrd) {
if (lengthSqrd == 0.0) @panic("Clamping vector with length 0");
const inv = size / math.sqrt(lengthSqrd);
self.x *= inv;
self.y *= inv;
self.z *= inv;
}
}
pub fn ClampToMaxSize(self: *Vec3, size: f32) void {
const lengthSqrd = self.LengthSqrd();
const sizeSqrd = size * size;
if (lengthSqrd > sizeSqrd) {
if (lengthSqrd == 0.0) @panic("Clamping vector with length 0");
const inv = size / math.sqrt(lengthSqrd);
self.x *= inv;
self.y *= inv;
self.z *= inv;
}
}
pub fn GetClampedToMinSize(self: *const Vec3, size: f32) Vec3 {
const lengthSqrd = self.LengthSqrd();
const sizeSqrd = size * size;
if (lengthSqrd < sizeSqrd) {
if (lengthSqrd == 0.0) @panic("Clamping vector with length 0");
const inv = size / math.sqrt(lengthSqrd);
return Vec3{
.x = self.x * inv,
.y = self.y * inv,
.z = self.z * inv,
};
}
}
pub fn GetClampedToMaxSize(self: *const Vec3, size: f32) Vec3 {
const lengthSqrd = self.LengthSqrd();
const sizeSqrd = size * size;
if (lengthSqrd > sizeSqrd) {
if (lengthSqrd == 0.0) @panic("Clamping vector with length 0");
const inv = size / math.sqrt(lengthSqrd);
return Vec3{
.x = self.x * inv,
.y = self.y * inv,
.z = self.z * inv,
};
}
}
pub fn ScaleToSize(self: *Vec3, size: f32) void {
const length = self.Length();
if (length == 0.0) @panic("Trying to scale up a vector with length 0");
const scaleAmount = size / length;
self.Scale(scaleAmount);
}
pub fn GetScaledToSize(self: *Vec3, size: f32) Vec3 {
const length = self.Length();
if (length == 0.0) @panic("Trying to scale up a vector with length 0");
const scaleAmount = size / length;
return self.GetScaled(scaleAmount);
}
pub fn Normalized(self: *const Vec3) Vec3 {
const length = self.Length();
if (length == 0.0) @panic("Normalizing vector with length 0");
return Vec3{
.x = self.x / length,
.y = self.y / length,
.z = self.z / length,
};
}
pub fn NormalizeSelf(self: *Vec3) void {
const length = self.Length();
if (length == 0.0) @panic("Normalizing vector with length 0");
self.x /= length;
self.y /= length;
self.z /= length;
}
pub fn RotatedByQuat(self: *const Vec3, q: Quat) Vec3 {
const qxyz = Vec3{ .x = q.x, .y = q.y, .z = q.z };
const t = qxyz.Cross(self.*).GetScaled(2.0);
return self.Add(t.GetScaled(q.w)).Add(qxyz.Cross(t));
}
pub fn RotateByQuat(self: *Vec3, q: Quat) void {
const qxyz = Vec3{ .x = q.x, .y = q.y, .z = q.z };
const t = qxyz.Cross(self.*).GetScaled(2.0);
self = self.Add(t.GetScaled(q.w).Add(qxyz.Cross(t)));
}
};
pub fn Vec3_xy0(v2: *const Vec2) Vec3 {
return Vec3{ v2.x, v2.y, 0.0 };
}
pub fn Vec3_x0y(v2: *const Vec2) Vec3 {
return Vec3{ v2.x, 0.0, v2.y };
}
pub fn Vec3_0xy(v2: *const Vec2) Vec3 {
return Vec3{ 0.0, v2.x, v2.y };
}
//TODO testing
test "eden.math.Vec3" {
const debug = @import("std").debug;
const assert = debug.assert;
{
const v1 = Vec3{ .x = 1.0, .y = 2.0, .z = 3.0 };
const v2 = Vec3{ .x = 3.0, .y = 2.0, .z = 3.0 };
const v3 = v1.Add(v2);
assert(v3.x == 4.0 and v3.y == 4.0 and v3.z == 4.0);
}
} | src/math/Vec3.zig |
usingnamespace @import("../c.zig");
const std = @import("std");
const Vec3 = @import("../math/Vec3.zig").Vec3;
const Vec2 = @import("../math/Vec2.zig").Vec2;
const mat4x4 = @import("../math/Mat4x4.zig");
const Mat4x4 = mat4x4.Mat4x4;
const Camera = @import("Camera.zig").Camera;
const ArrayList = std.ArrayList;
const noPointerOffset: ?*const c_void = @intToPtr(?*c_void, 0);
pub const Mesh = struct {
m_name: []const u8,
m_vertices: ArrayList(Vec3),
m_normals: ArrayList(Vec3),
m_texCoords: ArrayList(Vec2), //currently only one coord channel
m_indices: ArrayList(u32),
m_vertexBO: GLuint,
m_normalBO: GLuint,
m_texCoordBO: GLuint,
m_indexBO: GLuint,
//TODO testing; handle different shaders and different attrib layouts
pub fn Draw(self: *const Mesh, camera: *const Camera, shader: GLuint) void {
glUseProgram(shader);
var vao: GLuint = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, self.m_vertexBO);
//glBindBuffer(GL_ARRAY_BUFFER, self.m_normalBO);
//glBindBuffer(GL_ARRAY_BUFFER, self.m_texCoordBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.m_indexBO);
glEnableVertexAttribArray(0);
//glEnableVertexAttribArray(1);
//glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, noPointerOffset);
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, noPointerOffset);
//glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, noPointerOffset);
//TODO fix model
const model = mat4x4.identity;
const projection = camera.GetProjectionMatrix();
const view = camera.GetViewMatrix();
const mLocation: GLint = glGetUniformLocation(shader, "model");
if (mLocation == -1) {
std.debug.warn("failed to find camera matrix uniform location in shader\n", .{});
} else {
glUniformMatrix4fv(mLocation, 1, GL_FALSE, &model.m[0][0]);
}
const pLocation: GLint = glGetUniformLocation(shader, "projection");
if (pLocation == -1) {
std.debug.warn("failed to find camera matrix uniform location in shader\n", .{});
} else {
glUniformMatrix4fv(pLocation, 1, GL_FALSE, &projection.m[0][0]);
}
const vLocation: GLint = glGetUniformLocation(shader, "view");
if (vLocation == -1) {
std.debug.warn("failed to find camera matrix uniform location in shader\n", .{});
} else {
glUniformMatrix4fv(vLocation, 1, GL_FALSE, &view.m[0][0]);
}
glDrawElements(GL_TRIANGLES, @intCast(c_int, self.m_indices.items.len), GL_UNSIGNED_INT, noPointerOffset);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
//glDisableVertexAttribArray(1);
//glDisableVertexAttribArray(2);
}
pub fn PushDataToBuffers(self: *Mesh) void {
//TODO clear any existing data
self.m_vertexBO = try self.LoadMeshIntoVertexBO();
self.m_normalBO = try self.LoadMeshIntoNormalBO();
self.m_texCoordBO = try self.LoadMeshIntoTexCoordBO();
self.m_indexBO = try self.LoadMeshIntoIndexBO();
}
fn LoadMeshIntoVertexBO(mesh: *const Mesh) !GLuint {
var vertexBuffer: GLuint = 0;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, @intCast(c_longlong, mesh.m_vertices.items.len * @sizeOf(Vec3)), &mesh.m_vertices.items[0], GL_STATIC_DRAW);
return vertexBuffer;
}
fn LoadMeshIntoNormalBO(mesh: *const Mesh) !GLuint {
var normalBuffer: GLuint = 0;
glGenBuffers(1, &normalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
glBufferData(GL_ARRAY_BUFFER, @intCast(c_longlong, mesh.m_normals.items.len * @sizeOf(Vec3)), &mesh.m_normals.items[0], GL_STATIC_DRAW);
return normalBuffer;
}
fn LoadMeshIntoTexCoordBO(mesh: *const Mesh) !GLuint {
var texCoordBuffer: GLuint = 0;
glGenBuffers(1, &texCoordBuffer);
glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer);
glBufferData(GL_ARRAY_BUFFER, @intCast(c_longlong, mesh.m_texCoords.items.len * @sizeOf(Vec2)), &mesh.m_texCoords.items[0], GL_STATIC_DRAW);
return texCoordBuffer;
}
fn LoadMeshIntoIndexBO(mesh: *const Mesh) !GLuint {
var indexBuffer: GLuint = 0;
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, @intCast(c_longlong, mesh.m_indices.items.len * @sizeOf(u32)), &mesh.m_indices.items[0], GL_STATIC_DRAW);
return indexBuffer;
}
};
// how should actual instances come together between mesh, texture maps, shader, and instanced shader parameters?
pub const MeshInstance = struct {
m_meshID: u32,
m_transformID: u32,
}; | src/presentation/Mesh.zig |
const std = @import("std");
const builtin = @import("builtin");
pub fn build(b: *std.build.Builder) void {
const default_abi = if (builtin.os.tag == .windows) .gnu else null; // doesn't require vcruntime
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{
.default_target = .{
.abi = default_abi,
},
});
const example_assets_install = b.addInstallDirectory(.{
.source_dir = "examples/assets",
.install_dir = .bin,
.install_subdir = "assets",
});
const examples = [_][]const u8{
"simple_window",
"single_triangle",
"cubes",
"phong_lighting",
"imgui_demo",
"imgui_fontawesome",
"imgui_ttf",
"vector_graphics",
"vg_benchmark",
"mesh_generation",
"gltf_demo",
"environment_mapping",
"bullet_test",
};
const build_examples = b.step("build_examples", "compile and install all examples");
inline for (examples) |name| {
const exe = b.addExecutable(
name,
"examples" ++ std.fs.path.sep_str ++ name ++ ".zig",
);
exe.setBuildMode(mode);
exe.setTarget(target);
link(b, exe, target);
const install_cmd = b.addInstallArtifact(exe);
const run_cmd = exe.run();
run_cmd.step.dependOn(&install_cmd.step);
run_cmd.step.dependOn(&example_assets_install.step);
run_cmd.cwd = "zig-out" ++ std.fs.path.sep_str ++ "bin";
const run_step = b.step(
name,
"run example " ++ name,
);
run_step.dependOn(&run_cmd.step);
build_examples.dependOn(&install_cmd.step);
}
}
/// link zplay framework to executable
pub fn link(
b: *std.build.Builder,
exe: *std.build.LibExeObjStep,
target: std.zig.CrossTarget,
) void {
const root_path = comptime rootPath();
// link dependencies
const deps = .{
@import("build/sdl.zig"),
@import("build/opengl.zig"),
@import("build/stb.zig"),
@import("build/imgui.zig"),
@import("build/gltf.zig"),
@import("build/nanovg.zig"),
@import("build/nanosvg.zig"),
@import("build/bullet.zig"),
};
inline for (deps) |d| {
d.link(b, exe, target, root_path);
}
// use zplay
const sdl = @import("./src/deps/sdl/Sdk.zig").init(b);
exe.addPackage(.{
.name = "zplay",
.path = .{ .path = root_path ++ "/src/zplay.zig" },
.dependencies = &[_]std.build.Pkg{
sdl.getWrapperPackage("sdl"),
},
});
}
/// root path
fn rootPath() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
} | build.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const lualib = @cImport({
@cInclude("lua.h");
@cInclude("lauxlib.h");
@cInclude("lualib.h");
});
pub const Lua = struct {
const LuaUserData = struct {
allocator: std.mem.Allocator,
registeredTypes: std.StringArrayHashMap([]const u8) = undefined,
fn init(_allocator: std.mem.Allocator) LuaUserData {
return LuaUserData {
.allocator = _allocator,
.registeredTypes = std.StringArrayHashMap([]const u8).init(_allocator)
};
}
fn destroy(self: *LuaUserData) void {
self.registeredTypes.clearAndFree();
}
};
L: *lualib.lua_State,
ud: *LuaUserData,
pub fn init(allocator: std.mem.Allocator) !Lua {
var _ud = try allocator.create(LuaUserData);
_ud.* = LuaUserData.init(allocator);
var _state = lualib.lua_newstate(alloc, _ud) orelse return error.OutOfMemory;
var state = Lua{
.L = _state,
.ud = _ud,
};
return state;
}
pub fn destroy(self: *Lua) void {
_ = lualib.lua_close(self.L);
self.ud.destroy();
var allocator = self.ud.allocator;
allocator.destroy(self.ud);
}
pub fn openLibs(self: *Lua) void {
_ = lualib.luaL_openlibs(self.L);
}
pub fn injectPrettyPrint(self: *Lua) void {
const cmd =
\\-- Print contents of `tbl`, with indentation.
\\-- `indent` sets the initial level of indentation.
\\function pretty_print (tbl, indent)
\\ if not indent then indent = 0 end
\\ for k, v in pairs(tbl) do
\\ formatting = string.rep(" ", indent) .. k .. ": "
\\ if type(v) == "table" then
\\ print(formatting)
\\ pretty_print(v, indent+1)
\\ elseif type(v) == 'boolean' then
\\ print(formatting .. tostring(v))
\\ else
\\ print(formatting .. v)
\\ end
\\ end
\\end
;
self.run(cmd);
}
pub fn run(self: *Lua, script: []const u8) void {
_ = lualib.luaL_loadstring(self.L, @ptrCast([*c]const u8, script));
_ = lualib.lua_pcallk(self.L, 0, 0, 0, 0, null);
}
pub fn set(self: *Lua, name: []const u8, value: anytype) void {
_ = push(self.L, value);
_ = lualib.lua_setglobal(self.L, @ptrCast([*c]const u8, name));
}
pub fn get(self: *Lua, comptime T: type, name: []const u8) !T {
const typ = lualib.lua_getglobal(self.L, @ptrCast([*c]const u8, name));
if (typ != lualib.LUA_TNIL) {
return try pop(T, self.L);
} else {
return error.novalue;
}
}
pub fn getResource(self: *Lua, comptime T: type, name: []const u8) !T {
const typ = lualib.lua_getglobal(self.L, @ptrCast([*c]const u8, name));
if (typ != lualib.LUA_TNIL) {
return try popResource(T, self.L);
} else {
return error.novalue;
}
}
pub fn createTable(self: *Lua) !Lua.Table {
_ = lualib.lua_createtable(self.L, 0, 0);
return try popResource(Lua.Table, self.L);
}
pub fn createUserType(self: *Lua, comptime T: type, params: anytype) !Ref(T) {
var metaTableName: []const u8 = undefined;
// Allocate memory
var ptr = @ptrCast(*T, @alignCast(@alignOf(T), lualib.lua_newuserdata(self.L, @sizeOf(T))));
// set its metatable
if (getUserData(self.L).registeredTypes.get(@typeName(T))) |name| {
metaTableName = name;
} else {
return error.unregistered_type;
}
_ = lualib.luaL_getmetatable(self.L, @ptrCast([*c]const u8, metaTableName[0..]));
_ = lualib.lua_setmetatable(self.L, -2);
// (3) init & copy wrapped object
// Call init
const ArgTypes = std.meta.ArgsTuple(@TypeOf(T.init));
var args: ArgTypes = undefined;
const fields_info = std.meta.fields(@TypeOf(params));
const len = args.len;
comptime var idx = 0;
inline while (idx < len) : (idx += 1) {
args[idx] = @field(params, fields_info[idx].name);
}
ptr.* = @call(.{}, T.init, args);
// (4) check and store the callback table
//_ = lua.luaL_checktype(L, 1, lua.LUA_TTABLE);
_ = lualib.lua_pushvalue(self.L, 1);
_ = lualib.lua_setuservalue(self.L, -2);
var res = try popResource(Ref(T), self.L);
res.ptr = ptr;
return res;
}
pub fn release(self: *Lua, v: anytype) void {
_ = allocateDeallocateHelper(@TypeOf(v), true, self.ud.allocator, v);
}
pub fn newUserType(self: *Lua, comptime T: type) !void {
comptime var hasInit: bool = false;
comptime var hasDestroy: bool = false;
comptime var metaTblName: [1024]u8 = undefined;
_ = comptime try std.fmt.bufPrint(metaTblName[0..], "{s}", .{@typeName(T)});
// Init Lua states
comptime var allocFuns = struct {
fn new(L: ?*lualib.lua_State) callconv(.C) c_int {
// (1) get arguments
var caller = ZigCallHelper(@TypeOf(T.init)).LowLevelHelpers.init();
caller.prepareArgs(L) catch unreachable;
// (2) create Lua object
var ptr = @ptrCast(*T, @alignCast(@alignOf(T), lualib.lua_newuserdata(L, @sizeOf(T))));
// set its metatable
_ = lualib.luaL_getmetatable(L, @ptrCast([*c]const u8, metaTblName[0..]));
_ = lualib.lua_setmetatable(L, -2);
// (3) init & copy wrapped object
caller.call(T.init) catch unreachable;
ptr.* = caller.result;
// (4) check and store the callback table
//_ = lua.luaL_checktype(L, 1, lua.LUA_TTABLE);
_ = lualib.lua_pushvalue(L, 1);
_ = lualib.lua_setuservalue(L, -2);
return 1;
}
fn gc(L: ?*lualib.lua_State) callconv(.C) c_int {
var ptr = @ptrCast(*T, @alignCast(@alignOf(T), lualib.luaL_checkudata(L, 1, @ptrCast([*c]const u8, metaTblName[0..]))));
ptr.destroy();
return 0;
}
};
// Create metatable
_ = lualib.luaL_newmetatable(self.L, @ptrCast([*c]const u8, metaTblName[0..]));
// Metatable.__index = metatable
lualib.lua_pushvalue(self.L, -1);
lualib.lua_setfield(self.L, -2, "__index");
//lua.luaL_setfuncs(self.L, &methods, 0); =>
lualib.lua_pushcclosure(self.L, allocFuns.gc, 0);
lualib.lua_setfield(self.L, -2, "__gc");
// Collect information
switch (@typeInfo(T)) {
.Struct => |StructInfo| {
inline for (StructInfo.decls) |decl| {
switch (decl.data) {
.Fn => |_| {
if (comptime std.mem.eql(u8, decl.name, "init") == true) {
hasInit = true;
} else if (comptime std.mem.eql(u8, decl.name, "destroy") == true) {
hasDestroy = true;
} else if (decl.is_pub) {
comptime var field = @field(T, decl.name);
const Caller = ZigCallHelper(@TypeOf(field));
Caller.pushFunctor(self.L, field) catch unreachable;
lualib.lua_setfield(self.L, -2, @ptrCast([*c]const u8, decl.name));
}
},
else => {},
}
}
},
else => @compileError("Only Struct supported."),
}
if ((hasInit == false) or (hasDestroy == false)) {
@compileError("Struct has to have init and destroy methods.");
}
// Only the 'new' function
// <==_ = lua.luaL_newlib(lua.L, &arraylib_f); ==>
lualib.luaL_checkversion(self.L);
lualib.lua_createtable(self.L, 0, 1);
// lua.luaL_setfuncs(self.L, &funcs, 0); =>
lualib.lua_pushcclosure(self.L, allocFuns.new, 0);
lualib.lua_setfield(self.L, -2, "new");
// Set as global ('require' requires luaopen_{libraname} named static C functionsa and we don't want to provide one)
_ = lualib.lua_setglobal(self.L, @ptrCast([*c]const u8, metaTblName[0..]));
// Store in the registry
try getUserData(self.L).registeredTypes.put(@typeName(T), metaTblName[0..]);
}
pub fn Function(comptime T: type) type {
const FuncType = T;
const RetType =
switch (@typeInfo(FuncType)) {
.Fn => |FunctionInfo| FunctionInfo.return_type,
else => @compileError("Unsupported type."),
};
return struct {
const Self = @This();
L: *lualib.lua_State,
ref: c_int = undefined,
func: FuncType = undefined,
// This 'Init' assumes, that the top element of the stack is a Lua function
pub fn init(_L: *lualib.lua_State) Self {
const _ref = lualib.luaL_ref(_L, lualib.LUA_REGISTRYINDEX);
var res = Self{
.L = _L,
.ref = _ref,
};
return res;
}
pub fn destroy(self: *const Self) void {
lualib.luaL_unref(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
}
pub fn call(self: *const Self, args: anytype) !RetType.? {
const ArgsType = @TypeOf(args);
if (@typeInfo(ArgsType) != .Struct) {
("Expected tuple or struct argument, found " ++ @typeName(ArgsType));
}
// Getting function reference
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
// Preparing arguments
comptime var i = 0;
const fields_info = std.meta.fields(ArgsType);
inline while (i < fields_info.len) : (i += 1) {
Lua.push(self.L, args[i]);
}
// Calculating retval count
comptime var retValCount = switch (@typeInfo(RetType.?)) {
.Void => 0,
.Struct => |StructInfo| StructInfo.fields.len,
else => 1,
};
// Calling
if (lualib.lua_pcallk(self.L, fields_info.len, retValCount, 0, 0, null) != lualib.LUA_OK) {
return error.lua_runtime_error;
}
// Getting return value(s)
if (retValCount > 0) {
return Lua.pop(RetType.?, self.L);
}
}
};
}
pub const Table = struct {
const Self = @This();
L: *lualib.lua_State,
ref: c_int = undefined,
// This 'Init' assumes, that the top element of the stack is a Lua table
pub fn init(_L: *lualib.lua_State) Self {
const _ref = lualib.luaL_ref(_L, lualib.LUA_REGISTRYINDEX);
var res = Self{
.L = _L,
.ref = _ref,
};
return res;
}
// Unregister this shit
pub fn destroy(self: *const Self) void {
lualib.luaL_unref(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
}
pub fn clone(self: *const Self) Self {
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
return Table.init(self.L, self.allocator);
}
pub fn set(self: *const Self, key: anytype, value: anytype) void {
// Getting table reference
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
// Push key, value
Lua.push(self.L, key);
Lua.push(self.L, value);
// Set
lualib.lua_settable(self.L, -3);
}
pub fn get(self: *const Self, comptime T: type, key: anytype) !T {
// Getting table by reference
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
// Push key
Lua.push(self.L, key);
// Get
_ = lualib.lua_gettable(self.L, -2);
return try Lua.pop(T, self.L);
}
pub fn getResource(self: *const Self, comptime T: type, key: anytype) !T {
// Getting table reference
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
// Push key
Lua.push(self.L, key);
// Get
_ = lualib.lua_gettable(self.L, -2);
return try Lua.popResource(T, self.L);
}
};
pub fn Ref(comptime T: type) type {
return struct {
const Self = @This();
L: *lualib.lua_State,
ref: c_int = undefined,
ptr: *T = undefined,
pub fn init(_L: *lualib.lua_State) Self {
const _ref = lualib.luaL_ref(_L, lualib.LUA_REGISTRYINDEX);
var res = Self{
.L = _L,
.ref = _ref,
};
return res;
}
pub fn destroy(self: *const Self) void {
_ = lualib.luaL_unref(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
}
pub fn clone(self: *const Self) Self {
_ = lualib.lua_rawgeti(self.L, lualib.LUA_REGISTRYINDEX, self.ref);
var result = Self.init(self.L);
result.ptr = self.ptr;
return result;
}
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
fn pushSlice(comptime T: type, L: *lualib.lua_State, values: []const T) void {
lualib.lua_createtable(L, @intCast(c_int, values.len), 0);
for (values) |value, i| {
push(L, i + 1);
push(L, value);
lualib.lua_settable(L, -3);
}
}
fn push(L: *lualib.lua_State, value: anytype) void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Void => lualib.lua_pushnil(L),
.Bool => lualib.lua_pushboolean(L, @boolToInt(value)),
.Int, .ComptimeInt => lualib.lua_pushinteger(L, @intCast(c_longlong, value)),
.Float, .ComptimeFloat => lualib.lua_pushnumber(L, value),
.Array => |info| {
pushSlice(info.child, L, value[0..]);
},
.Pointer => |PointerInfo| switch (PointerInfo.size) {
.Slice => {
if (PointerInfo.child == u8) {
_ = lualib.lua_pushlstring(L, value.ptr, value.len);
} else {
@compileError("invalid type: '" ++ @typeName(T) ++ "'");
}
},
.One => {
switch (@typeInfo(PointerInfo.child)) {
.Array => |childInfo| {
if (childInfo.child == u8) {
_ = lualib.lua_pushstring(L, @ptrCast([*c]const u8, value));
} else {
@compileError("invalid type: '" ++ @typeName(T) ++ "'");
}
},
.Struct => {
unreachable;
},
else => @compileError("BAszomalassan"),
}
},
.Many => {
if (PointerInfo.child == u8) {
_ = lualib.lua_pushstring(L, @ptrCast([*c]const u8, value));
} else {
@compileError("invalid type: '" ++ @typeName(T) ++ "'. Typeinfo: '" ++ @typeInfo(PointerInfo.child) ++ "'");
}
},
.C => {
if (PointerInfo.child == u8) {
_ = lualib.lua_pushstring(L, value);
} else {
@compileError("invalid type: '" ++ @typeName(T) ++ "'");
}
},
},
.Fn => {
const Helper = ZigCallHelper(@TypeOf(value));
Helper.pushFunctor(L, value) catch unreachable;
},
.Struct => |_| {
comptime var funIdx = std.mem.indexOf(u8, @typeName(T), "Function") orelse -1;
comptime var tblIdx = std.mem.indexOf(u8, @typeName(T), "Table") orelse -1;
comptime var refIdx = std.mem.indexOf(u8, @typeName(T), "Ref(") orelse -1;
if (funIdx >= 0 or tblIdx >= 0 or refIdx >= 0) {
_ = lualib.lua_rawgeti(L, lualib.LUA_REGISTRYINDEX, value.ref);
} else @compileError("Only Function ands Lua.Table supported; '" ++ @typeName(T) ++ "' not.");
},
// .Type => {
// },
else => @compileError("Unsupported type: '" ++ @typeName(@TypeOf(value)) ++ "'"),
}
}
fn pop(comptime T: type, L: *lualib.lua_State) !T {
defer lualib.lua_pop(L, 1);
switch (@typeInfo(T)) {
.Bool => {
var res = lualib.lua_toboolean(L, -1);
return if (res > 0) true else false;
},
.Int, .ComptimeInt => {
var isnum: i32 = 0;
var result: T = @intCast(T, lualib.lua_tointegerx(L, -1, isnum));
return result;
},
.Float, .ComptimeFloat => {
var isnum: i32 = 0;
var result: T = @floatCast(T, lualib.lua_tonumberx(L, -1, isnum));
return result;
},
// Only string, allocless get (Lua holds the pointer, it is only a slice pointing to it)
.Pointer => |PointerInfo| switch (PointerInfo.size) {
.Slice => {
// [] const u8 case
if (PointerInfo.child == u8 and PointerInfo.is_const) {
var len: usize = 0;
var ptr = lualib.lua_tolstring(L, -1, @ptrCast([*c]usize, &len));
var result: T = ptr[0..len];
return result;
} else @compileError("Only '[]const u8' (aka string) is supported allocless.");
},
.One => {
var optionalTbl = getUserData(L).registeredTypes.get(@typeName(PointerInfo.child));
if (optionalTbl) |tbl| {
var result = @ptrCast(T, @alignCast(@alignOf(PointerInfo.child), lualib.luaL_checkudata(L, -1, @ptrCast([*c]const u8, tbl[0..]))));
return result;
} else {
return error.invalidType;
}
},
else => @compileError("invalid type: '" ++ @typeName(T) ++ "'"),
},
.Struct => |StructInfo| {
if (StructInfo.is_tuple) {
@compileError("Tuples are not supported.");
}
comptime var funIdx = std.mem.indexOf(u8, @typeName(T), "Function") orelse -1;
comptime var tblIdx = std.mem.indexOf(u8, @typeName(T), "Table") orelse -1;
if (funIdx >= 0 or tblIdx >= 0) {
@compileError("Only allocGet supports Lua.Function and Lua.Table. Your type '" ++ @typeName(T) ++ "' is not supported.");
}
var result: T = .{ 0, 0 };
comptime var i = 0;
const fields_info = std.meta.fields(T);
inline while (i < fields_info.len) : (i += 1) {
result[i] = pop(@TypeOf(result[i]), L);
}
},
else => @compileError("invalid type: '" ++ @typeName(T) ++ "'"),
}
}
fn popResource(comptime T: type, L: *lualib.lua_State) !T {
switch (@typeInfo(T)) {
.Pointer => |PointerInfo| switch (PointerInfo.size) {
.Slice => {
defer lualib.lua_pop(L, 1);
if (lualib.lua_type(L, -1) == lualib.LUA_TTABLE) {
lualib.lua_len(L, -1);
const len = try pop(u64, L);
var res = try getAllocator(L).alloc(PointerInfo.child, @intCast(usize, len));
var i: u32 = 0;
while (i < len) : (i += 1) {
push(L, i + 1);
_ = lualib.lua_gettable(L, -2);
res[i] = try pop(PointerInfo.child, L);
}
return res;
} else {
return error.bad_type;
}
},
else => @compileError("Only Slice is supported."),
},
.Struct => |_| {
comptime var funIdx = std.mem.indexOf(u8, @typeName(T), "Function") orelse -1;
comptime var tblIdx = std.mem.indexOf(u8, @typeName(T), "Table") orelse -1;
comptime var refIdx = std.mem.indexOf(u8, @typeName(T), "Ref(") orelse -1;
if (funIdx >= 0) {
if (lualib.lua_type(L, -1) == lualib.LUA_TFUNCTION) {
return T.init(L);
} else {
defer lualib.lua_pop(L, 1);
return error.bad_type;
}
} else if (tblIdx >= 0) {
if (lualib.lua_type(L, -1) == lualib.LUA_TTABLE) {
return T.init(L);
} else {
defer lualib.lua_pop(L, 1);
return error.bad_type;
}
} else if (refIdx >= 0) {
if (lualib.lua_type(L, -1) == lualib.LUA_TUSERDATA) {
return T.init(L);
} else {
defer lualib.lua_pop(L, 1);
return error.bad_type;
}
} else @compileError("Only Function supported; '" ++ @typeName(T) ++ "' not.");
},
else => @compileError("invalid type: '" ++ @typeName(T) ++ "'"),
}
}
// It is a helper function, with two responsibilities:
// 1. When it's called with only a type (allocator and value are both null) in compile time it returns that
// the given type is allocated or not
// 2. When it's called with full arguments it cleans up.
fn allocateDeallocateHelper(comptime T: type, comptime deallocate: bool, allocator: ?std.mem.Allocator, value: ?T) bool {
switch (@typeInfo(T)) {
.Pointer => |PointerInfo| switch (PointerInfo.size) {
.Slice => {
if (PointerInfo.child == u8 and PointerInfo.is_const) {
return false;
} else {
if (deallocate) {
allocator.?.free(value.?);
}
return true;
}
},
else => return false,
},
.Struct => |_| {
comptime var funIdx = std.mem.indexOf(u8, @typeName(T), "Function") orelse -1;
comptime var tblIdx = std.mem.indexOf(u8, @typeName(T), "Table") orelse -1;
comptime var refIdx = std.mem.indexOf(u8, @typeName(T), "Ref(") orelse -1;
if (funIdx >= 0 or tblIdx >= 0 or refIdx >= 0) {
if (deallocate) {
value.?.destroy();
}
return true;
} else return false;
},
else => {
return false;
},
}
}
fn ZigCallHelper(comptime funcType: type) type {
const info = @typeInfo(funcType);
if (info != .Fn) {
@compileError("ZigCallHelper expects a function type");
}
const ReturnType = info.Fn.return_type.?;
const ArgTypes = std.meta.ArgsTuple(funcType);
const resultCnt = if (ReturnType == void) 0 else 1;
return struct {
pub const LowLevelHelpers = struct {
const Self = @This();
args: ArgTypes = undefined,
result: ReturnType = undefined,
pub fn init() Self {
return Self{};
}
fn prepareArgs(self: *Self, L: ?*lualib.lua_State) !void {
// Prepare arguments
comptime var i = self.args.len - 1;
inline while (i > -1) : (i -= 1) {
if (comptime allocateDeallocateHelper(@TypeOf(self.args[i]), false, null, null)) {
self.args[i] = popResource(@TypeOf(self.args[i]), L.?) catch unreachable;
} else {
self.args[i] = pop(@TypeOf(self.args[i]), L.?) catch unreachable;
}
}
}
fn call(self: *Self, func: funcType) !void {
self.result = @call(.{}, func, self.args);
}
fn pushResult(self: *Self, L: ?*lualib.lua_State) !void {
if (resultCnt > 0) {
push(L.?, self.result);
}
}
fn destroyArgs(self: *Self, L: ?*lualib.lua_State) !void {
comptime var i = self.args.len - 1;
inline while (i > -1) : (i -= 1) {
_ = allocateDeallocateHelper(@TypeOf(self.args[i]), true, getAllocator(L), self.args[i]);
}
_ = allocateDeallocateHelper(ReturnType, true, getAllocator(L), self.result);
}
};
pub fn pushFunctor(L: ?*lualib.lua_State, func: funcType) !void {
const funcPtrAsInt = @intCast(c_longlong, @ptrToInt(func));
lualib.lua_pushinteger(L, funcPtrAsInt);
const cfun = struct {
fn helper(_L: ?*lualib.lua_State) callconv(.C) c_int {
var f: LowLevelHelpers = undefined;
// Prepare arguments from stack
f.prepareArgs(_L) catch unreachable;
// Get func pointer upvalue as int => convert to func ptr then call
var ptr = lualib.lua_tointegerx(_L, lualib.lua_upvalueindex(1), null);
f.call(@intToPtr(funcType, @intCast(usize, ptr))) catch unreachable;
// The end
f.pushResult(_L) catch unreachable;
// Release arguments
f.destroyArgs(_L) catch unreachable;
return resultCnt;
}
}.helper;
lualib.lua_pushcclosure(L, cfun, 1);
}
};
}
fn getUserData(L: ?*lualib.lua_State) *Lua.LuaUserData {
var ud : *anyopaque = undefined;
_ = lualib.lua_getallocf (L, @ptrCast([*c]?*anyopaque, &ud));
const userData = @ptrCast(*Lua.LuaUserData, @alignCast(@alignOf(Lua.LuaUserData), ud));
return userData;
}
fn getAllocator(L: ?*lualib.lua_State) std.mem.Allocator {
return getUserData(L).allocator;
}
// Credit: https://github.com/daurnimator/zig-autolua
fn alloc(ud: ?*anyopaque, ptr: ?*anyopaque, osize: usize, nsize: usize) callconv(.C) ?*anyopaque {
const c_alignment = 16;
const userData = @ptrCast(*Lua.LuaUserData, @alignCast(@alignOf(Lua.LuaUserData), ud));
if (@ptrCast(?[*]align(c_alignment) u8, @alignCast(c_alignment, ptr))) |previous_pointer| {
const previous_slice = previous_pointer[0..osize];
if (osize >= nsize) {
// Lua assumes that the allocator never fails when osize >= nsize.
return userData.allocator.alignedShrink(previous_slice, c_alignment, nsize).ptr;
} else {
return (userData.allocator.reallocAdvanced(previous_slice, c_alignment, nsize, .exact) catch return null).ptr;
}
} else {
// osize is any of LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, LUA_TUSERDATA, or LUA_TTHREAD
// when (and only when) Lua is creating a new object of that type.
// When osize is some other value, Lua is allocating memory for something else.
return (userData.allocator.alignedAlloc(u8, c_alignment, nsize) catch return null).ptr;
}
}
};
pub fn main() anyerror!void {
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs();
var tbl = try lua.createTable();
defer lua.release(tbl);
tbl.set("welcome", "All your codebase are belong to us.");
lua.set("zig", tbl);
lua.run("print(zig.welcome)");
} | src/lua.zig |
const std = @import("std");
const alka = @import("alka");
const m = alka.math;
usingnamespace alka.log;
pub const mlog = std.log.scoped(.app);
pub const log_level: std.log.Level = .info;
fn draw() !void {
const asset = alka.getAssetManager();
const staticfont = try asset.getTexture(1);
const font = try asset.getFont(0);
const r = m.Rectangle{ .position = m.Vec2f{ .x = 200.0, .y = 200.0 }, .size = m.Vec2f{ .x = 500.0, .y = 500.0 } };
const srect = m.Rectangle{ .position = m.Vec2f{ .x = 0.0, .y = 0.0 }, .size = m.Vec2f{ .x = @intToFloat(f32, staticfont.width), .y = @intToFloat(f32, staticfont.height) } };
const col = alka.Colour{ .r = 1, .g = 1, .b = 1, .a = 1 };
try alka.drawTexture(1, r, srect, col);
// id, position, size, colour
try alka.drawTextPoint(0, 'A', m.Vec2f{ .x = 200, .y = 300 }, 24, col);
try alka.drawTextPoint(0, 'L', m.Vec2f{ .x = 200 + 15, .y = 300 }, 24, col);
try alka.drawTextPoint(0, 'K', m.Vec2f{ .x = 200 + 15 * 2, .y = 300 }, 24, col);
try alka.drawTextPoint(0, 'A', m.Vec2f{ .x = 200 + 15 * 3, .y = 300 }, 24, col);
try alka.drawText(0, "This is rendered on the fly!", m.Vec2f{ .x = 100, .y = 500 }, 32, col);
const alloc = alka.getAllocator();
var debug: []u8 = try alloc.alloc(u8, 255);
defer alloc.free(debug);
debug = try std.fmt.bufPrintZ(debug, "fps: {}", .{alka.getFps()});
try alka.drawText(0, debug, m.Vec2f{ .x = 20, .y = 20 }, 24, col);
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const callbacks = alka.Callbacks{
.update = null,
.fixed = null,
.draw = draw,
.resize = null,
.close = null,
};
try alka.init(&gpa.allocator, callbacks, 1024, 768, "Text Rendering", 0, false);
// .. bitmap width & height, pixel size
const texture = try alka.renderer.Texture.createFromTTF(&gpa.allocator, "assets/arial.ttf", "Hello", 500, 500, 24);
// min, mag
texture.setFilter(alka.gl.TextureParamater.filter_mipmap_nearest, alka.gl.TextureParamater.filter_linear);
// id, texture
try alka.getAssetManager().loadTexturePro(1, texture); // texture 0 & shader 0 is reserved for defaults
// id, path, pixel size
try alka.getAssetManager().loadFont(0, "assets/arial.ttf", 128);
const font = try alka.getAssetManager().getFont(0);
// min, mag
font.texture.setFilter(alka.gl.TextureParamater.filter_mipmap_nearest, alka.gl.TextureParamater.filter_linear);
try alka.open();
try alka.update();
try alka.close();
try alka.deinit();
const leaked = gpa.deinit();
if (leaked) return error.Leak;
} | examples/text_rendering.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
pub fn asin(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f32 => asin32(x),
f64 => asin64(x),
else => @compileError("asin not implemented for " ++ @typeName(T)),
};
}
fn r32(z: f32) f32 {
const pS0 = 1.6666586697e-01;
const pS1 = -4.2743422091e-02;
const pS2 = -8.6563630030e-03;
const qS1 = -7.0662963390e-01;
const p = z * (pS0 + z * (pS1 + z * pS2));
const q = 1.0 + z * qS1;
return p / q;
}
fn asin32(x: f32) f32 {
const pio2 = 1.570796326794896558e+00;
const hx: u32 = @bitCast(u32, x);
const ix: u32 = hx & 0x7FFFFFFF;
// |x| >= 1
if (ix >= 0x3F800000) {
// |x| >= 1
if (ix == 0x3F800000) {
return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact
} else {
return math.nan(f32); // asin(|x| > 1) is nan
}
}
// |x| < 0.5
if (ix < 0x3F000000) {
// 0x1p-126 <= |x| < 0x1p-12
if (ix < 0x39800000 and ix >= 0x00800000) {
return x;
} else {
return x + x * r32(x * x);
}
}
// 1 > |x| >= 0.5
const z = (1 - math.fabs(x)) * 0.5;
const s = math.sqrt(z);
const fx = pio2 - 2 * (s + s * r32(z));
if (hx >> 31 != 0) {
return -fx;
} else {
return fx;
}
}
fn r64(z: f64) f64 {
const pS0: f64 = 1.66666666666666657415e-01;
const pS1: f64 = -3.25565818622400915405e-01;
const pS2: f64 = 2.01212532134862925881e-01;
const pS3: f64 = -4.00555345006794114027e-02;
const pS4: f64 = 7.91534994289814532176e-04;
const pS5: f64 = 3.47933107596021167570e-05;
const qS1: f64 = -2.40339491173441421878e+00;
const qS2: f64 = 2.02094576023350569471e+00;
const qS3: f64 = -6.88283971605453293030e-01;
const qS4: f64 = 7.70381505559019352791e-02;
const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))));
const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)));
return p / q;
}
fn asin64(x: f64) f64 {
const pio2_hi: f64 = 1.57079632679489655800e+00;
const pio2_lo: f64 = 6.12323399573676603587e-17;
const ux = @bitCast(u64, x);
const hx = @intCast(u32, ux >> 32);
const ix = hx & 0x7FFFFFFF;
// |x| >= 1 or nan
if (ix >= 0x3FF00000) {
const lx = @intCast(u32, ux & 0xFFFFFFFF);
// asin(1) = +-pi/2 with inexact
if ((ix - 0x3FF00000) | lx == 0) {
return x * pio2_hi + 0x1.0p-120;
} else {
return math.nan(f64);
}
}
// |x| < 0.5
if (ix < 0x3FE00000) {
// if 0x1p-1022 <= |x| < 0x1p-26 avoid raising overflow
if (ix < 0x3E500000 and ix >= 0x00100000) {
return x;
} else {
return x + x * r64(x * x);
}
}
// 1 > |x| >= 0.5
const z = (1 - math.fabs(x)) * 0.5;
const s = math.sqrt(z);
const r = r64(z);
var fx: f64 = undefined;
// |x| > 0.975
if (ix >= 0x3FEF3333) {
fx = pio2_hi - 2 * (s + s * r);
} else {
const jx = @bitCast(u64, s);
const df = @bitCast(f64, jx & 0xFFFFFFFF00000000);
const c = (z - df * df) / (s + df);
fx = 0.5 * pio2_hi - (2 * s * r - (pio2_lo - 2 * c) - (0.5 * pio2_hi - 2 * df));
}
if (hx >> 31 != 0) {
return -fx;
} else {
return fx;
}
}
test "math.asin" {
expect(asin(f32(0.0)) == asin32(0.0));
expect(asin(f64(0.0)) == asin64(0.0));
}
test "math.asin32" {
const epsilon = 0.000001;
expect(math.approxEq(f32, asin32(0.0), 0.0, epsilon));
expect(math.approxEq(f32, asin32(0.2), 0.201358, epsilon));
expect(math.approxEq(f32, asin32(-0.2), -0.201358, epsilon));
expect(math.approxEq(f32, asin32(0.3434), 0.350535, epsilon));
expect(math.approxEq(f32, asin32(0.5), 0.523599, epsilon));
expect(math.approxEq(f32, asin32(0.8923), 1.102415, epsilon));
}
test "math.asin64" {
const epsilon = 0.000001;
expect(math.approxEq(f64, asin64(0.0), 0.0, epsilon));
expect(math.approxEq(f64, asin64(0.2), 0.201358, epsilon));
expect(math.approxEq(f64, asin64(-0.2), -0.201358, epsilon));
expect(math.approxEq(f64, asin64(0.3434), 0.350535, epsilon));
expect(math.approxEq(f64, asin64(0.5), 0.523599, epsilon));
expect(math.approxEq(f64, asin64(0.8923), 1.102415, epsilon));
}
test "math.asin32.special" {
expect(asin32(0.0) == 0.0);
expect(asin32(-0.0) == -0.0);
expect(math.isNan(asin32(-2)));
expect(math.isNan(asin32(1.5)));
}
test "math.asin64.special" {
expect(asin64(0.0) == 0.0);
expect(asin64(-0.0) == -0.0);
expect(math.isNan(asin64(-2)));
expect(math.isNan(asin64(1.5)));
} | std/math/asin.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const BigIntConst = std.math.big.int.Const;
const BigIntMutable = std.math.big.int.Mutable;
const Type = @import("type.zig").Type;
const Value = @import("value.zig").Value;
const TypedValue = @import("TypedValue.zig");
const ir = @import("ir.zig");
const IrModule = @import("Module.zig");
/// These are instructions that correspond to the ZIR text format. See `ir.Inst` for
/// in-memory, analyzed instructions with types and values.
/// We use a table to map these instruction to their respective semantically analyzed
/// instructions because it is possible to have multiple analyses on the same ZIR
/// happening at the same time.
pub const Inst = struct {
tag: Tag,
/// Byte offset into the source.
src: usize,
/// These names are used directly as the instruction names in the text format.
pub const Tag = enum {
/// Arithmetic addition, asserts no integer overflow.
add,
/// Twos complement wrapping integer addition.
addwrap,
/// Allocates stack local memory. Its lifetime ends when the block ends that contains
/// this instruction. The operand is the type of the allocated object.
alloc,
/// Same as `alloc` except mutable.
alloc_mut,
/// Same as `alloc` except the type is inferred.
alloc_inferred,
/// Same as `alloc_inferred` except mutable.
alloc_inferred_mut,
/// Create an `anyframe->T`.
anyframe_type,
/// Array concatenation. `a ++ b`
array_cat,
/// Array multiplication `a ** b`
array_mul,
/// Create an array type
array_type,
/// Create an array type with sentinel
array_type_sentinel,
/// Given a pointer to an indexable object, returns the len property. This is
/// used by for loops. This instruction also emits a for-loop specific instruction
/// if the indexable object is not indexable.
indexable_ptr_len,
/// Function parameter value. These must be first in a function's main block,
/// in respective order with the parameters.
/// TODO make this instruction implicit; after we transition to having ZIR
/// instructions be same sized and referenced by index, the first N indexes
/// will implicitly be references to the parameters of the function.
arg,
/// Type coercion.
as,
/// Inline assembly.
@"asm",
/// Await an async function.
@"await",
/// Bitwise AND. `&`
bit_and,
/// TODO delete this instruction, it has no purpose.
bitcast,
/// An arbitrary typed pointer is pointer-casted to a new Pointer.
/// The destination type is given by LHS. The cast is to be evaluated
/// as if it were a bit-cast operation from the operand pointer element type to the
/// provided destination type.
bitcast_ref,
/// A typed result location pointer is bitcasted to a new result location pointer.
/// The new result location pointer has an inferred type.
bitcast_result_ptr,
/// Bitwise NOT. `~`
bit_not,
/// Bitwise OR. `|`
bit_or,
/// A labeled block of code, which can return a value.
block,
/// A block of code, which can return a value. There are no instructions that break out of
/// this block; it is implied that the final instruction is the result.
block_flat,
/// Same as `block` but additionally makes the inner instructions execute at comptime.
block_comptime,
/// Same as `block_flat` but additionally makes the inner instructions execute at comptime.
block_comptime_flat,
/// Boolean AND. See also `bit_and`.
bool_and,
/// Boolean NOT. See also `bit_not`.
bool_not,
/// Boolean OR. See also `bit_or`.
bool_or,
/// Return a value from a `Block`.
@"break",
breakpoint,
/// Same as `break` but without an operand; the operand is assumed to be the void value.
break_void,
/// Function call.
call,
/// `<`
cmp_lt,
/// `<=`
cmp_lte,
/// `==`
cmp_eq,
/// `>=`
cmp_gte,
/// `>`
cmp_gt,
/// `!=`
cmp_neq,
/// Coerces a result location pointer to a new element type. It is evaluated "backwards"-
/// as type coercion from the new element type to the old element type.
/// LHS is destination element type, RHS is result pointer.
coerce_result_ptr,
/// Emit an error message and fail compilation.
compile_error,
/// Log compile time variables and emit an error message.
compile_log,
/// Conditional branch. Splits control flow based on a boolean condition value.
condbr,
/// Special case, has no textual representation.
@"const",
/// Container field with just the name.
container_field_named,
/// Container field with a type and a name,
container_field_typed,
/// Container field with all the bells and whistles.
container_field,
/// Declares the beginning of a statement. Used for debug info.
dbg_stmt,
/// Represents a pointer to a global decl.
decl_ref,
/// Represents a pointer to a global decl by string name.
decl_ref_str,
/// Equivalent to a decl_ref followed by deref.
decl_val,
/// Load the value from a pointer.
deref,
/// Arithmetic division. Asserts no integer overflow.
div,
/// Given a pointer to an array, slice, or pointer, returns a pointer to the element at
/// the provided index.
elem_ptr,
/// Given an array, slice, or pointer, returns the element at the provided index.
elem_val,
/// Emits a compile error if the operand is not `void`.
ensure_result_used,
/// Emits a compile error if an error is ignored.
ensure_result_non_error,
/// Create a `E!T` type.
error_union_type,
/// Create an error set.
error_set,
/// `error.Foo` syntax.
error_value,
/// Export the provided Decl as the provided name in the compilation's output object file.
@"export",
/// Given a pointer to a struct or object that contains virtual fields, returns a pointer
/// to the named field. The field name is a []const u8. Used by a.b syntax.
field_ptr,
/// Given a struct or object that contains virtual fields, returns the named field.
/// The field name is a []const u8. Used by a.b syntax.
field_val,
/// Given a pointer to a struct or object that contains virtual fields, returns a pointer
/// to the named field. The field name is a comptime instruction. Used by @field.
field_ptr_named,
/// Given a struct or object that contains virtual fields, returns the named field.
/// The field name is a comptime instruction. Used by @field.
field_val_named,
/// Convert a larger float type to any other float type, possibly causing a loss of precision.
floatcast,
/// Declare a function body.
@"fn",
/// Returns a function type, assuming unspecified calling convention.
fn_type,
/// Same as `fn_type` but the function is variadic.
fn_type_var_args,
/// Returns a function type, with a calling convention instruction operand.
fn_type_cc,
/// Same as `fn_type_cc` but the function is variadic.
fn_type_cc_var_args,
/// @import(operand)
import,
/// Integer literal.
int,
/// Convert an integer value to another integer type, asserting that the destination type
/// can hold the same mathematical value.
intcast,
/// Make an integer type out of signedness and bit count.
int_type,
/// Return a boolean false if an optional is null. `x != null`
is_non_null,
/// Return a boolean true if an optional is null. `x == null`
is_null,
/// Return a boolean false if an optional is null. `x.* != null`
is_non_null_ptr,
/// Return a boolean true if an optional is null. `x.* == null`
is_null_ptr,
/// Return a boolean true if value is an error
is_err,
/// Return a boolean true if dereferenced pointer is an error
is_err_ptr,
/// A labeled block of code that loops forever. At the end of the body it is implied
/// to repeat; no explicit "repeat" instruction terminates loop bodies.
loop,
/// Merge two error sets into one, `E1 || E2`.
merge_error_sets,
/// Ambiguously remainder division or modulus. If the computation would possibly have
/// a different value depending on whether the operation is remainder division or modulus,
/// a compile error is emitted. Otherwise the computation is performed.
mod_rem,
/// Arithmetic multiplication. Asserts no integer overflow.
mul,
/// Twos complement wrapping integer multiplication.
mulwrap,
/// An await inside a nosuspend scope.
nosuspend_await,
/// Given a reference to a function and a parameter index, returns the
/// type of the parameter. TODO what happens when the parameter is `anytype`?
param_type,
/// An alternative to using `const` for simple primitive values such as `true` or `u8`.
/// TODO flatten so that each primitive has its own ZIR Inst Tag.
primitive,
/// Convert a pointer to a `usize` integer.
ptrtoint,
/// Turns an R-Value into a const L-Value. In other words, it takes a value,
/// stores it in a memory location, and returns a const pointer to it. If the value
/// is `comptime`, the memory location is global static constant data. Otherwise,
/// the memory location is in the stack frame, local to the scope containing the
/// instruction.
ref,
/// Resume an async function.
@"resume",
/// Obtains a pointer to the return value.
ret_ptr,
/// Obtains the return type of the in-scope function.
ret_type,
/// Sends control flow back to the function's callee. Takes an operand as the return value.
@"return",
/// Same as `return` but there is no operand; the operand is implicitly the void value.
return_void,
/// Changes the maximum number of backwards branches that compile-time
/// code execution can use before giving up and making a compile error.
set_eval_branch_quota,
/// Integer shift-left. Zeroes are shifted in from the right hand side.
shl,
/// Integer shift-right. Arithmetic or logical depending on the signedness of the integer type.
shr,
/// Create a const pointer type with element type T. `*const T`
single_const_ptr_type,
/// Create a mutable pointer type with element type T. `*T`
single_mut_ptr_type,
/// Create a const pointer type with element type T. `[*]const T`
many_const_ptr_type,
/// Create a mutable pointer type with element type T. `[*]T`
many_mut_ptr_type,
/// Create a const pointer type with element type T. `[*c]const T`
c_const_ptr_type,
/// Create a mutable pointer type with element type T. `[*c]T`
c_mut_ptr_type,
/// Create a mutable slice type with element type T. `[]T`
mut_slice_type,
/// Create a const slice type with element type T. `[]T`
const_slice_type,
/// Create a pointer type with attributes
ptr_type,
/// Each `store_to_inferred_ptr` puts the type of the stored value into a set,
/// and then `resolve_inferred_alloc` triggers peer type resolution on the set.
/// The operand is a `alloc_inferred` or `alloc_inferred_mut` instruction, which
/// is the allocation that needs to have its type inferred.
resolve_inferred_alloc,
/// Slice operation `array_ptr[start..end:sentinel]`
slice,
/// Slice operation with just start `lhs[rhs..]`
slice_start,
/// Write a value to a pointer. For loading, see `deref`.
store,
/// Same as `store` but the type of the value being stored will be used to infer
/// the block type. The LHS is the pointer to store to.
store_to_block_ptr,
/// Same as `store` but the type of the value being stored will be used to infer
/// the pointer type.
store_to_inferred_ptr,
/// String Literal. Makes an anonymous Decl and then takes a pointer to it.
str,
/// Create a struct type.
struct_type,
/// Arithmetic subtraction. Asserts no integer overflow.
sub,
/// Twos complement wrapping integer subtraction.
subwrap,
/// Returns the type of a value.
typeof,
/// Is the builtin @TypeOf which returns the type after peertype resolution of one or more params
typeof_peer,
/// Asserts control-flow will not reach this instruction. Not safety checked - the compiler
/// will assume the correctness of this instruction.
unreachable_unsafe,
/// Asserts control-flow will not reach this instruction. In safety-checked modes,
/// this will generate a call to the panic function unless it can be proven unreachable
/// by the compiler.
unreachable_safe,
/// Bitwise XOR. `^`
xor,
/// Create an optional type '?T'
optional_type,
/// Create an optional type '?T'. The operand is a pointer value. The optional type will
/// be the type of the pointer element, wrapped in an optional.
optional_type_from_ptr_elem,
/// Create a union type.
union_type,
/// ?T => T with safety.
/// Given an optional value, returns the payload value, with a safety check that
/// the value is non-null. Used for `orelse`, `if` and `while`.
optional_payload_safe,
/// ?T => T without safety.
/// Given an optional value, returns the payload value. No safety checks.
optional_payload_unsafe,
/// *?T => *T with safety.
/// Given a pointer to an optional value, returns a pointer to the payload value,
/// with a safety check that the value is non-null. Used for `orelse`, `if` and `while`.
optional_payload_safe_ptr,
/// *?T => *T without safety.
/// Given a pointer to an optional value, returns a pointer to the payload value.
/// No safety checks.
optional_payload_unsafe_ptr,
/// E!T => T with safety.
/// Given an error union value, returns the payload value, with a safety check
/// that the value is not an error. Used for catch, if, and while.
err_union_payload_safe,
/// E!T => T without safety.
/// Given an error union value, returns the payload value. No safety checks.
err_union_payload_unsafe,
/// *E!T => *T with safety.
/// Given a pointer to an error union value, returns a pointer to the payload value,
/// with a safety check that the value is not an error. Used for catch, if, and while.
err_union_payload_safe_ptr,
/// *E!T => *T without safety.
/// Given a pointer to a error union value, returns a pointer to the payload value.
/// No safety checks.
err_union_payload_unsafe_ptr,
/// E!T => E without safety.
/// Given an error union value, returns the error code. No safety checks.
err_union_code,
/// *E!T => E without safety.
/// Given a pointer to an error union value, returns the error code. No safety checks.
err_union_code_ptr,
/// Takes a *E!T and raises a compiler error if T != void
ensure_err_payload_void,
/// Create a enum literal,
enum_literal,
/// Create an enum type.
enum_type,
/// Does nothing; returns a void value.
void_value,
/// Suspend an async function.
@"suspend",
/// Suspend an async function.
/// Same as .suspend but with a block.
suspend_block,
/// A switch expression.
switchbr,
/// Same as `switchbr` but the target is a pointer to the value being switched on.
switchbr_ref,
/// A range in a switch case, `lhs...rhs`.
/// Only checks that `lhs >= rhs` if they are ints, everything else is
/// validated by the .switch instruction.
switch_range,
pub fn Type(tag: Tag) type {
return switch (tag) {
.alloc_inferred,
.alloc_inferred_mut,
.breakpoint,
.dbg_stmt,
.return_void,
.ret_ptr,
.ret_type,
.unreachable_unsafe,
.unreachable_safe,
.void_value,
.@"suspend",
=> NoOp,
.alloc,
.alloc_mut,
.bool_not,
.compile_error,
.deref,
.@"return",
.is_null,
.is_non_null,
.is_null_ptr,
.is_non_null_ptr,
.is_err,
.is_err_ptr,
.ptrtoint,
.ensure_result_used,
.ensure_result_non_error,
.bitcast_result_ptr,
.ref,
.bitcast_ref,
.typeof,
.resolve_inferred_alloc,
.single_const_ptr_type,
.single_mut_ptr_type,
.many_const_ptr_type,
.many_mut_ptr_type,
.c_const_ptr_type,
.c_mut_ptr_type,
.mut_slice_type,
.const_slice_type,
.optional_type,
.optional_type_from_ptr_elem,
.optional_payload_safe,
.optional_payload_unsafe,
.optional_payload_safe_ptr,
.optional_payload_unsafe_ptr,
.err_union_payload_safe,
.err_union_payload_unsafe,
.err_union_payload_safe_ptr,
.err_union_payload_unsafe_ptr,
.err_union_code,
.err_union_code_ptr,
.ensure_err_payload_void,
.anyframe_type,
.bit_not,
.import,
.set_eval_branch_quota,
.indexable_ptr_len,
.@"resume",
.@"await",
.nosuspend_await,
=> UnOp,
.add,
.addwrap,
.array_cat,
.array_mul,
.array_type,
.bit_and,
.bit_or,
.bool_and,
.bool_or,
.div,
.mod_rem,
.mul,
.mulwrap,
.shl,
.shr,
.store,
.store_to_block_ptr,
.store_to_inferred_ptr,
.sub,
.subwrap,
.cmp_lt,
.cmp_lte,
.cmp_eq,
.cmp_gte,
.cmp_gt,
.cmp_neq,
.as,
.floatcast,
.intcast,
.bitcast,
.coerce_result_ptr,
.xor,
.error_union_type,
.merge_error_sets,
.slice_start,
.switch_range,
=> BinOp,
.block,
.block_flat,
.block_comptime,
.block_comptime_flat,
.suspend_block,
=> Block,
.switchbr, .switchbr_ref => SwitchBr,
.arg => Arg,
.array_type_sentinel => ArrayTypeSentinel,
.@"break" => Break,
.break_void => BreakVoid,
.call => Call,
.decl_ref => DeclRef,
.decl_ref_str => DeclRefStr,
.decl_val => DeclVal,
.compile_log => CompileLog,
.loop => Loop,
.@"const" => Const,
.str => Str,
.int => Int,
.int_type => IntType,
.field_ptr, .field_val => Field,
.field_ptr_named, .field_val_named => FieldNamed,
.@"asm" => Asm,
.@"fn" => Fn,
.@"export" => Export,
.param_type => ParamType,
.primitive => Primitive,
.fn_type, .fn_type_var_args => FnType,
.fn_type_cc, .fn_type_cc_var_args => FnTypeCc,
.elem_ptr, .elem_val => Elem,
.condbr => CondBr,
.ptr_type => PtrType,
.enum_literal => EnumLiteral,
.error_set => ErrorSet,
.error_value => ErrorValue,
.slice => Slice,
.typeof_peer => TypeOfPeer,
.container_field_named => ContainerFieldNamed,
.container_field_typed => ContainerFieldTyped,
.container_field => ContainerField,
.enum_type => EnumType,
.union_type => UnionType,
.struct_type => StructType,
};
}
/// Returns whether the instruction is one of the control flow "noreturn" types.
/// Function calls do not count.
pub fn isNoReturn(tag: Tag) bool {
return switch (tag) {
.add,
.addwrap,
.alloc,
.alloc_mut,
.alloc_inferred,
.alloc_inferred_mut,
.array_cat,
.array_mul,
.array_type,
.array_type_sentinel,
.indexable_ptr_len,
.arg,
.as,
.@"asm",
.bit_and,
.bitcast,
.bitcast_ref,
.bitcast_result_ptr,
.bit_or,
.block,
.block_flat,
.block_comptime,
.block_comptime_flat,
.bool_not,
.bool_and,
.bool_or,
.breakpoint,
.call,
.cmp_lt,
.cmp_lte,
.cmp_eq,
.cmp_gte,
.cmp_gt,
.cmp_neq,
.coerce_result_ptr,
.@"const",
.dbg_stmt,
.decl_ref,
.decl_ref_str,
.decl_val,
.deref,
.div,
.elem_ptr,
.elem_val,
.ensure_result_used,
.ensure_result_non_error,
.@"export",
.floatcast,
.field_ptr,
.field_val,
.field_ptr_named,
.field_val_named,
.@"fn",
.fn_type,
.fn_type_var_args,
.fn_type_cc,
.fn_type_cc_var_args,
.int,
.intcast,
.int_type,
.is_non_null,
.is_null,
.is_non_null_ptr,
.is_null_ptr,
.is_err,
.is_err_ptr,
.mod_rem,
.mul,
.mulwrap,
.param_type,
.primitive,
.ptrtoint,
.ref,
.ret_ptr,
.ret_type,
.shl,
.shr,
.single_const_ptr_type,
.single_mut_ptr_type,
.many_const_ptr_type,
.many_mut_ptr_type,
.c_const_ptr_type,
.c_mut_ptr_type,
.mut_slice_type,
.const_slice_type,
.store,
.store_to_block_ptr,
.store_to_inferred_ptr,
.str,
.sub,
.subwrap,
.typeof,
.xor,
.optional_type,
.optional_type_from_ptr_elem,
.optional_payload_safe,
.optional_payload_unsafe,
.optional_payload_safe_ptr,
.optional_payload_unsafe_ptr,
.err_union_payload_safe,
.err_union_payload_unsafe,
.err_union_payload_safe_ptr,
.err_union_payload_unsafe_ptr,
.err_union_code,
.err_union_code_ptr,
.ptr_type,
.ensure_err_payload_void,
.enum_literal,
.merge_error_sets,
.anyframe_type,
.error_union_type,
.bit_not,
.error_set,
.error_value,
.slice,
.slice_start,
.import,
.typeof_peer,
.resolve_inferred_alloc,
.set_eval_branch_quota,
.compile_log,
.enum_type,
.union_type,
.struct_type,
.void_value,
.switch_range,
.@"resume",
.@"await",
.nosuspend_await,
=> false,
.@"break",
.break_void,
.condbr,
.compile_error,
.@"return",
.return_void,
.unreachable_unsafe,
.unreachable_safe,
.loop,
.container_field_named,
.container_field_typed,
.container_field,
.switchbr,
.switchbr_ref,
.@"suspend",
.suspend_block,
=> true,
};
}
};
/// Prefer `castTag` to this.
pub fn cast(base: *Inst, comptime T: type) ?*T {
if (@hasField(T, "base_tag")) {
return base.castTag(T.base_tag);
}
inline for (@typeInfo(Tag).Enum.fields) |field| {
const tag = @intToEnum(Tag, field.value);
if (base.tag == tag) {
if (T == tag.Type()) {
return @fieldParentPtr(T, "base", base);
}
return null;
}
}
unreachable;
}
pub fn castTag(base: *Inst, comptime tag: Tag) ?*tag.Type() {
if (base.tag == tag) {
return @fieldParentPtr(tag.Type(), "base", base);
}
return null;
}
pub const NoOp = struct {
base: Inst,
positionals: struct {},
kw_args: struct {},
};
pub const UnOp = struct {
base: Inst,
positionals: struct {
operand: *Inst,
},
kw_args: struct {},
};
pub const BinOp = struct {
base: Inst,
positionals: struct {
lhs: *Inst,
rhs: *Inst,
},
kw_args: struct {},
};
pub const Arg = struct {
pub const base_tag = Tag.arg;
base: Inst,
positionals: struct {
/// This exists to be passed to the arg TZIR instruction, which
/// needs it for debug info.
name: []const u8,
},
kw_args: struct {},
};
pub const Block = struct {
pub const base_tag = Tag.block;
base: Inst,
positionals: struct {
body: Body,
},
kw_args: struct {},
};
pub const Break = struct {
pub const base_tag = Tag.@"break";
base: Inst,
positionals: struct {
block: *Block,
operand: *Inst,
},
kw_args: struct {},
};
pub const BreakVoid = struct {
pub const base_tag = Tag.break_void;
base: Inst,
positionals: struct {
block: *Block,
},
kw_args: struct {},
};
// TODO break this into multiple call instructions to avoid paying the cost
// of the calling convention field most of the time.
pub const Call = struct {
pub const base_tag = Tag.call;
base: Inst,
positionals: struct {
func: *Inst,
args: []*Inst,
modifier: std.builtin.CallOptions.Modifier = .auto,
},
kw_args: struct {},
};
pub const DeclRef = struct {
pub const base_tag = Tag.decl_ref;
base: Inst,
positionals: struct {
decl: *IrModule.Decl,
},
kw_args: struct {},
};
pub const DeclRefStr = struct {
pub const base_tag = Tag.decl_ref_str;
base: Inst,
positionals: struct {
name: *Inst,
},
kw_args: struct {},
};
pub const DeclVal = struct {
pub const base_tag = Tag.decl_val;
base: Inst,
positionals: struct {
decl: *IrModule.Decl,
},
kw_args: struct {},
};
pub const CompileLog = struct {
pub const base_tag = Tag.compile_log;
base: Inst,
positionals: struct {
to_log: []*Inst,
},
kw_args: struct {},
};
pub const Const = struct {
pub const base_tag = Tag.@"const";
base: Inst,
positionals: struct {
typed_value: TypedValue,
},
kw_args: struct {},
};
pub const Str = struct {
pub const base_tag = Tag.str;
base: Inst,
positionals: struct {
bytes: []const u8,
},
kw_args: struct {},
};
pub const Int = struct {
pub const base_tag = Tag.int;
base: Inst,
positionals: struct {
int: BigIntConst,
},
kw_args: struct {},
};
pub const Loop = struct {
pub const base_tag = Tag.loop;
base: Inst,
positionals: struct {
body: Body,
},
kw_args: struct {},
};
pub const Field = struct {
base: Inst,
positionals: struct {
object: *Inst,
field_name: []const u8,
},
kw_args: struct {},
};
pub const FieldNamed = struct {
base: Inst,
positionals: struct {
object: *Inst,
field_name: *Inst,
},
kw_args: struct {},
};
pub const Asm = struct {
pub const base_tag = Tag.@"asm";
base: Inst,
positionals: struct {
asm_source: *Inst,
return_type: *Inst,
},
kw_args: struct {
@"volatile": bool = false,
output: ?*Inst = null,
inputs: []const []const u8 = &.{},
clobbers: []const []const u8 = &.{},
args: []*Inst = &[0]*Inst{},
},
};
pub const Fn = struct {
pub const base_tag = Tag.@"fn";
base: Inst,
positionals: struct {
fn_type: *Inst,
body: Body,
},
kw_args: struct {},
};
pub const FnType = struct {
pub const base_tag = Tag.fn_type;
base: Inst,
positionals: struct {
param_types: []*Inst,
return_type: *Inst,
},
kw_args: struct {},
};
pub const FnTypeCc = struct {
pub const base_tag = Tag.fn_type_cc;
base: Inst,
positionals: struct {
param_types: []*Inst,
return_type: *Inst,
cc: *Inst,
},
kw_args: struct {},
};
pub const IntType = struct {
pub const base_tag = Tag.int_type;
base: Inst,
positionals: struct {
signed: *Inst,
bits: *Inst,
},
kw_args: struct {},
};
pub const Export = struct {
pub const base_tag = Tag.@"export";
base: Inst,
positionals: struct {
symbol_name: *Inst,
decl_name: []const u8,
},
kw_args: struct {},
};
pub const ParamType = struct {
pub const base_tag = Tag.param_type;
base: Inst,
positionals: struct {
func: *Inst,
arg_index: usize,
},
kw_args: struct {},
};
pub const Primitive = struct {
pub const base_tag = Tag.primitive;
base: Inst,
positionals: struct {
tag: Builtin,
},
kw_args: struct {},
pub const Builtin = enum {
i8,
u8,
i16,
u16,
i32,
u32,
i64,
u64,
isize,
usize,
c_short,
c_ushort,
c_int,
c_uint,
c_long,
c_ulong,
c_longlong,
c_ulonglong,
c_longdouble,
c_void,
f16,
f32,
f64,
f128,
bool,
void,
noreturn,
type,
anyerror,
comptime_int,
comptime_float,
@"true",
@"false",
@"null",
@"undefined",
void_value,
pub fn toTypedValue(self: Builtin) TypedValue {
return switch (self) {
.i8 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i8_type) },
.u8 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u8_type) },
.i16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i16_type) },
.u16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u16_type) },
.i32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i32_type) },
.u32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u32_type) },
.i64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i64_type) },
.u64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u64_type) },
.isize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.isize_type) },
.usize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.usize_type) },
.c_short => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_short_type) },
.c_ushort => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ushort_type) },
.c_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_int_type) },
.c_uint => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_uint_type) },
.c_long => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_long_type) },
.c_ulong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulong_type) },
.c_longlong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longlong_type) },
.c_ulonglong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulonglong_type) },
.c_longdouble => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longdouble_type) },
.c_void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_void_type) },
.f16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f16_type) },
.f32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f32_type) },
.f64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f64_type) },
.f128 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f128_type) },
.bool => .{ .ty = Type.initTag(.type), .val = Value.initTag(.bool_type) },
.void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.void_type) },
.noreturn => .{ .ty = Type.initTag(.type), .val = Value.initTag(.noreturn_type) },
.type => .{ .ty = Type.initTag(.type), .val = Value.initTag(.type_type) },
.anyerror => .{ .ty = Type.initTag(.type), .val = Value.initTag(.anyerror_type) },
.comptime_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_int_type) },
.comptime_float => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_float_type) },
.@"true" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_true) },
.@"false" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_false) },
.@"null" => .{ .ty = Type.initTag(.@"null"), .val = Value.initTag(.null_value) },
.@"undefined" => .{ .ty = Type.initTag(.@"undefined"), .val = Value.initTag(.undef) },
.void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.void_value) },
};
}
};
};
pub const Elem = struct {
base: Inst,
positionals: struct {
array: *Inst,
index: *Inst,
},
kw_args: struct {},
};
pub const CondBr = struct {
pub const base_tag = Tag.condbr;
base: Inst,
positionals: struct {
condition: *Inst,
then_body: Body,
else_body: Body,
},
kw_args: struct {},
};
pub const PtrType = struct {
pub const base_tag = Tag.ptr_type;
base: Inst,
positionals: struct {
child_type: *Inst,
},
kw_args: struct {
@"allowzero": bool = false,
@"align": ?*Inst = null,
align_bit_start: ?*Inst = null,
align_bit_end: ?*Inst = null,
mutable: bool = true,
@"volatile": bool = false,
sentinel: ?*Inst = null,
size: std.builtin.TypeInfo.Pointer.Size = .One,
},
};
pub const ArrayTypeSentinel = struct {
pub const base_tag = Tag.array_type_sentinel;
base: Inst,
positionals: struct {
len: *Inst,
sentinel: *Inst,
elem_type: *Inst,
},
kw_args: struct {},
};
pub const EnumLiteral = struct {
pub const base_tag = Tag.enum_literal;
base: Inst,
positionals: struct {
name: []const u8,
},
kw_args: struct {},
};
pub const ErrorSet = struct {
pub const base_tag = Tag.error_set;
base: Inst,
positionals: struct {
fields: [][]const u8,
},
kw_args: struct {},
};
pub const ErrorValue = struct {
pub const base_tag = Tag.error_value;
base: Inst,
positionals: struct {
name: []const u8,
},
kw_args: struct {},
};
pub const Slice = struct {
pub const base_tag = Tag.slice;
base: Inst,
positionals: struct {
array_ptr: *Inst,
start: *Inst,
},
kw_args: struct {
end: ?*Inst = null,
sentinel: ?*Inst = null,
},
};
pub const TypeOfPeer = struct {
pub const base_tag = .typeof_peer;
base: Inst,
positionals: struct {
items: []*Inst,
},
kw_args: struct {},
};
pub const ContainerFieldNamed = struct {
pub const base_tag = Tag.container_field_named;
base: Inst,
positionals: struct {
bytes: []const u8,
},
kw_args: struct {},
};
pub const ContainerFieldTyped = struct {
pub const base_tag = Tag.container_field_typed;
base: Inst,
positionals: struct {
bytes: []const u8,
ty: *Inst,
},
kw_args: struct {},
};
pub const ContainerField = struct {
pub const base_tag = Tag.container_field;
base: Inst,
positionals: struct {
bytes: []const u8,
},
kw_args: struct {
ty: ?*Inst = null,
init: ?*Inst = null,
alignment: ?*Inst = null,
is_comptime: bool = false,
},
};
pub const EnumType = struct {
pub const base_tag = Tag.enum_type;
base: Inst,
positionals: struct {
fields: []*Inst,
},
kw_args: struct {
tag_type: ?*Inst = null,
layout: std.builtin.TypeInfo.ContainerLayout = .Auto,
},
};
pub const StructType = struct {
pub const base_tag = Tag.struct_type;
base: Inst,
positionals: struct {
fields: []*Inst,
},
kw_args: struct {
layout: std.builtin.TypeInfo.ContainerLayout = .Auto,
},
};
pub const UnionType = struct {
pub const base_tag = Tag.union_type;
base: Inst,
positionals: struct {
fields: []*Inst,
},
kw_args: struct {
init_inst: ?*Inst = null,
has_enum_token: bool,
layout: std.builtin.TypeInfo.ContainerLayout = .Auto,
},
};
pub const SwitchBr = struct {
base: Inst,
positionals: struct {
target: *Inst,
/// List of all individual items and ranges
items: []*Inst,
cases: []Case,
else_body: Body,
/// Pointer to first range if such exists.
range: ?*Inst = null,
special_prong: SpecialProng = .none,
},
kw_args: struct {},
pub const SpecialProng = enum {
none,
@"else",
underscore,
};
pub const Case = struct {
item: *Inst,
body: Body,
};
};
};
pub const ErrorMsg = struct {
byte_offset: usize,
msg: []const u8,
};
pub const Body = struct {
instructions: []*Inst,
};
pub const Module = struct {
decls: []*Decl,
arena: std.heap.ArenaAllocator,
error_msg: ?ErrorMsg = null,
metadata: std.AutoHashMap(*Inst, MetaData),
body_metadata: std.AutoHashMap(*Body, BodyMetaData),
pub const Decl = struct {
name: []const u8,
/// Hash of slice into the source of the part after the = and before the next instruction.
contents_hash: std.zig.SrcHash,
inst: *Inst,
};
pub const MetaData = struct {
deaths: ir.Inst.DeathsInt,
addr: usize,
};
pub const BodyMetaData = struct {
deaths: []*Inst,
};
pub fn deinit(self: *Module, allocator: *Allocator) void {
self.metadata.deinit();
self.body_metadata.deinit();
allocator.free(self.decls);
self.arena.deinit();
self.* = undefined;
}
/// This is a debugging utility for rendering the tree to stderr.
pub fn dump(self: Module) void {
self.writeToStream(std.heap.page_allocator, std.io.getStdErr().writer()) catch {};
}
const DeclAndIndex = struct {
decl: *Decl,
index: usize,
};
/// TODO Look into making a table to speed this up.
pub fn findDecl(self: Module, name: []const u8) ?DeclAndIndex {
for (self.decls) |decl, i| {
if (mem.eql(u8, decl.name, name)) {
return DeclAndIndex{
.decl = decl,
.index = i,
};
}
}
return null;
}
pub fn findInstDecl(self: Module, inst: *Inst) ?DeclAndIndex {
for (self.decls) |decl, i| {
if (decl.inst == inst) {
return DeclAndIndex{
.decl = decl,
.index = i,
};
}
}
return null;
}
/// The allocator is used for temporary storage, but this function always returns
/// with no resources allocated.
pub fn writeToStream(self: Module, allocator: *Allocator, stream: anytype) !void {
var write = Writer{
.module = &self,
.inst_table = InstPtrTable.init(allocator),
.block_table = std.AutoHashMap(*Inst.Block, []const u8).init(allocator),
.loop_table = std.AutoHashMap(*Inst.Loop, []const u8).init(allocator),
.arena = std.heap.ArenaAllocator.init(allocator),
.indent = 2,
.next_instr_index = undefined,
};
defer write.arena.deinit();
defer write.inst_table.deinit();
defer write.block_table.deinit();
defer write.loop_table.deinit();
// First, build a map of *Inst to @ or % indexes
try write.inst_table.ensureCapacity(@intCast(u32, self.decls.len));
for (self.decls) |decl, decl_i| {
try write.inst_table.putNoClobber(decl.inst, .{ .inst = decl.inst, .index = null, .name = decl.name });
}
for (self.decls) |decl, i| {
write.next_instr_index = 0;
try stream.print("@{s} ", .{decl.name});
try write.writeInstToStream(stream, decl.inst);
try stream.writeByte('\n');
}
}
};
const InstPtrTable = std.AutoHashMap(*Inst, struct { inst: *Inst, index: ?usize, name: []const u8 });
const Writer = struct {
module: *const Module,
inst_table: InstPtrTable,
block_table: std.AutoHashMap(*Inst.Block, []const u8),
loop_table: std.AutoHashMap(*Inst.Loop, []const u8),
arena: std.heap.ArenaAllocator,
indent: usize,
next_instr_index: usize,
fn writeInstToStream(
self: *Writer,
stream: anytype,
inst: *Inst,
) (@TypeOf(stream).Error || error{OutOfMemory})!void {
inline for (@typeInfo(Inst.Tag).Enum.fields) |enum_field| {
const expected_tag = @field(Inst.Tag, enum_field.name);
if (inst.tag == expected_tag) {
return self.writeInstToStreamGeneric(stream, expected_tag, inst);
}
}
unreachable; // all tags handled
}
fn writeInstToStreamGeneric(
self: *Writer,
stream: anytype,
comptime inst_tag: Inst.Tag,
base: *Inst,
) (@TypeOf(stream).Error || error{OutOfMemory})!void {
const SpecificInst = inst_tag.Type();
const inst = @fieldParentPtr(SpecificInst, "base", base);
const Positionals = @TypeOf(inst.positionals);
try stream.writeAll("= " ++ @tagName(inst_tag) ++ "(");
const pos_fields = @typeInfo(Positionals).Struct.fields;
inline for (pos_fields) |arg_field, i| {
if (i != 0) {
try stream.writeAll(", ");
}
try self.writeParamToStream(stream, &@field(inst.positionals, arg_field.name));
}
comptime var need_comma = pos_fields.len != 0;
const KW_Args = @TypeOf(inst.kw_args);
inline for (@typeInfo(KW_Args).Struct.fields) |arg_field, i| {
if (@typeInfo(arg_field.field_type) == .Optional) {
if (@field(inst.kw_args, arg_field.name)) |non_optional| {
if (need_comma) try stream.writeAll(", ");
try stream.print("{s}=", .{arg_field.name});
try self.writeParamToStream(stream, &non_optional);
need_comma = true;
}
} else {
if (need_comma) try stream.writeAll(", ");
try stream.print("{s}=", .{arg_field.name});
try self.writeParamToStream(stream, &@field(inst.kw_args, arg_field.name));
need_comma = true;
}
}
try stream.writeByte(')');
}
fn writeParamToStream(self: *Writer, stream: anytype, param_ptr: anytype) !void {
const param = param_ptr.*;
if (@typeInfo(@TypeOf(param)) == .Enum) {
return stream.writeAll(@tagName(param));
}
switch (@TypeOf(param)) {
*Inst => return self.writeInstParamToStream(stream, param),
?*Inst => return self.writeInstParamToStream(stream, param.?),
[]*Inst => {
try stream.writeByte('[');
for (param) |inst, i| {
if (i != 0) {
try stream.writeAll(", ");
}
try self.writeInstParamToStream(stream, inst);
}
try stream.writeByte(']');
},
Body => {
try stream.writeAll("{\n");
if (self.module.body_metadata.get(param_ptr)) |metadata| {
if (metadata.deaths.len > 0) {
try stream.writeByteNTimes(' ', self.indent);
try stream.writeAll("; deaths={");
for (metadata.deaths) |death, i| {
if (i != 0) try stream.writeAll(", ");
try self.writeInstParamToStream(stream, death);
}
try stream.writeAll("}\n");
}
}
for (param.instructions) |inst| {
const my_i = self.next_instr_index;
self.next_instr_index += 1;
try self.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = undefined });
try stream.writeByteNTimes(' ', self.indent);
try stream.print("%{d} ", .{my_i});
if (inst.cast(Inst.Block)) |block| {
const name = try std.fmt.allocPrint(&self.arena.allocator, "label_{d}", .{my_i});
try self.block_table.put(block, name);
} else if (inst.cast(Inst.Loop)) |loop| {
const name = try std.fmt.allocPrint(&self.arena.allocator, "loop_{d}", .{my_i});
try self.loop_table.put(loop, name);
}
self.indent += 2;
try self.writeInstToStream(stream, inst);
if (self.module.metadata.get(inst)) |metadata| {
try stream.print(" ; deaths=0b{b}", .{metadata.deaths});
// This is conditionally compiled in because addresses mess up the tests due
// to Address Space Layout Randomization. It's super useful when debugging
// codegen.zig though.
if (!std.builtin.is_test) {
try stream.print(" 0x{x}", .{metadata.addr});
}
}
self.indent -= 2;
try stream.writeByte('\n');
}
try stream.writeByteNTimes(' ', self.indent - 2);
try stream.writeByte('}');
},
bool => return stream.writeByte("01"[@boolToInt(param)]),
[]u8, []const u8 => return stream.print("\"{}\"", .{std.zig.fmtEscapes(param)}),
BigIntConst, usize => return stream.print("{}", .{param}),
TypedValue => return stream.print("TypedValue{{ .ty = {}, .val = {}}}", .{ param.ty, param.val }),
*IrModule.Decl => return stream.print("Decl({s})", .{param.name}),
*Inst.Block => {
const name = self.block_table.get(param) orelse "!BADREF!";
return stream.print("\"{}\"", .{std.zig.fmtEscapes(name)});
},
*Inst.Loop => {
const name = self.loop_table.get(param).?;
return stream.print("\"{}\"", .{std.zig.fmtEscapes(name)});
},
[][]const u8, []const []const u8 => {
try stream.writeByte('[');
for (param) |str, i| {
if (i != 0) {
try stream.writeAll(", ");
}
try stream.print("\"{}\"", .{std.zig.fmtEscapes(str)});
}
try stream.writeByte(']');
},
[]Inst.SwitchBr.Case => {
if (param.len == 0) {
return stream.writeAll("{}");
}
try stream.writeAll("{\n");
for (param) |*case, i| {
if (i != 0) {
try stream.writeAll(",\n");
}
try stream.writeByteNTimes(' ', self.indent);
self.indent += 2;
try self.writeParamToStream(stream, &case.item);
try stream.writeAll(" => ");
try self.writeParamToStream(stream, &case.body);
self.indent -= 2;
}
try stream.writeByte('\n');
try stream.writeByteNTimes(' ', self.indent - 2);
try stream.writeByte('}');
},
else => |T| @compileError("unimplemented: rendering parameter of type " ++ @typeName(T)),
}
}
fn writeInstParamToStream(self: *Writer, stream: anytype, inst: *Inst) !void {
if (self.inst_table.get(inst)) |info| {
if (info.index) |i| {
try stream.print("%{d}", .{info.index});
} else {
try stream.print("@{s}", .{info.name});
}
} else if (inst.cast(Inst.DeclVal)) |decl_val| {
try stream.print("@{s}", .{decl_val.positionals.decl.name});
} else {
// This should be unreachable in theory, but since ZIR is used for debugging the compiler
// we output some debug text instead.
try stream.print("?{s}?", .{@tagName(inst.tag)});
}
}
};
/// For debugging purposes, prints a function representation to stderr.
pub fn dumpFn(old_module: IrModule, module_fn: *IrModule.Fn) void {
const allocator = old_module.gpa;
var ctx: DumpTzir = .{
.allocator = allocator,
.arena = std.heap.ArenaAllocator.init(allocator),
.old_module = &old_module,
.module_fn = module_fn,
.indent = 2,
.inst_table = DumpTzir.InstTable.init(allocator),
.partial_inst_table = DumpTzir.InstTable.init(allocator),
.const_table = DumpTzir.InstTable.init(allocator),
};
defer ctx.inst_table.deinit();
defer ctx.partial_inst_table.deinit();
defer ctx.const_table.deinit();
defer ctx.arena.deinit();
switch (module_fn.state) {
.queued => std.debug.print("(queued)", .{}),
.inline_only => std.debug.print("(inline_only)", .{}),
.in_progress => std.debug.print("(in_progress)", .{}),
.sema_failure => std.debug.print("(sema_failure)", .{}),
.dependency_failure => std.debug.print("(dependency_failure)", .{}),
.success => {
const writer = std.io.getStdErr().writer();
ctx.dump(module_fn.body, writer) catch @panic("failed to dump TZIR");
},
}
}
const DumpTzir = struct {
allocator: *Allocator,
arena: std.heap.ArenaAllocator,
old_module: *const IrModule,
module_fn: *IrModule.Fn,
indent: usize,
inst_table: InstTable,
partial_inst_table: InstTable,
const_table: InstTable,
next_index: usize = 0,
next_partial_index: usize = 0,
next_const_index: usize = 0,
const InstTable = std.AutoArrayHashMap(*ir.Inst, usize);
/// TODO: Improve this code to include a stack of ir.Body and store the instructions
/// in there. Now we are putting all the instructions in a function local table,
/// however instructions that are in a Body can be thown away when the Body ends.
fn dump(dtz: *DumpTzir, body: ir.Body, writer: std.fs.File.Writer) !void {
// First pass to pre-populate the table so that we can show even invalid references.
// Must iterate the same order we iterate the second time.
// We also look for constants and put them in the const_table.
try dtz.fetchInstsAndResolveConsts(body);
std.debug.print("Module.Function(name={s}):\n", .{dtz.module_fn.owner_decl.name});
for (dtz.const_table.items()) |entry| {
const constant = entry.key.castTag(.constant).?;
try writer.print(" @{d}: {} = {};\n", .{
entry.value, constant.base.ty, constant.val,
});
}
return dtz.dumpBody(body, writer);
}
fn fetchInstsAndResolveConsts(dtz: *DumpTzir, body: ir.Body) error{OutOfMemory}!void {
for (body.instructions) |inst| {
try dtz.inst_table.put(inst, dtz.next_index);
dtz.next_index += 1;
switch (inst.tag) {
.alloc,
.retvoid,
.unreach,
.breakpoint,
.dbg_stmt,
.arg,
=> {},
.ref,
.ret,
.bitcast,
.not,
.is_non_null,
.is_non_null_ptr,
.is_null,
.is_null_ptr,
.is_err,
.is_err_ptr,
.ptrtoint,
.floatcast,
.intcast,
.load,
.optional_payload,
.optional_payload_ptr,
.wrap_optional,
.wrap_errunion_payload,
.wrap_errunion_err,
.unwrap_errunion_payload,
.unwrap_errunion_err,
.unwrap_errunion_payload_ptr,
.unwrap_errunion_err_ptr,
=> {
const un_op = inst.cast(ir.Inst.UnOp).?;
try dtz.findConst(un_op.operand);
},
.add,
.sub,
.mul,
.cmp_lt,
.cmp_lte,
.cmp_eq,
.cmp_gte,
.cmp_gt,
.cmp_neq,
.store,
.bool_and,
.bool_or,
.bit_and,
.bit_or,
.xor,
=> {
const bin_op = inst.cast(ir.Inst.BinOp).?;
try dtz.findConst(bin_op.lhs);
try dtz.findConst(bin_op.rhs);
},
.br => {
const br = inst.castTag(.br).?;
try dtz.findConst(&br.block.base);
try dtz.findConst(br.operand);
},
.br_block_flat => {
const br_block_flat = inst.castTag(.br_block_flat).?;
try dtz.findConst(&br_block_flat.block.base);
try dtz.fetchInstsAndResolveConsts(br_block_flat.body);
},
.br_void => {
const br_void = inst.castTag(.br_void).?;
try dtz.findConst(&br_void.block.base);
},
.block => {
const block = inst.castTag(.block).?;
try dtz.fetchInstsAndResolveConsts(block.body);
},
.condbr => {
const condbr = inst.castTag(.condbr).?;
try dtz.findConst(condbr.condition);
try dtz.fetchInstsAndResolveConsts(condbr.then_body);
try dtz.fetchInstsAndResolveConsts(condbr.else_body);
},
.loop => {
const loop = inst.castTag(.loop).?;
try dtz.fetchInstsAndResolveConsts(loop.body);
},
.call => {
const call = inst.castTag(.call).?;
try dtz.findConst(call.func);
for (call.args) |arg| {
try dtz.findConst(arg);
}
},
// TODO fill out this debug printing
.assembly,
.constant,
.varptr,
.switchbr,
=> {},
}
}
}
fn dumpBody(dtz: *DumpTzir, body: ir.Body, writer: std.fs.File.Writer) (std.fs.File.WriteError || error{OutOfMemory})!void {
for (body.instructions) |inst| {
const my_index = dtz.next_partial_index;
try dtz.partial_inst_table.put(inst, my_index);
dtz.next_partial_index += 1;
try writer.writeByteNTimes(' ', dtz.indent);
try writer.print("%{d}: {} = {s}(", .{
my_index, inst.ty, @tagName(inst.tag),
});
switch (inst.tag) {
.alloc,
.retvoid,
.unreach,
.breakpoint,
.dbg_stmt,
=> try writer.writeAll(")\n"),
.ref,
.ret,
.bitcast,
.not,
.is_non_null,
.is_null,
.is_non_null_ptr,
.is_null_ptr,
.is_err,
.is_err_ptr,
.ptrtoint,
.floatcast,
.intcast,
.load,
.optional_payload,
.optional_payload_ptr,
.wrap_optional,
.wrap_errunion_err,
.wrap_errunion_payload,
.unwrap_errunion_err,
.unwrap_errunion_payload,
.unwrap_errunion_payload_ptr,
.unwrap_errunion_err_ptr,
=> {
const un_op = inst.cast(ir.Inst.UnOp).?;
const kinky = try dtz.writeInst(writer, un_op.operand);
if (kinky != null) {
try writer.writeAll(") // Instruction does not dominate all uses!\n");
} else {
try writer.writeAll(")\n");
}
},
.add,
.sub,
.mul,
.cmp_lt,
.cmp_lte,
.cmp_eq,
.cmp_gte,
.cmp_gt,
.cmp_neq,
.store,
.bool_and,
.bool_or,
.bit_and,
.bit_or,
.xor,
=> {
const bin_op = inst.cast(ir.Inst.BinOp).?;
const lhs_kinky = try dtz.writeInst(writer, bin_op.lhs);
try writer.writeAll(", ");
const rhs_kinky = try dtz.writeInst(writer, bin_op.rhs);
if (lhs_kinky != null or rhs_kinky != null) {
try writer.writeAll(") // Instruction does not dominate all uses!");
if (lhs_kinky) |lhs| {
try writer.print(" %{d}", .{lhs});
}
if (rhs_kinky) |rhs| {
try writer.print(" %{d}", .{rhs});
}
try writer.writeAll("\n");
} else {
try writer.writeAll(")\n");
}
},
.arg => {
const arg = inst.castTag(.arg).?;
try writer.print("{s})\n", .{arg.name});
},
.br => {
const br = inst.castTag(.br).?;
const lhs_kinky = try dtz.writeInst(writer, &br.block.base);
try writer.writeAll(", ");
const rhs_kinky = try dtz.writeInst(writer, br.operand);
if (lhs_kinky != null or rhs_kinky != null) {
try writer.writeAll(") // Instruction does not dominate all uses!");
if (lhs_kinky) |lhs| {
try writer.print(" %{d}", .{lhs});
}
if (rhs_kinky) |rhs| {
try writer.print(" %{d}", .{rhs});
}
try writer.writeAll("\n");
} else {
try writer.writeAll(")\n");
}
},
.br_block_flat => {
const br_block_flat = inst.castTag(.br_block_flat).?;
const block_kinky = try dtz.writeInst(writer, &br_block_flat.block.base);
if (block_kinky != null) {
try writer.writeAll(", { // Instruction does not dominate all uses!\n");
} else {
try writer.writeAll(", {\n");
}
const old_indent = dtz.indent;
dtz.indent += 2;
try dtz.dumpBody(br_block_flat.body, writer);
dtz.indent = old_indent;
try writer.writeByteNTimes(' ', dtz.indent);
try writer.writeAll("})\n");
},
.br_void => {
const br_void = inst.castTag(.br_void).?;
const kinky = try dtz.writeInst(writer, &br_void.block.base);
if (kinky) |_| {
try writer.writeAll(") // Instruction does not dominate all uses!\n");
} else {
try writer.writeAll(")\n");
}
},
.block => {
const block = inst.castTag(.block).?;
try writer.writeAll("{\n");
const old_indent = dtz.indent;
dtz.indent += 2;
try dtz.dumpBody(block.body, writer);
dtz.indent = old_indent;
try writer.writeByteNTimes(' ', dtz.indent);
try writer.writeAll("})\n");
},
.condbr => {
const condbr = inst.castTag(.condbr).?;
const condition_kinky = try dtz.writeInst(writer, condbr.condition);
if (condition_kinky != null) {
try writer.writeAll(", { // Instruction does not dominate all uses!\n");
} else {
try writer.writeAll(", {\n");
}
const old_indent = dtz.indent;
dtz.indent += 2;
try dtz.dumpBody(condbr.then_body, writer);
try writer.writeByteNTimes(' ', old_indent);
try writer.writeAll("}, {\n");
try dtz.dumpBody(condbr.else_body, writer);
dtz.indent = old_indent;
try writer.writeByteNTimes(' ', old_indent);
try writer.writeAll("})\n");
},
.loop => {
const loop = inst.castTag(.loop).?;
try writer.writeAll("{\n");
const old_indent = dtz.indent;
dtz.indent += 2;
try dtz.dumpBody(loop.body, writer);
dtz.indent = old_indent;
try writer.writeByteNTimes(' ', dtz.indent);
try writer.writeAll("})\n");
},
.call => {
const call = inst.castTag(.call).?;
const args_kinky = try dtz.allocator.alloc(?usize, call.args.len);
defer dtz.allocator.free(args_kinky);
std.mem.set(?usize, args_kinky, null);
var any_kinky_args = false;
const func_kinky = try dtz.writeInst(writer, call.func);
for (call.args) |arg, i| {
try writer.writeAll(", ");
args_kinky[i] = try dtz.writeInst(writer, arg);
any_kinky_args = any_kinky_args or args_kinky[i] != null;
}
if (func_kinky != null or any_kinky_args) {
try writer.writeAll(") // Instruction does not dominate all uses!");
if (func_kinky) |func_index| {
try writer.print(" %{d}", .{func_index});
}
for (args_kinky) |arg_kinky| {
if (arg_kinky) |arg_index| {
try writer.print(" %{d}", .{arg_index});
}
}
try writer.writeAll("\n");
} else {
try writer.writeAll(")\n");
}
},
// TODO fill out this debug printing
.assembly,
.constant,
.varptr,
.switchbr,
=> {
try writer.writeAll("!TODO!)\n");
},
}
}
}
fn writeInst(dtz: *DumpTzir, writer: std.fs.File.Writer, inst: *ir.Inst) !?usize {
if (dtz.partial_inst_table.get(inst)) |operand_index| {
try writer.print("%{d}", .{operand_index});
return null;
} else if (dtz.const_table.get(inst)) |operand_index| {
try writer.print("@{d}", .{operand_index});
return null;
} else if (dtz.inst_table.get(inst)) |operand_index| {
try writer.print("%{d}", .{operand_index});
return operand_index;
} else {
try writer.writeAll("!BADREF!");
return null;
}
}
fn findConst(dtz: *DumpTzir, operand: *ir.Inst) !void {
if (operand.tag == .constant) {
try dtz.const_table.put(operand, dtz.next_const_index);
dtz.next_const_index += 1;
}
}
};
/// For debugging purposes, like dumpFn but for unanalyzed zir blocks
pub fn dumpZir(allocator: *Allocator, kind: []const u8, decl_name: [*:0]const u8, instructions: []*Inst) !void {
var fib = std.heap.FixedBufferAllocator.init(&[_]u8{});
var module = Module{
.decls = &[_]*Module.Decl{},
.arena = std.heap.ArenaAllocator.init(&fib.allocator),
.metadata = std.AutoHashMap(*Inst, Module.MetaData).init(&fib.allocator),
.body_metadata = std.AutoHashMap(*Body, Module.BodyMetaData).init(&fib.allocator),
};
var write = Writer{
.module = &module,
.inst_table = InstPtrTable.init(allocator),
.block_table = std.AutoHashMap(*Inst.Block, []const u8).init(allocator),
.loop_table = std.AutoHashMap(*Inst.Loop, []const u8).init(allocator),
.arena = std.heap.ArenaAllocator.init(allocator),
.indent = 4,
.next_instr_index = 0,
};
defer write.arena.deinit();
defer write.inst_table.deinit();
defer write.block_table.deinit();
defer write.loop_table.deinit();
try write.inst_table.ensureCapacity(@intCast(u32, instructions.len));
const stderr = std.io.getStdErr().writer();
try stderr.print("{s} {s} {{ // unanalyzed\n", .{ kind, decl_name });
for (instructions) |inst| {
const my_i = write.next_instr_index;
write.next_instr_index += 1;
if (inst.cast(Inst.Block)) |block| {
const name = try std.fmt.allocPrint(&write.arena.allocator, "label_{d}", .{my_i});
try write.block_table.put(block, name);
} else if (inst.cast(Inst.Loop)) |loop| {
const name = try std.fmt.allocPrint(&write.arena.allocator, "loop_{d}", .{my_i});
try write.loop_table.put(loop, name);
}
try write.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = "inst" });
try stderr.print(" %{d} ", .{my_i});
try write.writeInstToStream(stderr, inst);
try stderr.writeByte('\n');
}
try stderr.print("}} // {s} {s}\n\n", .{ kind, decl_name });
} | src/zir.zig |
const std = @import("std");
const expect = std.testing.expect;
const str = []const u8;
const tools = @import("tools.zig");
const streql = tools.streql;
/// A "formatted struct" encapsulates a complex type like slice, array or struct
/// into a new struct that defines how it can be parsed.
/// If a struct has this enum in its declarations, it is a formatted struct.
const FormattedStruct = enum {
join_struct,
match_struct,
};
/// Join(T, sep) returns a formatted struct given a type T.
/// It specifies that the elements in the type T are separated by S.
pub fn Join(comptime T: type, comptime sep: str) type {
//TODO Join(u32, " ") makes no sense b/c u32 is not composed of several
// elements. I tried to return TypeError in this case, but keyword try
// is not accepted in struct definition. Which means that every Join()
// types should be pre-declared in consts... the thing becomes cumbersome?
// switch (@typeInfo(T)) {
// .Struct, .Pointer, .Array => {},
// else => return TypeError.TypeError,
// }
return struct {
child: T,
pub const fmt_struct: FormattedStruct = .join_struct;
pub const child_type: type = T;
pub fn tokenize(val: str) std.mem.TokenIterator {
return std.mem.tokenize(val, sep);
}
};
}
/// A formatted struct that matches a string without storing data.
/// Useful to assert that some syntactic element (keyword, brackets, ...) is
/// present.
pub fn Match(comptime match: str) type {
return struct {
// no fields! no data.
pub const fmt_struct: FormattedStruct = .match_struct;
pub const to_match = match;
};
}
/// Returns true if the struct T contains any nested formatted struct.
pub fn isFormattedStruct(comptime T: type) bool {
if (@typeInfo(T) != .Struct)
return false;
inline for (@typeInfo(T).Struct.decls) |decl, i| {
if (decl.data == .Var) {
if (decl.data.Var == FormattedStruct) {
return true;
}
}
}
return false;
}
/// When we parse a formatted struct of type T, we want to return the unformatted type Unformat(T). Indeed, formatted types are cumbersome (they add one nesting level per formatted struct) and are not what the user want to obtain in the end.
/// This helper casts all the a new type cast converts
pub fn castUnformatRecur(comptime T: type, parsed: *T, unformatted: *Unformat(T)) void {
const typeinfo_T = @typeInfo(T);
switch (typeinfo_T) {
.Struct => {
comptime const is_formatted_struct = isFormattedStruct(T);
if (!is_formatted_struct) {
inline for (typeinfo_T.Struct.fields) |f, i| {
// this is not a formatted struct, so both formatted and
// unformatted structs should have the same field names
const corresponding_field_name = @typeInfo(Unformat(T)).Struct.fields[i].name;
comptime expect(streql(f.name, corresponding_field_name));
comptime expect(T == @TypeOf(parsed.*));
castUnformatRecur(
f.field_type,
&@field(parsed.*, f.name),
&@field(unformatted.*, f.name),
);
}
} else if (is_formatted_struct) {
if (T.fmt_struct == .join_struct) {
const cast = @ptrCast(*Unformat(T), &(parsed.*.child));
unformatted.* = cast.*;
} else if (T.fmt_struct == .match_struct) {
// do nothing: match structs do not hold data.
}
}
},
.Pointer => {
castUnformatRecur(
typeinfo_T.Pointer.child,
parsed.*,
unformatted.*,
);
},
else => {
unformatted.* = parsed.*;
},
}
}
/// Transform a formatted struct, or any type containing nested formatted
/// structs, into a type without.
pub fn Unformat(comptime T: type) type {
comptime var typeinfo = @typeInfo(T);
switch (typeinfo) {
.Struct => {
comptime const is_fmt_struct: bool = isFormattedStruct(T);
if (is_fmt_struct) {
if (T.fmt_struct == .join_struct) {
return Unformat(T.child_type);
}
}
// return a new type where all fields are recursively Unformatted
// Match fields should be ommited, so we are going to count them
const fields = typeinfo.Struct.fields;
const StructField = std.builtin.TypeInfo.StructField;
comptime var new_fields: [fields.len]StructField = undefined;
comptime var fields_have_changed: bool = false;
std.mem.copy(StructField, new_fields[0..], fields);
// if the type is already unformatted and Unformat(T) = T, we do
// not want to recreate a new type with a different name: we
// simply return the current type.
comptime var i: u32 = 0;
inline for (fields) |f, j| {
const unfmt_type = Unformat(f.field_type);
new_fields[j].field_type = unfmt_type;
if (f.field_type != unfmt_type) { // type has been modified:
fields_have_changed = true;
new_fields[j].default_value = null; //nested_type
}
}
if (!fields_have_changed) {
return T;
}
// TODO Warning! The new type can't have decls! Limitation of @Type
// at least until Zig 0.7
const dummy_decls: [0]std.builtin.TypeInfo.Declaration = undefined;
const s = std.builtin.TypeInfo.Struct{
.layout = typeinfo.Struct.layout,
.fields = new_fields[0..],
.decls = &dummy_decls,
.is_tuple = typeinfo.Struct.is_tuple,
};
const nested_type = @Type(std.builtin.TypeInfo{
.Struct = s,
});
return nested_type;
},
.Pointer => {
// TODO: why doesn't the following work?:
// return *Unformat(typeinfo.Pointer.child);
const tp = typeinfo.Pointer;
var s: std.builtin.TypeInfo.Pointer = tp;
s.child = Unformat(tp.child);
return @Type(std.builtin.TypeInfo{ .Pointer = s });
},
.Array => {
const tp = typeinfo.Array;
var s: std.builtin.TypeInfo.Array = tp;
s.child = Unformat(tp.child);
return @Type(std.builtin.TypeInfo{ .Array = s });
},
.Int => return T,
else => return T,
}
}
test "join and unformat" {
const u32_joined: type = Join([]u32, " ");
expect(isFormattedStruct(u32_joined));
const ufmt_u: type = Unformat(u32_joined);
expect(ufmt_u == []u32);
const ufmt: type = Unformat(u32);
expect(ufmt == u32);
} | src/fmt_structs.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const parseInt = @import("parseInt.zig").parse;
const inputRules =
\\light red bags contain 1 bright white bag, 2 muted yellow bags.
\\dark orange bags contain 3 bright white bags, 4 muted yellow bags.
\\bright white bags contain 1 shiny gold bag.
\\muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
\\shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
\\dark olive bags contain 3 faded blue bags, 4 dotted black bags.
\\vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
\\faded blue bags contain no other bags.
\\dotted black bags contain no other bags.
;
const inputRules2 =
\\shiny gold bags contain 2 dark red bags.
\\dark red bags contain 2 dark orange bags.
\\dark orange bags contain 2 dark yellow bags.
\\dark yellow bags contain 2 dark green bags.
\\dark green bags contain 2 dark blue bags.
\\dark blue bags contain 2 dark violet bags.
\\dark violet bags contain no other bags.
;
// const inputRules = @embedFile("input07.txt");
fn lineIterator(string: []const u8) std.mem.TokenIterator {
return std.mem.tokenize(string, "\n\r");
}
const RulePair = struct {
count: u32,
name: []const u8,
};
const Rule = struct {
name: []const u8,
contains: std.ArrayList(RulePair),
};
fn parseBag(line: []const u8, tokens: *std.mem.TokenIterator) []const u8 {
var namePart1 = tokens.next().?;
var namePart2 = tokens.next().?;
return line[0 .. namePart1.len + namePart2.len + 1];
}
const RuleIterator = struct {
buffer: []const u8,
position: usize,
tokens: *std.mem.TokenIterator,
isFinished: bool = false,
pub fn init(line: []const u8, tokens: *std.mem.TokenIterator) RuleIterator {
return .{
.buffer = line,
.position = 0,
.tokens = tokens,
};
}
fn next(self: *RuleIterator) ?RulePair {
if (self.isFinished)
return null;
var number = self.tokens.next().?;
if (std.mem.eql(u8, number, "no")) //Contains no rules.
return null;
self.position += number.len + 1;
var color = parseBag(self.buffer[self.position..], self.tokens);
self.position += color.len + 1;
var bags = self.tokens.next().?;
if (std.mem.eql(u8, bags, "bags.") or std.mem.eql(u8, bags, "bag.")) {
self.isFinished = true;
} else {
self.position += bags.len + 1;
}
return RulePair{
.count = parseInt(u32, number, 10) catch return null,
.name = color,
};
}
};
fn parseLine(allocator: *Allocator, line: []const u8) !Rule {
var rule: Rule = undefined;
var tokens = std.mem.tokenize(line, " ");
rule.name = parseBag(line, &tokens);
var bags = tokens.next().?;
if (!std.mem.eql(u8, bags, "bags"))
unreachable;
_ = tokens.next().?; //ignore the "contain" word.
var linePointer = line[rule.name.len + " bags contain ".len ..];
rule.contains = std.ArrayList(RulePair).init(allocator);
var ruleIterator = RuleIterator.init(linePointer, &tokens);
while (ruleIterator.next()) |r|
try rule.contains.append(r);
return rule;
}
fn getAllRules(allocator: *Allocator, input: []const u8) ![]Rule {
var rules = std.ArrayList(Rule).init(allocator);
defer rules.deinit();
var lines = lineIterator(input);
while (lines.next()) |line| {
var rule = try parseLine(allocator, line);
try rules.append(rule);
}
return rules.toOwnedSlice();
}
fn part1() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
defer _ = gpa.deinit();
var map = std.StringHashMap(Rule).init(allocator);
defer map.deinit();
var queue = std.PriorityQueue([]const u8).init(allocator, stringCompareFn);
var canContain = std.StringHashMap(bool).init(allocator);
var rules = try getAllRules(allocator, inputRules);
for (rules) |rule| {
var canContainShinyGold = false;
if (map.contains(rule.name)) {
print("RULES CAN BE DUPLICATED: {s}!\n", .{rule.name});
unreachable;
}
print("[{s}]", .{rule.name});
for (rule.contains.items) |i| {
print(", {s}: {d}", .{ i.name, i.count });
if (std.mem.eql(u8, i.name, "shiny gold")) {
canContainShinyGold = true;
}
}
print("\n", .{});
if (canContainShinyGold) {
try canContain.put(rule.name, true);
try queue.add(rule.name);
} else {
try map.put(rule.name, rule);
try canContain.put(rule.name, false);
}
}
print("\n\n", .{});
while (queue.count() > 0) {
var bag = queue.remove();
print("Bag: {s}\n", .{bag});
var keys = map.keyIterator();
while (keys.next()) |key| {
var rule = map.get(key.*).?; //No need to check, key _should_ be there.
for (rule.contains.items) |i| containsFor: {
if (canContain.get(i.name).?) {
try queue.add(rule.name);
_ = map.remove(rule.name);
try canContain.put(rule.name, true);
break :containsFor;
}
}
}
}
print("\nCan contain:\n", .{});
var count: usize = 0;
var keys = canContain.keyIterator();
while (keys.next()) |key| {
if (canContain.get(key.*).?) {
count += 1;
print(" - {s}\n", .{key.*});
}
}
print("\nIn total, {d} bags can contain shiny gold bags.\n", .{count});
}
fn stringCompareFn(string1: []const u8, string2: []const u8) std.math.Order {
return std.mem.order(u8, string1, string2);
}
fn part2() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = &gpa.allocator;
// defer _ = gpa.deinit();
var rules = try getAllRules(allocator, inputRules);
defer allocator.free(rules);
var map = std.StringHashMap(Rule).init(allocator);
defer map.deinit();
const Pair = struct { count: usize, rule: *Rule };
var queue = std.TailQueue(Pair){};
var arenaAllocator = std.heap.ArenaAllocator.init(allocator);
for (rules) |rule| {
try map.put(rule.name, rule);
print("[{s}]", .{rule.name});
for (rule.contains.items) |i| {
print(", {d}, {s}", .{ i.count, i.name });
}
print("\n", .{});
}
{
var sg = map.get("shiny gold").?;
var node = try arenaAllocator.allocator.create(std.TailQueue(Pair).Node);
node.data = .{ .count = 1, .rule = &sg };
queue.append(node);
}
print("\n\n", .{});
var total: usize = 0;
while (queue.len > 0) {
var node = queue.pop().?;
var pair = node.data;
var contains = pair.rule.contains;
print("-> {d}: {s}\n", .{ pair.count, pair.rule.name });
var subTotal: usize = pair.count;
if (contains.items.len > 0) {
for (contains.items) |i| {
var r = map.get(i.name).?;
var newNode = try arenaAllocator.allocator.create(std.TailQueue(Pair).Node);
newNode.data = .{ .count = pair.count + i.count * pair.count, .rule = &r };
subTotal += i.count * pair.count;
queue.append(newNode);
}
}
print("Adding to total: {d}, {s}\n", .{ pair.count, pair.rule.name });
total += subTotal;
arenaAllocator.allocator.destroy(node);
}
arenaAllocator.deinit();
print("\n\nTotal: {d}\n", .{total - 1});
}
pub fn main() !void {
// try part1();
try part2();
} | src/day07.zig |
const std = @import("std");
const upaya = @import("upaya");
const ts = @import("../tilescript.zig");
usingnamespace @import("imgui");
const brushes_win = @import("brushes.zig");
var buffer: [25]u8 = undefined;
pub fn draw(state: *ts.AppState) void {
igPushStyleVarVec2(ImGuiStyleVar_WindowMinSize, ImVec2{ .x = 200, .y = 200 });
defer igPopStyleVar(1);
if (state.prefs.windows.animations and igBegin("Animations", &state.prefs.windows.animations, ImGuiWindowFlags_None)) {
defer igEnd();
if (igBeginChildEx("##animations-child", igGetItemID(), ImVec2{ .y = -igGetFrameHeightWithSpacing() }, false, ImGuiWindowFlags_None)) {
defer igEndChild();
var delete_index: usize = std.math.maxInt(usize);
for (state.map.animations.items) |*anim, i| {
igPushIDInt(@intCast(c_int, i));
if (ts.tileImageButton(state, 16, anim.tile)) {
igOpenPopup("tile-chooser");
}
igSameLine(0, 5);
if (ogButton("Tiles")) {
igOpenPopup("animation-tiles");
}
igSameLine(0, 5);
igPushItemWidth(75);
_ = ogDragUnsignedFormat(u16, "", &anim.rate, 1, 0, std.math.maxInt(u16), "%dms");
igPopItemWidth();
igSameLine(igGetWindowContentRegionWidth() - 20, 0);
if (ogButton(icons.trash)) {
delete_index = i;
}
igSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 });
if (igBeginPopup("tile-chooser", ImGuiWindowFlags_None)) {
animTileSelectorPopup(state, anim, .single);
igEndPopup();
}
igSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 });
if (igBeginPopup("animation-tiles", ImGuiWindowFlags_None)) {
animTileSelectorPopup(state, anim, .multi);
igEndPopup();
}
igPopID();
}
if (delete_index < std.math.maxInt(usize)) {
_ = state.map.animations.orderedRemove(delete_index);
}
}
if (igButton("Add Animation", ImVec2{})) {
igOpenPopup("add-anim");
}
igSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 });
if (igBeginPopup("add-anim", ImGuiWindowFlags_None)) {
addAnimationPopup(state);
igEndPopup();
}
}
}
fn addAnimationPopup(state: *ts.AppState) void {
var content_start_pos = ogGetCursorScreenPos();
const zoom: usize = if (state.texture.width < 200 and state.texture.height < 200) 2 else 1;
ogImage(state.texture.imTextureID(), state.texture.width * @intCast(i32, zoom), state.texture.height * @intCast(i32, zoom));
if (igIsItemHovered(ImGuiHoveredFlags_None)) {
if (igIsMouseClicked(ImGuiMouseButton_Left, false)) {
var tile = ts.tileIndexUnderMouse(@intCast(usize, state.map.tile_size * zoom), content_start_pos);
var tile_index = @intCast(u8, tile.x + tile.y * state.tilesPerRow());
state.map.addAnimation(tile_index);
igCloseCurrentPopup();
}
}
}
fn animTileSelectorPopup(state: *ts.AppState, anim: *ts.data.Animation, selection_type: enum { single, multi }) void {
const per_row = state.tilesPerRow();
var content_start_pos = ogGetCursorScreenPos();
const zoom: usize = if (state.texture.width < 200 and state.texture.height < 200) 2 else 1;
const tile_spacing = state.map.tile_spacing * zoom;
const tile_size = state.map.tile_size * zoom;
ogImage(state.texture.imTextureID(), state.texture.width * @intCast(i32, zoom), state.texture.height * @intCast(i32, zoom));
const draw_list = igGetWindowDrawList();
// draw selected tile or tiles
if (selection_type == .multi) {
var iter = anim.tiles.iter();
while (iter.next()) |value| {
ts.addTileToDrawList(tile_size, content_start_pos, value, per_row, tile_spacing);
}
} else {
ts.addTileToDrawList(tile_size, content_start_pos, anim.tile, per_row, tile_spacing);
}
// check input for toggling state
if (igIsItemHovered(ImGuiHoveredFlags_None)) {
if (igIsMouseClicked(ImGuiMouseButton_Left, false)) {
var tile = ts.tileIndexUnderMouse(@intCast(usize, tile_size + tile_spacing), content_start_pos);
var tile_index = @intCast(u8, tile.x + tile.y * per_row);
if (selection_type == .multi) {
anim.toggleSelected(tile_index);
} else {
anim.tile = tile_index;
igCloseCurrentPopup();
}
}
}
if (selection_type == .multi and igButton("Clear", ImVec2{ .x = -1 })) {
anim.tiles.clear();
}
} | tilescript/windows/animations.zig |
const std = @import("std");
const DW = std.dwarf;
// zig fmt: off
pub const Register = enum(u8) {
// 0 through 7, 32-bit registers. id is int value
eax, ecx, edx, ebx, esp, ebp, esi, edi,
// 8-15, 16-bit registers. id is int value - 8.
ax, cx, dx, bx, sp, bp, si, di,
// 16-23, 8-bit registers. id is int value - 16.
al, cl, dl, bl, ah, ch, dh, bh,
/// Returns the bit-width of the register.
pub fn size(self: @This()) u7 {
return switch (@enumToInt(self)) {
0...7 => 32,
8...15 => 16,
16...23 => 8,
else => unreachable,
};
}
/// Returns the register's id. This is used in practically every opcode the
/// x86 has. It is embedded in some instructions, such as the `B8 +rd` move
/// instruction, and is used in the R/M byte.
pub fn id(self: @This()) u3 {
return @truncate(u3, @enumToInt(self));
}
/// Returns the index into `callee_preserved_regs`.
pub fn allocIndex(self: Register) ?u4 {
return switch (self) {
.eax, .ax, .al => 0,
.ecx, .cx, .cl => 1,
.edx, .dx, .dl => 2,
.esi, .si => 3,
.edi, .di => 4,
else => null,
};
}
/// Convert from any register to its 32 bit alias.
pub fn to32(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()));
}
/// Convert from any register to its 16 bit alias.
pub fn to16(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()) + 8);
}
/// Convert from any register to its 8 bit alias.
pub fn to8(self: Register) Register {
return @intToEnum(Register, @as(u8, self.id()) + 16);
}
pub fn dwarfLocOp(reg: Register) u8 {
return switch (reg.to32()) {
.eax => DW.OP_reg0,
.ecx => DW.OP_reg1,
.edx => DW.OP_reg2,
.ebx => DW.OP_reg3,
.esp => DW.OP_reg4,
.ebp => DW.OP_reg5,
.esi => DW.OP_reg6,
.edi => DW.OP_reg7,
else => unreachable,
};
}
};
// zig fmt: on
pub const callee_preserved_regs = [_]Register{ .eax, .ecx, .edx, .esi, .edi };
// TODO add these to Register enum and corresponding dwarfLocOp
// // Return Address register. This is stored in `0(%esp, "")` and is not a physical register.
// RA = (8, "RA"),
//
// ST0 = (11, "st0"),
// ST1 = (12, "st1"),
// ST2 = (13, "st2"),
// ST3 = (14, "st3"),
// ST4 = (15, "st4"),
// ST5 = (16, "st5"),
// ST6 = (17, "st6"),
// ST7 = (18, "st7"),
//
// XMM0 = (21, "xmm0"),
// XMM1 = (22, "xmm1"),
// XMM2 = (23, "xmm2"),
// XMM3 = (24, "xmm3"),
// XMM4 = (25, "xmm4"),
// XMM5 = (26, "xmm5"),
// XMM6 = (27, "xmm6"),
// XMM7 = (28, "xmm7"),
//
// MM0 = (29, "mm0"),
// MM1 = (30, "mm1"),
// MM2 = (31, "mm2"),
// MM3 = (32, "mm3"),
// MM4 = (33, "mm4"),
// MM5 = (34, "mm5"),
// MM6 = (35, "mm6"),
// MM7 = (36, "mm7"),
//
// MXCSR = (39, "mxcsr"),
//
// ES = (40, "es"),
// CS = (41, "cs"),
// SS = (42, "ss"),
// DS = (43, "ds"),
// FS = (44, "fs"),
// GS = (45, "gs"),
//
// TR = (48, "tr"),
// LDTR = (49, "ldtr"),
//
// FS_BASE = (93, "fs.base"),
// GS_BASE = (94, "gs.base"), | src/codegen/x86.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const data = @embedFile("../inputs/day08.txt");
pub fn main() anyerror!void {
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_impl.deinit();
const gpa = gpa_impl.allocator();
return main_with_allocator(gpa);
}
pub fn main_with_allocator(allocator: Allocator) anyerror!void {
const segments = try parse(allocator, data[0..]);
defer segments.deinit();
print("Part 1: {d}\n", .{part1(segments.items)});
print("Part 2: {d}\n", .{part2(segments.items)});
}
const Segment = struct {
unique_signals: [10][]const u8,
output: [4][]const u8,
};
fn parse(allocator: Allocator, input: []const u8) !std.ArrayList(Segment) {
var out = std.ArrayList(Segment).init(allocator);
var lines = std.mem.tokenize(u8, input, "\n");
while (lines.next()) |line| {
var segment: Segment = undefined;
var parts = std.mem.split(u8, line, " | ");
var unique_signals = std.mem.tokenize(u8, parts.next().?, " ");
for (segment.unique_signals) |*signal| {
signal.* = unique_signals.next().?;
}
var output = std.mem.tokenize(u8, parts.next().?, " ");
for (segment.output) |*o| {
o.* = output.next().?;
}
try out.append(segment);
}
return out;
}
fn part1(segments: []const Segment) usize {
var count: usize = 0;
for (segments) |segment| {
for (segment.output) |output| {
const l = output.len;
const digit_1 = l == 2;
const digit_4 = l == 4;
const digit_7 = l == 3;
const digit_8 = l == 7;
if (digit_1 or digit_4 or digit_7 or digit_8) count += 1;
}
}
return count;
}
fn part2(segments: []const Segment) usize {
var sum: usize = 0;
for (segments) |segment| {
sum += solve(segment);
}
return sum;
}
const BitSet = std.bit_set.IntegerBitSet(7);
fn idx(c: u8) usize {
return @as(usize, c - 'a');
}
fn digit(comptime n: usize) BitSet {
comptime var out = BitSet.initEmpty();
comptime {
switch (n) {
0 => {
out.set(idx('a'));
out.set(idx('b'));
out.set(idx('c'));
out.set(idx('e'));
out.set(idx('f'));
out.set(idx('g'));
},
1 => {
out.set(idx('c'));
out.set(idx('f'));
},
2 => {
out.set(idx('a'));
out.set(idx('c'));
out.set(idx('d'));
out.set(idx('e'));
out.set(idx('g'));
},
3 => {
out.set(idx('a'));
out.set(idx('c'));
out.set(idx('d'));
out.set(idx('f'));
out.set(idx('g'));
},
4 => {
out.set(idx('b'));
out.set(idx('c'));
out.set(idx('d'));
out.set(idx('f'));
},
5 => {
out.set(idx('a'));
out.set(idx('b'));
out.set(idx('d'));
out.set(idx('f'));
out.set(idx('g'));
},
6 => {
out.set(idx('a'));
out.set(idx('b'));
out.set(idx('d'));
out.set(idx('e'));
out.set(idx('f'));
out.set(idx('g'));
},
7 => {
out.set(idx('a'));
out.set(idx('c'));
out.set(idx('f'));
},
8 => {
out.set(idx('a'));
out.set(idx('b'));
out.set(idx('c'));
out.set(idx('d'));
out.set(idx('e'));
out.set(idx('f'));
out.set(idx('g'));
},
9 => {
out.set(idx('a'));
out.set(idx('b'));
out.set(idx('c'));
out.set(idx('d'));
out.set(idx('f'));
out.set(idx('g'));
},
else => @panic("Only digits 0..9 supported"),
}
}
return out;
}
fn get_possibilities(signal: []const u8) BitSet {
switch (signal.len) {
2 => {
return digit(1);
},
3 => {
return digit(7);
},
4 => {
return digit(4);
},
5 => {
comptime var possibilities = BitSet.initEmpty();
comptime {
possibilities.setUnion(digit(2));
possibilities.setUnion(digit(3));
possibilities.setUnion(digit(5));
}
return possibilities;
},
6 => {
comptime var possibilities = BitSet.initEmpty();
comptime {
possibilities.setUnion(digit(0));
possibilities.setUnion(digit(6));
possibilities.setUnion(digit(9));
}
return possibilities;
},
7 => {
return digit(8);
},
else => @panic("Invalid input"),
}
}
fn decode(input: []const u8, mapping: [7]usize) ?usize {
var bit_set = BitSet.initEmpty();
for (input) |c| {
bit_set.set(mapping[idx(c)]);
}
comptime var d: usize = 0;
inline while (d < 10) : (d += 1) {
if (bit_set.mask == digit(d).mask) return d;
}
return null;
}
fn search(mapping: [7]?usize, possibilities: [7]BitSet, segment: Segment) ?[7]usize {
var out: [7]usize = undefined;
var next: usize = 0;
for (mapping) |mo, i| {
if (mo) |m| {
out[i] = m;
next = i + 1;
} else {
break;
}
}
// Done
if (next == 7) return out;
var it = possibilities[next].iterator(.{});
while (it.next()) |n| {
var already_used = false;
for (out[0..next]) |x| {
if (x == n) {
already_used = true;
break;
}
}
if (!already_used) {
var rec_mapping: [7]?usize = undefined;
for (rec_mapping) |*r, i| {
if (i < next) {
r.* = out[i];
} else if (i == next) {
r.* = n;
} else {
r.* = mapping[i];
}
}
if (search(rec_mapping, possibilities, segment)) |result| {
var all_valid = true;
for (segment.unique_signals) |signal| {
if (decode(signal, result) == null) {
all_valid = false;
break;
}
}
for (segment.output) |output| {
if (decode(output, result) == null) {
all_valid = false;
break;
}
}
if (all_valid) return result;
}
}
}
return null;
}
fn solve(segment: Segment) usize {
// For each wire, what locations are possible
var possibilities = [_]BitSet{BitSet.initFull()} ** 7;
for (segment.unique_signals) |signal| {
const ps = get_possibilities(signal);
for (signal) |c| {
possibilities[idx(c)].setIntersection(ps);
}
}
for (segment.output) |output| {
const ps = get_possibilities(output);
for (output) |c| {
possibilities[idx(c)].setIntersection(ps);
}
}
const mapping = search([_]?usize{null} ** 7, possibilities, segment).?;
var out: usize = 0;
for (segment.output) |o| {
out *= 10;
out += decode(o, mapping).?;
}
return out;
}
test "7-segments" {
const input =
\\be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
\\edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
\\fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
\\fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
\\aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
\\fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
\\dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
\\bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
\\egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
\\gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
;
const allocator = std.testing.allocator;
const segments = try parse(allocator, input[0..]);
defer segments.deinit();
try std.testing.expectEqual(@as(usize, 26), part1(segments.items));
try std.testing.expectEqual(@as(usize, 61229), part2(segments.items));
} | src/day08.zig |
const std = @import("std");
const ansi = @import("ansi");
const range = @import("range").range;
pub fn answer(out: anytype, comptime prompt: []const u8, comptime T: type, comptime valfmt: []const u8, value: T) !T {
try out.print(comptime ansi.color.Fg(.Green, "? "), .{});
try out.print(comptime ansi.color.Bold(prompt ++ " "), .{});
try out.print(comptime ansi.color.Fg(.Cyan, valfmt ++ "\n"), .{value});
return value;
}
const PromptRet = struct {
n: usize,
value: []const u8,
};
fn doprompt(out: anytype, in: anytype, alloc: std.mem.Allocator, default: ?[]const u8) !PromptRet {
var n: usize = 1;
var value: []const u8 = undefined;
while (true) : (n += 1) {
try out.print(comptime ansi.color.Faint("> "), .{});
var input: []const u8 = try in.readUntilDelimiterAlloc(alloc, '\n', 100);
input = std.mem.trimRight(u8, input, "\r\n");
if (input.len == 0) if (default) |d| {
value = d;
break;
};
if (input.len > 0) {
value = input;
break;
}
}
return PromptRet{ .n = n, .value = value };
}
fn clean(out: anytype, n: usize) !void {
for (range(n)) |_| {
try out.print(comptime ansi.csi.CursorUp(1), .{});
try out.print(comptime ansi.csi.EraseInLine(0), .{});
}
}
pub fn forEnum(out: anytype, in: anytype, comptime prompt: []const u8, alloc: std.mem.Allocator, comptime options: type, default: ?options) !options {
comptime std.debug.assert(@typeInfo(options) == .Enum);
const def: ?[]const u8 = if (default) |d| @tagName(d) else null;
try out.print(comptime ansi.color.Fg(.Green, "? "), .{});
try out.print(comptime ansi.color.Bold(prompt ++ " "), .{});
try out.print(ansi.style.Faint ++ "(", .{});
inline for (std.meta.fields(options)) |f, i| {
if (i != 0) try out.print("/", .{});
if (std.mem.eql(u8, f.name, def orelse "")) {
try out.print(ansi.style.ResetIntensity, .{});
try out.print(comptime ansi.color.Fg(.Cyan, f.name), .{});
try out.print(ansi.style.Faint, .{});
} else try out.print(f.name, .{});
}
try out.print(")" ++ ansi.style.ResetIntensity ++ " ", .{});
var value: options = undefined;
var i: usize = 0;
while (true) {
const p = try doprompt(out, in, alloc, def);
defer if (!std.mem.eql(u8, p.value, def orelse "")) alloc.free(p.value);
i += p.n;
if (std.meta.stringToEnum(options, p.value)) |cap| {
value = cap;
break;
}
}
try clean(out, i);
_ = try answer(out, prompt, []const u8, "{s}", @tagName(value));
return value;
}
pub fn forString(out: anytype, in: anytype, comptime prompt: []const u8, alloc: std.mem.Allocator, default: ?[]const u8) ![]const u8 {
try out.print(comptime ansi.color.Fg(.Green, "? "), .{});
try out.print(comptime ansi.color.Bold(prompt ++ " "), .{});
if (default != null) {
try out.print(ansi.style.Faint ++ "(", .{});
try out.print("{s}", .{default.?});
try out.print(")" ++ ansi.style.ResetIntensity ++ " ", .{});
}
const p = try doprompt(out, in, alloc, default);
try clean(out, p.n);
return try answer(out, prompt, []const u8, "{s}", p.value);
}
pub fn forConfirm(out: anytype, in: anytype, comptime prompt: []const u8, alloc: std.mem.Allocator) !bool {
return (try forEnum(out, in, prompt, alloc, enum { y, n }, .y)) == .y;
}
// pub fn forNumber(comptime prompt: []const u8, alloc: *std.mem.Allocator, comptime T: type, default: ?T) !T {
// try out.print(comptime ansi.color.Fg(.Green, "? "), .{});
// try out.print(comptime ansi.color.Bold(prompt ++ " "), .{});
// if (default != null) {
// try out.print(ansi.style.Faint ++ "(", .{});
// try out.print("{d}", .{default.?});
// try out.print(")" ++ ansi.style.ResetIntensity ++ " ", .{});
// }
// var value: T = undefined;
// var i: usize = 0;
// while (true) {
// const n = if (default != null) try std.fmt.allocPrint(alloc, "{d}", .{default}) else null;
// defer if (n != null) alloc.free(n.?);
// const p = try doprompt(stdin, alloc, if (default != null) n else null);
// defer alloc.free(p.value);
// i += p.n;
// switch (@typeInfo(T)) {
// .Int => {
// if (std.fmt.parseInt(T, p.value, 10) catch null) |cap| {
// value = cap;
// break;
// }
// },
// .Float => {
// if (std.fmt.parseFloat(T, p.value) catch null) |cap| {
// value = cap;
// break;
// }
// },
// else => @compileError("expected number type instead got: " ++ @typeName(T)),
// }
// }
// clean(i);
// _ = answer(prompt, T, "{d}", value);
// return value;
// } | src/lib.zig |
const std = @import("std");
const ft = @import("freetype");
const zigimg = @import("zigimg");
const Atlas = @import("atlas.zig").Atlas;
const AtlasErr = @import("atlas.zig").Error;
const UVData = @import("atlas.zig").UVData;
const App = @import("main.zig").App;
const draw = @import("draw.zig");
pub const Label = @This();
const Vec2 = @Vector(2, f32);
const Vec4 = @Vector(4, f32);
const GlyphInfo = struct {
uv_data: UVData,
metrics: ft.GlyphMetrics,
};
face: ft.Face,
size: i32,
char_map: std.AutoHashMap(u21, GlyphInfo),
allocator: std.mem.Allocator,
const WriterContext = struct {
label: *Label,
app: *App,
position: Vec2,
text_color: Vec4,
};
const WriterError = ft.Error || std.mem.Allocator.Error || AtlasErr;
const Writer = std.io.Writer(WriterContext, WriterError, write);
pub fn writer(label: *Label, app: *App, position: Vec2, text_color: Vec4) Writer {
return Writer{
.context = .{
.label = label,
.app = app,
.position = position,
.text_color = text_color,
},
};
}
pub fn init(lib: ft.Library, font_path: []const u8, face_index: i32, char_size: i32, allocator: std.mem.Allocator) !Label {
return Label{
.face = try lib.newFace(font_path, face_index),
.size = char_size,
.char_map = std.AutoHashMap(u21, GlyphInfo).init(allocator),
.allocator = allocator,
};
}
pub fn deinit(label: *Label) void {
label.face.deinit();
label.char_map.deinit();
}
fn write(ctx: WriterContext, bytes: []const u8) WriterError!usize {
var offset = Vec2{ 0, 0 };
var j: usize = 0;
while (j < bytes.len) {
const len = std.unicode.utf8ByteSequenceLength(bytes[j]) catch unreachable;
const char = std.unicode.utf8Decode(bytes[j..(j + len)]) catch unreachable;
j += len;
switch (char) {
'\n' => {
offset[0] = 0;
offset[1] -= @intToFloat(f32, ctx.label.face.size().metrics().height >> 6);
},
' ' => {
const v = try ctx.label.char_map.getOrPut(char);
if (!v.found_existing) {
try ctx.label.face.setCharSize(ctx.label.size * 64, 0, 50, 0);
try ctx.label.face.loadChar(char, .{ .render = true });
const glyph = ctx.label.face.glyph;
v.value_ptr.* = GlyphInfo{
.uv_data = undefined,
.metrics = glyph().metrics(),
};
}
offset[0] += @intToFloat(f32, v.value_ptr.metrics.horiAdvance >> 6);
},
else => {
const v = try ctx.label.char_map.getOrPut(char);
if (!v.found_existing) {
try ctx.label.face.setCharSize(ctx.label.size * 64, 0, 50, 0);
try ctx.label.face.loadChar(char, .{ .render = true });
const glyph = ctx.label.face.glyph();
const glyph_bitmap = glyph.bitmap();
const glyph_width = glyph_bitmap.width();
const glyph_height = glyph_bitmap.rows();
// Add 1 pixel padding to texture to avoid bleeding over other textures
var glyph_data = try ctx.label.allocator.alloc(zigimg.color.Rgba32, (glyph_width + 2) * (glyph_height + 2));
defer ctx.label.allocator.free(glyph_data);
const glyph_buffer = glyph_bitmap.buffer().?;
for (glyph_data) |*data, i| {
const x = i % (glyph_width + 2);
const y = i / (glyph_width + 2);
// zig fmt: off
const glyph_col =
if (x == 0 or x == (glyph_width + 1) or y == 0 or y == (glyph_height + 1))
0
else
glyph_buffer[(y - 1) * glyph_width + (x - 1)];
// zig fmt: on
data.* = zigimg.color.Rgba32.initRGB(glyph_col, glyph_col, glyph_col);
}
var glyph_atlas_region = try ctx.app.texture_atlas_data.reserve(ctx.label.allocator, glyph_width + 2, glyph_height + 2);
ctx.app.texture_atlas_data.set(glyph_atlas_region, glyph_data);
glyph_atlas_region.x += 1;
glyph_atlas_region.y += 1;
glyph_atlas_region.width -= 2;
glyph_atlas_region.height -= 2;
const glyph_uv_data = glyph_atlas_region.getUVData(@intToFloat(f32, ctx.app.texture_atlas_data.size));
v.value_ptr.* = GlyphInfo{
.uv_data = glyph_uv_data,
.metrics = glyph.metrics(),
};
}
try draw.quad(
ctx.app,
ctx.position + offset + Vec2{ @intToFloat(f32, v.value_ptr.metrics.horiBearingX >> 6), @intToFloat(f32, (v.value_ptr.metrics.horiBearingY - v.value_ptr.metrics.height) >> 6) },
.{ @intToFloat(f32, v.value_ptr.metrics.width >> 6), @intToFloat(f32, v.value_ptr.metrics.height >> 6) },
.{ .blend_color = ctx.text_color },
v.value_ptr.uv_data,
);
offset[0] += @intToFloat(f32, v.value_ptr.metrics.horiAdvance >> 6);
},
}
}
return bytes.len;
}
pub fn print(label: *Label, app: *App, comptime fmt: []const u8, args: anytype, position: Vec2, text_color: Vec4) !void {
const w = writer(label, app, position, text_color);
try w.print(fmt, args);
} | examples/gkurve/label.zig |
const std = @import("std");
const utils = @import("./_utils.zig");
const common = @import("../_common_utils.zig");
const FV = common.FV;
pub const XADD = struct {
//! Command builder for XADD.
//!
//! Use `XADD.forStruct(T)` to create at `comptime` a specialized version of XADD
//! whose `.init` accepts a struct for your choosing instead of `fvs`.
//!
//! ```
//! const cmd = XADD.init("mykey", "*", .NoMaxLen, &[_]FV{
//! .{ .field = "field1", .value = "val1" },
//! .{ .field = "field2", .value = "val2" },
//! });
//!
//! const ExampleStruct = struct {
//! banana: usize,
//! id: []const u8,
//! };
//!
//! const example = ExampleStruct{
//! .banana = 10,
//! .id = "ok",
//! };
//!
//! const MyXADD = XADD.forStruct(ExampleStruct);
//!
//! const cmd1 = MyXADD.init("mykey", "*", .NoMaxLen, example);
//! ```
key: []const u8,
id: []const u8,
maxlen: MaxLen = .NoMaxLen,
fvs: []const FV,
/// Instantiates a new XADD command.
pub fn init(key: []const u8, id: []const u8, maxlen: MaxLen, fvs: []const FV) XADD {
return .{ .key = key, .id = id, .maxlen = maxlen, .fvs = fvs };
}
/// Type constructor that creates a specialized version of XADD whose
/// .init accepts a struct for your choosing instead of `fvs`.
pub const forStruct = _forStruct;
// This reassignment is necessary to avoid having two definitions of
// RedisCommand in the same scope (it causes a shadowing error).
/// Validates if the command is syntactically correct.
pub fn validate(self: XADD) !void {
if (self.key.len == 0) return error.EmptyKeyName;
if (self.fvs.len == 0) return error.FVsArrayIsEmpty;
if (!utils.isValidStreamID(.XADD, self.id)) return error.InvalidID;
// Check the individual KV pairs
// TODO: how the hell do I check for dups without an allocator?
var i: usize = 0;
while (i < self.fvs.len) : (i += 1) {
if (self.fvs[i].field.len == 0) return error.EmptyFieldName;
}
}
pub const RedisCommand = struct {
pub fn serialize(self: XADD, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"XADD",
self.key,
self.id,
self.maxlen,
self.fvs,
});
}
};
pub const MaxLen = union(enum) {
NoMaxLen,
MaxLen: u64,
PreciseMaxLen: u64,
pub const RedisArguments = struct {
pub fn count(self: MaxLen) usize {
return switch (self) {
.NoMaxLen => 0,
.MaxLen => 3,
.PreciseMaxLen => 2,
};
}
pub fn serialize(self: MaxLen, comptime rootSerializer: type, msg: anytype) !void {
switch (self) {
.NoMaxLen => {},
.MaxLen => |c| {
try rootSerializer.serializeArgument(msg, []const u8, "MAXLEN");
try rootSerializer.serializeArgument(msg, []const u8, "~");
try rootSerializer.serializeArgument(msg, u64, c);
},
.PreciseMaxLen => |c| {
try rootSerializer.serializeArgument(msg, []const u8, "MAXLEN");
try rootSerializer.serializeArgument(msg, u64, c);
},
}
}
};
};
};
fn _forStruct(comptime T: type) type {
// TODO: support pointers to struct, check that the struct is serializable (strings and numbers).
if (@typeInfo(T) != .Struct) @compileError("Only Struct types allowed.");
return struct {
key: []const u8,
id: []const u8,
maxlen: XADD.MaxLen,
values: T,
const Self = @This();
pub fn init(key: []const u8, id: []const u8, maxlen: XADD.MaxLen, values: T) Self {
return .{ .key = key, .id = id, .maxlen = maxlen, .values = values };
}
pub fn validate(self: Self) !void {
if (self.key.len == 0) return error.EmptyKeyName;
if (!utils.isValidStreamID(.XADD, self.id)) return error.InvalidID;
}
pub const RedisCommand = struct {
pub fn serialize(self: Self, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"XADD",
self.key,
self.id,
self.maxlen,
// Dirty trick to control struct serialization :3
self,
});
}
};
// We are marking ouserlves also as an argument to manage struct serialization.
pub const RedisArguments = struct {
pub fn count(_: Self) usize {
return comptime std.meta.fields(T).len * 2;
}
pub fn serialize(self: Self, comptime rootSerializer: type, msg: anytype) !void {
inline for (std.meta.fields(T)) |field| {
const arg = @field(self.values, field.name);
const ArgT = @TypeOf(arg);
try rootSerializer.serializeArgument(msg, []const u8, field.name);
try rootSerializer.serializeArgument(msg, ArgT, arg);
}
}
};
};
}
test "basic usage" {
const cmd = XADD.init("mykey", "*", .NoMaxLen, &[_]FV{
.{ .field = "field1", .value = "val1" },
.{ .field = "field2", .value = "val2" },
});
try cmd.validate();
const ExampleStruct = struct {
banana: usize,
id: []const u8,
};
const example = ExampleStruct{
.banana = 10,
.id = "ok",
};
const cmd1 = XADD.forStruct(ExampleStruct).init("mykey", "*", .NoMaxLen, example);
try cmd1.validate();
}
test "serializer" {
const serializer = @import("../../serializer.zig").CommandSerializer;
var correctBuf: [1000]u8 = undefined;
var correctMsg = std.io.fixedBufferStream(correctBuf[0..]);
var testBuf: [1000]u8 = undefined;
var testMsg = std.io.fixedBufferStream(testBuf[0..]);
{
{
correctMsg.reset();
testMsg.reset();
try serializer.serializeCommand(
testMsg.writer(),
XADD.init("k1", "1-1", .NoMaxLen, &[_]FV{.{ .field = "f1", .value = "v1" }}),
);
try serializer.serializeCommand(
correctMsg.writer(),
.{ "XADD", "k1", "1-1", "f1", "v1" },
);
// std.debug.warn("{}\n\n\n{}\n", .{ correctMsg.getWritten(), testMsg.getWritten() });
// try std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
{
correctMsg.reset();
testMsg.reset();
const MyStruct = struct {
field1: []const u8,
field2: u8,
field3: usize,
};
const MyXADD = XADD.forStruct(MyStruct);
try serializer.serializeCommand(
testMsg.writer(),
MyXADD.init("k1", "1-1", .NoMaxLen, .{ .field1 = "nice!", .field2 = 'a', .field3 = 42 }),
);
try serializer.serializeCommand(
correctMsg.writer(),
.{ "XADD", "k1", "1-1", "field1", "nice!", "field2", 'a', "field3", 42 },
);
try std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
{
correctMsg.reset();
testMsg.reset();
const MyStruct = struct {
field1: []const u8,
field2: u8,
field3: usize,
};
const MyXADD = XADD.forStruct(MyStruct);
try serializer.serializeCommand(
testMsg.writer(),
MyXADD.init(
"k1",
"1-1",
XADD.MaxLen{ .PreciseMaxLen = 40 },
.{ .field1 = "nice!", .field2 = 'a', .field3 = 42 },
),
);
try serializer.serializeCommand(
correctMsg.writer(),
.{ "XADD", "k1", "1-1", "MAXLEN", 40, "field1", "nice!", "field2", 'a', "field3", 42 },
);
try std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
}
} | src/commands/streams/xadd.zig |
const std = @import("std");
const napi = @import("../napi.zig");
const serde = @import("../serde.zig");
pub fn bind(env: napi.env, comptime f: anytype, comptime name: [:0]const u8, comptime A: std.mem.Allocator) !napi.value {
const T = @TypeOf(f);
const I = @typeInfo(T);
switch (I) {
else => @compileError("expected function, got " + @typeName(T)),
.Fn => |info| switch (info.calling_convention) {
else => return bind_sync(env, f, name),
.Async => return bind_async(env, f, name, A),
},
}
}
fn bind_sync(env: napi.env, comptime f: anytype, comptime name: [:0]const u8) !napi.value {
const info = @typeInfo(@TypeOf(f)).Fn;
const wrapper = opaque {
pub fn callback(re: napi.napi_env, ri: napi.napi_callback_info) callconv(.C) napi.napi_value {
if (zig(napi.env.init(re), ri)) |x| { return x.raw; }
else |err| napi.env.init(re).throw_error(@errorName(err)) catch {};
return null;
}
pub fn zig(e: napi.env, ri: napi.napi_callback_info) !napi.value {
const a = try args(e, f, ri, .{ .sync = true });
switch (@typeInfo(info.return_type.?)) {
else => return try e.create(@call(.{ .modifier = .no_async }, f, a)),
.ErrorUnion => return try e.create(try @call(.{ .modifier = .no_async }, f, a)),
}
}
};
var raw: napi.napi_value = undefined;
try napi.safe(napi.napi_create_function, .{env.raw, name, name.len, wrapper.callback, null, &raw});
return napi.value.init(raw);
}
fn bind_async(env: napi.env, comptime f: anytype, comptime name: [:0]const u8, comptime A: std.mem.Allocator) !napi.value {
const info = @typeInfo(@TypeOf(f)).Fn;
const has_error = .ErrorUnion == @typeInfo(info.return_type.?);
const wrapper = opaque {
pub fn callback(re: napi.napi_env, ri: napi.napi_callback_info) callconv(.C) napi.napi_value {
if (zig(napi.env.init(re), ri)) |x| { return x.raw; }
else |err| napi.env.init(re).throw_error(@errorName(err)) catch {};
return null;
}
pub fn zig(e: napi.env, ri: napi.napi_callback_info) !napi.value {
var p: napi.napi_value = undefined;
var d: napi.napi_deferred = undefined;
var w: napi.napi_async_work = undefined;
try napi.safe(napi.napi_create_promise, .{e.raw, &d, &p});
const State = struct {
d: napi.napi_deferred,
r: info.return_type.?,
A: std.heap.ArenaAllocator,
e: if (has_error) bool else void,
a: std.meta.ArgsTuple(@TypeOf(f)),
f: [count_args_refs(f)]napi.napi_ref,
};
const work_wrapper = opaque {
pub fn work(_: napi.napi_env, rs: ?*anyopaque) callconv(.C) void {
const state = @ptrCast(*State, @alignCast(@alignOf(*State), rs));
// fixes env.raw from previous env
// DISABLED: only serde types supported
// inline for (info.args) |arg, offset| {
// const T = arg.arg_type.?;
// switch (@typeInfo(T)) {
// else => {},
// .Struct => switch (T) {
// else => {},
// napi.env => state.a[offset].raw = re,
// },
// }
// }
nosuspend call(state);
}
pub fn call(state: *State) void {
var stack: [@sizeOf(@Frame(f))]u8 align(@alignOf(@Frame(f))) = undefined;
// TODO: replace x with &state.r (https://github.com/ziglang/zig/issues/7966)
if (!has_error) {
var x: info.return_type.? = undefined;
_ = await @asyncCall(&stack, &x, f, state.a);
state.r = x;
}
else {
var x: info.return_type.? = undefined;
if (await @asyncCall(&stack, &x, f, state.a))
|ok| {
state.r = ok;
state.e = false;
} else |err| {
state.r = err;
state.e = true;
}
}
}
pub fn done(re: napi.napi_env, _: napi.napi_status, rs: ?*anyopaque) callconv(.C) void {
const E = napi.env.init(re);
const state = @ptrCast(*State, @alignCast(@alignOf(*State), rs));
defer A.destroy(state);
defer state.A.deinit();
defer for (state.f) |ref| if (ref) |x| napi.safe(napi.napi_delete_reference, .{E.raw, x}) catch {};
const r = E.create(state.r) catch |err| {
return napi.safe(napi.napi_reject_deferred, .{E.raw, state.d, (E.create(err) catch unreachable).raw}) catch {};
};
switch (has_error) {
false => napi.safe(napi.napi_resolve_deferred, .{E.raw, state.d, r.raw}) catch {},
true => switch (state.e) {
true => napi.safe(napi.napi_reject_deferred, .{E.raw, state.d, r.raw}) catch {},
false => napi.safe(napi.napi_resolve_deferred, .{E.raw, state.d, r.raw}) catch {},
},
}
}
};
const state = try A.create(State);
state.d = d;
errdefer A.destroy(state);
errdefer state.A.deinit();
for (state.f) |*ref| ref.* = null;
state.A = std.heap.ArenaAllocator.init(A);
state.a = try args(e, f, ri, .{ .sync = false, .refs = &state.f, .alloc = state.A.allocator() });
errdefer for (state.f) |ref| if (ref) |x| napi.safe(napi.napi_delete_reference, .{e.raw, x}) catch {};
try napi.safe(napi.napi_create_async_work, .{e.raw, null, (try e.create(void)).raw, work_wrapper.work, work_wrapper.done, @ptrCast(* align(@alignOf(*State)) anyopaque, state), &w});
try napi.safe(napi.napi_queue_async_work, .{e.raw, w}); return napi.value.init(p);
}
};
var raw: napi.napi_value = undefined;
try napi.safe(napi.napi_create_function, .{env.raw, name, name.len, wrapper.callback, null, &raw});
return napi.value.init(raw);
}
inline fn count_args_refs(comptime f: anytype) comptime_int {
comptime var refs = 0;
const I = @typeInfo(@TypeOf(f)).Fn;
inline for (I.args) |arg| {
const T = arg.arg_type.?;
switch (@typeInfo(T)) {
else => {},
.Pointer => |info| switch (info.size) {
else => {},
.Slice => switch (info.child) {
else => {},
u8, i8, u16, i16, u32, i32, f32, u64, i64, f64,
f16, u24, i24, u40, i40, u48, i48, u56, i56, u128, i128, f128 => refs += 1,
},
}
}
}
return refs;
}
inline fn args(env: napi.env, comptime f: anytype, ri: napi.napi_callback_info, options: anytype) !std.meta.ArgsTuple(@TypeOf(f)) {
const I = @typeInfo(@TypeOf(f)).Fn;
var a: std.meta.ArgsTuple(@TypeOf(f)) = undefined;
switch (I.args.len) {
0 => return a,
else => {
var len = I.args.len;
var napi_args: [I.args.len]napi.napi_value = undefined;
try napi.safe(napi.napi_get_cb_info, .{env.raw, ri, &len, &napi_args, null, null});
comptime var refs = 0;
comptime var envs = 0;
inline for (I.args) |arg, offset| {
const T = arg.arg_type.?;
const raw = napi.value.init(napi_args[offset - envs]);
// TODO: move out
switch (@typeInfo(T)) {
.Bool => a[offset] = try serde.types.@"bool".deserialize(env, raw),
.Int, .Float => a[offset] = try serde.types.@"number".deserialize(env, T, raw),
else => @compileError("unsupported function parameter type: " ++ @typeName(T)),
.Union => switch (T) {
else => @compileError("unsupported function parameter type: " ++ @typeName(T)),
napi.serde.string => if (true == options.sync)
@compileError("serde.string is not allowed in sync function (use napi.string)")
else { a[offset] = try serde.types.@"string".deserialize(env, raw, options.alloc); }
},
.Struct => switch (T) {
else => @compileError("unsupported function parameter type: " ++ @typeName(T)),
napi.value => if (true == options.sync) { a[offset] = raw; } else @compileError("napi.value is not allowed in async function"),
napi.env => if (true == options.sync) { envs += 1; a[offset] = env; } else @compileError("napi.env is not allowed in async function"),
napi.object => if (true == options.sync) switch (try raw.typeof(env)) {
else => return napi.expected.expected_object,
.js_object => a[offset] = napi.object.init(raw.raw),
} else @compileError("napi.object is not allowed in async function"),
napi.string => if (true == options.sync) switch (try raw.typeof(env)) {
else => return napi.expected.expected_string,
.js_string => a[offset] = napi.string.init(raw.raw),
} else @compileError("napi.string is not allowed in async function (use serde.string)"),
napi.array => if (true == options.sync) {
var b: bool = undefined;
try napi.safe(napi.napi_is_array, .{env.raw, raw.raw, &b});
switch (b) {
else => return napi.expected.expected_array,
true => a[offset] = napi.array.init(raw.raw),
}
} else @compileError("napi.array is not allowed in async function"),
},
.Pointer => |info| switch (info.size) {
// TODO: support c char pointers / opaque type
else => @compileError("unsupported function parameter type: " ++ @typeName(T)),
.Slice => switch (info.child) {
else => @compileError("unsupported function parameter type: " ++ @typeName(T)),
u8, i8, u16, i16, u32, i32, f32, u64, i64, f64,
f16, u24, i24, u40, i40, u48, i48, u56, i56, u128, i128, f128 => {
const TT = info.child;
var is: bool = undefined;
const wt = switch (TT) {
else => unreachable,
f16 => .{ .s = @sizeOf(f16), .e = error.expected_f16_typedarray },
f32 => .{ .s = @sizeOf(f32), .e = error.expected_f32_typedarray },
f64 => .{ .s = @sizeOf(f64), .e = error.expected_f64_typedarray },
f128 => .{ .s = @sizeOf(f128), .e = error.expected_f128_typedarray },
u8, i8 => .{ .s = @sizeOf(u8), .e = if (u8 == TT) error.expected_u8_typedarray else error.expected_i8_typedarray },
u16, i16 => .{ .s = @sizeOf(u16), .e = if (u16 == TT) error.expected_u16_typedarray else error.expected_i16_typedarray },
u24, i24 => .{ .s = @sizeOf(u24), .e = if (u24 == TT) error.expected_u24_typedarray else error.expected_i24_typedarray },
u32, i32 => .{ .s = @sizeOf(u32), .e = if (u32 == TT) error.expected_u32_typedarray else error.expected_i32_typedarray },
u40, i40 => .{ .s = @sizeOf(u40), .e = if (u40 == TT) error.expected_u40_typedarray else error.expected_i40_typedarray },
u48, i48 => .{ .s = @sizeOf(u48), .e = if (u48 == TT) error.expected_u48_typedarray else error.expected_i48_typedarray },
u56, i56 => .{ .s = @sizeOf(u56), .e = if (u56 == TT) error.expected_u56_typedarray else error.expected_i56_typedarray },
u64, i64 => .{ .s = @sizeOf(u64), .e = if (u64 == TT) error.expected_u64_typedarray else error.expected_i64_typedarray },
u128, i128 => .{ .s = @sizeOf(u128), .e = if (u128 == TT) error.expected_u128_typedarray else error.expected_i128_typedarray },
};
try napi.safe(napi.napi_is_typedarray, .{env.raw, raw.raw, &is});
if (!is) {
var is_nb: bool = undefined;
try napi.safe(napi.napi_is_buffer, .{env.raw, raw.raw, &is_nb});
if (!is_nb) return error.expected_buffer_or_typedarray;
}
var l: usize = undefined;
var slice: [*]TT = undefined;
var t: napi.napi_typedarray_type = undefined;
switch (is) {
true => try napi.safe(napi.napi_get_typedarray_info, .{env.raw, raw.raw, &t, &l, @ptrCast([*]?*anyopaque, &slice), null, null}),
else => { t = napi.napi_uint8_array; try napi.safe(napi.napi_get_buffer_info, .{env.raw, raw.raw, @ptrCast([*]?*anyopaque, &slice), &l}); },
}
const tt: u8 = switch (t) {
else => unreachable,
napi.napi_int8_array => @sizeOf(i8),
napi.napi_uint8_array => @sizeOf(u8),
napi.napi_int16_array => @sizeOf(i16),
napi.napi_int32_array => @sizeOf(i32),
napi.napi_uint16_array => @sizeOf(u16),
napi.napi_uint32_array => @sizeOf(u32),
napi.napi_float32_array => @sizeOf(f32),
napi.napi_float64_array => @sizeOf(f64),
napi.napi_bigint64_array => @sizeOf(i64),
napi.napi_biguint64_array => @sizeOf(u64),
napi.napi_uint8_clamped_array => @sizeOf(u8),
};
if (tt != wt.s and (0 != ((l * tt) % wt.s))) return wt.e;
a[offset] = slice[0..(l * tt / wt.s)];
if (@hasField(@TypeOf(options), "refs")) {
try napi.safe(napi.napi_create_reference, .{env.raw, raw.raw, 1, &options.refs[refs]}); refs += 1;
}
},
},
}
}
}
return a;
},
}
} | src/bind/function.zig |
usingnamespace @import("bits.zig");
pub const __psp_max_fd = 1024;
pub const __psp_fdman_type = enum(u8) {
File,
Pipe,
Socket,
Tty,
};
pub const __psp_fdman_descriptor = struct {
filename: ?[]u8,
ftype: __psp_fdman_type,
sce_descriptor: c_int,
flags: u32,
ref_count: u32,
};
pub fn __psp_fdman_fdValid(fd: fd_t) bool {
return fd >= 0 and fd < __psp_max_fd and __psp_descriptormap[fd] != null;
}
pub fn __psp_fdman_fdType(fd: fd_t, ftype: __psp_fdman_type) bool {
return __psp_fdman_fdValid(fd) and __psp_descriptormap[fd].?.ftype == ftype;
}
comptime {
asm (@embedFile("interrupt.S"));
}
extern fn pspDisableInterrupts() u32;
extern fn pspEnableInterrupts(en: u32) void;
pub var __psp_descriptor_data_pool: [__psp_max_fd]__psp_fdman_descriptor = undefined;
pub var __psp_descriptormap: [__psp_max_fd]?*__psp_fdman_descriptor = undefined;
usingnamespace @import("../include/pspiofilemgr.zig");
usingnamespace @import("../include/pspstdio.zig");
usingnamespace @import("system.zig");
pub fn __psp_fdman_init() void {
@memset(@ptrCast([*]u8, &__psp_descriptor_data_pool), 0, __psp_max_fd * @sizeOf(__psp_fdman_descriptor));
@memset(@ptrCast([*]u8, &__psp_descriptormap), 0, __psp_max_fd * @sizeOf(?*__psp_fdman_descriptor));
var scefd = sceKernelStdin();
if (scefd >= 0) {
__psp_descriptormap[0] = &__psp_descriptor_data_pool[0];
__psp_descriptormap[0].?.sce_descriptor = @bitCast(u32, scefd);
__psp_descriptormap[0].?.ftype = __psp_fdman_type.Tty;
}
scefd = sceKernelStdout();
if (scefd >= 0) {
__psp_descriptormap[1] = &__psp_descriptor_data_pool[1];
__psp_descriptormap[1].?.sce_descriptor = @bitCast(u32, scefd);
__psp_descriptormap[1].?.ftype = __psp_fdman_type.Tty;
}
scefd = sceKernelStderr();
if (scefd >= 0) {
__psp_descriptormap[2] = &__psp_descriptor_data_pool[2];
__psp_descriptormap[2].?.sce_descriptor = @bitCast(u32, scefd);
__psp_descriptormap[2].?.ftype = __psp_fdman_type.Tty;
}
}
//Untested:
pub fn __psp_fdman_get_new_descriptor() i32 {
var i: usize = 0;
var inten: u32 = 0;
//Thread safety
inten = pspDisableInterrupts();
while (i < __psp_max_fd) : (i += 1) {
if (__psp_descriptormap[i] == null) {
__psp_descriptormap[i] = &__psp_descriptor_data_pool[i];
__psp_descriptormap[i].?.ref_count += 1;
pspEnableInterrupts(inten);
return @intCast(i32, i);
}
}
//Unlock
pspEnableInterrupts(inten);
errno = ENOMEM;
return -1;
}
pub fn __psp_fdman_get_dup_descriptor(fd: fd_t) i32 {
var i: usize = 0;
var inten: u32 = 0;
if (!__PSP_IS_FD_VALID(fd)) {
errno = EBADF;
return -1;
}
inten = pspDisableInterrupts();
while (i < __psp_max_fd) : (i += 1) {
if (__psp_descriptormap[i] == NULL) {
__psp_descriptormap[i] = &__psp_descriptor_data_pool[fd];
__psp_descriptormap[i].?.ref_count += 1;
pspEnableInterrupts(inten);
return i;
}
}
pspEnableInterrupts(inten);
errno = ENOMEM;
return -1;
}
pub fn __psp_fdman_release_descriptor(fd: fd_t) void {
if (!__psp_fdman_fdValid(fd)) {
errno = EBADF;
return;
}
__psp_descriptormap[fd].?.ref_count -= 1;
if (__psp_descriptormap[fd].?.ref_count == 0) {
__psp_descriptormap[fd].?.sce_descriptor = 0;
__psp_descriptormap[fd].?.filename = null;
__psp_descriptormap[fd].?.ftype = @intToEnum(__psp_fdman_type, 0);
__psp_descriptormap[fd].?.flags = 0;
}
__psp_descriptormap[fd] = null;
} | src/psp/os/fdman.zig |
const std = @import("std");
const expect = std.testing.expect;
const Mutex = std.Thread.Mutex;
pub const IndexType = u16;
pub const MeshHandle = *opaque {};
extern fn zmesh_set_allocator(
malloc: fn (size: usize) callconv(.C) ?*anyopaque,
calloc: fn (num: usize, size: usize) callconv(.C) ?*anyopaque,
realloc: fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque,
free: fn (ptr: ?*anyopaque) callconv(.C) void,
) void;
var allocator: ?std.mem.Allocator = null;
var allocations: ?std.AutoHashMap(usize, usize) = null;
var mutex: Mutex = .{};
export fn mallocFunc(size: usize) callconv(.C) ?*anyopaque {
mutex.lock();
defer mutex.unlock();
var slice = allocator.?.allocBytes(
@sizeOf(usize),
size,
0,
@returnAddress(),
) catch @panic("zmesh: out of memory");
allocations.?.put(@ptrToInt(slice.ptr), size) catch
@panic("zmesh: out of memory");
return slice.ptr;
}
export fn callocFunc(num: usize, size: usize) callconv(.C) ?*anyopaque {
const ptr = mallocFunc(num * size);
if (ptr != null) {
@memset(@ptrCast([*]u8, ptr), 0, num * size);
return ptr;
}
return null;
}
export fn reallocFunc(ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque {
mutex.lock();
defer mutex.unlock();
const old_len = if (ptr != null)
allocations.?.get(@ptrToInt(ptr.?)).?
else
0;
var old_mem = if (old_len > 0)
@ptrCast([*]u8, ptr)[0..old_len]
else
@as([*]u8, undefined)[0..0];
var slice = allocator.?.reallocBytes(
old_mem,
@sizeOf(usize),
size,
@sizeOf(usize),
0,
@returnAddress(),
) catch @panic("zmesh: out of memory");
if (ptr != null) {
const removed = allocations.?.remove(@ptrToInt(ptr.?));
std.debug.assert(removed);
}
allocations.?.put(@ptrToInt(slice.ptr), size) catch
@panic("zmesh: out of memory");
return slice.ptr;
}
export fn freeFunc(ptr: ?*anyopaque) callconv(.C) void {
if (ptr != null) {
mutex.lock();
defer mutex.unlock();
const size = allocations.?.fetchRemove(@ptrToInt(ptr.?)).?.value;
const slice = @ptrCast([*]u8, ptr.?)[0..size];
allocator.?.free(slice);
}
}
pub fn init(alloc: std.mem.Allocator) void {
std.debug.assert(allocator == null and allocations == null);
allocator = alloc;
allocations = std.AutoHashMap(usize, usize).init(allocator.?);
allocations.?.ensureTotalCapacity(32) catch unreachable;
zmesh_set_allocator(mallocFunc, callocFunc, reallocFunc, freeFunc);
}
pub fn deinit() void {
allocations.?.deinit();
allocations = null;
allocator = null;
}
const ParMesh = extern struct {
points: [*]f32,
npoints: c_int,
triangles: [*]IndexType,
ntriangles: c_int,
normals: ?[*]f32,
tcoords: ?[*]f32,
};
pub const Mesh = struct {
indices: []IndexType,
positions: [][3]f32,
normals: ?[][3]f32,
texcoords: ?[][2]f32,
handle: MeshHandle,
pub fn deinit(mesh: Mesh) void {
par_shapes_free_mesh(mesh.handle);
}
extern fn par_shapes_free_mesh(mesh: MeshHandle) void;
pub fn saveToObj(mesh: Mesh, filename: [*:0]const u8) void {
par_shapes_export(mesh.handle, filename);
}
extern fn par_shapes_export(mesh: MeshHandle, filename: [*:0]const u8) void;
pub fn computeAabb(mesh: Mesh, aabb: *[6]f32) void {
par_shapes_compute_aabb(mesh.handle, aabb);
}
extern fn par_shapes_compute_aabb(mesh: MeshHandle, aabb: *[6]f32) void;
pub fn clone(mesh: Mesh) Mesh {
return initMesh(par_shapes_clone(mesh.handle, null));
}
extern fn par_shapes_clone(mesh: MeshHandle, target: ?MeshHandle) MeshHandle;
pub fn merge(mesh: *Mesh, src_mesh: Mesh) void {
par_shapes_merge(mesh.handle, src_mesh.handle);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_merge(mesh: MeshHandle, src_mesh: MeshHandle) void;
pub fn translate(mesh: *Mesh, x: f32, y: f32, z: f32) void {
par_shapes_translate(mesh.handle, x, y, z);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_translate(mesh: MeshHandle, x: f32, y: f32, z: f32) void;
pub fn rotate(mesh: *Mesh, radians: f32, x: f32, y: f32, z: f32) void {
par_shapes_rotate(mesh.handle, radians, &.{ x, y, z });
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_rotate(
mesh: MeshHandle,
radians: f32,
axis: *const [3]f32,
) void;
pub fn scale(mesh: *Mesh, x: f32, y: f32, z: f32) void {
par_shapes_scale(mesh.handle, x, y, z);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_scale(mesh: MeshHandle, x: f32, y: f32, z: f32) void;
pub fn invert(mesh: *Mesh, start_face: i32, num_faces: i32) void {
par_shapes_invert(mesh.handle, start_face, num_faces);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_invert(
mesh: MeshHandle,
start_face: i32,
num_faces: i32,
) void;
pub fn removeDegenerate(mesh: *Mesh, min_area: f32) void {
par_shapes_remove_degenerate(mesh.handle, min_area);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_remove_degenerate(mesh: MeshHandle, min_area: f32) void;
pub fn unweld(mesh: *Mesh) void {
par_shapes_unweld(mesh.handle, true);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_unweld(mesh: MeshHandle, create_indices: bool) void;
pub fn weld(mesh: *Mesh, epsilon: f32, mapping: ?[*]IndexType) void {
const new_mesh = par_shapes_weld(mesh.handle, epsilon, mapping);
par_shapes_free_mesh(mesh.handle);
mesh.* = initMesh(new_mesh);
}
extern fn par_shapes_weld(
mesh: MeshHandle,
epsilon: f32,
mapping: ?[*]IndexType,
) MeshHandle;
pub fn computeNormals(mesh: *Mesh) void {
par_shapes_compute_normals(mesh.handle);
mesh.* = initMesh(mesh.handle);
}
extern fn par_shapes_compute_normals(mesh: MeshHandle) void;
};
fn initMesh(handle: MeshHandle) Mesh {
const parmesh = @ptrCast(
*ParMesh,
@alignCast(@alignOf(ParMesh), handle),
);
return .{
.handle = handle,
.positions = @ptrCast(
[*][3]f32,
parmesh.points,
)[0..@intCast(usize, parmesh.npoints)],
.indices = parmesh.triangles[0..@intCast(usize, parmesh.ntriangles * 3)],
.normals = if (parmesh.normals == null)
null
else
@ptrCast(
[*][3]f32,
parmesh.normals.?,
)[0..@intCast(usize, parmesh.npoints)],
.texcoords = if (parmesh.tcoords == null)
null
else
@ptrCast(
[*][2]f32,
parmesh.tcoords.?,
)[0..@intCast(usize, parmesh.npoints)],
};
}
pub fn initCylinder(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_cylinder(slices, stacks));
}
extern fn par_shapes_create_cylinder(slices: i32, stacks: i32) MeshHandle;
pub fn initCone(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_cone(slices, stacks));
}
extern fn par_shapes_create_cone(slices: i32, stacks: i32) MeshHandle;
pub fn initParametricDisk(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_parametric_disk(slices, stacks));
}
extern fn par_shapes_create_parametric_disk(slices: i32, stacks: i32) MeshHandle;
pub fn initTorus(slices: i32, stacks: i32, radius: f32) Mesh {
return initMesh(par_shapes_create_torus(slices, stacks, radius));
}
extern fn par_shapes_create_torus(slices: i32, stacks: i32, radius: f32) MeshHandle;
pub fn initParametricSphere(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_parametric_sphere(slices, stacks));
}
extern fn par_shapes_create_parametric_sphere(slices: i32, stacks: i32) MeshHandle;
pub fn initSubdividedSphere(num_subdivisions: i32) Mesh {
return initMesh(par_shapes_create_subdivided_sphere(num_subdivisions));
}
extern fn par_shapes_create_subdivided_sphere(num_subdivisions: i32) MeshHandle;
pub fn initTrefoilKnot(slices: i32, stacks: i32, radius: f32) Mesh {
return initMesh(par_shapes_create_trefoil_knot(slices, stacks, radius));
}
extern fn par_shapes_create_trefoil_knot(
slices: i32,
stacks: i32,
radius: f32,
) MeshHandle;
pub fn initHemisphere(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_hemisphere(slices, stacks));
}
extern fn par_shapes_create_hemisphere(slices: i32, stacks: i32) MeshHandle;
pub fn initPlane(slices: i32, stacks: i32) Mesh {
return initMesh(par_shapes_create_plane(slices, stacks));
}
extern fn par_shapes_create_plane(slices: i32, stacks: i32) MeshHandle;
pub fn initIcosahedron() Mesh {
return initMesh(par_shapes_create_icosahedron());
}
extern fn par_shapes_create_icosahedron() MeshHandle;
pub fn initDodecahedron() Mesh {
return initMesh(par_shapes_create_dodecahedron());
}
extern fn par_shapes_create_dodecahedron() MeshHandle;
pub fn initOctahedron() Mesh {
return initMesh(par_shapes_create_octahedron());
}
extern fn par_shapes_create_octahedron() MeshHandle;
pub fn initTetrahedron() Mesh {
return initMesh(par_shapes_create_tetrahedron());
}
extern fn par_shapes_create_tetrahedron() MeshHandle;
pub fn initCube() Mesh {
return initMesh(par_shapes_create_cube());
}
extern fn par_shapes_create_cube() MeshHandle;
pub fn initDisk(
radius: f32,
slices: i32,
center: *const [3]f32,
normal: *const [3]f32,
) Mesh {
return initMesh(par_shapes_create_disk(radius, slices, center, normal));
}
extern fn par_shapes_create_disk(
radius: f32,
slices: i32,
center: *const [3]f32,
normal: *const [3]f32,
) MeshHandle;
pub fn initRock(seed: i32, num_subdivisions: i32) Mesh {
return initMesh(par_shapes_create_rock(seed, num_subdivisions));
}
extern fn par_shapes_create_rock(seed: i32, num_subdivisions: i32) MeshHandle;
pub const UvToPositionFn = fn (
uv: *const [2]f32,
position: *[3]f32,
userdata: ?*anyopaque,
) callconv(.C) void;
pub fn initParametric(
fun: UvToPositionFn,
slices: i32,
stacks: i32,
userdata: ?*anyopaque,
) Mesh {
return initMesh(par_shapes_create_parametric(fun, slices, stacks, userdata));
}
extern fn par_shapes_create_parametric(
fun: UvToPositionFn,
slices: i32,
stacks: i32,
userdata: ?*anyopaque,
) MeshHandle;
const save = false;
test "zmesh.basic" {
init(std.testing.allocator);
defer deinit();
const cylinder = initCylinder(10, 10);
defer cylinder.deinit();
if (save) cylinder.saveToObj("zmesh.cylinder.obj");
const cone = initCone(10, 10);
defer cone.deinit();
if (save) cone.saveToObj("zmesh.cone.obj");
const pdisk = initParametricDisk(10, 10);
defer pdisk.deinit();
if (save) pdisk.saveToObj("zmesh.pdisk.obj");
const torus = initTorus(10, 10, 0.2);
defer torus.deinit();
if (save) torus.saveToObj("zmesh.torus.obj");
const psphere = initParametricSphere(10, 10);
defer psphere.deinit();
if (save) psphere.saveToObj("zmesh.psphere.obj");
const subdsphere = initSubdividedSphere(3);
defer subdsphere.deinit();
if (save) subdsphere.saveToObj("zmesh.subdsphere.obj");
const trefoil_knot = initTrefoilKnot(10, 100, 0.6);
defer trefoil_knot.deinit();
if (save) trefoil_knot.saveToObj("zmesh.trefoil_knot.obj");
const hemisphere = initHemisphere(10, 10);
defer hemisphere.deinit();
if (save) hemisphere.saveToObj("zmesh.hemisphere.obj");
const plane = initPlane(10, 10);
defer plane.deinit();
if (save) plane.saveToObj("zmesh.plane.obj");
const icosahedron = initIcosahedron();
defer icosahedron.deinit();
if (save) icosahedron.saveToObj("zmesh.icosahedron.obj");
const dodecahedron = initDodecahedron();
defer dodecahedron.deinit();
if (save) dodecahedron.saveToObj("zmesh.dodecahedron.obj");
const octahedron = initOctahedron();
defer octahedron.deinit();
if (save) octahedron.saveToObj("zmesh.octahedron.obj");
const tetrahedron = initTetrahedron();
defer tetrahedron.deinit();
if (save) tetrahedron.saveToObj("zmesh.tetrahedron.obj");
var cube = initCube();
defer cube.deinit();
cube.unweld();
cube.computeNormals();
if (save) cube.saveToObj("zmesh.cube.obj");
const rock = initRock(1337, 3);
defer rock.deinit();
if (save) rock.saveToObj("zmesh.rock.obj");
const disk = initDisk(3.0, 10, &.{ 1, 2, 3 }, &.{ 0, 1, 0 });
defer disk.deinit();
if (save) disk.saveToObj("zmesh.disk.obj");
}
test "zmesh.clone" {
init(std.testing.allocator);
defer deinit();
const cube = initCube();
defer cube.deinit();
var clone0 = cube.clone();
defer clone0.deinit();
try expect(@ptrToInt(clone0.handle) != @ptrToInt(cube.handle));
}
test "zmesh.merge" {
init(std.testing.allocator);
defer deinit();
var cube = initCube();
defer cube.deinit();
var sphere = initSubdividedSphere(3);
defer sphere.deinit();
cube.translate(0, 2, 0);
sphere.merge(cube);
cube.translate(0, 2, 0);
sphere.merge(cube);
if (save) sphere.saveToObj("zmesh.merge.obj");
}
test "zmesh.invert" {
init(std.testing.allocator);
defer deinit();
var hemisphere = initParametricSphere(10, 10);
defer hemisphere.deinit();
hemisphere.invert(0, 0);
hemisphere.removeDegenerate(0.001);
hemisphere.unweld();
hemisphere.weld(0.001, null);
if (save) hemisphere.saveToObj("zmesh.invert.obj");
} | modules/graphics/vendored/zmesh/src/zmesh.zig |
const std = @import("std");
const math = std.math;
const expect = std.testing.expect;
const kernel = @import("trig.zig");
const rem_pio2 = @import("rem_pio2.zig").rem_pio2;
const rem_pio2f = @import("rem_pio2f.zig").rem_pio2f;
pub fn __tanh(x: f16) callconv(.C) f16 {
// TODO: more efficient implementation
return @floatCast(f16, tanf(x));
}
pub fn tanf(x: f32) callconv(.C) f32 {
// Small multiples of pi/2 rounded to double precision.
const t1pio2: f64 = 1.0 * math.pi / 2.0; // 0x3FF921FB, 0x54442D18
const t2pio2: f64 = 2.0 * math.pi / 2.0; // 0x400921FB, 0x54442D18
const t3pio2: f64 = 3.0 * math.pi / 2.0; // 0x4012D97C, 0x7F3321D2
const t4pio2: f64 = 4.0 * math.pi / 2.0; // 0x401921FB, 0x54442D18
var ix = @bitCast(u32, x);
const sign = ix >> 31 != 0;
ix &= 0x7fffffff;
if (ix <= 0x3f490fda) { // |x| ~<= pi/4
if (ix < 0x39800000) { // |x| < 2**-12
// raise inexact if x!=0 and underflow if subnormal
math.doNotOptimizeAway(if (ix < 0x00800000) x / 0x1p120 else x + 0x1p120);
return x;
}
return kernel.__tandf(x, false);
}
if (ix <= 0x407b53d1) { // |x| ~<= 5*pi/4
if (ix <= 0x4016cbe3) { // |x| ~<= 3pi/4
return kernel.__tandf((if (sign) x + t1pio2 else x - t1pio2), true);
} else {
return kernel.__tandf((if (sign) x + t2pio2 else x - t2pio2), false);
}
}
if (ix <= 0x40e231d5) { // |x| ~<= 9*pi/4
if (ix <= 0x40afeddf) { // |x| ~<= 7*pi/4
return kernel.__tandf((if (sign) x + t3pio2 else x - t3pio2), true);
} else {
return kernel.__tandf((if (sign) x + t4pio2 else x - t4pio2), false);
}
}
// tan(Inf or NaN) is NaN
if (ix >= 0x7f800000) {
return x - x;
}
var y: f64 = undefined;
const n = rem_pio2f(x, &y);
return kernel.__tandf(y, n & 1 != 0);
}
pub fn tan(x: f64) callconv(.C) f64 {
var ix = @bitCast(u64, x) >> 32;
ix &= 0x7fffffff;
// |x| ~< pi/4
if (ix <= 0x3fe921fb) {
if (ix < 0x3e400000) { // |x| < 2**-27
// raise inexact if x!=0 and underflow if subnormal
math.doNotOptimizeAway(if (ix < 0x00100000) x / 0x1p120 else x + 0x1p120);
return x;
}
return kernel.__tan(x, 0.0, false);
}
// tan(Inf or NaN) is NaN
if (ix >= 0x7ff00000) {
return x - x;
}
var y: [2]f64 = undefined;
const n = rem_pio2(x, &y);
return kernel.__tan(y[0], y[1], n & 1 != 0);
}
pub fn __tanx(x: f80) callconv(.C) f80 {
// TODO: more efficient implementation
return @floatCast(f80, tanq(x));
}
pub fn tanq(x: f128) callconv(.C) f128 {
// TODO: more correct implementation
return tan(@floatCast(f64, x));
}
test "tan" {
try expect(tan(@as(f32, 0.0)) == tanf(0.0));
try expect(tan(@as(f64, 0.0)) == tan(0.0));
}
test "tan32" {
const epsilon = 0.00001;
try expect(math.approxEqAbs(f32, tanf(0.0), 0.0, epsilon));
try expect(math.approxEqAbs(f32, tanf(0.2), 0.202710, epsilon));
try expect(math.approxEqAbs(f32, tanf(0.8923), 1.240422, epsilon));
try expect(math.approxEqAbs(f32, tanf(1.5), 14.101420, epsilon));
try expect(math.approxEqAbs(f32, tanf(37.45), -0.254397, epsilon));
try expect(math.approxEqAbs(f32, tanf(89.123), 2.285852, epsilon));
}
test "tan64" {
const epsilon = 0.000001;
try expect(math.approxEqAbs(f64, tan(0.0), 0.0, epsilon));
try expect(math.approxEqAbs(f64, tan(0.2), 0.202710, epsilon));
try expect(math.approxEqAbs(f64, tan(0.8923), 1.240422, epsilon));
try expect(math.approxEqAbs(f64, tan(1.5), 14.101420, epsilon));
try expect(math.approxEqAbs(f64, tan(37.45), -0.254397, epsilon));
try expect(math.approxEqAbs(f64, tan(89.123), 2.2858376, epsilon));
}
test "tan32.special" {
try expect(tanf(0.0) == 0.0);
try expect(tanf(-0.0) == -0.0);
try expect(math.isNan(tanf(math.inf(f32))));
try expect(math.isNan(tanf(-math.inf(f32))));
try expect(math.isNan(tanf(math.nan(f32))));
}
test "tan64.special" {
try expect(tan(0.0) == 0.0);
try expect(tan(-0.0) == -0.0);
try expect(math.isNan(tan(math.inf(f64))));
try expect(math.isNan(tan(-math.inf(f64))));
try expect(math.isNan(tan(math.nan(f64))));
} | lib/std/special/compiler_rt/tan.zig |
const std = @import("std");
const mem = std.mem;
// TODO See stdlib, this is a modified non vectorized implementation
pub const ChaCha20Stream = struct {
const math = std.math;
pub const BlockVec = [16]u32;
pub fn initContext(key: [8]u32, d: [4]u32) BlockVec {
const c = "expand 32-byte k";
const constant_le = comptime [4]u32{
mem.readIntLittle(u32, c[0..4]),
mem.readIntLittle(u32, c[4..8]),
mem.readIntLittle(u32, c[8..12]),
mem.readIntLittle(u32, c[12..16]),
};
return BlockVec{
constant_le[0], constant_le[1], constant_le[2], constant_le[3],
key[0], key[1], key[2], key[3],
key[4], key[5], key[6], key[7],
d[0], d[1], d[2], d[3],
};
}
const QuarterRound = struct {
a: usize,
b: usize,
c: usize,
d: usize,
};
fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound {
return QuarterRound{
.a = a,
.b = b,
.c = c,
.d = d,
};
}
fn chacha20Core(x: *BlockVec, input: BlockVec) callconv(.Inline) void {
x.* = input;
const rounds = comptime [_]QuarterRound{
Rp(0, 4, 8, 12),
Rp(1, 5, 9, 13),
Rp(2, 6, 10, 14),
Rp(3, 7, 11, 15),
Rp(0, 5, 10, 15),
Rp(1, 6, 11, 12),
Rp(2, 7, 8, 13),
Rp(3, 4, 9, 14),
};
comptime var j: usize = 0;
inline while (j < 20) : (j += 2) {
inline for (rounds) |r| {
x[r.a] +%= x[r.b];
x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16));
x[r.c] +%= x[r.d];
x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12));
x[r.a] +%= x[r.b];
x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8));
x[r.c] +%= x[r.d];
x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7));
}
}
}
fn hashToBytes(out: *[64]u8, x: BlockVec) callconv(.Inline) void {
var i: usize = 0;
while (i < 4) : (i += 1) {
mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0]);
mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1]);
mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2]);
mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3]);
}
}
fn contextFeedback(x: *BlockVec, ctx: BlockVec) callconv(.Inline) void {
var i: usize = 0;
while (i < 16) : (i += 1) {
x[i] +%= ctx[i];
}
}
// TODO: Optimize this
pub fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, ctx: *BlockVec, idx: *usize, buf: *[64]u8) void {
var x: BlockVec = undefined;
const start_idx = idx.*;
var i: usize = 0;
while (i < in.len) {
if (idx.* % 64 == 0) {
if (idx.* != 0) {
ctx.*[12] += 1;
}
chacha20Core(x[0..], ctx.*);
contextFeedback(&x, ctx.*);
hashToBytes(buf, x);
}
out[i] = in[i] ^ buf[idx.* % 64];
i += 1;
idx.* += 1;
}
}
};
pub fn keyToWords(key: [32]u8) [8]u32 {
var k: [8]u32 = undefined;
var i: usize = 0;
while (i < 8) : (i += 1) {
k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]);
}
return k;
}
// See std.crypto.core.modes.ctr
/// This mode creates a key stream by encrypting an incrementing counter using a block cipher, and adding it to the source material.
pub fn ctr(
comptime BlockCipher: anytype,
block_cipher: BlockCipher,
dst: []u8,
src: []const u8,
counterInt: *u128,
idx: *usize,
endian: comptime std.builtin.Endian,
) void {
std.debug.assert(dst.len >= src.len);
const block_length = BlockCipher.block_length;
var cur_idx: usize = 0;
const offset = idx.* % block_length;
if (offset != 0) {
const part_len = std.math.min(block_length - offset, src.len);
var counter: [BlockCipher.block_length]u8 = undefined;
mem.writeInt(u128, &counter, counterInt.*, endian);
var pad = [_]u8{0} ** block_length;
mem.copy(u8, pad[offset..], src[0..part_len]);
block_cipher.xor(&pad, &pad, counter);
mem.copy(u8, dst[0..part_len], pad[offset..][0..part_len]);
cur_idx += part_len;
idx.* += part_len;
if (idx.* % block_length == 0)
counterInt.* += 1;
}
const start_idx = cur_idx;
const remaining = src.len - cur_idx;
cur_idx = 0;
const parallel_count = BlockCipher.block.parallel.optimal_parallel_blocks;
const wide_block_length = parallel_count * 16;
if (remaining >= wide_block_length) {
var counters: [parallel_count * 16]u8 = undefined;
while (cur_idx + wide_block_length <= remaining) : (cur_idx += wide_block_length) {
comptime var j = 0;
inline while (j < parallel_count) : (j += 1) {
mem.writeInt(u128, counters[j * 16 .. j * 16 + 16], counterInt.*, endian);
counterInt.* +%= 1;
}
block_cipher.xorWide(parallel_count, dst[start_idx..][cur_idx .. cur_idx + wide_block_length][0..wide_block_length], src[start_idx..][cur_idx .. cur_idx + wide_block_length][0..wide_block_length], counters);
idx.* += wide_block_length;
}
}
while (cur_idx + block_length <= remaining) : (cur_idx += block_length) {
var counter: [BlockCipher.block_length]u8 = undefined;
mem.writeInt(u128, &counter, counterInt.*, endian);
counterInt.* +%= 1;
block_cipher.xor(dst[start_idx..][cur_idx .. cur_idx + block_length][0..block_length], src[start_idx..][cur_idx .. cur_idx + block_length][0..block_length], counter);
idx.* += block_length;
}
if (cur_idx < remaining) {
std.debug.assert(idx.* % block_length == 0);
var counter: [BlockCipher.block_length]u8 = undefined;
mem.writeInt(u128, &counter, counterInt.*, endian);
var pad = [_]u8{0} ** block_length;
mem.copy(u8, &pad, src[start_idx..][cur_idx..]);
block_cipher.xor(&pad, &pad, counter);
mem.copy(u8, dst[start_idx..][cur_idx..], pad[0 .. remaining - cur_idx]);
idx.* += remaining - cur_idx;
if (idx.* % block_length == 0)
counterInt.* +%= 1;
}
}
// Ported from BearSSL's ec_prime_i31 engine
pub const ecc = struct {
pub const SECP384R1 = struct {
pub const point_len = 96;
const order = [point_len / 2]u8{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC7, 0x63, 0x4D, 0x81, 0xF4, 0x37, 0x2D, 0xDF,
0x58, 0x1A, 0x0D, 0xB2, 0x48, 0xB0, 0xA7, 0x7A,
0xEC, 0xEC, 0x19, 0x6A, 0xCC, 0xC5, 0x29, 0x73,
};
const P = [_]u32{
0x0000018C, 0x7FFFFFFF, 0x00000001, 0x00000000,
0x7FFFFFF8, 0x7FFFFFEF, 0x7FFFFFFF, 0x7FFFFFFF,
0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF,
0x7FFFFFFF, 0x00000FFF,
};
const R2 = [_]u32{
0x0000018C, 0x00000000, 0x00000080, 0x7FFFFE00,
0x000001FF, 0x00000800, 0x00000000, 0x7FFFE000,
0x00001FFF, 0x00008000, 0x00008000, 0x00000000,
0x00000000, 0x00000000,
};
const B = [_]u32{
0x0000018C, 0x6E666840, 0x070D0392, 0x5D810231,
0x7651D50C, 0x17E218D6, 0x1B192002, 0x44EFE441,
0x3A524E2B, 0x2719BA5F, 0x41F02209, 0x36C5643E,
0x5813EFFE, 0x000008A5,
};
const base_point = [point_len]u8{
0xAA, 0x87, 0xCA, 0x22, 0xBE, 0x8B, 0x05, 0x37,
0x8E, 0xB1, 0xC7, 0x1E, 0xF3, 0x20, 0xAD, 0x74,
0x6E, 0x1D, 0x3B, 0x62, 0x8B, 0xA7, 0x9B, 0x98,
0x59, 0xF7, 0x41, 0xE0, 0x82, 0x54, 0x2A, 0x38,
0x55, 0x02, 0xF2, 0x5D, 0xBF, 0x55, 0x29, 0x6C,
0x3A, 0x54, 0x5E, 0x38, 0x72, 0x76, 0x0A, 0xB7,
0x36, 0x17, 0xDE, 0x4A, 0x96, 0x26, 0x2C, 0x6F,
0x5D, 0x9E, 0x98, 0xBF, 0x92, 0x92, 0xDC, 0x29,
0xF8, 0xF4, 0x1D, 0xBD, 0x28, 0x9A, 0x14, 0x7C,
0xE9, 0xDA, 0x31, 0x13, 0xB5, 0xF0, 0xB8, 0xC0,
0x0A, 0x60, 0xB1, 0xCE, 0x1D, 0x7E, 0x81, 0x9D,
0x7A, 0x43, 0x1D, 0x7C, 0x90, 0xEA, 0x0E, 0x5F,
};
comptime {
std.debug.assert((P[0] - (P[0] >> 5) + 7) >> 2 == point_len + 1);
}
};
pub const SECP256R1 = struct {
pub const point_len = 64;
const order = [point_len / 2]u8{
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84,
0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51,
};
const P = [_]u32{
0x00000108, 0x7FFFFFFF,
0x7FFFFFFF, 0x7FFFFFFF,
0x00000007, 0x00000000,
0x00000000, 0x00000040,
0x7FFFFF80, 0x000000FF,
};
const R2 = [_]u32{
0x00000108, 0x00014000,
0x00018000, 0x00000000,
0x7FF40000, 0x7FEFFFFF,
0x7FF7FFFF, 0x7FAFFFFF,
0x005FFFFF, 0x00000000,
};
const B = [_]u32{
0x00000108, 0x6FEE1803,
0x6229C4BD, 0x21B139BE,
0x327150AA, 0x3567802E,
0x3F7212ED, 0x012E4355,
0x782DD38D, 0x0000000E,
};
const base_point = [point_len]u8{
0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47,
0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2,
0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0,
0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96,
0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B,
0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16,
0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE,
0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5,
};
comptime {
std.debug.assert((P[0] - (P[0] >> 5) + 7) >> 2 == point_len + 1);
}
};
fn jacobian_len(comptime Curve: type) usize {
return @divTrunc(Curve.order.len * 8 + 61, 31);
}
fn Jacobian(comptime Curve: type) type {
return [3][jacobian_len(Curve)]u32;
}
fn zero_jacobian(comptime Curve: type) Jacobian(Curve) {
var result = std.mem.zeroes(Jacobian(Curve));
result[0][0] = Curve.P[0];
result[1][0] = Curve.P[0];
result[2][0] = Curve.P[0];
return result;
}
pub fn scalarmult(
comptime Curve: type,
point: [Curve.point_len]u8,
k: []const u8,
) ![Curve.point_len]u8 {
var P: Jacobian(Curve) = undefined;
var res: u32 = decode_to_jacobian(Curve, &P, point);
point_mul(Curve, &P, k);
var out: [Curve.point_len]u8 = undefined;
encode_from_jacobian(Curve, &out, P);
if (res == 0)
return error.MultiplicationFailed;
return out;
}
pub fn KeyPair(comptime Curve: type) type {
return struct {
public_key: [Curve.point_len]u8,
secret_key: [Curve.point_len / 2]u8,
};
}
pub fn make_key_pair(comptime Curve: type, rand_bytes: [Curve.point_len / 2]u8) KeyPair(Curve) {
var key_bytes = rand_bytes;
comptime var mask: u8 = 0xFF;
comptime {
while (mask >= Curve.order[0]) {
mask >>= 1;
}
}
key_bytes[0] &= mask;
key_bytes[Curve.point_len / 2 - 1] |= 0x01;
return .{
.secret_key = key_bytes,
.public_key = scalarmult(Curve, Curve.base_point, &key_bytes) catch unreachable,
};
}
fn jacobian_with_one_set(comptime Curve: type, comptime fields: [2][jacobian_len(Curve)]u32) Jacobian(Curve) {
comptime const plen = (Curve.P[0] + 63) >> 5;
return fields ++ [1][jacobian_len(Curve)]u32{
[2]u32{ Curve.P[0], 1 } ++ ([1]u32{0} ** (plen - 2)),
};
}
fn encode_from_jacobian(comptime Curve: type, point: *[Curve.point_len]u8, P: Jacobian(Curve)) void {
var Q = P;
const T = comptime jacobian_with_one_set(Curve, [2][jacobian_len(Curve)]u32{ undefined, undefined });
_ = run_code(Curve, &Q, T, &code.affine);
encode_jacobian_part(point[0 .. Curve.point_len / 2], &Q[0]);
encode_jacobian_part(point[Curve.point_len / 2 ..], &Q[1]);
}
fn point_mul(comptime Curve: type, P: *Jacobian(Curve), x: []const u8) void {
var P2 = P.*;
point_double(Curve, &P2);
var P3 = P.*;
point_add(Curve, &P3, P2);
var Q = zero_jacobian(Curve);
var qz: u32 = 1;
var xlen = x.len;
var xidx: usize = 0;
while (xlen > 0) : ({
xlen -= 1;
xidx += 1;
}) {
var k: u3 = 6;
while (true) : (k -= 2) {
point_double(Curve, &Q);
point_double(Curve, &Q);
var T = P.*;
var U = Q;
const bits = @as(u32, x[xidx] >> k) & 3;
const bnz = NEQ(bits, 0);
CCOPY(EQ(bits, 2), mem.asBytes(&T), mem.asBytes(&P2));
CCOPY(EQ(bits, 3), mem.asBytes(&T), mem.asBytes(&P3));
point_add(Curve, &U, T);
CCOPY(bnz & qz, mem.asBytes(&Q), mem.asBytes(&T));
CCOPY(bnz & ~qz, mem.asBytes(&Q), mem.asBytes(&U));
qz &= ~bnz;
if (k == 0)
break;
}
}
P.* = Q;
}
fn point_double(comptime Curve: type, P: *Jacobian(Curve)) callconv(.Inline) void {
_ = run_code(Curve, P, P.*, &code.double);
}
fn point_add(comptime Curve: type, P1: *Jacobian(Curve), P2: Jacobian(Curve)) callconv(.Inline) void {
_ = run_code(Curve, P1, P2, &code._add);
}
fn decode_to_jacobian(
comptime Curve: type,
out: *Jacobian(Curve),
point: [Curve.point_len]u8,
) u32 {
out.* = zero_jacobian(Curve);
var result = decode_mod(Curve, &out.*[0], point[0 .. Curve.point_len / 2].*);
result &= decode_mod(Curve, &out.*[1], point[Curve.point_len / 2 ..].*);
const zlen = comptime ((Curve.P[0] + 63) >> 5);
comptime std.debug.assert(zlen == @typeInfo(@TypeOf(Curve.R2)).Array.len);
comptime std.debug.assert(zlen == @typeInfo(@TypeOf(Curve.B)).Array.len);
const Q = comptime jacobian_with_one_set(Curve, [2][jacobian_len(Curve)]u32{ Curve.R2, Curve.B });
result &= ~run_code(Curve, out, Q, &code.check);
return result;
}
const code = struct {
const P1x = 0;
const P1y = 1;
const P1z = 2;
const P2x = 3;
const P2y = 4;
const P2z = 5;
const Px = 0;
const Py = 1;
const Pz = 2;
const t1 = 6;
const t2 = 7;
const t3 = 8;
const t4 = 9;
const t5 = 10;
const t6 = 11;
const t7 = 12;
const t8 = 3;
const t9 = 4;
const t10 = 5;
fn MSET(comptime d: u16, comptime a: u16) u16 {
return 0x0000 + (d << 8) + (a << 4);
}
fn MADD(comptime d: u16, comptime a: u16) u16 {
return 0x1000 + (d << 8) + (a << 4);
}
fn MSUB(comptime d: u16, comptime a: u16) u16 {
return 0x2000 + (d << 8) + (a << 4);
}
fn MMUL(comptime d: u16, comptime a: u16, comptime b: u16) u16 {
return 0x3000 + (d << 8) + (a << 4) + b;
}
fn MINV(comptime d: u16, comptime a: u16, comptime b: u16) u16 {
return 0x4000 + (d << 8) + (a << 4) + b;
}
fn MTZ(comptime d: u16) u16 {
return 0x5000 + (d << 8);
}
const ENDCODE = 0;
const check = [_]u16{
// Convert x and y to Montgomery representation.
MMUL(t1, P1x, P2x),
MMUL(t2, P1y, P2x),
MSET(P1x, t1),
MSET(P1y, t2),
// Compute x^3 in t1.
MMUL(t2, P1x, P1x),
MMUL(t1, P1x, t2),
// Subtract 3*x from t1.
MSUB(t1, P1x),
MSUB(t1, P1x),
MSUB(t1, P1x),
// Add b.
MADD(t1, P2y),
// Compute y^2 in t2.
MMUL(t2, P1y, P1y),
// Compare y^2 with x^3 - 3*x + b; they must match.
MSUB(t1, t2),
MTZ(t1),
// Set z to 1 (in Montgomery representation).
MMUL(P1z, P2x, P2z),
ENDCODE,
};
const double = [_]u16{
// Compute z^2 (in t1).
MMUL(t1, Pz, Pz),
// Compute x-z^2 (in t2) and then x+z^2 (in t1).
MSET(t2, Px),
MSUB(t2, t1),
MADD(t1, Px),
// Compute m = 3*(x+z^2)*(x-z^2) (in t1).
MMUL(t3, t1, t2),
MSET(t1, t3),
MADD(t1, t3),
MADD(t1, t3),
// Compute s = 4*x*y^2 (in t2) and 2*y^2 (in t3).
MMUL(t3, Py, Py),
MADD(t3, t3),
MMUL(t2, Px, t3),
MADD(t2, t2),
// Compute x' = m^2 - 2*s.
MMUL(Px, t1, t1),
MSUB(Px, t2),
MSUB(Px, t2),
// Compute z' = 2*y*z.
MMUL(t4, Py, Pz),
MSET(Pz, t4),
MADD(Pz, t4),
// Compute y' = m*(s - x') - 8*y^4. Note that we already have
// 2*y^2 in t3.
MSUB(t2, Px),
MMUL(Py, t1, t2),
MMUL(t4, t3, t3),
MSUB(Py, t4),
MSUB(Py, t4),
ENDCODE,
};
const _add = [_]u16{
// Compute u1 = x1*z2^2 (in t1) and s1 = y1*z2^3 (in t3).
MMUL(t3, P2z, P2z),
MMUL(t1, P1x, t3),
MMUL(t4, P2z, t3),
MMUL(t3, P1y, t4),
// Compute u2 = x2*z1^2 (in t2) and s2 = y2*z1^3 (in t4).
MMUL(t4, P1z, P1z),
MMUL(t2, P2x, t4),
MMUL(t5, P1z, t4),
MMUL(t4, P2y, t5),
//Compute h = u2 - u1 (in t2) and r = s2 - s1 (in t4).
MSUB(t2, t1),
MSUB(t4, t3),
// Report cases where r = 0 through the returned flag.
MTZ(t4),
// Compute u1*h^2 (in t6) and h^3 (in t5).
MMUL(t7, t2, t2),
MMUL(t6, t1, t7),
MMUL(t5, t7, t2),
// Compute x3 = r^2 - h^3 - 2*u1*h^2.
// t1 and t7 can be used as scratch registers.
MMUL(P1x, t4, t4),
MSUB(P1x, t5),
MSUB(P1x, t6),
MSUB(P1x, t6),
//Compute y3 = r*(u1*h^2 - x3) - s1*h^3.
MSUB(t6, P1x),
MMUL(P1y, t4, t6),
MMUL(t1, t5, t3),
MSUB(P1y, t1),
//Compute z3 = h*z1*z2.
MMUL(t1, P1z, P2z),
MMUL(P1z, t1, t2),
ENDCODE,
};
const affine = [_]u16{
// Save z*R in t1.
MSET(t1, P1z),
// Compute z^3 in t2.
MMUL(t2, P1z, P1z),
MMUL(t3, P1z, t2),
MMUL(t2, t3, P2z),
// Invert to (1/z^3) in t2.
MINV(t2, t3, t4),
// Compute y.
MSET(t3, P1y),
MMUL(P1y, t2, t3),
// Compute (1/z^2) in t3.
MMUL(t3, t2, t1),
// Compute x.
MSET(t2, P1x),
MMUL(P1x, t2, t3),
ENDCODE,
};
};
fn decode_mod(
comptime Curve: type,
x: *[jacobian_len(Curve)]u32,
src: [Curve.point_len / 2]u8,
) u32 {
const mlen = comptime ((Curve.P[0] + 31) >> 5);
const tlen = comptime std.math.max(mlen << 2, Curve.point_len / 2) + 4;
var r: u32 = 0;
var pass: usize = 0;
while (pass < 2) : (pass += 1) {
var v: usize = 1;
var acc: u32 = 0;
var acc_len: u32 = 0;
var u: usize = 0;
while (u < tlen) : (u += 1) {
const b = if (u < Curve.point_len / 2)
@as(u32, src[Curve.point_len / 2 - 1 - u])
else
0;
acc |= b << @truncate(u5, acc_len);
acc_len += 8;
if (acc_len >= 31) {
const xw = acc & 0x7FFFFFFF;
acc_len -= 31;
acc = b >> @truncate(u5, 8 - acc_len);
if (v <= mlen) {
if (pass != 0) {
x[v] = r & xw;
} else {
const cc = @bitCast(u32, CMP(xw, Curve.P[v]));
r = MUX(EQ(cc, 0), r, cc);
}
} else if (pass == 0) {
r = MUX(EQ(xw, 0), r, 1);
}
v += 1;
}
}
r >>= 1;
r |= (r << 1);
}
x[0] = Curve.P[0];
return r & 1;
}
fn run_code(
comptime Curve: type,
P1: *Jacobian(Curve),
P2: Jacobian(Curve),
comptime Code: []const u16,
) u32 {
comptime const jaclen = jacobian_len(Curve);
var t: [13][jaclen]u32 = undefined;
var result: u32 = 1;
t[0..3].* = P1.*;
t[3..6].* = P2;
comptime var u: usize = 0;
inline while (true) : (u += 1) {
comptime var op = Code[u];
if (op == 0)
break;
comptime const d = (op >> 8) & 0x0F;
comptime const a = (op >> 4) & 0x0F;
comptime const b = op & 0x0F;
op >>= 12;
switch (op) {
0 => t[d] = t[a],
1 => {
var ctl = add(&t[d], &t[a], 1);
ctl |= NOT(sub(&t[d], &Curve.P, 0));
_ = sub(&t[d], &Curve.P, ctl);
},
2 => _ = add(&t[d], &Curve.P, sub(&t[d], &t[a], 1)),
3 => montymul(&t[d], &t[a], &t[b], &Curve.P, 1),
4 => {
var tp: [Curve.point_len / 2]u8 = undefined;
encode_jacobian_part(&tp, &Curve.P);
tp[Curve.point_len / 2 - 1] -= 2;
modpow(Curve, &t[d], tp, 1, &t[a], &t[b]);
},
else => result &= ~iszero(&t[d]),
}
}
P1.* = t[0..3].*;
return result;
}
fn MUL31(x: u32, y: u32) callconv(.Inline) u64 {
return @as(u64, x) * @as(u64, y);
}
fn MUL31_lo(x: u32, y: u32) callconv(.Inline) u32 {
return (x *% y) & 0x7FFFFFFF;
}
fn MUX(ctl: u32, x: u32, y: u32) callconv(.Inline) u32 {
return y ^ (@bitCast(u32, -@bitCast(i32, ctl)) & (x ^ y));
}
fn NOT(ctl: u32) callconv(.Inline) u32 {
return ctl ^ 1;
}
fn NEQ(x: u32, y: u32) callconv(.Inline) u32 {
const q = x ^ y;
return (q | @bitCast(u32, -@bitCast(i32, q))) >> 31;
}
fn EQ(x: u32, y: u32) callconv(.Inline) u32 {
const q = x ^ y;
return NOT((q | @bitCast(u32, -@bitCast(i32, q))) >> 31);
}
fn CMP(x: u32, y: u32) callconv(.Inline) i32 {
return @bitCast(i32, GT(x, y)) | -@bitCast(i32, GT(y, x));
}
fn GT(x: u32, y: u32) callconv(.Inline) u32 {
const z = y -% x;
return (z ^ ((x ^ y) & (x ^ z))) >> 31;
}
fn LT(x: u32, y: u32) callconv(.Inline) u32 {
return GT(y, x);
}
fn GE(x: u32, y: u32) callconv(.Inline) u32 {
return NOT(GT(y, x));
}
fn CCOPY(ctl: u32, dst: []u8, src: []const u8) void {
for (src) |s, i| {
dst[i] = @truncate(u8, MUX(ctl, s, dst[i]));
}
}
fn set_zero(out: [*]u32, bit_len: u32) callconv(.Inline) void {
out[0] = bit_len;
mem.set(u32, (out + 1)[0 .. (bit_len + 31) >> 5], 0);
}
fn divrem(_hi: u32, _lo: u32, d: u32, r: *u32) u32 {
var hi = _hi;
var lo = _lo;
var q: u32 = 0;
const ch = EQ(hi, d);
hi = MUX(ch, 0, hi);
var k: u5 = 31;
while (k > 0) : (k -= 1) {
const j = @truncate(u5, 32 - @as(u6, k));
const w = (hi << j) | (lo >> k);
const ctl = GE(w, d) | (hi >> k);
const hi2 = (w -% d) >> j;
const lo2 = lo -% (d << k);
hi = MUX(ctl, hi2, hi);
lo = MUX(ctl, lo2, lo);
q |= ctl << k;
}
const cf = GE(lo, d) | hi;
q |= cf;
r.* = MUX(cf, lo -% d, lo);
return q;
}
fn div(hi: u32, lo: u32, d: u32) callconv(.Inline) u32 {
var r: u32 = undefined;
return divrem(hi, lo, d, &r);
}
fn muladd_small(x: [*]u32, z: u32, m: [*]const u32) void {
var a0: u32 = undefined;
var a1: u32 = undefined;
var b0: u32 = undefined;
const mblr = @intCast(u5, m[0] & 31);
const mlen = (m[0] + 31) >> 5;
const hi = x[mlen];
if (mblr == 0) {
a0 = x[mlen];
mem.copyBackwards(u32, (x + 2)[0 .. mlen - 1], (x + 1)[0 .. mlen - 1]);
x[1] = z;
a1 = x[mlen];
b0 = m[mlen];
} else {
a0 = ((x[mlen] << (31 - mblr)) | (x[mlen - 1] >> mblr)) & 0x7FFFFFFF;
mem.copyBackwards(u32, (x + 2)[0 .. mlen - 1], (x + 1)[0 .. mlen - 1]);
x[1] = z;
a1 = ((x[mlen] << (31 - mblr)) | (x[mlen - 1] >> mblr)) & 0x7FFFFFFF;
b0 = ((m[mlen] << (31 - mblr)) | (m[mlen - 1] >> mblr)) & 0x7FFFFFFF;
}
const g = div(a0 >> 1, a1 | (a0 << 31), b0);
const q = MUX(EQ(a0, b0), 0x7FFFFFFF, MUX(EQ(g, 0), 0, g -% 1));
var cc: u32 = 0;
var tb: u32 = 1;
var u: usize = 1;
while (u <= mlen) : (u += 1) {
const mw = m[u];
const zl = MUL31(mw, q) + cc;
cc = @truncate(u32, zl >> 31);
const zw = @truncate(u32, zl) & 0x7FFFFFFF;
const xw = x[u];
var nxw = xw -% zw;
cc += nxw >> 31;
nxw &= 0x7FFFFFFF;
x[u] = nxw;
tb = MUX(EQ(nxw, mw), tb, GT(nxw, mw));
}
const over = GT(cc, hi);
const under = ~over & (tb | LT(cc, hi));
_ = add(x, m, over);
_ = sub(x, m, under);
}
fn to_monty(x: [*]u32, m: [*]const u32) void {
const mlen = (m[0] + 31) >> 5;
var k = mlen;
while (k > 0) : (k -= 1) {
muladd_small(x, 0, m);
}
}
fn modpow(
comptime Curve: type,
x: *[jacobian_len(Curve)]u32,
e: [Curve.point_len / 2]u8,
m0i: u32,
t1: *[jacobian_len(Curve)]u32,
t2: *[jacobian_len(Curve)]u32,
) void {
comptime const jaclen = jacobian_len(Curve);
t1.* = x.*;
to_monty(t1, &Curve.P);
set_zero(x, Curve.P[0]);
x[1] = 1;
comptime const bitlen = (Curve.point_len / 2) << 3;
var k: usize = 0;
while (k < bitlen) : (k += 1) {
const ctl = (e[Curve.point_len / 2 - 1 - (k >> 3)] >> (@truncate(u3, k & 7))) & 1;
montymul(t2, x, t1, &Curve.P, m0i);
CCOPY(ctl, mem.asBytes(x), mem.asBytes(t2));
montymul(t2, t1, t1, &Curve.P, m0i);
t1.* = t2.*;
}
}
fn encode_jacobian_part(dst: []u8, x: [*]const u32) void {
const xlen = (x[0] + 31) >> 5;
var buf = @ptrToInt(dst.ptr) + dst.len;
var len: usize = dst.len;
var k: usize = 1;
var acc: u32 = 0;
var acc_len: u5 = 0;
while (len != 0) {
const w = if (k <= xlen) x[k] else 0;
k += 1;
if (acc_len == 0) {
acc = w;
acc_len = 31;
} else {
const z = acc | (w << acc_len);
acc_len -= 1;
acc = w >> (31 - acc_len);
if (len >= 4) {
buf -= 4;
len -= 4;
mem.writeIntBig(u32, @intToPtr([*]u8, buf)[0..4], z);
} else {
switch (len) {
3 => {
@intToPtr(*u8, buf - 3).* = @truncate(u8, z >> 16);
@intToPtr(*u8, buf - 2).* = @truncate(u8, z >> 8);
},
2 => @intToPtr(*u8, buf - 2).* = @truncate(u8, z >> 8),
1 => {},
else => unreachable,
}
@intToPtr(*u8, buf - 1).* = @truncate(u8, z);
return;
}
}
}
}
fn montymul(
out: [*]u32,
x: [*]const u32,
y: [*]const u32,
m: [*]const u32,
m0i: u32,
) void {
const len = (m[0] + 31) >> 5;
const len4 = len & ~@as(usize, 3);
set_zero(out, m[0]);
var dh: u32 = 0;
var u: usize = 0;
while (u < len) : (u += 1) {
const xu = x[u + 1];
const f = MUL31_lo(out[1] + MUL31_lo(x[u + 1], y[1]), m0i);
var r: u64 = 0;
var v: usize = 0;
while (v < len4) : (v += 4) {
comptime var j = 1;
inline while (j <= 4) : (j += 1) {
const z = out[v + j] +% MUL31(xu, y[v + j]) +% MUL31(f, m[v + j]) +% r;
r = z >> 31;
out[v + j - 1] = @truncate(u32, z) & 0x7FFFFFFF;
}
}
while (v < len) : (v += 1) {
const z = out[v + 1] +% MUL31(xu, y[v + 1]) +% MUL31(f, m[v + 1]) +% r;
r = z >> 31;
out[v] = @truncate(u32, z) & 0x7FFFFFFF;
}
dh += @truncate(u32, r);
out[len] = dh & 0x7FFFFFFF;
dh >>= 31;
}
out[0] = m[0];
const ctl = NEQ(dh, 0) | NOT(sub(out, m, 0));
_ = sub(out, m, ctl);
}
fn add(a: [*]u32, b: [*]const u32, ctl: u32) u32 {
var u: usize = 1;
var cc: u32 = 0;
const m = (a[0] + 63) >> 5;
while (u < m) : (u += 1) {
const aw = a[u];
const bw = b[u];
const naw = aw +% bw +% cc;
cc = naw >> 31;
a[u] = MUX(ctl, naw & 0x7FFFFFFF, aw);
}
return cc;
}
fn sub(a: [*]u32, b: [*]const u32, ctl: u32) u32 {
var cc: u32 = 0;
const m = (a[0] + 63) >> 5;
var u: usize = 1;
while (u < m) : (u += 1) {
const aw = a[u];
const bw = b[u];
const naw = aw -% bw -% cc;
cc = naw >> 31;
a[u] = MUX(ctl, naw & 0x7FFFFFFF, aw);
}
return cc;
}
fn iszero(arr: [*]const u32) u32 {
const mlen = (arr[0] + 63) >> 5;
var z: u32 = 0;
var u: usize = mlen - 1;
while (u > 0) : (u -= 1) {
z |= arr[u];
}
return ~(z | @bitCast(u32, -@bitCast(i32, z))) >> 31;
}
};
test "elliptic curve functions with secp384r1 curve" {
{
// Decode to Jacobian then encode again with no operations
var P: ecc.Jacobian(ecc.SECP384R1) = undefined;
var res: u32 = ecc.decode_to_jacobian(ecc.SECP384R1, &P, ecc.SECP384R1.base_point);
var out: [96]u8 = undefined;
ecc.encode_from_jacobian(ecc.SECP384R1, &out, P);
try std.testing.expectEqual(ecc.SECP384R1.base_point, out);
// Multiply by one, check that the result is still the base point
mem.set(u8, &out, 0);
ecc.point_mul(ecc.SECP384R1, &P, &[1]u8{1});
ecc.encode_from_jacobian(ecc.SECP384R1, &out, P);
try std.testing.expectEqual(ecc.SECP384R1.base_point, out);
}
{
// @TODO Remove this once std.crypto.rand works in .evented mode
var rand = blk: {
var seed: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined;
try std.os.getrandom(&seed);
break :blk &std.rand.DefaultCsprng.init(seed).random;
};
// Derive a shared secret from a Diffie-Hellman key exchange
var seed: [48]u8 = undefined;
rand.bytes(&seed);
const kp1 = ecc.make_key_pair(ecc.SECP384R1, seed);
rand.bytes(&seed);
const kp2 = ecc.make_key_pair(ecc.SECP384R1, seed);
const shared1 = try ecc.scalarmult(ecc.SECP384R1, kp1.public_key, &kp2.secret_key);
const shared2 = try ecc.scalarmult(ecc.SECP384R1, kp2.public_key, &kp1.secret_key);
try std.testing.expectEqual(shared1, shared2);
}
// @TODO Add tests with known points.
} | src/crypto.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const Source = @import("Source.zig");
const Compilation = @import("Compilation.zig");
const Tree = @import("Tree.zig");
const Diagnostics = @This();
pub const Message = struct {
tag: Tag,
loc: Source.Location = .{},
extra: Extra = .{ .none = {} },
pub const Extra = union {
str: []const u8,
tok_id: struct {
expected: Tree.Token.Id,
actual: Tree.Token.Id,
},
arguments: struct {
expected: u32,
actual: u32,
},
unsigned: u64,
signed: i64,
none: void,
};
};
pub const Tag = enum {
// Maybe someday this will no longer be needed.
todo,
error_directive,
elif_without_if,
elif_after_else,
else_without_if,
else_after_else,
endif_without_if,
unsupported_pragma,
line_simple_digit,
line_invalid_filename,
unterminated_conditional_directive,
invalid_preprocessing_directive,
macro_name_missing,
extra_tokens_directive_end,
expected_value_in_expr,
closing_paren,
to_match_paren,
to_match_brace,
to_match_bracket,
header_str_closing,
header_str_match,
string_literal_in_pp_expr,
float_literal_in_pp_expr,
defined_as_macro_name,
macro_name_must_be_identifier,
whitespace_after_macro_name,
hash_hash_at_start,
hash_hash_at_end,
pasting_formed_invalid,
missing_paren_param_list,
unterminated_macro_param_list,
invalid_token_param_list,
hash_not_followed_param,
expected_filename,
empty_filename,
expected_invalid,
expected_token,
expected_expr,
expected_integer_constant_expr,
missing_type_specifier,
multiple_storage_class,
static_assert_failure,
static_assert_failure_message,
expected_type,
cannot_combine_spec,
duplicate_decl_spec,
restrict_non_pointer,
expected_external_decl,
expected_ident_or_l_paren,
missing_declaration,
func_not_in_root,
illegal_initializer,
extern_initializer,
spec_from_typedef,
type_is_invalid,
param_before_var_args,
void_only_param,
void_param_qualified,
void_must_be_first_param,
invalid_storage_on_param,
threadlocal_non_var,
func_spec_non_func,
illegal_storage_on_func,
illegal_storage_on_global,
expected_stmt,
func_cannot_return_func,
func_cannot_return_array,
undeclared_identifier,
not_callable,
unsupported_str_cat,
static_func_not_global,
implicit_func_decl,
expected_param_decl,
invalid_old_style_params,
expected_fn_body,
invalid_void_param,
unused_value,
continue_not_in_loop,
break_not_in_loop_or_switch,
unreachable_code,
duplicate_label,
previous_label,
undeclared_label,
case_not_in_switch,
duplicate_switch_case_signed,
duplicate_switch_case_unsigned,
multiple_default,
previous_case,
expected_arguments,
expected_arguments_old,
expected_at_least_arguments,
invalid_static_star,
static_non_param,
array_qualifiers,
star_non_param,
variable_len_array_file_scope,
useless_static,
negative_array_size,
array_incomplete_elem,
array_func_elem,
static_non_outermost_array,
qualifier_non_outermost_array,
unterminated_macro_arg_list,
unknown_warning,
overflow_unsigned,
overflow_signed,
int_literal_too_big,
indirection_ptr,
addr_of_rvalue,
not_assignable,
ident_or_l_brace,
empty_enum,
redefinition,
previous_definition,
expected_identifier,
expected_str_literal,
parameter_missing,
empty_record,
wrong_tag,
expected_parens_around_typename,
alignof_expr,
invalid_sizeof,
macro_redefined,
generic_qual_type,
generic_duplicate,
generic_duplicate_default,
generic_no_match,
escape_sequence_overflow,
invalid_universal_character,
multichar_literal,
char_lit_too_wide,
must_use_struct,
must_use_union,
must_use_enum,
redefinition_different_sym,
redefinition_incompatible,
redefinition_of_parameter,
invalid_bin_types,
comparison_ptr_int,
comparison_distinct_ptr,
incompatible_pointers,
invalid_argument_un,
incompatible_assign,
implicit_ptr_to_int,
invalid_cast_to_float,
invalid_cast_to_pointer,
invalid_cast_type,
qual_cast,
invalid_index,
invalid_subscript,
array_after,
array_before,
statement_int,
statement_scalar,
func_should_return,
incompatible_return,
implicit_int_to_ptr,
func_does_not_return,
incompatible_param,
parameter_here,
atomic_array,
atomic_func,
atomic_incomplete,
addr_of_register,
variable_incomplete_ty,
alignas_on_func,
alignas_on_param,
minimum_alignment,
maximum_alignment,
negative_alignment,
align_ignored,
zero_align_ignored,
non_pow2_align,
pointer_mismatch,
static_assert_not_constant,
static_assert_missing_message,
unbound_vla,
array_too_large,
incompatible_ptr_init,
incompatible_ptr_assign,
vla_init,
func_init,
incompatible_init,
empty_scalar_init,
excess_scalar_init,
excess_str_init,
excess_struct_init,
excess_array_init,
str_init_too_long,
arr_init_too_long,
invalid_typeof,
division_by_zero,
builtin_choose_cond,
alignas_unavailable,
case_val_unavailable,
enum_val_unavailable,
incompatible_array_init,
initializer_overrides,
previous_initializer,
invalid_array_designator,
negative_array_designator,
oob_array_designator,
invalid_field_designator,
no_such_field_designator,
empty_aggregate_init_braces,
ptr_init_discards_quals,
ptr_assign_discards_quals,
};
const Options = struct {
@"unsupported-pragma": Kind = .warning,
@"c99-extensions": Kind = .warning,
@"implicit-int": Kind = .warning,
@"duplicate-decl-specifier": Kind = .warning,
@"missing-declaration": Kind = .warning,
@"extern-initializer": Kind = .warning,
@"implicit-function-declaration": Kind = .warning,
@"unused-value": Kind = .warning,
@"unreachable-code": Kind = .warning,
@"unknown-warning-option": Kind = .warning,
@"empty-struct": Kind = .off,
@"gnu-alignof-expression": Kind = .warning,
@"macro-redefined": Kind = .warning,
@"generic-qual-type": Kind = .warning,
multichar: Kind = .warning,
@"pointer-integer-compare": Kind = .warning,
@"compare-distinct-pointer-types": Kind = .warning,
@"literal-conversion": Kind = .warning,
@"cast-qualifiers": Kind = .warning,
@"array-bounds": Kind = .warning,
@"int-conversion": Kind = .warning,
@"pointer-type-mismatch": Kind = .warning,
@"c2x-extension": Kind = .warning,
@"incompatible-pointer-types": Kind = .warning,
@"excess-initializers": Kind = .warning,
@"division-by-zero": Kind = .warning,
@"initializer-overrides": Kind = .warning,
@"incompatible-pointer-types-discards-qualifiers": Kind = .warning,
};
list: std.ArrayList(Message),
color: bool = true,
fatal_errors: bool = false,
options: Options = .{},
errors: u32 = 0,
pub fn set(diag: *Diagnostics, name: []const u8, to: Kind) !void {
if (std.mem.eql(u8, name, "fatal-errors")) {
diag.fatal_errors = to != .off;
return;
}
inline for (std.meta.fields(Options)) |f| {
if (mem.eql(u8, f.name, name)) {
@field(diag.options, f.name) = to;
return;
}
}
try diag.add(.{
.tag = .unknown_warning,
.extra = .{ .str = name },
});
}
pub fn setAll(diag: *Diagnostics, to: Kind) void {
inline for (std.meta.fields(Options)) |f| {
@field(diag.options, f.name) = to;
}
}
pub fn init(gpa: *Allocator) Diagnostics {
return .{
.color = std.io.getStdErr().supportsAnsiEscapeCodes(),
.list = std.ArrayList(Message).init(gpa),
};
}
pub fn deinit(diag: *Diagnostics) void {
diag.list.deinit();
}
pub fn add(diag: *Diagnostics, msg: Message) Compilation.Error!void {
const kind = diag.tagKind(msg.tag);
if (kind == .off) return;
try diag.list.append(msg);
if (kind == .@"fatal error" or (kind == .@"error" and diag.fatal_errors))
return error.FatalError;
}
pub fn fatal(diag: *Diagnostics, path: []const u8, lcs: Source.LCS, comptime fmt: []const u8, args: anytype) Compilation.Error {
var m = MsgWriter.init(diag.color);
defer m.deinit();
m.location(path, lcs);
m.start(.@"fatal error");
m.print(fmt, args);
m.end(lcs);
return error.FatalError;
}
pub fn fatalNoSrc(diag: *Diagnostics, comptime fmt: []const u8, args: anytype) Compilation.Error {
if (std.builtin.os.tag == .windows or !diag.color) {
std.debug.print("fatal error: " ++ fmt ++ "\n", args);
} else {
const RED = "\x1b[31;1m";
const RESET = "\x1b[0m";
const BOLD = RESET ++ "\x1b[1m";
std.debug.print(RED ++ "fatal error: " ++ BOLD ++ fmt ++ "\n" ++ RESET, args);
}
return error.FatalError;
}
pub fn render(comp: *Compilation) void {
if (comp.diag.list.items.len == 0) return;
var m = MsgWriter.init(comp.diag.color);
defer m.deinit();
renderExtra(comp, &m);
}
pub fn renderExtra(comp: *Compilation, m: anytype) void {
var errors: u32 = 0;
var warnings: u32 = 0;
for (comp.diag.list.items) |msg| {
const kind = comp.diag.tagKind(msg.tag);
switch (kind) {
.@"fatal error", .@"error" => errors += 1,
.warning => warnings += 1,
.note => {},
.off => unreachable,
}
var lcs: ?Source.LCS = null;
if (msg.loc.id != .unused) {
const loc = if (msg.loc.next != null) msg.loc.next.?.* else msg.loc;
const source = comp.getSource(loc.id);
lcs = source.lineColString(loc.byte_offset);
switch (msg.tag) {
.escape_sequence_overflow,
.invalid_universal_character,
=> { // use msg.extra.unsigned for index into string literal
lcs.?.col += @truncate(u32, msg.extra.unsigned);
},
else => {},
}
m.location(source.path, lcs.?);
}
m.start(kind);
switch (msg.tag) {
.todo => m.print("TODO: {s}", .{msg.extra.str}),
.error_directive => m.print("{s}", .{msg.extra.str}),
.elif_without_if => m.write("#elif without #if"),
.elif_after_else => m.write("#elif after #else"),
.else_without_if => m.write("#else without #if"),
.else_after_else => m.write("#else after #else"),
.endif_without_if => m.write("#endif without #if"),
.unsupported_pragma => m.print("unsupported #pragma directive '{s}'", .{msg.extra.str}),
.line_simple_digit => m.write("#line directive requires a simple digit sequence"),
.line_invalid_filename => m.write("invalid filename for #line directive"),
.unterminated_conditional_directive => m.write("unterminated conditional directive"),
.invalid_preprocessing_directive => m.write("invalid preprocessing directive"),
.macro_name_missing => m.write("macro name missing"),
.extra_tokens_directive_end => m.write("extra tokens at end of macro directive"),
.expected_value_in_expr => m.write("expected value in expression"),
.closing_paren => m.write("expected closing ')'"),
.to_match_paren => m.write("to match this '('"),
.to_match_brace => m.write("to match this '{'"),
.to_match_bracket => m.write("to match this '['"),
.header_str_closing => m.write("expected closing '>'"),
.header_str_match => m.write("to match this '<'"),
.string_literal_in_pp_expr => m.write("string literal in preprocessor expression"),
.float_literal_in_pp_expr => m.write("floating point literal in preprocessor expression"),
.defined_as_macro_name => m.write("'defined' cannot be used as a macro name"),
.macro_name_must_be_identifier => m.write("macro name must be an identifier"),
.whitespace_after_macro_name => m.write("ISO C99 requires whitespace after the macro name"),
.hash_hash_at_start => m.write("'##' cannot appear at the start of a macro expansion"),
.hash_hash_at_end => m.write("'##' cannot appear at the end of a macro expansion"),
.pasting_formed_invalid => m.print("pasting formed '{s}', an invalid preprocessing token", .{msg.extra.str}),
.missing_paren_param_list => m.write("missing ')' in macro parameter list"),
.unterminated_macro_param_list => m.write("unterminated macro param list"),
.invalid_token_param_list => m.write("invalid token in macro parameter list"),
.hash_not_followed_param => m.write("'#' is not followed by a macro parameter"),
.expected_filename => m.write("expected \"FILENAME\" or <FILENAME>"),
.empty_filename => m.write("empty filename"),
.expected_invalid => m.print("expected '{s}', found invalid bytes", .{msg.extra.tok_id.expected.symbol()}),
.expected_token => m.print("expected '{s}', found '{s}'", .{
msg.extra.tok_id.expected.symbol(),
msg.extra.tok_id.actual.symbol(),
}),
.expected_expr => m.write("expected expression"),
.expected_integer_constant_expr => m.write("expression is not an integer constant expression"),
.missing_type_specifier => m.write("type specifier missing, defaults to 'int'"),
.multiple_storage_class => m.print("cannot combine with previous '{s}' declaration specifier", .{msg.extra.str}),
.static_assert_failure => m.write("static assertion failed"),
.static_assert_failure_message => m.print("static assertion failed {s}", .{msg.extra.str}),
.expected_type => m.write("expected a type"),
.cannot_combine_spec => m.print("cannot combine with previous '{s}' specifier", .{msg.extra.str}),
.duplicate_decl_spec => m.print("duplicate '{s}' declaration specifier", .{msg.extra.str}),
.restrict_non_pointer => m.print("restrict requires a pointer or reference ('{s}' is invalid)", .{msg.extra.str}),
.expected_external_decl => m.write("expected external declaration"),
.expected_ident_or_l_paren => m.write("expected identifier or '('"),
.missing_declaration => m.write("declaration does not declare anything"),
.func_not_in_root => m.write("function definition is not allowed here"),
.illegal_initializer => m.write("illegal initializer (only variables can be initialized)"),
.extern_initializer => m.write("extern variable has initializer"),
.spec_from_typedef => m.print("'{s}' came from typedef", .{msg.extra.str}),
.type_is_invalid => m.print("'{s}' is invalid", .{msg.extra.str}),
.param_before_var_args => m.write("ISO C requires a named parameter before '...'"),
.void_only_param => m.write("'void' must be the only parameter if specified"),
.void_param_qualified => m.write("'void' parameter cannot be qualified"),
.void_must_be_first_param => m.write("'void' must be the first parameter if specified"),
.invalid_storage_on_param => m.write("invalid storage class on function parameter"),
.threadlocal_non_var => m.write("_Thread_local only allowed on variables"),
.func_spec_non_func => m.print("'{s}' can only appear on functions", .{msg.extra.str}),
.illegal_storage_on_func => m.write("illegal storage class on function"),
.illegal_storage_on_global => m.write("illegal storage class on global variable"),
.expected_stmt => m.write("expected statement"),
.func_cannot_return_func => m.write("function cannot return a function"),
.func_cannot_return_array => m.write("function cannot return an array"),
.undeclared_identifier => m.print("use of undeclared identifier '{s}'", .{msg.extra.str}),
.not_callable => m.print("cannot call non function type '{s}'", .{msg.extra.str}),
.unsupported_str_cat => m.write("unsupported string literal concatenation"),
.static_func_not_global => m.write("static functions must be global"),
.implicit_func_decl => m.print("implicit declaration of function '{s}' is invalid in C99", .{msg.extra.str}),
.expected_param_decl => m.write("expected parameter declaration"),
.invalid_old_style_params => m.write("identifier parameter lists are only allowed in function definitions"),
.expected_fn_body => m.write("expected function body after function declaration"),
.invalid_void_param => m.write("parameter cannot have void type"),
.unused_value => m.write("expression result unused"),
.continue_not_in_loop => m.write("'continue' statement not in a loop"),
.break_not_in_loop_or_switch => m.write("'break' statement not in a loop or a switch"),
.unreachable_code => m.write("unreachable code"),
.duplicate_label => m.print("duplicate label '{s}'", .{msg.extra.str}),
.previous_label => m.print("previous definition of label '{s}' was here", .{msg.extra.str}),
.undeclared_label => m.print("use of undeclared label '{s}'", .{msg.extra.str}),
.case_not_in_switch => m.print("'{s}' statement not in a switch statement", .{msg.extra.str}),
.duplicate_switch_case_signed => m.print("duplicate case value '{d}'", .{msg.extra.signed}),
.duplicate_switch_case_unsigned => m.print("duplicate case value '{d}'", .{msg.extra.unsigned}),
.multiple_default => m.write("multiple default cases in the same switch"),
.previous_case => m.write("previous case defined here"),
.expected_arguments, .expected_arguments_old => m.print("expected {d} argument(s) got {d}", .{ msg.extra.arguments.expected, msg.extra.arguments.actual }),
.expected_at_least_arguments => m.print("expected at least {d} argument(s) got {d}", .{ msg.extra.arguments.expected, msg.extra.arguments.actual }),
.invalid_static_star => m.write("'static' may not be used with an unspecified variable length array size"),
.static_non_param => m.write("'static' used outside of function parameters"),
.array_qualifiers => m.write("type qualifier in non parameter array type"),
.star_non_param => m.write("star modifier used outside of function parameters"),
.variable_len_array_file_scope => m.write("variable length arrays not allowed at file scope"),
.useless_static => m.write("'static' useless without a constant size"),
.negative_array_size => m.write("array size must be 0 or greater"),
.array_incomplete_elem => m.print("array has incomplete element type '{s}'", .{msg.extra.str}),
.array_func_elem => m.write("arrays cannot have functions as their element type"),
.static_non_outermost_array => m.write("'static' used in non-outermost array type"),
.qualifier_non_outermost_array => m.write("type qualifier used in non-outermost array type"),
.unterminated_macro_arg_list => m.write("unterminated function macro argument list"),
.unknown_warning => m.print("unknown warning '{s}'", .{msg.extra.str}),
.overflow_signed => m.print("overflow in expression; result is'{d}'", .{msg.extra.signed}),
.overflow_unsigned => m.print("overflow in expression; result is '{d}'", .{msg.extra.unsigned}),
.int_literal_too_big => m.write("integer literal is too large to be represented in any integer type"),
.indirection_ptr => m.write("indirection requires pointer operand"),
.addr_of_rvalue => m.write("cannot take the address of an rvalue"),
.not_assignable => m.write("expression is not assignable"),
.ident_or_l_brace => m.write("expected identifier or '{'"),
.empty_enum => m.write("empty enum is invalid"),
.redefinition => m.print("redefinition of '{s}'", .{msg.extra.str}),
.previous_definition => m.write("previous definition is here"),
.expected_identifier => m.write("expected identifier"),
.expected_str_literal => m.write("expected string literal for diagnostic message in static_assert"),
.parameter_missing => m.print("parameter named '{s}' is missing", .{msg.extra.str}),
.empty_record => m.print("empty {s} is a GNU extension", .{msg.extra.str}),
.wrong_tag => m.print("use of '{s}' with tag type that does not match previous definition", .{msg.extra.str}),
.expected_parens_around_typename => m.write("expected parentheses around type name"),
.alignof_expr => m.write("'_Alignof' applied to an expression is a GNU extension"),
.invalid_sizeof => m.print("invalid application of 'sizeof' to an incomplete type '{s}'", .{msg.extra.str}),
.macro_redefined => m.print("'{s}' macro redefined", .{msg.extra.str}),
.generic_qual_type => m.write("generic association with qualifiers cannot be matched with"),
.generic_duplicate => m.print("type '{s}' in generic association compatible with previously specified type", .{msg.extra.str}),
.generic_duplicate_default => m.write("duplicate default generic association"),
.generic_no_match => m.print("controlling expression type '{s}' not compatible with any generic association type", .{msg.extra.str}),
.escape_sequence_overflow => m.write("escape sequence out of range"),
.invalid_universal_character => m.write("invalid universal character"),
.multichar_literal => m.write("multi-character character constant"),
.char_lit_too_wide => m.write("character constant too long for its type"),
.must_use_struct => m.print("must use 'struct' tag to refer to type '{s}'", .{msg.extra.str}),
.must_use_union => m.print("must use 'union' tag to refer to type '{s}'", .{msg.extra.str}),
.must_use_enum => m.print("must use 'enum' tag to refer to type '{s}'", .{msg.extra.str}),
.redefinition_different_sym => m.print("redefinition of '{s}' as different kind of symbol", .{msg.extra.str}),
.redefinition_incompatible => m.print("redefinition of '{s}' with a different type", .{msg.extra.str}),
.redefinition_of_parameter => m.print("redefinition of parameter '{s}'", .{msg.extra.str}),
.invalid_bin_types => m.print("invalid operands to binary expression ({s})", .{msg.extra.str}),
.comparison_ptr_int => m.print("comparison between pointer and integer ({s})", .{msg.extra.str}),
.comparison_distinct_ptr => m.print("comparison of distinct pointer types ({s})", .{msg.extra.str}),
.incompatible_pointers => m.print("incompatible pointer types ({s})", .{msg.extra.str}),
.invalid_argument_un => m.print("invalid argument type '{s}' to unary expression", .{msg.extra.str}),
.incompatible_assign => m.print("assignment to {s}", .{msg.extra.str}),
.implicit_ptr_to_int => m.print("implicit pointer to integer conversion from {s}", .{msg.extra.str}),
.invalid_cast_to_float => m.print("pointer cannot be cast to type '{s}'", .{msg.extra.str}),
.invalid_cast_to_pointer => m.print("operand of type '{s}' cannot be cast to a pointer type", .{msg.extra.str}),
.invalid_cast_type => m.print("cannot cast to non arithmetic or pointer type '{s}'", .{msg.extra.str}),
.qual_cast => m.print("cast to type '{s}' will not preserve qualifiers", .{msg.extra.str}),
.invalid_index => m.write("array subscript is not an integer"),
.invalid_subscript => m.write("subscripted value is not an array or pointer"),
.array_after => m.print("array index {d} is past the end of the array", .{msg.extra.unsigned}),
.array_before => m.print("array index {d} is before the beginning of the array", .{msg.extra.signed}),
.statement_int => m.print("statement requires expression with integer type ('{s}' invalid)", .{msg.extra.str}),
.statement_scalar => m.print("statement requires expression with scalar type ('{s}' invalid)", .{msg.extra.str}),
.func_should_return => m.print("non-void function '{s}' should return a value", .{msg.extra.str}),
.incompatible_return => m.print("returning '{s}' from a function with incompatible result type", .{msg.extra.str}),
.implicit_int_to_ptr => m.print("implicit integer to pointer conversion from {s}", .{msg.extra.str}),
.func_does_not_return => m.print("non-void function '{s}' does not return a value", .{msg.extra.str}),
.incompatible_param => m.print("passing '{s}' to parameter of incompatible type", .{msg.extra.str}),
.parameter_here => m.write("passing argument to parameter here"),
.atomic_array => m.print("atomic cannot be applied to array type '{s}'", .{msg.extra.str}),
.atomic_func => m.print("atomic cannot be applied to function type '{s}'", .{msg.extra.str}),
.atomic_incomplete => m.print("atomic cannot be applied to incomplete type '{s}'", .{msg.extra.str}),
.addr_of_register => m.write("address of register variable requested"),
.variable_incomplete_ty => m.print("variable has incomplete type '{s}'", .{msg.extra.str}),
.alignas_on_func => m.write("'_Alignas' attribute only applies to variables and fields"),
.alignas_on_param => m.write("'_Alignas' attribute cannot be applied to a function parameter"),
.minimum_alignment => m.print("requested alignment is less than minimum alignment of {d}", .{msg.extra.unsigned}),
.maximum_alignment => m.print("requested alignment of {d} is too large", .{msg.extra.unsigned}),
.negative_alignment => m.print("requested negative alignment of {d} is invalid", .{msg.extra.signed}),
.align_ignored => m.write("'_Alignas' attribute is ignored here"),
.zero_align_ignored => m.write("requested alignment of zero is ignored"),
.non_pow2_align => m.write("requested alignment is not a power of 2"),
.pointer_mismatch => m.print("pointer type mismatch ({s})", .{msg.extra.str}),
.static_assert_not_constant => m.write("static_assert expression is not an integral constant expression"),
.static_assert_missing_message => m.write("static_assert with no message is a C2X extension"),
.unbound_vla => m.write("variable length array must be bound in function definition"),
.array_too_large => m.write("array is too large"),
.incompatible_ptr_init => m.print("incompatible pointer types initializing {s}", .{msg.extra.str}),
.incompatible_ptr_assign => m.print("incompatible pointer types assigning to {s}", .{msg.extra.str}),
.vla_init => m.write("variable-sized object may not be initialized"),
.func_init => m.write("illegal initializer type"),
.incompatible_init => m.print("initializing {s}", .{msg.extra.str}),
.empty_scalar_init => m.write("scalar initializer cannot be empty"),
.excess_scalar_init => m.write("excess elements in scalar initializer"),
.excess_str_init => m.write("excess elements in string initializer"),
.excess_struct_init => m.write("excess elements in struct initializer"),
.excess_array_init => m.write("excess elements in array initializer"),
.str_init_too_long => m.write("initializer-string for char array is too long"),
.arr_init_too_long => m.print("cannot initialize type ({s})", .{msg.extra.str}),
.invalid_typeof => m.print("'{s} typeof' is invalid", .{msg.extra.str}),
.division_by_zero => m.print("{s} by zero is undefined", .{msg.extra.str}),
.builtin_choose_cond => m.write("'__builtin_choose_expr' requires a constant expression"),
.alignas_unavailable => m.write("'_Alignas' attribute requires integer constant expression"),
.case_val_unavailable => m.write("case value must be an integer constant expression"),
.enum_val_unavailable => m.write("enum value must be an integer constant expression"),
.incompatible_array_init => m.print("cannot initialize array of type {s}", .{msg.extra.str}),
.initializer_overrides => m.write("initializer overrides previous initialization"),
.previous_initializer => m.write("previous initialization"),
.invalid_array_designator => m.print("array designator used for non-array type '{s}'", .{msg.extra.str}),
.negative_array_designator => m.print("array designator value {d} is negative", .{msg.extra.signed}),
.oob_array_designator => m.print("array designator index {d} exceeds array bounds", .{msg.extra.unsigned}),
.invalid_field_designator => m.print("field designator used for non-record type '{s}'", .{msg.extra.str}),
.no_such_field_designator => m.print("record type has no field named '{s}'", .{msg.extra.str}),
.empty_aggregate_init_braces => m.write("initializer for aggregate with no elements requires explicit braces"),
.ptr_init_discards_quals => m.print("initializing {s} discards qualifiers", .{msg.extra.str}),
.ptr_assign_discards_quals => m.print("assigning to {s} discards qualifiers", .{msg.extra.str}),
}
m.end(lcs);
if (msg.loc.id != .unused) {
var maybe_loc = msg.loc.next;
if (msg.loc.next != null) maybe_loc = maybe_loc.?.next;
while (maybe_loc) |loc| {
const source = comp.getSource(loc.id);
const e_lcs = source.lineColString(loc.byte_offset);
m.location(source.path, e_lcs);
m.start(.note);
m.write("expanded from here");
m.end(e_lcs);
maybe_loc = loc.next;
}
}
}
const w_s: []const u8 = if (warnings == 1) "" else "s";
const e_s: []const u8 = if (errors == 1) "" else "s";
if (errors != 0 and warnings != 0) {
m.print("{d} warning{s} and {d} error{s} generated.\n", .{ warnings, w_s, errors, e_s });
} else if (warnings != 0) {
m.print("{d} warning{s} generated.\n", .{ warnings, w_s });
} else if (errors != 0) {
m.print("{d} error{s} generated.\n", .{ errors, e_s });
}
comp.diag.list.items.len = 0;
comp.diag.errors += errors;
}
pub const Kind = enum { @"fatal error", @"error", note, warning, off };
fn tagKind(diag: *Diagnostics, tag: Tag) Kind {
var kind: Kind = switch (tag) {
.todo,
.error_directive,
.elif_without_if,
.elif_after_else,
.else_without_if,
.else_after_else,
.endif_without_if,
.line_simple_digit,
.line_invalid_filename,
.unterminated_conditional_directive,
.invalid_preprocessing_directive,
.macro_name_missing,
.extra_tokens_directive_end,
.expected_value_in_expr,
.closing_paren,
.header_str_closing,
.string_literal_in_pp_expr,
.float_literal_in_pp_expr,
.defined_as_macro_name,
.macro_name_must_be_identifier,
.hash_hash_at_start,
.hash_hash_at_end,
.pasting_formed_invalid,
.missing_paren_param_list,
.unterminated_macro_param_list,
.invalid_token_param_list,
.hash_not_followed_param,
.expected_filename,
.empty_filename,
.expected_invalid,
.expected_token,
.expected_expr,
.expected_integer_constant_expr,
.multiple_storage_class,
.static_assert_failure,
.static_assert_failure_message,
.expected_type,
.cannot_combine_spec,
.restrict_non_pointer,
.expected_external_decl,
.expected_ident_or_l_paren,
.func_not_in_root,
.illegal_initializer,
.type_is_invalid,
.param_before_var_args,
.void_only_param,
.void_param_qualified,
.void_must_be_first_param,
.invalid_storage_on_param,
.threadlocal_non_var,
.func_spec_non_func,
.illegal_storage_on_func,
.illegal_storage_on_global,
.expected_stmt,
.func_cannot_return_func,
.func_cannot_return_array,
.undeclared_identifier,
.not_callable,
.unsupported_str_cat,
.static_func_not_global,
.expected_param_decl,
.expected_fn_body,
.invalid_void_param,
.continue_not_in_loop,
.break_not_in_loop_or_switch,
.duplicate_label,
.undeclared_label,
.case_not_in_switch,
.duplicate_switch_case_signed,
.duplicate_switch_case_unsigned,
.multiple_default,
.expected_arguments,
.expected_at_least_arguments,
.invalid_static_star,
.static_non_param,
.array_qualifiers,
.star_non_param,
.variable_len_array_file_scope,
.negative_array_size,
.array_incomplete_elem,
.array_func_elem,
.static_non_outermost_array,
.qualifier_non_outermost_array,
.unterminated_macro_arg_list,
.int_literal_too_big,
.indirection_ptr,
.addr_of_rvalue,
.not_assignable,
.ident_or_l_brace,
.empty_enum,
.redefinition,
.expected_identifier,
.wrong_tag,
.expected_str_literal,
.parameter_missing,
.expected_parens_around_typename,
.invalid_sizeof,
.generic_duplicate,
.generic_duplicate_default,
.generic_no_match,
.escape_sequence_overflow,
.invalid_universal_character,
.must_use_struct,
.must_use_union,
.must_use_enum,
.redefinition_different_sym,
.redefinition_incompatible,
.redefinition_of_parameter,
.invalid_bin_types,
.incompatible_pointers,
.invalid_argument_un,
.incompatible_assign,
.invalid_cast_to_float,
.invalid_cast_to_pointer,
.invalid_cast_type,
.invalid_index,
.invalid_subscript,
.statement_int,
.statement_scalar,
.func_should_return,
.incompatible_return,
.incompatible_param,
.atomic_array,
.atomic_func,
.atomic_incomplete,
.addr_of_register,
.variable_incomplete_ty,
.alignas_on_func,
.alignas_on_param,
.minimum_alignment,
.maximum_alignment,
.negative_alignment,
.non_pow2_align,
.static_assert_not_constant,
.unbound_vla,
.array_too_large,
.vla_init,
.func_init,
.incompatible_init,
.empty_scalar_init,
.arr_init_too_long,
.invalid_typeof,
.builtin_choose_cond,
.alignas_unavailable,
.case_val_unavailable,
.enum_val_unavailable,
.incompatible_array_init,
.invalid_array_designator,
.negative_array_designator,
.oob_array_designator,
.invalid_field_designator,
.no_such_field_designator,
.empty_aggregate_init_braces,
=> .@"error",
.to_match_paren,
.to_match_brace,
.to_match_bracket,
.header_str_match,
.spec_from_typedef,
.previous_label,
.previous_case,
.previous_definition,
.parameter_here,
.previous_initializer,
=> .note,
.invalid_old_style_params,
.expected_arguments_old,
.useless_static,
.overflow_unsigned,
.overflow_signed,
.char_lit_too_wide,
.func_does_not_return,
.align_ignored,
.zero_align_ignored,
=> .warning,
.unsupported_pragma => diag.options.@"unsupported-pragma",
.whitespace_after_macro_name => diag.options.@"c99-extensions",
.missing_type_specifier => diag.options.@"implicit-int",
.duplicate_decl_spec => diag.options.@"duplicate-decl-specifier",
.missing_declaration => diag.options.@"missing-declaration",
.extern_initializer => diag.options.@"extern-initializer",
.implicit_func_decl => diag.options.@"implicit-function-declaration",
.unused_value => diag.options.@"unused-value",
.unreachable_code => diag.options.@"unreachable-code",
.unknown_warning => diag.options.@"unknown-warning-option",
.empty_record => diag.options.@"empty-struct",
.alignof_expr => diag.options.@"gnu-alignof-expression",
.macro_redefined => diag.options.@"macro-redefined",
.generic_qual_type => diag.options.@"generic-qual-type",
.multichar_literal => diag.options.multichar,
.comparison_ptr_int => diag.options.@"pointer-integer-compare",
.comparison_distinct_ptr => diag.options.@"compare-distinct-pointer-types",
.implicit_ptr_to_int => diag.options.@"literal-conversion",
.qual_cast => diag.options.@"cast-qualifiers",
.array_after => diag.options.@"array-bounds",
.array_before => diag.options.@"array-bounds",
.implicit_int_to_ptr => diag.options.@"int-conversion",
.pointer_mismatch => diag.options.@"pointer-type-mismatch",
.static_assert_missing_message => diag.options.@"c2x-extension",
.incompatible_ptr_init,
.incompatible_ptr_assign,
=> diag.options.@"incompatible-pointer-types",
.ptr_init_discards_quals,
.ptr_assign_discards_quals,
=> diag.options.@"incompatible-pointer-types-discards-qualifiers",
.excess_scalar_init,
.excess_str_init,
.excess_struct_init,
.excess_array_init,
.str_init_too_long,
=> diag.options.@"excess-initializers",
.division_by_zero => diag.options.@"division-by-zero",
.initializer_overrides => diag.options.@"initializer-overrides",
};
if (kind == .@"error" and diag.fatal_errors) kind = .@"fatal error";
return kind;
}
const MsgWriter = struct {
// TODO Impl is private
held: @typeInfo(@TypeOf(std.Thread.Mutex.acquire)).Fn.return_type.?,
w: std.fs.File.Writer,
color: bool,
fn init(color: bool) MsgWriter {
return .{
.held = std.debug.getStderrMutex().acquire(),
.w = std.io.getStdErr().writer(),
.color = color,
};
}
fn deinit(m: *MsgWriter) void {
m.held.release();
}
fn print(m: *MsgWriter, comptime fmt: []const u8, args: anytype) void {
m.w.print(fmt, args) catch {};
}
fn write(m: *MsgWriter, msg: []const u8) void {
m.w.writeAll(msg) catch {};
}
fn location(m: *MsgWriter, path: []const u8, lcs: Source.LCS) void {
if (std.builtin.os.tag == .windows or !m.color) {
m.print("{s}:{d}:{d}: ", .{ path, lcs.line, lcs.col });
} else {
const BOLD = "\x1b[0m\x1b[1m";
m.print(BOLD ++ "{s}:{d}:{d}: ", .{ path, lcs.line, lcs.col });
}
}
fn start(m: *MsgWriter, kind: Kind) void {
if (std.builtin.os.tag == .windows or !m.color) {
m.print("{s}: ", .{@tagName(kind)});
} else {
const PURPLE = "\x1b[35;1m";
const CYAN = "\x1b[36;1m";
const RED = "\x1b[31;1m";
const BOLD = "\x1b[0m\x1b[1m";
const msg_kind_str = switch (kind) {
.@"fatal error" => RED ++ "fatal error: " ++ BOLD,
.@"error" => RED ++ "error: " ++ BOLD,
.note => CYAN ++ "note: " ++ BOLD,
.warning => PURPLE ++ "warning: " ++ BOLD,
.off => unreachable,
};
m.write(msg_kind_str);
}
}
fn end(m: *MsgWriter, lcs: ?Source.LCS) void {
if (std.builtin.os.tag == .windows or !m.color) {
if (lcs == null) {
m.write("\n");
return;
}
m.print("\n{s}\n", .{lcs.?.str});
m.print("{s: >[1]}^\n", .{ "", lcs.?.col - 1 });
} else {
const GREEN = "\x1b[32;1m";
const RESET = "\x1b[0m";
if (lcs == null) {
m.write("\n" ++ RESET);
return;
}
m.print("\n" ++ RESET ++ "{s}\n", .{lcs.?.str});
m.print("{s: >[1]}" ++ GREEN ++ "^" ++ RESET ++ "\n", .{ "", lcs.?.col - 1 });
}
}
}; | src/Diagnostics.zig |
usingnamespace @import("core.zig");
const glfw = @import("glfw");
const vk = @import("vulkan");
usingnamespace @import("vulkan/device.zig");
usingnamespace @import("vulkan/buffer.zig");
usingnamespace @import("vulkan/image.zig");
const TransferQueue = @import("transfer_queue.zig").TransferQueue;
const Input = @import("input.zig").Input;
const resources = @import("resources");
pub const c = @cImport({
@cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", "");
@cInclude("cimgui.h");
});
const ALL_SHADER_STAGES = vk.ShaderStageFlags{
.vertex_bit = true,
.tessellation_control_bit = true,
.tessellation_evaluation_bit = true,
.geometry_bit = true,
.fragment_bit = true,
.compute_bit = true,
.task_bit_nv = true,
.mesh_bit_nv = true,
.raygen_bit_khr = true,
.any_hit_bit_khr = true,
.closest_hit_bit_khr = true,
.miss_bit_khr = true,
.intersection_bit_khr = true,
.callable_bit_khr = true,
};
const SHADER_STAGES = vk.ShaderStageFlags{
.vertex_bit = true,
.fragment_bit = true,
};
pub const Layer = struct {
const Self = @This();
allocator: *Allocator,
context: *c.ImGuiContext,
io: *c.ImGuiIO,
device: Device,
pipeline_layout: vk.PipelineLayout,
pipeline: vk.Pipeline,
freed_buffers: std.ArrayList(Buffer),
texture_atlas: Image,
texture_sampler: vk.Sampler,
pub fn init(allocator: *Allocator, device: Device, transfer_queue: *TransferQueue, render_pass: vk.RenderPass, descriptor_set_layouts: []vk.DescriptorSetLayout) !Self {
var context = c.igCreateContext(null);
var io: *c.ImGuiIO = c.igGetIO();
io.ConfigFlags |= c.ImGuiConfigFlags_DockingEnable;
io.DeltaTime = 1.0 / 60.0;
c.igStyleColorsDark(null);
var pixels: ?[*]u8 = undefined;
var width: i32 = undefined;
var height: i32 = undefined;
var bytes: i32 = 0;
c.ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, @ptrCast([*c][*c]u8, &pixels), &width, &height, &bytes);
//TODO: init texture
var texture_atlas = try Image.init(
device,
.r8g8b8a8_unorm,
.{
.width = @intCast(u32, width),
.height = @intCast(u32, height),
},
.{ .device_local_bit = true },
);
try texture_atlas.createImageView();
if (pixels) |pixel_data| {
var pixel_slice: []u8 = undefined;
pixel_slice.ptr = pixel_data;
pixel_slice.len = @intCast(usize, width * height * bytes);
transfer_queue.copyToImage(texture_atlas, u8, pixel_slice);
}
var texture_sampler = try device.dispatch.createSampler(
device.handle,
.{
.flags = .{},
.mag_filter = .linear,
.min_filter = .linear,
.mipmap_mode = .linear,
.address_mode_u = .clamp_to_border,
.address_mode_v = .clamp_to_border,
.address_mode_w = .clamp_to_border,
.mip_lod_bias = 0.0,
.anisotropy_enable = vk.FALSE,
.max_anisotropy = 0.0,
.compare_enable = vk.FALSE,
.compare_op = .always,
.min_lod = 0.0,
.max_lod = 0.0,
.border_color = .float_transparent_black,
.unnormalized_coordinates = vk.FALSE,
},
null,
);
var push_constant_range = vk.PushConstantRange{
.stage_flags = SHADER_STAGES,
.offset = 0,
.size = 128,
};
var pipeline_layout = try device.dispatch.createPipelineLayout(device.handle, .{
.flags = .{},
.set_layout_count = @intCast(u32, descriptor_set_layouts.len),
.p_set_layouts = @ptrCast([*]const vk.DescriptorSetLayout, descriptor_set_layouts.ptr),
.push_constant_range_count = 1,
.p_push_constant_ranges = @ptrCast([*]const vk.PushConstantRange, &push_constant_range),
}, null);
var pipeline = try device.createPipeline(
pipeline_layout,
render_pass,
&resources.imgui_vert,
&resources.imgui_frag,
&ImguiVertex.binding_description,
&ImguiVertex.attribute_description,
&.{
.cull_mode = .{},
.blend_enable = true,
.src_color_blend_factor = .src_alpha,
.dst_color_blend_factor = .one_minus_src_alpha,
.color_blend_op = .add,
.src_alpha_blend_factor = .src_alpha,
.dst_alpha_blend_factor = .one_minus_src_alpha,
.alpha_blend_op = .add,
},
);
var freed_buffers = std.ArrayList(Buffer).init(allocator);
//KeyMap
io.KeyMap[c.ImGuiKey_Tab] = @enumToInt(glfw.Key.tab);
io.KeyMap[c.ImGuiKey_LeftArrow] = @enumToInt(glfw.Key.left);
io.KeyMap[c.ImGuiKey_RightArrow] = @enumToInt(glfw.Key.right);
io.KeyMap[c.ImGuiKey_UpArrow] = @enumToInt(glfw.Key.up);
io.KeyMap[c.ImGuiKey_DownArrow] = @enumToInt(glfw.Key.down);
io.KeyMap[c.ImGuiKey_PageUp] = @enumToInt(glfw.Key.page_up);
io.KeyMap[c.ImGuiKey_PageDown] = @enumToInt(glfw.Key.page_down);
io.KeyMap[c.ImGuiKey_End] = @enumToInt(glfw.Key.end);
io.KeyMap[c.ImGuiKey_Insert] = @enumToInt(glfw.Key.insert);
io.KeyMap[c.ImGuiKey_Delete] = @enumToInt(glfw.Key.delete);
io.KeyMap[c.ImGuiKey_Backspace] = @enumToInt(glfw.Key.backspace);
io.KeyMap[c.ImGuiKey_Space] = @enumToInt(glfw.Key.space);
io.KeyMap[c.ImGuiKey_Enter] = @enumToInt(glfw.Key.enter);
io.KeyMap[c.ImGuiKey_Escape] = @enumToInt(glfw.Key.escape);
io.KeyMap[c.ImGuiKey_KeyPadEnter] = @enumToInt(glfw.Key.kp_enter);
io.KeyMap[c.ImGuiKey_A] = @enumToInt(glfw.Key.a);
io.KeyMap[c.ImGuiKey_C] = @enumToInt(glfw.Key.c);
io.KeyMap[c.ImGuiKey_V] = @enumToInt(glfw.Key.v);
io.KeyMap[c.ImGuiKey_X] = @enumToInt(glfw.Key.x);
io.KeyMap[c.ImGuiKey_Y] = @enumToInt(glfw.Key.y);
io.KeyMap[c.ImGuiKey_Z] = @enumToInt(glfw.Key.z);
return Self{
.allocator = allocator,
.context = context,
.io = io,
.device = device,
.pipeline = pipeline,
.pipeline_layout = pipeline_layout,
.freed_buffers = freed_buffers,
.texture_atlas = texture_atlas,
.texture_sampler = texture_sampler,
};
}
pub fn deinit(self: Self) void {
self.texture_atlas.deinit();
self.device.dispatch.destroySampler(self.device.handle, self.texture_sampler, null);
for (self.freed_buffers.items) |buffer| {
buffer.deinit();
}
self.freed_buffers.deinit();
self.device.dispatch.destroyPipeline(self.device.handle, self.pipeline, null);
self.device.dispatch.destroyPipelineLayout(self.device.handle, self.pipeline_layout, null);
c.igDestroyContext(self.context);
}
pub fn update(self: Self, window: glfw.Window, input: *Input, delta_time: f32) void {
self.io.DeltaTime = delta_time;
//Window size update
var size = window.getSize() catch |err| {
std.log.err("Failed to get window size, can't use imgui", .{});
return;
};
self.io.DisplaySize = c.ImVec2{
.x = @intToFloat(f32, size.width),
.y = @intToFloat(f32, size.height),
};
if (input.getMousePos()) |mouse_pos| {
self.io.MousePos = c.ImVec2{
.x = mouse_pos[0],
.y = mouse_pos[1],
};
}
const mouse_buttons = [_]glfw.mouse_button.MouseButton{ glfw.mouse_button.MouseButton.left, glfw.mouse_button.MouseButton.right, glfw.mouse_button.MouseButton.middle, glfw.mouse_button.MouseButton.four, glfw.mouse_button.MouseButton.five };
for (mouse_buttons) |button, index| {
self.io.MouseDown[index] = input.getMouseDown(button);
}
const keyboard_buttons = [_]glfw.Key{ glfw.Key.tab, glfw.Key.left, glfw.Key.right, glfw.Key.up, glfw.Key.down, glfw.Key.page_up, glfw.Key.page_down, glfw.Key.end, glfw.Key.insert, glfw.Key.delete, glfw.Key.backspace, glfw.Key.space, glfw.Key.enter, glfw.Key.escape, glfw.Key.kp_enter, glfw.Key.a, glfw.Key.c, glfw.Key.v, glfw.Key.x, glfw.Key.y, glfw.Key.z };
for (keyboard_buttons) |button| {
var index = @intCast(usize, @enumToInt(button));
self.io.KeysDown[index] = input.getKeyDown(button);
}
var text_input = input.getAndClearTextInput();
defer text_input.deinit();
for (text_input.items) |character| {
c.ImGuiIO_AddInputCharacterUTF16(self.io, character);
}
}
pub fn beginFrame(self: *Self) void {
for (self.freed_buffers.items) |buffer| {
buffer.deinit();
}
self.freed_buffers.clearRetainingCapacity();
c.igNewFrame();
}
pub fn endFrame(self: *Self, command_buffer: vk.CommandBuffer, descriptor_sets: []vk.DescriptorSet) !void {
var open = true;
c.igShowDemoWindow(&open);
c.igEndFrame();
c.igRender();
var draw_data: *c.ImDrawData = c.igGetDrawData();
var size_x = draw_data.DisplaySize.x * draw_data.FramebufferScale.x;
var size_y = draw_data.DisplaySize.y * draw_data.FramebufferScale.y;
if (size_x <= 0 or size_y <= 0) {
return;
}
self.device.dispatch.cmdBindDescriptorSets(
command_buffer,
.graphics,
self.pipeline_layout,
0,
@intCast(u32, descriptor_sets.len),
@ptrCast([*]const vk.DescriptorSet, descriptor_sets.ptr),
0,
undefined,
);
self.device.dispatch.cmdBindPipeline(command_buffer, .graphics, self.pipeline);
{
var push_data: [4]f32 = undefined;
//Scale
push_data[0] = 2.0 / draw_data.DisplaySize.x;
push_data[1] = 2.0 / draw_data.DisplaySize.y;
//Translate
push_data[2] = -1.0 - (draw_data.DisplayPos.x * push_data[0]);
push_data[3] = -1.0 - (draw_data.DisplayPos.y * push_data[1]);
self.device.dispatch.cmdPushConstants(command_buffer, self.pipeline_layout, SHADER_STAGES, 0, @sizeOf(@TypeOf(push_data)), &push_data);
var clip_offset = draw_data.DisplayPos;
var clip_scale = draw_data.FramebufferScale;
var i: u32 = 0;
while (i < draw_data.CmdListsCount) : (i += 1) {
var cmd_list: *c.ImDrawList = draw_data.CmdLists[i];
var vertex_data: []c.ImDrawVert = undefined;
vertex_data.ptr = cmd_list.VtxBuffer.Data;
vertex_data.len = @intCast(usize, cmd_list.VtxBuffer.Size);
var vertex_data_size = @intCast(u32, vertex_data.len * @sizeOf(c.ImDrawVert));
var vertex_buffer = try Buffer.init(self.device, vertex_data_size, .{ .vertex_buffer_bit = true }, .{ .host_visible_bit = true, .host_coherent_bit = true });
try vertex_buffer.fill(c.ImDrawVert, vertex_data);
try self.freed_buffers.append(vertex_buffer);
var index_data: []c.ImDrawIdx = undefined;
index_data.ptr = cmd_list.IdxBuffer.Data;
index_data.len = @intCast(usize, cmd_list.IdxBuffer.Size);
var index_data_size = @intCast(u32, index_data.len * @sizeOf(c.ImDrawIdx));
var index_buffer = try Buffer.init(self.device, index_data_size, .{ .index_buffer_bit = true }, .{ .host_visible_bit = true, .host_coherent_bit = true });
try index_buffer.fill(c.ImDrawIdx, index_data);
try self.freed_buffers.append(index_buffer);
self.device.dispatch.cmdBindVertexBuffers(command_buffer, 0, 1, &[_]vk.Buffer{vertex_buffer.handle}, &[_]u64{0});
self.device.dispatch.cmdBindIndexBuffer(command_buffer, index_buffer.handle, 0, vk.IndexType.uint16);
var cmd_i: u32 = 0;
while (cmd_i < cmd_list.CmdBuffer.Size) : (cmd_i += 1) {
var pcmd: c.ImDrawCmd = cmd_list.CmdBuffer.Data[cmd_i];
if (pcmd.UserCallback) |callback| {
//callback(cmd_list, pcmd);
} else {
var clip_rect: c.ImVec4 = undefined;
clip_rect.x = (pcmd.ClipRect.x - clip_offset.x) * clip_scale.x;
clip_rect.y = (pcmd.ClipRect.y - clip_offset.y) * clip_scale.y;
clip_rect.z = (pcmd.ClipRect.z - clip_offset.x) * clip_scale.x;
clip_rect.w = (pcmd.ClipRect.w - clip_offset.y) * clip_scale.y;
if (clip_rect.x < draw_data.DisplaySize.x and clip_rect.y < draw_data.DisplaySize.y and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) {
// Negative offsets are illegal for Set Scissor
if (clip_rect.x < 0.0) {
clip_rect.x = 0.0;
}
if (clip_rect.y < 0.0) {
clip_rect.y = 0.0;
}
var scissor_rect: vk.Rect2D = undefined;
scissor_rect.offset.x = @floatToInt(i32, clip_rect.x);
scissor_rect.offset.y = @floatToInt(i32, clip_rect.y);
scissor_rect.extent.width = @floatToInt(u32, clip_rect.z - clip_rect.x);
scissor_rect.extent.height = @floatToInt(u32, clip_rect.w - clip_rect.y);
self.device.dispatch.cmdSetScissor(command_buffer, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor_rect));
self.device.dispatch.cmdDrawIndexed(command_buffer, pcmd.ElemCount, 1, pcmd.IdxOffset, 0, 0);
}
}
}
}
}
}
};
const ImguiVertex = struct {
const Self = @This();
const binding_description = vk.VertexInputBindingDescription{
.binding = 0,
.stride = @sizeOf(Self),
.input_rate = .vertex,
};
const attribute_description = [_]vk.VertexInputAttributeDescription{
.{
.binding = 0,
.location = 0,
.format = .r32g32_sfloat,
.offset = @byteOffsetOf(Self, "pos"),
},
.{
.binding = 0,
.location = 1,
.format = .r32g32_sfloat,
.offset = @byteOffsetOf(Self, "uv"),
},
.{
.binding = 0,
.location = 2,
.format = .r8g8b8a8_unorm,
.offset = @byteOffsetOf(Self, "color"),
},
};
pos: [2]f32,
uv: [2]f32,
color: [4]u8,
}; | src/imgui.zig |
const std = @import("std");
const Fifo = std.fifo.LinearFifo(u8, .{ .Static = 512 });
const File = std.fs.File;
const Term = @import("term.zig").Term;
pub const Key = enum(u16) {
F1 = 0xFFFF - 0,
F2 = 0xFFFF - 1,
F3 = 0xFFFF - 2,
F4 = 0xFFFF - 3,
F5 = 0xFFFF - 4,
F6 = 0xFFFF - 5,
F7 = 0xFFFF - 6,
F8 = 0xFFFF - 7,
F9 = 0xFFFF - 8,
F10 = 0xFFFF - 9,
F11 = 0xFFFF - 10,
F12 = 0xFFFF - 11,
Insert = 0xFFFF - 12,
Delete = 0xFFFF - 13,
Home = 0xFFFF - 14,
End = 0xFFFF - 15,
PageUp = 0xFFFF - 16,
PageDown = 0xFFFF - 17,
ArrowUp = 0xFFFF - 18,
ArrowDown = 0xFFFF - 19,
ArrowLeft = 0xFFFF - 20,
ArrowRight = 0xFFFF - 21,
MouseLeft = 0xFFFF - 22,
MouseRight = 0xFFFF - 23,
MouseMiddle = 0xFFFF - 24,
MouseRelease = 0xFFFF - 25,
MouseWheelUp = 0xFFFF - 26,
MouseWheelDown = 0xFFFF - 27,
CtrlTilde = 0x00,
CtrlA = 0x01,
CtrlB = 0x02,
CtrlC = 0x03,
CtrlD = 0x04,
CtrlE = 0x05,
CtrlF = 0x06,
CtrlG = 0x07,
Backspace = 0x08,
Tab = 0x09,
CtrlJ = 0x0A,
CtrlK = 0x0B,
CtrlL = 0x0C,
Enter = 0x0D,
CtrlN = 0x0E,
CtrlO = 0x0F,
CtrlP = 0x10,
CtrlQ = 0x11,
CtrlR = 0x12,
CtrlS = 0x13,
CtrlT = 0x14,
CtrlU = 0x15,
CtrlV = 0x16,
CtrlW = 0x17,
CtrlX = 0x18,
CtrlY = 0x19,
CtrlZ = 0x1A,
Esc = 0x1B,
Ctrl4 = 0x1C,
Ctrl5 = 0x1D,
Ctrl6 = 0x1E,
Ctrl7 = 0x1F,
Space = 0x20,
Backspace2 = 0x7F,
};
pub const Modifier = enum(u8) {
Alt = 0x01,
Motion = 0x02,
};
pub const EventType = enum {
Key,
Resize,
Mouse,
};
pub const KeyEvent = struct {
mod: u8,
key: u16,
ch: u21,
};
pub const ResizeEvent = struct {
w: i32,
h: i32,
};
pub const MouseAction = enum {
MouseLeft,
MouseRight,
MouseMiddle,
MouseRelease,
MouseWheelUp,
MouseWheelDown,
};
pub const MouseEvent = struct {
action: MouseAction,
motion: bool,
x: usize,
y: usize,
};
pub const Event = union(EventType) {
Key: KeyEvent,
Resize: ResizeEvent,
Mouse: MouseEvent,
};
fn parseMouseEvent(fifo: *Fifo) ?MouseEvent {
if (fifo.readableLength() >= 6 and peekStartsWith(fifo, "\x1B[M")) {
// X10 mouse encoding, the simplest one
// \033 [ M Cb Cx Cy
const b = fifo.peekItem(3) - 32;
const action = switch (b & 3) {
0 => if (b & 64 != 0) MouseAction.MouseWheelUp else MouseAction.MouseLeft,
1 => if (b & 64 != 0) MouseAction.MouseWheelDown else MouseAction.MouseMiddle,
2 => MouseAction.MouseRight,
3 => MouseAction.MouseRelease,
else => return null,
};
const x = @intCast(u8, fifo.peekItem(4) - 1 - 32);
const y = @intCast(u8, fifo.peekItem(5) - 1 - 32);
fifo.discard(6);
return MouseEvent{
.action = action,
.motion = (b & 32) != 0,
.x = x,
.y = y,
};
} else if (peekStartsWith(fifo, "\x1B[")) {
// xterm 1006 extended mode or urxvt 1015 extended mode
// xterm: \033 [ < Cb ; Cx ; Cy (M or m)
// urxvt: \033 [ Cb ; Cx ; Cy M
const is_u = !(fifo.count >= 2 and fifo.peekItem(2) == '<');
const offset = if (is_u) 2 else @as(usize, 3);
var buf: [32]u8 = undefined;
var read_n = fifo.read(buf[0..]);
var read = buf[0..read_n];
var iter = std.mem.split(u8, read[offset..], ";");
// Get the absolute index of m/M in the buffer to unget the data past
// it before returning.
const abs_index_m = std.mem.indexOfAny(u8, read, "mM") orelse {
fifo.unget(read) catch unreachable;
return null;
};
const cb = iter.next();
const cx = iter.next();
const rest = iter.next();
if (cb == null or cx == null or rest == null) {
fifo.unget(read) catch unreachable;
return null;
}
// Add cb, cx offset and 2 (to account for the ';').
const index_m = abs_index_m - (cb.?.len + cx.?.len + offset + 2);
const cy = rest.?[0..index_m];
// const is_m = rest.?[index_m] == 'M';
const n1 = std.fmt.parseInt(u8, cb.?, 10) catch |e| std.debug.panic("{}", .{e});
const n2 = std.fmt.parseInt(u8, cx.?, 10) catch return null;
const n3 = std.fmt.parseInt(u8, cy, 10) catch return null;
const b = if (is_u) n1 - 32 else n1;
const x = n2 - 1;
const y = n3 - 1;
const action = switch (b & 3) {
0 => if (b & 64 != 0) MouseAction.MouseWheelUp else MouseAction.MouseLeft,
1 => if (b & 64 != 0) MouseAction.MouseWheelDown else MouseAction.MouseMiddle,
2 => MouseAction.MouseRight,
3 => MouseAction.MouseRelease,
else => return null,
};
if (abs_index_m + 1 < read_n) {
fifo.unget(read[abs_index_m + 1 .. read_n]) catch unreachable;
}
return MouseEvent{
.action = action,
.motion = (b & 32) != 0,
.x = x,
.y = y,
};
} else {
return null;
}
}
fn peekStartsWith(fifo: *Fifo, needle: []const u8) bool {
if (needle.len > fifo.readableLength()) return false;
return for (needle) |x, i| {
if (x != fifo.peekItem(i)) break false;
} else true;
}
fn parseEscapeSequence(fifo: *Fifo, term: Term) ?Event {
if (parseMouseEvent(fifo)) |x| return Event{ .Mouse = x };
for (term.keys.data) |k, i| {
if (peekStartsWith(fifo, k)) {
fifo.discard(k.len);
const key_ev = KeyEvent{
.mod = 0,
.key = 0xFFFF - @intCast(u16, i),
.ch = 0,
};
return Event{ .Key = key_ev };
}
}
return null;
}
pub fn extractEvent(fifo: *Fifo, term: Term, settings: InputSettings) ?Event {
// If the FIFO is empty, return null
if (fifo.readableLength() == 0) return null;
// Escape
if (fifo.peekItem(0) == '\x1B') {
if (parseEscapeSequence(fifo, term)) |x| {
return x;
} else {
switch (settings.mode) {
.Esc => {
const key_ev = KeyEvent{
.mod = 0,
.key = @enumToInt(Key.Esc),
.ch = 0,
};
return Event{ .Key = key_ev };
},
.Alt => {},
}
}
}
// Functional key
if (fifo.peekItem(0) <= @enumToInt(Key.Space) or
fifo.peekItem(0) == @enumToInt(Key.Backspace2))
{
const key_ev = KeyEvent{
.mod = 0,
.key = @intCast(u16, fifo.readItem() orelse unreachable),
.ch = 0,
};
return Event{ .Key = key_ev };
}
// UTF-8
if (std.unicode.utf8ByteSequenceLength(fifo.peekItem(0))) |utf8_len| {
if (fifo.readableLength() >= utf8_len) {
var buf: [3]u8 = undefined;
const amt = try fifo.reader().readAll(buf[0..utf8_len]);
const decoded = std.unicode.utf8Decode(buf[0..amt]) catch unreachable;
const key_ev = KeyEvent{
.mod = 0,
.key = 0,
.ch = @intCast(u21, decoded),
};
return Event{ .Key = key_ev };
}
} else |_| {
// Quietly discard this byte
fifo.discard(1);
}
return null;
}
pub fn getEvent(inout: File, fifo: *Fifo, term: Term, settings: InputSettings) !?Event {
// Read everything we can into the buffer
var b: [64]u8 = undefined;
while (true) {
const amt_read = try inout.readAll(&b);
try fifo.write(b[0..amt_read]);
if (amt_read < 64) break;
}
if (extractEvent(fifo, term, settings)) |x| {
return x;
}
return null;
}
pub fn waitFillEvent(inout: File, fifo: *Fifo, term: Term, settings: InputSettings) !Event {
while (true) {
if (try getEvent(inout, fifo, term, settings)) |event| {
return event;
}
// Wait for events
var event = std.os.epoll_event{
.data = std.os.epoll_data{
.@"u32" = 0,
},
.events = std.os.EPOLLIN,
};
var recieved_events: [1]std.os.epoll_event = undefined;
const epfd = try std.os.epoll_create1(0);
defer std.os.close(epfd);
try std.os.epoll_ctl(epfd, std.os.EPOLL_CTL_ADD, inout.handle, &event);
_ = std.os.epoll_wait(epfd, &recieved_events, -1);
}
unreachable;
}
pub const InputMode = enum {
Esc,
Alt,
};
pub const InputSettings = struct {
mode: InputMode = InputMode.Esc,
mouse: bool = false,
const Self = @This();
pub fn applySettings(self: Self, term: Term, writer: anytype) !void {
if (self.mouse) {
try writer.writeAll(term.funcs.get(.EnterMouse));
} else {
try writer.writeAll(term.funcs.get(.ExitMouse));
}
}
}; | src/input.zig |
const std = @import("std");
const testing = std.testing;
const log = std.log;
const numtheory = @import("numtheory");
const mul_mod = numtheory.mul_mod;
/// Represents p(x)=a*x+b
pub const Polynomial = struct {
const Self = @This();
a: i64,
b: i64,
// Computes f * g (mod m)
pub fn composeWith(f: Self, g: Self, m: i64) Polynomial {
std.debug.assert(m > 0);
// f = a*x + b
// g = a'*x + b'
// (f * g)(x) = f(a'x+b') = a*(a'x+b') + b = aa' * x + (ab' + b)
// FIXME: incorrect result when directly returning, i.e. return Polynomial { ... }
// See https://github.com/ziglang/zig/issues/4021
const new_b = @mod(mul_mod(f.a, g.b, m) + f.b, m);
return Polynomial{ .a = mul_mod(f.a, g.a, m), .b = new_b };
}
/// Compute f^e mod m (composition).
pub fn power(f: Self, e: u64, m: i64) Polynomial {
var x = Polynomial{ .a = 1, .b = 0 };
var y = f;
var ee = e;
while (ee != 0) {
if (ee & 1 != 0) x = x.composeWith(y, m);
y = y.composeWith(y, m);
ee = ee >> 1;
}
return x;
}
pub fn eval(self: Self, x: i64, m: i64) i64 {
std.debug.assert(m > 0);
return @mod(self.a * x + self.b, m);
}
};
test "composeWith is associative" {
const p1 = Polynomial{ .a = 1, .b = -6 }; // x - 6
const p2 = Polynomial{ .a = 7, .b = 0 }; // 7x
const p3 = Polynomial{ .a = -1, .b = -1 }; // -x-1
const m: i64 = 10;
var result = p2.composeWith(p1, m);
try testing.expectEqual(@as(i64, 7), result.a);
try testing.expectEqual(@as(i64, 8), result.b);
result = p3.composeWith(result, m);
try testing.expectEqual(@as(i64, 3), result.a);
try testing.expectEqual(@as(i64, 1), result.b);
result = p3.composeWith(p2, m).composeWith(p1, m);
try testing.expectEqual(@as(i64, 3), result.a);
try testing.expectEqual(@as(i64, 1), result.b);
}
test "composeWith 2" {
const p1 = Polynomial{ .a = -1, .b = -1 };
const p2 = Polynomial{ .a = 1, .b = -8 };
const m: i64 = 10;
var result = p2.composeWith(p1, m);
try testing.expectEqual(@as(i64, 9), result.a);
try testing.expectEqual(@as(i64, 1), result.b);
} | day22/src/polynomial.zig |
const std = @import("std");
const Builder = @import("std").build.Builder;
const Target = @import("std").Target;
const CrossTarget = @import("std").zig.CrossTarget;
const pkgs = @import("deps.zig").pkgs;
fn build_bios(b: *Builder) *std.build.RunStep {
const out_path = b.pathJoin(&.{ b.install_path, "/bin" });
const bios = b.addExecutable("stage1.elf", "stage1/stage1.zig");
bios.setMainPkgPath(".");
bios.addPackagePath("io", "lib/io.zig");
bios.addPackagePath("console", "stage1/bios/console.zig");
bios.addPackagePath("graphics", "stage1/bios/graphics.zig");
bios.addPackagePath("filesystem", "stage1/bios/filesystem.zig");
bios.addPackagePath("allocator", "stage1/bios/allocator.zig");
bios.addAssemblyFile("stage1/bios/entry.s");
bios.setOutputDir(out_path);
const features = std.Target.x86.Feature;
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_features = std.Target.Cpu.Feature.Set.empty;
disabled_features.addFeature(@enumToInt(features.mmx));
disabled_features.addFeature(@enumToInt(features.sse));
disabled_features.addFeature(@enumToInt(features.sse2));
disabled_features.addFeature(@enumToInt(features.avx));
disabled_features.addFeature(@enumToInt(features.avx2));
enabled_features.addFeature(@enumToInt(features.soft_float));
bios.code_model = .kernel;
bios.setTarget(CrossTarget{
.cpu_arch = Target.Cpu.Arch.i386,
.os_tag = Target.Os.Tag.freestanding,
.abi = Target.Abi.none,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_features,
});
bios.setBuildMode(b.standardReleaseOptions());
bios.setLinkerScriptPath(.{ .path = "stage1/bios/linker.ld" });
pkgs.addAllTo(bios);
bios.install();
const bin = b.addInstallRaw(bios, "stage1.bin", .{});
// zig fmt: off
const bootsector = b.addSystemCommand(&[_][]const u8{
"nasm", "-Ox", "-w+all", "-fbin", "stage0/bootsect.s", "-Istage0",
"-o", out_path, "/stage0.bin",
});
// zig fmt: on
bootsector.step.dependOn(&bin.step);
// zig fmt: off
const append = b.addSystemCommand(&[_][]const u8{
"/bin/sh", "-c",
std.mem.concat(b.allocator, u8, &[_][]const u8{
"cat ",
out_path, "/stage0.bin ",
out_path, "/stage1.bin ",
">", out_path, "/xeptoboot.bin",
}) catch unreachable,
});
// zig fmt: on
append.step.dependOn(&bootsector.step);
const bios_step = b.step("bios", "Build the BIOS version");
bios_step.dependOn(&append.step);
return append;
}
fn build_uefi(b: *Builder) *std.build.LibExeObjStep {
const out_path = b.pathJoin(&.{ b.install_path, "/bin" });
const uefi = b.addExecutable("xeptoboot", "stage1/uefi/entry.zig");
uefi.setMainPkgPath(".");
uefi.addPackagePath("io", "lib/io.zig");
uefi.addPackagePath("console", "stage1/uefi/console.zig");
uefi.addPackagePath("graphics", "stage1/uefi/graphics.zig");
uefi.addPackagePath("filesystem", "stage1/uefi/filesystem.zig");
uefi.addPackagePath("allocator", "stage1/uefi/allocator.zig");
uefi.setOutputDir(out_path);
const features = std.Target.x86.Feature;
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_features = std.Target.Cpu.Feature.Set.empty;
disabled_features.addFeature(@enumToInt(features.mmx));
disabled_features.addFeature(@enumToInt(features.sse));
disabled_features.addFeature(@enumToInt(features.sse2));
disabled_features.addFeature(@enumToInt(features.avx));
disabled_features.addFeature(@enumToInt(features.avx2));
enabled_features.addFeature(@enumToInt(features.soft_float));
uefi.code_model = .kernel;
uefi.setTarget(CrossTarget{
.cpu_arch = Target.Cpu.Arch.x86_64,
.os_tag = Target.Os.Tag.uefi,
.abi = Target.Abi.msvc,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_features,
});
uefi.setBuildMode(b.standardReleaseOptions());
pkgs.addAllTo(uefi);
uefi.install();
const uefi_step = b.step("uefi", "Build the UEFI version");
uefi_step.dependOn(&uefi.step);
return uefi;
}
fn run_qemu_bios(b: *Builder, path: []const u8) *std.build.RunStep {
const cmd = &[_][]const u8{
// zig fmt: off
"qemu-system-x86_64",
"-hda", path,
"-debugcon", "stdio",
"-vga", "virtio",
"-m", "4G",
// This prevents the BIOS to boot the bootsector
// "-machine", "q35,accel=kvm:whpx:tcg",
"-machine", "accel=kvm:whpx:tcg",
"-no-reboot", "-no-shutdown",
// zig fmt: on
};
const run_step = b.addSystemCommand(cmd);
const run_command = b.step("run-bios", "Run the BIOS version");
run_command.dependOn(&run_step.step);
return run_step;
}
fn run_qemu_uefi(b: *Builder, dir: []const u8) *std.build.RunStep {
const cmd = &[_][]const u8{
// zig fmt: off
"/bin/sh", "-c",
std.mem.concat(b.allocator, u8, &[_][]const u8{
"mkdir -p ", dir, "/efi-root/EFI/BOOT && ",
"cp ", dir, "/bin/xeptoboot.efi ", dir, "/efi-root/EFI/BOOT/BOOTX64.EFI && ",
"cp ", dir, "/../xeptoboot.zzz.example ", dir, "/efi-root/xeptoboot.zzz && ",
"qemu-system-x86_64 ",
// This doesn't work for some reason
// "-drive if=none,format=raw,media=disk,file=fat:rw:", dir, "/efi-root ",
"-hda fat:rw:", dir, "/efi-root ",
"-debugcon stdio ",
"-vga virtio ",
"-m 4G ",
"-machine q35,accel=kvm:whpx:tcg ",
"-drive if=pflash,format=raw,unit=0,file=external/ovmf-prebuilt/bin/RELEASEX64_OVMF.fd,readonly=on ",
"-no-reboot -no-shutdown",
}) catch unreachable,
// zig fmt: on
};
const run_step = b.addSystemCommand(cmd);
const run_command = b.step("run-uefi", "Run the UEFI version");
run_command.dependOn(&run_step.step);
return run_step;
}
pub fn build(b: *Builder) void {
const bios_path = b.pathJoin(&.{b.install_path, "/bin/xeptoboot.bin"});
const bios = build_bios(b);
const uefi = build_uefi(b);
const bios_step = run_qemu_bios(b, bios_path);
bios_step.step.dependOn(&bios.step);
const uefi_step = run_qemu_uefi(b, b.install_path);
uefi_step.step.dependOn(&uefi.step);
b.default_step.dependOn(&uefi_step.step);
} | build.zig |
const std = @import("std");
const file = std.os.File;
const assert = std.debug.assert;
const warn = std.debug.warn;
pub fn main() anyerror!void {
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
const allocator = &direct_allocator.allocator;
const input_file = try file.openRead("day3input.txt");
defer input_file.close();
const buf = try allocator.alloc(u8,try input_file.getEndPos());
defer allocator.free(buf);
_ = input_file.inStream().stream.readFull(buf);
// 1000 sq foot grid, packed struct to make four u2's be in one byte
var cloth_grid = try allocator.alloc(u2,1000*1000);
defer allocator.free(cloth_grid);
std.mem.set(u2,cloth_grid,0);
warn("\ntype of u2buf: {}\n", @typeName(@typeOf(cloth_grid)));
warn("\nbytelength: {}\n", @sliceToBytes(cloth_grid).len);
var iter = std.mem.split(buf,"\n");
while (iter.next()) |chunk_info| {
var field_iter = std.mem.split(chunk_info,"# @,:x");
_ = field_iter.next();
var x_coord = try std.fmt.parseInt(u32,field_iter.next() orelse []u8{0},10);
var y_coord = try std.fmt.parseInt(u32,field_iter.next() orelse []u8{0},10);
var x_length = try std.fmt.parseInt(u32,field_iter.next() orelse []u8{0},10);
var y_length = try std.fmt.parseInt(u32,field_iter.next() orelse []u8{0},10);
tickOffChunks(cloth_grid,x_coord,y_coord,x_length,y_length);
}
const std_out = try std.io.getStdOut();
defer std_out.close();
try std_out.outStream().stream.print("\nThis many square inches of fabric have overlapping claims: {}\n", countOverlappingClaims(cloth_grid));
}
fn tickOffChunks( buf: []u2,
x_coord: u32,
y_coord: u32,
x_length: u32,
y_length: u32,) void {
const hop_distance = 1000;
var index: u32 = (y_coord * hop_distance) + x_coord;
var y_temp_len = y_length;
while (y_temp_len > 0) {
var x_temp_len = x_length;
while (x_temp_len > 0 and index < buf.len) {
if (buf[index] < std.math.maxInt(u2)) {
buf[index] += 1;
}
index += 1;
x_temp_len -= 1;
}
index += hop_distance - x_length;
y_temp_len -= 1;
}
}
fn countOverlappingClaims(buf: []u2) u32 {
var answer: u32 = 0;
for (buf) |count| {
if (count > 1) {
answer += 1;
}
}
return answer;
}
test "u2 array" {
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
const allocator = &direct_allocator.allocator;
var u2buf = try allocator.alloc(u2,1000*1000);
warn("\ntype of u2buf: {}\n", @typeName(@typeOf(u2buf)));
warn("\nbytelength: {}\n", @sliceToBytes(u2buf).len);
var u2buf_slice = u2buf[0..];
warn("\ntype of u2buf_slice: {}\n", @typeName(@typeOf(u2buf_slice)));
} | src/day3.zig |
const std = @import("std");
const print = std.debug.print;
const net = std.net;
const os = std.os;
const datetime = @import("./zig-datetime/datetime.zig");
const timezones = @import("./zig-datetime/timezones.zig");
pub fn main() !void {
print("Configuring local address...\n", .{});
const localhost = try net.Address.parseIp6("::1", 8080);
print("Creating socket...\n", .{});
const sock_listen = try os.socket(os.AF_INET6, os.SOCK_STREAM, os.IPPROTO_TCP);
defer {
print("Closing listening socket...\n", .{});
os.close(sock_listen);
}
print("Binding socket to local address...\n", .{});
var sock_len = localhost.getOsSockLen();
try os.bind(sock_listen, &localhost.any, sock_len);
print("Listening...\n", .{});
try os.listen(sock_listen, 10);
print("Waiting for connection...\n", .{});
var accepted_addr: net.Address = undefined;
var addr_len: os.socklen_t = @sizeOf(net.Address);
var sock_client = try os.accept(sock_listen, &accepted_addr.any, &addr_len, os.SOCK_CLOEXEC);
defer {
print("Closing connection...\n", .{});
os.close(sock_client);
}
print("Client is connected...\n", .{});
print("{}\n", .{accepted_addr});
print("Reading request...\n", .{});
var request: [1024]u8 = undefined;
const bytes_recv = os.recv(sock_client, request[0..], 0);
print("Received {} bytes.\n", .{bytes_recv});
print("Sending response...\n", .{});
const response = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/plain\r\n\r\nLocal time is: ";
var bytes_sent = os.send(sock_client, response, 0);
print("Sent {} of {} bytes.\n", .{ bytes_sent, response.len });
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var now = datetime.Datetime.now().shiftTimezone(&timezones.Europe.Rome);
var now_str = try now.formatHttp(&gpa.allocator);
defer gpa.allocator.free(now_str);
bytes_sent = os.send(sock_client, now_str, 0);
print("Sent {} of {} bytes.\n", .{ bytes_sent, now_str.len });
print("Finished...\n", .{});
} | chap02/time_server_ipv6_lowlvl.zig |
const std = @import("std");
const AnimationData = @import("../ModelFiles/AnimationFiles.zig").AnimationData;
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
const Asset = @import("../Assets/Assets.zig").Asset;
const ShaderInstance = @import("Shader.zig").ShaderInstance;
const Mesh = @import("Mesh.zig").Mesh;
const ModelData = @import("../ModelFiles/ModelFiles.zig").ModelData;
const this_frame_time = &@import("RTRenderEngine.zig").this_frame_time;
var identity_matrix_buffer: ?[]f32 = null;
pub const Animation = struct {
ref_count: ReferenceCounter = ReferenceCounter{},
animation_asset: ?*Asset = null,
model_asset: ?*Asset = null,
animation_data: *AnimationData,
model: *ModelData,
animation_start_time: u64 = 0,
matrices: []f32,
allocator: *std.mem.Allocator,
paused: bool = false,
paused_at_time: u64 = 0,
fn create_matrices(animation_data: *AnimationData, model: *ModelData, allocator: *std.mem.Allocator) ![]f32 {
const num_frames = animation_data.frame_count;
var matrices = try allocator.alloc(f32, num_frames * model.bone_count * 4 * 4);
var frame_index: u32 = 0;
while (frame_index < num_frames) : (frame_index += 1) {
var bone_i: u32 = 0;
var bone_o: u32 = 0; // offset into bones data used by getBoneName
while (bone_i < model.bone_count) : (bone_i += 1) {
const name = model.getBoneName(&bone_o) catch break;
const animation_bone_index = animation_data.*.getBoneIndex(name) catch continue;
const animation_bone_matrix_offset = (frame_index * animation_data.bone_count + animation_bone_index) * 4 * 4;
const o = (frame_index * model.bone_count + bone_i) * 4 * 4;
std.mem.copy(f32, matrices[o .. o + 4 * 4], animation_data.matrices_absolute[animation_bone_matrix_offset .. animation_bone_matrix_offset + 4 * 4]);
}
}
return matrices;
}
pub fn init(animation_data: *AnimationData, model: *ModelData, allocator: *std.mem.Allocator) !Animation {
if (model.attributes_bitmap & (1 << @enumToInt(ModelData.VertexAttributeType.BoneIndices)) == 0 or model.bone_count == 0) {
return error.MeshNasNoBones;
}
var matrices = try create_matrices(animation_data, model, allocator);
return Animation{
.animation_data = animation_data,
.model = model,
.matrices = matrices,
.allocator = allocator,
.animation_start_time = this_frame_time.*,
};
}
pub fn initFromAssets(animation_asset: *Asset, model_asset: *Asset, allocator: *std.mem.Allocator) !Animation {
if (animation_asset.asset_type != Asset.AssetType.Animation or model_asset.asset_type != Asset.AssetType.Model) {
return error.InvalidAssetType;
}
if (animation_asset.state != Asset.AssetState.Ready or model_asset.state != Asset.AssetState.Ready) {
return error.InvalidAssetState;
}
var a = try init(&animation_asset.animation.?, &model_asset.model.?, allocator);
a.animation_asset = animation_asset;
a.model_asset = model_asset;
animation_asset.ref_count.inc();
animation_asset.ref_count2.inc();
model_asset.ref_count.inc();
return a;
}
fn detatchAssets(self: *Animation, free_if_unused: bool) void {
if (self.animation_asset != null) {
self.animation_asset.?.ref_count.dec();
if (free_if_unused and self.animation_asset.?.ref_count.n == 0) {
self.animation_asset.?.free(false);
}
self.animation_asset = null;
}
if (self.model_asset != null) {
self.model_asset.?.ref_count.dec();
if (free_if_unused and self.model_asset.?.ref_count.n == 0) {
self.model_asset.?.free(false);
}
self.model_asset = null;
}
}
pub fn play(self: *Animation) void {
self.animation_start_time = this_frame_time.*;
}
pub fn pause(self: *Animation) void {
if (self.paused == false) {
self.paused = true;
self.paused_at_time = this_frame_time.*;
}
}
pub fn unpause(self: *Animation) void {
if (self.paused == true) {
self.paused = false;
self.animation_start_time += this_frame_time.* - self.paused_at_time;
}
}
// Used during render - do not call this function
pub fn setAnimationMatrices(self: *Animation, shader: *const ShaderInstance, model: *ModelData) !void {
if (model.bone_count != self.model.bone_count) {
return error.ModelNotCompatible;
}
var now: u64 = this_frame_time.*;
if (self.paused) {
now = self.paused_at_time;
}
const time_difference = now - self.animation_start_time;
var frame_index = @intCast(u32, time_difference / (self.animation_data.frame_duration));
if (time_difference % self.animation_data.frame_duration >= time_difference / 2) {
frame_index += 1;
}
frame_index = frame_index % self.animation_data.frame_count;
const o = frame_index * model.bone_count * 4 * 4;
try shader.setBoneMatrices(self.matrices[o .. o + model.bone_count * 4 * 4]);
}
pub fn setAnimationIdentityMatrices(shader: *const ShaderInstance, allocator: *std.mem.Allocator) !void {
if (identity_matrix_buffer == null) {
identity_matrix_buffer = try allocator.alloc(f32, 128 * 4 * 4);
var bone_i: u32 = 0;
while (bone_i < 128) : (bone_i += 1) {
std.mem.copy(f32, identity_matrix_buffer.?[bone_i * 4 * 4 .. bone_i * 4 * 4 + 4 * 4], &[16]f32{
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
});
}
}
try shader.setBoneMatrices(identity_matrix_buffer.?);
}
pub fn deinit(self: *Animation) void {
self.ref_count.deinit();
self.detatchAssets(false);
self.allocator.free(self.matrices);
}
pub fn freeIfUnused(self: *Animation) void {
if (self.ref_count.n != 0) {
return;
}
self.ref_count.deinit();
self.detatchAssets(true);
self.allocator.free(self.matrices);
}
}; | src/RTRenderEngine/Animation.zig |
gconst std = @import("std");
const process = @import("../../process.zig");
const platform = @import("../../platform.zig");
const time = @import("../../time.zig");
const util = @import("../../util.zig");
const w3 = @import("../../wasm3.zig");
const syscall = @import("../../syscall.zig");
usingnamespace @import("wasi_defs.zig");
const Process = process.Process;
inline fn myProc(ctx: w3.ZigFunctionCtx) *Process {
return ctx.cookie.?.as(Process);
}
pub const Debug = struct {
pub const namespaces = [_][:0]const u8{"shinkou_debug"};
pub fn earlyprintk(ctx: w3.ZigFunctionCtx, args: struct { string: []u8 }) !void {
platform.earlyprintk(args.string);
}
pub fn read_kmem(ctx: w3.ZigFunctionCtx, args: struct { phys_addr: u64, buffer: []u8 }) !void {
var ptr = @intToPtr([*]u8, @truncate(usize, phys_addr));
std.mem.copy(u8, buffer, ptr[0..buffer.len]);
}
pub fn write_kmem(ctx: w3.ZigFunctionCtx, args: struct { phys_addr: u64, buffer: []u8 }) !void {
var ptr = @intToPtr([*]u8, @truncate(usize, phys_addr));
std.mem.copy(u8, ptr[0..buffer.len], buffer);
}
};
pub const Preview1 = struct {
pub const namespaces = [_][:0]const u8{ "wasi_snapshot_preview1", "wasi_unstable" };
const IoVec = extern struct {
bufptr: u32,
buflen: u32,
}; // These structs will always be manually padded if needed
const PrestatDir = extern struct {
fd_type: u8 = 0,
name_len: u32 = 0,
};
const Self = @This();
pub fn proc_exit(ctx: w3.ZigFunctionCtx, args: struct { exit_code: u32 }) !void {
syscall.exit(myProc(ctx), args.exit_code);
return w3.Error.Exit;
}
pub fn sched_yield(ctx: w3.ZigFunctionCtx, args: struct {}) !u32 {
myProc(ctx).task().yield();
return errnoInt(.ESUCCESS);
}
pub fn clock_time_get(ctx: w3.ZigFunctionCtx, args: struct { clock_id: Clock, precision: i64, timestamp: w3.u64_ptr }) !u32 {
args.timestamp.* = @bitCast(u64, switch (args.clock_id) {
.realtime => time.getClockNano(.real),
.monotonic => time.getClockNano(.monotonic),
.uptime => time.getClockNano(.uptime),
else => { return errnoInt(.EINVAL); }
});
return errnoInt(.ESUCCESS);
}
pub fn fd_prestat_get(ctx: w3.ZigFunctionCtx, args: struct { fd: u32, prestat: *align(1) Self.PrestatDir }) !u32 {
util.compAssert(@sizeOf(Self.PrestatDir) == 8);
myProc(ctx).task().yield();
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.fd))) |fd| {
if (!fd.preopen) return errnoInt(.ENOTSUP);
args.prestat.* = .{ .name_len = if (fd.name != null) @truncate(u32, fd.name.?.len) else 0 };
return errnoInt(.ESUCCESS);
}
return errnoInt(.EBADF);
}
pub fn fd_prestat_dir_name(ctx: w3.ZigFunctionCtx, args: struct { fd: u32, name: []u8 }) !u32 {
myProc(ctx).task().yield();
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.fd))) |fd| {
std.mem.copy(u8, args.name, if (fd.name != null) fd.name.? else "");
return errnoInt(.ESUCCESS);
}
return errnoInt(.EBADF);
}
pub fn fd_renumber(ctx: w3.ZigFunctionCtx, args: struct { from: u32, to: u32 }) !u32 {
myProc(ctx).task().yield();
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.from))) |from| {
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.to))) |to| {
to.close() catch |err| return errnoInt(errorToNo(err));
}
try myProc(ctx).open_nodes.put(@truncate(process.Fd.Num, args.to), from);
_ = myProc(ctx).open_nodes.remove(from.num);
from.num = @truncate(process.Fd.Num, args.to);
return errnoInt(.ESUCCESS);
}
return errnoInt(.EBADF);
}
pub fn fd_write(ctx: w3.ZigFunctionCtx, args: struct { fd: u32, iovecs: []align(1) Self.IoVec, written: w3.u32_ptr }) !u32 {
util.compAssert(@sizeOf(Self.IoVec) == 8);
myProc(ctx).task().yield();
args.written.* = 0;
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.fd))) |fd| {
for (args.iovecs) |iovec| {
args.written.* += @truncate(u32, fd.write(ctx.memory[iovec.bufptr .. iovec.bufptr + iovec.buflen]) catch |err| return errnoInt(errorToNo(err)));
}
return errnoInt(.ESUCCESS);
}
return errnoInt(.EBADF);
}
pub fn fd_read(ctx: w3.ZigFunctionCtx, args: struct { fd: u32, iovecs: []align(1) Self.IoVec, amount: w3.u32_ptr }) !u32 {
util.compAssert(@sizeOf(Self.IoVec) == 8);
myProc(ctx).task().yield();
args.amount.* = 0;
if (myProc(ctx).open_nodes.get(@truncate(process.Fd.Num, args.fd))) |fd| {
for (args.iovecs) |iovec| {
args.amount.* += @truncate(u32, fd.read(ctx.memory[iovec.bufptr .. iovec.bufptr + iovec.buflen]) catch |err| return errnoInt(errorToNo(err)));
}
return errnoInt(.ESUCCESS);
}
return errnoInt(.EBADF);
}
pub fn args_sizes_get(ctx: w3.ZigFunctionCtx, args: struct { argc: w3.u32_ptr, argv_buf_size: w3.u32_ptr }) !u32 {
args.argc.* = @truncate(u32, myProc(ctx).argc);
args.argv_buf_size.* = @truncate(u32, myProc(ctx).argv.len) + 1;
return errnoInt(.ESUCCESS);
}
// TODO: make this secure
pub fn args_get(ctx: w3.ZigFunctionCtx, args: struct { argv: [*]align(1) u32, argv_buf: u32 }) !u32 {
std.mem.copy(u8, ctx.memory[args.argv_buf..], myProc(ctx).argv);
ctx.memory[args.argv_buf + myProc(ctx).argv.len] = 0;
if (myProc(ctx).argv.len == 0) return errnoInt(.ESUCCESS);
args.argv[0] = args.argv_buf;
var i: usize = 1;
for (myProc(ctx).argv) |c, off| {
if (off == (myProc(ctx).argv.len - 1)) break;
if (c != '\x00') continue;
args.argv[i] = args.argv_buf + @truncate(u32, off + 1);
i += 1;
}
return errnoInt(.ESUCCESS);
}
}; | kernel/runtime/wasm/wasi.zig |
const std = @import("std");
const assert = std.debug.assert;
const zp = @import("zplay");
const dig = zp.deps.dig;
const alg = zp.deps.alg;
const bt = zp.deps.bt;
const Vec3 = alg.Vec3;
const Vec4 = alg.Vec4;
const Mat4 = alg.Mat4;
const VertexArray = zp.graphics.common.VertexArray;
const Texture2D = zp.graphics.texture.Texture2D;
const Renderer = zp.graphics.@"3d".Renderer;
const SimpleRenderer = zp.graphics.@"3d".SimpleRenderer;
const PhongRenderer = zp.graphics.@"3d".PhongRenderer;
const Light = zp.graphics.@"3d".Light;
const Model = zp.graphics.@"3d".Model;
const Material = zp.graphics.@"3d".Material;
const Camera = zp.graphics.@"3d".Camera;
var simple_renderer: SimpleRenderer = undefined;
var phong_renderer: PhongRenderer = undefined;
var color_material: Material = undefined;
var wireframe_mode = false;
var scene: Scene = undefined;
var camera = Camera.fromPositionAndTarget(
Vec3.new(5, 10, 25),
Vec3.new(-4, 8, 0),
null,
);
fn init(ctx: *zp.Context) anyerror!void {
std.log.info("game init", .{});
// init imgui
try dig.init(ctx.window);
// create renderer
simple_renderer = SimpleRenderer.init();
phong_renderer = PhongRenderer.init(std.testing.allocator);
phong_renderer.setDirLight(Light.init(.{
.directional = .{
.ambient = Vec3.new(0.8, 0.8, 0.8),
.diffuse = Vec3.new(0.5, 0.5, 0.3),
.specular = Vec3.new(0.1, 0.1, 0.1),
.direction = Vec3.new(-1, -1, 0),
},
}));
// init color_material
color_material = Material.init(.{
.single_texture = try Texture2D.fromPixelData(
std.testing.allocator,
&.{ 0, 255, 0, 255 },
1,
1,
.{},
),
});
// create scene
scene = try Scene.init(std.testing.allocator, ctx);
// graphics init
ctx.graphics.toggleCapability(.depth_test, true);
ctx.graphics.toggleCapability(.stencil_test, true);
}
fn loop(ctx: *zp.Context) void {
// camera movement
const distance = ctx.delta_tick * camera.move_speed;
if (ctx.isKeyPressed(.w)) {
camera.move(.forward, distance);
}
if (ctx.isKeyPressed(.s)) {
camera.move(.backward, distance);
}
if (ctx.isKeyPressed(.a)) {
camera.move(.left, distance);
}
if (ctx.isKeyPressed(.d)) {
camera.move(.right, distance);
}
if (ctx.isKeyPressed(.left)) {
camera.rotate(0, -1);
}
if (ctx.isKeyPressed(.right)) {
camera.rotate(0, 1);
}
if (ctx.isKeyPressed(.up)) {
camera.rotate(1, 0);
}
if (ctx.isKeyPressed(.down)) {
camera.rotate(-1, 0);
}
while (ctx.pollEvent()) |e| {
switch (e) {
.window_event => |we| {
switch (we.data) {
.resized => |size| {
ctx.graphics.setViewport(0, 0, size.width, size.height);
},
else => {},
}
},
.keyboard_event => |key| {
if (key.trigger_type == .up) {
switch (key.scan_code) {
.escape => ctx.kill(),
.f1 => ctx.toggleFullscreeen(null),
else => {},
}
}
},
.quit_event => ctx.kill(),
else => {},
}
}
var width: u32 = undefined;
var height: u32 = undefined;
ctx.graphics.getDrawableSize(ctx.window, &width, &height);
ctx.graphics.clear(true, true, true, [_]f32{ 0.2, 0.3, 0.3, 1.0 });
// render world
var rd = phong_renderer.renderer();
rd.begin();
scene.update(ctx, rd) catch unreachable;
rd.end();
// settings
dig.beginFrame();
{
dig.setNextWindowPos(
.{ .x = @intToFloat(f32, width) - 10, .y = 50 },
.{
.cond = dig.c.ImGuiCond_Always,
.pivot = .{ .x = 1, .y = 0 },
},
);
if (dig.begin(
"settings",
null,
dig.c.ImGuiWindowFlags_NoResize |
dig.c.ImGuiWindowFlags_AlwaysAutoResize,
)) {
if (dig.checkbox("wireframe", &wireframe_mode)) {
ctx.graphics.setPolygonMode(if (wireframe_mode) .line else .fill);
}
}
dig.end();
}
dig.endFrame();
}
const Scene = struct {
const Object = struct {
model: Model,
body: bt.Body,
size: Vec3 = undefined,
};
const default_linear_damping: f32 = 0.1;
const default_angular_damping: f32 = 0.1;
const default_world_friction: f32 = 0.15;
world: bt.World,
objs: std.ArrayList(Object),
physics_debug: *PhysicsDebug,
fn init(allocator: std.mem.Allocator, ctx: *zp.Context) !Scene {
var width: u32 = undefined;
var height: u32 = undefined;
ctx.graphics.getDrawableSize(ctx.window, &width, &height);
var self = Scene{
.world = bt.worldCreate(),
.objs = std.ArrayList(Object).init(allocator),
.physics_debug = try allocator.create(PhysicsDebug),
};
bt.worldSetGravity(self.world, &Vec3.new(0.0, -10.0, 0.0).toArray());
// physics debug draw
self.physics_debug.* = PhysicsDebug.init(allocator);
bt.worldDebugSetCallbacks(self.world, &.{
.drawLine1 = PhysicsDebug.drawLine1Callback,
.drawLine2 = PhysicsDebug.drawLine2Callback,
.drawContactPoint = PhysicsDebug.drawContactPointCallback,
.reportErrorWarning = PhysicsDebug.reportErrorWarningCallback,
.user_data = self.physics_debug,
});
// init/add objects
var room = Object{
.model = try Model.fromGLTF(
allocator,
"assets/world.gltf",
false,
try Texture2D.fromPixelData(
allocator,
&.{ 128, 128, 128, 255 },
1,
1,
.{},
),
),
.body = bt.bodyAllocate(),
};
var shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_TRIANGLE_MESH);
bt.shapeTriMeshCreateBegin(shape);
bt.shapeTriMeshAddIndexVertexArray(
shape,
@intCast(i32, room.model.meshes.items[0].indices.?.items.len / 3),
room.model.meshes.items[0].indices.?.items.ptr,
3 * @sizeOf(u32),
@intCast(i32, room.model.meshes.items[0].positions.items.len),
room.model.meshes.items[0].positions.items.ptr,
@sizeOf(Vec3),
);
bt.shapeTriMeshCreateEnd(shape);
try self.addBodyToWorld(&room, 0, shape, Vec3.zero());
bt.bodySetFriction(room.body, default_world_friction);
var capsule = Object{
.model = try Model.fromGLTF(
allocator,
"assets/capsule.gltf",
false,
null,
),
.body = bt.bodyAllocate(),
};
shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_CAPSULE);
bt.shapeCapsuleCreate(shape, 1, 2, bt.c.CBT_LINEAR_AXIS_Y);
try self.addBodyToWorld(&capsule, 30, shape, Vec3.new(-5, 12, -2));
var cylinder = Object{
.model = try Model.fromGLTF(
allocator,
"assets/cylinder.gltf",
false,
null,
),
.body = bt.bodyAllocate(),
};
shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_CYLINDER);
bt.shapeCylinderCreate(shape, &Vec3.new(1.5, 2.0, 1.5).toArray(), bt.c.CBT_LINEAR_AXIS_Y);
try self.addBodyToWorld(&cylinder, 60, shape, Vec3.new(-5, 10, -2));
var cube = Object{
.model = try Model.fromGLTF(
allocator,
"assets/cube.gltf",
false,
null,
),
.body = bt.bodyAllocate(),
};
shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_BOX);
bt.shapeBoxCreate(shape, &Vec3.new(0.5, 1.0, 2.0).toArray());
try self.addBodyToWorld(&cube, 50, shape, Vec3.new(-5, 8, -2));
var cone = Object{
.model = try Model.fromGLTF(
allocator,
"assets/cone.gltf",
false,
null,
),
.body = bt.bodyAllocate(),
};
shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_CONE);
bt.shapeConeCreate(shape, 1.0, 2.0, bt.c.CBT_LINEAR_AXIS_Y);
try self.addBodyToWorld(&cone, 15, shape, Vec3.new(-5, 5, -2));
var sphere = Object{
.model = try Model.fromGLTF(
allocator,
"assets/sphere.gltf",
false,
null,
),
.body = bt.bodyAllocate(),
};
shape = bt.shapeAllocate(bt.c.CBT_SHAPE_TYPE_SPHERE);
bt.shapeSphereCreate(shape, 1.5);
try self.addBodyToWorld(&sphere, 25, shape, Vec3.new(-5, 3, -2));
// allocate texture units
var unit: i32 = 0;
for (self.objs.items) |obj| {
for (obj.model.materials.items) |m| {
unit = m.allocTextureUnit(unit);
}
}
_ = color_material.allocTextureUnit(unit);
return self;
}
fn addBodyToWorld(self: *Scene, obj: *Object, mass: f32, shape: bt.Shape, position: Vec3) !void {
const shape_type = bt.shapeGetType(shape);
obj.size = switch (shape_type) {
bt.c.CBT_SHAPE_TYPE_BOX => blk: {
var half_extents: bt.Vector3 = undefined;
bt.shapeBoxGetHalfExtentsWithoutMargin(shape, &half_extents);
break :blk Vec3.fromSlice(&half_extents);
},
bt.c.CBT_SHAPE_TYPE_SPHERE => blk: {
break :blk Vec3.set(bt.shapeSphereGetRadius(shape));
},
bt.c.CBT_SHAPE_TYPE_CONE => blk: {
assert(bt.shapeConeGetUpAxis(shape) == bt.c.CBT_LINEAR_AXIS_Y);
const radius = bt.shapeConeGetRadius(shape);
const height = bt.shapeConeGetHeight(shape);
assert(radius == 1.0 and height == 2.0);
break :blk Vec3.new(radius, 0.5 * height, radius);
},
bt.c.CBT_SHAPE_TYPE_CYLINDER => blk: {
var half_extents: bt.Vector3 = undefined;
assert(bt.shapeCylinderGetUpAxis(shape) == bt.c.CBT_LINEAR_AXIS_Y);
bt.shapeCylinderGetHalfExtentsWithoutMargin(shape, &half_extents);
assert(half_extents[0] == half_extents[2]);
break :blk Vec3.fromSlice(&half_extents);
},
bt.c.CBT_SHAPE_TYPE_CAPSULE => blk: {
assert(bt.shapeCapsuleGetUpAxis(shape) == bt.c.CBT_LINEAR_AXIS_Y);
const radius = bt.shapeCapsuleGetRadius(shape);
const half_height = bt.shapeCapsuleGetHalfHeight(shape);
assert(radius == 1.0 and half_height == 1.0);
break :blk Vec3.new(radius, half_height, radius);
},
bt.c.CBT_SHAPE_TYPE_TRIANGLE_MESH => Vec3.set(1),
bt.c.CBT_SHAPE_TYPE_COMPOUND => Vec3.set(1),
else => blk: {
assert(false);
break :blk Vec3.set(1);
},
};
try self.objs.append(obj.*);
bt.bodyCreate(
obj.body,
mass,
&bt.convertMat4ToTransform(Mat4.fromTranslate(position)),
shape,
);
bt.bodySetUserIndex(obj.body, 0, @intCast(i32, self.objs.items.len - 1));
bt.bodySetDamping(obj.body, default_linear_damping, default_angular_damping);
bt.bodySetActivationState(obj.body, bt.c.CBT_DISABLE_DEACTIVATION);
bt.worldAddBody(self.world, obj.body);
}
fn update(self: Scene, ctx: *zp.Context, rd: Renderer) !void {
var width: u32 = undefined;
var height: u32 = undefined;
ctx.graphics.getDrawableSize(ctx.window, &width, &height);
const mouse_state = ctx.getMouseState();
// calc projection matrix
const projection = Mat4.perspective(
camera.zoom,
@intToFloat(f32, width) / @intToFloat(f32, height),
0.1,
1000,
);
// update physical world
_ = bt.worldStepSimulation(self.world, ctx.delta_tick, 1, 1.0 / 60.0);
// get selected object
var result: bt.RayCastResult = undefined;
var ray_target = camera.getRayTestTarget(
width,
height,
@intCast(u32, mouse_state.x),
@intCast(u32, mouse_state.y),
);
var hit_idx: u32 = undefined;
var hit = bt.rayTestClosest(
self.world,
&camera.position.toArray(),
&ray_target.toArray(),
bt.c.CBT_COLLISION_FILTER_DEFAULT,
bt.c.CBT_COLLISION_FILTER_ALL,
bt.c.CBT_RAYCAST_FLAG_USE_USE_GJK_CONVEX_TEST,
&result,
);
if (hit and result.body != null) {
hit_idx = @intCast(u32, bt.bodyGetUserIndex(result.body, 0));
if (hit_idx == 0) hit = false;
}
// render objects
for (self.objs.items) |obj, idx| {
// draw debug lines
var linear_velocity: bt.Vector3 = undefined;
var angular_velocity: bt.Vector3 = undefined;
var position: bt.Vector3 = undefined;
bt.bodyGetLinearVelocity(obj.body, &linear_velocity);
bt.bodyGetAngularVelocity(obj.body, &angular_velocity);
bt.bodyGetCenterOfMassPosition(obj.body, &position);
const p1_linear = Vec3.fromSlice(&position).add(Vec3.fromSlice(&linear_velocity));
const p1_angular = Vec3.fromSlice(&position).add(Vec3.fromSlice(&angular_velocity));
const color_linear = bt.Vector3{ 1.0, 0.0, 1.0 };
const color_angular = bt.Vector3{ 0.0, 1.0, 1.0 };
bt.worldDebugDrawLine1(self.world, &position, &p1_linear.toArray(), &color_linear);
bt.worldDebugDrawLine1(self.world, &position, &p1_angular.toArray(), &color_angular);
// draw object, highlight selected object
var tr: bt.Transform = undefined;
bt.bodyGetGraphicsWorldTransform(obj.body, &tr);
if (hit and hit_idx == idx) {
ctx.graphics.setStencilOption(.{
.test_func = .always,
.test_ref = 1,
.action_dppass = .replace,
});
}
try obj.model.render(
rd,
bt.convertTransformToMat4(tr).mult(Mat4.fromScale(obj.size)),
projection,
camera,
null,
null,
);
if (hit and hit_idx == idx) {
ctx.graphics.setStencilOption(.{
.test_func = .not_equal,
.test_ref = 1,
});
simple_renderer.renderer().begin();
defer rd.begin();
try obj.model.render(
simple_renderer.renderer(),
bt.convertTransformToMat4(tr)
.mult(Mat4.fromScale(Vec3.set(1.05)))
.mult(Mat4.fromScale(obj.size)),
projection,
camera,
color_material,
null,
);
}
}
// render physical debug
bt.worldDebugDraw(self.world);
var old_line_width = ctx.graphics.line_width;
ctx.graphics.setLineWidth(5);
self.physics_debug.render(projection);
ctx.graphics.setLineWidth(old_line_width);
}
};
const PhysicsDebug = struct {
positions: std.ArrayList(Vec3),
colors: std.ArrayList(Vec4),
vertex_array: VertexArray,
simple_renderer: SimpleRenderer,
fn init(allocator: std.mem.Allocator) PhysicsDebug {
var debug = PhysicsDebug{
.positions = std.ArrayList(Vec3).init(allocator),
.colors = std.ArrayList(Vec4).init(allocator),
.vertex_array = VertexArray.init(2),
.simple_renderer = SimpleRenderer.init(),
};
debug.simple_renderer.mix_factor = 1.0;
debug.vertex_array.bufferDataAlloc(0, 100 * @sizeOf(Vec3), .array_buffer, .stream_draw);
debug.vertex_array.bufferDataAlloc(1, 100 * @sizeOf(Vec4), .array_buffer, .stream_draw);
debug.vertex_array.use();
defer debug.vertex_array.disuse();
debug.vertex_array.setAttribute(
0,
SimpleRenderer.ATTRIB_LOCATION_POS,
3,
f32,
false,
0,
0,
);
debug.vertex_array.setAttribute(
1,
SimpleRenderer.ATTRIB_LOCATION_COLOR,
4,
f32,
false,
0,
0,
);
return debug;
}
fn deinit(debug: *PhysicsDebug) void {
debug.positions.deinit();
debug.colors.deinit();
debug.vertex_array.deinit();
debug.simple_renderer.deinit();
debug.* = undefined;
}
fn render(debug: *PhysicsDebug, projection: Mat4) void {
if (debug.positions.items.len == 0) return;
debug.vertex_array.bufferSubData(0, 0, Vec3, debug.positions.items, .array_buffer);
debug.vertex_array.bufferSubData(1, 0, Vec4, debug.colors.items, .array_buffer);
var rd = debug.simple_renderer.renderer();
rd.begin();
defer rd.end();
rd.render(
debug.vertex_array,
false,
.lines,
0,
@intCast(u32, debug.positions.items.len),
Mat4.identity(),
projection,
camera,
null,
null,
) catch unreachable;
debug.positions.resize(0) catch unreachable;
debug.colors.resize(0) catch unreachable;
}
fn drawLine1(debug: *PhysicsDebug, p0: Vec3, p1: Vec3, color: Vec4) void {
debug.positions.appendSlice(&.{ p0, p1 }) catch unreachable;
debug.colors.appendSlice(&.{ color, color }) catch unreachable;
}
fn drawLine2(debug: *PhysicsDebug, p0: Vec3, p1: Vec3, color0: Vec4, color1: Vec4) void {
debug.positions.appendSlice(&.{ p0, p1 }) catch unreachable;
debug.colors.appendSlice(&.{ color0, color1 }) catch unreachable;
}
fn drawContactPoint(debug: *PhysicsDebug, point: Vec3, normal: Vec3, distance: f32, color: Vec4) void {
debug.drawLine1(point, point.add(normal.scale(distance)), color);
debug.drawLine1(point, point.add(normal.scale(0.01)), Vec4.zero());
}
fn drawLine1Callback(p0: [*c]const f32, p1: [*c]const f32, color: [*c]const f32, user: ?*anyopaque) callconv(.C) void {
const ptr = @ptrCast(*PhysicsDebug, @alignCast(@alignOf(PhysicsDebug), user.?));
ptr.drawLine1(
Vec3.new(p0[0], p0[1], p0[2]),
Vec3.new(p1[0], p1[1], p1[2]),
Vec4.new(color[0], color[1], color[2], 1.0),
);
}
fn drawLine2Callback(
p0: [*c]const f32,
p1: [*c]const f32,
color0: [*c]const f32,
color1: [*c]const f32,
user: ?*anyopaque,
) callconv(.C) void {
const ptr = @ptrCast(*PhysicsDebug, @alignCast(@alignOf(PhysicsDebug), user.?));
ptr.drawLine2(
Vec3.new(p0[0], p0[1], p0[2]),
Vec3.new(p1[0], p1[1], p1[2]),
Vec4.new(color0[0], color0[1], color0[2], 1),
Vec4.new(color1[0], color1[1], color1[2], 1),
);
}
fn drawContactPointCallback(
point: [*c]const f32,
normal: [*c]const f32,
distance: f32,
_: c_int,
color: [*c]const f32,
user: ?*anyopaque,
) callconv(.C) void {
const ptr = @ptrCast(*PhysicsDebug, @alignCast(@alignOf(PhysicsDebug), user.?));
ptr.drawContactPoint(
Vec3.new(point[0], point[1], point[2]),
Vec3.new(normal[0], normal[1], normal[2]),
distance,
Vec4.new(color[0], color[1], color[2], 1.0),
);
}
fn reportErrorWarningCallback(str: [*c]const u8, _: ?*anyopaque) callconv(.C) void {
std.log.info("{s}", .{str});
}
};
fn quit(ctx: *zp.Context) void {
_ = ctx;
std.log.info("game quit", .{});
}
pub fn main() anyerror!void {
try zp.run(.{
.initFn = init,
.loopFn = loop,
.quitFn = quit,
.enable_maximized = true,
});
} | examples/bullet_test.zig |
const std = @import("std");
const fs = std.fs;
const json = std.json;
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
pub const BlockPropertyVariantsType = union(enum) {
Enum,
Bool,
Number: struct {
start: usize,
max: usize,
},
pub fn from(self: @This(), name: []const u8, writer: anytype) !void {
try writer.writeAll("@intCast(GlobalPaletteInt, ");
switch (self) {
.Enum => try writer.print("@enumToInt(b.{s})", .{name}),
.Bool => try writer.print("if(b.{s}) @as(GlobalPaletteInt, 0) else @as(GlobalPaletteInt, 1)", .{name}),
.Number => |n| try writer.print("b.{s} - {}", .{ name, n.start }),
}
try writer.writeAll(");\n");
}
};
pub const BlockProperty = struct {
name: []const u8,
variants: [][]const u8,
variants_type: BlockPropertyVariantsType,
pub fn init(name: []const u8, variants: [][]const u8) BlockProperty {
var prop = BlockProperty{
.name = name,
.variants = variants,
.variants_type = undefined,
};
if (variants.len == 2 and mem.eql(u8, "true", variants[0]) and mem.eql(u8, "false", variants[1])) {
prop.variants_type = .Bool;
} else {
var max_num: ?isize = null;
var start_num: ?isize = null;
blk: {
var last: ?isize = null;
for (variants) |variant| {
const val = std.fmt.parseInt(isize, variant, 10) catch |err| {
assert(err == error.InvalidCharacter);
break :blk;
};
if (last == null) {
start_num = val;
last = val;
} else {
if (val == last.? + 1) {
last = val;
} else {
break :blk;
}
}
}
max_num = last;
break :blk;
}
if (max_num) |num| {
prop.variants_type = .{ .Number = .{
.max = @intCast(usize, num),
.start = @intCast(usize, start_num.?),
} };
} else {
for (variants) |variant| {
assert(std.ascii.isAlpha(variant[0]));
}
prop.variants_type = .Enum;
}
}
return prop;
}
pub fn deinit(self: BlockProperty, alloc: Allocator) void {
alloc.free(self.variants);
}
};
pub const HuhError = error{Huh};
pub const Block = struct {
name: []const u8,
properties: ?[]BlockProperty = null,
default_state: usize,
begin_id: usize,
pub fn init(alloc: Allocator, token_stream: *json.TokenStream) !?Block {
var block: Block = undefined;
var token = (try token_stream.next()).?;
if (token == .ObjectEnd) return null;
block.name = token.String.slice(token_stream.slice, token_stream.i - 1);
assert((try token_stream.next()).? == .ObjectBegin);
var id: ?usize = null;
var default_ind: ?usize = null;
while (true) {
token = (try token_stream.next()).?;
if (token == .ObjectEnd) break;
const field_name = token.String.slice(token_stream.slice, token_stream.i - 1);
if (mem.eql(u8, field_name, "states")) {
assert((try token_stream.next()).? == .ArrayBegin);
while (true) {
token = (try token_stream.next()).?;
if (token == .ArrayEnd) break;
assert(token == .ObjectBegin);
var state_id: ?usize = null;
var is_default: ?bool = null;
while (true) {
token = (try token_stream.next()).?;
if (token == .ObjectEnd) break;
const state_field_name = token.String.slice(token_stream.slice, token_stream.i - 1);
token = (try token_stream.next()).?;
if (mem.eql(u8, state_field_name, "properties")) {
assert(token == .ObjectBegin);
token = (try token_stream.next()).?;
while (token != .ObjectEnd) : (token = (try token_stream.next()).?) {
assert(token == .String);
assert((try token_stream.next()).? == .String);
}
} else if (mem.eql(u8, state_field_name, "id")) {
assert(token.Number.is_integer);
const state_id_slice = token.Number.slice(token_stream.slice, token_stream.i - 1);
state_id = try std.fmt.parseInt(usize, state_id_slice, 10);
} else if (mem.eql(u8, state_field_name, "default")) {
assert(token == .True or token == .False);
is_default = token == .True;
} else return error.Huh;
}
if (id == null or (state_id != null and id.? > state_id.?)) {
id = state_id;
}
if (is_default != null and is_default.?) {
default_ind = state_id;
}
}
} else if (mem.eql(u8, field_name, "properties")) {
assert((try token_stream.next()).? == .ObjectBegin);
var props = std.ArrayList(BlockProperty).init(alloc);
defer props.deinit();
while (true) {
token = (try token_stream.next()).?;
if (token == .ObjectEnd) break;
const prop_name = token.String.slice(token_stream.slice, token_stream.i - 1);
assert((try token_stream.next()).? == .ArrayBegin);
var variants = std.ArrayList([]const u8).init(alloc);
defer variants.deinit();
while (true) {
token = (try token_stream.next()).?;
if (token == .ArrayEnd) break;
const variant_name = token.String.slice(token_stream.slice, token_stream.i - 1);
try variants.append(variant_name);
}
const owned = variants.toOwnedSlice();
errdefer alloc.free(owned);
try props.append(BlockProperty.init(prop_name, owned));
}
assert(block.properties == null);
block.properties = props.toOwnedSlice();
}
}
block.begin_id = id.?;
block.default_state = default_ind.? - id.?;
return block;
}
pub fn deinit(self: Block, alloc: Allocator) void {
if (self.properties) |props| {
for (props) |prop| {
prop.deinit(alloc);
}
alloc.free(props);
}
}
pub fn bareName(self: Block) []const u8 {
const comp = "minecraft:";
assert(mem.eql(u8, self.name[0..comp.len], comp));
return self.name[comp.len..];
}
pub fn propPermCount(self: Block) usize {
if (self.properties) |props| {
var count: usize = 1;
for (props) |prop| {
count *= prop.variants.len;
}
return count;
} else return 1;
}
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{
.stack_trace_frames = 16,
}){};
defer _ = gpa.deinit();
var alloc = gpa.allocator();
var file = try fs.cwd().openFile("data/reports/blocks.json", .{});
var file_data = try file.readToEndAlloc(alloc, 3999999999);
defer alloc.free(file_data);
var token_stream = json.TokenStream.init(file_data);
var blocks = std.ArrayList(Block).init(alloc);
defer {
for (blocks.items) |block| {
block.deinit(alloc);
}
blocks.deinit();
}
assert((try token_stream.next()).? == .ObjectBegin);
//var count: usize = 0;
while (try Block.init(alloc, &token_stream)) |block| {
try blocks.append(block);
//count += 1;
//if (count > 62) break;
}
//for (blocks.items) |block| {
// std.log.info("{any}", .{block});
//}
var data = std.ArrayList(u8).init(alloc);
defer data.deinit();
var buffered_writer = std.io.bufferedWriter(data.writer());
var writer = buffered_writer.writer();
var largest_id: usize = 0;
for (blocks.items) |block| {
const high_block_id = block.begin_id + block.propPermCount() - 1;
if (high_block_id > largest_id) largest_id = high_block_id;
}
try writer.print(
\\const std = @import("std");
\\pub const BlockFromIdError = error{{
\\ InvalidId,
\\}};
\\pub const GlobalPaletteMaxId = {};
\\pub const GlobalPaletteInt = std.math.IntFittingRange(0, GlobalPaletteMaxId);
\\pub const BlockMaterial = enum {{
\\
, .{largest_id});
for (blocks.items) |block| {
try writer.print(" {s},\n", .{block.bareName()});
}
try writer.writeAll(
\\
\\
\\ pub fn fromGlobalPaletteId(id: GlobalPaletteInt) !BlockMaterial {
\\ switch(id) {
\\
);
for (blocks.items) |block| {
const perm_count = block.propPermCount();
if (perm_count != 1) {
try writer.print(" " ** 3 ++ "{}...{} => return BlockMaterial.{s},\n", .{ block.begin_id, block.begin_id + perm_count - 1, block.bareName() });
} else {
try writer.print(" " ** 3 ++ "{} => return BlockMaterial.{s},\n", .{ block.begin_id, block.bareName() });
}
}
try writer.writeAll(
\\ else => return BlockFromIdError.InvalidId,
\\ }
\\ }
\\
\\ pub fn toDefaultGlobalPaletteId(material: BlockMaterial) GlobalPaletteInt {
\\ switch(material) {
\\
);
for (blocks.items) |block| {
try writer.print(" " ** 3 ++ "BlockMaterial.{s} => return {},\n", .{ block.bareName(), block.begin_id + block.default_state });
}
try writer.writeAll(
\\ }
\\ }
\\ pub fn toFirstGlobalPaletteId(material: BlockMaterial) GlobalPaletteInt {
\\ switch(material) {
\\
);
for (blocks.items) |block| {
try writer.print(" " ** 3 ++ "BlockMaterial.{s} => return {},\n", .{ block.bareName(), block.begin_id });
}
try writer.writeAll(
\\ }
\\ }
\\
);
try writer.writeAll(
\\};
\\
\\pub const Block = union(BlockMaterial) {
\\
);
for (blocks.items) |block| {
if (block.properties) |props| {
try writer.print(" {s}: struct {{\n", .{block.bareName()});
for (props) |prop| {
switch (prop.variants_type) {
.Enum => {
try writer.print(" " ** 2 ++ "{s}: enum {{\n", .{prop.name});
for (prop.variants) |variant| {
//try writer.print(" " ** 3 ++ "@\"{s}\",\n", .{variant});
try writer.print(" " ** 3 ++ "{s},\n", .{variant});
}
try writer.writeAll(" " ** 2 ++ "},\n");
},
.Bool => {
try writer.print(" " ** 2 ++ "{s}: bool,\n", .{prop.name});
},
.Number => |n| {
const bit_count = std.math.log2_int_ceil(usize, n.max + n.start + 1);
try writer.print(" " ** 2 ++ "{s}: u{},\n", .{ prop.name, bit_count });
},
}
}
try writer.writeAll(" },\n");
} else {
try writer.print(" {s}: void,\n", .{block.bareName()});
}
}
try writer.writeAll(
\\ const fields = @typeInfo(Block).Union.fields;
\\
\\ pub fn fromGlobalPaletteId(id: GlobalPaletteInt) !Block {
\\ switch(id) {
\\
);
for (blocks.items) |block, b_ind| {
const perm_count = block.propPermCount();
if (perm_count != 1) {
try writer.print(" " ** 3 ++ "{}...{} => {{\n", .{ block.begin_id, block.begin_id + perm_count - 1 });
try writer.print(" " ** 4 ++ "var variant_id = id - {};\n", .{block.begin_id});
try writer.print(" " ** 4 ++ "const property_fields = @typeInfo(fields[{}].field_type).Struct.fields;\n", .{b_ind});
const props = block.properties.?;
var i: usize = props.len;
while (i != 0) : (i -= 1) {
const prop = props[i - 1];
try writer.print(" " ** 4 ++ "const @\"{s}\" = ", .{prop.name});
switch (prop.variants_type) {
.Enum => {
try writer.print("@intToEnum(property_fields[{}].field_type, variant_id % {});\n", .{ i - 1, prop.variants.len });
},
.Bool => {
try writer.print("(variant_id % 2) == 0;\n", .{});
},
.Number => |n| {
try writer.print("@intCast(u{}, (variant_id % {}) + {});\n", .{ std.math.log2_int_ceil(usize, n.start + n.max + 1), prop.variants.len, n.start });
},
}
if (i != 1) {
try writer.print(" " ** 4 ++ "variant_id /= {};\n", .{prop.variants.len});
}
}
try writer.writeAll(" " ** 4 ++ "_ = property_fields;\n");
try writer.print(" " ** 4 ++ "return Block{{ .{s} = .{{\n", .{block.bareName()});
for (block.properties.?) |prop| {
try writer.print(" " ** 5 ++ ".{s} = @\"{s}\",\n", .{ prop.name, prop.name });
}
try writer.writeAll(" " ** 4 ++ "} };\n" ++ (" " ** 3) ++ "},\n");
} else {
try writer.print(" " ** 3 ++ "{} => return Block.{s},\n", .{ block.begin_id, block.bareName() });
}
}
try writer.writeAll(
\\ else => return BlockFromIdError.InvalidId,
\\ }
\\ }
\\
\\ pub fn toGlobalPaletteId(self: Block) GlobalPaletteInt {
\\ switch(self) {
\\
);
for (blocks.items) |block| {
if (block.properties != null and block.properties.?.len > 0) {
const props = block.properties.?;
try writer.print(" " ** 3 ++ "Block.{s} => |b| {{\n", .{block.bareName()});
//try writer.print(" " ** 4 ++ "const first_id: GlobalPaletteInt = {};\n", .{block.begin_id});
try writer.writeAll(" " ** 4 ++ "var local_id: GlobalPaletteInt = ");
try props[0].variants_type.from(props[0].name, writer);
var i: usize = props.len;
while (i != 0) : (i -= 1) {
const prop = props[i - 1];
if (i != 1) {
try writer.print(" " ** 4 ++ "local_id = (local_id * {}) + ", .{prop.variants.len});
try prop.variants_type.from(prop.name, writer);
}
}
try writer.print(" " ** 4 ++ "return {} + local_id;\n", .{block.begin_id});
try writer.writeAll(" " ** 3 ++ "},\n");
} else {
try writer.print(" " ** 3 ++ "Block.{s} => return {},\n", .{ block.bareName(), block.begin_id });
}
}
try writer.writeAll(
\\ }
\\ }
\\
\\};
\\
\\
);
try writer.writeAll(
\\const testing = std.testing;
\\test "from global palette id" {
\\ {
\\ const block = try Block.fromGlobalPaletteId(160);
\\ try testing.expect(block.oak_leaves.distance == 7);
\\ try testing.expect(block.oak_leaves.persistent == true);
\\ }
\\ {
\\ const block = try Block.fromGlobalPaletteId(20);
\\ try testing.expect(block == .dark_oak_planks);
\\ }
\\ {
\\ const block = try Block.fromGlobalPaletteId(21);
\\ try testing.expect(block.oak_sapling.stage == 0);
\\ }
\\}
\\
\\test "to global palette id" {
\\ {
\\ const id = Block.toGlobalPaletteId(try Block.fromGlobalPaletteId(160));
\\ try testing.expect(id == 160);
\\ }
\\}
);
try buffered_writer.flush();
std.debug.print("{s}\n", .{data.items});
const target_filename = "src/gen/blocks.zig";
//const target_filename = "blocks.zig";
var target_file = try fs.cwd().createFile(target_filename, .{});
defer target_file.close();
try target_file.writeAll(data.items);
} | scripts/generate_blocks.zig |
const c = @cImport({
@cInclude("cfl_widget.h");
@cInclude("cfl.h");
});
const enums = @import("enums.zig");
const group = @import("group.zig");
const image = @import("image.zig");
pub const WidgetPtr = ?*c.Fl_Widget;
fn shim(w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void {
_ = w;
c.Fl_awake_msg(data);
}
pub const Widget = struct {
inner: ?*c.Fl_Widget,
pub fn new(coord_x: i32, coord_y: i32, width: i32, height: i32, title: [*c]const u8) Widget {
const ptr = c.Fl_Widget_new(coord_x, coord_y, width, height, title);
if (ptr == null) unreachable;
return Widget{
.inner = ptr,
};
}
pub fn raw(self: *Widget) ?*c.Fl_Widget {
return self.inner;
}
pub fn fromRaw(ptr: ?*c.Fl_Widget) Widget {
return Widget{
.inner = ptr,
};
}
pub fn fromWidgetPtr(wid: WidgetPtr) Widget {
return Widget{
.inner = @ptrCast(?*c.Fl_Widget, wid),
};
}
pub fn fromVoidPtr(ptr: ?*c_void) Widget {
return Widget{
.inner = @ptrCast(?*c.Fl_Widget, ptr),
};
}
pub fn toVoidPtr(self: *Widget) ?*c_void {
return @ptrCast(?*c_void, self.inner);
}
pub fn delete(self: *Widget) void {
c.Fl_Widget_delete(self.inner);
self.inner = null;
}
pub fn setCallback(self: *Widget, cb: fn (w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void, data: ?*c_void) void {
c.Fl_Widget_set_callback(self.inner, cb, data);
}
pub fn emit(self: *Widget, comptime T: type, msg: T) void {
self.setCallback(shim, @intToPtr(?*c_void, @bitCast(usize, msg)));
}
pub fn setColor(self: *Widget, col: u32) void {
c.Fl_Widget_set_color(self.inner, col);
}
pub fn show(self: *Widget) void {
c.Fl_Widget_show(self.inner);
}
pub fn hide(self: *Widget) void {
c.Fl_Widget_hide(self.inner);
}
pub fn setLabel(self: *Widget, str: [*c]const u8) void {
c.Fl_Widget_set_label(self.inner, str);
}
pub fn resize(self: *Widget, coord_x: i32, coord_y: i32, width: i32, height: i32) void {
c.Fl_Widget_resize(self.inner, coord_x, coord_y, width, height);
}
pub fn redraw(self: *Widget) void {
c.Fl_Widget_redraw(self.inner);
}
pub fn x(self: *const Widget) i32 {
return c.Fl_Widget_x(self.inner);
}
pub fn y(self: *const Widget) i32 {
return c.Fl_Widget_y(self.inner);
}
pub fn w(self: *const Widget) i32 {
return c.Fl_Widget_w(self.inner);
}
pub fn h(self: *const Widget) i32 {
return c.Fl_Widget_h(self.inner);
}
pub fn label(self: *const Widget) [*c]const u8 {
return c.Fl_Widget_label(self.inner);
}
pub fn getType(self: *Widget, comptime T: type) T {
return @intToEnum(c.Fl_Widget_set_type(self.inner), T);
}
pub fn setType(self: *Widget, comptime T: type, t: T) void {
c.Fl_Widget_set_type(self.inner, @enumToInt(t));
}
pub fn color(self: *const Widget) enums.Color {
return @intToEnum(enums.Color, c.Fl_Widget_color(self.inner));
}
pub fn labelColor(self: *const Widget) enums.Color {
return @intToEnum(enums.Color, c.Fl_Widget_label_color(self.inner));
}
pub fn setLabelColor(self: *Widget, col: enums.Color) void {
c.Fl_Widget_set_label_color(self.inner, @enumToInt(col));
}
pub fn labelFont(self: *const Widget) enums.Font {
return @intToEnum(c.Fl_Widget_label_font(self.inner), enums.Font);
}
pub fn setLabelFont(self: *Widget, font: enums.Font) void {
c.Fl_Widget_set_label_font(self.inner, @enumToInt(font));
}
pub fn labelSize(self: *const Widget) i32 {
c.Fl_Widget_label_size(self.inner);
}
pub fn setLabelSize(self: *Widget, sz: i32) void {
c.Fl_Widget_set_label_size(self.inner, sz);
}
pub fn setAlign(self: *Widget, a: i32) void {
c.Fl_Widget_set_align(self.inner, a);
}
pub fn setTrigger(self: *Widget, callbackTrigger: i32) void {
c.Fl_Widget_set_trigger(self.inner, callbackTrigger);
}
pub fn setBox(self: *Widget, boxtype: enums.BoxType) void {
c.Fl_Widget_set_box(self.inner, @enumToInt(boxtype));
}
pub fn setImage(self: *Widget, img: ?image.Image) void {
if (img) |i| {
c.Fl_Widget_set_image(self.inner, i.inner);
} else {
c.Fl_Widget_set_image(self.inner, null);
}
}
pub fn setDeimage(self: *Widget, img: ?image.Image) void {
if (img) |i| {
c.Fl_Widget_set_deimage(self.inner, i.inner);
} else {
c.Fl_Widget_set_deimage(self.inner, null);
}
}
pub fn trigger(self: *const Widget) i32 {
return c.Fl_Widget_trigger(self.inner);
}
pub fn parent(self: *const Widget) group.Group {
return group.Group{ .inner = c.Fl_Widget_parent(self.inner) };
}
pub fn selectionColor(self: *Widget) enums.Color {
return c.Fl_Widget_selection_color(self.inner);
}
pub fn setSelectionColor(self: *Widget, col: enums.Color) void {
c.Fl_Widget_set_selection_color(self.inner, col);
}
pub fn doCallback(self: *Widget) void {
c.Fl_Widget_do_callback(self.inner);
}
pub fn clearVisiblFocus(self: *Widget) void {
c.Fl_Widget_clear_visible_focus(self.inner);
}
pub fn visibleFocus(self: *Widget, v: bool) void {
c.Fl_Widget_visible_focus(self.inner, v);
}
pub fn getAlign(self: *const Widget) i32 {
return c.Fl_Widget_align(self.inner);
}
pub fn setLabelLype(self: *Widget, typ: enums.LabelType) void {
c.Fl_Widget_set_label_type(self.inner, @enumToInt(typ));
}
pub fn tooltip(self: *const Widget) [*c]const u8 {
return c.Fl_Widget_tooltip(self.inner);
}
pub fn setTooltip(self: *Widget, txt: [*c]const u8) void {
c.Fl_Widget_set_tooltip(
self.inner,
txt,
);
}
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/widget.zig |
const fmath = @import("index.zig");
pub fn cos(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(cos32, x),
f64 => @inlineCall(cos64, x),
else => @compileError("cos not implemented for " ++ @typeName(T)),
}
}
// sin polynomial coefficients
const S0 = 1.58962301576546568060E-10;
const S1 = -2.50507477628578072866E-8;
const S2 = 2.75573136213857245213E-6;
const S3 = -1.98412698295895385996E-4;
const S4 = 8.33333333332211858878E-3;
const S5 = -1.66666666666666307295E-1;
// cos polynomial coeffiecients
const C0 = -1.13585365213876817300E-11;
const C1 = 2.08757008419747316778E-9;
const C2 = -2.75573141792967388112E-7;
const C3 = 2.48015872888517045348E-5;
const C4 = -1.38888888888730564116E-3;
const C5 = 4.16666666666665929218E-2;
// NOTE: This is taken from the go stdlib. The musl implementation is much more complex.
//
// This may have slight differences on some edge cases and may need to replaced if so.
fn cos32(x_: f32) -> f32 {
const pi4a = 7.85398125648498535156e-1;
const pi4b = 3.77489470793079817668E-8;
const pi4c = 2.69515142907905952645E-15;
const m4pi = 1.273239544735162542821171882678754627704620361328125;
var x = x_;
if (fmath.isNan(x) or fmath.isInf(x)) {
return fmath.nan(f32);
}
var sign = false;
if (x < 0) {
x = -x;
}
var y = fmath.floor(x * m4pi);
var j = i64(y);
if (j & 1 == 1) {
j += 1;
y += 1;
}
j &= 7;
if (j > 3) {
j -= 4;
sign = !sign;
}
if (j > 1) {
sign = !sign;
}
const z = ((x - y * pi4a) - y * pi4b) - y * pi4c;
const w = z * z;
const r = {
if (j == 1 or j == 2) {
z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0)))))
} else {
1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0)))))
}
};
if (sign) {
-r
} else {
r
}
}
fn cos64(x_: f64) -> f64 {
const pi4a = 7.85398125648498535156e-1;
const pi4b = 3.77489470793079817668E-8;
const pi4c = 2.69515142907905952645E-15;
const m4pi = 1.273239544735162542821171882678754627704620361328125;
var x = x_;
if (fmath.isNan(x) or fmath.isInf(x)) {
return fmath.nan(f64);
}
var sign = false;
if (x < 0) {
x = -x;
}
var y = fmath.floor(x * m4pi);
var j = i64(y);
if (j & 1 == 1) {
j += 1;
y += 1;
}
j &= 7;
if (j > 3) {
j -= 4;
sign = !sign;
}
if (j > 1) {
sign = !sign;
}
const z = ((x - y * pi4a) - y * pi4b) - y * pi4c;
const w = z * z;
const r = {
if (j == 1 or j == 2) {
z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0)))))
} else {
1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0)))))
}
};
if (sign) {
-r
} else {
r
}
}
test "cos" {
fmath.assert(cos(f32(0.0)) == cos32(0.0));
fmath.assert(cos(f64(0.0)) == cos64(0.0));
}
test "cos32" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, cos32(0.0), 1.0, epsilon));
fmath.assert(fmath.approxEq(f32, cos32(0.2), 0.980067, epsilon));
fmath.assert(fmath.approxEq(f32, cos32(0.8923), 0.627623, epsilon));
fmath.assert(fmath.approxEq(f32, cos32(1.5), 0.070737, epsilon));
fmath.assert(fmath.approxEq(f32, cos32(37.45), 0.969132, epsilon));
fmath.assert(fmath.approxEq(f32, cos32(89.123), 0.400798, epsilon));
}
test "cos64" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, cos64(0.0), 1.0, epsilon));
fmath.assert(fmath.approxEq(f64, cos64(0.2), 0.980067, epsilon));
fmath.assert(fmath.approxEq(f64, cos64(0.8923), 0.627623, epsilon));
fmath.assert(fmath.approxEq(f64, cos64(1.5), 0.070737, epsilon));
fmath.assert(fmath.approxEq(f64, cos64(37.45), 0.969132, epsilon));
fmath.assert(fmath.approxEq(f64, cos64(89.123), 0.40080, epsilon));
} | src/cos.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const panic = std.debug.panic;
const info = std.log.info;
const crypto = std.crypto;
const sha256 = crypto.hash.sha2.Sha256;
const fmt = std.fmt;
const assert = std.debug.assert;
pub const Lmdb = @import("lmdb.zig").Lmdb;
pub const BLOCK_DB = "blocks";
pub fn reportOOM() noreturn {
panic("allocator is Out Of Memory", .{});
}
//TARGET_ZERO_BITS must be a multiple of 4 and it determines the number of zeros in the target hash which determines difficult
//The higer TARGET_ZERO_BITS the harder or time consuming it is to find a hash
//NOTE: when we define a target adjusting algorithm this won't be a global constant anymore
//it specifies the target hash which is used to check hashes which are valid
//a block is only accepted by the network if its hash meets the network's difficulty target
//the number of leading zeros in the target serves as a good approximation of the current difficult
const TARGET_ZERO_BITS = 8;
//CHANGE_AFTER_BETTER_SERIALIZATION: storing []const u8 as [N]u8 for easy serialization till pointer swizilling and unswizilling is learnt
pub const Block = struct {
//when the block is created
timestamp: i64,
//difficulty bits is the block header storing the difficulty at which the block was mined
difficulty_bits: u7 = TARGET_ZERO_BITS, //u7 limit value from 0 to 127
//Thus miners must discover by brute force the "nonce" that, when included in the block, results in an acceptable hash.
nonce: usize = 0,
//the actual valuable information contained in the block .eg Transactions which is usually a differenct data
//structure
data: [32]u8,
//stores the hash of the previous block
previous_hash: [32]u8,
//hash of the current block
hash: [32]u8 = undefined,
pub fn genesisBlock() Block {
var genesis_block = Block{
.timestamp = std.time.timestamp(),
.data = "Genesis Block is the First Block".*,
.previous_hash = undefined,
};
var hash: [32]u8 = undefined;
const nonce = genesis_block.POW(&hash);
genesis_block.hash = hash;
genesis_block.nonce = nonce;
return genesis_block;
}
///Validate POW
//refactor and deduplicate
pub fn validate(block: Block) bool {
const target_hash = getTargetHash(block.difficulty_bits);
var time_buf: [16]u8 = undefined;
var bits_buf: [3]u8 = undefined;
var nonce_buf: [16]u8 = undefined;
const timestamp = fmt.bufPrintIntToSlice(&time_buf, block.timestamp, 16, .lower, .{});
const difficulty_bits = fmt.bufPrintIntToSlice(&bits_buf, block.difficulty_bits, 16, .lower, .{});
const nonce = fmt.bufPrintIntToSlice(&nonce_buf, block.nonce, 16, .lower, .{});
//timestamp ,previous_hash and hash form the BlockHeader
var block_headers_buf: [128]u8 = undefined;
const block_headers = fmt.bufPrint(&block_headers_buf, "{[previous_hash]s}{[data]s}{[timestamp]s}{[difficulty_bits]s}{[nonce]s}", .{
.previous_hash = block.previous_hash[0..],
.data = block.data[0..],
.timestamp = timestamp,
.difficulty_bits = difficulty_bits,
.nonce = nonce,
}) catch unreachable;
var hash: [32]u8 = undefined;
sha256.hash(block_headers, &hash, .{});
const hash_int = @bitCast(u256, hash);
const is_block_valid = if (hash_int < target_hash) true else false;
return is_block_valid;
}
fn getTargetHash(target_dificulty: u7) u256 {
//hast to be compaired with for valid hashes to prove work done
const @"256bit": u9 = 256; //256 bit is 32 byte which is the size of a sha256 hash
const @"1": u256 = 1; //a 32 byte integer with the value of 1
const target_hash = @"1" << @intCast(u8, @"256bit" - target_dificulty);
return target_hash;
}
///Proof of Work mining algorithm
///The usize returned is the nonce with which a valid block was mined
pub fn POW(block: Block, hash: *[32]u8) usize {
const target_hash = getTargetHash(block.difficulty_bits);
var nonce: usize = 0;
//TODO : optimize the sizes of these buffers base on the base and use exactly the amount that is needed
var time_buf: [16]u8 = undefined;
var bits_buf: [3]u8 = undefined;
var nonce_buf: [16]u8 = undefined;
const timestamp = fmt.bufPrintIntToSlice(&time_buf, block.timestamp, 16, .lower, .{});
const difficulty_bits = fmt.bufPrintIntToSlice(&bits_buf, block.difficulty_bits, 16, .lower, .{});
// const size = comptime (block.previous_hash.len + block.data.len + time_buf.len + bits_buf.len + nonce_buf.len);
var block_headers_buf: [128]u8 = undefined;
while (nonce < std.math.maxInt(usize)) {
const nonce_val = fmt.bufPrintIntToSlice(&nonce_buf, nonce, 16, .lower, .{});
//timestamp ,previous_hash and hash form the BlockHeader
const block_headers = fmt.bufPrint(&block_headers_buf, "{[previous_hash]s}{[data]s}{[timestamp]s}{[difficulty_bits]s}{[nonce]s}", .{
.previous_hash = block.previous_hash,
.data = block.data,
.timestamp = timestamp,
.difficulty_bits = difficulty_bits,
.nonce = nonce_val,
}) catch unreachable;
sha256.hash(block_headers, hash, .{});
const hash_int = mem.bytesToValue(u256, hash[0..]);
if (hash_int < target_hash) {
return nonce;
} else {
nonce += 1;
}
}
unreachable;
}
pub fn newBlock(data: [32]u8, previous_hash: [32]u8) Block {
var new_block = Block{
.timestamp = std.time.timestamp(),
.data = data,
.previous_hash = previous_hash,
};
var hash: [32]u8 = undefined;
const nonce = new_block.POW(&hash);
new_block.hash = hash;
new_block.nonce = nonce;
return new_block;
}
};
test "Block Test" {
var genesis_block = Block.genesisBlock();
const new_block = Block.newBlock("testing Block".* ++ [_]u8{'0'} ** 19, genesis_block.hash);
try testing.expectEqualSlices(u8, genesis_block.hash[0..], new_block.previous_hash[0..]);
var hash: [32]u8 = undefined;
const nonce = new_block.POW(&hash);
try testing.expectEqual(nonce, new_block.nonce);
try testing.expectEqualStrings(hash[0..], new_block.hash[0..]);
}
//READ: https://en.bitcoin.it/wiki/Block_hashing_algorithm https://en.bitcoin.it/wiki/Proof_of_work https://en.bitcoin.it/wiki/Hashcash
const LAST = "last";
pub const BlockChain = struct {
last_hash: [32]u8,
db: Lmdb,
///create a new BlockChain
pub fn newChain(db: Lmdb, genesis_block: Block) BlockChain {
const txn = db.startTxn(.rw, BLOCK_DB);
defer txn.commitTxns();
if (txn.getAs([32]u8, LAST)) |last_block_hash| {
return .{ .last_hash = last_block_hash, .db = db };
} else |err| switch (err) {
error.KeyNotFound => {
txn.put(genesis_block.hash[0..], genesis_block) catch unreachable;
txn.put(LAST, genesis_block.hash) catch unreachable;
return .{ .last_hash = genesis_block.hash, .db = db };
},
else => unreachable,
}
}
///add a new Block to the BlockChain
pub fn addBlock(bc: *BlockChain, block_data: [32]u8) void {
info("Mining the block containing - '{s}'", .{block_data[0..]});
const new_block = Block.newBlock(block_data, bc.last_hash);
info("'{s}' - has a valid hash of '{}'", .{ block_data[0..], fmt.fmtSliceHexUpper(new_block.hash[0..]) });
info("nonce is {}", .{new_block.nonce});
info("POW: {}\n\n", .{new_block.validate()});
assert(new_block.validate() == true);
const txn = bc.db.startTxn(.rw, BLOCK_DB);
defer txn.commitTxns();
txn.put(new_block.hash[0..], new_block) catch unreachable;
txn.update(LAST, new_block.hash) catch unreachable;
bc.last_hash = new_block.hash;
}
};
pub const ChainIterator = struct {
db: *const Lmdb,
//Notice that an iterator initially points at the tip of a blockchain, thus blocks will be obtained from top to bottom, from newest to oldest.
current_hash: [32]u8,
pub fn iterator(bc: BlockChain) ChainIterator {
return .{ .db = &bc.db, .current_hash = bc.last_hash };
}
///the returned usize is the address of the Block in memory
///the ptr can be obtained with @intToPtr
pub fn next(self: *ChainIterator) ?Block {
const txn = self.db.startTxn(.ro, BLOCK_DB);
defer txn.doneReading();
if (txn.getAs(Block, self.current_hash[0..])) |current_block| {
self.current_hash = current_block.previous_hash;
return current_block;
// return @ptrToInt(current_block);
} else |_| {
return null;
}
}
}; | src/blockchain.zig |
const std = @import("std");
// these might be in the standard library already but I don't know how to describe what they do well enough to ask.
// nice to have things
fn interpolateInt(a: anytype, b: @TypeOf(a), progress: f64) @TypeOf(a) {
const OO = @TypeOf(a);
const floa = @intToFloat(f64, a);
const flob = @intToFloat(f64, b);
return @floatToInt(OO, floa + (flob - floa) * progress);
}
/// interpolate between two values. clamps to edges.
pub fn interpolate(a: anytype, b: @TypeOf(a), progress: f64) @TypeOf(a) {
const Type = @TypeOf(a);
if (progress < 0) return a;
if (progress > 1) return b;
switch (Type) {
u8 => return interpolateInt(a, b, progress),
i64 => return interpolateInt(a, b, progress),
u64 => return interpolateInt(a, b, progress),
else => {},
}
switch (@typeInfo(Type)) {
.Int => @compileError("Currently only supports u8, i64, u64"),
.Struct => |stru| {
var res: Type = undefined;
inline for (stru.fields) |field| {
@field(res, field.name) = interpolate(@field(a, field.name), @field(b, field.name), progress);
}
return res;
},
else => @compileError("Unsupported"),
}
}
test "interpolation" {
std.testing.expectEqual(interpolate(@as(u64, 25), 27, 0.5), 26);
std.testing.expectEqual(interpolate(@as(u8, 15), 0, 0.2), 12);
const Kind = struct { a: u64 };
std.testing.expectEqual(interpolate(Kind{ .a = 10 }, Kind{ .a = 8 }, 0.5), Kind{ .a = 9 });
std.testing.expectEqual(interpolate(@as(i64, 923), 1200, 0.999999875), 1199);
std.testing.expectEqual(interpolate(@as(i64, 923), 1200, 1.000421875), 1200);
}
fn ensureAllDefined(comptime ValuesType: type, comptime Enum: type) void {
comptime {
const fields = @typeInfo(Enum).Enum.fields;
const fieldCount = fields.len;
const valuesInfo = @typeInfo(ValuesType).Struct;
var ensure: [fieldCount]bool = undefined;
for (fields) |field, i| {
ensure[i] = false;
}
for (valuesInfo.fields) |field| {
// var val: Enum = std.meta.stringToEnum(Enum, field.name);
var val: Enum = @field(Enum, field.name);
const index = @enumToInt(val);
if (ensure[index]) {
@compileError("Duplicate key: " ++ field.name);
}
ensure[index] = true;
}
for (fields) |field, i| {
if (!ensure[i]) {
@compileLog(@intToEnum(Enum, i));
@compileError("Missing key");
}
}
}
}
/// A "struct" with enum keys
pub fn EnumArray(comptime Enum: type, comptime Value: type) type {
const fields = @typeInfo(Enum).Enum.fields;
const fieldCount = fields.len;
return struct {
const V = @This();
data: [fieldCount]Value,
pub fn init(values: anytype) V {
const ValuesType = @TypeOf(values);
const valuesInfo = @typeInfo(ValuesType).Struct;
ensureAllDefined(ValuesType, Enum);
var res: [fieldCount]Value = undefined;
inline for (valuesInfo.fields) |field| {
var val: Enum = @field(Enum, field.name);
const index = @enumToInt(val);
res[index] = @field(values, field.name);
}
return .{ .data = res };
}
pub fn initDefault(value: Value) V {
var res: [fieldCount]Value = undefined;
inline for (fields) |field, i| {
res[i] = value;
}
return .{ .data = res };
}
pub fn get(arr: V, key: Enum) Value {
return arr.data[@enumToInt(key)];
}
pub fn getPtr(arr: *V, key: Enum) *Value {
return &arr.data[@enumToInt(key)];
}
pub fn set(arr: *V, key: Enum, value: Value) Value {
var prev = arr.data[@enumToInt(key)];
arr.data[@enumToInt(key)] = value;
return prev;
}
};
}
// holds all the values of the union at once instead of just one value
pub fn UnionArray(comptime Union: type) type {
const tinfo = @typeInfo(Union);
const Enum = tinfo.Union.tag_type.?;
const Value = Union;
const fields = @typeInfo(Enum).Enum.fields;
const fieldCount = fields.len;
return struct {
const V = @This();
data: [fieldCount]Value,
pub fn initUndefined() V {
var res: [fieldCount]Value = undefined;
return .{ .data = res };
}
pub fn get(arr: V, key: Enum) Value {
return arr.data[@enumToInt(key)];
}
pub fn getPtr(arr: *V, key: Enum) *Value {
return &arr.data[@enumToInt(key)];
}
pub fn set(arr: *V, value: Union) Value {
const enumk = @enumToInt(std.meta.activeTag(value));
defer arr.data[enumk] = value; // does this make the control flow more confusing? it's nice because I don't need a temporary name but it also could definitely be more confusing.
return arr.data[enumk];
}
};
}
// don't think this can be implemented yet because the fn
// can't be varargs
// vararg tuples please zig ty
/// usingnamespace vtable(@This());
pub fn vtable(comptime Vtable: type) type {
const ti = @typeInfo(Vtable).Struct;
return struct {
pub fn from(comptime Container: type) Vtable {
var result: Vtable = undefined;
inline for (ti.fields) |field| {
@field(result, field.name) = struct {
// pub fn a(...args: anytype)
}.a;
}
}
};
}
// comptime only
pub fn UnionCallReturnType(comptime Union: type, comptime method: []const u8) type {
var res: ?type = null;
for (@typeInfo(Union).Union.fields) |field| {
const returnType = @typeInfo(@TypeOf(@field(field.field_type, method))).Fn.return_type orelse
@compileError("Generic functions are not supported");
if (res == null) res = returnType;
if (res) |re| if (re != returnType) @compileError("Return types for fn " ++ method ++ " differ. First found " ++ @typeName(re) ++ ", then found " ++ @typeName(returnType));
}
return res orelse @panic("Union must have at least one field");
}
pub fn DePointer(comptime Type: type) type {
return switch (@typeInfo(Type)) {
.Pointer => |ptr| ptr.child,
else => Type,
};
}
pub fn unionCall(comptime Union: type, comptime method: []const u8, enumValue: @TagType(Union), args: anytype) UnionCallReturnType(Union, method) {
const typeInfo = @typeInfo(Union).Union;
const TagType = std.meta.TagType(Union);
const callOpts: std.builtin.CallOptions = .{};
inline for (typeInfo.fields) |field| {
if (@enumToInt(enumValue) == field.enum_field.?.value) {
return @call(callOpts, @field(field.field_type, method), args);
}
}
@panic("Did not match any enum value");
}
pub fn unionCallReturnsThis(comptime Union: type, comptime method: []const u8, enumValue: @TagType(Union), args: anytype) Union {
const typeInfo = @typeInfo(Union).Union;
const TagType = std.meta.TagType(Union);
const callOpts: std.builtin.CallOptions = .{};
inline for (typeInfo.fields) |field| {
if (@enumToInt(enumValue) == field.enum_field.?.value) {
return @unionInit(Union, field.name, @call(callOpts, @field(field.field_type, method), args));
}
}
@panic("Did not match any enum value");
}
// should it be unionCallThis(unionv, .deinit, .{args})? feels better imo.
pub fn unionCallThis(comptime method: []const u8, unionValue: anytype, args: anytype) UnionCallReturnType(DePointer(@TypeOf(unionValue)), method) {
const isPtr = @typeInfo(@TypeOf(unionValue)) == .Pointer;
const Union = DePointer(@TypeOf(unionValue));
const typeInfo = @typeInfo(Union).Union;
const TagType = std.meta.TagType(Union);
const callOpts: std.builtin.CallOptions = .{};
inline for (typeInfo.fields) |field| {
if (@enumToInt(std.meta.activeTag(if (isPtr) unionValue.* else unionValue)) == field.enum_field.?.value) {
return @call(callOpts, @field(field.field_type, method), .{if (isPtr) &@field(unionValue, field.name) else @field(unionValue, field.name)} ++ args);
}
}
@panic("Did not match any enum value");
}
pub fn FieldType(comptime Container: type, comptime fieldName: []const u8) type {
if (!@hasField(Container, fieldName)) @compileError("Container does not have field " ++ fieldName);
// @TypeOf(@field(@as(Container, undefined), fieldName));
// ^compiler crash
switch (@typeInfo(Container)) {
.Union => |uni| for (uni.fields) |field| {
if (std.mem.eql(u8, field.name, fieldName)) return field.field_type;
},
.Struct => |stru| for (stru.fields) |field| {
if (std.mem.eql(u8, field.name, fieldName)) return field.field_type;
},
else => @compileError("Must be Union | Struct"),
}
unreachable;
}
pub fn Function(comptime Args: anytype, comptime Return: type) type {
return struct {
data: usize,
call: fn (thisArg: usize, args: Args) Return,
};
}
fn FunctionReturn(comptime Type: type) type {
const fnData = @typeInfo(@TypeOf(Type.call)).Fn;
if (fnData.is_generic) @compileLog("Generic functions are not allowed");
const Args = blk: {
var Args: []const type = &[_]type{};
inline for (fnData.args) |arg| {
Args = Args ++ [_]type{arg.arg_type.?};
}
break :blk Args;
};
const ReturnType = fnData.return_type.?;
return struct {
pub const All = Function(Args, ReturnType);
pub const Args = Args;
pub const ReturnType = ReturnType;
};
}
pub fn function(data: anytype) FunctionReturn(@typeInfo(@TypeOf(data)).Pointer.child).All {
const Type = @typeInfo(@TypeOf(data)).Pointer.child;
comptime if (@TypeOf(data) != *const Type) unreachable;
const FnReturn = FunctionReturn(Type);
const CallFn = struct {
pub fn call(thisArg: FnReturn.All, args: anytype) FnReturn.Return {
return @call(data.call, .{@intToPtr(@TypeOf(data), thisArg.data)} ++ args);
}
}.call;
@compileLog(FnReturn.All);
return .{
.data = @ptrToInt(data),
.call = &CallFn,
};
}
test "function" {
// oops Unreachable at /deps/zig/src/analyze.cpp:5922 in type_requires_comptime. This is a bug in the Zig compiler.
// zig compiler bug + something is wrong in my code
if (false) {
const Position = struct { x: i64, y: i64 };
const testFn: Function(.{ f64, Position }, f32) = function(&struct {
number: f64,
pub fn call(data: *@This(), someValue: f64, argOne: Position) f32 {
return @floatCast(f32, data.number + someValue + @intToFloat(f64, argOne.x) + @intToFloat(f64, argOne.y));
}
}{ .number = 35.6 });
// function call is only supported within the lifetime of the data pointer
// should it have an optional deinit method?
std.testing.expectEqual(testFn.call(.{ 25, .{ .x = 56, .y = 25 } }), 25.6);
std.testing.expectEqual(testFn.call(.{ 666, .{ .x = 12, .y = 4 } }), 25.6);
// unfortunately there is no varargs or way to comptime set custom fn args so this has to be a .{array}
}
}
/// the stdlib comptime hashmap is only created once and makes a "perfect hash"
/// so this works I guess.
///
/// comptime "hash"map. all accesses and sets are ~~O(1)~~ O(n)
pub fn ComptimeHashMap(comptime Key: type, comptime Value: type) type {
const Item = struct { key: Key, value: Value };
return struct {
const HM = @This();
items: []const Item,
pub fn init() HM {
return HM{
.items = &[_]Item{},
};
}
fn findIndex(comptime hm: HM, comptime key: Key) ?u64 {
for (hm.items) |itm, i| {
if (Key == []const u8) {
if (std.mem.eql(u8, itm.key, key))
return i;
} else if (itm.key == key)
return i;
}
return null;
}
pub fn get(comptime hm: HM, comptime key: Key) ?Value {
if (hm.findIndex(key)) |indx| return hm.items[indx].value;
return null;
}
pub fn set(comptime hm: *HM, comptime key: Key, comptime value: Value) ?Value {
if (hm.findIndex(key)) |prevIndex| {
const prev = hm.items[prevIndex].value;
// hm.items[prevIndex].value = value; // did you really think it would be that easy?
var newItems: [hm.items.len]Item = undefined;
for (hm.items) |prevItem, i| {
if (i == prevIndex) {
newItems[i] = Item{ .key = prevItem.key, .value = value };
} else {
newItems[i] = prevItem;
}
}
hm.items = &newItems;
return prev;
}
hm.items = hm.items ++ &[_]Item{Item{ .key = key, .value = value }};
return null;
}
};
}
// this can also be made using memoization and blk:
pub const TypeIDMap = struct {
latestID: u64,
hm: ComptimeHashMap(type, u64),
infoStrings: []const []const u8,
pub fn init() TypeIDMap {
return .{
.latestID = 0,
.hm = ComptimeHashMap(type, u64).init(),
.infoStrings = &[_][]const u8{"empty"},
};
}
pub fn get(comptime tidm: *TypeIDMap, comptime Type: type) u64 {
if (tidm.hm.get(Type)) |index| return index;
tidm.latestID += 1;
if (tidm.hm.set(Type, tidm.latestID)) |_| @compileError("never");
tidm.infoStrings = tidm.infoStrings ++ &[_][]const u8{@typeName(Type)};
// @compileLog("ID", tidm.latestID, "=", Type);
return tidm.latestID;
}
};
/// a pointer to arbitrary data. panics if attempted to be read as the wrong type.
pub const AnyPtr = comptime blk: {
var typeIDMap = TypeIDMap.init();
break :blk struct {
pointer: usize,
typeID: u64,
pub fn fromPtr(value: anytype) AnyPtr {
const ti = @typeInfo(@TypeOf(value));
if (ti != .Pointer) @compileError("must be *ptr");
if (ti.Pointer.size != .One) @compileError("must be ptr to one item");
if (ti.Pointer.is_const) @compileError("const not yet allowed");
const thisTypeID = comptime typeID(ti.Pointer.child);
return .{ .pointer = @ptrToInt(value), .typeID = thisTypeID };
}
pub fn readAs(any: AnyPtr, comptime RV: type) *RV {
const thisTypeID = comptime typeIDMap.get(RV);
if (any.typeID != thisTypeID)
std.debug.panic(
"\x1b[31mError!\x1b(B\x1b[m Item is of type {}, but was read as type {}.\n",
.{ typeIDMap.infoStrings[any.typeID], typeIDMap.infoStrings[thisTypeID] },
);
return @intToPtr(*RV, any.pointer);
}
pub fn typeID(comptime Type: type) u64 {
return comptime typeIDMap.get(Type);
}
fn typeName(any: AnyPtr) []const u8 {
return typeIDMap.infoStrings[any.typeID];
}
};
};
pub fn expectEqualStrings(str1: []const u8, str2: []const u8) void {
if (std.mem.eql(u8, str1, str2)) return;
std.debug.panic("\nExpected `{}`, got `{}`\n", .{ str1, str2 });
}
pub fn fixedCoerce(comptime Container: type, asl: anytype) Container {
if (@typeInfo(@TypeOf(asl)) != .Struct) {
return @as(Container, asl);
}
if (@TypeOf(asl) == Container) {
return asl;
}
var result: Container = undefined;
switch (@typeInfo(Container)) {
.Struct => |ti| {
comptime var setFields: [ti.fields.len]bool = [_]bool{false} ** ti.fields.len;
inline for (@typeInfo(@TypeOf(asl)).Struct.fields) |rmfld| {
comptime const i = for (ti.fields) |fld, i| {
if (std.mem.eql(u8, fld.name, rmfld.name)) break i;
} else @compileError("Field " ++ rmfld.name ++ " is not in " ++ @typeName(Container));
comptime setFields[i] = true;
const field = ti.fields[i];
@field(result, rmfld.name) = fixedCoerce(field.field_type, @field(asl, field.name));
}
comptime for (setFields) |bol, i| if (!bol) {
comptime const field = ti.fields[i];
if (field.default_value) |defv|
@field(result, field.name) = defv
else
@compileError("Did not set field " ++ field.name);
};
},
.Enum => @compileError("enum niy"),
else => @compileError("cannot coerce anon struct literal to " ++ @typeName(Container)),
}
return result;
}
test "fixedCoerce" {
const SomeValue = struct { b: u32 = 4, a: u16 };
const OtherValue = struct { a: u16, b: u32 = 4 };
std.testing.expectEqual(SomeValue{ .a = 5, .b = 4 }, fixedCoerce(SomeValue, .{ .a = 5 }));
std.testing.expectEqual(SomeValue{ .a = 5, .b = 10 }, fixedCoerce(SomeValue, .{ .a = 5, .b = 10 }));
std.testing.expectEqual(@as(u32, 25), fixedCoerce(u32, 25));
std.testing.expectEqual(SomeValue{ .a = 5 }, SomeValue{ .a = 5 });
// should fail:
// unfortunately, since there is no way of detecting anon literals vs real structs, this may not be possible
// *: maybe check if @TypeOf(&@as(@TypeOf(asl)).someField) is const? idk. that is a bug though
// that may be fixed in the future.
std.testing.expectEqual(SomeValue{ .a = 5 }, fixedCoerce(SomeValue, OtherValue{ .a = 5 }));
const InnerStruct = struct { b: u16 };
const DoubleStruct = struct { a: InnerStruct };
std.testing.expectEqual(DoubleStruct{ .a = InnerStruct{ .b = 10 } }, fixedCoerce(DoubleStruct, .{ .a = .{ .b = 10 } }));
}
test "anyptr" {
var number: u32 = 25;
var longlonglong: u64 = 25;
var anyPtr = AnyPtr.fromPtr(&number);
std.testing.expectEqual(AnyPtr.typeID(u32), AnyPtr.typeID(u32));
var anyPtrLonglong = AnyPtr.fromPtr(&longlonglong);
std.testing.expectEqual(AnyPtr.typeID(u64), AnyPtr.typeID(u64));
// type names only work after they have been used at least once,
// so typeName will probably be broken most of the time.
expectEqualStrings("u32", anyPtr.typeName());
expectEqualStrings("u64", anyPtrLonglong.typeName());
}
test "enum array" {
const Enum = enum { One, Two, Three };
const EnumArr = EnumArray(Enum, bool);
var val = EnumArr.initDefault(false);
std.testing.expect(!val.get(.One));
std.testing.expect(!val.get(.Two));
std.testing.expect(!val.get(.Three));
_ = val.set(.Two, true);
_ = val.set(.Three, true);
std.testing.expect(!val.get(.One));
std.testing.expect(val.get(.Two));
std.testing.expect(val.get(.Three));
}
test "enum array initialization" {
const Enum = enum { One, Two, Three };
const EnumArr = EnumArray(Enum, bool);
var val = EnumArr.init(.{ .One = true, .Two = false, .Three = true });
std.testing.expect(val.get(.One));
std.testing.expect(!val.get(.Two));
std.testing.expect(val.get(.Three));
}
test "union array" {
const Union = union(enum) { One: bool, Two: []const u8, Three: i64 };
const UnionArr = UnionArray(Union);
// var val = UnionArr.init(.{ .One = true, .Two = "hi!", .Three = 27 });
var val = UnionArr.initUndefined();
_ = val.set(.{ .One = true });
_ = val.set(.{ .Two = "hi!" });
_ = val.set(.{ .Three = 27 });
std.testing.expect(val.get(.One).One);
std.testing.expect(std.mem.eql(u8, val.get(.Two).Two, "hi!"));
std.testing.expect(val.get(.Three).Three == 27);
_ = val.set(.{ .Two = "bye!" });
_ = val.set(.{ .Three = 54 });
std.testing.expect(val.get(.One).One);
std.testing.expect(std.mem.eql(u8, val.get(.Two).Two, "bye!"));
std.testing.expect(val.get(.Three).Three == 54);
}
test "unionCall" {
const Union = union(enum) {
TwentyFive: struct {
fn init() i64 {
return 25;
}
}, FiftySix: struct {
fn init() i64 {
return 56;
}
}
};
std.testing.expectEqual(unionCall(Union, "init", .TwentyFive, .{}), 25);
std.testing.expectEqual(unionCall(Union, "init", .FiftySix, .{}), 56);
}
test "unionCallReturnsThis" {
const Union = union(enum) {
number: Number,
boolean: Boolean,
const Number = struct {
num: i64,
pub fn init() Number {
return .{ .num = 91 };
}
};
const Boolean = struct {
boo: bool,
pub fn init() Boolean {
return .{ .boo = true };
}
};
};
std.testing.expectEqual(unionCallReturnsThis(Union, "init", .number, .{}), Union{ .number = .{ .num = 91 } });
std.testing.expectEqual(unionCallReturnsThis(Union, "init", .boolean, .{}), Union{ .boolean = .{ .boo = true } });
}
test "unionCallThis" {
const Union = union(enum) {
TwentyFive: struct {
v: i32,
v2: i64,
fn print(value: @This()) i64 {
return value.v2 + 25;
}
}, FiftySix: struct {
v: i64,
fn print(value: @This()) i64 {
return value.v;
}
}
};
std.testing.expectEqual(unionCallThis("print", Union{ .TwentyFive = .{ .v = 5, .v2 = 10 } }, .{}), 35);
std.testing.expectEqual(unionCallThis("print", Union{ .FiftySix = .{ .v = 28 } }, .{}), 28);
}
test "unionCallThis pointer arg" {
const Union = union(enum) {
TwentyFive: struct {
v: i32,
v2: i64,
fn print(value: *@This()) i64 {
return value.v2 + 25;
}
}, FiftySix: struct {
v: i64,
fn print(value: *@This()) i64 {
return value.v;
}
}
};
var val = Union{ .TwentyFive = .{ .v = 5, .v2 = 10 } };
std.testing.expectEqual(unionCallThis("print", &val, .{}), 35);
val = Union{ .FiftySix = .{ .v = 28 } };
std.testing.expectEqual(unionCallThis("print", &val, .{}), 28);
}
test "FieldType" {
const Struct = struct {
thing: u8,
text: []const u8,
};
comptime std.testing.expectEqual(FieldType(Struct, "thing"), u8);
comptime std.testing.expectEqual(FieldType(Struct, "text"), []const u8);
const Union = union {
a: f64,
b: bool,
};
comptime std.testing.expectEqual(FieldType(Union, "a"), f64);
comptime std.testing.expectEqual(FieldType(Union, "b"), bool);
}
// ====
// iteration experiments
// ====
pub fn IteratorFns(comptime Iter: type) type {
return struct {
// pub fn pipe(other: anytype, args: anytype) anytype {}
};
}
pub const StringSplitIterator = struct {
pub const ItItem = []const u8;
string: []const u8,
split: []const u8,
/// split a string at at. if at == "", split at every byte (not codepoint).
pub fn split(string: []const u8, at: []const u8) StringSplitIterator {
return .{ .string = string, .split = at };
}
pub fn next(me: *StringSplitIterator) ?[]const u8 {
var res = me.string;
while (!std.mem.startsWith(u8, me.string, me.split)) {
if (me.string.len == 0) {
if (res.len > 0) return res;
return null;
}
me.string = me.string[1..];
}
if (me.string.len == 0) {
if (res.len > 0) return res;
return null;
}
if (me.split.len == 0) {
me.string = me.string[1..]; // split("something", "");
}
defer me.string = me.string[me.split.len..];
return res[0 .. res.len - me.string.len];
}
usingnamespace IteratorFns(@This());
};
/// you own the returned slice
pub fn stringMerge(alloc: *std.mem.Allocator, striter: anytype) ![]const u8 {
var res = std.ArrayList(u8).init(alloc);
errdefer res.deinit();
var itcpy = striter;
while (itcpy.next()) |itm| try res.appendSlice(itm);
return res.toOwnedSlice();
}
fn IteratorJoinType(comptime OITQ: type) type {
return struct {
pub const ItItem = OITQ.ItItem;
const Me = @This();
oiter: OITQ,
join: ItItem,
nextv: ?ItItem = null,
mode: enum { oiter, join } = .oiter,
pub fn next(me: *Me) ?ItItem {
switch (me.mode) {
.oiter => {
me.mode = .join;
if (me.nextv == null) me.nextv = me.oiter.next();
defer me.nextv = me.oiter.next();
return me.nextv;
},
.join => {
if (me.nextv == null) return null;
me.mode = .oiter;
return me.join;
},
}
}
usingnamespace IteratorFns(@This());
};
}
fn suspendIterator(string: []const u8, out: anytype) void {
for (string) |_, i| {
out.emit(string[i .. i + 1]);
}
}
pub fn FunctionIterator(comptime fnction: anytype, comptime Data: type, comptime Out: type) type {
return struct {
const SuspIterCllr = @This();
fn iteratorCaller(string: Data, out: *[]const u8, resfr: *?anyframe) void {
suspend resfr.* = @frame();
fnction(string, struct {
out: *Out,
resfr: *?anyframe,
pub fn emit(me: @This(), val: Out) void {
me.out.* = val;
suspend me.resfr.* = @frame();
me.out.* = undefined; // in case any other suspends happen, eg async io
}
}{ .out = out, .resfr = resfr });
resfr.* = null;
}
frame: ?anyframe,
funcfram: @Frame(iteratorCaller),
out: Out,
text: Data,
pub fn init(text: Data) SuspIterCllr {
return .{ .frame = undefined, .funcfram = undefined, .out = undefined, .text = text };
}
pub fn start(sic: *SuspIterCllr) void {
// this cannot be done in init until @resultLocation is available I think
sic.funcfram = async iteratorCaller(sic.text, &sic.out, &sic.frame);
}
pub fn next(sic: *SuspIterCllr) ?Out {
resume sic.frame orelse return null;
_ = sic.frame orelse return null;
const res = sic.out;
return res;
}
pub const ItItem = Out;
};
}
test "suspend iterator" {
var si = FunctionIterator(suspendIterator, []const u8, []const u8).init("Hello, World!");
si.start();
while (si.next()) |v| {
std.debug.warn("V: `{}`\n", .{v});
}
}
/// Join every other item of an iterator with a value
/// EG iteratorJoin(iteratorArray("One", "Two", "Three"), ", ") == ["One", ", ", "Two", ", ", "Three"]
pub fn iteratorJoin(oiter: anytype, join: @TypeOf(oiter).ItItem) IteratorJoinType(@TypeOf(oiter)) {
return IteratorJoinType(@TypeOf(oiter)){ .oiter = oiter, .join = join };
}
fn testStringSplit(comptime str: []const u8, comptime at: []const u8, comptime expdt: []const []const u8) void {
var split = StringSplitIterator.split(str, at);
var i: usize = 0;
while (split.next()) |section| : (i += 1) {
if (!std.mem.eql(u8, section, expdt[i])) {
std.debug.panic("Expected `{}`, got `{}`\n", .{ expdt[i], section });
}
}
}
test "string split" {
testStringSplit("testing:-:string:-huh:-:interesting:-::-:a", ":-:", &[_][]const u8{ "testing", "string:-huh", "interesting", "", "a" });
testStringSplit("evrychar", "", &[_][]const u8{ "e", "v", "r", "y", "c", "h", "a", "r" });
}
test "string join" {
const alloc = std.testing.allocator;
const res = try stringMerge(alloc, iteratorJoin(StringSplitIterator.split("testing", ""), ","));
defer alloc.free(res);
std.testing.expectEqualStrings("t,e,s,t,i,n,g", res);
}
// goal: integrate this with my printing lib
// so you can print a string iterator
// want to replace some text and print it? print(split("some text", "e").pipe(join, .{"E"}))
// or even better, replace("some text", "e", "E")
// want to print every item of an arraylist with each item <one>, <two>?
// sliceIter(al.items).pipe(map, fn(out, value) void {out("<"); out(value); out(">")} ).pipe(join, ", ")
// remove the items starting with a capital letter?
// .pipe(filter, fn(value) bool (value.len > 0 and !std.text.isCapital(value[0]) ))
// fun with streams
pub fn scale(val: anytype, from: [2]@TypeOf(val), to: [2]@TypeOf(val)) @TypeOf(val) {
std.debug.assert(from[0] < from[1]);
std.debug.assert(to[0] < to[1]);
return (val - from[0]) * (to[1] - to[0]) / (from[1] - from[0]) + to[0];
}
test "math.scale" {
std.testing.expectEqual(scale(@as(f64, 25), [_]f64{ 0, 100 }, [_]f64{ 0, 1 }), 0.25);
std.testing.expectEqual(scale(@as(f64, 25), [_]f64{ 0, 100 }, [_]f64{ 10, 11 }), 10.25);
} | src/helpers.zig |
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 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.
//
// For more information, please refer to <http://unlicense.org/>
const std = @import("std");
const Vector = std.meta.Vector;
pub fn vec(comptime n: comptime_int, x: anytype) std.meta.Vector(n, f32) {
if (comptime std.meta.trait.isNumber(@TypeOf(x))) {
return @splat(n, @as(f32, x));
} else {
const a: [n]f32 = x;
return a;
}
}
test "vec(f32)" {
try std.testing.expectEqual(
Vector(3, f32){ 1, 1, 1 },
vec(3, 1),
);
}
test "vec([3]f32)" {
try std.testing.expectEqual(
Vector(3, f32){ 1, 2, 3 },
vec(3, [3]f32{ 1, 2, 3 }),
);
}
test "vec(tuple)" {
try std.testing.expectEqual(
Vector(3, f32){ 1, 2, 3 },
vec(3, .{ 1, 2, 3 }),
);
}
/// Column-major matrix
pub fn Mat(comptime cols_: comptime_int, comptime rows_: comptime_int) type {
return struct {
m: Vector(cols * rows, f32),
pub const cols: Size = cols_;
pub const rows: Size = rows_;
const ColIndex = std.math.IntFittingRange(0, cols - 1);
const RowIndex = std.math.IntFittingRange(0, rows - 1);
const Size = std.math.IntFittingRange(0, cols_ * rows_);
const Self = @This();
pub fn get(self: Self, x: ColIndex, y: RowIndex) f32 {
return self.m[@as(Size, x) * rows + y];
}
pub fn set(self: *Self, x: ColIndex, y: RowIndex, v: f32) void {
self.m[@as(Size, x) * rows + y] = v;
}
pub fn add(a: Self, b: Self) Self {
return .{ .m = a.m + b.m };
}
pub fn sub(a: Self, b: Self) Self {
return .{ .m = a.m - b.m };
}
pub fn mul(a: Self, b: anytype) Mat(@TypeOf(b).cols, rows) {
if (cols != @TypeOf(b).rows) {
@compileError(std.fmt.comptimePrint("Expected matrix with {} rows, got {s}.", .{ cols, @typeName(@TypeOf(b)) }));
}
const ocols = @TypeOf(b).cols;
const orows = rows;
var r: Mat(ocols, orows) = undefined;
comptime var x = 0;
inline while (x < ocols) : (x += 1) {
comptime var y = 0;
inline while (y < orows) : (y += 1) {
r.set(x, y, @reduce(.Add, a.row(y) * b.col(x)));
}
}
return r;
}
fn col(self: Self, comptime x: ColIndex) Vector(rows, f32) {
const mask = comptime blk: {
var mask: Vector(rows, i32) = undefined;
var i: Size = 0;
while (i < rows) : (i += 1) {
mask[i] = x * rows + i;
}
break :blk mask;
};
// Compiler bug means I can't pass Vector(0, f32){} as b
return @shuffle(f32, self.m, self.m, mask);
}
fn row(self: Self, comptime y: RowIndex) Vector(cols, f32) {
const mask = comptime blk: {
var mask: Vector(cols, i32) = undefined;
var i: Size = 0;
while (i < cols) : (i += 1) {
mask[i] = i * rows + y;
}
break :blk mask;
};
// Compiler bug means I can't pass Vector(0, f32){} as b
return @shuffle(f32, self.m, self.m, mask);
}
pub fn transpose(self: Self) Self {
const mask = comptime blk: {
var mask: Vector(rows * cols, i32) = undefined;
var x = 0;
while (x < cols) : (x += 1) {
var y = 0;
while (y < rows) : (y += 1) {
// We insert the row-major index at the column-major position, transposing the matrix
mask[x * rows + y] = y * cols + x;
}
}
break :blk mask;
};
// Compiler bug means I can't pass Vector(0, f32){} as b
const res = @shuffle(f32, self.m, self.m, mask);
return .{ .m = res };
}
/// Convert to row-major flat array
/// To get a column-major flat array, cast the `m` field
pub fn toArray(m: Self) [cols * rows]f32 {
return m.transpose().m;
}
/// Convert to column-major nested array
pub fn colMajor(m: Self) [cols][rows]f32 {
const a: [rows * cols]f32 = m.m;
return @bitCast([cols][rows]f32, a);
}
/// Convert to row-major nested array
pub fn rowMajor(m: Self) [rows][cols]f32 {
return m.transpose().colMajor();
}
};
}
/// Construct a (column-major) matrix from a row-major array
pub fn mat(comptime rows: comptime_int, comptime cols: comptime_int, m: [cols * rows]f32) Mat(rows, cols) {
return (Mat(cols, rows){ .m = m }).transpose();
}
test "mat44 + mat44" {
const a = mat(4, 4, .{
1, 2, 3, 4,
2, 3, 4, 5,
3, 4, 5, 6,
4, 5, 6, 7,
});
const b = mat(4, 4, .{
2, 3, 4, 5,
1, 2, 3, 4,
4, 5, 6, 7,
3, 4, 5, 6,
});
try std.testing.expectEqual(mat(4, 4, .{
3, 5, 7, 9,
3, 5, 7, 9,
7, 9, 11, 13,
7, 9, 11, 13,
}), a.add(b));
}
test "mat44 - mat44" {
const a = mat(4, 4, .{
1, 2, 3, 4,
2, 3, 4, 5,
3, 4, 5, 6,
4, 5, 6, 7,
});
const b = mat(4, 4, .{
2, 3, 4, 5,
1, 2, 3, 4,
4, 5, 6, 7,
3, 4, 5, 6,
});
try std.testing.expectEqual(mat(4, 4, .{
-1, -1, -1, -1,
1, 1, 1, 1,
-1, -1, -1, -1,
1, 1, 1, 1,
}), a.sub(b));
}
test "mat22 * mat22" {
const a = mat(2, 2, .{
1, 2,
3, 4,
});
const b = mat(2, 2, .{
5, 6,
7, 8,
});
try std.testing.expectEqual(mat(2, 2, .{
19, 22,
43, 50,
}), a.mul(b));
}
test "mat44 * mat44" {
const a = mat(4, 4, .{
1, 2, 3, 4,
2, 3, 4, 5,
3, 4, 5, 6,
4, 5, 6, 7,
});
const b = mat(4, 4, .{
2, 3, 4, 5,
1, 2, 3, 4,
4, 5, 6, 7,
3, 4, 5, 6,
});
try std.testing.expectEqual(mat(4, 4, .{
28, 38, 48, 58,
38, 52, 66, 80,
48, 66, 84, 102,
58, 80, 102, 124,
}), a.mul(b));
}
test "transpose mat44" {
const a = mat(4, 4, .{
1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4,
});
try std.testing.expectEqual(mat(4, 4, .{
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4, 4,
}), a.transpose());
}
/// Construct an identity matrix for the given size
pub fn id(comptime n: comptime_int) Mat(n, n) {
comptime {
var m = std.mem.zeroes(Mat(n, n));
var i = 0;
while (i < n) : (i += 1) {
m.set(i, i, 1);
}
return m;
}
}
/// Construct a 4x4 matrix from a translation vector
pub fn translate(v: [3]f32) Mat(4, 4) {
return mat(4, 4, .{
1, 0, 0, v[0],
0, 1, 0, v[1],
0, 0, 1, v[2],
0, 0, 0, 1,
});
}
/// Construct a 4x4 matrix from a rotation quaternion
pub fn rotate(q: [4]f32) Mat(4, 4) {
// Stored as xyzw since that's the order used by GLSL and glTF
const w = 3;
const x = 0;
const y = 1;
const z = 2;
return mat(4, 4, .{
q[w], -q[z], q[y], -q[x],
q[z], q[w], -q[x], -q[y],
-q[y], q[x], q[w], -q[z],
q[x], q[y], q[z], q[w],
}).mul(mat(4, 4, .{
q[w], -q[z], q[y], q[x],
q[z], q[w], -q[x], q[y],
-q[y], q[x], q[w], q[z],
-q[x], -q[y], -q[z], q[w],
}));
}
/// Construct a 4x4 matrix from a scale vector
pub fn scale(v: [3]f32) Mat(4, 4) {
return mat(4, 4, .{
v[0], 0, 0, 0,
0, v[1], 0, 0,
0, 0, v[2], 0,
0, 0, 0, 1,
});
}
test "id4" {
try std.testing.expectEqual(mat(4, 4, .{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
}), id(4));
} | src/zm.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.