code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const debug = std.debug; const allocator = std.heap.page_allocator; const mem = std.mem; const filePathUtils = @import("FilePathUtils.zig"); const c = @import("../c.zig"); pub const ImageFileError = error{ STBI_LoadFailed, STBI_WriteFailed, }; pub const ImageFile = struct { m_imageData: [*]u8, m_width: u16, m_height: u16, m_channels: u16, m_freed: bool, pub fn FreeImage(self: *ImageFile) void { debug.assert(!self.m_freed); c.stbi_image_free(self.m_imageData); self.m_freed = true; } }; pub fn LoadImage(cwdRelativePath: []const u8) !ImageFile { var width: c_int = undefined; var height: c_int = undefined; var channels: c_int = undefined; const imagePath = try filePathUtils.CwdToAbsolute(allocator, cwdRelativePath); defer allocator.free(imagePath); var image = c.stbi_load(imagePath.ptr, &width, &height, &channels, 0); if (image == null) { // could log stbi_failure_reason... return ImageFileError.STBI_LoadFailed; } else { return ImageFile{ .m_imageData = image, .m_width = @intCast(u16, width), .m_height = @intCast(u16, height), .m_channels = @intCast(u16, channels), .m_freed = false, }; } } //TODO including stb_image_write.h causing compile errors //pub fn SaveImageAs(image: *ImageFile, cwdRelativePath: []const u8) !void { // const ext = try filePathUtils.GetExtension(cwdRelativePath); // var stbiReturnCode: c_int = 0; // if (mem.eql(u8, ext, ".png")) { // stbiReturnCode = c.stbi_write_png( // cwdRelativePath.ptr, // image.m_width, // image.m_height, // image.m_channels, // image.m_imageData, // image.m_width * image.m_channels, // ); // } // //TODO if we can ever get rid of STB_ONLY_PNG... // //else if (mem.eql(u8, ext, ".jpg")) { // // stbiReturnCode = c.stbi_write_jpg( // // cwdRelativePath.ptr, // // image.m_width, // // image.m_height, // // image.m_channels, // // image.m_imageData, // // 100, // // ); // //} else if (mem.eql(u8, ext, ".tga")) { // // stbiReturnCode = c.stbi_write_tga( // // cwdRelativePath.ptr, // // image.m_width, // // image.m_height, // // image.m_channels, // // image.m_imageData, // // ); // //} else if (mem.eql(u8, ext, ".bmp")) { // // stbiReturnCode = c.stbi_write_bmp( // // cwdRelativePath.ptr, // // image.m_width, // // image.m_height, // // image.m_channels, // // image.m_imageData, // // ); // //} // else { // return filePathUtils.FilePathError.InvalidExtension; // } // // // Handle stbi failure code // if (stbiReturnCode == 0) { // return ImageFileError.STBI_WriteFailed; // } //}
src/coreutil/ImageFileUtil.zig
pub const FONT_ICON_FILE_NAME_FAR = "fa-regular-400.ttf"; pub const FONT_ICON_FILE_NAME_FAS = "fa-solid-900.ttf"; pub const ICON_MIN_FA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xe005, .hexadecimal); pub const ICON_MAX_FA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xf8ff, .hexadecimal); pub const ICON_FA_AD = "\xef\x99\x81"; pub const ICON_FA_ADDRESS_BOOK = "\xef\x8a\xb9"; pub const ICON_FA_ADDRESS_CARD = "\xef\x8a\xbb"; pub const ICON_FA_ADJUST = "\xef\x81\x82"; pub const ICON_FA_AIR_FRESHENER = "\xef\x97\x90"; pub const ICON_FA_ALIGN_CENTER = "\xef\x80\xb7"; pub const ICON_FA_ALIGN_JUSTIFY = "\xef\x80\xb9"; pub const ICON_FA_ALIGN_LEFT = "\xef\x80\xb6"; pub const ICON_FA_ALIGN_RIGHT = "\xef\x80\xb8"; pub const ICON_FA_ALLERGIES = "\xef\x91\xa1"; pub const ICON_FA_AMBULANCE = "\xef\x83\xb9"; pub const ICON_FA_AMERICAN_SIGN_LANGUAGE_INTERPRETING = "\xef\x8a\xa3"; pub const ICON_FA_ANCHOR = "\xef\x84\xbd"; pub const ICON_FA_ANGLE_DOUBLE_DOWN = "\xef\x84\x83"; pub const ICON_FA_ANGLE_DOUBLE_LEFT = "\xef\x84\x80"; pub const ICON_FA_ANGLE_DOUBLE_RIGHT = "\xef\x84\x81"; pub const ICON_FA_ANGLE_DOUBLE_UP = "\xef\x84\x82"; pub const ICON_FA_ANGLE_DOWN = "\xef\x84\x87"; pub const ICON_FA_ANGLE_LEFT = "\xef\x84\x84"; pub const ICON_FA_ANGLE_RIGHT = "\xef\x84\x85"; pub const ICON_FA_ANGLE_UP = "\xef\x84\x86"; pub const ICON_FA_ANGRY = "\xef\x95\x96"; pub const ICON_FA_ANKH = "\xef\x99\x84"; pub const ICON_FA_APPLE_ALT = "\xef\x97\x91"; pub const ICON_FA_ARCHIVE = "\xef\x86\x87"; pub const ICON_FA_ARCHWAY = "\xef\x95\x97"; pub const ICON_FA_ARROW_ALT_CIRCLE_DOWN = "\xef\x8d\x98"; pub const ICON_FA_ARROW_ALT_CIRCLE_LEFT = "\xef\x8d\x99"; pub const ICON_FA_ARROW_ALT_CIRCLE_RIGHT = "\xef\x8d\x9a"; pub const ICON_FA_ARROW_ALT_CIRCLE_UP = "\xef\x8d\x9b"; pub const ICON_FA_ARROW_CIRCLE_DOWN = "\xef\x82\xab"; pub const ICON_FA_ARROW_CIRCLE_LEFT = "\xef\x82\xa8"; pub const ICON_FA_ARROW_CIRCLE_RIGHT = "\xef\x82\xa9"; pub const ICON_FA_ARROW_CIRCLE_UP = "\xef\x82\xaa"; pub const ICON_FA_ARROW_DOWN = "\xef\x81\xa3"; pub const ICON_FA_ARROW_LEFT = "\xef\x81\xa0"; pub const ICON_FA_ARROW_RIGHT = "\xef\x81\xa1"; pub const ICON_FA_ARROW_UP = "\xef\x81\xa2"; pub const ICON_FA_ARROWS_ALT = "\xef\x82\xb2"; pub const ICON_FA_ARROWS_ALT_H = "\xef\x8c\xb7"; pub const ICON_FA_ARROWS_ALT_V = "\xef\x8c\xb8"; pub const ICON_FA_ASSISTIVE_LISTENING_SYSTEMS = "\xef\x8a\xa2"; pub const ICON_FA_ASTERISK = "\xef\x81\xa9"; pub const ICON_FA_AT = "\xef\x87\xba"; pub const ICON_FA_ATLAS = "\xef\x95\x98"; pub const ICON_FA_ATOM = "\xef\x97\x92"; pub const ICON_FA_AUDIO_DESCRIPTION = "\xef\x8a\x9e"; pub const ICON_FA_AWARD = "\xef\x95\x99"; pub const ICON_FA_BABY = "\xef\x9d\xbc"; pub const ICON_FA_BABY_CARRIAGE = "\xef\x9d\xbd"; pub const ICON_FA_BACKSPACE = "\xef\x95\x9a"; pub const ICON_FA_BACKWARD = "\xef\x81\x8a"; pub const ICON_FA_BACON = "\xef\x9f\xa5"; pub const ICON_FA_BACTERIA = "\xee\x81\x99"; pub const ICON_FA_BACTERIUM = "\xee\x81\x9a"; pub const ICON_FA_BAHAI = "\xef\x99\xa6"; pub const ICON_FA_BALANCE_SCALE = "\xef\x89\x8e"; pub const ICON_FA_BALANCE_SCALE_LEFT = "\xef\x94\x95"; pub const ICON_FA_BALANCE_SCALE_RIGHT = "\xef\x94\x96"; pub const ICON_FA_BAN = "\xef\x81\x9e"; pub const ICON_FA_BAND_AID = "\xef\x91\xa2"; pub const ICON_FA_BARCODE = "\xef\x80\xaa"; pub const ICON_FA_BARS = "\xef\x83\x89"; pub const ICON_FA_BASEBALL_BALL = "\xef\x90\xb3"; pub const ICON_FA_BASKETBALL_BALL = "\xef\x90\xb4"; pub const ICON_FA_BATH = "\xef\x8b\x8d"; pub const ICON_FA_BATTERY_EMPTY = "\xef\x89\x84"; pub const ICON_FA_BATTERY_FULL = "\xef\x89\x80"; pub const ICON_FA_BATTERY_HALF = "\xef\x89\x82"; pub const ICON_FA_BATTERY_QUARTER = "\xef\x89\x83"; pub const ICON_FA_BATTERY_THREE_QUARTERS = "\xef\x89\x81"; pub const ICON_FA_BED = "\xef\x88\xb6"; pub const ICON_FA_BEER = "\xef\x83\xbc"; pub const ICON_FA_BELL = "\xef\x83\xb3"; pub const ICON_FA_BELL_SLASH = "\xef\x87\xb6"; pub const ICON_FA_BEZIER_CURVE = "\xef\x95\x9b"; pub const ICON_FA_BIBLE = "\xef\x99\x87"; pub const ICON_FA_BICYCLE = "\xef\x88\x86"; pub const ICON_FA_BIKING = "\xef\xa1\x8a"; pub const ICON_FA_BINOCULARS = "\xef\x87\xa5"; pub const ICON_FA_BIOHAZARD = "\xef\x9e\x80"; pub const ICON_FA_BIRTHDAY_CAKE = "\xef\x87\xbd"; pub const ICON_FA_BLENDER = "\xef\x94\x97"; pub const ICON_FA_BLENDER_PHONE = "\xef\x9a\xb6"; pub const ICON_FA_BLIND = "\xef\x8a\x9d"; pub const ICON_FA_BLOG = "\xef\x9e\x81"; pub const ICON_FA_BOLD = "\xef\x80\xb2"; pub const ICON_FA_BOLT = "\xef\x83\xa7"; pub const ICON_FA_BOMB = "\xef\x87\xa2"; pub const ICON_FA_BONE = "\xef\x97\x97"; pub const ICON_FA_BONG = "\xef\x95\x9c"; pub const ICON_FA_BOOK = "\xef\x80\xad"; pub const ICON_FA_BOOK_DEAD = "\xef\x9a\xb7"; pub const ICON_FA_BOOK_MEDICAL = "\xef\x9f\xa6"; pub const ICON_FA_BOOK_OPEN = "\xef\x94\x98"; pub const ICON_FA_BOOK_READER = "\xef\x97\x9a"; pub const ICON_FA_BOOKMARK = "\xef\x80\xae"; pub const ICON_FA_BORDER_ALL = "\xef\xa1\x8c"; pub const ICON_FA_BORDER_NONE = "\xef\xa1\x90"; pub const ICON_FA_BORDER_STYLE = "\xef\xa1\x93"; pub const ICON_FA_BOWLING_BALL = "\xef\x90\xb6"; pub const ICON_FA_BOX = "\xef\x91\xa6"; pub const ICON_FA_BOX_OPEN = "\xef\x92\x9e"; pub const ICON_FA_BOX_TISSUE = "\xee\x81\x9b"; pub const ICON_FA_BOXES = "\xef\x91\xa8"; pub const ICON_FA_BRAILLE = "\xef\x8a\xa1"; pub const ICON_FA_BRAIN = "\xef\x97\x9c"; pub const ICON_FA_BREAD_SLICE = "\xef\x9f\xac"; pub const ICON_FA_BRIEFCASE = "\xef\x82\xb1"; pub const ICON_FA_BRIEFCASE_MEDICAL = "\xef\x91\xa9"; pub const ICON_FA_BROADCAST_TOWER = "\xef\x94\x99"; pub const ICON_FA_BROOM = "\xef\x94\x9a"; pub const ICON_FA_BRUSH = "\xef\x95\x9d"; pub const ICON_FA_BUG = "\xef\x86\x88"; pub const ICON_FA_BUILDING = "\xef\x86\xad"; pub const ICON_FA_BULLHORN = "\xef\x82\xa1"; pub const ICON_FA_BULLSEYE = "\xef\x85\x80"; pub const ICON_FA_BURN = "\xef\x91\xaa"; pub const ICON_FA_BUS = "\xef\x88\x87"; pub const ICON_FA_BUS_ALT = "\xef\x95\x9e"; pub const ICON_FA_BUSINESS_TIME = "\xef\x99\x8a"; pub const ICON_FA_CALCULATOR = "\xef\x87\xac"; pub const ICON_FA_CALENDAR = "\xef\x84\xb3"; pub const ICON_FA_CALENDAR_ALT = "\xef\x81\xb3"; pub const ICON_FA_CALENDAR_CHECK = "\xef\x89\xb4"; pub const ICON_FA_CALENDAR_DAY = "\xef\x9e\x83"; pub const ICON_FA_CALENDAR_MINUS = "\xef\x89\xb2"; pub const ICON_FA_CALENDAR_PLUS = "\xef\x89\xb1"; pub const ICON_FA_CALENDAR_TIMES = "\xef\x89\xb3"; pub const ICON_FA_CALENDAR_WEEK = "\xef\x9e\x84"; pub const ICON_FA_CAMERA = "\xef\x80\xb0"; pub const ICON_FA_CAMERA_RETRO = "\xef\x82\x83"; pub const ICON_FA_CAMPGROUND = "\xef\x9a\xbb"; pub const ICON_FA_CANDY_CANE = "\xef\x9e\x86"; pub const ICON_FA_CANNABIS = "\xef\x95\x9f"; pub const ICON_FA_CAPSULES = "\xef\x91\xab"; pub const ICON_FA_CAR = "\xef\x86\xb9"; pub const ICON_FA_CAR_ALT = "\xef\x97\x9e"; pub const ICON_FA_CAR_BATTERY = "\xef\x97\x9f"; pub const ICON_FA_CAR_CRASH = "\xef\x97\xa1"; pub const ICON_FA_CAR_SIDE = "\xef\x97\xa4"; pub const ICON_FA_CARAVAN = "\xef\xa3\xbf"; pub const ICON_FA_CARET_DOWN = "\xef\x83\x97"; pub const ICON_FA_CARET_LEFT = "\xef\x83\x99"; pub const ICON_FA_CARET_RIGHT = "\xef\x83\x9a"; pub const ICON_FA_CARET_SQUARE_DOWN = "\xef\x85\x90"; pub const ICON_FA_CARET_SQUARE_LEFT = "\xef\x86\x91"; pub const ICON_FA_CARET_SQUARE_RIGHT = "\xef\x85\x92"; pub const ICON_FA_CARET_SQUARE_UP = "\xef\x85\x91"; pub const ICON_FA_CARET_UP = "\xef\x83\x98"; pub const ICON_FA_CARROT = "\xef\x9e\x87"; pub const ICON_FA_CART_ARROW_DOWN = "\xef\x88\x98"; pub const ICON_FA_CART_PLUS = "\xef\x88\x97"; pub const ICON_FA_CASH_REGISTER = "\xef\x9e\x88"; pub const ICON_FA_CAT = "\xef\x9a\xbe"; pub const ICON_FA_CERTIFICATE = "\xef\x82\xa3"; pub const ICON_FA_CHAIR = "\xef\x9b\x80"; pub const ICON_FA_CHALKBOARD = "\xef\x94\x9b"; pub const ICON_FA_CHALKBOARD_TEACHER = "\xef\x94\x9c"; pub const ICON_FA_CHARGING_STATION = "\xef\x97\xa7"; pub const ICON_FA_CHART_AREA = "\xef\x87\xbe"; pub const ICON_FA_CHART_BAR = "\xef\x82\x80"; pub const ICON_FA_CHART_LINE = "\xef\x88\x81"; pub const ICON_FA_CHART_PIE = "\xef\x88\x80"; pub const ICON_FA_CHECK = "\xef\x80\x8c"; pub const ICON_FA_CHECK_CIRCLE = "\xef\x81\x98"; pub const ICON_FA_CHECK_DOUBLE = "\xef\x95\xa0"; pub const ICON_FA_CHECK_SQUARE = "\xef\x85\x8a"; pub const ICON_FA_CHEESE = "\xef\x9f\xaf"; pub const ICON_FA_CHESS = "\xef\x90\xb9"; pub const ICON_FA_CHESS_BISHOP = "\xef\x90\xba"; pub const ICON_FA_CHESS_BOARD = "\xef\x90\xbc"; pub const ICON_FA_CHESS_KING = "\xef\x90\xbf"; pub const ICON_FA_CHESS_KNIGHT = "\xef\x91\x81"; pub const ICON_FA_CHESS_PAWN = "\xef\x91\x83"; pub const ICON_FA_CHESS_QUEEN = "\xef\x91\x85"; pub const ICON_FA_CHESS_ROOK = "\xef\x91\x87"; pub const ICON_FA_CHEVRON_CIRCLE_DOWN = "\xef\x84\xba"; pub const ICON_FA_CHEVRON_CIRCLE_LEFT = "\xef\x84\xb7"; pub const ICON_FA_CHEVRON_CIRCLE_RIGHT = "\xef\x84\xb8"; pub const ICON_FA_CHEVRON_CIRCLE_UP = "\xef\x84\xb9"; pub const ICON_FA_CHEVRON_DOWN = "\xef\x81\xb8"; pub const ICON_FA_CHEVRON_LEFT = "\xef\x81\x93"; pub const ICON_FA_CHEVRON_RIGHT = "\xef\x81\x94"; pub const ICON_FA_CHEVRON_UP = "\xef\x81\xb7"; pub const ICON_FA_CHILD = "\xef\x86\xae"; pub const ICON_FA_CHURCH = "\xef\x94\x9d"; pub const ICON_FA_CIRCLE = "\xef\x84\x91"; pub const ICON_FA_CIRCLE_NOTCH = "\xef\x87\x8e"; pub const ICON_FA_CITY = "\xef\x99\x8f"; pub const ICON_FA_CLINIC_MEDICAL = "\xef\x9f\xb2"; pub const ICON_FA_CLIPBOARD = "\xef\x8c\xa8"; pub const ICON_FA_CLIPBOARD_CHECK = "\xef\x91\xac"; pub const ICON_FA_CLIPBOARD_LIST = "\xef\x91\xad"; pub const ICON_FA_CLOCK = "\xef\x80\x97"; pub const ICON_FA_CLONE = "\xef\x89\x8d"; pub const ICON_FA_CLOSED_CAPTIONING = "\xef\x88\x8a"; pub const ICON_FA_CLOUD = "\xef\x83\x82"; pub const ICON_FA_CLOUD_DOWNLOAD_ALT = "\xef\x8e\x81"; pub const ICON_FA_CLOUD_MEATBALL = "\xef\x9c\xbb"; pub const ICON_FA_CLOUD_MOON = "\xef\x9b\x83"; pub const ICON_FA_CLOUD_MOON_RAIN = "\xef\x9c\xbc"; pub const ICON_FA_CLOUD_RAIN = "\xef\x9c\xbd"; pub const ICON_FA_CLOUD_SHOWERS_HEAVY = "\xef\x9d\x80"; pub const ICON_FA_CLOUD_SUN = "\xef\x9b\x84"; pub const ICON_FA_CLOUD_SUN_RAIN = "\xef\x9d\x83"; pub const ICON_FA_CLOUD_UPLOAD_ALT = "\xef\x8e\x82"; pub const ICON_FA_COCKTAIL = "\xef\x95\xa1"; pub const ICON_FA_CODE = "\xef\x84\xa1"; pub const ICON_FA_CODE_BRANCH = "\xef\x84\xa6"; pub const ICON_FA_COFFEE = "\xef\x83\xb4"; pub const ICON_FA_COG = "\xef\x80\x93"; pub const ICON_FA_COGS = "\xef\x82\x85"; pub const ICON_FA_COINS = "\xef\x94\x9e"; pub const ICON_FA_COLUMNS = "\xef\x83\x9b"; pub const ICON_FA_COMMENT = "\xef\x81\xb5"; pub const ICON_FA_COMMENT_ALT = "\xef\x89\xba"; pub const ICON_FA_COMMENT_DOLLAR = "\xef\x99\x91"; pub const ICON_FA_COMMENT_DOTS = "\xef\x92\xad"; pub const ICON_FA_COMMENT_MEDICAL = "\xef\x9f\xb5"; pub const ICON_FA_COMMENT_SLASH = "\xef\x92\xb3"; pub const ICON_FA_COMMENTS = "\xef\x82\x86"; pub const ICON_FA_COMMENTS_DOLLAR = "\xef\x99\x93"; pub const ICON_FA_COMPACT_DISC = "\xef\x94\x9f"; pub const ICON_FA_COMPASS = "\xef\x85\x8e"; pub const ICON_FA_COMPRESS = "\xef\x81\xa6"; pub const ICON_FA_COMPRESS_ALT = "\xef\x90\xa2"; pub const ICON_FA_COMPRESS_ARROWS_ALT = "\xef\x9e\x8c"; pub const ICON_FA_CONCIERGE_BELL = "\xef\x95\xa2"; pub const ICON_FA_COOKIE = "\xef\x95\xa3"; pub const ICON_FA_COOKIE_BITE = "\xef\x95\xa4"; pub const ICON_FA_COPY = "\xef\x83\x85"; pub const ICON_FA_COPYRIGHT = "\xef\x87\xb9"; pub const ICON_FA_COUCH = "\xef\x92\xb8"; pub const ICON_FA_CREDIT_CARD = "\xef\x82\x9d"; pub const ICON_FA_CROP = "\xef\x84\xa5"; pub const ICON_FA_CROP_ALT = "\xef\x95\xa5"; pub const ICON_FA_CROSS = "\xef\x99\x94"; pub const ICON_FA_CROSSHAIRS = "\xef\x81\x9b"; pub const ICON_FA_CROW = "\xef\x94\xa0"; pub const ICON_FA_CROWN = "\xef\x94\xa1"; pub const ICON_FA_CRUTCH = "\xef\x9f\xb7"; pub const ICON_FA_CUBE = "\xef\x86\xb2"; pub const ICON_FA_CUBES = "\xef\x86\xb3"; pub const ICON_FA_CUT = "\xef\x83\x84"; pub const ICON_FA_DATABASE = "\xef\x87\x80"; pub const ICON_FA_DEAF = "\xef\x8a\xa4"; pub const ICON_FA_DEMOCRAT = "\xef\x9d\x87"; pub const ICON_FA_DESKTOP = "\xef\x84\x88"; pub const ICON_FA_DHARMACHAKRA = "\xef\x99\x95"; pub const ICON_FA_DIAGNOSES = "\xef\x91\xb0"; pub const ICON_FA_DICE = "\xef\x94\xa2"; pub const ICON_FA_DICE_D20 = "\xef\x9b\x8f"; pub const ICON_FA_DICE_D6 = "\xef\x9b\x91"; pub const ICON_FA_DICE_FIVE = "\xef\x94\xa3"; pub const ICON_FA_DICE_FOUR = "\xef\x94\xa4"; pub const ICON_FA_DICE_ONE = "\xef\x94\xa5"; pub const ICON_FA_DICE_SIX = "\xef\x94\xa6"; pub const ICON_FA_DICE_THREE = "\xef\x94\xa7"; pub const ICON_FA_DICE_TWO = "\xef\x94\xa8"; pub const ICON_FA_DIGITAL_TACHOGRAPH = "\xef\x95\xa6"; pub const ICON_FA_DIRECTIONS = "\xef\x97\xab"; pub const ICON_FA_DISEASE = "\xef\x9f\xba"; pub const ICON_FA_DIVIDE = "\xef\x94\xa9"; pub const ICON_FA_DIZZY = "\xef\x95\xa7"; pub const ICON_FA_DNA = "\xef\x91\xb1"; pub const ICON_FA_DOG = "\xef\x9b\x93"; pub const ICON_FA_DOLLAR_SIGN = "\xef\x85\x95"; pub const ICON_FA_DOLLY = "\xef\x91\xb2"; pub const ICON_FA_DOLLY_FLATBED = "\xef\x91\xb4"; pub const ICON_FA_DONATE = "\xef\x92\xb9"; pub const ICON_FA_DOOR_CLOSED = "\xef\x94\xaa"; pub const ICON_FA_DOOR_OPEN = "\xef\x94\xab"; pub const ICON_FA_DOT_CIRCLE = "\xef\x86\x92"; pub const ICON_FA_DOVE = "\xef\x92\xba"; pub const ICON_FA_DOWNLOAD = "\xef\x80\x99"; pub const ICON_FA_DRAFTING_COMPASS = "\xef\x95\xa8"; pub const ICON_FA_DRAGON = "\xef\x9b\x95"; pub const ICON_FA_DRAW_POLYGON = "\xef\x97\xae"; pub const ICON_FA_DRUM = "\xef\x95\xa9"; pub const ICON_FA_DRUM_STEELPAN = "\xef\x95\xaa"; pub const ICON_FA_DRUMSTICK_BITE = "\xef\x9b\x97"; pub const ICON_FA_DUMBBELL = "\xef\x91\x8b"; pub const ICON_FA_DUMPSTER = "\xef\x9e\x93"; pub const ICON_FA_DUMPSTER_FIRE = "\xef\x9e\x94"; pub const ICON_FA_DUNGEON = "\xef\x9b\x99"; pub const ICON_FA_EDIT = "\xef\x81\x84"; pub const ICON_FA_EGG = "\xef\x9f\xbb"; pub const ICON_FA_EJECT = "\xef\x81\x92"; pub const ICON_FA_ELLIPSIS_H = "\xef\x85\x81"; pub const ICON_FA_ELLIPSIS_V = "\xef\x85\x82"; pub const ICON_FA_ENVELOPE = "\xef\x83\xa0"; pub const ICON_FA_ENVELOPE_OPEN = "\xef\x8a\xb6"; pub const ICON_FA_ENVELOPE_OPEN_TEXT = "\xef\x99\x98"; pub const ICON_FA_ENVELOPE_SQUARE = "\xef\x86\x99"; pub const ICON_FA_EQUALS = "\xef\x94\xac"; pub const ICON_FA_ERASER = "\xef\x84\xad"; pub const ICON_FA_ETHERNET = "\xef\x9e\x96"; pub const ICON_FA_EURO_SIGN = "\xef\x85\x93"; pub const ICON_FA_EXCHANGE_ALT = "\xef\x8d\xa2"; pub const ICON_FA_EXCLAMATION = "\xef\x84\xaa"; pub const ICON_FA_EXCLAMATION_CIRCLE = "\xef\x81\xaa"; pub const ICON_FA_EXCLAMATION_TRIANGLE = "\xef\x81\xb1"; pub const ICON_FA_EXPAND = "\xef\x81\xa5"; pub const ICON_FA_EXPAND_ALT = "\xef\x90\xa4"; pub const ICON_FA_EXPAND_ARROWS_ALT = "\xef\x8c\x9e"; pub const ICON_FA_EXTERNAL_LINK_ALT = "\xef\x8d\x9d"; pub const ICON_FA_EXTERNAL_LINK_SQUARE_ALT = "\xef\x8d\xa0"; pub const ICON_FA_EYE = "\xef\x81\xae"; pub const ICON_FA_EYE_DROPPER = "\xef\x87\xbb"; pub const ICON_FA_EYE_SLASH = "\xef\x81\xb0"; pub const ICON_FA_FAN = "\xef\xa1\xa3"; pub const ICON_FA_FAST_BACKWARD = "\xef\x81\x89"; pub const ICON_FA_FAST_FORWARD = "\xef\x81\x90"; pub const ICON_FA_FAUCET = "\xee\x80\x85"; pub const ICON_FA_FAX = "\xef\x86\xac"; pub const ICON_FA_FEATHER = "\xef\x94\xad"; pub const ICON_FA_FEATHER_ALT = "\xef\x95\xab"; pub const ICON_FA_FEMALE = "\xef\x86\x82"; pub const ICON_FA_FIGHTER_JET = "\xef\x83\xbb"; pub const ICON_FA_FILE = "\xef\x85\x9b"; pub const ICON_FA_FILE_ALT = "\xef\x85\x9c"; pub const ICON_FA_FILE_ARCHIVE = "\xef\x87\x86"; pub const ICON_FA_FILE_AUDIO = "\xef\x87\x87"; pub const ICON_FA_FILE_CODE = "\xef\x87\x89"; pub const ICON_FA_FILE_CONTRACT = "\xef\x95\xac"; pub const ICON_FA_FILE_CSV = "\xef\x9b\x9d"; pub const ICON_FA_FILE_DOWNLOAD = "\xef\x95\xad"; pub const ICON_FA_FILE_EXCEL = "\xef\x87\x83"; pub const ICON_FA_FILE_EXPORT = "\xef\x95\xae"; pub const ICON_FA_FILE_IMAGE = "\xef\x87\x85"; pub const ICON_FA_FILE_IMPORT = "\xef\x95\xaf"; pub const ICON_FA_FILE_INVOICE = "\xef\x95\xb0"; pub const ICON_FA_FILE_INVOICE_DOLLAR = "\xef\x95\xb1"; pub const ICON_FA_FILE_MEDICAL = "\xef\x91\xb7"; pub const ICON_FA_FILE_MEDICAL_ALT = "\xef\x91\xb8"; pub const ICON_FA_FILE_PDF = "\xef\x87\x81"; pub const ICON_FA_FILE_POWERPOINT = "\xef\x87\x84"; pub const ICON_FA_FILE_PRESCRIPTION = "\xef\x95\xb2"; pub const ICON_FA_FILE_SIGNATURE = "\xef\x95\xb3"; pub const ICON_FA_FILE_UPLOAD = "\xef\x95\xb4"; pub const ICON_FA_FILE_VIDEO = "\xef\x87\x88"; pub const ICON_FA_FILE_WORD = "\xef\x87\x82"; pub const ICON_FA_FILL = "\xef\x95\xb5"; pub const ICON_FA_FILL_DRIP = "\xef\x95\xb6"; pub const ICON_FA_FILM = "\xef\x80\x88"; pub const ICON_FA_FILTER = "\xef\x82\xb0"; pub const ICON_FA_FINGERPRINT = "\xef\x95\xb7"; pub const ICON_FA_FIRE = "\xef\x81\xad"; pub const ICON_FA_FIRE_ALT = "\xef\x9f\xa4"; pub const ICON_FA_FIRE_EXTINGUISHER = "\xef\x84\xb4"; pub const ICON_FA_FIRST_AID = "\xef\x91\xb9"; pub const ICON_FA_FISH = "\xef\x95\xb8"; pub const ICON_FA_FIST_RAISED = "\xef\x9b\x9e"; pub const ICON_FA_FLAG = "\xef\x80\xa4"; pub const ICON_FA_FLAG_CHECKERED = "\xef\x84\x9e"; pub const ICON_FA_FLAG_USA = "\xef\x9d\x8d"; pub const ICON_FA_FLASK = "\xef\x83\x83"; pub const ICON_FA_FLUSHED = "\xef\x95\xb9"; pub const ICON_FA_FOLDER = "\xef\x81\xbb"; pub const ICON_FA_FOLDER_MINUS = "\xef\x99\x9d"; pub const ICON_FA_FOLDER_OPEN = "\xef\x81\xbc"; pub const ICON_FA_FOLDER_PLUS = "\xef\x99\x9e"; pub const ICON_FA_FONT = "\xef\x80\xb1"; pub const ICON_FA_FONT_AWESOME_LOGO_FULL = "\xef\x93\xa6"; pub const ICON_FA_FOOTBALL_BALL = "\xef\x91\x8e"; pub const ICON_FA_FORWARD = "\xef\x81\x8e"; pub const ICON_FA_FROG = "\xef\x94\xae"; pub const ICON_FA_FROWN = "\xef\x84\x99"; pub const ICON_FA_FROWN_OPEN = "\xef\x95\xba"; pub const ICON_FA_FUNNEL_DOLLAR = "\xef\x99\xa2"; pub const ICON_FA_FUTBOL = "\xef\x87\xa3"; pub const ICON_FA_GAMEPAD = "\xef\x84\x9b"; pub const ICON_FA_GAS_PUMP = "\xef\x94\xaf"; pub const ICON_FA_GAVEL = "\xef\x83\xa3"; pub const ICON_FA_GEM = "\xef\x8e\xa5"; pub const ICON_FA_GENDERLESS = "\xef\x88\xad"; pub const ICON_FA_GHOST = "\xef\x9b\xa2"; pub const ICON_FA_GIFT = "\xef\x81\xab"; pub const ICON_FA_GIFTS = "\xef\x9e\x9c"; pub const ICON_FA_GLASS_CHEERS = "\xef\x9e\x9f"; pub const ICON_FA_GLASS_MARTINI = "\xef\x80\x80"; pub const ICON_FA_GLASS_MARTINI_ALT = "\xef\x95\xbb"; pub const ICON_FA_GLASS_WHISKEY = "\xef\x9e\xa0"; pub const ICON_FA_GLASSES = "\xef\x94\xb0"; pub const ICON_FA_GLOBE = "\xef\x82\xac"; pub const ICON_FA_GLOBE_AFRICA = "\xef\x95\xbc"; pub const ICON_FA_GLOBE_AMERICAS = "\xef\x95\xbd"; pub const ICON_FA_GLOBE_ASIA = "\xef\x95\xbe"; pub const ICON_FA_GLOBE_EUROPE = "\xef\x9e\xa2"; pub const ICON_FA_GOLF_BALL = "\xef\x91\x90"; pub const ICON_FA_GOPURAM = "\xef\x99\xa4"; pub const ICON_FA_GRADUATION_CAP = "\xef\x86\x9d"; pub const ICON_FA_GREATER_THAN = "\xef\x94\xb1"; pub const ICON_FA_GREATER_THAN_EQUAL = "\xef\x94\xb2"; pub const ICON_FA_GRIMACE = "\xef\x95\xbf"; pub const ICON_FA_GRIN = "\xef\x96\x80"; pub const ICON_FA_GRIN_ALT = "\xef\x96\x81"; pub const ICON_FA_GRIN_BEAM = "\xef\x96\x82"; pub const ICON_FA_GRIN_BEAM_SWEAT = "\xef\x96\x83"; pub const ICON_FA_GRIN_HEARTS = "\xef\x96\x84"; pub const ICON_FA_GRIN_SQUINT = "\xef\x96\x85"; pub const ICON_FA_GRIN_SQUINT_TEARS = "\xef\x96\x86"; pub const ICON_FA_GRIN_STARS = "\xef\x96\x87"; pub const ICON_FA_GRIN_TEARS = "\xef\x96\x88"; pub const ICON_FA_GRIN_TONGUE = "\xef\x96\x89"; pub const ICON_FA_GRIN_TONGUE_SQUINT = "\xef\x96\x8a"; pub const ICON_FA_GRIN_TONGUE_WINK = "\xef\x96\x8b"; pub const ICON_FA_GRIN_WINK = "\xef\x96\x8c"; pub const ICON_FA_GRIP_HORIZONTAL = "\xef\x96\x8d"; pub const ICON_FA_GRIP_LINES = "\xef\x9e\xa4"; pub const ICON_FA_GRIP_LINES_VERTICAL = "\xef\x9e\xa5"; pub const ICON_FA_GRIP_VERTICAL = "\xef\x96\x8e"; pub const ICON_FA_GUITAR = "\xef\x9e\xa6"; pub const ICON_FA_H_SQUARE = "\xef\x83\xbd"; pub const ICON_FA_HAMBURGER = "\xef\xa0\x85"; pub const ICON_FA_HAMMER = "\xef\x9b\xa3"; pub const ICON_FA_HAMSA = "\xef\x99\xa5"; pub const ICON_FA_HAND_HOLDING = "\xef\x92\xbd"; pub const ICON_FA_HAND_HOLDING_HEART = "\xef\x92\xbe"; pub const ICON_FA_HAND_HOLDING_MEDICAL = "\xee\x81\x9c"; pub const ICON_FA_HAND_HOLDING_USD = "\xef\x93\x80"; pub const ICON_FA_HAND_HOLDING_WATER = "\xef\x93\x81"; pub const ICON_FA_HAND_LIZARD = "\xef\x89\x98"; pub const ICON_FA_HAND_MIDDLE_FINGER = "\xef\xa0\x86"; pub const ICON_FA_HAND_PAPER = "\xef\x89\x96"; pub const ICON_FA_HAND_PEACE = "\xef\x89\x9b"; pub const ICON_FA_HAND_POINT_DOWN = "\xef\x82\xa7"; pub const ICON_FA_HAND_POINT_LEFT = "\xef\x82\xa5"; pub const ICON_FA_HAND_POINT_RIGHT = "\xef\x82\xa4"; pub const ICON_FA_HAND_POINT_UP = "\xef\x82\xa6"; pub const ICON_FA_HAND_POINTER = "\xef\x89\x9a"; pub const ICON_FA_HAND_ROCK = "\xef\x89\x95"; pub const ICON_FA_HAND_SCISSORS = "\xef\x89\x97"; pub const ICON_FA_HAND_SPARKLES = "\xee\x81\x9d"; pub const ICON_FA_HAND_SPOCK = "\xef\x89\x99"; pub const ICON_FA_HANDS = "\xef\x93\x82"; pub const ICON_FA_HANDS_HELPING = "\xef\x93\x84"; pub const ICON_FA_HANDS_WASH = "\xee\x81\x9e"; pub const ICON_FA_HANDSHAKE = "\xef\x8a\xb5"; pub const ICON_FA_HANDSHAKE_ALT_SLASH = "\xee\x81\x9f"; pub const ICON_FA_HANDSHAKE_SLASH = "\xee\x81\xa0"; pub const ICON_FA_HANUKIAH = "\xef\x9b\xa6"; pub const ICON_FA_HARD_HAT = "\xef\xa0\x87"; pub const ICON_FA_HASHTAG = "\xef\x8a\x92"; pub const ICON_FA_HAT_COWBOY = "\xef\xa3\x80"; pub const ICON_FA_HAT_COWBOY_SIDE = "\xef\xa3\x81"; pub const ICON_FA_HAT_WIZARD = "\xef\x9b\xa8"; pub const ICON_FA_HDD = "\xef\x82\xa0"; pub const ICON_FA_HEAD_SIDE_COUGH = "\xee\x81\xa1"; pub const ICON_FA_HEAD_SIDE_COUGH_SLASH = "\xee\x81\xa2"; pub const ICON_FA_HEAD_SIDE_MASK = "\xee\x81\xa3"; pub const ICON_FA_HEAD_SIDE_VIRUS = "\xee\x81\xa4"; pub const ICON_FA_HEADING = "\xef\x87\x9c"; pub const ICON_FA_HEADPHONES = "\xef\x80\xa5"; pub const ICON_FA_HEADPHONES_ALT = "\xef\x96\x8f"; pub const ICON_FA_HEADSET = "\xef\x96\x90"; pub const ICON_FA_HEART = "\xef\x80\x84"; pub const ICON_FA_HEART_BROKEN = "\xef\x9e\xa9"; pub const ICON_FA_HEARTBEAT = "\xef\x88\x9e"; pub const ICON_FA_HELICOPTER = "\xef\x94\xb3"; pub const ICON_FA_HIGHLIGHTER = "\xef\x96\x91"; pub const ICON_FA_HIKING = "\xef\x9b\xac"; pub const ICON_FA_HIPPO = "\xef\x9b\xad"; pub const ICON_FA_HISTORY = "\xef\x87\x9a"; pub const ICON_FA_HOCKEY_PUCK = "\xef\x91\x93"; pub const ICON_FA_HOLLY_BERRY = "\xef\x9e\xaa"; pub const ICON_FA_HOME = "\xef\x80\x95"; pub const ICON_FA_HORSE = "\xef\x9b\xb0"; pub const ICON_FA_HORSE_HEAD = "\xef\x9e\xab"; pub const ICON_FA_HOSPITAL = "\xef\x83\xb8"; pub const ICON_FA_HOSPITAL_ALT = "\xef\x91\xbd"; pub const ICON_FA_HOSPITAL_SYMBOL = "\xef\x91\xbe"; pub const ICON_FA_HOSPITAL_USER = "\xef\xa0\x8d"; pub const ICON_FA_HOT_TUB = "\xef\x96\x93"; pub const ICON_FA_HOTDOG = "\xef\xa0\x8f"; pub const ICON_FA_HOTEL = "\xef\x96\x94"; pub const ICON_FA_HOURGLASS = "\xef\x89\x94"; pub const ICON_FA_HOURGLASS_END = "\xef\x89\x93"; pub const ICON_FA_HOURGLASS_HALF = "\xef\x89\x92"; pub const ICON_FA_HOURGLASS_START = "\xef\x89\x91"; pub const ICON_FA_HOUSE_DAMAGE = "\xef\x9b\xb1"; pub const ICON_FA_HOUSE_USER = "\xee\x81\xa5"; pub const ICON_FA_HRYVNIA = "\xef\x9b\xb2"; pub const ICON_FA_I_CURSOR = "\xef\x89\x86"; pub const ICON_FA_ICE_CREAM = "\xef\xa0\x90"; pub const ICON_FA_ICICLES = "\xef\x9e\xad"; pub const ICON_FA_ICONS = "\xef\xa1\xad"; pub const ICON_FA_ID_BADGE = "\xef\x8b\x81"; pub const ICON_FA_ID_CARD = "\xef\x8b\x82"; pub const ICON_FA_ID_CARD_ALT = "\xef\x91\xbf"; pub const ICON_FA_IGLOO = "\xef\x9e\xae"; pub const ICON_FA_IMAGE = "\xef\x80\xbe"; pub const ICON_FA_IMAGES = "\xef\x8c\x82"; pub const ICON_FA_INBOX = "\xef\x80\x9c"; pub const ICON_FA_INDENT = "\xef\x80\xbc"; pub const ICON_FA_INDUSTRY = "\xef\x89\xb5"; pub const ICON_FA_INFINITY = "\xef\x94\xb4"; pub const ICON_FA_INFO = "\xef\x84\xa9"; pub const ICON_FA_INFO_CIRCLE = "\xef\x81\x9a"; pub const ICON_FA_ITALIC = "\xef\x80\xb3"; pub const ICON_FA_JEDI = "\xef\x99\xa9"; pub const ICON_FA_JOINT = "\xef\x96\x95"; pub const ICON_FA_JOURNAL_WHILLS = "\xef\x99\xaa"; pub const ICON_FA_KAABA = "\xef\x99\xab"; pub const ICON_FA_KEY = "\xef\x82\x84"; pub const ICON_FA_KEYBOARD = "\xef\x84\x9c"; pub const ICON_FA_KHANDA = "\xef\x99\xad"; pub const ICON_FA_KISS = "\xef\x96\x96"; pub const ICON_FA_KISS_BEAM = "\xef\x96\x97"; pub const ICON_FA_KISS_WINK_HEART = "\xef\x96\x98"; pub const ICON_FA_KIWI_BIRD = "\xef\x94\xb5"; pub const ICON_FA_LANDMARK = "\xef\x99\xaf"; pub const ICON_FA_LANGUAGE = "\xef\x86\xab"; pub const ICON_FA_LAPTOP = "\xef\x84\x89"; pub const ICON_FA_LAPTOP_CODE = "\xef\x97\xbc"; pub const ICON_FA_LAPTOP_HOUSE = "\xee\x81\xa6"; pub const ICON_FA_LAPTOP_MEDICAL = "\xef\xa0\x92"; pub const ICON_FA_LAUGH = "\xef\x96\x99"; pub const ICON_FA_LAUGH_BEAM = "\xef\x96\x9a"; pub const ICON_FA_LAUGH_SQUINT = "\xef\x96\x9b"; pub const ICON_FA_LAUGH_WINK = "\xef\x96\x9c"; pub const ICON_FA_LAYER_GROUP = "\xef\x97\xbd"; pub const ICON_FA_LEAF = "\xef\x81\xac"; pub const ICON_FA_LEMON = "\xef\x82\x94"; pub const ICON_FA_LESS_THAN = "\xef\x94\xb6"; pub const ICON_FA_LESS_THAN_EQUAL = "\xef\x94\xb7"; pub const ICON_FA_LEVEL_DOWN_ALT = "\xef\x8e\xbe"; pub const ICON_FA_LEVEL_UP_ALT = "\xef\x8e\xbf"; pub const ICON_FA_LIFE_RING = "\xef\x87\x8d"; pub const ICON_FA_LIGHTBULB = "\xef\x83\xab"; pub const ICON_FA_LINK = "\xef\x83\x81"; pub const ICON_FA_LIRA_SIGN = "\xef\x86\x95"; pub const ICON_FA_LIST = "\xef\x80\xba"; pub const ICON_FA_LIST_ALT = "\xef\x80\xa2"; pub const ICON_FA_LIST_OL = "\xef\x83\x8b"; pub const ICON_FA_LIST_UL = "\xef\x83\x8a"; pub const ICON_FA_LOCATION_ARROW = "\xef\x84\xa4"; pub const ICON_FA_LOCK = "\xef\x80\xa3"; pub const ICON_FA_LOCK_OPEN = "\xef\x8f\x81"; pub const ICON_FA_LONG_ARROW_ALT_DOWN = "\xef\x8c\x89"; pub const ICON_FA_LONG_ARROW_ALT_LEFT = "\xef\x8c\x8a"; pub const ICON_FA_LONG_ARROW_ALT_RIGHT = "\xef\x8c\x8b"; pub const ICON_FA_LONG_ARROW_ALT_UP = "\xef\x8c\x8c"; pub const ICON_FA_LOW_VISION = "\xef\x8a\xa8"; pub const ICON_FA_LUGGAGE_CART = "\xef\x96\x9d"; pub const ICON_FA_LUNGS = "\xef\x98\x84"; pub const ICON_FA_LUNGS_VIRUS = "\xee\x81\xa7"; pub const ICON_FA_MAGIC = "\xef\x83\x90"; pub const ICON_FA_MAGNET = "\xef\x81\xb6"; pub const ICON_FA_MAIL_BULK = "\xef\x99\xb4"; pub const ICON_FA_MALE = "\xef\x86\x83"; pub const ICON_FA_MAP = "\xef\x89\xb9"; pub const ICON_FA_MAP_MARKED = "\xef\x96\x9f"; pub const ICON_FA_MAP_MARKED_ALT = "\xef\x96\xa0"; pub const ICON_FA_MAP_MARKER = "\xef\x81\x81"; pub const ICON_FA_MAP_MARKER_ALT = "\xef\x8f\x85"; pub const ICON_FA_MAP_PIN = "\xef\x89\xb6"; pub const ICON_FA_MAP_SIGNS = "\xef\x89\xb7"; pub const ICON_FA_MARKER = "\xef\x96\xa1"; pub const ICON_FA_MARS = "\xef\x88\xa2"; pub const ICON_FA_MARS_DOUBLE = "\xef\x88\xa7"; pub const ICON_FA_MARS_STROKE = "\xef\x88\xa9"; pub const ICON_FA_MARS_STROKE_H = "\xef\x88\xab"; pub const ICON_FA_MARS_STROKE_V = "\xef\x88\xaa"; pub const ICON_FA_MASK = "\xef\x9b\xba"; pub const ICON_FA_MEDAL = "\xef\x96\xa2"; pub const ICON_FA_MEDKIT = "\xef\x83\xba"; pub const ICON_FA_MEH = "\xef\x84\x9a"; pub const ICON_FA_MEH_BLANK = "\xef\x96\xa4"; pub const ICON_FA_MEH_ROLLING_EYES = "\xef\x96\xa5"; pub const ICON_FA_MEMORY = "\xef\x94\xb8"; pub const ICON_FA_MENORAH = "\xef\x99\xb6"; pub const ICON_FA_MERCURY = "\xef\x88\xa3"; pub const ICON_FA_METEOR = "\xef\x9d\x93"; pub const ICON_FA_MICROCHIP = "\xef\x8b\x9b"; pub const ICON_FA_MICROPHONE = "\xef\x84\xb0"; pub const ICON_FA_MICROPHONE_ALT = "\xef\x8f\x89"; pub const ICON_FA_MICROPHONE_ALT_SLASH = "\xef\x94\xb9"; pub const ICON_FA_MICROPHONE_SLASH = "\xef\x84\xb1"; pub const ICON_FA_MICROSCOPE = "\xef\x98\x90"; pub const ICON_FA_MINUS = "\xef\x81\xa8"; pub const ICON_FA_MINUS_CIRCLE = "\xef\x81\x96"; pub const ICON_FA_MINUS_SQUARE = "\xef\x85\x86"; pub const ICON_FA_MITTEN = "\xef\x9e\xb5"; pub const ICON_FA_MOBILE = "\xef\x84\x8b"; pub const ICON_FA_MOBILE_ALT = "\xef\x8f\x8d"; pub const ICON_FA_MONEY_BILL = "\xef\x83\x96"; pub const ICON_FA_MONEY_BILL_ALT = "\xef\x8f\x91"; pub const ICON_FA_MONEY_BILL_WAVE = "\xef\x94\xba"; pub const ICON_FA_MONEY_BILL_WAVE_ALT = "\xef\x94\xbb"; pub const ICON_FA_MONEY_CHECK = "\xef\x94\xbc"; pub const ICON_FA_MONEY_CHECK_ALT = "\xef\x94\xbd"; pub const ICON_FA_MONUMENT = "\xef\x96\xa6"; pub const ICON_FA_MOON = "\xef\x86\x86"; pub const ICON_FA_MORTAR_PESTLE = "\xef\x96\xa7"; pub const ICON_FA_MOSQUE = "\xef\x99\xb8"; pub const ICON_FA_MOTORCYCLE = "\xef\x88\x9c"; pub const ICON_FA_MOUNTAIN = "\xef\x9b\xbc"; pub const ICON_FA_MOUSE = "\xef\xa3\x8c"; pub const ICON_FA_MOUSE_POINTER = "\xef\x89\x85"; pub const ICON_FA_MUG_HOT = "\xef\x9e\xb6"; pub const ICON_FA_MUSIC = "\xef\x80\x81"; pub const ICON_FA_NETWORK_WIRED = "\xef\x9b\xbf"; pub const ICON_FA_NEUTER = "\xef\x88\xac"; pub const ICON_FA_NEWSPAPER = "\xef\x87\xaa"; pub const ICON_FA_NOT_EQUAL = "\xef\x94\xbe"; pub const ICON_FA_NOTES_MEDICAL = "\xef\x92\x81"; pub const ICON_FA_OBJECT_GROUP = "\xef\x89\x87"; pub const ICON_FA_OBJECT_UNGROUP = "\xef\x89\x88"; pub const ICON_FA_OIL_CAN = "\xef\x98\x93"; pub const ICON_FA_OM = "\xef\x99\xb9"; pub const ICON_FA_OTTER = "\xef\x9c\x80"; pub const ICON_FA_OUTDENT = "\xef\x80\xbb"; pub const ICON_FA_PAGER = "\xef\xa0\x95"; pub const ICON_FA_PAINT_BRUSH = "\xef\x87\xbc"; pub const ICON_FA_PAINT_ROLLER = "\xef\x96\xaa"; pub const ICON_FA_PALETTE = "\xef\x94\xbf"; pub const ICON_FA_PALLET = "\xef\x92\x82"; pub const ICON_FA_PAPER_PLANE = "\xef\x87\x98"; pub const ICON_FA_PAPERCLIP = "\xef\x83\x86"; pub const ICON_FA_PARACHUTE_BOX = "\xef\x93\x8d"; pub const ICON_FA_PARAGRAPH = "\xef\x87\x9d"; pub const ICON_FA_PARKING = "\xef\x95\x80"; pub const ICON_FA_PASSPORT = "\xef\x96\xab"; pub const ICON_FA_PASTAFARIANISM = "\xef\x99\xbb"; pub const ICON_FA_PASTE = "\xef\x83\xaa"; pub const ICON_FA_PAUSE = "\xef\x81\x8c"; pub const ICON_FA_PAUSE_CIRCLE = "\xef\x8a\x8b"; pub const ICON_FA_PAW = "\xef\x86\xb0"; pub const ICON_FA_PEACE = "\xef\x99\xbc"; pub const ICON_FA_PEN = "\xef\x8c\x84"; pub const ICON_FA_PEN_ALT = "\xef\x8c\x85"; pub const ICON_FA_PEN_FANCY = "\xef\x96\xac"; pub const ICON_FA_PEN_NIB = "\xef\x96\xad"; pub const ICON_FA_PEN_SQUARE = "\xef\x85\x8b"; pub const ICON_FA_PENCIL_ALT = "\xef\x8c\x83"; pub const ICON_FA_PENCIL_RULER = "\xef\x96\xae"; pub const ICON_FA_PEOPLE_ARROWS = "\xee\x81\xa8"; pub const ICON_FA_PEOPLE_CARRY = "\xef\x93\x8e"; pub const ICON_FA_PEPPER_HOT = "\xef\xa0\x96"; pub const ICON_FA_PERCENT = "\xef\x8a\x95"; pub const ICON_FA_PERCENTAGE = "\xef\x95\x81"; pub const ICON_FA_PERSON_BOOTH = "\xef\x9d\x96"; pub const ICON_FA_PHONE = "\xef\x82\x95"; pub const ICON_FA_PHONE_ALT = "\xef\xa1\xb9"; pub const ICON_FA_PHONE_SLASH = "\xef\x8f\x9d"; pub const ICON_FA_PHONE_SQUARE = "\xef\x82\x98"; pub const ICON_FA_PHONE_SQUARE_ALT = "\xef\xa1\xbb"; pub const ICON_FA_PHONE_VOLUME = "\xef\x8a\xa0"; pub const ICON_FA_PHOTO_VIDEO = "\xef\xa1\xbc"; pub const ICON_FA_PIGGY_BANK = "\xef\x93\x93"; pub const ICON_FA_PILLS = "\xef\x92\x84"; pub const ICON_FA_PIZZA_SLICE = "\xef\xa0\x98"; pub const ICON_FA_PLACE_OF_WORSHIP = "\xef\x99\xbf"; pub const ICON_FA_PLANE = "\xef\x81\xb2"; pub const ICON_FA_PLANE_ARRIVAL = "\xef\x96\xaf"; pub const ICON_FA_PLANE_DEPARTURE = "\xef\x96\xb0"; pub const ICON_FA_PLANE_SLASH = "\xee\x81\xa9"; pub const ICON_FA_PLAY = "\xef\x81\x8b"; pub const ICON_FA_PLAY_CIRCLE = "\xef\x85\x84"; pub const ICON_FA_PLUG = "\xef\x87\xa6"; pub const ICON_FA_PLUS = "\xef\x81\xa7"; pub const ICON_FA_PLUS_CIRCLE = "\xef\x81\x95"; pub const ICON_FA_PLUS_SQUARE = "\xef\x83\xbe"; pub const ICON_FA_PODCAST = "\xef\x8b\x8e"; pub const ICON_FA_POLL = "\xef\x9a\x81"; pub const ICON_FA_POLL_H = "\xef\x9a\x82"; pub const ICON_FA_POO = "\xef\x8b\xbe"; pub const ICON_FA_POO_STORM = "\xef\x9d\x9a"; pub const ICON_FA_POOP = "\xef\x98\x99"; pub const ICON_FA_PORTRAIT = "\xef\x8f\xa0"; pub const ICON_FA_POUND_SIGN = "\xef\x85\x94"; pub const ICON_FA_POWER_OFF = "\xef\x80\x91"; pub const ICON_FA_PRAY = "\xef\x9a\x83"; pub const ICON_FA_PRAYING_HANDS = "\xef\x9a\x84"; pub const ICON_FA_PRESCRIPTION = "\xef\x96\xb1"; pub const ICON_FA_PRESCRIPTION_BOTTLE = "\xef\x92\x85"; pub const ICON_FA_PRESCRIPTION_BOTTLE_ALT = "\xef\x92\x86"; pub const ICON_FA_PRINT = "\xef\x80\xaf"; pub const ICON_FA_PROCEDURES = "\xef\x92\x87"; pub const ICON_FA_PROJECT_DIAGRAM = "\xef\x95\x82"; pub const ICON_FA_PUMP_MEDICAL = "\xee\x81\xaa"; pub const ICON_FA_PUMP_SOAP = "\xee\x81\xab"; pub const ICON_FA_PUZZLE_PIECE = "\xef\x84\xae"; pub const ICON_FA_QRCODE = "\xef\x80\xa9"; pub const ICON_FA_QUESTION = "\xef\x84\xa8"; pub const ICON_FA_QUESTION_CIRCLE = "\xef\x81\x99"; pub const ICON_FA_QUIDDITCH = "\xef\x91\x98"; pub const ICON_FA_QUOTE_LEFT = "\xef\x84\x8d"; pub const ICON_FA_QUOTE_RIGHT = "\xef\x84\x8e"; pub const ICON_FA_QURAN = "\xef\x9a\x87"; pub const ICON_FA_RADIATION = "\xef\x9e\xb9"; pub const ICON_FA_RADIATION_ALT = "\xef\x9e\xba"; pub const ICON_FA_RAINBOW = "\xef\x9d\x9b"; pub const ICON_FA_RANDOM = "\xef\x81\xb4"; pub const ICON_FA_RECEIPT = "\xef\x95\x83"; pub const ICON_FA_RECORD_VINYL = "\xef\xa3\x99"; pub const ICON_FA_RECYCLE = "\xef\x86\xb8"; pub const ICON_FA_REDO = "\xef\x80\x9e"; pub const ICON_FA_REDO_ALT = "\xef\x8b\xb9"; pub const ICON_FA_REGISTERED = "\xef\x89\x9d"; pub const ICON_FA_REMOVE_FORMAT = "\xef\xa1\xbd"; pub const ICON_FA_REPLY = "\xef\x8f\xa5"; pub const ICON_FA_REPLY_ALL = "\xef\x84\xa2"; pub const ICON_FA_REPUBLICAN = "\xef\x9d\x9e"; pub const ICON_FA_RESTROOM = "\xef\x9e\xbd"; pub const ICON_FA_RETWEET = "\xef\x81\xb9"; pub const ICON_FA_RIBBON = "\xef\x93\x96"; pub const ICON_FA_RING = "\xef\x9c\x8b"; pub const ICON_FA_ROAD = "\xef\x80\x98"; pub const ICON_FA_ROBOT = "\xef\x95\x84"; pub const ICON_FA_ROCKET = "\xef\x84\xb5"; pub const ICON_FA_ROUTE = "\xef\x93\x97"; pub const ICON_FA_RSS = "\xef\x82\x9e"; pub const ICON_FA_RSS_SQUARE = "\xef\x85\x83"; pub const ICON_FA_RUBLE_SIGN = "\xef\x85\x98"; pub const ICON_FA_RULER = "\xef\x95\x85"; pub const ICON_FA_RULER_COMBINED = "\xef\x95\x86"; pub const ICON_FA_RULER_HORIZONTAL = "\xef\x95\x87"; pub const ICON_FA_RULER_VERTICAL = "\xef\x95\x88"; pub const ICON_FA_RUNNING = "\xef\x9c\x8c"; pub const ICON_FA_RUPEE_SIGN = "\xef\x85\x96"; pub const ICON_FA_SAD_CRY = "\xef\x96\xb3"; pub const ICON_FA_SAD_TEAR = "\xef\x96\xb4"; pub const ICON_FA_SATELLITE = "\xef\x9e\xbf"; pub const ICON_FA_SATELLITE_DISH = "\xef\x9f\x80"; pub const ICON_FA_SAVE = "\xef\x83\x87"; pub const ICON_FA_SCHOOL = "\xef\x95\x89"; pub const ICON_FA_SCREWDRIVER = "\xef\x95\x8a"; pub const ICON_FA_SCROLL = "\xef\x9c\x8e"; pub const ICON_FA_SD_CARD = "\xef\x9f\x82"; pub const ICON_FA_SEARCH = "\xef\x80\x82"; pub const ICON_FA_SEARCH_DOLLAR = "\xef\x9a\x88"; pub const ICON_FA_SEARCH_LOCATION = "\xef\x9a\x89"; pub const ICON_FA_SEARCH_MINUS = "\xef\x80\x90"; pub const ICON_FA_SEARCH_PLUS = "\xef\x80\x8e"; pub const ICON_FA_SEEDLING = "\xef\x93\x98"; pub const ICON_FA_SERVER = "\xef\x88\xb3"; pub const ICON_FA_SHAPES = "\xef\x98\x9f"; pub const ICON_FA_SHARE = "\xef\x81\xa4"; pub const ICON_FA_SHARE_ALT = "\xef\x87\xa0"; pub const ICON_FA_SHARE_ALT_SQUARE = "\xef\x87\xa1"; pub const ICON_FA_SHARE_SQUARE = "\xef\x85\x8d"; pub const ICON_FA_SHEKEL_SIGN = "\xef\x88\x8b"; pub const ICON_FA_SHIELD_ALT = "\xef\x8f\xad"; pub const ICON_FA_SHIELD_VIRUS = "\xee\x81\xac"; pub const ICON_FA_SHIP = "\xef\x88\x9a"; pub const ICON_FA_SHIPPING_FAST = "\xef\x92\x8b"; pub const ICON_FA_SHOE_PRINTS = "\xef\x95\x8b"; pub const ICON_FA_SHOPPING_BAG = "\xef\x8a\x90"; pub const ICON_FA_SHOPPING_BASKET = "\xef\x8a\x91"; pub const ICON_FA_SHOPPING_CART = "\xef\x81\xba"; pub const ICON_FA_SHOWER = "\xef\x8b\x8c"; pub const ICON_FA_SHUTTLE_VAN = "\xef\x96\xb6"; pub const ICON_FA_SIGN = "\xef\x93\x99"; pub const ICON_FA_SIGN_IN_ALT = "\xef\x8b\xb6"; pub const ICON_FA_SIGN_LANGUAGE = "\xef\x8a\xa7"; pub const ICON_FA_SIGN_OUT_ALT = "\xef\x8b\xb5"; pub const ICON_FA_SIGNAL = "\xef\x80\x92"; pub const ICON_FA_SIGNATURE = "\xef\x96\xb7"; pub const ICON_FA_SIM_CARD = "\xef\x9f\x84"; pub const ICON_FA_SINK = "\xee\x81\xad"; pub const ICON_FA_SITEMAP = "\xef\x83\xa8"; pub const ICON_FA_SKATING = "\xef\x9f\x85"; pub const ICON_FA_SKIING = "\xef\x9f\x89"; pub const ICON_FA_SKIING_NORDIC = "\xef\x9f\x8a"; pub const ICON_FA_SKULL = "\xef\x95\x8c"; pub const ICON_FA_SKULL_CROSSBONES = "\xef\x9c\x94"; pub const ICON_FA_SLASH = "\xef\x9c\x95"; pub const ICON_FA_SLEIGH = "\xef\x9f\x8c"; pub const ICON_FA_SLIDERS_H = "\xef\x87\x9e"; pub const ICON_FA_SMILE = "\xef\x84\x98"; pub const ICON_FA_SMILE_BEAM = "\xef\x96\xb8"; pub const ICON_FA_SMILE_WINK = "\xef\x93\x9a"; pub const ICON_FA_SMOG = "\xef\x9d\x9f"; pub const ICON_FA_SMOKING = "\xef\x92\x8d"; pub const ICON_FA_SMOKING_BAN = "\xef\x95\x8d"; pub const ICON_FA_SMS = "\xef\x9f\x8d"; pub const ICON_FA_SNOWBOARDING = "\xef\x9f\x8e"; pub const ICON_FA_SNOWFLAKE = "\xef\x8b\x9c"; pub const ICON_FA_SNOWMAN = "\xef\x9f\x90"; pub const ICON_FA_SNOWPLOW = "\xef\x9f\x92"; pub const ICON_FA_SOAP = "\xee\x81\xae"; pub const ICON_FA_SOCKS = "\xef\x9a\x96"; pub const ICON_FA_SOLAR_PANEL = "\xef\x96\xba"; pub const ICON_FA_SORT = "\xef\x83\x9c"; pub const ICON_FA_SORT_ALPHA_DOWN = "\xef\x85\x9d"; pub const ICON_FA_SORT_ALPHA_DOWN_ALT = "\xef\xa2\x81"; pub const ICON_FA_SORT_ALPHA_UP = "\xef\x85\x9e"; pub const ICON_FA_SORT_ALPHA_UP_ALT = "\xef\xa2\x82"; pub const ICON_FA_SORT_AMOUNT_DOWN = "\xef\x85\xa0"; pub const ICON_FA_SORT_AMOUNT_DOWN_ALT = "\xef\xa2\x84"; pub const ICON_FA_SORT_AMOUNT_UP = "\xef\x85\xa1"; pub const ICON_FA_SORT_AMOUNT_UP_ALT = "\xef\xa2\x85"; pub const ICON_FA_SORT_DOWN = "\xef\x83\x9d"; pub const ICON_FA_SORT_NUMERIC_DOWN = "\xef\x85\xa2"; pub const ICON_FA_SORT_NUMERIC_DOWN_ALT = "\xef\xa2\x86"; pub const ICON_FA_SORT_NUMERIC_UP = "\xef\x85\xa3"; pub const ICON_FA_SORT_NUMERIC_UP_ALT = "\xef\xa2\x87"; pub const ICON_FA_SORT_UP = "\xef\x83\x9e"; pub const ICON_FA_SPA = "\xef\x96\xbb"; pub const ICON_FA_SPACE_SHUTTLE = "\xef\x86\x97"; pub const ICON_FA_SPELL_CHECK = "\xef\xa2\x91"; pub const ICON_FA_SPIDER = "\xef\x9c\x97"; pub const ICON_FA_SPINNER = "\xef\x84\x90"; pub const ICON_FA_SPLOTCH = "\xef\x96\xbc"; pub const ICON_FA_SPRAY_CAN = "\xef\x96\xbd"; pub const ICON_FA_SQUARE = "\xef\x83\x88"; pub const ICON_FA_SQUARE_FULL = "\xef\x91\x9c"; pub const ICON_FA_SQUARE_ROOT_ALT = "\xef\x9a\x98"; pub const ICON_FA_STAMP = "\xef\x96\xbf"; pub const ICON_FA_STAR = "\xef\x80\x85"; pub const ICON_FA_STAR_AND_CRESCENT = "\xef\x9a\x99"; pub const ICON_FA_STAR_HALF = "\xef\x82\x89"; pub const ICON_FA_STAR_HALF_ALT = "\xef\x97\x80"; pub const ICON_FA_STAR_OF_DAVID = "\xef\x9a\x9a"; pub const ICON_FA_STAR_OF_LIFE = "\xef\x98\xa1"; pub const ICON_FA_STEP_BACKWARD = "\xef\x81\x88"; pub const ICON_FA_STEP_FORWARD = "\xef\x81\x91"; pub const ICON_FA_STETHOSCOPE = "\xef\x83\xb1"; pub const ICON_FA_STICKY_NOTE = "\xef\x89\x89"; pub const ICON_FA_STOP = "\xef\x81\x8d"; pub const ICON_FA_STOP_CIRCLE = "\xef\x8a\x8d"; pub const ICON_FA_STOPWATCH = "\xef\x8b\xb2"; pub const ICON_FA_STOPWATCH_20 = "\xee\x81\xaf"; pub const ICON_FA_STORE = "\xef\x95\x8e"; pub const ICON_FA_STORE_ALT = "\xef\x95\x8f"; pub const ICON_FA_STORE_ALT_SLASH = "\xee\x81\xb0"; pub const ICON_FA_STORE_SLASH = "\xee\x81\xb1"; pub const ICON_FA_STREAM = "\xef\x95\x90"; pub const ICON_FA_STREET_VIEW = "\xef\x88\x9d"; pub const ICON_FA_STRIKETHROUGH = "\xef\x83\x8c"; pub const ICON_FA_STROOPWAFEL = "\xef\x95\x91"; pub const ICON_FA_SUBSCRIPT = "\xef\x84\xac"; pub const ICON_FA_SUBWAY = "\xef\x88\xb9"; pub const ICON_FA_SUITCASE = "\xef\x83\xb2"; pub const ICON_FA_SUITCASE_ROLLING = "\xef\x97\x81"; pub const ICON_FA_SUN = "\xef\x86\x85"; pub const ICON_FA_SUPERSCRIPT = "\xef\x84\xab"; pub const ICON_FA_SURPRISE = "\xef\x97\x82"; pub const ICON_FA_SWATCHBOOK = "\xef\x97\x83"; pub const ICON_FA_SWIMMER = "\xef\x97\x84"; pub const ICON_FA_SWIMMING_POOL = "\xef\x97\x85"; pub const ICON_FA_SYNAGOGUE = "\xef\x9a\x9b"; pub const ICON_FA_SYNC = "\xef\x80\xa1"; pub const ICON_FA_SYNC_ALT = "\xef\x8b\xb1"; pub const ICON_FA_SYRINGE = "\xef\x92\x8e"; pub const ICON_FA_TABLE = "\xef\x83\x8e"; pub const ICON_FA_TABLE_TENNIS = "\xef\x91\x9d"; pub const ICON_FA_TABLET = "\xef\x84\x8a"; pub const ICON_FA_TABLET_ALT = "\xef\x8f\xba"; pub const ICON_FA_TABLETS = "\xef\x92\x90"; pub const ICON_FA_TACHOMETER_ALT = "\xef\x8f\xbd"; pub const ICON_FA_TAG = "\xef\x80\xab"; pub const ICON_FA_TAGS = "\xef\x80\xac"; pub const ICON_FA_TAPE = "\xef\x93\x9b"; pub const ICON_FA_TASKS = "\xef\x82\xae"; pub const ICON_FA_TAXI = "\xef\x86\xba"; pub const ICON_FA_TEETH = "\xef\x98\xae"; pub const ICON_FA_TEETH_OPEN = "\xef\x98\xaf"; pub const ICON_FA_TEMPERATURE_HIGH = "\xef\x9d\xa9"; pub const ICON_FA_TEMPERATURE_LOW = "\xef\x9d\xab"; pub const ICON_FA_TENGE = "\xef\x9f\x97"; pub const ICON_FA_TERMINAL = "\xef\x84\xa0"; pub const ICON_FA_TEXT_HEIGHT = "\xef\x80\xb4"; pub const ICON_FA_TEXT_WIDTH = "\xef\x80\xb5"; pub const ICON_FA_TH = "\xef\x80\x8a"; pub const ICON_FA_TH_LARGE = "\xef\x80\x89"; pub const ICON_FA_TH_LIST = "\xef\x80\x8b"; pub const ICON_FA_THEATER_MASKS = "\xef\x98\xb0"; pub const ICON_FA_THERMOMETER = "\xef\x92\x91"; pub const ICON_FA_THERMOMETER_EMPTY = "\xef\x8b\x8b"; pub const ICON_FA_THERMOMETER_FULL = "\xef\x8b\x87"; pub const ICON_FA_THERMOMETER_HALF = "\xef\x8b\x89"; pub const ICON_FA_THERMOMETER_QUARTER = "\xef\x8b\x8a"; pub const ICON_FA_THERMOMETER_THREE_QUARTERS = "\xef\x8b\x88"; pub const ICON_FA_THUMBS_DOWN = "\xef\x85\xa5"; pub const ICON_FA_THUMBS_UP = "\xef\x85\xa4"; pub const ICON_FA_THUMBTACK = "\xef\x82\x8d"; pub const ICON_FA_TICKET_ALT = "\xef\x8f\xbf"; pub const ICON_FA_TIMES = "\xef\x80\x8d"; pub const ICON_FA_TIMES_CIRCLE = "\xef\x81\x97"; pub const ICON_FA_TINT = "\xef\x81\x83"; pub const ICON_FA_TINT_SLASH = "\xef\x97\x87"; pub const ICON_FA_TIRED = "\xef\x97\x88"; pub const ICON_FA_TOGGLE_OFF = "\xef\x88\x84"; pub const ICON_FA_TOGGLE_ON = "\xef\x88\x85"; pub const ICON_FA_TOILET = "\xef\x9f\x98"; pub const ICON_FA_TOILET_PAPER = "\xef\x9c\x9e"; pub const ICON_FA_TOILET_PAPER_SLASH = "\xee\x81\xb2"; pub const ICON_FA_TOOLBOX = "\xef\x95\x92"; pub const ICON_FA_TOOLS = "\xef\x9f\x99"; pub const ICON_FA_TOOTH = "\xef\x97\x89"; pub const ICON_FA_TORAH = "\xef\x9a\xa0"; pub const ICON_FA_TORII_GATE = "\xef\x9a\xa1"; pub const ICON_FA_TRACTOR = "\xef\x9c\xa2"; pub const ICON_FA_TRADEMARK = "\xef\x89\x9c"; pub const ICON_FA_TRAFFIC_LIGHT = "\xef\x98\xb7"; pub const ICON_FA_TRAILER = "\xee\x81\x81"; pub const ICON_FA_TRAIN = "\xef\x88\xb8"; pub const ICON_FA_TRAM = "\xef\x9f\x9a"; pub const ICON_FA_TRANSGENDER = "\xef\x88\xa4"; pub const ICON_FA_TRANSGENDER_ALT = "\xef\x88\xa5"; pub const ICON_FA_TRASH = "\xef\x87\xb8"; pub const ICON_FA_TRASH_ALT = "\xef\x8b\xad"; pub const ICON_FA_TRASH_RESTORE = "\xef\xa0\xa9"; pub const ICON_FA_TRASH_RESTORE_ALT = "\xef\xa0\xaa"; pub const ICON_FA_TREE = "\xef\x86\xbb"; pub const ICON_FA_TROPHY = "\xef\x82\x91"; pub const ICON_FA_TRUCK = "\xef\x83\x91"; pub const ICON_FA_TRUCK_LOADING = "\xef\x93\x9e"; pub const ICON_FA_TRUCK_MONSTER = "\xef\x98\xbb"; pub const ICON_FA_TRUCK_MOVING = "\xef\x93\x9f"; pub const ICON_FA_TRUCK_PICKUP = "\xef\x98\xbc"; pub const ICON_FA_TSHIRT = "\xef\x95\x93"; pub const ICON_FA_TTY = "\xef\x87\xa4"; pub const ICON_FA_TV = "\xef\x89\xac"; pub const ICON_FA_UMBRELLA = "\xef\x83\xa9"; pub const ICON_FA_UMBRELLA_BEACH = "\xef\x97\x8a"; pub const ICON_FA_UNDERLINE = "\xef\x83\x8d"; pub const ICON_FA_UNDO = "\xef\x83\xa2"; pub const ICON_FA_UNDO_ALT = "\xef\x8b\xaa"; pub const ICON_FA_UNIVERSAL_ACCESS = "\xef\x8a\x9a"; pub const ICON_FA_UNIVERSITY = "\xef\x86\x9c"; pub const ICON_FA_UNLINK = "\xef\x84\xa7"; pub const ICON_FA_UNLOCK = "\xef\x82\x9c"; pub const ICON_FA_UNLOCK_ALT = "\xef\x84\xbe"; pub const ICON_FA_UPLOAD = "\xef\x82\x93"; pub const ICON_FA_USER = "\xef\x80\x87"; pub const ICON_FA_USER_ALT = "\xef\x90\x86"; pub const ICON_FA_USER_ALT_SLASH = "\xef\x93\xba"; pub const ICON_FA_USER_ASTRONAUT = "\xef\x93\xbb"; pub const ICON_FA_USER_CHECK = "\xef\x93\xbc"; pub const ICON_FA_USER_CIRCLE = "\xef\x8a\xbd"; pub const ICON_FA_USER_CLOCK = "\xef\x93\xbd"; pub const ICON_FA_USER_COG = "\xef\x93\xbe"; pub const ICON_FA_USER_EDIT = "\xef\x93\xbf"; pub const ICON_FA_USER_FRIENDS = "\xef\x94\x80"; pub const ICON_FA_USER_GRADUATE = "\xef\x94\x81"; pub const ICON_FA_USER_INJURED = "\xef\x9c\xa8"; pub const ICON_FA_USER_LOCK = "\xef\x94\x82"; pub const ICON_FA_USER_MD = "\xef\x83\xb0"; pub const ICON_FA_USER_MINUS = "\xef\x94\x83"; pub const ICON_FA_USER_NINJA = "\xef\x94\x84"; pub const ICON_FA_USER_NURSE = "\xef\xa0\xaf"; pub const ICON_FA_USER_PLUS = "\xef\x88\xb4"; pub const ICON_FA_USER_SECRET = "\xef\x88\x9b"; pub const ICON_FA_USER_SHIELD = "\xef\x94\x85"; pub const ICON_FA_USER_SLASH = "\xef\x94\x86"; pub const ICON_FA_USER_TAG = "\xef\x94\x87"; pub const ICON_FA_USER_TIE = "\xef\x94\x88"; pub const ICON_FA_USER_TIMES = "\xef\x88\xb5"; pub const ICON_FA_USERS = "\xef\x83\x80"; pub const ICON_FA_USERS_COG = "\xef\x94\x89"; pub const ICON_FA_USERS_SLASH = "\xee\x81\xb3"; pub const ICON_FA_UTENSIL_SPOON = "\xef\x8b\xa5"; pub const ICON_FA_UTENSILS = "\xef\x8b\xa7"; pub const ICON_FA_VECTOR_SQUARE = "\xef\x97\x8b"; pub const ICON_FA_VENUS = "\xef\x88\xa1"; pub const ICON_FA_VENUS_DOUBLE = "\xef\x88\xa6"; pub const ICON_FA_VENUS_MARS = "\xef\x88\xa8"; pub const ICON_FA_VEST = "\xee\x82\x85"; pub const ICON_FA_VEST_PATCHES = "\xee\x82\x86"; pub const ICON_FA_VIAL = "\xef\x92\x92"; pub const ICON_FA_VIALS = "\xef\x92\x93"; pub const ICON_FA_VIDEO = "\xef\x80\xbd"; pub const ICON_FA_VIDEO_SLASH = "\xef\x93\xa2"; pub const ICON_FA_VIHARA = "\xef\x9a\xa7"; pub const ICON_FA_VIRUS = "\xee\x81\xb4"; pub const ICON_FA_VIRUS_SLASH = "\xee\x81\xb5"; pub const ICON_FA_VIRUSES = "\xee\x81\xb6"; pub const ICON_FA_VOICEMAIL = "\xef\xa2\x97"; pub const ICON_FA_VOLLEYBALL_BALL = "\xef\x91\x9f"; pub const ICON_FA_VOLUME_DOWN = "\xef\x80\xa7"; pub const ICON_FA_VOLUME_MUTE = "\xef\x9a\xa9"; pub const ICON_FA_VOLUME_OFF = "\xef\x80\xa6"; pub const ICON_FA_VOLUME_UP = "\xef\x80\xa8"; pub const ICON_FA_VOTE_YEA = "\xef\x9d\xb2"; pub const ICON_FA_VR_CARDBOARD = "\xef\x9c\xa9"; pub const ICON_FA_WALKING = "\xef\x95\x94"; pub const ICON_FA_WALLET = "\xef\x95\x95"; pub const ICON_FA_WAREHOUSE = "\xef\x92\x94"; pub const ICON_FA_WATER = "\xef\x9d\xb3"; pub const ICON_FA_WAVE_SQUARE = "\xef\xa0\xbe"; pub const ICON_FA_WEIGHT = "\xef\x92\x96"; pub const ICON_FA_WEIGHT_HANGING = "\xef\x97\x8d"; pub const ICON_FA_WHEELCHAIR = "\xef\x86\x93"; pub const ICON_FA_WIFI = "\xef\x87\xab"; pub const ICON_FA_WIND = "\xef\x9c\xae"; pub const ICON_FA_WINDOW_CLOSE = "\xef\x90\x90"; pub const ICON_FA_WINDOW_MAXIMIZE = "\xef\x8b\x90"; pub const ICON_FA_WINDOW_MINIMIZE = "\xef\x8b\x91"; pub const ICON_FA_WINDOW_RESTORE = "\xef\x8b\x92"; pub const ICON_FA_WINE_BOTTLE = "\xef\x9c\xaf"; pub const ICON_FA_WINE_GLASS = "\xef\x93\xa3"; pub const ICON_FA_WINE_GLASS_ALT = "\xef\x97\x8e"; pub const ICON_FA_WON_SIGN = "\xef\x85\x99"; pub const ICON_FA_WRENCH = "\xef\x82\xad"; pub const ICON_FA_X_RAY = "\xef\x92\x97"; pub const ICON_FA_YEN_SIGN = "\xef\x85\x97"; pub const ICON_FA_YIN_YANG = "\xef\x9a\xad";
src/deps/imgui/fonts/fontawesome.zig
const std = @import("std"); const ArrayList = std.ArrayList; // TODO: change to "core" when we dependencies untangled const core = @import("../index.zig"); const Coord = core.geometry.Coord; const sign = core.geometry.sign; const GameEngine = @import("./game_engine.zig").GameEngine; const game_model = @import("./game_model.zig"); const GameState = game_model.GameState; const IdMap = game_model.IdMap; const SomeQueues = @import("../client/game_engine_client.zig").SomeQueues; const Request = core.protocol.Request; const Response = core.protocol.Response; const Action = core.protocol.Action; const Event = core.protocol.Event; const Species = core.protocol.Species; const PerceivedHappening = core.protocol.PerceivedHappening; const PerceivedFrame = core.protocol.PerceivedFrame; const getHeadPosition = core.game_logic.getHeadPosition; const getAllPositions = core.game_logic.getAllPositions; const hasFastMove = core.game_logic.hasFastMove; const isFastMoveAligned = core.game_logic.isFastMoveAligned; const StateDiff = game_model.StateDiff; const HistoryList = std.TailQueue([]StateDiff); const HistoryNode = HistoryList.Node; const allocator = std.heap.c_allocator; pub fn server_main(main_player_queues: *SomeQueues) !void { var game_engine: GameEngine = undefined; game_engine.init(allocator); var game_state = try GameState.generate(allocator); // create ai clients const main_player_id: u32 = 1; var you_are_alive = true; // Welcome to swarkland! try main_player_queues.enqueueResponse(Response{ .load_state = try game_engine.getStaticPerception(game_state, main_player_id) }); var response_for_ais = IdMap(Response).init(allocator); var history = HistoryList{}; // start main loop mainLoop: while (true) { var actions = IdMap(Action).init(allocator); // do ai { var iterator = game_state.individuals.iterator(); while (iterator.next()) |kv| { const id = kv.key; if (id == main_player_id) continue; const response = response_for_ais.get(id) orelse Response{ .load_state = try game_engine.getStaticPerception(game_state, id) }; try actions.putNoClobber(id, doAi(response)); } } response_for_ais.clearRetainingCapacity(); // read all the inputs, which will block for the human client. var is_rewind = false; { retryRead: while (true) { switch (main_player_queues.waitAndTakeRequest() orelse { core.debug.thread_lifecycle.print("clean shutdown. close", .{}); main_player_queues.closeResponses(); break :mainLoop; }) { .act => |action| { if (!you_are_alive) { // no. you're are dead. try main_player_queues.enqueueResponse(Response.reject_request); continue :retryRead; } std.debug.assert(game_engine.validateAction(action)); try actions.putNoClobber(main_player_id, action); }, .rewind => { if (history.len == 0) { // What do you want me to do, send you back to the main menu? try main_player_queues.enqueueResponse(Response.reject_request); continue :retryRead; } // delay actually rewinding so that we receive all requests. is_rewind = true; }, } break; } } if (is_rewind) { // Time goes backward. const state_changes = rewind(&history).?; try game_state.undoStateChanges(state_changes); for (state_changes) |_, i| { const diff = state_changes[state_changes.len - 1 - i]; switch (diff) { .despawn => |individual| { if (individual.id == main_player_id) { you_are_alive = true; } }, else => {}, } } try main_player_queues.enqueueResponse(Response{ .load_state = try game_engine.getStaticPerception(game_state, main_player_id) }); } else { // Time goes forward. var scratch_game_state = try game_state.clone(); const happenings = try game_engine.computeHappenings(&scratch_game_state, actions); core.debug.happening.deepPrint("happenings: ", happenings); try pushHistoryRecord(&history, happenings.state_changes); try game_state.applyStateChanges(happenings.state_changes); for (happenings.state_changes) |diff| { switch (diff) { .despawn => |individual| { if (individual.id == main_player_id) { you_are_alive = false; } }, else => {}, } } var iterator = happenings.individual_to_perception.iterator(); while (iterator.next()) |kv| { const id = kv.key; const response = Response{ .stuff_happens = PerceivedHappening{ .frames = kv.value, }, }; if (id == main_player_id) { try main_player_queues.enqueueResponse(response); } else { try response_for_ais.putNoClobber(id, response); } } } } } fn rewind(history: *HistoryList) ?[]StateDiff { const node = history.pop() orelse return null; return node.data; } fn pushHistoryRecord(history: *HistoryList, state_changes: []StateDiff) !void { const history_node: *HistoryNode = try allocator.create(HistoryNode); history_node.data = state_changes; history.append(history_node); } fn doAi(response: Response) Action { // This should be sitting waiting for us already, since we just wrote it earlier. var last_frame = switch (response) { .load_state => |frame| frame, .stuff_happens => |perceived_happening| perceived_happening.frames[perceived_happening.frames.len - 1], else => @panic("unexpected response type in AI"), }; return getNaiveAiDecision(last_frame); } fn getNaiveAiDecision(last_frame: PerceivedFrame) Action { var target_position: ?Coord = null; var target_priority: i32 = -0x80000000; for (last_frame.others) |other| { const other_priority = getTargetHostilityPriority(last_frame.self.species, other.species) orelse continue; if (target_priority > other_priority) continue; if (other_priority > target_priority) { target_position = null; target_priority = other_priority; } const other_coord = getHeadPosition(other.rel_position); if (target_position) |previous_coord| { // target whichever is closest. (positions are relative to me.) if (other_coord.magnitudeOrtho() < previous_coord.magnitudeOrtho()) { target_position = other_coord; } } else { target_position = other_coord; } } if (target_position == null) { // nothing to do. return .wait; } const delta = target_position.?; std.debug.assert(!(delta.x == 0 and delta.y == 0)); const range = core.game_logic.getAttackRange(last_frame.self.species); if (delta.x * delta.y == 0) { // straight shot const delta_unit = delta.signumed(); if (hesitatesOneSpaceAway(last_frame.self.species) and delta.magnitudeOrtho() == 2) { // preemptive attack return Action{ .kick = delta_unit }; } if (hasFastMove(last_frame.self.species) and isFastMoveAligned(last_frame.self.rel_position, delta_unit.scaled(2))) { // charge! return Action{ .fast_move = delta_unit.scaled(2) }; } else if (delta.x * delta.x + delta.y * delta.y <= range * range) { if (hesitatesOneSpaceAway(last_frame.self.species)) { // just kick return Action{ .kick = delta_unit }; } // within attack range return Action{ .attack = delta_unit }; } else { // We want to get closer. if (last_frame.terrain.matrix.getCoord(delta_unit.minus(last_frame.terrain.rel_position))) |cell| { if (cell.floor == .lava) { // I'm scared of lava return .wait; } } // Move straight twoard the target, even if someone else is in the way return Action{ .move = delta_unit }; } } // We have a diagonal space to traverse. // We need to choose between the long leg of the rectangle and the short leg. const options = [_]Coord{ Coord{ .x = sign(delta.x), .y = 0 }, Coord{ .x = 0, .y = sign(delta.y) }, }; const long_index: usize = blk: { if (delta.x * delta.x > delta.y * delta.y) { // x is longer break :blk 0; } else if (delta.x * delta.x < delta.y * delta.y) { // y is longer break :blk 1; } else { // exactly diagonal. let's say that clockwise is longer. break :blk @boolToInt(delta.x != delta.y); } }; // Archers want to line up for a shot; melee wants to avoid lining up for a shot. var option_index = if (range == 1) long_index else 1 - long_index; // If something's in the way, then prefer the other way. // If something's in the way in both directions, then go with our initial preference. { var flip_flop_counter: usize = 0; flip_flop_loop: while (flip_flop_counter < 2) : (flip_flop_counter += 1) { const move_into_position = options[option_index]; if (last_frame.terrain.matrix.getCoord(move_into_position.minus(last_frame.terrain.rel_position))) |cell| { if (cell.floor == .lava or !core.game_logic.isOpenSpace(cell.wall)) { // Can't go that way. option_index = 1 - option_index; continue :flip_flop_loop; } } for (last_frame.others) |perceived_other| { for (getAllPositions(&perceived_other.rel_position)) |rel_position| { if (rel_position.equals(move_into_position)) { // somebody's there already. option_index = 1 - option_index; continue :flip_flop_loop; } } } } } if (hesitatesOneSpaceAway(last_frame.self.species) and delta.magnitudeOrtho() == 2) { // preemptive attack return Action{ .kick = options[option_index] }; } else { return Action{ .move = options[option_index] }; } } fn hesitatesOneSpaceAway(species: Species) bool { switch (species) { .kangaroo => return true, else => return false, } } fn getTargetHostilityPriority(me: Species, you: Species) ?i32 { // this is straight up racism. if (me == you) return null; if (me == .human) { // humans, being the enlightened race, want to murder everything else equally. return 9; } switch (you) { // humans are just the worst. .human => return 9, // orcs are like humans. .orc => return 6, // half human. .centaur => return 5, // whatever. else => return 1, } }
src/server/game_server.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day15.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); var map = std.ArrayList(u8).init(gpa); defer { map.deinit(); } var width : usize = 0; { var maybeWidth : ?usize = null; var lines = std.mem.tokenize(data, "\r\n"); while (lines.next()) |line| { if (maybeWidth == null) { maybeWidth = line.len; } else { std.debug.assert(maybeWidth.? == line.len); } for (line) |c| { try map.append(c - '0'); } } width = maybeWidth.?; } print("🎁 Lowest total risk: {}\n", .{try aStar(map, width)}); print("Day 15 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); const biggerWidth = width * 5; var biggerMap = std.ArrayList(u8).init(gpa); defer { biggerMap.deinit(); } var yTile : u8 = 0; while (yTile < 5) : (yTile += 1) { var y : u32 = 0; while (y < width) : (y += 1) { var xTile : u8 = 0; while (xTile < 5) : (xTile += 1) { var x : u32 = 0; while (x < width) : (x += 1) { const originalValue = map.items[y * width + x]; const value = (originalValue + yTile + xTile) % 9; try biggerMap.append(if (0 == value) 9 else value); } } } } print("🎁 Lowest total risk: {}\n", .{try aStar(biggerMap, biggerWidth)}); print("Day 15 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } fn aStar(map: std.ArrayList(u8), width: usize) !usize { var openSet = std.ArrayList(usize).init(gpa); defer { openSet.deinit(); } // We start at (0, 0). try openSet.append(0); var costs = std.ArrayList(u32).init(gpa); defer { costs.deinit(); } // Initially everything so that it costs a bomb! try costs.appendNTimes(std.math.maxInt(u32) - 10, map.items.len); // Except the start, it cost us 0 to get where we already are! costs.items[0] = 0; while (openSet.items.len > 0) { const current = openSet.orderedRemove(0); if (current == (map.items.len - 1)) { return costs.items[current] + map.items[current] - map.items[0]; } const x = current % width; const y = current / width; const cost = map.items[current] + costs.items[current]; if (x > 0) { const neighbour = current - 1; if (cost < costs.items[neighbour]) { costs.items[neighbour] = cost; try appendNeighbour(neighbour, &openSet, costs); } } if (x < (width - 1)) { const neighbour = current + 1; if (cost < costs.items[neighbour]) { costs.items[neighbour] = cost; try appendNeighbour(neighbour, &openSet, costs); } } if (y > 0) { const neighbour = current - width; if (cost < costs.items[neighbour]) { costs.items[neighbour] = cost; try appendNeighbour(neighbour, &openSet, costs); } } if (y < (width - 1)) { const neighbour = current + width; if (cost < costs.items[neighbour]) { costs.items[neighbour] = cost; try appendNeighbour(neighbour, &openSet, costs); } } } unreachable; } fn appendNeighbour(neighbour : usize, openSet : *std.ArrayList(usize), costs : std.ArrayList(u32)) !void { var insertIndex : ?usize = null; for (openSet.items) |item, i| { if (compare(costs, item, neighbour)) { continue; } insertIndex = i; break; } if (insertIndex == null) { try openSet.append(neighbour); } else { try openSet.insert(insertIndex.?, neighbour); // If we inserted ourselves within the set, we might have already been in the set (with a higher cost). // So run from just after we inserted to the end to check if we exist again, and remove ourselves if // we happen to! { var index = insertIndex.? + 1; while (index < openSet.items.len) : (index += 1) { const item = openSet.items[index]; if (item == neighbour) { const removed = openSet.orderedRemove(index); break; } } } } } fn compare(costs: std.ArrayList(u32), a: usize, b: usize) bool { return costs.items[a] < costs.items[b]; }
src/day15.zig
const Coff = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const log = std.log.scoped(.coff); allocator: Allocator, file: std.fs.File, name: []const u8, header: Header, section_table: std.ArrayListUnmanaged(SectionHeader) = .{}, sections: std.ArrayListUnmanaged(Section) = .{}, relocations: std.AutoHashMapUnmanaged(u16, []const Relocation) = .{}, symbols: std.ArrayListUnmanaged(Symbol) = .{}, string_table: []const u8, pub const Header = struct { machine: std.coff.MachineType, number_of_sections: u16, timedate_stamp: u32, pointer_to_symbol_table: u32, number_of_symbols: u32, size_of_optional_header: u16, characteristics: u16, }; pub const Section = struct { ptr: [*]const u8, size: u32, fn slice(section: Section) []const u8 { return section.ptr[0..section.size]; } fn fromSlice(buf: []const u8) Section { return .{ .ptr = buf.ptr, .size = @intCast(u32, buf.len) }; } }; pub const Relocation = struct { virtual_address: u32, symbol_table_index: u32, tag: u16, }; pub const Symbol = struct { name: [8]u8, value: u32, section_number: i16, sym_type: u16, storage_class: Class, number_aux_symbols: u8, pub fn getName(symbol: Symbol, coff: *const Coff) []const u8 { if (std.mem.eql(u8, symbol.name[0..4], &.{ 0, 0, 0, 0 })) { const offset = std.mem.readIntLittle(u32, symbol.name[4..8]); return coff.getString(offset); } return std.mem.sliceTo(&symbol.name, 0); } pub fn complexType(symbol: Symbol) ComplexType { return @intToEnum(ComplexType, @truncate(u8, symbol.sym_type >> 4)); } pub fn baseType(symbol: Symbol) BaseType { return @intToEnum(BaseType, @truncate(u8, symbol.sym_type >> 8)); } const ComplexType = enum(u8) { ///No derived type; the symbol is a simple scalar variable. IMAGE_SYM_DTYPE_NULL = 0, ///The symbol is a pointer to base type. IMAGE_SYM_DTYPE_POINTER = 1, ///The symbol is a function that returns a base type. IMAGE_SYM_DTYPE_FUNCTION = 2, ///The symbol is an array of base type. IMAGE_SYM_DTYPE_ARRAY = 3, }; pub const BaseType = enum(u8) { ///No type information or unknown base type. Microsoft tools use this setting IMAGE_SYM_TYPE_NULL = 0, ///No valid type; used with void pointers and functions IMAGE_SYM_TYPE_VOID = 1, ///A character (signed byte) IMAGE_SYM_TYPE_CHAR = 2, ///A 2-byte signed integer IMAGE_SYM_TYPE_SHORT = 3, ///A natural integer type (normally 4 bytes in Windows) IMAGE_SYM_TYPE_INT = 4, ///A 4-byte signed integer IMAGE_SYM_TYPE_LONG = 5, ///A 4-byte floating-point number IMAGE_SYM_TYPE_FLOAT = 6, ///An 8-byte floating-point number IMAGE_SYM_TYPE_DOUBLE = 7, ///A structure IMAGE_SYM_TYPE_STRUCT = 8, ///A union IMAGE_SYM_TYPE_UNION = 9, ///An enumerated type IMAGE_SYM_TYPE_ENUM = 10, ///A member of enumeration (a specific value) IMAGE_SYM_TYPE_MOE = 11, ///A byte; unsigned 1-byte integer IMAGE_SYM_TYPE_BYTE = 12, ///A word; unsigned 2-byte integer IMAGE_SYM_TYPE_WORD = 13, ///An unsigned integer of natural size (normally, 4 bytes) IMAGE_SYM_TYPE_UINT = 14, ///An unsigned 4-byte integer IMAGE_SYM_TYPE_DWORD = 15, }; pub const Class = enum(u8) { ///No assigned storage class. IMAGE_SYM_CLASS_NULL = 0, ///The automatic (stack) variable. The Value field specifies the stack frame offset. IMAGE_SYM_CLASS_AUTOMATIC = 1, ///A value that Microsoft tools use for external symbols. The Value field indicates the size if the section number is IMAGE_SYM_UNDEFINED (0). If the section number is not zero, then the Value field specifies the offset within the section. IMAGE_SYM_CLASS_EXTERNAL = 2, ///The offset of the symbol within the section. If the Value field is zero, then the symbol represents a section name. IMAGE_SYM_CLASS_STATIC = 3, ///A register variable. The Value field specifies the register number. IMAGE_SYM_CLASS_REGISTER = 4, ///A symbol that is defined externally. IMAGE_SYM_CLASS_EXTERNAL_DEF = 5, ///A code label that is defined within the module. The Value field specifies the offset of the symbol within the section. IMAGE_SYM_CLASS_LABEL = 6, ///A reference to a code label that is not defined. IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7, ///The structure member. The Value field specifies the n th member. IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8, ///A formal argument (parameter) of a function. The Value field specifies the n th argument. IMAGE_SYM_CLASS_ARGUMENT = 9, ///The structure tag-name entry. IMAGE_SYM_CLASS_STRUCT_TAG = 10, ///A union member. The Value field specifies the n th member. IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11, ///The Union tag-name entry. IMAGE_SYM_CLASS_UNION_TAG = 12, ///A Typedef entry. IMAGE_SYM_CLASS_TYPE_DEFINITION = 13, ///A static data declaration. IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14, ///An enumerated type tagname entry. IMAGE_SYM_CLASS_ENUM_TAG = 15, ///A member of an enumeration. The Value field specifies the n th member. IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16, ///A register parameter. IMAGE_SYM_CLASS_REGISTER_PARAM = 17, ///A bit-field reference. The Value field specifies the n th bit in the bit field. IMAGE_SYM_CLASS_BIT_FIELD = 18, ///A .bb (beginning of block) or .eb (end of block) record. The Value field is the relocatable address of the code location. IMAGE_SYM_CLASS_BLOCK = 100, ///A value that Microsoft tools use for symbol records that define the extent of a function: begin function (.bf ), end function ( .ef ), and lines in function ( .lf ). For .lf records, the Value field gives the number of source lines in the function. For .ef records, the Value field gives the size of the function code. IMAGE_SYM_CLASS_FUNCTION = 101, ///An end-of-structure entry. IMAGE_SYM_CLASS_END_OF_STRUCT = 102, ///A value that Microsoft tools, as well as traditional COFF format, use for the source-file symbol record. The symbol is followed by auxiliary records that name the file. IMAGE_SYM_CLASS_FILE = 103, ///A definition of a section (Microsoft tools use STATIC storage class instead). IMAGE_SYM_CLASS_SECTION = 104, ///A weak external. For more information, see Auxiliary Format 3: Weak Externals. IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105, ///A CLR token symbol. The name is an ASCII string that consists of the hexadecimal value of the token. For more information, see CLR Token Definition (Object Only). IMAGE_SYM_CLASS_CLR_TOKEN = 107, //A special symbol that represents the end of function, for debugging purposes. IMAGE_SYM_CLASS_END_OF_FUNCTION = 0xFF, }; }; pub const SectionHeader = struct { name: [8]u8, virtual_size: u32, virtual_address: u32, size_of_raw_data: u32, pointer_to_raw_data: u32, pointer_to_relocations: u32, pointer_to_line_numbers: u32, number_of_relocations: u16, number_of_line_numbers: u16, characteristics: u32, pub fn getName(header: SectionHeader, coff: *const Coff) []const u8 { // when name starts with a slash '/', the name of the section // contains a long name. The following bytes contain the offset into // the string table if (header.name[0] == '/') { const offset_len = std.mem.indexOfScalar(u8, header.name[1..], 0) orelse 7; const offset = std.fmt.parseInt(u32, header.name[1..][0..offset_len], 10) catch return ""; return coff.getString(offset); } return std.mem.sliceTo(&header.name, 0); } /// Returns the alignment for the section in bytes pub fn alignment(header: SectionHeader) u32 { if (header.characteristics & flags.IMAGE_SCN_ALIGN_1BYTES != 0) return 1; if (header.characteristics & flags.IMAGE_SCN_ALIGN_2BYTES != 0) return 2; if (header.characteristics & flags.IMAGE_SCN_ALIGN_4BYTES != 0) return 4; if (header.characteristics & flags.IMAGE_SCN_ALIGN_8BYTES != 0) return 8; if (header.characteristics & flags.IMAGE_SCN_ALIGN_16BYTES != 0) return 16; if (header.characteristics & flags.IMAGE_SCN_ALIGN_32BYTES != 0) return 32; if (header.characteristics & flags.IMAGE_SCN_ALIGN_64BYTES != 0) return 64; if (header.characteristics & flags.IMAGE_SCN_ALIGN_128BYTES != 0) return 128; if (header.characteristics & flags.IMAGE_SCN_ALIGN_256BYTES != 0) return 256; if (header.characteristics & flags.IMAGE_SCN_ALIGN_512BYTES != 0) return 512; if (header.characteristics & flags.IMAGE_SCN_ALIGN_1024BYTES != 0) return 1024; if (header.characteristics & flags.IMAGE_SCN_ALIGN_2048BYTES != 0) return 2048; if (header.characteristics & flags.IMAGE_SCN_ALIGN_4096BYTES != 0) return 4096; if (header.characteristics & flags.IMAGE_SCN_ALIGN_8192BYTES != 0) return 8192; unreachable; } pub const flags = struct { /// The section should not be padded to the next boundary. /// This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. /// This is valid only for object files. pub const IMAGE_SCN_TYPE_NO_PAD = 0x00000008; /// The section contains executable code. pub const IMAGE_SCN_CNT_CODE = 0x00000020; /// The section contains initialized data. pub const IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040; /// The section contains uninitialized data. pub const IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080; /// Reserved for future use. pub const IMAGE_SCN_LNK_OTHER = 0x00000100; /// The section contains comments or other information. The .drectve section has this type. This is valid for object files only. pub const IMAGE_SCN_LNK_INFO = 0x00000200; /// The section will not become part of the image. This is valid only for object files. pub const IMAGE_SCN_LNK_REMOVE = 0x00000800; /// The section contains COMDAT data. For more information, see COMDAT Sections (Object Only). This is valid only for object files. pub const IMAGE_SCN_LNK_COMDAT = 0x00001000; /// The section contains data referenced through the global pointer (GP). pub const IMAGE_SCN_GPREL = 0x00008000; /// Reserved for future use. pub const IMAGE_SCN_MEM_PURGEABLE = 0x00020000; /// Reserved for future use. pub const IMAGE_SCN_MEM_16BIT = 0x00020000; /// Reserved for future use. pub const IMAGE_SCN_MEM_LOCKED = 0x00040000; /// Reserved for future use. pub const IMAGE_SCN_MEM_PRELOAD = 0x00080000; /// Align data on a 1-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_1BYTES = 0x00100000; /// Align data on a 2-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_2BYTES = 0x00200000; /// Align data on a 4-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_4BYTES = 0x00300000; /// Align data on an 8-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_8BYTES = 0x00400000; /// Align data on a 16-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_16BYTES = 0x00500000; /// Align data on a 32-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_32BYTES = 0x00600000; /// Align data on a 64-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_64BYTES = 0x00700000; /// Align data on a 128-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_128BYTES = 0x00800000; /// Align data on a 256-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_256BYTES = 0x00900000; /// Align data on a 512-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_512BYTES = 0x00A00000; /// Align data on a 1024-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000; /// Align data on a 2048-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000; /// Align data on a 4096-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000; /// Align data on an 8192-byte boundary. Valid only for object files. pub const IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000; /// The section contains extended relocations. pub const IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000; /// The section can be discarded as needed. pub const IMAGE_SCN_MEM_DISCARDABLE = 0x02000000; /// The section cannot be cached. pub const IMAGE_SCN_MEM_NOT_CACHED = 0x04000000; /// The section is not pageable. pub const IMAGE_SCN_MEM_NOT_PAGED = 0x08000000; /// The section can be shared in memory. pub const IMAGE_SCN_MEM_SHARED = 0x10000000; /// The section can be executed as code. pub const IMAGE_SCN_MEM_EXECUTE = 0x20000000; /// The section can be read. pub const IMAGE_SCN_MEM_READ = 0x40000000; /// The section can be written to. pub const IMAGE_SCN_MEM_WRITE = 0x80000000; }; /// When a section name contains the symbol `$`, it is considered /// a grouped section. e.g. a section named `.text$X` contributes /// to the `.text` section within the image. /// The character after the dollar sign, indicates the order when /// multiple (same prefix) sections were found. pub fn isGrouped(header: SectionHeader) bool { return std.mem.indexOfScalar(u8, &header.name, '$') != null; } }; /// Initializes a new `Coff` instance. The file will not be parsed yet. pub fn init(allocator: Allocator, file: std.fs.File, path: []const u8) Coff { return .{ .allocator = allocator, .file = file, .name = path, .header = undefined, .string_table = undefined, }; } /// Frees all resources of the `Coff` file. This does not close the file handle. pub fn deinit(coff: *Coff) void { const gpa = coff.allocator; coff.section_table.deinit(gpa); for (coff.sections.items) |section, sec_index| { gpa.free(section.slice()); if (coff.relocations.get(@intCast(u16, sec_index))) |relocs| { gpa.free(relocs); } } coff.sections.deinit(gpa); coff.relocations.deinit(gpa); coff.* = undefined; } /// Parses the Coff file in its entirety and allocates any /// resources required. Memory is owned by the `coff` instance. pub fn parse(coff: *Coff) !void { const reader = coff.file.reader(); const machine = std.meta.intToEnum(std.coff.MachineType, try reader.readIntLittle(u16)) catch { log.err("Given file {s} is not a coff file or contains an unknown machine", .{coff.name}); return error.UnknownMachine; }; coff.header = .{ .machine = machine, .number_of_sections = try reader.readIntLittle(u16), .timedate_stamp = try reader.readIntLittle(u32), .pointer_to_symbol_table = try reader.readIntLittle(u32), .number_of_symbols = try reader.readIntLittle(u32), .size_of_optional_header = try reader.readIntLittle(u16), .characteristics = try reader.readIntLittle(u16), }; // When the object file contains an optional header, we simply // skip it as object files are not interested in this data. if (coff.header.size_of_optional_header != 0) { try coff.file.seekBy(@intCast(i64, coff.header.size_of_optional_header)); } try parseStringTable(coff); try parseSectionTable(coff); try parseSectionData(coff); try parseRelocations(coff); try parseSymbolTable(coff); } fn parseStringTable(coff: *Coff) !void { const reader = coff.file.reader(); const current_pos = try coff.file.getPos(); try coff.file.seekTo(coff.stringTableOffset()); const size = try reader.readIntLittle(u32); const buffer = try coff.allocator.alloc(u8, size - 4); // account for 4 bytes of size field itself errdefer coff.allocator.free(buffer); try reader.readNoEof(buffer); coff.string_table = buffer; try coff.file.seekTo(current_pos); } fn getString(coff: *const Coff, offset: u32) []const u8 { const str = @ptrCast([*:0]const u8, coff.string_table.ptr + offset); return std.mem.sliceTo(str, 0); } fn parseSectionTable(coff: *Coff) !void { if (coff.header.number_of_sections == 0) return; try coff.section_table.ensureUnusedCapacity(coff.allocator, coff.header.number_of_sections); const reader = coff.file.reader(); var index: u16 = 0; while (index < coff.header.number_of_sections) : (index += 1) { const sec_header = coff.section_table.addOneAssumeCapacity(); var name: [8]u8 = undefined; try reader.readNoEof(&name); sec_header.* = .{ .name = name, .virtual_size = try reader.readIntLittle(u32), .virtual_address = try reader.readIntLittle(u32), .size_of_raw_data = try reader.readIntLittle(u32), .pointer_to_raw_data = try reader.readIntLittle(u32), .pointer_to_relocations = try reader.readIntLittle(u32), .pointer_to_line_numbers = try reader.readIntLittle(u32), .number_of_relocations = try reader.readIntLittle(u16), .number_of_line_numbers = try reader.readIntLittle(u16), .characteristics = try reader.readIntLittle(u32), }; log.debug("Parsed section header: '{s}'", .{std.mem.sliceTo(&name, 0)}); if (sec_header.virtual_size != 0) { log.err("Invalid object file. Expected virtual size '0' but found '{d}'", .{sec_header.virtual_size}); return error.InvalidVirtualSize; } } } fn stringTableOffset(coff: Coff) u32 { return coff.header.pointer_to_symbol_table + (coff.header.number_of_symbols * 18); } /// Parses a string from the string table found at given `offset`. /// Populates the given `buffer` with the string and returns the length. fn parseStringFromOffset(coff: *Coff, offset: u32, buf: []u8) !usize { std.debug.assert(buf.len != 0); const current_pos = try coff.file.getPos(); try coff.file.seekTo(coff.stringTableOffset() + offset); const str = (try coff.file.reader().readUntilDelimiterOrEof(buf, 0)) orelse ""; try coff.file.seekTo(current_pos); return str.len; } /// Parses all section data of the coff file. /// Asserts section headers are known. fn parseSectionData(coff: *Coff) !void { if (coff.header.number_of_sections == 0) return; std.debug.assert(coff.section_table.items.len == coff.header.number_of_sections); try coff.sections.ensureUnusedCapacity(coff.allocator, coff.header.number_of_sections); const reader = coff.file.reader(); for (coff.section_table.items) |sec_header| { try coff.file.seekTo(sec_header.pointer_to_raw_data); const buf = try coff.allocator.alloc(u8, sec_header.virtual_size); try reader.readNoEof(buf); coff.sections.appendAssumeCapacity(Section.fromSlice(buf)); } } fn parseRelocations(coff: *Coff) !void { if (coff.header.number_of_sections == 0) return; const reader = coff.file.reader(); for (coff.section_table.items) |sec_header, index| { if (sec_header.number_of_relocations == 0) continue; const sec_index = @intCast(u16, index); const relocations = try coff.allocator.alloc(Relocation, sec_header.number_of_relocations); errdefer coff.allocator.free(relocations); try coff.file.seekTo(sec_header.pointer_to_relocations); for (relocations) |*reloc| { reloc.* = .{ .virtual_address = try reader.readIntLittle(u32), .symbol_table_index = try reader.readIntLittle(u32), .tag = try reader.readIntLittle(u16), }; } try coff.relocations.putNoClobber(coff.allocator, sec_index, relocations); } } fn parseSymbolTable(coff: *Coff) !void { if (coff.header.number_of_symbols == 0) return; try coff.symbols.ensureUnusedCapacity(coff.allocator, coff.header.number_of_symbols); try coff.file.seekTo(coff.header.pointer_to_symbol_table); const reader = coff.file.reader(); var index: u32 = 0; while (index < coff.header.number_of_symbols) : (index += 1) { var name: [8]u8 = undefined; try reader.readNoEof(&name); const sym: Symbol = .{ .name = name, .value = try reader.readIntLittle(u32), .section_number = try reader.readIntLittle(i16), .sym_type = try reader.readIntLittle(u16), .storage_class = @intToEnum(Symbol.Class, try reader.readByte()), .number_aux_symbols = try reader.readByte(), }; coff.symbols.appendAssumeCapacity(sym); } }
src/Coff.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const json = std.json; const StringHashMap = std.StringHashMap; //; const c = @import("c.zig"); const math = @import("math.zig"); usingnamespace math; //; // glfw parser thing // parse the base64 buffers to u8 buffer // for default 3d utils // have 3d mesh // materials // animations // skeletal and morph // skeletal: vertex shader // morph: also in vertex shader? // default animated shader // TODO uri type? // get rid of all float cast and int cast in here and just use i64 and f64? //; fn jsonValueDeepClone(allocator: *Allocator, j: json.Value) Allocator.Error!json.Value { switch (j) { .Null => return json.Value.Null, .Bool => |val| return json.Value{ .Bool = val }, .Integer => |val| return json.Value{ .Integer = val }, .Float => |val| return json.Value{ .Float = val }, .String => |val| return json.Value{ .String = try allocator.dupe(u8, val) }, .Array => |val| { var arr = try json.Array.initCapacity(allocator, val.items.len); for (val.items) |i| { try arr.append(try jsonValueDeepClone(allocator, i)); } return json.Value{ .Array = arr }; }, .Object => |val| { var ht = json.ObjectMap.init(allocator); var iter = val.iterator(); while (iter.next()) |entry| { try ht.put(entry.key, try jsonValueDeepClone(allocator, entry.value)); } return json.Value{ .Object = ht }; }, } } fn jsonValueFreeClone(allocator: *Allocator, j: *json.Value) void { switch (j.*) { .String => |val| allocator.free(val), .Array => |*val| { for (val.items) |*i| { jsonValueFreeClone(allocator, i); } val.deinit(); }, .Object => |*val| { var iter = val.iterator(); while (iter.next()) |entry| { jsonValueFreeClone(allocator, &entry.value); } val.deinit(); }, else => {}, } } fn jsonValueToFloat(comptime T: type, j: json.Value) T { return switch (j) { .Float => |f| @floatCast(T, f), .Integer => |i| @intToFloat(T, i), // TODO this is probably okay as unreachable else => unreachable, }; } //; pub const Accessor = struct { pub const ComponentType = enum(c.GLenum) { Byte = c.GL_BYTE, UnsignedByte = c.GL_UNSIGNED_BYTE, Short = c.GL_SHORT, UnsignedShort = c.GL_UNSIGNED_SHORT, UnsignedInt = c.GL_UNSIGNED_INT, Float = c.GL_FLOAT, }; pub const DataType = enum { Scalar, Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, }; buffer_view: ?usize = null, byte_offset: ?usize = 0, component_type: ComponentType, normalized: ?bool = false, count: usize, data_type: DataType, // TODO min max // TODO sparse name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; // TODO animation pub const Asset = struct { copyright: ?[]u8 = null, generator: ?[]u8 = null, version: []const u8, min_version: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Buffer = struct { uri: ?[]u8 = null, byte_length: usize, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const BufferView = struct { pub const Target = enum(c.GLenum) { ArrayBuffer = c.GL_ARRAY_BUFFER, ElementArrayBuffer = c.GL_ELEMENT_ARRAY_BUFFER, }; buffer: usize, byte_offset: ?usize = 0, byte_length: usize, byte_stride: ?usize = null, target: ?Target = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Camera = struct { pub const CameraType = enum { Orthographic, Perspective, }; orthographic: ?Orthographic = null, perspective: ?Perspective = null, camera_type: ?CameraType = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; // TODO channel pub const Extensions = json.Value; pub const Extras = json.Value; pub const Image = struct { pub const MimeType = enum { JPEG, PNG, }; uri: ?[]u8 = null, buffer_view: ?usize = null, mime_type: ?MimeType = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; // sparse indices pub const Material = struct { pub const AlphaMode = enum { Opaque, Mask, Blend, }; pbr_metallic_roughness: ?PbrMetallicRoughness = .{}, normal_texture: ?NormalTextureInfo = null, occlusion_texture: ?OcclusionTextureInfo = null, emissive_texture: ?TextureInfo = null, emissive_factor: ?Color = Color.black(), alpha_mode: ?AlphaMode = .Opaque, alpha_cutoff: ?f32 = 0.5, double_sided: ?bool = false, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Mesh = struct { primitives: []Primitive, weights: ?[]f32 = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Node = struct { camera: ?usize = null, children: ?[]usize = null, // TODO skin matrix: ?Mat4 = Mat4.identity(), mesh: ?usize = null, rotation: ?Quaternion = Quaternion.identity(), scale: ?Vec3 = Vec3.one(), translation: ?Vec3 = Vec3.zero(), // TODO weights name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const NormalTextureInfo = struct { index: usize, tex_coord: ?usize = 0, scale: ?f32 = 1, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const OcclusionTextureInfo = struct { index: usize, tex_coord: ?usize = 0, strength: ?f32 = 1, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Orthographic = struct { xmag: f32, ymag: f32, zfar: f32, znear: f32, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const PbrMetallicRoughness = struct { base_color_factor: ?Color = Color.white(), base_color_texture: ?TextureInfo = null, metallic_factor: ?f32 = 1, roughness_factor: ?f32 = 1, metallic_roughness_texture: ?TextureInfo = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Perspective = struct { aspect_ratio: ?f32 = null, yfov: f32, zfar: ?f32 = null, znear: f32, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Primitive = struct { pub const AttributeMap = StringHashMap(usize); pub const Mode = enum(c.GLenum) { Points = c.GL_POINTS, Lines = c.GL_LINES, LineLoop = c.GL_LINE_LOOP, LineStrip = c.GL_LINE_STRIP, Triangles = c.GL_TRIANGLES, TriangleStrip = c.GL_TRIANGLE_STRIP, TriangleFan = c.GL_TRIANGLE_FAN, }; attributes: AttributeMap, indices: ?usize = null, material: ?usize = null, mode: ?Mode = .Triangles, targets: ?[]AttributeMap = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Sampler = struct { pub const Filter = enum(c.GLenum) { Nearest = c.GL_NEAREST, Linear = c.GL_LINEAR, NearestMipmapNearest = c.GL_NEAREST_MIPMAP_NEAREST, LinearMipmapNearest = c.GL_LINEAR_MIPMAP_NEAREST, NearestMipmapLinear = c.GL_NEAREST_MIPMAP_LINEAR, LinearMipmapLinear = c.GL_LINEAR_MIPMAP_LINEAR, }; pub const Wrap = enum(c.GLenum) { ClampToEdge = c.GL_CLAMP_TO_EDGE, MirroredRepeat = c.GL_MIRRORED_REPEAT, Repeat = c.GL_REPEAT, }; mag_filter: ?Filter = null, min_filter: ?Filter = null, wrap_s: ?Wrap = .Repeat, wrap_t: ?Wrap = .Repeat, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const Scene = struct { nodes: ?[]usize = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; // TODO skin // TODO sparse // TODO target pub const Texture = struct { source: ?usize = null, sampler: ?usize = null, name: ?[]u8 = null, extensions: ?Extensions = null, extras: ?Extras = null, }; pub const TextureInfo = struct { index: usize, tex_coord: ?usize = 0, extensions: ?Extensions = null, extras: ?Extras = null, }; // TODO sparse values //; pub const GlTF = struct { extensions_used: ?[][]u8 = null, extensions_required: ?[][]u8 = null, accessors: ?[]Accessor = null, // animations asset: Asset, buffers: ?[]Buffer = null, buffer_views: ?[]BufferView = null, cameras: ?[]Camera = null, images: ?[]Image = null, materials: ?[]Material = null, meshes: ?[]Mesh = null, nodes: ?[]Node = null, samplers: ?[]Sampler = null, scene: ?usize = null, scenes: ?[]Scene = null, // skins textures: ?[]Texture = null, extensions: ?Extensions = null, extras: ?Extras = null, }; //; pub const GlTF_Parser = struct { const Self = @This(); pub const Error = error{ AssetInfoNotFound, NoVersionSpecified, GlTF_VersionNotSupported, InvalidAccessor, InvalidBuffer, InvalidBufferView, InvalidCamera, InvalidImage, InvalidMaterial, InvalidMesh, }; allocator: *Allocator, parser: json.Parser, pub fn init(allocator: *Allocator) Self { return .{ .allocator = allocator, .parser = json.Parser.init(allocator, false), }; } pub fn deinit(self: *Self) void { self.parser.deinit(); } //; pub fn parseFromString(self: *Self, input: []const u8) !GlTF { var j = try self.parser.parse(input); defer j.deinit(); const root = j.root; // TODO better error handling for if json objects arent the right type? // not a big deal as long as user cant supply thier own assets const j_asset = root.Object.get("asset") orelse return Error.AssetInfoNotFound; const version = j_asset.Object.get("version") orelse return Error.NoVersionSpecified; if (!std.mem.eql(u8, version.String, "2.0")) return Error.GlTF_VersionNotSupported; var ret = GlTF{ .asset = .{ .version = try self.allocator.dupe(u8, version.String), }, }; // TODO if (root.Object.get("extensionsUsed")) |exts| {} if (root.Object.get("extensionsRequired")) |exts| {} try parseAsset(self, &ret, j_asset); if (root.Object.get("accessors")) |jv| { try self.parseAccessors(&ret, jv); } if (root.Object.get("buffers")) |jv| { try self.parseBuffers(&ret, jv); } if (root.Object.get("bufferViews")) |jv| { try self.parseBufferViews(&ret, jv); } if (root.Object.get("cameras")) |jv| { try self.parseCameras(&ret, jv); } if (root.Object.get("images")) |jv| { try self.parseImages(&ret, jv); } if (root.Object.get("materials")) |jv| { try self.parseMaterials(&ret, jv); } if (root.Object.get("meshes")) |jv| { try self.parseMeshes(&ret, jv); } if (root.Object.get("nodes")) |jv| { try self.parseNodes(&ret, jv); } if (root.Object.get("samplers")) |jv| { try self.parseSamplers(&ret, jv); } if (root.Object.get("scene")) |jv| { ret.scene = @intCast(usize, jv.Integer); } if (root.Object.get("scenes")) |jv| { try self.parseScenes(&ret, jv); } if (root.Object.get("textures")) |jv| { try self.parseTextures(&ret, jv); } if (root.Object.get("extensions")) |jv| { ret.extensions = try jsonValueDeepClone(self.allocator, jv); } if (root.Object.get("extras")) |jv| { ret.extras = try jsonValueDeepClone(self.allocator, jv); } return ret; } pub fn freeParse(self: *Self, gltf: *GlTF) void { self.freeAsset(gltf); self.freeAccessors(gltf); self.freeBuffers(gltf); self.freeBufferViews(gltf); self.freeCameras(gltf); self.freeImages(gltf); self.freeMaterials(gltf); self.freeMeshes(gltf); self.freeNodes(gltf); self.freeSamplers(gltf); self.freeScenes(gltf); self.freeTextures(gltf); if (gltf.extensions) |*ext| jsonValueFreeClone(self.allocator, ext); if (gltf.extras) |*ext| jsonValueFreeClone(self.allocator, ext); } //; // TODO take *Asset not *GlTF fn parseAsset(self: *Self, gltf: *GlTF, j_val: json.Value) !void { // TODO handle memory leaks if (j_val.Object.get("copyright")) |jv| { gltf.asset.copyright = try self.allocator.dupe(u8, jv.String); } if (j_val.Object.get("generator")) |jv| { gltf.asset.generator = try self.allocator.dupe(u8, jv.String); } if (j_val.Object.get("minVersion")) |jv| { gltf.asset.min_version = try self.allocator.dupe(u8, jv.String); } if (j_val.Object.get("extensions")) |jv| { gltf.asset.extensions = try jsonValueDeepClone(self.allocator, jv); } if (j_val.Object.get("extras")) |jv| { gltf.asset.extras = try jsonValueDeepClone(self.allocator, jv); } } fn freeAsset(self: *Self, gltf: *GlTF) void { self.allocator.free(gltf.asset.version); if (gltf.asset.copyright) |str| self.allocator.free(str); if (gltf.asset.generator) |str| self.allocator.free(str); if (gltf.asset.min_version) |str| self.allocator.free(str); if (gltf.asset.extensions) |*ext| jsonValueFreeClone(self.allocator, ext); if (gltf.asset.extras) |*ext| jsonValueFreeClone(self.allocator, ext); } fn parseAccessors(self: *Self, gltf: *GlTF, j_val: json.Value) !void { const len = j_val.Array.items.len; gltf.accessors = try self.allocator.alloc(Accessor, len); for (j_val.Array.items) |jv, i| { const gl_type = jv.Object.get("componentType") orelse return Error.InvalidAccessor; const count = jv.Object.get("count") orelse return Error.InvalidAccessor; const data_type_str = (jv.Object.get("type") orelse return Error.InvalidAccessor).String; const data_type = if (std.mem.eql(u8, data_type_str, "SCALAR")) blk: { break :blk Accessor.DataType.Scalar; } else if (std.mem.eql(u8, data_type_str, "VEC2")) blk: { break :blk Accessor.DataType.Vec2; } else if (std.mem.eql(u8, data_type_str, "VEC3")) blk: { break :blk Accessor.DataType.Vec3; } else if (std.mem.eql(u8, data_type_str, "VEC4")) blk: { break :blk Accessor.DataType.Vec4; } else if (std.mem.eql(u8, data_type_str, "MAT2")) blk: { break :blk Accessor.DataType.Mat2; } else if (std.mem.eql(u8, data_type_str, "MAT3")) blk: { break :blk Accessor.DataType.Mat3; } else if (std.mem.eql(u8, data_type_str, "MAT4")) blk: { break :blk Accessor.DataType.Mat4; } else { return Error.InvalidAccessor; }; var curr = &gltf.accessors.?[i]; curr.* = .{ .component_type = @intToEnum(Accessor.ComponentType, @intCast(c.GLenum, gl_type.Integer)), .count = @intCast(usize, count.Integer), .data_type = data_type, }; if (jv.Object.get("bufferView")) |jv_| { curr.buffer_view = @intCast(usize, jv_.Integer); } if (jv.Object.get("byteOffset")) |jv_| { curr.byte_offset = @intCast(usize, jv_.Integer); } if (jv.Object.get("normalized")) |jv_| { curr.normalized = jv_.Bool; } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeAccessors(self: *Self, gltf: *GlTF) void { if (gltf.accessors) |objs| { for (objs) |*obj| { if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseBuffers(self: *Self, gltf: *GlTF, j_val: json.Value) !void { const len = j_val.Array.items.len; gltf.buffers = try self.allocator.alloc(Buffer, len); for (j_val.Array.items) |jv, i| { const byte_length = jv.Object.get("byteLength") orelse return Error.InvalidBuffer; var curr = &gltf.buffers.?[i]; curr.* = .{ .byte_length = @intCast(usize, byte_length.Integer), }; if (jv.Object.get("uri")) |jv_| { curr.uri = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeBuffers(self: *Self, gltf: *GlTF) void { if (gltf.buffers) |objs| { for (objs) |*obj| { if (obj.uri) |uri| self.allocator.free(uri); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*ext| jsonValueFreeClone(self.allocator, ext); if (obj.extras) |*ext| jsonValueFreeClone(self.allocator, ext); } self.allocator.free(objs); } } fn parseBufferViews(self: *Self, gltf: *GlTF, j_val: json.Value) !void { const len = j_val.Array.items.len; gltf.buffer_views = try self.allocator.alloc(BufferView, len); for (j_val.Array.items) |jv, i| { const buffer = jv.Object.get("buffer") orelse return Error.InvalidBufferView; const byte_length = jv.Object.get("byteLength") orelse return Error.InvalidBufferView; var curr = &gltf.buffer_views.?[i]; curr.* = .{ .buffer = @intCast(usize, buffer.Integer), .byte_length = @intCast(usize, byte_length.Integer), }; if (jv.Object.get("byteOffset")) |jv_| { curr.byte_offset = @intCast(usize, jv_.Integer); } if (jv.Object.get("byteStride")) |jv_| { curr.byte_stride = @intCast(usize, jv_.Integer); } if (jv.Object.get("target")) |jv_| { curr.target = @intToEnum(BufferView.Target, @intCast(c.GLenum, jv_.Integer)); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeBufferViews(self: *Self, gltf: *GlTF) void { if (gltf.buffer_views) |objs| { for (objs) |*obj| { if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseCameras(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.cameras = try self.allocator.alloc(Camera, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.cameras.?[i]; curr.* = .{}; if (jv.Object.get("type")) |jv_| { const str = jv_.String; if (std.mem.eql(u8, str, "orthographic")) { curr.camera_type = .Orthographic; } else if (std.mem.eql(u8, str, "perspective")) { curr.camera_type = .Perspective; } else { return Error.InvalidCamera; } } if (jv.Object.get("orthographic")) |jv_| { try self.parseOrthographic(&curr.orthographic, jv_); } if (jv.Object.get("perspective")) |jv_| { try self.parsePerspective(&curr.perspective, jv_); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeCameras(self: *Self, gltf: *GlTF) void { if (gltf.cameras) |objs| { for (objs) |*obj| { if (obj.orthographic) |*data| self.freeOrthographic(data); if (obj.perspective) |*data| self.freePerspective(data); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseImages(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.images = try self.allocator.alloc(Image, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.images.?[i]; curr.* = .{}; if (jv.Object.get("uri")) |jv_| { curr.uri = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("bufferView")) |jv_| { curr.buffer_view = @intCast(usize, jv_.Integer); } if (jv.Object.get("mimeType")) |jv_| { const str = jv_.String; if (std.mem.eql(u8, str, "image/jpeg")) { curr.mime_type = .JPEG; } else if (std.mem.eql(u8, str, "image/png")) { curr.mime_type = .PNG; } else { return Error.InvalidImage; } } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeImages(self: *Self, gltf: *GlTF) void { if (gltf.images) |objs| { for (objs) |*obj| { if (obj.uri) |uri| self.allocator.free(uri); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseMaterials(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.materials = try self.allocator.alloc(Material, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.materials.?[i]; curr.* = .{}; if (jv.Object.get("pbrMetallicRoughness")) |jv_| { try self.parsePbrMetallicRoughness(&curr.pbr_metallic_roughness, jv_); } if (jv.Object.get("normalTexture")) |jv_| { try self.parseNormalTextureInfo(&curr.normal_texture, jv_); } if (jv.Object.get("occlusionTexture")) |jv_| { try self.parseOcclusionTextureInfo(&curr.occlusion_texture, jv_); } if (jv.Object.get("emissiveTexture")) |jv_| { try self.parseTextureInfo(&curr.emissive_texture, jv_); } if (jv.Object.get("emissiveFactor")) |jv_| { curr.emissive_factor.?.r = jsonValueToFloat(f32, jv_.Array.items[0]); curr.emissive_factor.?.g = jsonValueToFloat(f32, jv_.Array.items[1]); curr.emissive_factor.?.b = jsonValueToFloat(f32, jv_.Array.items[2]); curr.emissive_factor.?.a = jsonValueToFloat(f32, jv_.Array.items[3]); } if (jv.Object.get("alphaMode")) |jv_| { if (std.mem.eql(u8, jv_.String, "OPAQUE")) { curr.alpha_mode = .Opaque; } else if (std.mem.eql(u8, jv_.String, "MASK")) { curr.alpha_mode = .Mask; } else if (std.mem.eql(u8, jv_.String, "BLEND")) { curr.alpha_mode = .Blend; } else { return Error.InvalidMaterial; } } if (jv.Object.get("alphaCutoff")) |jv_| { curr.alpha_cutoff = jsonValueToFloat(f32, jv_); } if (jv.Object.get("doubleSided")) |jv_| { curr.double_sided = jv_.Bool; } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeMaterials(self: *Self, gltf: *GlTF) void { if (gltf.materials) |objs| { for (objs) |*obj| { if (obj.pbr_metallic_roughness) |*pbr| self.freePbrMetallicRoughness(pbr); if (obj.normal_texture) |*nti| self.freeNormalTextureInfo(nti); if (obj.occlusion_texture) |*oti| self.freeOcclusionTextureInfo(oti); if (obj.emissive_texture) |*eti| self.freeTextureInfo(eti); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseMeshes(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.meshes = try self.allocator.alloc(Mesh, len); for (j_array.Array.items) |jv, i| { const primitives = jv.Object.get("primitives") orelse return Error.InvalidMesh; var curr = &gltf.meshes.?[i]; curr.* = .{ .primitives = try self.allocator.alloc(Primitive, primitives.Array.items.len), }; for (primitives.Array.items) |jv_, pi| { try self.parsePrimitive(&curr.primitives[pi], jv_); } if (jv.Object.get("weights")) |jv_| { curr.weights = try self.allocator.alloc(f32, jv_.Array.items.len); for (jv_.Array.items) |weight, wi| { curr.weights.?[wi] = jsonValueToFloat(f32, weight); } } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeMeshes(self: *Self, gltf: *GlTF) void { if (gltf.meshes) |objs| { for (objs) |*obj| { for (obj.primitives) |*p| { self.freePrimitive(p); self.allocator.free(obj.primitives); } if (obj.weights) |weights| self.allocator.free(weights); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseNodes(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.nodes = try self.allocator.alloc(Node, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.nodes.?[i]; curr.* = .{}; if (jv.Object.get("camera")) |jv_| { curr.camera = @intCast(usize, jv_.Integer); } if (jv.Object.get("children")) |jv_| { curr.children = try self.allocator.alloc(usize, jv_.Array.items.len); for (jv_.Array.items) |jv__, ci| { curr.children.?[ci] = @intCast(usize, jv__.Integer); } } if (jv.Object.get("matrix")) |jv_| { curr.matrix = Mat4.identity(); for (jv_.Array.items) |item, ai| { const y = ai % 4; const x = ai / 4; curr.matrix.?.data[y][x] = jsonValueToFloat(f32, item); } } if (jv.Object.get("mesh")) |jv_| { curr.mesh = @intCast(usize, jv_.Integer); } if (jv.Object.get("rotation")) |jv_| { curr.rotation = Quaternion.identity(); curr.rotation.?.x = jsonValueToFloat(f32, jv_.Array.items[0]); curr.rotation.?.y = jsonValueToFloat(f32, jv_.Array.items[1]); curr.rotation.?.z = jsonValueToFloat(f32, jv_.Array.items[2]); curr.rotation.?.w = jsonValueToFloat(f32, jv_.Array.items[3]); } if (jv.Object.get("scale")) |jv_| { curr.scale = Vec3.one(); curr.scale.?.x = jsonValueToFloat(f32, jv_.Array.items[0]); curr.scale.?.y = jsonValueToFloat(f32, jv_.Array.items[1]); curr.scale.?.z = jsonValueToFloat(f32, jv_.Array.items[2]); } if (jv.Object.get("translation")) |jv_| { curr.translation = Vec3.zero(); curr.translation.?.x = jsonValueToFloat(f32, jv_.Array.items[0]); curr.translation.?.y = jsonValueToFloat(f32, jv_.Array.items[1]); curr.translation.?.z = jsonValueToFloat(f32, jv_.Array.items[2]); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeNodes(self: *Self, gltf: *GlTF) void { if (gltf.nodes) |objs| { for (objs) |*obj| { if (obj.children) |chl| self.allocator.free(chl); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseNormalTextureInfo(self: *Self, data: *?NormalTextureInfo, jv: json.Value) !void { const index = jv.Object.get("index") orelse return Error.InvalidMaterial; data.* = .{ .index = @intCast(usize, index.Integer), }; if (jv.Object.get("texCoord")) |jv_| { data.*.?.tex_coord = @intCast(usize, jv_.Integer); } if (jv.Object.get("scale")) |jv_| { data.*.?.scale = jsonValueToFloat(f32, jv_); } if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freeNormalTextureInfo(self: *Self, data: *NormalTextureInfo) void { if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parseOcclusionTextureInfo(self: *Self, data: *?OcclusionTextureInfo, jv: json.Value) !void { const index = jv.Object.get("index") orelse return Error.InvalidMaterial; data.* = .{ .index = @intCast(usize, index.Integer), }; if (jv.Object.get("texCoord")) |jv_| { data.*.?.tex_coord = @intCast(usize, jv_.Integer); } if (jv.Object.get("strength")) |jv_| { data.*.?.strength = jsonValueToFloat(f32, jv_); } if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freeOcclusionTextureInfo(self: *Self, data: *OcclusionTextureInfo) void { if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parseOrthographic(self: *Self, data: *?Orthographic, jv: json.Value) !void { const xmag = jv.Object.get("xmag") orelse return Error.InvalidCamera; const ymag = jv.Object.get("ymag") orelse return Error.InvalidCamera; const zfar = jv.Object.get("zfar") orelse return Error.InvalidCamera; const znear = jv.Object.get("znear") orelse return Error.InvalidCamera; data.* = .{ .xmag = jsonValueToFloat(f32, xmag), .ymag = jsonValueToFloat(f32, ymag), .zfar = jsonValueToFloat(f32, zfar), .znear = jsonValueToFloat(f32, znear), }; if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freeOrthographic(self: *Self, data: *Orthographic) void { if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parsePbrMetallicRoughness(self: *Self, data: *?PbrMetallicRoughness, jv: json.Value) !void { data.* = .{}; if (jv.Object.get("baseColorFactor")) |jv_| { data.*.?.base_color_factor.?.r = jsonValueToFloat(f32, jv_.Array.items[0]); data.*.?.base_color_factor.?.g = jsonValueToFloat(f32, jv_.Array.items[1]); data.*.?.base_color_factor.?.b = jsonValueToFloat(f32, jv_.Array.items[2]); data.*.?.base_color_factor.?.a = jsonValueToFloat(f32, jv_.Array.items[3]); } if (jv.Object.get("baseColorTexture")) |jv_| { try self.parseTextureInfo(&data.*.?.base_color_texture, jv_); } if (jv.Object.get("metallicFactor")) |jv_| { data.*.?.metallic_factor = jsonValueToFloat(f32, jv_); } if (jv.Object.get("roughnessFactor")) |jv_| { data.*.?.roughness_factor = jsonValueToFloat(f32, jv_); } if (jv.Object.get("metallicRoughnessTexture")) |jv_| { try self.parseTextureInfo(&data.*.?.metallic_roughness_texture, jv_); } if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freePbrMetallicRoughness(self: *Self, data: *PbrMetallicRoughness) void { if (data.base_color_texture) |*bct| self.freeTextureInfo(bct); if (data.metallic_roughness_texture) |*mrt| self.freeTextureInfo(mrt); if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parsePerspective(self: *Self, data: *?Perspective, jv: json.Value) !void { const yfov = jv.Object.get("yfov") orelse return Error.InvalidCamera; const znear = jv.Object.get("znear") orelse return Error.InvalidCamera; data.* = .{ .yfov = jsonValueToFloat(f32, yfov), .znear = jsonValueToFloat(f32, znear), }; if (jv.Object.get("aspectRatio")) |jv_| { data.*.?.aspect_ratio = jsonValueToFloat(f32, jv_); } if (jv.Object.get("zfar")) |jv_| { data.*.?.zfar = jsonValueToFloat(f32, jv_); } if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freePerspective(self: *Self, data: *Perspective) void { if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parsePrimitive(self: *Self, data: *Primitive, jv: json.Value) !void { const attributes = jv.Object.get("attributes") orelse return Error.InvalidMesh; data.* = .{ .attributes = Primitive.AttributeMap.init(self.allocator), }; { var iter = attributes.Object.iterator(); while (iter.next()) |entry| { try data.*.attributes.put(entry.key, @intCast(usize, entry.value.Integer)); } } if (jv.Object.get("indices")) |jv_| { data.indices = @intCast(usize, jv_.Integer); } if (jv.Object.get("material")) |jv_| { data.material = @intCast(usize, jv_.Integer); } if (jv.Object.get("mode")) |jv_| { var mode: Primitive.Mode = undefined; if (std.mem.eql(u8, jv_.String, "POINTS")) { mode = .Points; } else if (std.mem.eql(u8, jv_.String, "LINES")) { mode = .Lines; } else if (std.mem.eql(u8, jv_.String, "LINE_LOOP")) { mode = .LineLoop; } else if (std.mem.eql(u8, jv_.String, "LINE_STRIP")) { mode = .LineStrip; } else if (std.mem.eql(u8, jv_.String, "TRIANGLES")) { mode = .Triangles; } else if (std.mem.eql(u8, jv_.String, "TRIANGLE_STRIP")) { mode = .TriangleStrip; } else if (std.mem.eql(u8, jv_.String, "TRIANGLE_FAN")) { mode = .TriangleFan; } else { return Error.InvalidMesh; } data.mode = mode; } if (jv.Object.get("targets")) |jv_| { var targets = try self.allocator.alloc(Primitive.AttributeMap, jv_.Array.items.len); for (jv_.Array.items) |j_target, i| { targets[i] = Primitive.AttributeMap.init(self.allocator); var iter = j_target.Object.iterator(); while (iter.next()) |entry| { try targets[i].put(entry.key, @intCast(usize, entry.value.Integer)); } } data.targets = targets; } if (jv.Object.get("extensions")) |jv_| { data.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freePrimitive(self: *Self, data: *Primitive) void { data.attributes.deinit(); if (data.targets) |targets| { for (targets) |*target| { target.deinit(); } self.allocator.free(targets); } if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } fn parseSamplers(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.samplers = try self.allocator.alloc(Sampler, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.samplers.?[i]; curr.* = .{}; if (jv.Object.get("minFilter")) |jv_| { curr.min_filter = @intToEnum(Sampler.Filter, @intCast(c.GLenum, jv_.Integer)); } if (jv.Object.get("magFilter")) |jv_| { curr.mag_filter = @intToEnum(Sampler.Filter, @intCast(c.GLenum, jv_.Integer)); } if (jv.Object.get("wrapS")) |jv_| { curr.wrap_s = @intToEnum(Sampler.Wrap, @intCast(c.GLenum, jv_.Integer)); } if (jv.Object.get("wrapT")) |jv_| { curr.wrap_t = @intToEnum(Sampler.Wrap, @intCast(c.GLenum, jv_.Integer)); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeSamplers(self: *Self, gltf: *GlTF) void { if (gltf.samplers) |objs| { for (objs) |*obj| { if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseScenes(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.scenes = try self.allocator.alloc(Scene, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.scenes.?[i]; curr.* = .{}; if (jv.Object.get("nodes")) |jv_| { curr.nodes = try self.allocator.alloc(usize, jv_.Array.items.len); for (jv_.Array.items) |item, ai| { curr.nodes.?[ai] = @intCast(usize, item.Integer); } } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeScenes(self: *Self, gltf: *GlTF) void { if (gltf.scenes) |objs| { for (objs) |*obj| { if (obj.nodes) |nodes| self.allocator.free(nodes); if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseTextures(self: *Self, gltf: *GlTF, j_array: json.Value) !void { const len = j_array.Array.items.len; gltf.textures = try self.allocator.alloc(Texture, len); for (j_array.Array.items) |jv, i| { var curr = &gltf.textures.?[i]; curr.* = .{}; if (jv.Object.get("source")) |jv_| { curr.source = @intCast(usize, jv_.Integer); } if (jv.Object.get("sampler")) |jv_| { curr.sampler = @intCast(usize, jv_.Integer); } if (jv.Object.get("name")) |jv_| { curr.name = try self.allocator.dupe(u8, jv_.String); } if (jv.Object.get("extensions")) |jv_| { curr.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { curr.extras = try jsonValueDeepClone(self.allocator, jv_); } } } fn freeTextures(self: *Self, gltf: *GlTF) void { if (gltf.textures) |objs| { for (objs) |*obj| { if (obj.name) |name| self.allocator.free(name); if (obj.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (obj.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } self.allocator.free(objs); } } fn parseTextureInfo(self: *Self, data: *?TextureInfo, jv: json.Value) !void { const index = jv.Object.get("index") orelse return Error.InvalidMaterial; data.* = .{ .index = @intCast(usize, index.Integer), }; if (jv.Object.get("texCoord")) |jv_| { data.*.?.tex_coord = @intCast(usize, jv_.Integer); } if (jv.Object.get("extensions")) |jv_| { data.*.?.extensions = try jsonValueDeepClone(self.allocator, jv_); } if (jv.Object.get("extras")) |jv_| { data.*.?.extras = try jsonValueDeepClone(self.allocator, jv_); } } fn freeTextureInfo(self: *Self, data: *TextureInfo) void { if (data.extensions) |*jv| jsonValueFreeClone(self.allocator, jv); if (data.extras) |*jv| jsonValueFreeClone(self.allocator, jv); } }; test "gltf" { const testing = std.testing; const suz = @import("content.zig").gltf.suzanne; var parser = GlTF_Parser.init(testing.allocator); defer parser.deinit(); var gltf = try parser.parseFromString(suz); defer parser.freeParse(&gltf); std.log.warn("{}", .{gltf.samplers.?[0]}); for (gltf.nodes.?) |item| { std.log.warn("\n{}\n\n", .{item}); } }
src/gltf.zig
const std = @import("std"); pub const CaseFoldMap = @import("../../components.zig").CaseFoldMap; pub const Props = @import("../../components.zig").DerivedCoreProperties; pub const Cats = @import("../../components.zig").DerivedGeneralCategory; pub const LowerMap = @import("../../components.zig").LowerMap; pub const TitleMap = @import("../../components.zig").TitleMap; pub const UpperMap = @import("../../components.zig").UpperMap; const Self = @This(); /// isCased detects cased letters. pub fn isCased(cp: u21) bool { // ASCII optimization. if ((cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z')) return true; return Props.isCased(cp); } /// isLetter covers all letters in Unicode, not just ASCII. pub fn isLetter(cp: u21) bool { // ASCII optimization. if ((cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z')) return true; return Cats.isLowercaseLetter(cp) or Cats.isModifierLetter(cp) or Cats.isOtherLetter(cp) or Cats.isTitlecaseLetter(cp) or Cats.isUppercaseLetter(cp); } /// isAscii detects ASCII only letters. pub fn isAsciiLetter(cp: u21) bool { return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z'); } /// isLower detects code points that are lowercase. pub fn isLower(cp: u21) bool { // ASCII optimization. if (cp >= 'a' and cp <= 'z') return true; return Props.isLowercase(cp); } /// isAsciiLower detects ASCII only lowercase letters. pub fn isAsciiLower(cp: u21) bool { return cp >= 'a' and cp <= 'z'; } /// isTitle detects code points in titlecase. pub fn isTitle(cp: u21) bool { return Cats.isTitlecaseLetter(cp); } /// isUpper detects code points in uppercase. pub fn isUpper(cp: u21) bool { // ASCII optimization. if (cp >= 'A' and cp <= 'Z') return true; return Props.isUppercase(cp); } /// isAsciiUpper detects ASCII only uppercase letters. pub fn isAsciiUpper(cp: u21) bool { return cp >= 'A' and cp <= 'Z'; } /// toLower returns the lowercase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toLower(cp: u21) u21 { // ASCII optimization. if (cp >= 'A' and cp <= 'Z') return cp ^ 32; // Only cased letters. if (!Props.isChangesWhenCasemapped(cp)) return cp; return LowerMap.toLower(cp); } /// toAsciiLower converts an ASCII letter to lowercase. pub fn toAsciiLower(cp: u21) u21 { return if (cp >= 'A' and cp <= 'Z') cp ^ 32 else cp; } /// toTitle returns the titlecase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toTitle(cp: u21) u21 { // Only cased letters. if (!Props.isChangesWhenCasemapped(cp)) return cp; return TitleMap.toTitle(cp); } /// toUpper returns the uppercase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toUpper(cp: u21) u21 { // ASCII optimization. if (cp >= 'a' and cp <= 'z') return cp ^ 32; // Only cased letters. if (!Props.isChangesWhenCasemapped(cp)) return cp; return UpperMap.toUpper(cp); } /// toAsciiUpper converts an ASCII letter to uppercase. pub fn toAsciiUpper(cp: u21) u21 { return if (cp >= 'a' and cp <= 'z') cp ^ 32 else cp; } /// toCaseFold will convert a code point into its case folded equivalent. Note that this can result /// in a mapping to more than one code point, known as the full case fold. The returned array has 3 /// elements and the code points span until the first element equal to 0 or the end, whichever is first. pub fn toCaseFold(cp: u21) [3]u21 { return CaseFoldMap.toCaseFold(cp); } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "Component struct" { const z = 'z'; try expect(isLetter(z)); try expect(!isUpper(z)); const uz = toUpper(z); try expect(isUpper(uz)); try expectEqual(uz, 'Z'); } test "Component isCased" { try expect(isCased('a')); try expect(isCased('A')); try expect(!isCased('1')); } test "Component isLower" { try expect(isLower('a')); try expect(isAsciiLower('a')); try expect(isLower('é')); try expect(isLower('i')); try expect(!isLower('A')); try expect(!isLower('É')); try expect(!isLower('İ')); } const expectEqualSlices = std.testing.expectEqualSlices; test "Component toCaseFold" { var result = toCaseFold('A'); try expectEqualSlices(u21, &[_]u21{ 'a', 0, 0 }, &result); result = toCaseFold('a'); try expectEqualSlices(u21, &[_]u21{ 'a', 0, 0 }, &result); result = toCaseFold('1'); try expectEqualSlices(u21, &[_]u21{ '1', 0, 0 }, &result); result = toCaseFold('\u{00DF}'); try expectEqualSlices(u21, &[_]u21{ 0x0073, 0x0073, 0 }, &result); result = toCaseFold('\u{0390}'); try expectEqualSlices(u21, &[_]u21{ 0x03B9, 0x0308, 0x0301 }, &result); } test "Component toLower" { try expectEqual(toLower('a'), 'a'); try expectEqual(toLower('A'), 'a'); try expectEqual(toLower('İ'), 'i'); try expectEqual(toLower('É'), 'é'); try expectEqual(toLower(0x80), 0x80); try expectEqual(toLower(0x80), 0x80); try expectEqual(toLower('Å'), 'å'); try expectEqual(toLower('å'), 'å'); try expectEqual(toLower('\u{212A}'), 'k'); try expectEqual(toLower('1'), '1'); } test "Component isUpper" { try expect(!isUpper('a')); try expect(!isAsciiUpper('a')); try expect(!isUpper('é')); try expect(!isUpper('i')); try expect(isUpper('A')); try expect(isUpper('É')); try expect(isUpper('İ')); } test "Component toUpper" { try expectEqual(toUpper('a'), 'A'); try expectEqual(toUpper('A'), 'A'); try expectEqual(toUpper('i'), 'I'); try expectEqual(toUpper('é'), 'É'); try expectEqual(toUpper(0x80), 0x80); try expectEqual(toUpper('Å'), 'Å'); try expectEqual(toUpper('å'), 'Å'); try expectEqual(toUpper('1'), '1'); } test "Component isTitle" { try expect(!isTitle('a')); try expect(!isTitle('é')); try expect(!isTitle('i')); try expect(isTitle('\u{1FBC}')); try expect(isTitle('\u{1FCC}')); try expect(isTitle('Lj')); } test "Component toTitle" { try expectEqual(toTitle('a'), 'A'); try expectEqual(toTitle('A'), 'A'); try expectEqual(toTitle('i'), 'I'); try expectEqual(toTitle('é'), 'É'); try expectEqual(toTitle('1'), '1'); } test "Component isLetter" { var cp: u21 = 'a'; while (cp <= 'z') : (cp += 1) { try expect(isLetter(cp)); } cp = 'A'; while (cp <= 'Z') : (cp += 1) { try expect(isLetter(cp)); } try expect(isLetter('É')); try expect(isLetter('\u{2CEB3}')); try expect(!isLetter('\u{0003}')); }
src/components/aggregate/Letter.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Submarine = struct { pub const Mode = enum { Simple, Complex, }; mode: Mode, xpos: usize, depth: usize, aim: usize, pub fn init(mode: Mode) Submarine { var self = Submarine{ .mode = mode, .xpos = 0, .depth = 0, .aim = 0, }; return self; } pub fn deinit(_: *Submarine) void {} pub fn process_command(self: *Submarine, line: []const u8) void { var it = std.mem.tokenize(u8, line, " "); const c = it.next().?; const n = std.fmt.parseInt(usize, it.next().?, 10) catch unreachable; if (std.mem.eql(u8, c, "forward")) { switch (self.mode) { Mode.Simple => { self.xpos += n; }, Mode.Complex => { self.xpos += n; self.depth += n * self.aim; }, } return; } if (std.mem.eql(u8, c, "down")) { switch (self.mode) { Mode.Simple => { self.depth += n; }, Mode.Complex => { self.aim += n; }, } return; } if (std.mem.eql(u8, c, "up")) { switch (self.mode) { Mode.Simple => { self.depth -= n; }, Mode.Complex => { self.aim -= n; }, } return; } unreachable; } pub fn get_position(self: *Submarine) usize { return self.xpos * self.depth; } }; test "sample part a" { const data: []const u8 = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 ; var submarine = Submarine.init(Submarine.Mode.Simple); defer submarine.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { submarine.process_command(line); } const pos = submarine.get_position(); try testing.expect(pos == 150); } test "sample part b" { const data: []const u8 = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 ; var submarine = Submarine.init(Submarine.Mode.Complex); defer submarine.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { submarine.process_command(line); } const pos = submarine.get_position(); try testing.expect(pos == 900); }
2021/p02/submarine.zig
const std = @import("std"); const print = @import("std").debug.print; const fs = std.fs; const os = std.os; const mem = @import("std").mem; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; pub const io_mode = .evented; const web = @import("zhp"); const spi = @import("bus/spi.zig"); const config = @import("config.zig"); const threads = @import("threads.zig"); const camera = @import("camera.zig"); const led_driver = @import("led_driver.zig"); const gnss = @import("gnss.zig"); const info = @import("info.zig"); const handlers = @import("handlers.zig"); pub const routes = handlers.routes; var led: led_driver.LP50xx = undefined; fn write_info_json() !void { if (try info.stat()) |stat| { print("stat {any}\n", .{stat}); const file = try std.fs.cwd().createFile("test.json", .{}); defer file.close(); try std.json.stringify(stat, std.json.StringifyOptions{ .whitespace = .{ .indent = .{ .Space = 2 } }, }, file.writer()); } } pub fn main() anyerror!void { attachSegfaultHandler(); defer std.debug.assert(!gpa.deinit()); const allocator = &gpa.allocator; var cfg = config.load(allocator); var loop: std.event.Loop = undefined; try loop.initMultiThreaded(); defer loop.deinit(); var i2c_fd = try fs.openFileAbsolute("/dev/i2c-1", fs.File.OpenFlags{ .read = true, .write = true }); defer i2c_fd.close(); var spi01_fd = try fs.openFileAbsolute("/dev/spidev0.1", fs.File.OpenFlags{ .read = true, .write = true }); defer spi01_fd.close(); led = led_driver.LP50xx{ .fd = i2c_fd }; if (led.read_register(0x00, 1)) |value| { print("CONFIG0 = 0x{s}\n", .{std.fmt.fmtSliceHexUpper(value)}); } if (led.read_register(0x01, 1)) |value| { print("CONFIG1 = 0x{s}\n", .{std.fmt.fmtSliceHexUpper(value)}); } led.off(); led.enable(); led.set_brightness(0x30); // Set PWR led to green, others off led.set(0, [_]u8{ 0, 0, 0 }); led.set(1, [_]u8{ 0, 0, 0 }); led.set(2, [_]u8{ 0, 255, 0 }); var led_ctx = threads.HeartBeatContext{ .led = led, .idx = 2 }; try loop.runDetached(allocator, threads.heartbeat_thread, .{led_ctx}); var handle = spi.SPI{ .fd = spi01_fd }; print("SPI configure {any}\n", .{handle.configure(0, 5500)}); var pos = gnss.init(handle); var gnss_rate = @divFloor(1000, @intCast(u16, cfg.camera.fps)); // var gnss_rate: u16 = 10000; pos.configure(); pos.set_rate(gnss_rate); threads.gnss_ctx = threads.GnssContext{ .led = led, .gnss = &pos, .rate = gnss_rate }; try loop.runDetached(allocator, threads.gnss_thread, .{threads.gnss_ctx}); // This will error if the socket doesn't exists. We ignore that error std.fs.cwd().deleteFile(cfg.recording.socket) catch {}; const address = std.net.Address.initUnix(cfg.recording.socket) catch |err| { std.debug.panic("Error creating unix socket: {}", .{err}); }; var server = std.net.StreamServer.init(.{}); defer server.deinit(); server.listen(address) catch |err| { std.debug.panic("Error listening to unix socket: {}", .{err}); }; threads.rec_ctx = threads.RecordingContext{ .config = cfg.recording, .allocator = allocator, .server = &server, .stop = std.atomic.Atomic(bool).init(false), .gnss = threads.gnss_ctx, }; try loop.runDetached(allocator, threads.recording_cleanup_thread, .{threads.rec_ctx}); try loop.runDetached(allocator, threads.recording_server_thread, .{&threads.rec_ctx}); threads.camera_ctx = threads.CameraContext{ .config = cfg.camera, .allocator = allocator, .socket = threads.rec_ctx.config.socket, }; // try loop.runDetached(allocator, camera.bridge_thread, .{threads.camera_ctx}); var app = web.Application.init(allocator, .{ .debug = true }); var app_ctx = threads.AppContext{ .app = &app, .config = cfg.api }; try loop.runDetached(allocator, threads.app_thread, .{app_ctx}); loop.run(); } fn resetSegfaultHandler() void { var act = os.Sigaction{ .handler = .{ .sigaction = os.SIG_DFL }, .mask = os.empty_sigset, .flags = 0, }; os.sigaction(os.SIGSEGV, &act, null); os.sigaction(os.SIGILL, &act, null); os.sigaction(os.SIGBUS, &act, null); } fn handleSignal(sig: i32, sig_info: *const os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) noreturn { // Reset to the default handler so that if a segfault happens in this handler it will crash // the process. Also when this handler returns, the original instruction will be repeated // and the resulting segfault will crash the process rather than continually dump stack traces. resetSegfaultHandler(); led.off(); const addr = @ptrToInt(sig_info.fields.sigfault.addr); // Don't use std.debug.print() as stderr_mutex may still be locked. nosuspend { const stderr = std.io.getStdErr().writer(); _ = switch (sig) { os.SIGSEGV => stderr.print("Segmentation fault at address 0x{x}\n", .{addr}), os.SIGILL => stderr.print("Illegal instruction at address 0x{x}\n", .{addr}), os.SIGBUS => stderr.print("Bus error at address 0x{x}\n", .{addr}), os.SIGINT => stderr.print("Exit due to CTRL-C\n", .{}), else => stderr.print("Exit due to signal {}\n", .{sig}), } catch os.abort(); } os.abort(); } /// Attaches a global SIGSEGV handler pub fn attachSegfaultHandler() void { var act = os.Sigaction{ .handler = .{ .sigaction = handleSignal }, .mask = os.empty_sigset, .flags = (os.SA_SIGINFO | os.SA_RESTART | os.SA_RESETHAND), }; os.sigaction(os.SIGINT, &act, null); os.sigaction(os.SIGQUIT, &act, null); os.sigaction(os.SIGILL, &act, null); os.sigaction(os.SIGTRAP, &act, null); os.sigaction(os.SIGABRT, &act, null); os.sigaction(os.SIGBUS, &act, null); }
src/main.zig
const builtin = @import("builtin"); const georgios = @import("georgios"); comptime {_ = georgios;} const system_calls = georgios.system_calls; pub const panic = georgios.panic; const Game = struct { const Rng = georgios.utils.Rand(u32); const Dir = enum { Up, Down, Right, Left, }; const Point = struct { x: u32, y: u32, pub fn eql(self: *const Point, other: Point) bool { return self.x == other.x and self.y == other.y; } }; max: Point = undefined, running: bool = true, head: Point = undefined, // NOTE: After 128, the snake will stop growing, but also will leave behind // a segment for each food it gets over 128. body: georgios.utils.CircularBuffer(Point, 128, .DiscardOldest) = .{}, score: usize = undefined, dir: Dir = .Right, rng: Rng = undefined, food: Point = undefined, fn get_input(self: *Game) void { while (system_calls.get_key(.NonBlocking)) |key_event| { if (key_event.kind == .Pressed) { switch (key_event.unshifted_key) { .Key_CursorUp => if (self.dir != .Down) { self.dir = .Up; }, .Key_CursorDown => if (self.dir != .Up) { self.dir = .Down; }, .Key_CursorRight => if (self.dir != .Left) { self.dir = .Right; }, .Key_CursorLeft => if (self.dir != .Right) { self.dir = .Left; }, .Key_Escape => { system_calls.print_string("\x1bc"); system_calls.exit(0); }, else => {}, } } } } fn in_body(self: *const Game, point: Point) bool { var i: usize = 0; while (self.body.get(i)) |p| { if (p.eql(point)) return true; i += 1; } return false; } fn draw(s: []const u8, p: Point) void { var buffer: [128]u8 = undefined; var ts = georgios.utils.ToString{.buffer = buffer[0..]}; ts.string("\x1b[") catch unreachable; ts.uint(p.y) catch unreachable; ts.char(';') catch unreachable; ts.uint(p.x) catch unreachable; ts.char('H') catch unreachable; ts.string(s) catch unreachable; system_calls.print_string(ts.get()); } fn draw_head(self: *const Game, alive: bool) void { draw(if (alive) "♦" else "‼", self.head); } fn update_head_and_body(self: *Game, new_pos: Point) void { const old_pos = self.head; self.head = new_pos; self.draw_head(true); if (self.head.eql(self.food)) { self.body.push(old_pos); self.score += 1; self.show_score(); self.gen_food(); } else { if (self.score > 0) { self.body.push(old_pos); draw(" ", self.body.pop().?); } else { draw(" ", old_pos); } } } fn random_point(self: *Game) Point { return .{ .x = self.rng.get() % self.max.x, .y = self.rng.get() % self.max.y, }; } fn gen_food(self: *Game) void { self.food = self.random_point(); while (self.in_body(self.food)) { self.food = self.random_point(); } draw("@", self.food); } fn show_score(self: *Game) void { var p: Point = .{.x = 0, .y = self.max.y + 1}; while (p.x < self.max.x + 1) { draw("▓", p); p.x += 1; } p.x = 1; var buffer: [128]u8 = undefined; var ts = georgios.utils.ToString{.buffer = buffer[0..]}; ts.string("SCORE: ") catch unreachable; ts.uint(self.score) catch unreachable; draw(ts.get(), p); } pub fn reset(self: *Game) void { self.max = .{ .x = system_calls.console_width() - 2, .y = system_calls.console_height() - 2, }; self.rng = .{.seed = system_calls.time()}; system_calls.print_string("\x1bc\x1b[25l"); self.head = .{.x = self.max.x / 2, .y = self.max.y / 2}; self.draw_head(true); self.gen_food(); self.score = 0; self.show_score(); self.body.reset(); } pub fn game_over(self: *Game) usize { self.draw_head(false); // Dead system_calls.sleep_milliseconds(500); self.reset(); return 500; } pub fn tick(self: *Game) usize { self.get_input(); if ((self.dir == .Up and self.head.y == 0) or (self.dir == .Down and self.head.y == self.max.y) or (self.dir == .Right and self.head.x == self.max.x) or (self.dir == .Left and self.head.x == 0)) { return self.game_over(); } var new_pos = self.head; switch (self.dir) { .Up => new_pos.y -= 1, .Down => new_pos.y += 1, .Right => new_pos.x += 1, .Left => new_pos.x -= 1, } if (self.in_body(new_pos)) { return self.game_over(); } self.update_head_and_body(new_pos); // Speed up a bit as time goes on var delay: usize = if (self.score < 32) 100 - 10 * self.score / 4 else 20; if (self.dir == .Down or self.dir == .Up) { delay *= 2; } return delay; } }; pub fn main() void { var game = Game{}; game.reset(); while (game.running) { // TODO: Delta time to correct for speed? system_calls.sleep_milliseconds(game.tick()); } }
programs/snake/snake.zig
const std = @import("std"); const os = @import("root").os; const pmm = os.memory.pmm; const vmm = os.memory.vmm; const paging = os.memory.paging; const platform = os.platform; // Shared memory object pub const MemoryObject = struct { frames: []usize, ref_count: usize, allocator: *std.mem.Allocator, page_size: usize, pub fn create(allocator: *std.mem.Allocator, size: usize) !*MemoryObject { const instance = try allocator.create(@This()); instance.ref_count = 1; instance.allocator = allocator; errdefer allocator.destroy(instance); std.debug.assert(platform.paging.page_sizes.len > 0); const page_size = platform.paging.page_sizes[0]; const page_count = os.lib.libalign.align_up(usize, size, page_size) / page_size; instance.page_size = page_size; instance.frames = try allocator.alloc(usize, page_count); errdefer allocator.free(instance.frames); for (instance.frames) |*page, i| { page.* = pmm.alloc_phys(page_size) catch |err| { for (instance.frames[0..i]) |*page_to_dispose| { pmm.free_phys(page_to_dispose.*, page_size); } return err; }; } return instance; } pub fn borrow(self: *@This()) *@This() { _ = @atomicRmw(usize, &self.ref_count, .Add, 1, .AcqRel); return self; } pub fn drop(self: *@This()) void { if (@atomicRmw(usize, &self.ref_count, .Sub, 1, .AcqRel) > 1) { return; } for (self.frames[0..self.frames.len]) |*page| { pmm.free_phys(page.*, self.page_size); } self.allocator.free(self.frames); self.allocator.destroy(self); } /// Size in virtual memory pub fn virtual_size(self: *const @This()) usize { return self.frames.len * self.page_size; } }; /// Shared memory mapper interface pub const Mapper = struct { /// Map errors pub const Error = error{ OutOfVirtualMemory, MappingFailure, }; /// Callback to map shared memory object. Reference is already borrowed map_impl: fn (self: *@This(), object: *const MemoryObject, perms: paging.Perms, memtype: platform.paging.MemoryType) Error!usize, /// Callback to unmap shared memory object. Reference is not dropped unmap_impl: fn (self: *@This(), object: *const MemoryObject, addr: usize) void, // Wrappers to make things a little bit nicer /// Map shared memory object. Reference is already borrowed pub fn map(self: *@This(), object: *const MemoryObject, perms: paging.Perms, memtype: platform.paging.MemoryType) !usize { return self.map_impl(self, object, perms, memtype); } /// Unmap shared memory object. Reference is not dropped pub fn unmap(self: *@This(), object: *const MemoryObject, addr: usize) void { return self.unmap_impl(self, object, addr); } }; /// Map memory object in the kernel virtual address space fn map_obj_in_kernel(_: *Mapper, object: *const MemoryObject, perms: paging.Perms, memtype: platform.paging.MemoryType) Mapper.Error!usize { // Allocate non-backed memory const fake_arr = vmm.nonbacked_range.allocator.allocFn(&vmm.nonbacked_range.allocator, object.virtual_size(), 1, 1, 0) catch return error.OutOfVirtualMemory; errdefer _ = vmm.nonbacked_range.allocator.resizeFn(&vmm.nonbacked_range.allocator, fake_arr, 1, 0, 1, 0) catch unreachable; // Map pages const base = @ptrToInt(fake_arr.ptr); var i: usize = 0; while (i < object.frames.len) : (i += 1) { const virt = base + i * object.page_size; const phys = object.frames[i]; const size = object.page_size; errdefer paging.unmap(.{ .virt = base, .size = size * i, .reclaim_pages = false }); paging.map_phys(.{ .virt = virt, .phys = phys, .size = size, .perm = perms, .memtype = memtype }) catch return error.MappingFailure; } return base; } /// Unmap memory object from the kernel virtual address space pub fn unmap_obj_in_kernel(_: *Mapper, object: *const MemoryObject, addr: usize) void { const fake_arr = @intToPtr([*]u8, addr)[0..object.virtual_size()]; paging.unmap(.{ .virt = addr, .size = object.virtual_size(), .reclaim_pages = false }); _ = vmm.nonbacked_range.allocator.resizeFn(&vmm.nonbacked_range.allocator, fake_arr, 1, 0, 1, 0) catch unreachable; } /// Exposed mapper inteface for the kernel arena pub var kernel_mapper = Mapper{ .map_impl = map_obj_in_kernel, .unmap_impl = unmap_obj_in_kernel, };
src/kepler/memory.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const Allocator = mem.Allocator; const Self = @This(); const print = std.debug.print; const CFO = @import("./CFO.zig"); const SSA_GVN = @import("./SSA_GVN.zig"); const builtin = @import("builtin"); // const stage2 = builtin.zig_backend != .stage1; const ArrayList = std.ArrayList; const assert = std.debug.assert; const IPReg = CFO.IPReg; const VMathOp = CFO.VMathOp; const FMode = CFO.FMode; const AOp = CFO.AOp; a: Allocator, // TODO: unmanage all these: n: ArrayList(Node), b: ArrayList(Block), dfs: ArrayList(u16), sccorder: ArrayList(u16), refs: ArrayList(u16), narg: u16 = 0, nvar: u16 = 0, // variables 2.0: virtual registero nvreg: u16 = 0, vregs: ArrayList(u16), // 8-byte slots in stack frame nslots: u8 = 0, // filler value for unintialized refs. not a sentinel for // actually invalid refs! pub const DEAD: u16 = 0xFEFF; // For blocks: we cannot have more than 2^14 blocks anyway // for vars: don't allocate last block! pub const NoRef: u16 = 0xFFFF; pub fn uv(s: usize) u16 { return @intCast(u16, s); } pub const Node = struct { s: [2]u16 = .{ 0, 0 }, // sucessors dfnum: u16 = 0, idom: u16 = 0, predref: u16 = 0, npred: u16 = 0, // NB: might be NoRef if the node was deleted, // a reachable node must have at least one block even if empty! firstblk: u16, lastblk: u16, dfs_parent: u16 = 0, // TODO: unused lowlink: u16 = 0, scc: u16 = 0, // XXX: not a topological index, just an identidifer live_in: u64 = 0, // TODO: globally allocate a [n_nodes*nvreg] multibitset }; pub const EMPTY: Inst = .{ .tag = .empty, .op1 = 0, .op2 = 0 }; pub const BLK_SIZE = 4; pub const BLK_SHIFT = 2; pub const Block = struct { node: u16, succ: u16 = NoRef, i: [BLK_SIZE]Inst = .{EMPTY} ** BLK_SIZE, pub fn next(self: @This()) ?u16 { return if (self.succ != NoRef) self.succ else null; } }; test "sizey" { // @compileLog(@sizeOf(Inst)); // @compileLog(@sizeOf(Block)); assert(@sizeOf(Block) <= 64); } pub const Inst = struct { tag: Tag, spec: u8 = 0, op1: u16, op2: u16, // reindex: u16 = 0, mckind: MCKind = .unallocated_raw, mcidx: u8 = undefined, // n_use: u16 = 0, last_use: u16 = NoRef, vreg: u16 = NoRef, fn free(self: @This()) bool { return self.tag == .empty; } // TODO: handle spec being split between u4 type and u4 somethingelse? pub fn spec_type(self: Inst) ValType { // TODO: jesus this is terrible return if (self.spec >= TODO_INT_SPEC) .intptr else .avxval; } const TODO_INT_SPEC: u8 = 8; const FMODE_MASK: u8 = (1 << 4) - 1; const VOP_MASK: u8 = ~FMODE_MASK; pub fn vop(self: Inst) VMathOp { return @intToEnum(VMathOp, (self.spec & VOP_MASK) >> 4); } pub fn fmode(self: Inst) FMode { return @intToEnum(FMode, self.spec & FMODE_MASK); } pub fn res_type(inst: Inst) ?ValType { return switch (inst.tag) { .empty => null, .arg => inst.spec_type(), // TODO: haIIIII .variable => inst.spec_type(), // gets preserved to the phis .putvar => null, .phi => inst.spec_type(), .putphi => null, // stated in the phi instruction .constant => inst.spec_type(), .renum => null, // should be removed at this point .load => inst.spec_type(), .lea => .intptr, // Lea? Who's Lea?? .store => null, .iop => .intptr, .ilessthan => null, // technically the FLAG register but anyway .vmath => .avxval, .ret => null, }; } pub fn ipreg(i: Inst) ?IPReg { return if (i.mckind == .ipreg) @intToEnum(IPReg, i.mcidx) else null; } pub fn avxreg(i: Inst) ?u4 { return if (i.mckind == .vfreg) @intCast(u4, i.mcidx) else null; } }; pub const Tag = enum(u8) { empty = 0, // empty slot. must not be refered to! arg, variable, putvar, // non-phi assignment phi, /// assign to phi of (only) successor /// note: despite swearing in the intel church. /// op1 is source and op2 is dest, to simplify stuff /// i e n_op(putphi) == 1 for the most part putphi, renum, constant, load, lea, store, iop, // imath group? ilessthan, // icmp group? vmath, ret, }; pub const MCKind = enum(u8) { // not yet allocated, or Inst that trivially produces no value unallocated_raw, // general purpose register like rax, r12, etc ipreg, // SSE/AVX registers, ie xmm0/ymm0-15 vfreg, // unallocated, but has a ipreg hint unallocated_ipreghint, // unallocated, but has a vfreg hint unallocated_vfreghint, // TODO: support non-uniform sizes of spilled value frameslot, // unused value, perhaps should have been deleted before alloc dead, // not stored as such, will be emitted togheter with the next inst // example "lea" and then "store", or "load" and then iop/vmath fused, fn unallocated(self: @This()) bool { return switch (self) { .unallocated_raw => true, .unallocated_ipreghint => true, .unallocated_vfreghint => true, else => false, }; } }; // number of op:s which are inst references. // otherwise they can store whatever data pub fn n_op(tag: Tag, rw: bool) u2 { return switch (tag) { .empty => 0, .arg => 0, .variable => 0, // really only one, but we will get rid of this lie // before getting into any serious analysis. .putvar => 2, .phi => 0, // works on stage1: // .putphi => @as(u2, if (rw) 2 else 1), // works on stage2: // .putphi => if (rw) 2 else 1, // works on both: (clown_emoji) .putphi => if (rw) @as(u2, 2) else @as(u2, 1), // TODO: booooooo .constant => 0, .renum => 1, .load => 2, // base, idx .lea => 2, // base, idx. elided when only used for a store! .store => 2, // addr, val .iop => 2, .ilessthan => 2, .vmath => 2, .ret => 1, }; } // TODO: expand into precise types, like "dword" or "4 packed doubles" const ValType = enum(u4) { intptr = 0, avxval, pub fn spec(self: @This()) u4 { return @enumToInt(self); } }; // TODO: refactor these to an array of InstMetadata structs // or this is res_type != null? pub fn has_res(tag: Tag) bool { return switch (tag) { .empty => false, .arg => true, .variable => true, // ASCHUALLY no, but looks like yes .putvar => false, .phi => true, .putphi => false, // storage location is stated in the phi instruction .constant => true, .renum => true, // TODO: removed at this point .load => true, .lea => true, // Lea? Who's Lea?? .store => false, .iop => true, .ilessthan => false, // technically yes, but no .vmath => true, .ret => false, }; } pub fn init(n: u16, allocator: Allocator) !Self { return Self{ .a = allocator, .n = try ArrayList(Node).initCapacity(allocator, n), .dfs = ArrayList(u16).init(allocator), .vregs = ArrayList(u16).init(allocator), .sccorder = ArrayList(u16).init(allocator), .refs = try ArrayList(u16).initCapacity(allocator, 4 * n), .b = try ArrayList(Block).initCapacity(allocator, 2 * n), }; } pub fn deinit(self: *Self) void { self.n.deinit(); self.dfs.deinit(); self.sccorder.deinit(); self.refs.deinit(); self.b.deinit(); } pub fn toref(blkid: u16, idx: u16) u16 { assert(idx < BLK_SIZE); return (blkid << BLK_SHIFT) | idx; } fn fromref(ref: u16) struct { block: u16, idx: u16 } { const IDX_MASK: u16 = BLK_SIZE - 1; const BLK_MASK: u16 = ~IDX_MASK; return .{ .block = (ref & BLK_MASK) >> BLK_SHIFT, .idx = ref & IDX_MASK, }; } const BIREF = struct { n: u16, i: *Inst }; pub fn biref(self: *Self, ref: u16) ?BIREF { if (ref == NoRef) { return null; } const r = fromref(ref); const blk = &self.b.items[r.block]; return BIREF{ .n = blk.node, .i = &blk.i[r.idx] }; } pub fn iref(self: *Self, ref: u16) ?*Inst { return if (self.biref(ref)) |bi| bi.i else null; } pub fn vspec(vop: VMathOp, fmode: FMode) u8 { return (vop.off() << 4) | @as(u8, @enumToInt(fmode)); } pub fn addNode(self: *Self) !u16 { const n = try self.n.addOne(); const b = try self.b.addOne(); var nodeid = uv(self.n.items.len - 1); var blkid = uv(self.b.items.len - 1); n.* = .{ .firstblk = blkid, .lastblk = blkid }; b.* = .{ .node = nodeid }; return nodeid; } // add inst to the end of block pub fn addInst(self: *Self, node: u16, inst: Inst) !u16 { const n = &self.n.items[node]; // must exist: var blkid = n.lastblk; var blk = &self.b.items[blkid]; // TODO: later we can add more constraints for where "empty" ins can be var lastfree: u8 = BLK_SIZE; var i: u8 = BLK_SIZE - 1; while (true) : (i -= 1) { if (blk.i[@intCast(u8, i)].free()) { lastfree = i; } else { break; } if (i == 0) { break; } } if (lastfree == BLK_SIZE) { blkid = uv(self.b.items.len); blk.succ = blkid; blk = try self.b.addOne(); blk.* = .{ .node = node }; n.lastblk = blkid; lastfree = 0; } blk.i[lastfree] = inst; return toref(blkid, lastfree); } // add inst to the beginning of the block, _without_ renumbering any exiting instruction pub fn preInst(self: *Self, node: u16, inst: Inst) !u16 { const n = &self.n.items[node]; var blkid = n.firstblk; var blk = &self.b.items[blkid]; var firstfree: i8 = -1; var i: i8 = 0; while (i < BLK_SIZE) : (i += 1) { if (blk.i[@intCast(u8, i)].free()) { firstfree = i; } else { break; } } if (firstfree == -1) { const nextblk = blkid; blkid = uv(self.b.items.len); blk = try self.b.addOne(); blk.* = .{ .node = node, .succ = nextblk }; n.firstblk = blkid; firstfree = BLK_SIZE - 1; } const free = @intCast(u8, firstfree); blk.i[free] = inst; return toref(blkid, free); } pub fn const_int(self: *Self, node: u16, val: u16) !u16 { // TODO: actually store constants in a buffer, or something return self.addInst(node, .{ .tag = .constant, .op1 = val, .op2 = 0, .spec = Inst.TODO_INT_SPEC }); } pub fn binop(self: *Self, node: u16, tag: Tag, op1: u16, op2: u16) !u16 { return self.addInst(node, .{ .tag = tag, .op1 = op1, .op2 = op2 }); } // TODO: better abstraction for types (once we have real types) pub fn vbinop(self: *Self, node: u16, tag: Tag, fmode: FMode, op1: u16, op2: u16) !u16 { return self.addInst(node, .{ .tag = tag, .op1 = op1, .op2 = op2, .spec = @enumToInt(fmode) }); } pub fn vmath(self: *Self, node: u16, vop: VMathOp, fmode: FMode, op1: u16, op2: u16) !u16 { // TODO: somewhere, typecheck that FMode matches fmode of args.. return self.addInst(node, .{ .tag = .vmath, .spec = vspec(vop, fmode), .op1 = op1, .op2 = op2 }); } pub fn iop(self: *Self, node: u16, vop: AOp, op1: u16, op2: u16) !u16 { return self.addInst(node, .{ .tag = .iop, .spec = vop.opx(), .op1 = op1, .op2 = op2 }); } pub fn putvar(self: *Self, node: u16, op1: u16, op2: u16) !void { _ = try self.binop(node, .putvar, op1, op2); } pub fn store(self: *Self, node: u16, base: u16, idx: u16, val: u16) !u16 { // FUBBIT: all possible instances of fusing should be detected in analysis anyway const addr = try self.addInst(node, .{ .tag = .lea, .op1 = base, .op2 = idx, .mckind = .fused }); return self.addInst(node, .{ .tag = .store, .op1 = addr, .op2 = val, .spec = self.iref(val).?.spec }); } pub fn ret(self: *Self, node: u16, val: u16) !void { _ = try self.addInst(node, .{ .tag = .ret, .op1 = val, .op2 = 0 }); } pub fn prePhi(self: *Self, node: u16, v: Inst) !u16 { return self.preInst(node, .{ .tag = .phi, .op1 = v.op1, .op2 = 0, .spec = v.spec }); } // TODO: maintain wf of block 0: first all args, then all vars. pub fn arg(self: *Self) !u16 { if (self.n.items.len == 0) return error.EEEEE; const inst = try self.addInst(0, .{ .tag = .arg, .op1 = self.narg, .op2 = 0, .spec = Inst.TODO_INT_SPEC }); self.narg += 1; return inst; } pub fn variable(self: *Self) !u16 { if (self.n.items.len == 0) return error.EEEEE; const inst = try self.addInst(0, .{ .tag = .variable, .op1 = self.nvar, .op2 = 0, .spec = Inst.TODO_INT_SPEC }); self.nvar += 1; return inst; } pub fn preds(self: *Self, i: u16) []u16 { const v = self.n.items[i]; return self.refs.items[v.predref..][0..v.npred]; } pub fn p(self: *Self, s1: u16, s2: u16) void { var z1: u16 = s1; var z2: u16 = s2; if (true and s2 != 0) { z1 = s2; z2 = s1; } // TODO: this is INVALID self.n.appendAssumeCapacity(.{ .s = .{ z1, z2 }, .firstblk = NoRef, .lastblk = NoRef }); } fn predlink(self: *Self, i: u16, si: u1, split: bool) !void { var n = self.n.items; const s = n[i].s[si]; if (s == 0) return; if (split and n[s].npred > 1) { const inter = try self.addNode(); n = self.n.items; // haii n[inter].npred = 1; n[i].s[si] = inter; n[inter].s[0] = s; addpred(self, s, inter); addpred(self, inter, i); } else { addpred(self, s, i); } } fn addpred(self: *Self, s: u16, i: u16) void { const n = self.n.items; // tricky: build the reflist per node backwards, // so the end result is the start index if (n[s].predref == 0) { self.refs.appendNTimesAssumeCapacity(DEAD, n[s].npred); n[s].predref = uv(self.refs.items.len); } n[s].predref -= 1; self.refs.items[n[s].predref] = i; } pub fn calc_preds(self: *Self) !void { const n = self.n.items; // TODO: policy for rebuilding refs from scratch? if (self.refs.items.len > 0) unreachable; for (n) |v| { if (v.s[0] > 0) { n[v.s[0]].npred += 1; } if (v.s[1] > 0 and v.s[1] != v.s[0]) { n[v.s[1]].npred += 1; } } for (n) |v, i| { const shared = v.s[1] > 0 and v.s[1] == v.s[0]; if (shared) return error.NotSureAboutThis; const split = v.s[1] > 0; try self.predlink(@intCast(u16, i), 0, split); try self.predlink(@intCast(u16, i), 1, split); } } pub fn calc_dfs(self: *Self) !void { const n = self.n.items; var stack = try ArrayList(u16).initCapacity(self.a, n.len); try self.dfs.ensureTotalCapacity(n.len); defer stack.deinit(); stack.appendAssumeCapacity(0); while (stack.items.len > 0) { const v = stack.pop(); if (n[v].dfnum > 0) { // already visited continue; } if (false) print("dfs[{}] = {};\n", .{ self.dfs.items.len, v }); n[v].dfnum = uv(self.dfs.items.len); self.dfs.appendAssumeCapacity(v); for (n[v].s) |si| { // origin cannot be revisited anyway if (si > 0 and n[si].dfnum == 0) { n[si].dfs_parent = v; stack.appendAssumeCapacity(si); } } } } pub fn calc_scc(self: *Self) !void { const n = self.n.items; try self.dfs.ensureTotalCapacity(n.len); var stack = try ArrayList(u16).initCapacity(self.a, n.len); defer stack.deinit(); try self.sccorder.ensureTotalCapacity(n.len); self.scc_connect(&stack, 0); } pub fn scc_connect(self: *Self, stack: *ArrayList(u16), v: u16) void { const n = self.n.items; n[v].dfnum = uv(self.dfs.items.len); self.dfs.appendAssumeCapacity(v); stack.appendAssumeCapacity(v); n[v].lowlink = n[v].dfnum; for (n[v].s) |w| { // origin cannot be revisited anyway if (w > 0) { if (n[w].dfnum == 0) { n[w].dfs_parent = v; self.scc_connect(stack, w); n[v].lowlink = math.min(n[v].lowlink, n[w].lowlink); } else if (n[w].dfnum < n[v].dfnum and n[w].scc == 0) { // or whatever n[v].lowlink = math.min(n[v].lowlink, n[w].dfnum); } } } if (n[v].lowlink == n[v].dfnum) { while (true) { const w = stack.pop(); self.sccorder.appendAssumeCapacity(w); // XXX: not topologically sorted, just enables the check: n[i].scc == n[j].scc n[w].scc = v; if (w == v) break; } } } pub fn reorder_nodes(self: *Self) !void { const newlink = try self.a.alloc(u16, self.n.items.len); defer self.a.free(newlink); mem.set(u16, newlink, NoRef); const oldlink = try self.a.alloc(u16, self.n.items.len); defer self.a.free(oldlink); mem.set(u16, oldlink, NoRef); var newpos: u16 = 0; var last_scc: u16 = NoRef; var cur_scc: u16 = NoRef; var sci = self.sccorder.items.len - 1; while (true) : (sci -= 1) { const old_ni = self.sccorder.items[sci]; const ni = if (old_ni < newpos) oldlink[old_ni] else old_ni; const n = &self.n.items[ni]; oldlink[newpos] = ni; newlink[old_ni] = newpos; if (n.scc != last_scc) { last_scc = n.scc; cur_scc = newpos; } n.scc = cur_scc; mem.swap(Node, n, &self.n.items[newpos]); newpos += 1; if (sci == 0) break; } assert(newpos <= self.n.items.len); // oopsie woopsie, we killed some dead nodes! self.n.items.len = newpos; // fixup references: for (self.n.items) |*n, ni| { for (n.s) |*s| { if (s.* != NoRef) { s.* = newlink[s.*]; } } for (self.preds(uv(ni))) |*pi| { pi.* = newlink[pi.*]; } var cur_blk: ?u16 = n.firstblk; while (cur_blk) |blk| { var b = &self.b.items[blk]; b.node = uv(ni); cur_blk = b.next(); } } } // assumes already reorder_nodes ! pub fn reorder_inst(self: *Self) !void { const newlink = try self.a.alloc(u16, self.b.items.len * BLK_SIZE); mem.set(u16, newlink, NoRef); const newblkpos = try self.a.alloc(u16, self.b.items.len); // not needed but for debug: // mem.set(u16, newblkpos, NoRef); defer self.a.free(newlink); defer self.a.free(newblkpos); var newpos: u16 = 0; // already in scc order for (self.n.items) |*n| { var cur_blk: ?u16 = n.firstblk; var blklink: ?u16 = null; while (cur_blk) |old_blk| { // TRICKY: we might have swapped out the block const newblk = newpos >> BLK_SHIFT; const blk = if (old_blk < newblk) newblkpos[old_blk] else old_blk; var b = &self.b.items[blk]; // TODO: RUNDA UPP if (blklink) |link| { self.b.items[link].succ = newblk; } else { n.firstblk = newblk; } blklink = newblk; for (b.i) |_, idx| { // TODO: compact away .empty, later when opts is punching holes and stuff newlink[toref(old_blk, uv(idx))] = newpos; newpos += 1; } newblkpos[newblk] = blk; // newblkpos[blk] = newblk; cur_blk = b.next(); mem.swap(Block, b, &self.b.items[newblk]); if (cur_blk == null) { n.lastblk = newblk; } } } // order irrelevant here, just fixing up broken refs for (self.n.items) |*n, ni| { if (n.dfnum == 0 and ni > 0) { // He's dead, Jim! n.firstblk = NoRef; n.lastblk = NoRef; continue; } var cur_blk: ?u16 = n.firstblk; while (cur_blk) |blk| { var b = &self.b.items[blk]; for (b.i) |*i| { const nops = n_op(i.tag, true); if (nops > 0) { i.op1 = newlink[i.op1]; if (nops > 1) { i.op2 = newlink[i.op2]; } } } cur_blk = b.next(); } } } // ni = node id of user pub fn adduse(self: *Self, ni: u16, user: u16, used: u16) void { const ref = self.biref(used).?; //ref.i.n_use += 1; ref.i.last_use = user; // it leaks to another block: give it a virtual register number if (ref.n != ni) { if (ref.i.vreg == NoRef) { ref.i.vreg = self.nvreg; self.nvreg += 1; self.vregs.appendAssumeCapacity(used); } } } // TODO: not idempotent! does not reset n_use=0 first. // NB: requires reorder_nodes() [scc] and reorder_inst() pub fn calc_use(self: *Self) !void { // TODO: NOT LIKE THIS try self.vregs.ensureTotalCapacity(64); for (self.n.items) |*n, ni| { var cur_blk: ?u16 = n.firstblk; while (cur_blk) |blk| { var b = &self.b.items[blk]; for (b.i) |*i, idx| { const ref = toref(blk, uv(idx)); const nops = n_op(i.tag, false); if (nops > 0) { self.adduse(uv(ni), ref, i.op1); if (nops > 1) { self.adduse(uv(ni), ref, i.op2); } } } cur_blk = b.next(); } } var ni: u16 = uv(self.n.items.len - 1); // TODO: at this point the number of vregs is known. so a bitset for // node X vreg can be allocated here. var scc_end: ?u16 = null; var scc_last: bool = false; while (true) : (ni -= 1) { const n = &self.n.items[ni]; var live: u64 = 0; for (n.s) |s| { if (s != NoRef) { live |= self.n.items[s].live_in; } } var cur_blk: ?u16 = n.lastblk; if (scc_end == null) { // end exclusive scc_end = toref(cur_blk.?, BLK_SIZE - 1); scc_last = true; } while (cur_blk) |blk| { var b = &self.b.items[blk]; var idx: usize = BLK_SIZE; while (idx > 0) { idx -= 1; const i = &b.i[idx]; _ = i; if (i.vreg != NoRef) { live &= ~(@as(usize, 1) << @intCast(u6, i.vreg)); } const nops = n_op(i.tag, true); if (nops > 0) { const ref = self.iref(i.op1).?; if (ref.vreg != NoRef) live |= (@as(usize, 1) << @intCast(u6, ref.vreg)); if (nops > 1) { const ref2 = self.iref(i.op2).?; if (ref2.vreg != NoRef) live |= (@as(usize, 1) << @intCast(u6, ref2.vreg)); } } } cur_blk = if (blk != n.firstblk) blk - 1 else null; } n.live_in = live; if (n.scc == ni) { // if scc was not a singleton, we are now at the first node // at a SCC which might be a loop. For values live // at the entry, extend the liveness interval to the end if (!scc_last) { var ireg: u16 = 0; while (ireg < self.nvreg) : (ireg += 1) { if ((live & (@as(usize, 1) << @intCast(u6, ireg))) != 0) { const i = self.iref(self.vregs.items[ireg]).?; i.last_use = math.max(i.last_use, scc_end.?); } } } scc_end = null; } scc_last = false; if (ni == 0) break; } } pub fn alloc_arg(self: *Self, inst: *Inst) !void { _ = self; const regs: [6]IPReg = .{ .rdi, .rsi, .rdx, .rcx, .r8, .r9 }; if (inst.op1 >= regs.len) return error.ARA; inst.mckind = .ipreg; inst.mcidx = regs[inst.op1].id(); } // fills up some registers, and then goes to the stack. // reuses op1 if it is from the same block and we are the last user pub fn trivial_alloc(self: *Self) !void { // TRRICKY: start with the ABI arg registers, and just skip as many args as we have const regs: [8]IPReg = .{ .rdi, .rsi, .rdx, .rcx, .r8, .r9, .r10, .r11 }; var used: usize = self.narg; var avxused: u8 = 0; for (self.n.items) |*n| { var cur_blk: ?u16 = n.firstblk; while (cur_blk) |blk| { var b = &self.b.items[blk]; for (b.i) |*i, idx| { const ref = toref(blk, uv(idx)); if (i.tag == .arg) { try self.alloc_arg(i); } else if (has_res(i.tag) and i.mckind.unallocated()) { const regkind: MCKind = if (i.res_type() == ValType.avxval) .vfreg else .ipreg; const op1 = if (n_op(i.tag, false) > 0) self.iref(i.op1) else null; if (op1) |o| { if (o.mckind == regkind and o.vreg == NoRef and o.last_use == ref) { i.mckind = regkind; i.mcidx = o.mcidx; continue; } } if (i.res_type() == ValType.avxval) { if (avxused == 16) { return error.GOOOF; } i.mckind = .vfreg; i.mcidx = avxused; avxused += 1; } else if (used < regs.len) { i.mckind = .ipreg; i.mcidx = regs[used].id(); used += 1; } else { i.mckind = .frameslot; if (self.nslots == 255) { return error.UDunGoofed; } i.mcidx = self.nslots; self.nslots += 1; } } } cur_blk = b.next(); } } } pub fn scan_alloc(self: *Self) !void { var active_avx: [16]u16 = ([1]u16{0}) ** 16; var active_ipreg: [16]u16 = ([1]u16{0}) ** 16; active_ipreg[IPReg.rsp.id()] = NoRef; // just say NO to -fomiting the framepointer! active_ipreg[IPReg.rbp.id()] = NoRef; // TODO: handle auxilary register properly (by explicit load/spill?) active_ipreg[IPReg.rax.id()] = NoRef; // TODO: allocate callee-saved registers active_ipreg[IPReg.rbx.id()] = NoRef; active_ipreg[IPReg.r12.id()] = NoRef; active_ipreg[IPReg.r13.id()] = NoRef; active_ipreg[IPReg.r14.id()] = NoRef; active_ipreg[IPReg.r15.id()] = NoRef; for (self.n.items) |*n| { var cur_blk: ?u16 = n.firstblk; while (cur_blk) |blk| { var b = &self.b.items[blk]; for (b.i) |*i, idx| { const ref = toref(blk, uv(idx)); if (i.tag == .arg) { try self.alloc_arg(i); assert(active_ipreg[i.mcidx] <= ref); active_ipreg[i.mcidx] = i.last_use; } else if (has_res(i.tag) and i.mckind.unallocated()) { const is_avx = (i.res_type() == ValType.avxval); const regkind: MCKind = if (is_avx) .vfreg else .ipreg; const the_active = if (is_avx) &active_avx else &active_ipreg; if (i.tag == .constant and i.spec == 0) { i.mckind = .fused; continue; } // TODO: reghint var regid: ?u4 = null; for (the_active) |l, ri| { if (l <= ref) { regid = @intCast(u4, ri); break; } } if (regid) |ri| { i.mckind = regkind; i.mcidx = ri; the_active[ri] = i.last_use; } else { i.mckind = .frameslot; if (self.nslots == 255) { return error.UDunGoofed; } i.mcidx = self.nslots; // TODO: lol reuse slots self.nslots += 1; } } } cur_blk = b.next(); } } } pub fn debug_print(self: *Self) void { print("\n", .{}); for (self.n.items) |*n, i| { print("node {} (npred {}, scc {}):", .{ i, n.npred, n.scc }); if (n.live_in != 0) { print(" LIVEIN", .{}); var ireg: u16 = 0; while (ireg < self.nvreg) : (ireg += 1) { const live = (n.live_in & (@as(usize, 1) << @intCast(u6, ireg))) != 0; if (live) { print(" {}", .{ireg}); } } } if (n.firstblk == NoRef) { print(" VERY DEAD\n", .{}); continue; } print("\n", .{}); self.print_blk(n.firstblk); if (n.s[1] == 0) { if (n.s[0] == 0) { print(" diverge\n", .{}); } else if (n.s[0] != i + 1) { print(" jump {}\n", .{n.s[0]}); } } else { print(" split: {any}\n", .{n.s}); } } } fn print_blk(self: *Self, firstblk: u16) void { var cur_blk: ?u16 = firstblk; while (cur_blk) |blk| { // print("THE BLOCK: {}\n", .{blk}); var b = &self.b.items[blk]; for (b.i) |i, idx| { if (i.tag == .empty) { continue; } const chr: u8 = if (has_res(i.tag)) '=' else ' '; print(" %{} {c} {s}", .{ toref(blk, uv(idx)), chr, @tagName(i.tag) }); if (i.tag == .variable) { print(" {s}", .{@tagName(i.spec_type())}); } if (i.tag == .vmath) { print(".{s}", .{@tagName(i.vop())}); } else if (i.tag == .iop) { print(".{s}", .{@tagName(@intToEnum(AOp, i.spec))}); } else if (i.tag == .constant) { print(" c[{}]", .{i.op1}); } else if (i.tag == .putphi) { print(" %{} <-", .{i.op2}); } const nop = n_op(i.tag, false); if (nop > 0) { print(" %{}", .{i.op1}); if (nop > 1) { print(", %{}", .{i.op2}); } } print_mcval(i); if (i.last_use != NoRef) { // this is a compiler bug ("*" emitted for Noref) //print(" <{}{s}>", .{ i.n_use, @as([]const u8, if (i.vreg != NoRef) "*" else "") }); // this is getting ridiculous if (i.vreg != NoRef) { print(" |{}=>%{}|", .{ i.vreg, i.last_use }); } else { print(" <%{}>", .{i.last_use}); } // print(" <{}{s}>", .{ i.last_use, marker }); //print(" <{}:{}>", .{ i.n_use, i.vreg }); } print("\n", .{}); } cur_blk = b.next(); } } fn print_mcval(i: Inst) void { switch (i.mckind) { .frameslot => print(" [rbp-8*{}]", .{i.mcidx}), .ipreg => print(" ${s}", .{@tagName(@intToEnum(IPReg, i.mcidx))}), .vfreg => print(" $ymm{}", .{i.mcidx}), else => { if (i.tag == .load or i.tag == .phi or i.tag == .arg) { if (i.res_type()) |t| { print(" {s}", .{@tagName(t)}); } } }, } } const test_allocator = std.testing.allocator; const expectEqual = std.testing.expectEqual; pub fn test_analysis(self: *Self) !void { try self.calc_preds(); //try self.calc_dfs(); try self.calc_scc(); // also provides dfs try self.reorder_nodes(); try SSA_GVN.ssa_gvn(self); try self.reorder_inst(); try self.calc_use(); try self.scan_alloc(); }
src/FLIR.zig
const std = @import("std"); const Token = struct { tag: Tag, loc: Loc, pub const Loc = struct { start: usize, end: usize, }; pub const Tag = union(enum) { kw_type, kw_struct, kw_ref, kw_flat, kw_view, kw_entry, kw_fn, kw_if, kw_else, kw_while, kw_for, kw_return, kw_break, kw_continue, kw_and, kw_or, kw_const, kw_var, kw_undefined, dot, comma, pipe, colon, semicolon, lbrace, rbrace, lbracket, rbracket, lparen, rparen, equals, plus, minus, mult, div, mod, lshift, rshift, plus_eq, minus_eq, mult_eq, div_eq, mod_eq, lshift_eq, rshift_eq, @"and", or_eq, // we don't have an 'or', it's called 'pipe' because captures and_eq, cmp_eq, cmp_leq, cmp_geq, cmp_lt, cmp_gt, type_uint: u64, type_sint: u64, type_float: u64, int_lit: i65, float_lit: f64, dimension: [2]u64, identifier: []const u8, builtin: []const u8, }; }; pub fn Tokenizer(comptime Reader: type) type { return struct { ps: std.io.PeekStream(.{ .Static = max_lookahead }, Reader), pos: usize = 0, arena: std.heap.ArenaAllocator, const Self = @This(); const max_lookahead = 64; pub fn init(allocator: *std.mem.Allocator, r: Reader) Self { return .{ .ps = std.io.peekStream(max_lookahead, r), .arena = std.heap.ArenaAllocator.init(allocator), }; } pub fn deinit(self: *Self) void { self.arena.deinit(); } pub fn next(self: *Self) !Token { // consume trailing whitespace while (self.ps.reader().readByte()) |c| { if (!std.ascii.isSpace(c)) { self.ps.putBackByte(c) catch unreachable; break; } self.pos += 1; } else |err| return err; const keywords = [_]std.meta.Tuple(&.{ []const u8, Token.Tag }){ .{ "type", .kw_type }, .{ "struct", .kw_struct }, .{ "ref", .kw_ref }, .{ "flat", .kw_flat }, .{ "view", .kw_view }, .{ "entry", .kw_entry }, .{ "fn", .kw_fn }, .{ "if", .kw_if }, .{ "else", .kw_else }, .{ "while", .kw_while }, .{ "for", .kw_for }, .{ "return", .kw_return }, .{ "break", .kw_break }, .{ "continue", .kw_continue }, .{ "and", .kw_and }, .{ "or", .kw_or }, .{ "const", .kw_const }, .{ "undefined", .kw_undefined }, .{ "var", .kw_var }, }; inline for (keywords) |kw| { if (try self.matchKeyword(kw[0])) |loc| { return Token{ .tag = kw[1], .loc = loc }; } } if (try self.parseLiteral()) |tok| return tok; if (try self.parseBuiltin()) |tok| return tok; if (try self.parseIdent()) |tok| return tok; const lits = [_]std.meta.Tuple(&.{ []const u8, Token.Tag }){ .{ ".", .dot }, .{ ",", .comma }, .{ "|", .pipe }, .{ ":", .colon }, .{ ";", .semicolon }, .{ "{", .lbrace }, .{ "}", .rbrace }, .{ "[", .lbracket }, .{ "]", .rbracket }, .{ "(", .lparen }, .{ ")", .rparen }, .{ "+=", .plus_eq }, .{ "-=", .minus_eq }, .{ "*=", .mult_eq }, .{ "/=", .div_eq }, .{ "%=", .mod_eq }, .{ "<<=", .lshift_eq }, .{ ">>=", .rshift_eq }, .{ "|=", .or_eq }, .{ "&=", .and_eq }, .{ "+", .plus }, .{ "-", .minus }, .{ "*", .mult }, .{ "/", .div }, .{ "%", .mod }, .{ "<<", .lshift }, .{ ">>", .rshift }, .{ "&", .@"and" }, .{ "==", .cmp_eq }, .{ ">=", .cmp_geq }, .{ "<=", .cmp_leq }, .{ ">", .cmp_gt }, .{ "<", .cmp_lt }, .{ "=", .equals }, }; inline for (lits) |l| { if (try self.match(l[0])) |loc| { return Token{ .tag = l[1], .loc = loc }; } } return error.BadToken; } fn parseLiteral(self: *Self) !?Token { const str = try self.getAlphaNum("+-0123456789", true); defer self.arena.allocator.free(str); if (str.len == 0) return null; const tag: Token.Tag = blk: { if (std.mem.indexOfScalar(u8, str, 'x')) |idx| { if (std.fmt.parseUnsigned(u64, str[0..idx], 10)) |rows| { if (std.fmt.parseUnsigned(u64, str[idx + 1 ..], 10)) |cols| { break :blk .{ .dimension = .{ rows, cols } }; } else |err| if (err == error.Overflow) return error.Overflow; } else |err| if (err == error.Overflow) return error.Overflow; } if (std.fmt.parseInt(i65, str, 0)) |i| { break :blk .{ .int_lit = i }; } else |err| switch (err) { error.Overflow => return error.Overflow, error.InvalidCharacter => {}, } if (std.fmt.parseFloat(f64, str)) |f| { break :blk .{ .float_lit = f }; } else |_| {} return error.BadLiteral; }; const start = self.pos; self.pos += str.len; const loc = Token.Loc{ .start = start, .end = self.pos }; return Token{ .loc = loc, .tag = tag }; } fn parseBuiltin(self: *Self) !?Token { const str = try self.getAlphaNum("@", false); if (str.len == 0) return null; const start = self.pos; self.pos += str.len; const loc = Token.Loc{ .start = start, .end = self.pos }; return Token{ .loc = loc, .tag = .{ .builtin = str } }; } // This will also consume literals, so it's important it's run // *after* parseLiteral fn parseIdent(self: *Self) !?Token { const str = try self.getAlphaNum(null, false); if (str.len == 0) return null; const tag: Token.Tag = blk: { if (str[0] == 'u' or str[0] == 's' or str[0] == 'f') { if (std.fmt.parseUnsigned(u64, str[1..], 10)) |x| { switch (str[0]) { 'u' => break :blk .{ .type_uint = x }, 's' => break :blk .{ .type_sint = x }, 'f' => break :blk .{ .type_float = x }, else => unreachable, } } else |_| {} } break :blk .{ .identifier = str }; }; const start = self.pos; self.pos += str.len; const loc = Token.Loc{ .start = start, .end = self.pos }; return Token{ .loc = loc, .tag = tag }; } fn getAlphaNum(self: *Self, first_chars: ?[]const u8, allow_dot: bool) ![]u8 { var str = std.ArrayList(u8).init(&self.arena.allocator); defer str.deinit(); var i: usize = 0; while (self.ps.reader().readByte()) |c| : (i += 1) { if (i == 0) { if (first_chars) |cs| { if (std.mem.indexOfScalar(u8, cs, c) == null) { self.ps.putBackByte(c) catch unreachable; break; } else { try str.append(c); continue; } } } if ((c < 'a' or c > 'z') and (c < 'A' or c > 'Z') and (c < '0' or c > '9') and c != '_' and (c != '.' or !allow_dot)) { self.ps.putBackByte(c) catch unreachable; break; } try str.append(c); } else |err| switch (err) { error.EndOfStream => {}, else => |e| return e, } return str.toOwnedSlice(); } fn match(self: *Self, comptime str: []const u8) !?Token.Loc { if (str.len > max_lookahead) @compileError("Insufficient lookahead"); for (str) |c, i| { const c1 = self.ps.reader().readByte() catch |err| switch (err) { error.EndOfStream => { self.ps.putBack(str[0..i]) catch unreachable; return null; }, else => |e| return e, }; if (c1 != c) { self.ps.putBackByte(c1) catch unreachable; self.ps.putBack(str[0..i]) catch unreachable; return null; } } const start = self.pos; self.pos += str.len; return Token.Loc{ .start = start, .end = self.pos }; } fn matchKeyword(self: *Self, comptime str: []const u8) !?Token.Loc { if (str.len + 1 > max_lookahead) @compileError("Insufficient lookahead"); const res = (try self.match(str)) orelse return null; const c = self.ps.reader().readByte() catch |err| switch (err) { error.EndOfStream => return res, else => |e| return e, }; if ((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c == '_') { self.ps.putBack(str) catch unreachable; return null; } return res; } }; } pub fn tokenizer(allocator: *std.mem.Allocator, r: anytype) Tokenizer(@TypeOf(r)) { return Tokenizer(@TypeOf(r)).init(allocator, r); } fn tokenEql(a: Token, b: Token) bool { if (a.loc.start != b.loc.start) return false; if (a.loc.end != b.loc.end) return false; if (@as(std.meta.Tag(Token.Tag), a.tag) != @as(std.meta.Tag(Token.Tag), b.tag)) return false; switch (a.tag) { .type_uint, .type_sint, .type_float => |x| switch (b.tag) { .type_uint, .type_sint, .type_float => |y| return x == y, else => unreachable, }, .int_lit => |x| return x == b.tag.int_lit, .float_lit => |x| return x == b.tag.float_lit, .dimension => |x| return std.meta.eql(x, b.tag.dimension), .identifier => |x| return std.mem.eql(u8, x, b.tag.identifier), .builtin => |x| return std.mem.eql(u8, x, b.tag.builtin), else => return true, } } test { var r = std.io.fixedBufferStream( \\ fn foo(x: u8) [3x4]u8 { \\ const y = @myBuiltin(x, 4.5); \\ \\ if (y) |y1| return y1; \\ \\ return .{ \\ 1, 2, 3, 4, \\ 2, 3, 4, 5, \\ 3, 4, 5, 6, \\ }; \\ } ).reader(); var tok = tokenizer(std.testing.allocator, r); defer tok.deinit(); const expected = [_]Token{ .{ .tag = .kw_fn, .loc = .{ .start = 1, .end = 3 } }, .{ .tag = .{ .identifier = "foo" }, .loc = .{ .start = 3, .end = 6 } }, .{ .tag = .lparen, .loc = .{ .start = 6, .end = 7 } }, .{ .tag = .{ .identifier = "x" }, .loc = .{ .start = 7, .end = 8 } }, .{ .tag = .colon, .loc = .{ .start = 8, .end = 9 } }, .{ .tag = .{ .type_uint = 8 }, .loc = .{ .start = 10, .end = 12 } }, .{ .tag = .rparen, .loc = .{ .start = 12, .end = 13 } }, .{ .tag = .lbracket, .loc = .{ .start = 14, .end = 15 } }, .{ .tag = .{ .dimension = .{ 3, 4 } }, .loc = .{ .start = 15, .end = 18 } }, .{ .tag = .rbracket, .loc = .{ .start = 18, .end = 19 } }, .{ .tag = .{ .type_uint = 8 }, .loc = .{ .start = 19, .end = 21 } }, .{ .tag = .lbrace, .loc = .{ .start = 22, .end = 23 } }, .{ .tag = .kw_const, .loc = .{ .start = 30, .end = 35 } }, .{ .tag = .{ .identifier = "y" }, .loc = .{ .start = 35, .end = 36 } }, .{ .tag = .equals, .loc = .{ .start = 37, .end = 38 } }, .{ .tag = .{ .builtin = "@myBuiltin" }, .loc = .{ .start = 39, .end = 49 } }, .{ .tag = .lparen, .loc = .{ .start = 49, .end = 50 } }, .{ .tag = .{ .identifier = "x" }, .loc = .{ .start = 50, .end = 51 } }, .{ .tag = .comma, .loc = .{ .start = 51, .end = 52 } }, .{ .tag = .{ .float_lit = 4.5e+00 }, .loc = .{ .start = 53, .end = 56 } }, .{ .tag = .rparen, .loc = .{ .start = 56, .end = 57 } }, .{ .tag = .semicolon, .loc = .{ .start = 57, .end = 58 } }, .{ .tag = .kw_if, .loc = .{ .start = 66, .end = 68 } }, .{ .tag = .lparen, .loc = .{ .start = 68, .end = 69 } }, .{ .tag = .{ .identifier = "y" }, .loc = .{ .start = 69, .end = 70 } }, .{ .tag = .rparen, .loc = .{ .start = 70, .end = 71 } }, .{ .tag = .pipe, .loc = .{ .start = 72, .end = 73 } }, .{ .tag = .{ .identifier = "y1" }, .loc = .{ .start = 73, .end = 75 } }, .{ .tag = .pipe, .loc = .{ .start = 75, .end = 76 } }, .{ .tag = .kw_return, .loc = .{ .start = 77, .end = 83 } }, .{ .tag = .{ .identifier = "y1" }, .loc = .{ .start = 83, .end = 85 } }, .{ .tag = .semicolon, .loc = .{ .start = 85, .end = 86 } }, .{ .tag = .kw_return, .loc = .{ .start = 94, .end = 100 } }, .{ .tag = .dot, .loc = .{ .start = 100, .end = 101 } }, .{ .tag = .lbrace, .loc = .{ .start = 101, .end = 102 } }, .{ .tag = .{ .int_lit = 1 }, .loc = .{ .start = 113, .end = 114 } }, .{ .tag = .comma, .loc = .{ .start = 114, .end = 115 } }, .{ .tag = .{ .int_lit = 2 }, .loc = .{ .start = 116, .end = 117 } }, .{ .tag = .comma, .loc = .{ .start = 117, .end = 118 } }, .{ .tag = .{ .int_lit = 3 }, .loc = .{ .start = 119, .end = 120 } }, .{ .tag = .comma, .loc = .{ .start = 120, .end = 121 } }, .{ .tag = .{ .int_lit = 4 }, .loc = .{ .start = 122, .end = 123 } }, .{ .tag = .comma, .loc = .{ .start = 123, .end = 124 } }, .{ .tag = .{ .int_lit = 2 }, .loc = .{ .start = 135, .end = 136 } }, .{ .tag = .comma, .loc = .{ .start = 136, .end = 137 } }, .{ .tag = .{ .int_lit = 3 }, .loc = .{ .start = 138, .end = 139 } }, .{ .tag = .comma, .loc = .{ .start = 139, .end = 140 } }, .{ .tag = .{ .int_lit = 4 }, .loc = .{ .start = 141, .end = 142 } }, .{ .tag = .comma, .loc = .{ .start = 142, .end = 143 } }, .{ .tag = .{ .int_lit = 5 }, .loc = .{ .start = 144, .end = 145 } }, .{ .tag = .comma, .loc = .{ .start = 145, .end = 146 } }, .{ .tag = .{ .int_lit = 3 }, .loc = .{ .start = 157, .end = 158 } }, .{ .tag = .comma, .loc = .{ .start = 158, .end = 159 } }, .{ .tag = .{ .int_lit = 4 }, .loc = .{ .start = 160, .end = 161 } }, .{ .tag = .comma, .loc = .{ .start = 161, .end = 162 } }, .{ .tag = .{ .int_lit = 5 }, .loc = .{ .start = 163, .end = 164 } }, .{ .tag = .comma, .loc = .{ .start = 164, .end = 165 } }, .{ .tag = .{ .int_lit = 6 }, .loc = .{ .start = 166, .end = 167 } }, .{ .tag = .comma, .loc = .{ .start = 167, .end = 168 } }, .{ .tag = .rbrace, .loc = .{ .start = 175, .end = 176 } }, .{ .tag = .semicolon, .loc = .{ .start = 176, .end = 177 } }, .{ .tag = .rbrace, .loc = .{ .start = 179, .end = 180 } }, }; var i: usize = 0; while (tok.next()) |t| : (i += 1) { try std.testing.expect(i < expected.len); try std.testing.expect(tokenEql(t, expected[i])); } else |err| switch (err) { error.EndOfStream => {}, else => |e| return e, } try std.testing.expectEqual(i, expected.len); }
src/tokenizer.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; const Id = @import("./ui.zig").Id; const Rect = @import("./ui.zig").Rect; const Text = @import("./ui.zig").Text; const TextAlignment = @import("./ui.zig").TextAlignment; const Triangle = @import("./ui.zig").Triangle; const TriangleDir = @import("./ui.zig").TriangleDir; const Color = @import("./ui.zig").Color; pub const Clip = struct { x: f32, y: f32, w: f32, h: f32 }; pub const DrawCommand = union(enum) { Text: Text, Triangle: Triangle, Rect: Rect, Clip: Clip, }; pub const DrawerData = struct { vertices: []f32, indices: []u32 }; const CommandList = ArrayList(DrawCommand); const DrawCommands = AutoHashMap(Id, CommandList); pub const DrawSlice = struct { offset: usize, vertex_count: usize, texts: []Text, clip: Clip, }; pub const Drawer = struct { command_id: Id = 0, commands: DrawCommands, draw_list: ArrayList(DrawSlice), _vertices: ArrayList(f32), _indices: ArrayList(u32), _texts: ArrayList(Text), allocator: *Allocator, const Self = @This(); // TODO: USE THE ARENA ALLOCATOR FOR THE _TEXTS // ANS FIX THE BUG. pub fn init(arena_alloc: *Allocator) Self { return .{ .commands = DrawCommands.init(arena_alloc), .draw_list = ArrayList(DrawSlice).init(arena_alloc), ._vertices = ArrayList(f32).init(arena_alloc), ._indices = ArrayList(u32).init(arena_alloc), // Temporary hack! ._texts = ArrayList(Text).init(std.heap.page_allocator), .allocator = arena_alloc, }; } pub fn set_cmd_id(drawer: *Self, id: Id) void { drawer.command_id = id; _ = drawer.commands.getOrPutValue( id, CommandList.init(drawer.allocator) ) catch unreachable; } /// We're trying to save some system call by retaining capacity. pub fn reset(drawer: *Self) void { var it = drawer.commands.iterator(); while (it.next()) |*entry| entry.*.value_ptr.shrinkAndFree(0); drawer.draw_list.shrinkRetainingCapacity(0); drawer._vertices.shrinkRetainingCapacity(0); drawer._indices.shrinkRetainingCapacity(0); drawer._texts.shrinkRetainingCapacity(0); } /// Get vertex and indices from the UI. /// Here, user should send the data to the GPU. It's /// the step just before drawing it. pub fn process_ui(drawer: *Self, orders: []const Id) DrawerData { var i: u32 = 0; var offset: usize = 0; var text_offset: usize = 0; for (orders) |overlay_id| { if (drawer.commands.get(overlay_id)) |cmd_list| { var vertex_count: usize = 0; var clip: Clip = undefined; for (cmd_list.items) |cmd| { switch (cmd) { .Triangle => |triangle| { const e = triangle.edges; const c = triangle.color.to_array(); drawer._vertices.appendSlice(&[_]f32{ e[0], e[1], 0, 0, c[0], c[1], c[2], c[3], e[2], e[3], 0, 0, c[0], c[1], c[2], c[3], e[4], e[5], 0, 0, c[0], c[1], c[2], c[3], }) catch unreachable; drawer._indices.appendSlice(&[_]u32{ 0 + i, 1 + i, 2 + i, }) catch unreachable; i += 3; vertex_count += 3; }, .Rect => |rect| { const a_x = rect.x; const a_y = rect.y; const b_x = rect.x + rect.w; const b_y = rect.y; const c_x = rect.x + rect.w; const c_y = rect.y + rect.h; const d_x = rect.x; const d_y = rect.y + rect.h; const c = rect.color.to_array(); // POS, UV, COLOR drawer._vertices.appendSlice(&[_]f32{ a_x, a_y, 0, 0, c[0], c[1], c[2], c[3], b_x, b_y, 0, 0, c[0], c[1], c[2], c[3], c_x, c_y, 0, 0, c[0], c[1], c[2], c[3], d_x, d_y, 0, 0, c[0], c[1], c[2], c[3], }) catch unreachable; drawer._indices.appendSlice(&[_]u32{ 0 + i, 1 + i, 2 + i, 0 + i, 2 + i, 3 + i, }) catch unreachable; i += 4; vertex_count += 6; }, .Clip => |clip_bounds| { clip = clip_bounds; }, .Text => |text| { drawer._texts.append(text) catch unreachable; }, } } drawer.draw_list.append(.{ .vertex_count = vertex_count, .texts = drawer._texts.items[text_offset..], .offset = offset, .clip = clip, }) catch unreachable; if (drawer._texts.items.len > 0) { text_offset = drawer._texts.items.len; } offset += vertex_count; } } return .{ .vertices = drawer._vertices.items, .indices = drawer._indices.items, }; } pub fn push_rect(drawer: *Self, r: Rect) void { const id = drawer.command_id; if (drawer.commands.getEntry(id)) |*entry| { entry.*.value_ptr.append(.{ .Rect = r }) catch unreachable; } } pub fn push_triangle( drawer: *Self, region: Rect, _: f32, color: Color, direction: TriangleDir, ) void { const id = drawer.command_id; if (drawer.commands.getEntry(id)) |*entry| { const triangle = Triangle.new(region, color, direction); entry.value_ptr.append(.{ .Triangle = triangle }) catch unreachable; } } pub fn push_clip(drawer: *Self, x: f32, y: f32, w: f32, h: f32) void { const id = drawer.command_id; if (drawer.commands.getEntry(id)) |*entry| { entry.value_ptr.append(.{ .Clip = .{ .x = x, .y = y, .w = w, .h = h, }, }) catch unreachable; } } pub fn push_text(drawer: *Self, text: Text) void { const id = drawer.command_id; if (drawer.commands.getEntry(id)) |*entry| { entry.value_ptr.append(.{ .Text = text }) catch unreachable; } } pub fn push_borders( drawer: *Self, r: Rect, thickness: f32, color: Color, ) void { const id = drawer.command_id; if (drawer.commands.getEntry(id)) |*entry| { entry.value_ptr.appendSlice(&[4]DrawCommand{ .{ .Rect = .{ .x = r.x, .y = r.y, .w = thickness, .h = r.h, .color = color, }, }, // Right. .{ .Rect = .{ .x = r.x + r.w - thickness, .y = r.y, .w = thickness, .h = r.h, .color = color, }, }, // Top. .{ .Rect = .{ .x = r.x, .y = r.y, .w = r.w, .h = thickness, .color = color, }, }, // Bottom. .{ .Rect = .{ .x = r.x, .y = r.y + r.h - thickness, .w = r.w, .h = thickness, .color = color, }, }, } ) catch unreachable; } } };
src/drawer.zig
pub fn isUnassigned(cp: u21) bool { if (cp < 0x378 or cp > 0x10ffff) return false; return switch (cp) { 0x378...0x379 => true, 0x380...0x383 => true, 0x38b => true, 0x38d => true, 0x3a2 => true, 0x530 => true, 0x557...0x558 => true, 0x58b...0x58c => true, 0x590 => true, 0x5c8...0x5cf => true, 0x5eb...0x5ee => true, 0x5f5...0x5ff => true, 0x70e => true, 0x74b...0x74c => true, 0x7b2...0x7bf => true, 0x7fb...0x7fc => true, 0x82e...0x82f => true, 0x83f => true, 0x85c...0x85d => true, 0x85f => true, 0x86b...0x86f => true, 0x88f => true, 0x892...0x897 => true, 0x984 => true, 0x98d...0x98e => true, 0x991...0x992 => true, 0x9a9 => true, 0x9b1 => true, 0x9b3...0x9b5 => true, 0x9ba...0x9bb => true, 0x9c5...0x9c6 => true, 0x9c9...0x9ca => true, 0x9cf...0x9d6 => true, 0x9d8...0x9db => true, 0x9de => true, 0x9e4...0x9e5 => true, 0x9ff...0xa00 => true, 0xa04 => true, 0xa0b...0xa0e => true, 0xa11...0xa12 => true, 0xa29 => true, 0xa31 => true, 0xa34 => true, 0xa37 => true, 0xa3a...0xa3b => true, 0xa3d => true, 0xa43...0xa46 => true, 0xa49...0xa4a => true, 0xa4e...0xa50 => true, 0xa52...0xa58 => true, 0xa5d => true, 0xa5f...0xa65 => true, 0xa77...0xa80 => true, 0xa84 => true, 0xa8e => true, 0xa92 => true, 0xaa9 => true, 0xab1 => true, 0xab4 => true, 0xaba...0xabb => true, 0xac6 => true, 0xaca => true, 0xace...0xacf => true, 0xad1...0xadf => true, 0xae4...0xae5 => true, 0xaf2...0xaf8 => true, 0xb00 => true, 0xb04 => true, 0xb0d...0xb0e => true, 0xb11...0xb12 => true, 0xb29 => true, 0xb31 => true, 0xb34 => true, 0xb3a...0xb3b => true, 0xb45...0xb46 => true, 0xb49...0xb4a => true, 0xb4e...0xb54 => true, 0xb58...0xb5b => true, 0xb5e => true, 0xb64...0xb65 => true, 0xb78...0xb81 => true, 0xb84 => true, 0xb8b...0xb8d => true, 0xb91 => true, 0xb96...0xb98 => true, 0xb9b => true, 0xb9d => true, 0xba0...0xba2 => true, 0xba5...0xba7 => true, 0xbab...0xbad => true, 0xbba...0xbbd => true, 0xbc3...0xbc5 => true, 0xbc9 => true, 0xbce...0xbcf => true, 0xbd1...0xbd6 => true, 0xbd8...0xbe5 => true, 0xbfb...0xbff => true, 0xc0d => true, 0xc11 => true, 0xc29 => true, 0xc3a...0xc3b => true, 0xc45 => true, 0xc49 => true, 0xc4e...0xc54 => true, 0xc57 => true, 0xc5b...0xc5c => true, 0xc5e...0xc5f => true, 0xc64...0xc65 => true, 0xc70...0xc76 => true, 0xc8d => true, 0xc91 => true, 0xca9 => true, 0xcb4 => true, 0xcba...0xcbb => true, 0xcc5 => true, 0xcc9 => true, 0xcce...0xcd4 => true, 0xcd7...0xcdc => true, 0xcdf => true, 0xce4...0xce5 => true, 0xcf0 => true, 0xcf3...0xcff => true, 0xd0d => true, 0xd11 => true, 0xd45 => true, 0xd49 => true, 0xd50...0xd53 => true, 0xd64...0xd65 => true, 0xd80 => true, 0xd84 => true, 0xd97...0xd99 => true, 0xdb2 => true, 0xdbc => true, 0xdbe...0xdbf => true, 0xdc7...0xdc9 => true, 0xdcb...0xdce => true, 0xdd5 => true, 0xdd7 => true, 0xde0...0xde5 => true, 0xdf0...0xdf1 => true, 0xdf5...0xe00 => true, 0xe3b...0xe3e => true, 0xe5c...0xe80 => true, 0xe83 => true, 0xe85 => true, 0xe8b => true, 0xea4 => true, 0xea6 => true, 0xebe...0xebf => true, 0xec5 => true, 0xec7 => true, 0xece...0xecf => true, 0xeda...0xedb => true, 0xee0...0xeff => true, 0xf48 => true, 0xf6d...0xf70 => true, 0xf98 => true, 0xfbd => true, 0xfcd => true, 0xfdb...0xfff => true, 0x10c6 => true, 0x10c8...0x10cc => true, 0x10ce...0x10cf => true, 0x1249 => true, 0x124e...0x124f => true, 0x1257 => true, 0x1259 => true, 0x125e...0x125f => true, 0x1289 => true, 0x128e...0x128f => true, 0x12b1 => true, 0x12b6...0x12b7 => true, 0x12bf => true, 0x12c1 => true, 0x12c6...0x12c7 => true, 0x12d7 => true, 0x1311 => true, 0x1316...0x1317 => true, 0x135b...0x135c => true, 0x137d...0x137f => true, 0x139a...0x139f => true, 0x13f6...0x13f7 => true, 0x13fe...0x13ff => true, 0x169d...0x169f => true, 0x16f9...0x16ff => true, 0x1716...0x171e => true, 0x1737...0x173f => true, 0x1754...0x175f => true, 0x176d => true, 0x1771 => true, 0x1774...0x177f => true, 0x17de...0x17df => true, 0x17ea...0x17ef => true, 0x17fa...0x17ff => true, 0x181a...0x181f => true, 0x1879...0x187f => true, 0x18ab...0x18af => true, 0x18f6...0x18ff => true, 0x191f => true, 0x192c...0x192f => true, 0x193c...0x193f => true, 0x1941...0x1943 => true, 0x196e...0x196f => true, 0x1975...0x197f => true, 0x19ac...0x19af => true, 0x19ca...0x19cf => true, 0x19db...0x19dd => true, 0x1a1c...0x1a1d => true, 0x1a5f => true, 0x1a7d...0x1a7e => true, 0x1a8a...0x1a8f => true, 0x1a9a...0x1a9f => true, 0x1aae...0x1aaf => true, 0x1acf...0x1aff => true, 0x1b4d...0x1b4f => true, 0x1b7f => true, 0x1bf4...0x1bfb => true, 0x1c38...0x1c3a => true, 0x1c4a...0x1c4c => true, 0x1c89...0x1c8f => true, 0x1cbb...0x1cbc => true, 0x1cc8...0x1ccf => true, 0x1cfb...0x1cff => true, 0x1f16...0x1f17 => true, 0x1f1e...0x1f1f => true, 0x1f46...0x1f47 => true, 0x1f4e...0x1f4f => true, 0x1f58 => true, 0x1f5a => true, 0x1f5c => true, 0x1f5e => true, 0x1f7e...0x1f7f => true, 0x1fb5 => true, 0x1fc5 => true, 0x1fd4...0x1fd5 => true, 0x1fdc => true, 0x1ff0...0x1ff1 => true, 0x1ff5 => true, 0x1fff => true, 0x2065 => true, 0x2072...0x2073 => true, 0x208f => true, 0x209d...0x209f => true, 0x20c1...0x20cf => true, 0x20f1...0x20ff => true, 0x218c...0x218f => true, 0x2427...0x243f => true, 0x244b...0x245f => true, 0x2b74...0x2b75 => true, 0x2b96 => true, 0x2cf4...0x2cf8 => true, 0x2d26 => true, 0x2d28...0x2d2c => true, 0x2d2e...0x2d2f => true, 0x2d68...0x2d6e => true, 0x2d71...0x2d7e => true, 0x2d97...0x2d9f => true, 0x2da7 => true, 0x2daf => true, 0x2db7 => true, 0x2dbf => true, 0x2dc7 => true, 0x2dcf => true, 0x2dd7 => true, 0x2ddf => true, 0x2e5e...0x2e7f => true, 0x2e9a => true, 0x2ef4...0x2eff => true, 0x2fd6...0x2fef => true, 0x2ffc...0x2fff => true, 0x3040 => true, 0x3097...0x3098 => true, 0x3100...0x3104 => true, 0x3130 => true, 0x318f => true, 0x31e4...0x31ef => true, 0x321f => true, 0xa48d...0xa48f => true, 0xa4c7...0xa4cf => true, 0xa62c...0xa63f => true, 0xa6f8...0xa6ff => true, 0xa7cb...0xa7cf => true, 0xa7d2 => true, 0xa7d4 => true, 0xa7da...0xa7f1 => true, 0xa82d...0xa82f => true, 0xa83a...0xa83f => true, 0xa878...0xa87f => true, 0xa8c6...0xa8cd => true, 0xa8da...0xa8df => true, 0xa954...0xa95e => true, 0xa97d...0xa97f => true, 0xa9ce => true, 0xa9da...0xa9dd => true, 0xa9ff => true, 0xaa37...0xaa3f => true, 0xaa4e...0xaa4f => true, 0xaa5a...0xaa5b => true, 0xaac3...0xaada => true, 0xaaf7...0xab00 => true, 0xab07...0xab08 => true, 0xab0f...0xab10 => true, 0xab17...0xab1f => true, 0xab27 => true, 0xab2f => true, 0xab6c...0xab6f => true, 0xabee...0xabef => true, 0xabfa...0xabff => true, 0xd7a4...0xd7af => true, 0xd7c7...0xd7ca => true, 0xd7fc...0xd7ff => true, 0xfa6e...0xfa6f => true, 0xfada...0xfaff => true, 0xfb07...0xfb12 => true, 0xfb18...0xfb1c => true, 0xfb37 => true, 0xfb3d => true, 0xfb3f => true, 0xfb42 => true, 0xfb45 => true, 0xfbc3...0xfbd2 => true, 0xfd90...0xfd91 => true, 0xfdc8...0xfdce => true, 0xfdd0...0xfdef => true, 0xfe1a...0xfe1f => true, 0xfe53 => true, 0xfe67 => true, 0xfe6c...0xfe6f => true, 0xfe75 => true, 0xfefd...0xfefe => true, 0xff00 => true, 0xffbf...0xffc1 => true, 0xffc8...0xffc9 => true, 0xffd0...0xffd1 => true, 0xffd8...0xffd9 => true, 0xffdd...0xffdf => true, 0xffe7 => true, 0xffef...0xfff8 => true, 0xfffe...0xffff => true, 0x1000c => true, 0x10027 => true, 0x1003b => true, 0x1003e => true, 0x1004e...0x1004f => true, 0x1005e...0x1007f => true, 0x100fb...0x100ff => true, 0x10103...0x10106 => true, 0x10134...0x10136 => true, 0x1018f => true, 0x1019d...0x1019f => true, 0x101a1...0x101cf => true, 0x101fe...0x1027f => true, 0x1029d...0x1029f => true, 0x102d1...0x102df => true, 0x102fc...0x102ff => true, 0x10324...0x1032c => true, 0x1034b...0x1034f => true, 0x1037b...0x1037f => true, 0x1039e => true, 0x103c4...0x103c7 => true, 0x103d6...0x103ff => true, 0x1049e...0x1049f => true, 0x104aa...0x104af => true, 0x104d4...0x104d7 => true, 0x104fc...0x104ff => true, 0x10528...0x1052f => true, 0x10564...0x1056e => true, 0x1057b => true, 0x1058b => true, 0x10593 => true, 0x10596 => true, 0x105a2 => true, 0x105b2 => true, 0x105ba => true, 0x105bd...0x105ff => true, 0x10737...0x1073f => true, 0x10756...0x1075f => true, 0x10768...0x1077f => true, 0x10786 => true, 0x107b1 => true, 0x107bb...0x107ff => true, 0x10806...0x10807 => true, 0x10809 => true, 0x10836 => true, 0x10839...0x1083b => true, 0x1083d...0x1083e => true, 0x10856 => true, 0x1089f...0x108a6 => true, 0x108b0...0x108df => true, 0x108f3 => true, 0x108f6...0x108fa => true, 0x1091c...0x1091e => true, 0x1093a...0x1093e => true, 0x10940...0x1097f => true, 0x109b8...0x109bb => true, 0x109d0...0x109d1 => true, 0x10a04 => true, 0x10a07...0x10a0b => true, 0x10a14 => true, 0x10a18 => true, 0x10a36...0x10a37 => true, 0x10a3b...0x10a3e => true, 0x10a49...0x10a4f => true, 0x10a59...0x10a5f => true, 0x10aa0...0x10abf => true, 0x10ae7...0x10aea => true, 0x10af7...0x10aff => true, 0x10b36...0x10b38 => true, 0x10b56...0x10b57 => true, 0x10b73...0x10b77 => true, 0x10b92...0x10b98 => true, 0x10b9d...0x10ba8 => true, 0x10bb0...0x10bff => true, 0x10c49...0x10c7f => true, 0x10cb3...0x10cbf => true, 0x10cf3...0x10cf9 => true, 0x10d28...0x10d2f => true, 0x10d3a...0x10e5f => true, 0x10e7f => true, 0x10eaa => true, 0x10eae...0x10eaf => true, 0x10eb2...0x10eff => true, 0x10f28...0x10f2f => true, 0x10f5a...0x10f6f => true, 0x10f8a...0x10faf => true, 0x10fcc...0x10fdf => true, 0x10ff7...0x10fff => true, 0x1104e...0x11051 => true, 0x11076...0x1107e => true, 0x110c3...0x110cc => true, 0x110ce...0x110cf => true, 0x110e9...0x110ef => true, 0x110fa...0x110ff => true, 0x11135 => true, 0x11148...0x1114f => true, 0x11177...0x1117f => true, 0x111e0 => true, 0x111f5...0x111ff => true, 0x11212 => true, 0x1123f...0x1127f => true, 0x11287 => true, 0x11289 => true, 0x1128e => true, 0x1129e => true, 0x112aa...0x112af => true, 0x112eb...0x112ef => true, 0x112fa...0x112ff => true, 0x11304 => true, 0x1130d...0x1130e => true, 0x11311...0x11312 => true, 0x11329 => true, 0x11331 => true, 0x11334 => true, 0x1133a => true, 0x11345...0x11346 => true, 0x11349...0x1134a => true, 0x1134e...0x1134f => true, 0x11351...0x11356 => true, 0x11358...0x1135c => true, 0x11364...0x11365 => true, 0x1136d...0x1136f => true, 0x11375...0x113ff => true, 0x1145c => true, 0x11462...0x1147f => true, 0x114c8...0x114cf => true, 0x114da...0x1157f => true, 0x115b6...0x115b7 => true, 0x115de...0x115ff => true, 0x11645...0x1164f => true, 0x1165a...0x1165f => true, 0x1166d...0x1167f => true, 0x116ba...0x116bf => true, 0x116ca...0x116ff => true, 0x1171b...0x1171c => true, 0x1172c...0x1172f => true, 0x11747...0x117ff => true, 0x1183c...0x1189f => true, 0x118f3...0x118fe => true, 0x11907...0x11908 => true, 0x1190a...0x1190b => true, 0x11914 => true, 0x11917 => true, 0x11936 => true, 0x11939...0x1193a => true, 0x11947...0x1194f => true, 0x1195a...0x1199f => true, 0x119a8...0x119a9 => true, 0x119d8...0x119d9 => true, 0x119e5...0x119ff => true, 0x11a48...0x11a4f => true, 0x11aa3...0x11aaf => true, 0x11af9...0x11bff => true, 0x11c09 => true, 0x11c37 => true, 0x11c46...0x11c4f => true, 0x11c6d...0x11c6f => true, 0x11c90...0x11c91 => true, 0x11ca8 => true, 0x11cb7...0x11cff => true, 0x11d07 => true, 0x11d0a => true, 0x11d37...0x11d39 => true, 0x11d3b => true, 0x11d3e => true, 0x11d48...0x11d4f => true, 0x11d5a...0x11d5f => true, 0x11d66 => true, 0x11d69 => true, 0x11d8f => true, 0x11d92 => true, 0x11d99...0x11d9f => true, 0x11daa...0x11edf => true, 0x11ef9...0x11faf => true, 0x11fb1...0x11fbf => true, 0x11ff2...0x11ffe => true, 0x1239a...0x123ff => true, 0x1246f => true, 0x12475...0x1247f => true, 0x12544...0x12f8f => true, 0x12ff3...0x12fff => true, 0x1342f => true, 0x13439...0x143ff => true, 0x14647...0x167ff => true, 0x16a39...0x16a3f => true, 0x16a5f => true, 0x16a6a...0x16a6d => true, 0x16abf => true, 0x16aca...0x16acf => true, 0x16aee...0x16aef => true, 0x16af6...0x16aff => true, 0x16b46...0x16b4f => true, 0x16b5a => true, 0x16b62 => true, 0x16b78...0x16b7c => true, 0x16b90...0x16e3f => true, 0x16e9b...0x16eff => true, 0x16f4b...0x16f4e => true, 0x16f88...0x16f8e => true, 0x16fa0...0x16fdf => true, 0x16fe5...0x16fef => true, 0x16ff2...0x16fff => true, 0x187f8...0x187ff => true, 0x18cd6...0x18cff => true, 0x18d09...0x1afef => true, 0x1aff4 => true, 0x1affc => true, 0x1afff => true, 0x1b123...0x1b14f => true, 0x1b153...0x1b163 => true, 0x1b168...0x1b16f => true, 0x1b2fc...0x1bbff => true, 0x1bc6b...0x1bc6f => true, 0x1bc7d...0x1bc7f => true, 0x1bc89...0x1bc8f => true, 0x1bc9a...0x1bc9b => true, 0x1bca4...0x1ceff => true, 0x1cf2e...0x1cf2f => true, 0x1cf47...0x1cf4f => true, 0x1cfc4...0x1cfff => true, 0x1d0f6...0x1d0ff => true, 0x1d127...0x1d128 => true, 0x1d1eb...0x1d1ff => true, 0x1d246...0x1d2df => true, 0x1d2f4...0x1d2ff => true, 0x1d357...0x1d35f => true, 0x1d379...0x1d3ff => true, 0x1d455 => true, 0x1d49d => true, 0x1d4a0...0x1d4a1 => true, 0x1d4a3...0x1d4a4 => true, 0x1d4a7...0x1d4a8 => true, 0x1d4ad => true, 0x1d4ba => true, 0x1d4bc => true, 0x1d4c4 => true, 0x1d506 => true, 0x1d50b...0x1d50c => true, 0x1d515 => true, 0x1d51d => true, 0x1d53a => true, 0x1d53f => true, 0x1d545 => true, 0x1d547...0x1d549 => true, 0x1d551 => true, 0x1d6a6...0x1d6a7 => true, 0x1d7cc...0x1d7cd => true, 0x1da8c...0x1da9a => true, 0x1daa0 => true, 0x1dab0...0x1deff => true, 0x1df1f...0x1dfff => true, 0x1e007 => true, 0x1e019...0x1e01a => true, 0x1e022 => true, 0x1e025 => true, 0x1e02b...0x1e0ff => true, 0x1e12d...0x1e12f => true, 0x1e13e...0x1e13f => true, 0x1e14a...0x1e14d => true, 0x1e150...0x1e28f => true, 0x1e2af...0x1e2bf => true, 0x1e2fa...0x1e2fe => true, 0x1e300...0x1e7df => true, 0x1e7e7 => true, 0x1e7ec => true, 0x1e7ef => true, 0x1e7ff => true, 0x1e8c5...0x1e8c6 => true, 0x1e8d7...0x1e8ff => true, 0x1e94c...0x1e94f => true, 0x1e95a...0x1e95d => true, 0x1e960...0x1ec70 => true, 0x1ecb5...0x1ed00 => true, 0x1ed3e...0x1edff => true, 0x1ee04 => true, 0x1ee20 => true, 0x1ee23 => true, 0x1ee25...0x1ee26 => true, 0x1ee28 => true, 0x1ee33 => true, 0x1ee38 => true, 0x1ee3a => true, 0x1ee3c...0x1ee41 => true, 0x1ee43...0x1ee46 => true, 0x1ee48 => true, 0x1ee4a => true, 0x1ee4c => true, 0x1ee50 => true, 0x1ee53 => true, 0x1ee55...0x1ee56 => true, 0x1ee58 => true, 0x1ee5a => true, 0x1ee5c => true, 0x1ee5e => true, 0x1ee60 => true, 0x1ee63 => true, 0x1ee65...0x1ee66 => true, 0x1ee6b => true, 0x1ee73 => true, 0x1ee78 => true, 0x1ee7d => true, 0x1ee7f => true, 0x1ee8a => true, 0x1ee9c...0x1eea0 => true, 0x1eea4 => true, 0x1eeaa => true, 0x1eebc...0x1eeef => true, 0x1eef2...0x1efff => true, 0x1f02c...0x1f02f => true, 0x1f094...0x1f09f => true, 0x1f0af...0x1f0b0 => true, 0x1f0c0 => true, 0x1f0d0 => true, 0x1f0f6...0x1f0ff => true, 0x1f1ae...0x1f1e5 => true, 0x1f203...0x1f20f => true, 0x1f23c...0x1f23f => true, 0x1f249...0x1f24f => true, 0x1f252...0x1f25f => true, 0x1f266...0x1f2ff => true, 0x1f6d8...0x1f6dc => true, 0x1f6ed...0x1f6ef => true, 0x1f6fd...0x1f6ff => true, 0x1f774...0x1f77f => true, 0x1f7d9...0x1f7df => true, 0x1f7ec...0x1f7ef => true, 0x1f7f1...0x1f7ff => true, 0x1f80c...0x1f80f => true, 0x1f848...0x1f84f => true, 0x1f85a...0x1f85f => true, 0x1f888...0x1f88f => true, 0x1f8ae...0x1f8af => true, 0x1f8b2...0x1f8ff => true, 0x1fa54...0x1fa5f => true, 0x1fa6e...0x1fa6f => true, 0x1fa75...0x1fa77 => true, 0x1fa7d...0x1fa7f => true, 0x1fa87...0x1fa8f => true, 0x1faad...0x1faaf => true, 0x1fabb...0x1fabf => true, 0x1fac6...0x1facf => true, 0x1fada...0x1fadf => true, 0x1fae8...0x1faef => true, 0x1faf7...0x1faff => true, 0x1fb93 => true, 0x1fbcb...0x1fbef => true, 0x1fbfa...0x1ffff => true, 0x2a6e0...0x2a6ff => true, 0x2b739...0x2b73f => true, 0x2b81e...0x2b81f => true, 0x2cea2...0x2ceaf => true, 0x2ebe1...0x2f7ff => true, 0x2fa1e...0x2ffff => true, 0x3134b...0xe0000 => true, 0xe0002...0xe001f => true, 0xe0080...0xe00ff => true, 0xe01f0...0xeffff => true, 0xffffe...0xfffff => true, 0x10fffe...0x10ffff => true, else => false, }; } pub fn isUppercaseLetter(cp: u21) bool { if (cp < 0x41 or cp > 0x1e921) return false; return switch (cp) { 0x41...0x5a => true, 0xc0...0xd6 => true, 0xd8...0xde => true, 0x100 => true, 0x102 => true, 0x104 => true, 0x106 => true, 0x108 => true, 0x10a => true, 0x10c => true, 0x10e => true, 0x110 => true, 0x112 => true, 0x114 => true, 0x116 => true, 0x118 => true, 0x11a => true, 0x11c => true, 0x11e => true, 0x120 => true, 0x122 => true, 0x124 => true, 0x126 => true, 0x128 => true, 0x12a => true, 0x12c => true, 0x12e => true, 0x130 => true, 0x132 => true, 0x134 => true, 0x136 => true, 0x139 => true, 0x13b => true, 0x13d => true, 0x13f => true, 0x141 => true, 0x143 => true, 0x145 => true, 0x147 => true, 0x14a => true, 0x14c => true, 0x14e => true, 0x150 => true, 0x152 => true, 0x154 => true, 0x156 => true, 0x158 => true, 0x15a => true, 0x15c => true, 0x15e => true, 0x160 => true, 0x162 => true, 0x164 => true, 0x166 => true, 0x168 => true, 0x16a => true, 0x16c => true, 0x16e => true, 0x170 => true, 0x172 => true, 0x174 => true, 0x176 => true, 0x178...0x179 => true, 0x17b => true, 0x17d => true, 0x181...0x182 => true, 0x184 => true, 0x186...0x187 => true, 0x189...0x18b => true, 0x18e...0x191 => true, 0x193...0x194 => true, 0x196...0x198 => true, 0x19c...0x19d => true, 0x19f...0x1a0 => true, 0x1a2 => true, 0x1a4 => true, 0x1a6...0x1a7 => true, 0x1a9 => true, 0x1ac => true, 0x1ae...0x1af => true, 0x1b1...0x1b3 => true, 0x1b5 => true, 0x1b7...0x1b8 => true, 0x1bc => true, 0x1c4 => true, 0x1c7 => true, 0x1ca => true, 0x1cd => true, 0x1cf => true, 0x1d1 => true, 0x1d3 => true, 0x1d5 => true, 0x1d7 => true, 0x1d9 => true, 0x1db => true, 0x1de => true, 0x1e0 => true, 0x1e2 => true, 0x1e4 => true, 0x1e6 => true, 0x1e8 => true, 0x1ea => true, 0x1ec => true, 0x1ee => true, 0x1f1 => true, 0x1f4 => true, 0x1f6...0x1f8 => true, 0x1fa => true, 0x1fc => true, 0x1fe => true, 0x200 => true, 0x202 => true, 0x204 => true, 0x206 => true, 0x208 => true, 0x20a => true, 0x20c => true, 0x20e => true, 0x210 => true, 0x212 => true, 0x214 => true, 0x216 => true, 0x218 => true, 0x21a => true, 0x21c => true, 0x21e => true, 0x220 => true, 0x222 => true, 0x224 => true, 0x226 => true, 0x228 => true, 0x22a => true, 0x22c => true, 0x22e => true, 0x230 => true, 0x232 => true, 0x23a...0x23b => true, 0x23d...0x23e => true, 0x241 => true, 0x243...0x246 => true, 0x248 => true, 0x24a => true, 0x24c => true, 0x24e => true, 0x370 => true, 0x372 => true, 0x376 => true, 0x37f => true, 0x386 => true, 0x388...0x38a => true, 0x38c => true, 0x38e...0x38f => true, 0x391...0x3a1 => true, 0x3a3...0x3ab => true, 0x3cf => true, 0x3d2...0x3d4 => true, 0x3d8 => true, 0x3da => true, 0x3dc => true, 0x3de => true, 0x3e0 => true, 0x3e2 => true, 0x3e4 => true, 0x3e6 => true, 0x3e8 => true, 0x3ea => true, 0x3ec => true, 0x3ee => true, 0x3f4 => true, 0x3f7 => true, 0x3f9...0x3fa => true, 0x3fd...0x42f => true, 0x460 => true, 0x462 => true, 0x464 => true, 0x466 => true, 0x468 => true, 0x46a => true, 0x46c => true, 0x46e => true, 0x470 => true, 0x472 => true, 0x474 => true, 0x476 => true, 0x478 => true, 0x47a => true, 0x47c => true, 0x47e => true, 0x480 => true, 0x48a => true, 0x48c => true, 0x48e => true, 0x490 => true, 0x492 => true, 0x494 => true, 0x496 => true, 0x498 => true, 0x49a => true, 0x49c => true, 0x49e => true, 0x4a0 => true, 0x4a2 => true, 0x4a4 => true, 0x4a6 => true, 0x4a8 => true, 0x4aa => true, 0x4ac => true, 0x4ae => true, 0x4b0 => true, 0x4b2 => true, 0x4b4 => true, 0x4b6 => true, 0x4b8 => true, 0x4ba => true, 0x4bc => true, 0x4be => true, 0x4c0...0x4c1 => true, 0x4c3 => true, 0x4c5 => true, 0x4c7 => true, 0x4c9 => true, 0x4cb => true, 0x4cd => true, 0x4d0 => true, 0x4d2 => true, 0x4d4 => true, 0x4d6 => true, 0x4d8 => true, 0x4da => true, 0x4dc => true, 0x4de => true, 0x4e0 => true, 0x4e2 => true, 0x4e4 => true, 0x4e6 => true, 0x4e8 => true, 0x4ea => true, 0x4ec => true, 0x4ee => true, 0x4f0 => true, 0x4f2 => true, 0x4f4 => true, 0x4f6 => true, 0x4f8 => true, 0x4fa => true, 0x4fc => true, 0x4fe => true, 0x500 => true, 0x502 => true, 0x504 => true, 0x506 => true, 0x508 => true, 0x50a => true, 0x50c => true, 0x50e => true, 0x510 => true, 0x512 => true, 0x514 => true, 0x516 => true, 0x518 => true, 0x51a => true, 0x51c => true, 0x51e => true, 0x520 => true, 0x522 => true, 0x524 => true, 0x526 => true, 0x528 => true, 0x52a => true, 0x52c => true, 0x52e => true, 0x531...0x556 => true, 0x10a0...0x10c5 => true, 0x10c7 => true, 0x10cd => true, 0x13a0...0x13f5 => true, 0x1c90...0x1cba => true, 0x1cbd...0x1cbf => true, 0x1e00 => true, 0x1e02 => true, 0x1e04 => true, 0x1e06 => true, 0x1e08 => true, 0x1e0a => true, 0x1e0c => true, 0x1e0e => true, 0x1e10 => true, 0x1e12 => true, 0x1e14 => true, 0x1e16 => true, 0x1e18 => true, 0x1e1a => true, 0x1e1c => true, 0x1e1e => true, 0x1e20 => true, 0x1e22 => true, 0x1e24 => true, 0x1e26 => true, 0x1e28 => true, 0x1e2a => true, 0x1e2c => true, 0x1e2e => true, 0x1e30 => true, 0x1e32 => true, 0x1e34 => true, 0x1e36 => true, 0x1e38 => true, 0x1e3a => true, 0x1e3c => true, 0x1e3e => true, 0x1e40 => true, 0x1e42 => true, 0x1e44 => true, 0x1e46 => true, 0x1e48 => true, 0x1e4a => true, 0x1e4c => true, 0x1e4e => true, 0x1e50 => true, 0x1e52 => true, 0x1e54 => true, 0x1e56 => true, 0x1e58 => true, 0x1e5a => true, 0x1e5c => true, 0x1e5e => true, 0x1e60 => true, 0x1e62 => true, 0x1e64 => true, 0x1e66 => true, 0x1e68 => true, 0x1e6a => true, 0x1e6c => true, 0x1e6e => true, 0x1e70 => true, 0x1e72 => true, 0x1e74 => true, 0x1e76 => true, 0x1e78 => true, 0x1e7a => true, 0x1e7c => true, 0x1e7e => true, 0x1e80 => true, 0x1e82 => true, 0x1e84 => true, 0x1e86 => true, 0x1e88 => true, 0x1e8a => true, 0x1e8c => true, 0x1e8e => true, 0x1e90 => true, 0x1e92 => true, 0x1e94 => true, 0x1e9e => true, 0x1ea0 => true, 0x1ea2 => true, 0x1ea4 => true, 0x1ea6 => true, 0x1ea8 => true, 0x1eaa => true, 0x1eac => true, 0x1eae => true, 0x1eb0 => true, 0x1eb2 => true, 0x1eb4 => true, 0x1eb6 => true, 0x1eb8 => true, 0x1eba => true, 0x1ebc => true, 0x1ebe => true, 0x1ec0 => true, 0x1ec2 => true, 0x1ec4 => true, 0x1ec6 => true, 0x1ec8 => true, 0x1eca => true, 0x1ecc => true, 0x1ece => true, 0x1ed0 => true, 0x1ed2 => true, 0x1ed4 => true, 0x1ed6 => true, 0x1ed8 => true, 0x1eda => true, 0x1edc => true, 0x1ede => true, 0x1ee0 => true, 0x1ee2 => true, 0x1ee4 => true, 0x1ee6 => true, 0x1ee8 => true, 0x1eea => true, 0x1eec => true, 0x1eee => true, 0x1ef0 => true, 0x1ef2 => true, 0x1ef4 => true, 0x1ef6 => true, 0x1ef8 => true, 0x1efa => true, 0x1efc => true, 0x1efe => true, 0x1f08...0x1f0f => true, 0x1f18...0x1f1d => true, 0x1f28...0x1f2f => true, 0x1f38...0x1f3f => true, 0x1f48...0x1f4d => true, 0x1f59 => true, 0x1f5b => true, 0x1f5d => true, 0x1f5f => true, 0x1f68...0x1f6f => true, 0x1fb8...0x1fbb => true, 0x1fc8...0x1fcb => true, 0x1fd8...0x1fdb => true, 0x1fe8...0x1fec => true, 0x1ff8...0x1ffb => true, 0x2102 => true, 0x2107 => true, 0x210b...0x210d => true, 0x2110...0x2112 => true, 0x2115 => true, 0x2119...0x211d => true, 0x2124 => true, 0x2126 => true, 0x2128 => true, 0x212a...0x212d => true, 0x2130...0x2133 => true, 0x213e...0x213f => true, 0x2145 => true, 0x2183 => true, 0x2c00...0x2c2f => true, 0x2c60 => true, 0x2c62...0x2c64 => true, 0x2c67 => true, 0x2c69 => true, 0x2c6b => true, 0x2c6d...0x2c70 => true, 0x2c72 => true, 0x2c75 => true, 0x2c7e...0x2c80 => true, 0x2c82 => true, 0x2c84 => true, 0x2c86 => true, 0x2c88 => true, 0x2c8a => true, 0x2c8c => true, 0x2c8e => true, 0x2c90 => true, 0x2c92 => true, 0x2c94 => true, 0x2c96 => true, 0x2c98 => true, 0x2c9a => true, 0x2c9c => true, 0x2c9e => true, 0x2ca0 => true, 0x2ca2 => true, 0x2ca4 => true, 0x2ca6 => true, 0x2ca8 => true, 0x2caa => true, 0x2cac => true, 0x2cae => true, 0x2cb0 => true, 0x2cb2 => true, 0x2cb4 => true, 0x2cb6 => true, 0x2cb8 => true, 0x2cba => true, 0x2cbc => true, 0x2cbe => true, 0x2cc0 => true, 0x2cc2 => true, 0x2cc4 => true, 0x2cc6 => true, 0x2cc8 => true, 0x2cca => true, 0x2ccc => true, 0x2cce => true, 0x2cd0 => true, 0x2cd2 => true, 0x2cd4 => true, 0x2cd6 => true, 0x2cd8 => true, 0x2cda => true, 0x2cdc => true, 0x2cde => true, 0x2ce0 => true, 0x2ce2 => true, 0x2ceb => true, 0x2ced => true, 0x2cf2 => true, 0xa640 => true, 0xa642 => true, 0xa644 => true, 0xa646 => true, 0xa648 => true, 0xa64a => true, 0xa64c => true, 0xa64e => true, 0xa650 => true, 0xa652 => true, 0xa654 => true, 0xa656 => true, 0xa658 => true, 0xa65a => true, 0xa65c => true, 0xa65e => true, 0xa660 => true, 0xa662 => true, 0xa664 => true, 0xa666 => true, 0xa668 => true, 0xa66a => true, 0xa66c => true, 0xa680 => true, 0xa682 => true, 0xa684 => true, 0xa686 => true, 0xa688 => true, 0xa68a => true, 0xa68c => true, 0xa68e => true, 0xa690 => true, 0xa692 => true, 0xa694 => true, 0xa696 => true, 0xa698 => true, 0xa69a => true, 0xa722 => true, 0xa724 => true, 0xa726 => true, 0xa728 => true, 0xa72a => true, 0xa72c => true, 0xa72e => true, 0xa732 => true, 0xa734 => true, 0xa736 => true, 0xa738 => true, 0xa73a => true, 0xa73c => true, 0xa73e => true, 0xa740 => true, 0xa742 => true, 0xa744 => true, 0xa746 => true, 0xa748 => true, 0xa74a => true, 0xa74c => true, 0xa74e => true, 0xa750 => true, 0xa752 => true, 0xa754 => true, 0xa756 => true, 0xa758 => true, 0xa75a => true, 0xa75c => true, 0xa75e => true, 0xa760 => true, 0xa762 => true, 0xa764 => true, 0xa766 => true, 0xa768 => true, 0xa76a => true, 0xa76c => true, 0xa76e => true, 0xa779 => true, 0xa77b => true, 0xa77d...0xa77e => true, 0xa780 => true, 0xa782 => true, 0xa784 => true, 0xa786 => true, 0xa78b => true, 0xa78d => true, 0xa790 => true, 0xa792 => true, 0xa796 => true, 0xa798 => true, 0xa79a => true, 0xa79c => true, 0xa79e => true, 0xa7a0 => true, 0xa7a2 => true, 0xa7a4 => true, 0xa7a6 => true, 0xa7a8 => true, 0xa7aa...0xa7ae => true, 0xa7b0...0xa7b4 => true, 0xa7b6 => true, 0xa7b8 => true, 0xa7ba => true, 0xa7bc => true, 0xa7be => true, 0xa7c0 => true, 0xa7c2 => true, 0xa7c4...0xa7c7 => true, 0xa7c9 => true, 0xa7d0 => true, 0xa7d6 => true, 0xa7d8 => true, 0xa7f5 => true, 0xff21...0xff3a => true, 0x10400...0x10427 => true, 0x104b0...0x104d3 => true, 0x10570...0x1057a => true, 0x1057c...0x1058a => true, 0x1058c...0x10592 => true, 0x10594...0x10595 => true, 0x10c80...0x10cb2 => true, 0x118a0...0x118bf => true, 0x16e40...0x16e5f => true, 0x1d400...0x1d419 => true, 0x1d434...0x1d44d => true, 0x1d468...0x1d481 => true, 0x1d49c => true, 0x1d49e...0x1d49f => true, 0x1d4a2 => true, 0x1d4a5...0x1d4a6 => true, 0x1d4a9...0x1d4ac => true, 0x1d4ae...0x1d4b5 => true, 0x1d4d0...0x1d4e9 => true, 0x1d504...0x1d505 => true, 0x1d507...0x1d50a => true, 0x1d50d...0x1d514 => true, 0x1d516...0x1d51c => true, 0x1d538...0x1d539 => true, 0x1d53b...0x1d53e => true, 0x1d540...0x1d544 => true, 0x1d546 => true, 0x1d54a...0x1d550 => true, 0x1d56c...0x1d585 => true, 0x1d5a0...0x1d5b9 => true, 0x1d5d4...0x1d5ed => true, 0x1d608...0x1d621 => true, 0x1d63c...0x1d655 => true, 0x1d670...0x1d689 => true, 0x1d6a8...0x1d6c0 => true, 0x1d6e2...0x1d6fa => true, 0x1d71c...0x1d734 => true, 0x1d756...0x1d76e => true, 0x1d790...0x1d7a8 => true, 0x1d7ca => true, 0x1e900...0x1e921 => true, else => false, }; } pub fn isLowercaseLetter(cp: u21) bool { if (cp < 0x61 or cp > 0x1e943) return false; return switch (cp) { 0x61...0x7a => true, 0xb5 => true, 0xdf...0xf6 => true, 0xf8...0xff => true, 0x101 => true, 0x103 => true, 0x105 => true, 0x107 => true, 0x109 => true, 0x10b => true, 0x10d => true, 0x10f => true, 0x111 => true, 0x113 => true, 0x115 => true, 0x117 => true, 0x119 => true, 0x11b => true, 0x11d => true, 0x11f => true, 0x121 => true, 0x123 => true, 0x125 => true, 0x127 => true, 0x129 => true, 0x12b => true, 0x12d => true, 0x12f => true, 0x131 => true, 0x133 => true, 0x135 => true, 0x137...0x138 => true, 0x13a => true, 0x13c => true, 0x13e => true, 0x140 => true, 0x142 => true, 0x144 => true, 0x146 => true, 0x148...0x149 => true, 0x14b => true, 0x14d => true, 0x14f => true, 0x151 => true, 0x153 => true, 0x155 => true, 0x157 => true, 0x159 => true, 0x15b => true, 0x15d => true, 0x15f => true, 0x161 => true, 0x163 => true, 0x165 => true, 0x167 => true, 0x169 => true, 0x16b => true, 0x16d => true, 0x16f => true, 0x171 => true, 0x173 => true, 0x175 => true, 0x177 => true, 0x17a => true, 0x17c => true, 0x17e...0x180 => true, 0x183 => true, 0x185 => true, 0x188 => true, 0x18c...0x18d => true, 0x192 => true, 0x195 => true, 0x199...0x19b => true, 0x19e => true, 0x1a1 => true, 0x1a3 => true, 0x1a5 => true, 0x1a8 => true, 0x1aa...0x1ab => true, 0x1ad => true, 0x1b0 => true, 0x1b4 => true, 0x1b6 => true, 0x1b9...0x1ba => true, 0x1bd...0x1bf => true, 0x1c6 => true, 0x1c9 => true, 0x1cc => true, 0x1ce => true, 0x1d0 => true, 0x1d2 => true, 0x1d4 => true, 0x1d6 => true, 0x1d8 => true, 0x1da => true, 0x1dc...0x1dd => true, 0x1df => true, 0x1e1 => true, 0x1e3 => true, 0x1e5 => true, 0x1e7 => true, 0x1e9 => true, 0x1eb => true, 0x1ed => true, 0x1ef...0x1f0 => true, 0x1f3 => true, 0x1f5 => true, 0x1f9 => true, 0x1fb => true, 0x1fd => true, 0x1ff => true, 0x201 => true, 0x203 => true, 0x205 => true, 0x207 => true, 0x209 => true, 0x20b => true, 0x20d => true, 0x20f => true, 0x211 => true, 0x213 => true, 0x215 => true, 0x217 => true, 0x219 => true, 0x21b => true, 0x21d => true, 0x21f => true, 0x221 => true, 0x223 => true, 0x225 => true, 0x227 => true, 0x229 => true, 0x22b => true, 0x22d => true, 0x22f => true, 0x231 => true, 0x233...0x239 => true, 0x23c => true, 0x23f...0x240 => true, 0x242 => true, 0x247 => true, 0x249 => true, 0x24b => true, 0x24d => true, 0x24f...0x293 => true, 0x295...0x2af => true, 0x371 => true, 0x373 => true, 0x377 => true, 0x37b...0x37d => true, 0x390 => true, 0x3ac...0x3ce => true, 0x3d0...0x3d1 => true, 0x3d5...0x3d7 => true, 0x3d9 => true, 0x3db => true, 0x3dd => true, 0x3df => true, 0x3e1 => true, 0x3e3 => true, 0x3e5 => true, 0x3e7 => true, 0x3e9 => true, 0x3eb => true, 0x3ed => true, 0x3ef...0x3f3 => true, 0x3f5 => true, 0x3f8 => true, 0x3fb...0x3fc => true, 0x430...0x45f => true, 0x461 => true, 0x463 => true, 0x465 => true, 0x467 => true, 0x469 => true, 0x46b => true, 0x46d => true, 0x46f => true, 0x471 => true, 0x473 => true, 0x475 => true, 0x477 => true, 0x479 => true, 0x47b => true, 0x47d => true, 0x47f => true, 0x481 => true, 0x48b => true, 0x48d => true, 0x48f => true, 0x491 => true, 0x493 => true, 0x495 => true, 0x497 => true, 0x499 => true, 0x49b => true, 0x49d => true, 0x49f => true, 0x4a1 => true, 0x4a3 => true, 0x4a5 => true, 0x4a7 => true, 0x4a9 => true, 0x4ab => true, 0x4ad => true, 0x4af => true, 0x4b1 => true, 0x4b3 => true, 0x4b5 => true, 0x4b7 => true, 0x4b9 => true, 0x4bb => true, 0x4bd => true, 0x4bf => true, 0x4c2 => true, 0x4c4 => true, 0x4c6 => true, 0x4c8 => true, 0x4ca => true, 0x4cc => true, 0x4ce...0x4cf => true, 0x4d1 => true, 0x4d3 => true, 0x4d5 => true, 0x4d7 => true, 0x4d9 => true, 0x4db => true, 0x4dd => true, 0x4df => true, 0x4e1 => true, 0x4e3 => true, 0x4e5 => true, 0x4e7 => true, 0x4e9 => true, 0x4eb => true, 0x4ed => true, 0x4ef => true, 0x4f1 => true, 0x4f3 => true, 0x4f5 => true, 0x4f7 => true, 0x4f9 => true, 0x4fb => true, 0x4fd => true, 0x4ff => true, 0x501 => true, 0x503 => true, 0x505 => true, 0x507 => true, 0x509 => true, 0x50b => true, 0x50d => true, 0x50f => true, 0x511 => true, 0x513 => true, 0x515 => true, 0x517 => true, 0x519 => true, 0x51b => true, 0x51d => true, 0x51f => true, 0x521 => true, 0x523 => true, 0x525 => true, 0x527 => true, 0x529 => true, 0x52b => true, 0x52d => true, 0x52f => true, 0x560...0x588 => true, 0x10d0...0x10fa => true, 0x10fd...0x10ff => true, 0x13f8...0x13fd => true, 0x1c80...0x1c88 => true, 0x1d00...0x1d2b => true, 0x1d6b...0x1d77 => true, 0x1d79...0x1d9a => true, 0x1e01 => true, 0x1e03 => true, 0x1e05 => true, 0x1e07 => true, 0x1e09 => true, 0x1e0b => true, 0x1e0d => true, 0x1e0f => true, 0x1e11 => true, 0x1e13 => true, 0x1e15 => true, 0x1e17 => true, 0x1e19 => true, 0x1e1b => true, 0x1e1d => true, 0x1e1f => true, 0x1e21 => true, 0x1e23 => true, 0x1e25 => true, 0x1e27 => true, 0x1e29 => true, 0x1e2b => true, 0x1e2d => true, 0x1e2f => true, 0x1e31 => true, 0x1e33 => true, 0x1e35 => true, 0x1e37 => true, 0x1e39 => true, 0x1e3b => true, 0x1e3d => true, 0x1e3f => true, 0x1e41 => true, 0x1e43 => true, 0x1e45 => true, 0x1e47 => true, 0x1e49 => true, 0x1e4b => true, 0x1e4d => true, 0x1e4f => true, 0x1e51 => true, 0x1e53 => true, 0x1e55 => true, 0x1e57 => true, 0x1e59 => true, 0x1e5b => true, 0x1e5d => true, 0x1e5f => true, 0x1e61 => true, 0x1e63 => true, 0x1e65 => true, 0x1e67 => true, 0x1e69 => true, 0x1e6b => true, 0x1e6d => true, 0x1e6f => true, 0x1e71 => true, 0x1e73 => true, 0x1e75 => true, 0x1e77 => true, 0x1e79 => true, 0x1e7b => true, 0x1e7d => true, 0x1e7f => true, 0x1e81 => true, 0x1e83 => true, 0x1e85 => true, 0x1e87 => true, 0x1e89 => true, 0x1e8b => true, 0x1e8d => true, 0x1e8f => true, 0x1e91 => true, 0x1e93 => true, 0x1e95...0x1e9d => true, 0x1e9f => true, 0x1ea1 => true, 0x1ea3 => true, 0x1ea5 => true, 0x1ea7 => true, 0x1ea9 => true, 0x1eab => true, 0x1ead => true, 0x1eaf => true, 0x1eb1 => true, 0x1eb3 => true, 0x1eb5 => true, 0x1eb7 => true, 0x1eb9 => true, 0x1ebb => true, 0x1ebd => true, 0x1ebf => true, 0x1ec1 => true, 0x1ec3 => true, 0x1ec5 => true, 0x1ec7 => true, 0x1ec9 => true, 0x1ecb => true, 0x1ecd => true, 0x1ecf => true, 0x1ed1 => true, 0x1ed3 => true, 0x1ed5 => true, 0x1ed7 => true, 0x1ed9 => true, 0x1edb => true, 0x1edd => true, 0x1edf => true, 0x1ee1 => true, 0x1ee3 => true, 0x1ee5 => true, 0x1ee7 => true, 0x1ee9 => true, 0x1eeb => true, 0x1eed => true, 0x1eef => true, 0x1ef1 => true, 0x1ef3 => true, 0x1ef5 => true, 0x1ef7 => true, 0x1ef9 => true, 0x1efb => true, 0x1efd => true, 0x1eff...0x1f07 => true, 0x1f10...0x1f15 => true, 0x1f20...0x1f27 => true, 0x1f30...0x1f37 => true, 0x1f40...0x1f45 => true, 0x1f50...0x1f57 => true, 0x1f60...0x1f67 => true, 0x1f70...0x1f7d => true, 0x1f80...0x1f87 => true, 0x1f90...0x1f97 => true, 0x1fa0...0x1fa7 => true, 0x1fb0...0x1fb4 => true, 0x1fb6...0x1fb7 => true, 0x1fbe => true, 0x1fc2...0x1fc4 => true, 0x1fc6...0x1fc7 => true, 0x1fd0...0x1fd3 => true, 0x1fd6...0x1fd7 => true, 0x1fe0...0x1fe7 => true, 0x1ff2...0x1ff4 => true, 0x1ff6...0x1ff7 => true, 0x210a => true, 0x210e...0x210f => true, 0x2113 => true, 0x212f => true, 0x2134 => true, 0x2139 => true, 0x213c...0x213d => true, 0x2146...0x2149 => true, 0x214e => true, 0x2184 => true, 0x2c30...0x2c5f => true, 0x2c61 => true, 0x2c65...0x2c66 => true, 0x2c68 => true, 0x2c6a => true, 0x2c6c => true, 0x2c71 => true, 0x2c73...0x2c74 => true, 0x2c76...0x2c7b => true, 0x2c81 => true, 0x2c83 => true, 0x2c85 => true, 0x2c87 => true, 0x2c89 => true, 0x2c8b => true, 0x2c8d => true, 0x2c8f => true, 0x2c91 => true, 0x2c93 => true, 0x2c95 => true, 0x2c97 => true, 0x2c99 => true, 0x2c9b => true, 0x2c9d => true, 0x2c9f => true, 0x2ca1 => true, 0x2ca3 => true, 0x2ca5 => true, 0x2ca7 => true, 0x2ca9 => true, 0x2cab => true, 0x2cad => true, 0x2caf => true, 0x2cb1 => true, 0x2cb3 => true, 0x2cb5 => true, 0x2cb7 => true, 0x2cb9 => true, 0x2cbb => true, 0x2cbd => true, 0x2cbf => true, 0x2cc1 => true, 0x2cc3 => true, 0x2cc5 => true, 0x2cc7 => true, 0x2cc9 => true, 0x2ccb => true, 0x2ccd => true, 0x2ccf => true, 0x2cd1 => true, 0x2cd3 => true, 0x2cd5 => true, 0x2cd7 => true, 0x2cd9 => true, 0x2cdb => true, 0x2cdd => true, 0x2cdf => true, 0x2ce1 => true, 0x2ce3...0x2ce4 => true, 0x2cec => true, 0x2cee => true, 0x2cf3 => true, 0x2d00...0x2d25 => true, 0x2d27 => true, 0x2d2d => true, 0xa641 => true, 0xa643 => true, 0xa645 => true, 0xa647 => true, 0xa649 => true, 0xa64b => true, 0xa64d => true, 0xa64f => true, 0xa651 => true, 0xa653 => true, 0xa655 => true, 0xa657 => true, 0xa659 => true, 0xa65b => true, 0xa65d => true, 0xa65f => true, 0xa661 => true, 0xa663 => true, 0xa665 => true, 0xa667 => true, 0xa669 => true, 0xa66b => true, 0xa66d => true, 0xa681 => true, 0xa683 => true, 0xa685 => true, 0xa687 => true, 0xa689 => true, 0xa68b => true, 0xa68d => true, 0xa68f => true, 0xa691 => true, 0xa693 => true, 0xa695 => true, 0xa697 => true, 0xa699 => true, 0xa69b => true, 0xa723 => true, 0xa725 => true, 0xa727 => true, 0xa729 => true, 0xa72b => true, 0xa72d => true, 0xa72f...0xa731 => true, 0xa733 => true, 0xa735 => true, 0xa737 => true, 0xa739 => true, 0xa73b => true, 0xa73d => true, 0xa73f => true, 0xa741 => true, 0xa743 => true, 0xa745 => true, 0xa747 => true, 0xa749 => true, 0xa74b => true, 0xa74d => true, 0xa74f => true, 0xa751 => true, 0xa753 => true, 0xa755 => true, 0xa757 => true, 0xa759 => true, 0xa75b => true, 0xa75d => true, 0xa75f => true, 0xa761 => true, 0xa763 => true, 0xa765 => true, 0xa767 => true, 0xa769 => true, 0xa76b => true, 0xa76d => true, 0xa76f => true, 0xa771...0xa778 => true, 0xa77a => true, 0xa77c => true, 0xa77f => true, 0xa781 => true, 0xa783 => true, 0xa785 => true, 0xa787 => true, 0xa78c => true, 0xa78e => true, 0xa791 => true, 0xa793...0xa795 => true, 0xa797 => true, 0xa799 => true, 0xa79b => true, 0xa79d => true, 0xa79f => true, 0xa7a1 => true, 0xa7a3 => true, 0xa7a5 => true, 0xa7a7 => true, 0xa7a9 => true, 0xa7af => true, 0xa7b5 => true, 0xa7b7 => true, 0xa7b9 => true, 0xa7bb => true, 0xa7bd => true, 0xa7bf => true, 0xa7c1 => true, 0xa7c3 => true, 0xa7c8 => true, 0xa7ca => true, 0xa7d1 => true, 0xa7d3 => true, 0xa7d5 => true, 0xa7d7 => true, 0xa7d9 => true, 0xa7f6 => true, 0xa7fa => true, 0xab30...0xab5a => true, 0xab60...0xab68 => true, 0xab70...0xabbf => true, 0xfb00...0xfb06 => true, 0xfb13...0xfb17 => true, 0xff41...0xff5a => true, 0x10428...0x1044f => true, 0x104d8...0x104fb => true, 0x10597...0x105a1 => true, 0x105a3...0x105b1 => true, 0x105b3...0x105b9 => true, 0x105bb...0x105bc => true, 0x10cc0...0x10cf2 => true, 0x118c0...0x118df => true, 0x16e60...0x16e7f => true, 0x1d41a...0x1d433 => true, 0x1d44e...0x1d454 => true, 0x1d456...0x1d467 => true, 0x1d482...0x1d49b => true, 0x1d4b6...0x1d4b9 => true, 0x1d4bb => true, 0x1d4bd...0x1d4c3 => true, 0x1d4c5...0x1d4cf => true, 0x1d4ea...0x1d503 => true, 0x1d51e...0x1d537 => true, 0x1d552...0x1d56b => true, 0x1d586...0x1d59f => true, 0x1d5ba...0x1d5d3 => true, 0x1d5ee...0x1d607 => true, 0x1d622...0x1d63b => true, 0x1d656...0x1d66f => true, 0x1d68a...0x1d6a5 => true, 0x1d6c2...0x1d6da => true, 0x1d6dc...0x1d6e1 => true, 0x1d6fc...0x1d714 => true, 0x1d716...0x1d71b => true, 0x1d736...0x1d74e => true, 0x1d750...0x1d755 => true, 0x1d770...0x1d788 => true, 0x1d78a...0x1d78f => true, 0x1d7aa...0x1d7c2 => true, 0x1d7c4...0x1d7c9 => true, 0x1d7cb => true, 0x1df00...0x1df09 => true, 0x1df0b...0x1df1e => true, 0x1e922...0x1e943 => true, else => false, }; } pub fn isTitlecaseLetter(cp: u21) bool { if (cp < 0x1c5 or cp > 0x1ffc) return false; return switch (cp) { 0x1c5 => true, 0x1c8 => true, 0x1cb => true, 0x1f2 => true, 0x1f88...0x1f8f => true, 0x1f98...0x1f9f => true, 0x1fa8...0x1faf => true, 0x1fbc => true, 0x1fcc => true, 0x1ffc => true, else => false, }; } pub fn isModifierLetter(cp: u21) bool { if (cp < 0x2b0 or cp > 0x1e94b) return false; return switch (cp) { 0x2b0...0x2c1 => true, 0x2c6...0x2d1 => true, 0x2e0...0x2e4 => true, 0x2ec => true, 0x2ee => true, 0x374 => true, 0x37a => true, 0x559 => true, 0x640 => true, 0x6e5...0x6e6 => true, 0x7f4...0x7f5 => true, 0x7fa => true, 0x81a => true, 0x824 => true, 0x828 => true, 0x8c9 => true, 0x971 => true, 0xe46 => true, 0xec6 => true, 0x10fc => true, 0x17d7 => true, 0x1843 => true, 0x1aa7 => true, 0x1c78...0x1c7d => true, 0x1d2c...0x1d6a => true, 0x1d78 => true, 0x1d9b...0x1dbf => true, 0x2071 => true, 0x207f => true, 0x2090...0x209c => true, 0x2c7c...0x2c7d => true, 0x2d6f => true, 0x2e2f => true, 0x3005 => true, 0x3031...0x3035 => true, 0x303b => true, 0x309d...0x309e => true, 0x30fc...0x30fe => true, 0xa015 => true, 0xa4f8...0xa4fd => true, 0xa60c => true, 0xa67f => true, 0xa69c...0xa69d => true, 0xa717...0xa71f => true, 0xa770 => true, 0xa788 => true, 0xa7f2...0xa7f4 => true, 0xa7f8...0xa7f9 => true, 0xa9cf => true, 0xa9e6 => true, 0xaa70 => true, 0xaadd => true, 0xaaf3...0xaaf4 => true, 0xab5c...0xab5f => true, 0xab69 => true, 0xff70 => true, 0xff9e...0xff9f => true, 0x10780...0x10785 => true, 0x10787...0x107b0 => true, 0x107b2...0x107ba => true, 0x16b40...0x16b43 => true, 0x16f93...0x16f9f => true, 0x16fe0...0x16fe1 => true, 0x16fe3 => true, 0x1aff0...0x1aff3 => true, 0x1aff5...0x1affb => true, 0x1affd...0x1affe => true, 0x1e137...0x1e13d => true, 0x1e94b => true, else => false, }; } pub fn isOtherLetter(cp: u21) bool { if (cp < 0xaa or cp > 0x3134a) return false; return switch (cp) { 0xaa => true, 0xba => true, 0x1bb => true, 0x1c0...0x1c3 => true, 0x294 => true, 0x5d0...0x5ea => true, 0x5ef...0x5f2 => true, 0x620...0x63f => true, 0x641...0x64a => true, 0x66e...0x66f => true, 0x671...0x6d3 => true, 0x6d5 => true, 0x6ee...0x6ef => true, 0x6fa...0x6fc => true, 0x6ff => true, 0x710 => true, 0x712...0x72f => true, 0x74d...0x7a5 => true, 0x7b1 => true, 0x7ca...0x7ea => true, 0x800...0x815 => true, 0x840...0x858 => true, 0x860...0x86a => true, 0x870...0x887 => true, 0x889...0x88e => true, 0x8a0...0x8c8 => true, 0x904...0x939 => true, 0x93d => true, 0x950 => true, 0x958...0x961 => true, 0x972...0x980 => true, 0x985...0x98c => true, 0x98f...0x990 => true, 0x993...0x9a8 => true, 0x9aa...0x9b0 => true, 0x9b2 => true, 0x9b6...0x9b9 => true, 0x9bd => true, 0x9ce => true, 0x9dc...0x9dd => true, 0x9df...0x9e1 => true, 0x9f0...0x9f1 => true, 0x9fc => true, 0xa05...0xa0a => true, 0xa0f...0xa10 => true, 0xa13...0xa28 => true, 0xa2a...0xa30 => true, 0xa32...0xa33 => true, 0xa35...0xa36 => true, 0xa38...0xa39 => true, 0xa59...0xa5c => true, 0xa5e => true, 0xa72...0xa74 => true, 0xa85...0xa8d => true, 0xa8f...0xa91 => true, 0xa93...0xaa8 => true, 0xaaa...0xab0 => true, 0xab2...0xab3 => true, 0xab5...0xab9 => true, 0xabd => true, 0xad0 => true, 0xae0...0xae1 => true, 0xaf9 => true, 0xb05...0xb0c => true, 0xb0f...0xb10 => true, 0xb13...0xb28 => true, 0xb2a...0xb30 => true, 0xb32...0xb33 => true, 0xb35...0xb39 => true, 0xb3d => true, 0xb5c...0xb5d => true, 0xb5f...0xb61 => true, 0xb71 => true, 0xb83 => true, 0xb85...0xb8a => true, 0xb8e...0xb90 => true, 0xb92...0xb95 => true, 0xb99...0xb9a => true, 0xb9c => true, 0xb9e...0xb9f => true, 0xba3...0xba4 => true, 0xba8...0xbaa => true, 0xbae...0xbb9 => true, 0xbd0 => true, 0xc05...0xc0c => true, 0xc0e...0xc10 => true, 0xc12...0xc28 => true, 0xc2a...0xc39 => true, 0xc3d => true, 0xc58...0xc5a => true, 0xc5d => true, 0xc60...0xc61 => true, 0xc80 => true, 0xc85...0xc8c => true, 0xc8e...0xc90 => true, 0xc92...0xca8 => true, 0xcaa...0xcb3 => true, 0xcb5...0xcb9 => true, 0xcbd => true, 0xcdd...0xcde => true, 0xce0...0xce1 => true, 0xcf1...0xcf2 => true, 0xd04...0xd0c => true, 0xd0e...0xd10 => true, 0xd12...0xd3a => true, 0xd3d => true, 0xd4e => true, 0xd54...0xd56 => true, 0xd5f...0xd61 => true, 0xd7a...0xd7f => true, 0xd85...0xd96 => true, 0xd9a...0xdb1 => true, 0xdb3...0xdbb => true, 0xdbd => true, 0xdc0...0xdc6 => true, 0xe01...0xe30 => true, 0xe32...0xe33 => true, 0xe40...0xe45 => true, 0xe81...0xe82 => true, 0xe84 => true, 0xe86...0xe8a => true, 0xe8c...0xea3 => true, 0xea5 => true, 0xea7...0xeb0 => true, 0xeb2...0xeb3 => true, 0xebd => true, 0xec0...0xec4 => true, 0xedc...0xedf => true, 0xf00 => true, 0xf40...0xf47 => true, 0xf49...0xf6c => true, 0xf88...0xf8c => true, 0x1000...0x102a => true, 0x103f => true, 0x1050...0x1055 => true, 0x105a...0x105d => true, 0x1061 => true, 0x1065...0x1066 => true, 0x106e...0x1070 => true, 0x1075...0x1081 => true, 0x108e => true, 0x1100...0x1248 => true, 0x124a...0x124d => true, 0x1250...0x1256 => true, 0x1258 => true, 0x125a...0x125d => true, 0x1260...0x1288 => true, 0x128a...0x128d => true, 0x1290...0x12b0 => true, 0x12b2...0x12b5 => true, 0x12b8...0x12be => true, 0x12c0 => true, 0x12c2...0x12c5 => true, 0x12c8...0x12d6 => true, 0x12d8...0x1310 => true, 0x1312...0x1315 => true, 0x1318...0x135a => true, 0x1380...0x138f => true, 0x1401...0x166c => true, 0x166f...0x167f => true, 0x1681...0x169a => true, 0x16a0...0x16ea => true, 0x16f1...0x16f8 => true, 0x1700...0x1711 => true, 0x171f...0x1731 => true, 0x1740...0x1751 => true, 0x1760...0x176c => true, 0x176e...0x1770 => true, 0x1780...0x17b3 => true, 0x17dc => true, 0x1820...0x1842 => true, 0x1844...0x1878 => true, 0x1880...0x1884 => true, 0x1887...0x18a8 => true, 0x18aa => true, 0x18b0...0x18f5 => true, 0x1900...0x191e => true, 0x1950...0x196d => true, 0x1970...0x1974 => true, 0x1980...0x19ab => true, 0x19b0...0x19c9 => true, 0x1a00...0x1a16 => true, 0x1a20...0x1a54 => true, 0x1b05...0x1b33 => true, 0x1b45...0x1b4c => true, 0x1b83...0x1ba0 => true, 0x1bae...0x1baf => true, 0x1bba...0x1be5 => true, 0x1c00...0x1c23 => true, 0x1c4d...0x1c4f => true, 0x1c5a...0x1c77 => true, 0x1ce9...0x1cec => true, 0x1cee...0x1cf3 => true, 0x1cf5...0x1cf6 => true, 0x1cfa => true, 0x2135...0x2138 => true, 0x2d30...0x2d67 => true, 0x2d80...0x2d96 => true, 0x2da0...0x2da6 => true, 0x2da8...0x2dae => true, 0x2db0...0x2db6 => true, 0x2db8...0x2dbe => true, 0x2dc0...0x2dc6 => true, 0x2dc8...0x2dce => true, 0x2dd0...0x2dd6 => true, 0x2dd8...0x2dde => true, 0x3006 => true, 0x303c => true, 0x3041...0x3096 => true, 0x309f => true, 0x30a1...0x30fa => true, 0x30ff => true, 0x3105...0x312f => true, 0x3131...0x318e => true, 0x31a0...0x31bf => true, 0x31f0...0x31ff => true, 0x3400...0x4dbf => true, 0x4e00...0xa014 => true, 0xa016...0xa48c => true, 0xa4d0...0xa4f7 => true, 0xa500...0xa60b => true, 0xa610...0xa61f => true, 0xa62a...0xa62b => true, 0xa66e => true, 0xa6a0...0xa6e5 => true, 0xa78f => true, 0xa7f7 => true, 0xa7fb...0xa801 => true, 0xa803...0xa805 => true, 0xa807...0xa80a => true, 0xa80c...0xa822 => true, 0xa840...0xa873 => true, 0xa882...0xa8b3 => true, 0xa8f2...0xa8f7 => true, 0xa8fb => true, 0xa8fd...0xa8fe => true, 0xa90a...0xa925 => true, 0xa930...0xa946 => true, 0xa960...0xa97c => true, 0xa984...0xa9b2 => true, 0xa9e0...0xa9e4 => true, 0xa9e7...0xa9ef => true, 0xa9fa...0xa9fe => true, 0xaa00...0xaa28 => true, 0xaa40...0xaa42 => true, 0xaa44...0xaa4b => true, 0xaa60...0xaa6f => true, 0xaa71...0xaa76 => true, 0xaa7a => true, 0xaa7e...0xaaaf => true, 0xaab1 => true, 0xaab5...0xaab6 => true, 0xaab9...0xaabd => true, 0xaac0 => true, 0xaac2 => true, 0xaadb...0xaadc => true, 0xaae0...0xaaea => true, 0xaaf2 => true, 0xab01...0xab06 => true, 0xab09...0xab0e => true, 0xab11...0xab16 => true, 0xab20...0xab26 => true, 0xab28...0xab2e => true, 0xabc0...0xabe2 => true, 0xac00...0xd7a3 => true, 0xd7b0...0xd7c6 => true, 0xd7cb...0xd7fb => true, 0xf900...0xfa6d => true, 0xfa70...0xfad9 => true, 0xfb1d => true, 0xfb1f...0xfb28 => true, 0xfb2a...0xfb36 => true, 0xfb38...0xfb3c => true, 0xfb3e => true, 0xfb40...0xfb41 => true, 0xfb43...0xfb44 => true, 0xfb46...0xfbb1 => true, 0xfbd3...0xfd3d => true, 0xfd50...0xfd8f => true, 0xfd92...0xfdc7 => true, 0xfdf0...0xfdfb => true, 0xfe70...0xfe74 => true, 0xfe76...0xfefc => true, 0xff66...0xff6f => true, 0xff71...0xff9d => true, 0xffa0...0xffbe => true, 0xffc2...0xffc7 => true, 0xffca...0xffcf => true, 0xffd2...0xffd7 => true, 0xffda...0xffdc => true, 0x10000...0x1000b => true, 0x1000d...0x10026 => true, 0x10028...0x1003a => true, 0x1003c...0x1003d => true, 0x1003f...0x1004d => true, 0x10050...0x1005d => true, 0x10080...0x100fa => true, 0x10280...0x1029c => true, 0x102a0...0x102d0 => true, 0x10300...0x1031f => true, 0x1032d...0x10340 => true, 0x10342...0x10349 => true, 0x10350...0x10375 => true, 0x10380...0x1039d => true, 0x103a0...0x103c3 => true, 0x103c8...0x103cf => true, 0x10450...0x1049d => true, 0x10500...0x10527 => true, 0x10530...0x10563 => true, 0x10600...0x10736 => true, 0x10740...0x10755 => true, 0x10760...0x10767 => true, 0x10800...0x10805 => true, 0x10808 => true, 0x1080a...0x10835 => true, 0x10837...0x10838 => true, 0x1083c => true, 0x1083f...0x10855 => true, 0x10860...0x10876 => true, 0x10880...0x1089e => true, 0x108e0...0x108f2 => true, 0x108f4...0x108f5 => true, 0x10900...0x10915 => true, 0x10920...0x10939 => true, 0x10980...0x109b7 => true, 0x109be...0x109bf => true, 0x10a00 => true, 0x10a10...0x10a13 => true, 0x10a15...0x10a17 => true, 0x10a19...0x10a35 => true, 0x10a60...0x10a7c => true, 0x10a80...0x10a9c => true, 0x10ac0...0x10ac7 => true, 0x10ac9...0x10ae4 => true, 0x10b00...0x10b35 => true, 0x10b40...0x10b55 => true, 0x10b60...0x10b72 => true, 0x10b80...0x10b91 => true, 0x10c00...0x10c48 => true, 0x10d00...0x10d23 => true, 0x10e80...0x10ea9 => true, 0x10eb0...0x10eb1 => true, 0x10f00...0x10f1c => true, 0x10f27 => true, 0x10f30...0x10f45 => true, 0x10f70...0x10f81 => true, 0x10fb0...0x10fc4 => true, 0x10fe0...0x10ff6 => true, 0x11003...0x11037 => true, 0x11071...0x11072 => true, 0x11075 => true, 0x11083...0x110af => true, 0x110d0...0x110e8 => true, 0x11103...0x11126 => true, 0x11144 => true, 0x11147 => true, 0x11150...0x11172 => true, 0x11176 => true, 0x11183...0x111b2 => true, 0x111c1...0x111c4 => true, 0x111da => true, 0x111dc => true, 0x11200...0x11211 => true, 0x11213...0x1122b => true, 0x11280...0x11286 => true, 0x11288 => true, 0x1128a...0x1128d => true, 0x1128f...0x1129d => true, 0x1129f...0x112a8 => true, 0x112b0...0x112de => true, 0x11305...0x1130c => true, 0x1130f...0x11310 => true, 0x11313...0x11328 => true, 0x1132a...0x11330 => true, 0x11332...0x11333 => true, 0x11335...0x11339 => true, 0x1133d => true, 0x11350 => true, 0x1135d...0x11361 => true, 0x11400...0x11434 => true, 0x11447...0x1144a => true, 0x1145f...0x11461 => true, 0x11480...0x114af => true, 0x114c4...0x114c5 => true, 0x114c7 => true, 0x11580...0x115ae => true, 0x115d8...0x115db => true, 0x11600...0x1162f => true, 0x11644 => true, 0x11680...0x116aa => true, 0x116b8 => true, 0x11700...0x1171a => true, 0x11740...0x11746 => true, 0x11800...0x1182b => true, 0x118ff...0x11906 => true, 0x11909 => true, 0x1190c...0x11913 => true, 0x11915...0x11916 => true, 0x11918...0x1192f => true, 0x1193f => true, 0x11941 => true, 0x119a0...0x119a7 => true, 0x119aa...0x119d0 => true, 0x119e1 => true, 0x119e3 => true, 0x11a00 => true, 0x11a0b...0x11a32 => true, 0x11a3a => true, 0x11a50 => true, 0x11a5c...0x11a89 => true, 0x11a9d => true, 0x11ab0...0x11af8 => true, 0x11c00...0x11c08 => true, 0x11c0a...0x11c2e => true, 0x11c40 => true, 0x11c72...0x11c8f => true, 0x11d00...0x11d06 => true, 0x11d08...0x11d09 => true, 0x11d0b...0x11d30 => true, 0x11d46 => true, 0x11d60...0x11d65 => true, 0x11d67...0x11d68 => true, 0x11d6a...0x11d89 => true, 0x11d98 => true, 0x11ee0...0x11ef2 => true, 0x11fb0 => true, 0x12000...0x12399 => true, 0x12480...0x12543 => true, 0x12f90...0x12ff0 => true, 0x13000...0x1342e => true, 0x14400...0x14646 => true, 0x16800...0x16a38 => true, 0x16a40...0x16a5e => true, 0x16a70...0x16abe => true, 0x16ad0...0x16aed => true, 0x16b00...0x16b2f => true, 0x16b63...0x16b77 => true, 0x16b7d...0x16b8f => true, 0x16f00...0x16f4a => true, 0x16f50 => true, 0x17000...0x187f7 => true, 0x18800...0x18cd5 => true, 0x18d00...0x18d08 => true, 0x1b000...0x1b122 => true, 0x1b150...0x1b152 => true, 0x1b164...0x1b167 => true, 0x1b170...0x1b2fb => true, 0x1bc00...0x1bc6a => true, 0x1bc70...0x1bc7c => true, 0x1bc80...0x1bc88 => true, 0x1bc90...0x1bc99 => true, 0x1df0a => true, 0x1e100...0x1e12c => true, 0x1e14e => true, 0x1e290...0x1e2ad => true, 0x1e2c0...0x1e2eb => true, 0x1e7e0...0x1e7e6 => true, 0x1e7e8...0x1e7eb => true, 0x1e7ed...0x1e7ee => true, 0x1e7f0...0x1e7fe => true, 0x1e800...0x1e8c4 => true, 0x1ee00...0x1ee03 => true, 0x1ee05...0x1ee1f => true, 0x1ee21...0x1ee22 => true, 0x1ee24 => true, 0x1ee27 => true, 0x1ee29...0x1ee32 => true, 0x1ee34...0x1ee37 => true, 0x1ee39 => true, 0x1ee3b => true, 0x1ee42 => true, 0x1ee47 => true, 0x1ee49 => true, 0x1ee4b => true, 0x1ee4d...0x1ee4f => true, 0x1ee51...0x1ee52 => true, 0x1ee54 => true, 0x1ee57 => true, 0x1ee59 => true, 0x1ee5b => true, 0x1ee5d => true, 0x1ee5f => true, 0x1ee61...0x1ee62 => true, 0x1ee64 => true, 0x1ee67...0x1ee6a => true, 0x1ee6c...0x1ee72 => true, 0x1ee74...0x1ee77 => true, 0x1ee79...0x1ee7c => true, 0x1ee7e => true, 0x1ee80...0x1ee89 => true, 0x1ee8b...0x1ee9b => true, 0x1eea1...0x1eea3 => true, 0x1eea5...0x1eea9 => true, 0x1eeab...0x1eebb => true, 0x20000...0x2a6df => true, 0x2a700...0x2b738 => true, 0x2b740...0x2b81d => true, 0x2b820...0x2cea1 => true, 0x2ceb0...0x2ebe0 => true, 0x2f800...0x2fa1d => true, 0x30000...0x3134a => true, else => false, }; } pub fn isNonspacingMark(cp: u21) bool { if (cp < 0x300 or cp > 0xe01ef) return false; return switch (cp) { 0x300...0x36f => true, 0x483...0x487 => true, 0x591...0x5bd => true, 0x5bf => true, 0x5c1...0x5c2 => true, 0x5c4...0x5c5 => true, 0x5c7 => true, 0x610...0x61a => true, 0x64b...0x65f => true, 0x670 => true, 0x6d6...0x6dc => true, 0x6df...0x6e4 => true, 0x6e7...0x6e8 => true, 0x6ea...0x6ed => true, 0x711 => true, 0x730...0x74a => true, 0x7a6...0x7b0 => true, 0x7eb...0x7f3 => true, 0x7fd => true, 0x816...0x819 => true, 0x81b...0x823 => true, 0x825...0x827 => true, 0x829...0x82d => true, 0x859...0x85b => true, 0x898...0x89f => true, 0x8ca...0x8e1 => true, 0x8e3...0x902 => true, 0x93a => true, 0x93c => true, 0x941...0x948 => true, 0x94d => true, 0x951...0x957 => true, 0x962...0x963 => true, 0x981 => true, 0x9bc => true, 0x9c1...0x9c4 => true, 0x9cd => true, 0x9e2...0x9e3 => true, 0x9fe => true, 0xa01...0xa02 => true, 0xa3c => true, 0xa41...0xa42 => true, 0xa47...0xa48 => true, 0xa4b...0xa4d => true, 0xa51 => true, 0xa70...0xa71 => true, 0xa75 => true, 0xa81...0xa82 => true, 0xabc => true, 0xac1...0xac5 => true, 0xac7...0xac8 => true, 0xacd => true, 0xae2...0xae3 => true, 0xafa...0xaff => true, 0xb01 => true, 0xb3c => true, 0xb3f => true, 0xb41...0xb44 => true, 0xb4d => true, 0xb55...0xb56 => true, 0xb62...0xb63 => true, 0xb82 => true, 0xbc0 => true, 0xbcd => true, 0xc00 => true, 0xc04 => true, 0xc3c => true, 0xc3e...0xc40 => true, 0xc46...0xc48 => true, 0xc4a...0xc4d => true, 0xc55...0xc56 => true, 0xc62...0xc63 => true, 0xc81 => true, 0xcbc => true, 0xcbf => true, 0xcc6 => true, 0xccc...0xccd => true, 0xce2...0xce3 => true, 0xd00...0xd01 => true, 0xd3b...0xd3c => true, 0xd41...0xd44 => true, 0xd4d => true, 0xd62...0xd63 => true, 0xd81 => true, 0xdca => true, 0xdd2...0xdd4 => true, 0xdd6 => true, 0xe31 => true, 0xe34...0xe3a => true, 0xe47...0xe4e => true, 0xeb1 => true, 0xeb4...0xebc => true, 0xec8...0xecd => true, 0xf18...0xf19 => true, 0xf35 => true, 0xf37 => true, 0xf39 => true, 0xf71...0xf7e => true, 0xf80...0xf84 => true, 0xf86...0xf87 => true, 0xf8d...0xf97 => true, 0xf99...0xfbc => true, 0xfc6 => true, 0x102d...0x1030 => true, 0x1032...0x1037 => true, 0x1039...0x103a => true, 0x103d...0x103e => true, 0x1058...0x1059 => true, 0x105e...0x1060 => true, 0x1071...0x1074 => true, 0x1082 => true, 0x1085...0x1086 => true, 0x108d => true, 0x109d => true, 0x135d...0x135f => true, 0x1712...0x1714 => true, 0x1732...0x1733 => true, 0x1752...0x1753 => true, 0x1772...0x1773 => true, 0x17b4...0x17b5 => true, 0x17b7...0x17bd => true, 0x17c6 => true, 0x17c9...0x17d3 => true, 0x17dd => true, 0x180b...0x180d => true, 0x180f => true, 0x1885...0x1886 => true, 0x18a9 => true, 0x1920...0x1922 => true, 0x1927...0x1928 => true, 0x1932 => true, 0x1939...0x193b => true, 0x1a17...0x1a18 => true, 0x1a1b => true, 0x1a56 => true, 0x1a58...0x1a5e => true, 0x1a60 => true, 0x1a62 => true, 0x1a65...0x1a6c => true, 0x1a73...0x1a7c => true, 0x1a7f => true, 0x1ab0...0x1abd => true, 0x1abf...0x1ace => true, 0x1b00...0x1b03 => true, 0x1b34 => true, 0x1b36...0x1b3a => true, 0x1b3c => true, 0x1b42 => true, 0x1b6b...0x1b73 => true, 0x1b80...0x1b81 => true, 0x1ba2...0x1ba5 => true, 0x1ba8...0x1ba9 => true, 0x1bab...0x1bad => true, 0x1be6 => true, 0x1be8...0x1be9 => true, 0x1bed => true, 0x1bef...0x1bf1 => true, 0x1c2c...0x1c33 => true, 0x1c36...0x1c37 => true, 0x1cd0...0x1cd2 => true, 0x1cd4...0x1ce0 => true, 0x1ce2...0x1ce8 => true, 0x1ced => true, 0x1cf4 => true, 0x1cf8...0x1cf9 => true, 0x1dc0...0x1dff => true, 0x20d0...0x20dc => true, 0x20e1 => true, 0x20e5...0x20f0 => true, 0x2cef...0x2cf1 => true, 0x2d7f => true, 0x2de0...0x2dff => true, 0x302a...0x302d => true, 0x3099...0x309a => true, 0xa66f => true, 0xa674...0xa67d => true, 0xa69e...0xa69f => true, 0xa6f0...0xa6f1 => true, 0xa802 => true, 0xa806 => true, 0xa80b => true, 0xa825...0xa826 => true, 0xa82c => true, 0xa8c4...0xa8c5 => true, 0xa8e0...0xa8f1 => true, 0xa8ff => true, 0xa926...0xa92d => true, 0xa947...0xa951 => true, 0xa980...0xa982 => true, 0xa9b3 => true, 0xa9b6...0xa9b9 => true, 0xa9bc...0xa9bd => true, 0xa9e5 => true, 0xaa29...0xaa2e => true, 0xaa31...0xaa32 => true, 0xaa35...0xaa36 => true, 0xaa43 => true, 0xaa4c => true, 0xaa7c => true, 0xaab0 => true, 0xaab2...0xaab4 => true, 0xaab7...0xaab8 => true, 0xaabe...0xaabf => true, 0xaac1 => true, 0xaaec...0xaaed => true, 0xaaf6 => true, 0xabe5 => true, 0xabe8 => true, 0xabed => true, 0xfb1e => true, 0xfe00...0xfe0f => true, 0xfe20...0xfe2f => true, 0x101fd => true, 0x102e0 => true, 0x10376...0x1037a => true, 0x10a01...0x10a03 => true, 0x10a05...0x10a06 => true, 0x10a0c...0x10a0f => true, 0x10a38...0x10a3a => true, 0x10a3f => true, 0x10ae5...0x10ae6 => true, 0x10d24...0x10d27 => true, 0x10eab...0x10eac => true, 0x10f46...0x10f50 => true, 0x10f82...0x10f85 => true, 0x11001 => true, 0x11038...0x11046 => true, 0x11070 => true, 0x11073...0x11074 => true, 0x1107f...0x11081 => true, 0x110b3...0x110b6 => true, 0x110b9...0x110ba => true, 0x110c2 => true, 0x11100...0x11102 => true, 0x11127...0x1112b => true, 0x1112d...0x11134 => true, 0x11173 => true, 0x11180...0x11181 => true, 0x111b6...0x111be => true, 0x111c9...0x111cc => true, 0x111cf => true, 0x1122f...0x11231 => true, 0x11234 => true, 0x11236...0x11237 => true, 0x1123e => true, 0x112df => true, 0x112e3...0x112ea => true, 0x11300...0x11301 => true, 0x1133b...0x1133c => true, 0x11340 => true, 0x11366...0x1136c => true, 0x11370...0x11374 => true, 0x11438...0x1143f => true, 0x11442...0x11444 => true, 0x11446 => true, 0x1145e => true, 0x114b3...0x114b8 => true, 0x114ba => true, 0x114bf...0x114c0 => true, 0x114c2...0x114c3 => true, 0x115b2...0x115b5 => true, 0x115bc...0x115bd => true, 0x115bf...0x115c0 => true, 0x115dc...0x115dd => true, 0x11633...0x1163a => true, 0x1163d => true, 0x1163f...0x11640 => true, 0x116ab => true, 0x116ad => true, 0x116b0...0x116b5 => true, 0x116b7 => true, 0x1171d...0x1171f => true, 0x11722...0x11725 => true, 0x11727...0x1172b => true, 0x1182f...0x11837 => true, 0x11839...0x1183a => true, 0x1193b...0x1193c => true, 0x1193e => true, 0x11943 => true, 0x119d4...0x119d7 => true, 0x119da...0x119db => true, 0x119e0 => true, 0x11a01...0x11a0a => true, 0x11a33...0x11a38 => true, 0x11a3b...0x11a3e => true, 0x11a47 => true, 0x11a51...0x11a56 => true, 0x11a59...0x11a5b => true, 0x11a8a...0x11a96 => true, 0x11a98...0x11a99 => true, 0x11c30...0x11c36 => true, 0x11c38...0x11c3d => true, 0x11c3f => true, 0x11c92...0x11ca7 => true, 0x11caa...0x11cb0 => true, 0x11cb2...0x11cb3 => true, 0x11cb5...0x11cb6 => true, 0x11d31...0x11d36 => true, 0x11d3a => true, 0x11d3c...0x11d3d => true, 0x11d3f...0x11d45 => true, 0x11d47 => true, 0x11d90...0x11d91 => true, 0x11d95 => true, 0x11d97 => true, 0x11ef3...0x11ef4 => true, 0x16af0...0x16af4 => true, 0x16b30...0x16b36 => true, 0x16f4f => true, 0x16f8f...0x16f92 => true, 0x16fe4 => true, 0x1bc9d...0x1bc9e => true, 0x1cf00...0x1cf2d => true, 0x1cf30...0x1cf46 => true, 0x1d167...0x1d169 => true, 0x1d17b...0x1d182 => true, 0x1d185...0x1d18b => true, 0x1d1aa...0x1d1ad => true, 0x1d242...0x1d244 => true, 0x1da00...0x1da36 => true, 0x1da3b...0x1da6c => true, 0x1da75 => true, 0x1da84 => true, 0x1da9b...0x1da9f => true, 0x1daa1...0x1daaf => true, 0x1e000...0x1e006 => true, 0x1e008...0x1e018 => true, 0x1e01b...0x1e021 => true, 0x1e023...0x1e024 => true, 0x1e026...0x1e02a => true, 0x1e130...0x1e136 => true, 0x1e2ae => true, 0x1e2ec...0x1e2ef => true, 0x1e8d0...0x1e8d6 => true, 0x1e944...0x1e94a => true, 0xe0100...0xe01ef => true, else => false, }; } pub fn isEnclosingMark(cp: u21) bool { if (cp < 0x488 or cp > 0xa672) return false; return switch (cp) { 0x488...0x489 => true, 0x1abe => true, 0x20dd...0x20e0 => true, 0x20e2...0x20e4 => true, 0xa670...0xa672 => true, else => false, }; } pub fn isSpacingMark(cp: u21) bool { if (cp < 0x903 or cp > 0x1d172) return false; return switch (cp) { 0x903 => true, 0x93b => true, 0x93e...0x940 => true, 0x949...0x94c => true, 0x94e...0x94f => true, 0x982...0x983 => true, 0x9be...0x9c0 => true, 0x9c7...0x9c8 => true, 0x9cb...0x9cc => true, 0x9d7 => true, 0xa03 => true, 0xa3e...0xa40 => true, 0xa83 => true, 0xabe...0xac0 => true, 0xac9 => true, 0xacb...0xacc => true, 0xb02...0xb03 => true, 0xb3e => true, 0xb40 => true, 0xb47...0xb48 => true, 0xb4b...0xb4c => true, 0xb57 => true, 0xbbe...0xbbf => true, 0xbc1...0xbc2 => true, 0xbc6...0xbc8 => true, 0xbca...0xbcc => true, 0xbd7 => true, 0xc01...0xc03 => true, 0xc41...0xc44 => true, 0xc82...0xc83 => true, 0xcbe => true, 0xcc0...0xcc4 => true, 0xcc7...0xcc8 => true, 0xcca...0xccb => true, 0xcd5...0xcd6 => true, 0xd02...0xd03 => true, 0xd3e...0xd40 => true, 0xd46...0xd48 => true, 0xd4a...0xd4c => true, 0xd57 => true, 0xd82...0xd83 => true, 0xdcf...0xdd1 => true, 0xdd8...0xddf => true, 0xdf2...0xdf3 => true, 0xf3e...0xf3f => true, 0xf7f => true, 0x102b...0x102c => true, 0x1031 => true, 0x1038 => true, 0x103b...0x103c => true, 0x1056...0x1057 => true, 0x1062...0x1064 => true, 0x1067...0x106d => true, 0x1083...0x1084 => true, 0x1087...0x108c => true, 0x108f => true, 0x109a...0x109c => true, 0x1715 => true, 0x1734 => true, 0x17b6 => true, 0x17be...0x17c5 => true, 0x17c7...0x17c8 => true, 0x1923...0x1926 => true, 0x1929...0x192b => true, 0x1930...0x1931 => true, 0x1933...0x1938 => true, 0x1a19...0x1a1a => true, 0x1a55 => true, 0x1a57 => true, 0x1a61 => true, 0x1a63...0x1a64 => true, 0x1a6d...0x1a72 => true, 0x1b04 => true, 0x1b35 => true, 0x1b3b => true, 0x1b3d...0x1b41 => true, 0x1b43...0x1b44 => true, 0x1b82 => true, 0x1ba1 => true, 0x1ba6...0x1ba7 => true, 0x1baa => true, 0x1be7 => true, 0x1bea...0x1bec => true, 0x1bee => true, 0x1bf2...0x1bf3 => true, 0x1c24...0x1c2b => true, 0x1c34...0x1c35 => true, 0x1ce1 => true, 0x1cf7 => true, 0x302e...0x302f => true, 0xa823...0xa824 => true, 0xa827 => true, 0xa880...0xa881 => true, 0xa8b4...0xa8c3 => true, 0xa952...0xa953 => true, 0xa983 => true, 0xa9b4...0xa9b5 => true, 0xa9ba...0xa9bb => true, 0xa9be...0xa9c0 => true, 0xaa2f...0xaa30 => true, 0xaa33...0xaa34 => true, 0xaa4d => true, 0xaa7b => true, 0xaa7d => true, 0xaaeb => true, 0xaaee...0xaaef => true, 0xaaf5 => true, 0xabe3...0xabe4 => true, 0xabe6...0xabe7 => true, 0xabe9...0xabea => true, 0xabec => true, 0x11000 => true, 0x11002 => true, 0x11082 => true, 0x110b0...0x110b2 => true, 0x110b7...0x110b8 => true, 0x1112c => true, 0x11145...0x11146 => true, 0x11182 => true, 0x111b3...0x111b5 => true, 0x111bf...0x111c0 => true, 0x111ce => true, 0x1122c...0x1122e => true, 0x11232...0x11233 => true, 0x11235 => true, 0x112e0...0x112e2 => true, 0x11302...0x11303 => true, 0x1133e...0x1133f => true, 0x11341...0x11344 => true, 0x11347...0x11348 => true, 0x1134b...0x1134d => true, 0x11357 => true, 0x11362...0x11363 => true, 0x11435...0x11437 => true, 0x11440...0x11441 => true, 0x11445 => true, 0x114b0...0x114b2 => true, 0x114b9 => true, 0x114bb...0x114be => true, 0x114c1 => true, 0x115af...0x115b1 => true, 0x115b8...0x115bb => true, 0x115be => true, 0x11630...0x11632 => true, 0x1163b...0x1163c => true, 0x1163e => true, 0x116ac => true, 0x116ae...0x116af => true, 0x116b6 => true, 0x11720...0x11721 => true, 0x11726 => true, 0x1182c...0x1182e => true, 0x11838 => true, 0x11930...0x11935 => true, 0x11937...0x11938 => true, 0x1193d => true, 0x11940 => true, 0x11942 => true, 0x119d1...0x119d3 => true, 0x119dc...0x119df => true, 0x119e4 => true, 0x11a39 => true, 0x11a57...0x11a58 => true, 0x11a97 => true, 0x11c2f => true, 0x11c3e => true, 0x11ca9 => true, 0x11cb1 => true, 0x11cb4 => true, 0x11d8a...0x11d8e => true, 0x11d93...0x11d94 => true, 0x11d96 => true, 0x11ef5...0x11ef6 => true, 0x16f51...0x16f87 => true, 0x16ff0...0x16ff1 => true, 0x1d165...0x1d166 => true, 0x1d16d...0x1d172 => true, else => false, }; } pub fn isDecimalNumber(cp: u21) bool { if (cp < 0x30 or cp > 0x1fbf9) return false; return switch (cp) { 0x30...0x39 => true, 0x660...0x669 => true, 0x6f0...0x6f9 => true, 0x7c0...0x7c9 => true, 0x966...0x96f => true, 0x9e6...0x9ef => true, 0xa66...0xa6f => true, 0xae6...0xaef => true, 0xb66...0xb6f => true, 0xbe6...0xbef => true, 0xc66...0xc6f => true, 0xce6...0xcef => true, 0xd66...0xd6f => true, 0xde6...0xdef => true, 0xe50...0xe59 => true, 0xed0...0xed9 => true, 0xf20...0xf29 => true, 0x1040...0x1049 => true, 0x1090...0x1099 => true, 0x17e0...0x17e9 => true, 0x1810...0x1819 => true, 0x1946...0x194f => true, 0x19d0...0x19d9 => true, 0x1a80...0x1a89 => true, 0x1a90...0x1a99 => true, 0x1b50...0x1b59 => true, 0x1bb0...0x1bb9 => true, 0x1c40...0x1c49 => true, 0x1c50...0x1c59 => true, 0xa620...0xa629 => true, 0xa8d0...0xa8d9 => true, 0xa900...0xa909 => true, 0xa9d0...0xa9d9 => true, 0xa9f0...0xa9f9 => true, 0xaa50...0xaa59 => true, 0xabf0...0xabf9 => true, 0xff10...0xff19 => true, 0x104a0...0x104a9 => true, 0x10d30...0x10d39 => true, 0x11066...0x1106f => true, 0x110f0...0x110f9 => true, 0x11136...0x1113f => true, 0x111d0...0x111d9 => true, 0x112f0...0x112f9 => true, 0x11450...0x11459 => true, 0x114d0...0x114d9 => true, 0x11650...0x11659 => true, 0x116c0...0x116c9 => true, 0x11730...0x11739 => true, 0x118e0...0x118e9 => true, 0x11950...0x11959 => true, 0x11c50...0x11c59 => true, 0x11d50...0x11d59 => true, 0x11da0...0x11da9 => true, 0x16a60...0x16a69 => true, 0x16ac0...0x16ac9 => true, 0x16b50...0x16b59 => true, 0x1d7ce...0x1d7ff => true, 0x1e140...0x1e149 => true, 0x1e2f0...0x1e2f9 => true, 0x1e950...0x1e959 => true, 0x1fbf0...0x1fbf9 => true, else => false, }; } pub fn isLetterNumber(cp: u21) bool { if (cp < 0x16ee or cp > 0x1246e) return false; return switch (cp) { 0x16ee...0x16f0 => true, 0x2160...0x2182 => true, 0x2185...0x2188 => true, 0x3007 => true, 0x3021...0x3029 => true, 0x3038...0x303a => true, 0xa6e6...0xa6ef => true, 0x10140...0x10174 => true, 0x10341 => true, 0x1034a => true, 0x103d1...0x103d5 => true, 0x12400...0x1246e => true, else => false, }; } pub fn isOtherNumber(cp: u21) bool { if (cp < 0xb2 or cp > 0x1f10c) return false; return switch (cp) { 0xb2...0xb3 => true, 0xb9 => true, 0xbc...0xbe => true, 0x9f4...0x9f9 => true, 0xb72...0xb77 => true, 0xbf0...0xbf2 => true, 0xc78...0xc7e => true, 0xd58...0xd5e => true, 0xd70...0xd78 => true, 0xf2a...0xf33 => true, 0x1369...0x137c => true, 0x17f0...0x17f9 => true, 0x19da => true, 0x2070 => true, 0x2074...0x2079 => true, 0x2080...0x2089 => true, 0x2150...0x215f => true, 0x2189 => true, 0x2460...0x249b => true, 0x24ea...0x24ff => true, 0x2776...0x2793 => true, 0x2cfd => true, 0x3192...0x3195 => true, 0x3220...0x3229 => true, 0x3248...0x324f => true, 0x3251...0x325f => true, 0x3280...0x3289 => true, 0x32b1...0x32bf => true, 0xa830...0xa835 => true, 0x10107...0x10133 => true, 0x10175...0x10178 => true, 0x1018a...0x1018b => true, 0x102e1...0x102fb => true, 0x10320...0x10323 => true, 0x10858...0x1085f => true, 0x10879...0x1087f => true, 0x108a7...0x108af => true, 0x108fb...0x108ff => true, 0x10916...0x1091b => true, 0x109bc...0x109bd => true, 0x109c0...0x109cf => true, 0x109d2...0x109ff => true, 0x10a40...0x10a48 => true, 0x10a7d...0x10a7e => true, 0x10a9d...0x10a9f => true, 0x10aeb...0x10aef => true, 0x10b58...0x10b5f => true, 0x10b78...0x10b7f => true, 0x10ba9...0x10baf => true, 0x10cfa...0x10cff => true, 0x10e60...0x10e7e => true, 0x10f1d...0x10f26 => true, 0x10f51...0x10f54 => true, 0x10fc5...0x10fcb => true, 0x11052...0x11065 => true, 0x111e1...0x111f4 => true, 0x1173a...0x1173b => true, 0x118ea...0x118f2 => true, 0x11c5a...0x11c6c => true, 0x11fc0...0x11fd4 => true, 0x16b5b...0x16b61 => true, 0x16e80...0x16e96 => true, 0x1d2e0...0x1d2f3 => true, 0x1d360...0x1d378 => true, 0x1e8c7...0x1e8cf => true, 0x1ec71...0x1ecab => true, 0x1ecad...0x1ecaf => true, 0x1ecb1...0x1ecb4 => true, 0x1ed01...0x1ed2d => true, 0x1ed2f...0x1ed3d => true, 0x1f100...0x1f10c => true, else => false, }; } pub fn isSpaceSeparator(cp: u21) bool { if (cp < 0x20 or cp > 0x3000) return false; return switch (cp) { 0x20 => true, 0xa0 => true, 0x1680 => true, 0x2000...0x200a => true, 0x202f => true, 0x205f => true, 0x3000 => true, else => false, }; } pub fn isLineSeparator(cp: u21) bool { return cp == 0x2028; } pub fn isParagraphSeparator(cp: u21) bool { return cp == 0x2029; } pub fn isControl(cp: u21) bool { if (cp < 0x0 or cp > 0x9f) return false; return switch (cp) { 0x0...0x1f => true, 0x7f...0x9f => true, else => false, }; } pub fn isFormat(cp: u21) bool { if (cp < 0xad or cp > 0xe007f) return false; return switch (cp) { 0xad => true, 0x600...0x605 => true, 0x61c => true, 0x6dd => true, 0x70f => true, 0x890...0x891 => true, 0x8e2 => true, 0x180e => true, 0x200b...0x200f => true, 0x202a...0x202e => true, 0x2060...0x2064 => true, 0x2066...0x206f => true, 0xfeff => true, 0xfff9...0xfffb => true, 0x110bd => true, 0x110cd => true, 0x13430...0x13438 => true, 0x1bca0...0x1bca3 => true, 0x1d173...0x1d17a => true, 0xe0001 => true, 0xe0020...0xe007f => true, else => false, }; } pub fn isPrivateUse(cp: u21) bool { if (cp < 0xe000 or cp > 0x10fffd) return false; return switch (cp) { 0xe000...0xf8ff => true, 0xf0000...0xffffd => true, 0x100000...0x10fffd => true, else => false, }; } pub fn isSurrogate(cp: u21) bool { if (cp < 0xd800 or cp > 0xdfff) return false; return switch (cp) { 0xd800...0xdfff => true, else => false, }; } pub fn isDashPunctuation(cp: u21) bool { if (cp < 0x2d or cp > 0x10ead) return false; return switch (cp) { 0x2d => true, 0x58a => true, 0x5be => true, 0x1400 => true, 0x1806 => true, 0x2010...0x2015 => true, 0x2e17 => true, 0x2e1a => true, 0x2e3a...0x2e3b => true, 0x2e40 => true, 0x2e5d => true, 0x301c => true, 0x3030 => true, 0x30a0 => true, 0xfe31...0xfe32 => true, 0xfe58 => true, 0xfe63 => true, 0xff0d => true, 0x10ead => true, else => false, }; } pub fn isOpenPunctuation(cp: u21) bool { if (cp < 0x28 or cp > 0xff62) return false; return switch (cp) { 0x28 => true, 0x5b => true, 0x7b => true, 0xf3a => true, 0xf3c => true, 0x169b => true, 0x201a => true, 0x201e => true, 0x2045 => true, 0x207d => true, 0x208d => true, 0x2308 => true, 0x230a => true, 0x2329 => true, 0x2768 => true, 0x276a => true, 0x276c => true, 0x276e => true, 0x2770 => true, 0x2772 => true, 0x2774 => true, 0x27c5 => true, 0x27e6 => true, 0x27e8 => true, 0x27ea => true, 0x27ec => true, 0x27ee => true, 0x2983 => true, 0x2985 => true, 0x2987 => true, 0x2989 => true, 0x298b => true, 0x298d => true, 0x298f => true, 0x2991 => true, 0x2993 => true, 0x2995 => true, 0x2997 => true, 0x29d8 => true, 0x29da => true, 0x29fc => true, 0x2e22 => true, 0x2e24 => true, 0x2e26 => true, 0x2e28 => true, 0x2e42 => true, 0x2e55 => true, 0x2e57 => true, 0x2e59 => true, 0x2e5b => true, 0x3008 => true, 0x300a => true, 0x300c => true, 0x300e => true, 0x3010 => true, 0x3014 => true, 0x3016 => true, 0x3018 => true, 0x301a => true, 0x301d => true, 0xfd3f => true, 0xfe17 => true, 0xfe35 => true, 0xfe37 => true, 0xfe39 => true, 0xfe3b => true, 0xfe3d => true, 0xfe3f => true, 0xfe41 => true, 0xfe43 => true, 0xfe47 => true, 0xfe59 => true, 0xfe5b => true, 0xfe5d => true, 0xff08 => true, 0xff3b => true, 0xff5b => true, 0xff5f => true, 0xff62 => true, else => false, }; } pub fn isClosePunctuation(cp: u21) bool { if (cp < 0x29 or cp > 0xff63) return false; return switch (cp) { 0x29 => true, 0x5d => true, 0x7d => true, 0xf3b => true, 0xf3d => true, 0x169c => true, 0x2046 => true, 0x207e => true, 0x208e => true, 0x2309 => true, 0x230b => true, 0x232a => true, 0x2769 => true, 0x276b => true, 0x276d => true, 0x276f => true, 0x2771 => true, 0x2773 => true, 0x2775 => true, 0x27c6 => true, 0x27e7 => true, 0x27e9 => true, 0x27eb => true, 0x27ed => true, 0x27ef => true, 0x2984 => true, 0x2986 => true, 0x2988 => true, 0x298a => true, 0x298c => true, 0x298e => true, 0x2990 => true, 0x2992 => true, 0x2994 => true, 0x2996 => true, 0x2998 => true, 0x29d9 => true, 0x29db => true, 0x29fd => true, 0x2e23 => true, 0x2e25 => true, 0x2e27 => true, 0x2e29 => true, 0x2e56 => true, 0x2e58 => true, 0x2e5a => true, 0x2e5c => true, 0x3009 => true, 0x300b => true, 0x300d => true, 0x300f => true, 0x3011 => true, 0x3015 => true, 0x3017 => true, 0x3019 => true, 0x301b => true, 0x301e...0x301f => true, 0xfd3e => true, 0xfe18 => true, 0xfe36 => true, 0xfe38 => true, 0xfe3a => true, 0xfe3c => true, 0xfe3e => true, 0xfe40 => true, 0xfe42 => true, 0xfe44 => true, 0xfe48 => true, 0xfe5a => true, 0xfe5c => true, 0xfe5e => true, 0xff09 => true, 0xff3d => true, 0xff5d => true, 0xff60 => true, 0xff63 => true, else => false, }; } pub fn isConnectorPunctuation(cp: u21) bool { if (cp < 0x5f or cp > 0xff3f) return false; return switch (cp) { 0x5f => true, 0x203f...0x2040 => true, 0x2054 => true, 0xfe33...0xfe34 => true, 0xfe4d...0xfe4f => true, 0xff3f => true, else => false, }; } pub fn isOtherPunctuation(cp: u21) bool { if (cp < 0x21 or cp > 0x1e95f) return false; return switch (cp) { 0x21...0x23 => true, 0x25...0x27 => true, 0x2a => true, 0x2c => true, 0x2e...0x2f => true, 0x3a...0x3b => true, 0x3f...0x40 => true, 0x5c => true, 0xa1 => true, 0xa7 => true, 0xb6...0xb7 => true, 0xbf => true, 0x37e => true, 0x387 => true, 0x55a...0x55f => true, 0x589 => true, 0x5c0 => true, 0x5c3 => true, 0x5c6 => true, 0x5f3...0x5f4 => true, 0x609...0x60a => true, 0x60c...0x60d => true, 0x61b => true, 0x61d...0x61f => true, 0x66a...0x66d => true, 0x6d4 => true, 0x700...0x70d => true, 0x7f7...0x7f9 => true, 0x830...0x83e => true, 0x85e => true, 0x964...0x965 => true, 0x970 => true, 0x9fd => true, 0xa76 => true, 0xaf0 => true, 0xc77 => true, 0xc84 => true, 0xdf4 => true, 0xe4f => true, 0xe5a...0xe5b => true, 0xf04...0xf12 => true, 0xf14 => true, 0xf85 => true, 0xfd0...0xfd4 => true, 0xfd9...0xfda => true, 0x104a...0x104f => true, 0x10fb => true, 0x1360...0x1368 => true, 0x166e => true, 0x16eb...0x16ed => true, 0x1735...0x1736 => true, 0x17d4...0x17d6 => true, 0x17d8...0x17da => true, 0x1800...0x1805 => true, 0x1807...0x180a => true, 0x1944...0x1945 => true, 0x1a1e...0x1a1f => true, 0x1aa0...0x1aa6 => true, 0x1aa8...0x1aad => true, 0x1b5a...0x1b60 => true, 0x1b7d...0x1b7e => true, 0x1bfc...0x1bff => true, 0x1c3b...0x1c3f => true, 0x1c7e...0x1c7f => true, 0x1cc0...0x1cc7 => true, 0x1cd3 => true, 0x2016...0x2017 => true, 0x2020...0x2027 => true, 0x2030...0x2038 => true, 0x203b...0x203e => true, 0x2041...0x2043 => true, 0x2047...0x2051 => true, 0x2053 => true, 0x2055...0x205e => true, 0x2cf9...0x2cfc => true, 0x2cfe...0x2cff => true, 0x2d70 => true, 0x2e00...0x2e01 => true, 0x2e06...0x2e08 => true, 0x2e0b => true, 0x2e0e...0x2e16 => true, 0x2e18...0x2e19 => true, 0x2e1b => true, 0x2e1e...0x2e1f => true, 0x2e2a...0x2e2e => true, 0x2e30...0x2e39 => true, 0x2e3c...0x2e3f => true, 0x2e41 => true, 0x2e43...0x2e4f => true, 0x2e52...0x2e54 => true, 0x3001...0x3003 => true, 0x303d => true, 0x30fb => true, 0xa4fe...0xa4ff => true, 0xa60d...0xa60f => true, 0xa673 => true, 0xa67e => true, 0xa6f2...0xa6f7 => true, 0xa874...0xa877 => true, 0xa8ce...0xa8cf => true, 0xa8f8...0xa8fa => true, 0xa8fc => true, 0xa92e...0xa92f => true, 0xa95f => true, 0xa9c1...0xa9cd => true, 0xa9de...0xa9df => true, 0xaa5c...0xaa5f => true, 0xaade...0xaadf => true, 0xaaf0...0xaaf1 => true, 0xabeb => true, 0xfe10...0xfe16 => true, 0xfe19 => true, 0xfe30 => true, 0xfe45...0xfe46 => true, 0xfe49...0xfe4c => true, 0xfe50...0xfe52 => true, 0xfe54...0xfe57 => true, 0xfe5f...0xfe61 => true, 0xfe68 => true, 0xfe6a...0xfe6b => true, 0xff01...0xff03 => true, 0xff05...0xff07 => true, 0xff0a => true, 0xff0c => true, 0xff0e...0xff0f => true, 0xff1a...0xff1b => true, 0xff1f...0xff20 => true, 0xff3c => true, 0xff61 => true, 0xff64...0xff65 => true, 0x10100...0x10102 => true, 0x1039f => true, 0x103d0 => true, 0x1056f => true, 0x10857 => true, 0x1091f => true, 0x1093f => true, 0x10a50...0x10a58 => true, 0x10a7f => true, 0x10af0...0x10af6 => true, 0x10b39...0x10b3f => true, 0x10b99...0x10b9c => true, 0x10f55...0x10f59 => true, 0x10f86...0x10f89 => true, 0x11047...0x1104d => true, 0x110bb...0x110bc => true, 0x110be...0x110c1 => true, 0x11140...0x11143 => true, 0x11174...0x11175 => true, 0x111c5...0x111c8 => true, 0x111cd => true, 0x111db => true, 0x111dd...0x111df => true, 0x11238...0x1123d => true, 0x112a9 => true, 0x1144b...0x1144f => true, 0x1145a...0x1145b => true, 0x1145d => true, 0x114c6 => true, 0x115c1...0x115d7 => true, 0x11641...0x11643 => true, 0x11660...0x1166c => true, 0x116b9 => true, 0x1173c...0x1173e => true, 0x1183b => true, 0x11944...0x11946 => true, 0x119e2 => true, 0x11a3f...0x11a46 => true, 0x11a9a...0x11a9c => true, 0x11a9e...0x11aa2 => true, 0x11c41...0x11c45 => true, 0x11c70...0x11c71 => true, 0x11ef7...0x11ef8 => true, 0x11fff => true, 0x12470...0x12474 => true, 0x12ff1...0x12ff2 => true, 0x16a6e...0x16a6f => true, 0x16af5 => true, 0x16b37...0x16b3b => true, 0x16b44 => true, 0x16e97...0x16e9a => true, 0x16fe2 => true, 0x1bc9f => true, 0x1da87...0x1da8b => true, 0x1e95e...0x1e95f => true, else => false, }; } pub fn isMathSymbol(cp: u21) bool { if (cp < 0x2b or cp > 0x1eef1) return false; return switch (cp) { 0x2b => true, 0x3c...0x3e => true, 0x7c => true, 0x7e => true, 0xac => true, 0xb1 => true, 0xd7 => true, 0xf7 => true, 0x3f6 => true, 0x606...0x608 => true, 0x2044 => true, 0x2052 => true, 0x207a...0x207c => true, 0x208a...0x208c => true, 0x2118 => true, 0x2140...0x2144 => true, 0x214b => true, 0x2190...0x2194 => true, 0x219a...0x219b => true, 0x21a0 => true, 0x21a3 => true, 0x21a6 => true, 0x21ae => true, 0x21ce...0x21cf => true, 0x21d2 => true, 0x21d4 => true, 0x21f4...0x22ff => true, 0x2320...0x2321 => true, 0x237c => true, 0x239b...0x23b3 => true, 0x23dc...0x23e1 => true, 0x25b7 => true, 0x25c1 => true, 0x25f8...0x25ff => true, 0x266f => true, 0x27c0...0x27c4 => true, 0x27c7...0x27e5 => true, 0x27f0...0x27ff => true, 0x2900...0x2982 => true, 0x2999...0x29d7 => true, 0x29dc...0x29fb => true, 0x29fe...0x2aff => true, 0x2b30...0x2b44 => true, 0x2b47...0x2b4c => true, 0xfb29 => true, 0xfe62 => true, 0xfe64...0xfe66 => true, 0xff0b => true, 0xff1c...0xff1e => true, 0xff5c => true, 0xff5e => true, 0xffe2 => true, 0xffe9...0xffec => true, 0x1d6c1 => true, 0x1d6db => true, 0x1d6fb => true, 0x1d715 => true, 0x1d735 => true, 0x1d74f => true, 0x1d76f => true, 0x1d789 => true, 0x1d7a9 => true, 0x1d7c3 => true, 0x1eef0...0x1eef1 => true, else => false, }; } pub fn isCurrencySymbol(cp: u21) bool { if (cp < 0x24 or cp > 0x1ecb0) return false; return switch (cp) { 0x24 => true, 0xa2...0xa5 => true, 0x58f => true, 0x60b => true, 0x7fe...0x7ff => true, 0x9f2...0x9f3 => true, 0x9fb => true, 0xaf1 => true, 0xbf9 => true, 0xe3f => true, 0x17db => true, 0x20a0...0x20c0 => true, 0xa838 => true, 0xfdfc => true, 0xfe69 => true, 0xff04 => true, 0xffe0...0xffe1 => true, 0xffe5...0xffe6 => true, 0x11fdd...0x11fe0 => true, 0x1e2ff => true, 0x1ecb0 => true, else => false, }; } pub fn isModifierSymbol(cp: u21) bool { if (cp < 0x5e or cp > 0x1f3ff) return false; return switch (cp) { 0x5e => true, 0x60 => true, 0xa8 => true, 0xaf => true, 0xb4 => true, 0xb8 => true, 0x2c2...0x2c5 => true, 0x2d2...0x2df => true, 0x2e5...0x2eb => true, 0x2ed => true, 0x2ef...0x2ff => true, 0x375 => true, 0x384...0x385 => true, 0x888 => true, 0x1fbd => true, 0x1fbf...0x1fc1 => true, 0x1fcd...0x1fcf => true, 0x1fdd...0x1fdf => true, 0x1fed...0x1fef => true, 0x1ffd...0x1ffe => true, 0x309b...0x309c => true, 0xa700...0xa716 => true, 0xa720...0xa721 => true, 0xa789...0xa78a => true, 0xab5b => true, 0xab6a...0xab6b => true, 0xfbb2...0xfbc2 => true, 0xff3e => true, 0xff40 => true, 0xffe3 => true, 0x1f3fb...0x1f3ff => true, else => false, }; } pub fn isOtherSymbol(cp: u21) bool { if (cp < 0xa6 or cp > 0x1fbca) return false; return switch (cp) { 0xa6 => true, 0xa9 => true, 0xae => true, 0xb0 => true, 0x482 => true, 0x58d...0x58e => true, 0x60e...0x60f => true, 0x6de => true, 0x6e9 => true, 0x6fd...0x6fe => true, 0x7f6 => true, 0x9fa => true, 0xb70 => true, 0xbf3...0xbf8 => true, 0xbfa => true, 0xc7f => true, 0xd4f => true, 0xd79 => true, 0xf01...0xf03 => true, 0xf13 => true, 0xf15...0xf17 => true, 0xf1a...0xf1f => true, 0xf34 => true, 0xf36 => true, 0xf38 => true, 0xfbe...0xfc5 => true, 0xfc7...0xfcc => true, 0xfce...0xfcf => true, 0xfd5...0xfd8 => true, 0x109e...0x109f => true, 0x1390...0x1399 => true, 0x166d => true, 0x1940 => true, 0x19de...0x19ff => true, 0x1b61...0x1b6a => true, 0x1b74...0x1b7c => true, 0x2100...0x2101 => true, 0x2103...0x2106 => true, 0x2108...0x2109 => true, 0x2114 => true, 0x2116...0x2117 => true, 0x211e...0x2123 => true, 0x2125 => true, 0x2127 => true, 0x2129 => true, 0x212e => true, 0x213a...0x213b => true, 0x214a => true, 0x214c...0x214d => true, 0x214f => true, 0x218a...0x218b => true, 0x2195...0x2199 => true, 0x219c...0x219f => true, 0x21a1...0x21a2 => true, 0x21a4...0x21a5 => true, 0x21a7...0x21ad => true, 0x21af...0x21cd => true, 0x21d0...0x21d1 => true, 0x21d3 => true, 0x21d5...0x21f3 => true, 0x2300...0x2307 => true, 0x230c...0x231f => true, 0x2322...0x2328 => true, 0x232b...0x237b => true, 0x237d...0x239a => true, 0x23b4...0x23db => true, 0x23e2...0x2426 => true, 0x2440...0x244a => true, 0x249c...0x24e9 => true, 0x2500...0x25b6 => true, 0x25b8...0x25c0 => true, 0x25c2...0x25f7 => true, 0x2600...0x266e => true, 0x2670...0x2767 => true, 0x2794...0x27bf => true, 0x2800...0x28ff => true, 0x2b00...0x2b2f => true, 0x2b45...0x2b46 => true, 0x2b4d...0x2b73 => true, 0x2b76...0x2b95 => true, 0x2b97...0x2bff => true, 0x2ce5...0x2cea => true, 0x2e50...0x2e51 => true, 0x2e80...0x2e99 => true, 0x2e9b...0x2ef3 => true, 0x2f00...0x2fd5 => true, 0x2ff0...0x2ffb => true, 0x3004 => true, 0x3012...0x3013 => true, 0x3020 => true, 0x3036...0x3037 => true, 0x303e...0x303f => true, 0x3190...0x3191 => true, 0x3196...0x319f => true, 0x31c0...0x31e3 => true, 0x3200...0x321e => true, 0x322a...0x3247 => true, 0x3250 => true, 0x3260...0x327f => true, 0x328a...0x32b0 => true, 0x32c0...0x33ff => true, 0x4dc0...0x4dff => true, 0xa490...0xa4c6 => true, 0xa828...0xa82b => true, 0xa836...0xa837 => true, 0xa839 => true, 0xaa77...0xaa79 => true, 0xfd40...0xfd4f => true, 0xfdcf => true, 0xfdfd...0xfdff => true, 0xffe4 => true, 0xffe8 => true, 0xffed...0xffee => true, 0xfffc...0xfffd => true, 0x10137...0x1013f => true, 0x10179...0x10189 => true, 0x1018c...0x1018e => true, 0x10190...0x1019c => true, 0x101a0 => true, 0x101d0...0x101fc => true, 0x10877...0x10878 => true, 0x10ac8 => true, 0x1173f => true, 0x11fd5...0x11fdc => true, 0x11fe1...0x11ff1 => true, 0x16b3c...0x16b3f => true, 0x16b45 => true, 0x1bc9c => true, 0x1cf50...0x1cfc3 => true, 0x1d000...0x1d0f5 => true, 0x1d100...0x1d126 => true, 0x1d129...0x1d164 => true, 0x1d16a...0x1d16c => true, 0x1d183...0x1d184 => true, 0x1d18c...0x1d1a9 => true, 0x1d1ae...0x1d1ea => true, 0x1d200...0x1d241 => true, 0x1d245 => true, 0x1d300...0x1d356 => true, 0x1d800...0x1d9ff => true, 0x1da37...0x1da3a => true, 0x1da6d...0x1da74 => true, 0x1da76...0x1da83 => true, 0x1da85...0x1da86 => true, 0x1e14f => true, 0x1ecac => true, 0x1ed2e => true, 0x1f000...0x1f02b => true, 0x1f030...0x1f093 => true, 0x1f0a0...0x1f0ae => true, 0x1f0b1...0x1f0bf => true, 0x1f0c1...0x1f0cf => true, 0x1f0d1...0x1f0f5 => true, 0x1f10d...0x1f1ad => true, 0x1f1e6...0x1f202 => true, 0x1f210...0x1f23b => true, 0x1f240...0x1f248 => true, 0x1f250...0x1f251 => true, 0x1f260...0x1f265 => true, 0x1f300...0x1f3fa => true, 0x1f400...0x1f6d7 => true, 0x1f6dd...0x1f6ec => true, 0x1f6f0...0x1f6fc => true, 0x1f700...0x1f773 => true, 0x1f780...0x1f7d8 => true, 0x1f7e0...0x1f7eb => true, 0x1f7f0 => true, 0x1f800...0x1f80b => true, 0x1f810...0x1f847 => true, 0x1f850...0x1f859 => true, 0x1f860...0x1f887 => true, 0x1f890...0x1f8ad => true, 0x1f8b0...0x1f8b1 => true, 0x1f900...0x1fa53 => true, 0x1fa60...0x1fa6d => true, 0x1fa70...0x1fa74 => true, 0x1fa78...0x1fa7c => true, 0x1fa80...0x1fa86 => true, 0x1fa90...0x1faac => true, 0x1fab0...0x1faba => true, 0x1fac0...0x1fac5 => true, 0x1fad0...0x1fad9 => true, 0x1fae0...0x1fae7 => true, 0x1faf0...0x1faf6 => true, 0x1fb00...0x1fb92 => true, 0x1fb94...0x1fbca => true, else => false, }; } pub fn isInitialPunctuation(cp: u21) bool { if (cp < 0xab or cp > 0x2e20) return false; return switch (cp) { 0xab => true, 0x2018 => true, 0x201b...0x201c => true, 0x201f => true, 0x2039 => true, 0x2e02 => true, 0x2e04 => true, 0x2e09 => true, 0x2e0c => true, 0x2e1c => true, 0x2e20 => true, else => false, }; } pub fn isFinalPunctuation(cp: u21) bool { if (cp < 0xbb or cp > 0x2e21) return false; return switch (cp) { 0xbb => true, 0x2019 => true, 0x201d => true, 0x203a => true, 0x2e03 => true, 0x2e05 => true, 0x2e0a => true, 0x2e0d => true, 0x2e1d => true, 0x2e21 => true, else => false, }; }
.gyro/ziglyph-jecolon-github.com-c37d93b6/pkg/src/autogen/derived_general_category.zig
const std = @import("std"); const Vec4 = @import("vector.zig").Vec4; const initPoint = @import("vector.zig").initPoint; const initVector = @import("vector.zig").initVector; const Mat4 = @import("matrix.zig").Mat4; const Ray = @import("ray.zig").Ray; const Color = @import("color.zig").Color; const World = @import("world.zig").World; const Canvas = @import("canvas.zig").Canvas; const calc = @import("calc.zig"); const utils = @import("utils.zig"); pub const Camera = struct { const Self = @This(); hsize: usize, vsize: usize, field_of_view: f64, half_width: f64, half_height: f64, pixel_size: f64, transform: Mat4 = Mat4.identity(), pub fn init(hsize: usize, vsize: usize, field_of_view: f64) Self { const half_view = std.math.tan(field_of_view * 0.5); const aspect = @intToFloat(f64, hsize) / @intToFloat(f64, vsize); const half_width = if (aspect >= 1.0) half_view else half_view * aspect; const half_height = if (aspect < 1.0) half_view else half_view / aspect; const pixel_size = (2.0 * half_width) / @intToFloat(f64, hsize); return Self{ .hsize = hsize, .vsize = vsize, .field_of_view = field_of_view, .half_width = half_width, .half_height = half_height, .pixel_size = pixel_size, }; } pub fn rayForPixel(self: Self, x: usize, y: usize) Ray { // the offset from the edge of the canvas to the pixel's center const x_offset = (@intToFloat(f64, x) + 0.5) * self.pixel_size; const y_offset = (@intToFloat(f64, y) + 0.5) * self.pixel_size; // the untransformed coordinates of the pixel in world space // (remember that the camera looks toward -z, so +x is to the *left*) const world_x = self.half_width - x_offset; const world_y = self.half_height - y_offset; // using the camera matrix, transform the canvas point and origin // and then compute the ray's direction vector // (remember that the canvas iat z=-1) const inv = self.transform.inverse(); const pixel = inv.multVec(initPoint(world_x, world_y, -1)); const origin = inv.multVec(initPoint(0, 0, 0)); const direction = pixel.sub(origin).normalize(); return Ray{ .origin = origin, .direction = direction, }; } pub fn render(self: Self, allocator: std.mem.Allocator, world: World) !Canvas { var canvas = try Canvas.init(allocator, self.hsize, self.vsize); var y: usize = 0; while (y < self.vsize) : (y += 1) { // const world_y = half - @intToFloat(f64, y) * pixel_size; var x: usize = 0; while (x < self.hsize) : (x += 1) { const ray = self.rayForPixel(x, y); const color = try calc.worldColorAt(world, ray, 5); canvas.set(x, y, color); } } return canvas; } }; test "Constructing a camera" { const c = Camera.init(160, 120, 0.5 * std.math.pi); try std.testing.expectEqual(@as(usize, 160), c.hsize); try std.testing.expectEqual(@as(usize, 120), c.vsize); try std.testing.expectEqual(@as(f64, 0.5 * std.math.pi), c.field_of_view); } test "The pixel size for a horizontal canvas" { const c = Camera.init(200, 125, 0.5 * std.math.pi); try utils.expectEpsilonEq(@as(f64, 0.01), c.pixel_size); } test "The pixel size for a vertical canvas" { const c = Camera.init(125, 200, 0.5 * std.math.pi); try utils.expectEpsilonEq(@as(f64, 0.01), c.pixel_size); } test "Constructing a ray through the center of the canvas" { const c = Camera.init(201, 101, std.math.pi * 0.5); const r = c.rayForPixel(100, 50); try utils.expectVec4ApproxEq(initPoint(0, 0, 0), r.origin); try utils.expectVec4ApproxEq(initVector(0, 0, -1), r.direction); } test "Constructing a ray through a corner of the canvas" { const c = Camera.init(201, 101, std.math.pi * 0.5); const r = c.rayForPixel(0, 0); try utils.expectVec4ApproxEq(initPoint(0, 0, 0), r.origin); try utils.expectVec4ApproxEq(initVector(0.66519, 0.33259, -0.66851), r.direction); } test "Constructing a ray when the camera is transformed" { var c = Camera.init(201, 101, std.math.pi * 0.5); c.transform = Mat4.identity().translate(0, -2, 5).rotateY(std.math.pi / 4.0); const r = c.rayForPixel(100, 50); try utils.expectVec4ApproxEq(initPoint(0, 2, -5), r.origin); try utils.expectVec4ApproxEq(initVector(std.math.sqrt(2.0) / 2.0, 0, -std.math.sqrt(2.0) / 2.0), r.direction); } const alloc = std.testing.allocator; test "Rendering a world with a camera" { var w = try World.initDefault(alloc); defer w.deinit(); const from = initPoint(0, 0, -5); const to = initPoint(0, 0, 0); const up = initVector(0, 1, 0); var c = Camera.init(11, 11, std.math.pi * 0.5); c.transform = calc.viewTransform(from, to, up); var image = try c.render(alloc, w); defer image.deinit(); try utils.expectColorApproxEq(Color.init(0.38066, 0.47583, 0.2855), image.at(5, 5)); }
camera.zig
const std = @import("std"); const testing = std.testing; const objc = @import("objc.zig"); const object = objc.object; const Class = objc.Class; const id = objc.id; const SEL = objc.SEL; /// Enum representing typecodes as defined by Apple's docs https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html const TypeEncodingToken = enum(u8) { char = 'c', int = 'i', short = 's', long = 'l', // treated as a 32-bit quantity on 64-bit programs long_long = 'q', unsigned_char = 'C', unsigned_int = 'I', unsigned_short = 'S', unsigned_long = 'L', unsigned_long_long = 'Q', float = 'f', double = 'd', bool = 'B', // A C++ bool or a C99 _Bool void = 'v', char_string = '*', // A character string (char *) object = '@', // An object (whether statically typed or typed id) class = '#', // A class object (Class) selector = ':', // A method selector (SEL) array_begin = '[', array_end = ']', struct_begin = '{', struct_end = '}', union_begin = '(', union_end = ')', pair_separator = '=', // Used to separate name-types pairs in structures and unions bitfield = 'b', // Precedes a number representing the size of the bitfield pointer = '^', // Precedes a typecode to represent a pointer to type unknown = '?', // An unknown type (among other things, this code is used for function pointers) }; pub fn writeEncodingForType(comptime MaybeT: ?type, writer: anytype) !void { var levels_of_indirection: u32 = 0; return writeEncodingForTypeInternal(MaybeT, &levels_of_indirection, writer); } fn writeEncodingForTypeInternal(comptime MaybeT: ?type, levels_of_indirection: *u32, writer: anytype) !void { const T = MaybeT orelse { try writeTypeEncodingToken(.void, writer); return; }; switch (T) { i8 => try writeTypeEncodingToken(.char, writer), c_int => try writeTypeEncodingToken(.int, writer), c_short => try writeTypeEncodingToken(.short, writer), c_long => try writeTypeEncodingToken(.long, writer), c_longlong => try writeTypeEncodingToken(.long_long, writer), u8 => try writeTypeEncodingToken(.unsigned_char, writer), c_uint => try writeTypeEncodingToken(.unsigned_int, writer), c_ushort => try writeTypeEncodingToken(.unsigned_short, writer), c_ulong => try writeTypeEncodingToken(.unsigned_long, writer), c_ulonglong => try writeTypeEncodingToken(.unsigned_long_long, writer), f32 => try writeTypeEncodingToken(.float, writer), f64 => try writeTypeEncodingToken(.double, writer), bool => try writeTypeEncodingToken(.bool, writer), void => try writeTypeEncodingToken(.void, writer), [*c]u8, [*c]const u8 => try writeTypeEncodingToken(.char_string, writer), id => try writeTypeEncodingToken(.object, writer), Class => try writeTypeEncodingToken(.class, writer), SEL => try writeTypeEncodingToken(.selector, writer), object => { try writeTypeEncodingToken(.struct_begin, writer); try writer.writeAll(@typeName(T)); try writeTypeEncodingToken(.pair_separator, writer); try writeTypeEncodingToken(.class, writer); try writeTypeEncodingToken(.struct_end, writer); }, else => switch (@typeInfo(T)) { .Fn => |fn_info| { try writeEncodingForTypeInternal(fn_info.return_type, levels_of_indirection, writer); inline for (fn_info.args) |arg| { try writeEncodingForTypeInternal(arg.arg_type, levels_of_indirection, writer); } }, .Array => |arr_info| { try writeTypeEncodingToken(.array_begin, writer); try writer.print("{d}", .{arr_info.len}); try writeEncodingForTypeInternal(arr_info.child, levels_of_indirection, writer); try writeTypeEncodingToken(.array_end, writer); }, .Struct => |struct_info| { try writeTypeEncodingToken(.struct_begin, writer); try writer.writeAll(@typeName(T)); if (levels_of_indirection.* < 2) { try writeTypeEncodingToken(.pair_separator, writer); inline for (struct_info.fields) |field| try writeEncodingForTypeInternal(field.field_type, levels_of_indirection, writer); } try writeTypeEncodingToken(.struct_end, writer); }, .Union => |union_info| { try writeTypeEncodingToken(.union_begin, writer); try writer.writeAll(@typeName(T)); if (levels_of_indirection.* < 2) { try writeTypeEncodingToken(.pair_separator, writer); inline for (union_info.fields) |field| try writeEncodingForTypeInternal(field.field_type, levels_of_indirection, writer); } try writeTypeEncodingToken(.union_end, writer); }, .Pointer => |ptr_info| switch (ptr_info.size) { .One => { levels_of_indirection.* += 1; try writeTypeEncodingToken(.pointer, writer); try writeEncodingForTypeInternal(ptr_info.child, levels_of_indirection, writer); }, else => @compileError("Unsupported type"), }, else => @compileError("Unsupported type"), }, } } fn writeTypeEncodingToken(token: TypeEncodingToken, writer: anytype) !void { try writer.writeByte(@enumToInt(token)); } test "write encoding for array" { var buffer: [0x100]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try writeEncodingForType([12]*f32, fbs.writer()); try testing.expectEqualSlices(u8, "[12^f]", fbs.getWritten()); } test "write encoding for struct, pointer to struct and pointer to pointer to struct" { const Example = struct { anObject: id, aString: [*c]u8, anInt: c_int, }; var buffer: [0x100]u8 = undefined; { var fbs = std.io.fixedBufferStream(&buffer); try writeEncodingForType(Example, fbs.writer()); try testing.expectEqualSlices(u8, "{Example=@*i}", fbs.getWritten()); } { var fbs = std.io.fixedBufferStream(&buffer); try writeEncodingForType(*Example, fbs.writer()); try testing.expectEqualSlices(u8, "^{Example=@*i}", fbs.getWritten()); } { var fbs = std.io.fixedBufferStream(&buffer); try writeEncodingForType(**Example, fbs.writer()); try testing.expectEqualSlices(u8, "^^{Example}", fbs.getWritten()); } } test "write encoding for fn" { try struct { pub fn runTest() !void { var buffer: [0x100]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try writeEncodingForType(@TypeOf(add), fbs.writer()); try testing.expectEqualSlices(u8, "i@:ii", fbs.getWritten()); } fn add(_: id, _: SEL, a: c_int, b: c_int) callconv(.C) c_int { return a + b; } }.runTest(); }
modules/platform/vendored/zig-objcrt/src/type-encoding.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const assert = std.debug.assert; const wz = @import("../main.zig"); const util = @import("../util.zig"); pub const ChunkEvent = struct { data: []const u8, final: bool = false, }; pub const Event = union(enum) { header: wz.MessageHeader, chunk: ChunkEvent, }; pub fn create(buffer: []u8, reader: anytype) MessageParser(@TypeOf(reader)) { assert(buffer.len >= 14); return MessageParser(@TypeOf(reader)).init(buffer, reader); } pub fn MessageParser(comptime Reader: type) type { return struct { const Self = @This(); read_buffer: []u8, chunk_read: usize = 0, mask_index: usize = 0, last_header: wz.MessageHeader = undefined, reader: Reader, state: util.ParserState = .header, pub fn init(buffer: []u8, reader: Reader) Self { return .{ .read_buffer = buffer, .reader = reader, }; } pub fn reset(self: *Self) void { self.chunk_read = 0; self.mask_index = 0; self.last_header = undefined; self.state = .header; } pub const NextError = error{EndOfStream} || Reader.Error; pub fn next(self: *Self) NextError!?Event { switch (self.state) { .header => { const initial_read = try self.reader.readAll(self.read_buffer[0..2]); if (initial_read != 2) return error.EndOfStream; self.last_header.fin = self.read_buffer[0] & 0x80 == 0x80; self.last_header.rsv1 = self.read_buffer[0] & 0x40 == 0x40; self.last_header.rsv2 = self.read_buffer[0] & 0x20 == 0x20; self.last_header.rsv3 = self.read_buffer[0] & 0x10 == 0x10; self.last_header.opcode = @intToEnum(wz.Opcode, @truncate(u4, self.read_buffer[0])); const masked = self.read_buffer[1] & 0x80 == 0x80; const check_len = @truncate(u7, self.read_buffer[1]); if (check_len == 127) { const length_read = try self.reader.readAll(self.read_buffer[2..10]); if (length_read != 8) return error.EndOfStream; self.last_header.length = mem.readIntBig(u64, self.read_buffer[2..10]); } else if (check_len == 126) { const length_read = try self.reader.readAll(self.read_buffer[2..4]); if (length_read != 2) return error.EndOfStream; self.last_header.length = mem.readIntBig(u16, self.read_buffer[2..4]); } else { self.last_header.length = check_len; } if (masked) { // This may leave a gap in the read buffer, but we have to have this space anyways. // This is faster than keeping track of where we were writing into. const mask_read = try self.reader.readAll(self.read_buffer[10..14]); if (mask_read != 4) return error.EndOfStream; self.last_header.mask = self.read_buffer[10..14].*; } else { self.last_header.mask = null; } self.chunk_read = 0; self.state = .chunk; return Event{ .header = self.last_header, }; }, .chunk => { const left = math.min(self.last_header.length - self.chunk_read, self.read_buffer.len); const read = try self.reader.read(self.read_buffer[0..left]); if (self.last_header.mask) |mask| { for (self.read_buffer[0..read]) |*c, i| { c.* = c.* ^ mask[(i + self.chunk_read) % 4]; } } self.chunk_read += read; assert(self.chunk_read <= self.last_header.length); if (self.chunk_read == self.last_header.length) { self.state = .header; } return Event{ .chunk = .{ .data = self.read_buffer[0..read], .final = self.chunk_read == self.last_header.length, }, }; }, } } }; } const testing = std.testing; const io = std.io; fn testNextField(parser: anytype, expected: ?Event) !void { const actual = try parser.next(); try testing.expect(util.reworkedMetaEql(actual, expected)); } test "parses simple unmasked payload" { var read_buffer: [32]u8 = undefined; var request = [_]u8{ 0x81, 0x04, 'a', 'b', 'c', 'd' }; var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 4, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = "abcd", .final = true, }, }); } test "parses simple masked payload" { var read_buffer: [32]u8 = undefined; var request = [_]u8{ 0x81, 0x84, 0xa9, 0xb8, 0xc7, 0xd6, 'a' ^ 0xa9, 'b' ^ 0xb8, 'c' ^ 0xc7, 'd' ^ 0xd6 }; var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 4, .mask = [4]u8{ 0xa9, 0xb8, 0xc7, 0xd6 }, }, }); try testNextField(&parser, .{ .chunk = .{ .data = "abcd", .final = true, }, }); } test "parses longer simple masked payload" { var read_buffer: [32]u8 = undefined; var request = [_]u8{ 0x81, 0x90, 0xa9, 0xb8, 0xc7, 0xd6 } ++ [_]u8{ 'a' ^ 0xa9, 'b' ^ 0xb8, 'c' ^ 0xc7, 'd' ^ 0xd6 } ** (0x10 / 4); var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 0x10, .mask = [4]u8{ 0xa9, 0xb8, 0xc7, 0xd6 }, }, }); try testNextField(&parser, .{ .chunk = .{ .data = &[_]u8{ 'a', 'b', 'c', 'd' } ** (0x10 / 4), .final = true, }, }); } test "parses more than one simple unmasked payload" { var read_buffer: [32]u8 = undefined; var request = [_]u8{ 0x81, 0x04, 'a', 'b', 'c', 'd', 0x81, 0x04, 'a', 'b', 'c', 'd', 0x81, 0x04, 'a', 'b', 'c', 'd' }; var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 4, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = "abcd", .final = true, }, }); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 4, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = "abcd", .final = true, }, }); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 4, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = "abcd", .final = true, }, }); } test "parses simple unmasked medium payload" { var read_buffer: [512]u8 = undefined; var request = [_]u8{ 0x81, 0x07e, 0x01, 0x00 } ++ [_]u8{ 'a', 'b', 'c', 'd' } ** (0x100 / 4); var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 0x100, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = &[_]u8{ 'a', 'b', 'c', 'd' } ** (0x100 / 4), .final = true, }, }); } test "parses chunks simple unmasked medium payload" { var read_buffer: [128]u8 = undefined; var request = [_]u8{ 0x81, 0x07e, 0x01, 0x00 } ++ [_]u8{ 'a', 'b', 'c', 'd' } ** (0x100 / 4); var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 0x100, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = &[_]u8{ 'a', 'b', 'c', 'd' } ** (128 / 4), .final = false, }, }); try testNextField(&parser, .{ .chunk = .{ .data = &[_]u8{ 'a', 'b', 'c', 'd' } ** (128 / 4), .final = true, }, }); } test "parses simple unmasked large payload" { var read_buffer: [0x10000]u8 = undefined; var request = [_]u8{ 0x81, 0x07f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00 } ++ [_]u8{ 'a', 'b', 'c', 'd' } ** (0x10000 / 4); var reader = io.fixedBufferStream(&request).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .header = .{ .fin = true, .rsv1 = false, .rsv2 = false, .rsv3 = false, .opcode = .text, .length = 0x10000, .mask = null, }, }); try testNextField(&parser, .{ .chunk = .{ .data = &[_]u8{ 'a', 'b', 'c', 'd' } ** (0x10000 / 4), .final = true, }, }); }
src/parser/message.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; const Allocator = std.mem.Allocator; const Point = struct { x: i64, y: i64, }; const HeightMap = struct { const Self = @This(); allocator: Allocator, heights: []u8, width: i64, height: i64, pub fn load(allocator: Allocator, str: []const u8) !Self { var heights = std.ArrayList(u8).init(allocator); var iter = std.mem.split(u8, str, "\n"); var rowCount: i64 = 0; var colCount: i64 = 0; while (iter.next()) |row| { if (row.len != 0) { if (colCount == 0) { colCount = @intCast(i64, row.len); } const trimmed = std.mem.trimRight(u8, row, "\n"); for (trimmed) |c| { const value = c - '0'; try heights.append(value); } rowCount += 1; } } return Self{ .allocator = allocator, .heights = heights.toOwnedSlice(), .width = colCount, .height = rowCount }; } pub fn deinit(self: *Self) void { self.allocator.free(self.heights); } fn offset(self: Self, x: i64, y: i64) ?i64 { if (x < 0 or y < 0) return null; if (x >= self.width) return null; if (y >= self.height) return null; return (y * self.width) + x; } fn pointHeight(self: Self, p: Point) i64 { const idx = self.offset(p.x, p.y) orelse return 9; return self.heights[@intCast(usize, idx)]; } fn neighbors(self: Self, x: i64, y: i64) ![]Point { var pts = std.ArrayList(Point).init(self.allocator); try pts.append(Point{ .x = x, .y = y - 1 }); try pts.append(Point{ .x = x, .y = y + 1 }); try pts.append(Point{ .x = x - 1, .y = y }); try pts.append(Point{ .x = x + 1, .y = y }); return pts.toOwnedSlice(); } fn isLowPoint(self: Self, x: i64, y: i64) !bool { const h = self.pointHeight(Point{ .x = x, .y = y }); var neighCount: u8 = 0; var neighs = try self.neighbors(x, y); defer self.allocator.free(neighs); for (neighs) |n| { if (h < self.pointHeight(n)) neighCount += 1; } return neighCount == 4; } fn lowPoints(self: Self) ![]Point { var pts = std.ArrayList(Point).init(self.allocator); var row: i64 = 0; while (row < self.height) : (row += 1) { var col: i64 = 0; while (col < self.width) : (col += 1) { if (try self.isLowPoint(col, row)) { try pts.append(Point{ .x = col, .y = row }); } } } return pts.toOwnedSlice(); } pub fn riskLevelSum(self: Self) !i64 { var total: i64 = 0; var lows = try self.lowPoints(); defer self.allocator.free(lows); for (lows) |l| { total += self.pointHeight(l) + 1; } return total; } fn basinSize(self: Self, p: Point) !i64 { var seen = std.AutoHashMap(Point, bool).init(self.allocator); defer seen.deinit(); var todo = std.ArrayList(Point).init(self.allocator); defer todo.deinit(); try todo.append(p); while (todo.items.len != 0) { var curr = todo.pop(); try seen.put(curr, true); var neighs = try self.neighbors(curr.x, curr.y); defer self.allocator.free(neighs); for (neighs) |n| { if (!seen.contains(n) and self.pointHeight(n) != 9) { try todo.append(n); } } } return seen.count(); } pub fn largestBasins(self: Self) !i64 { var lows = try self.lowPoints(); defer self.allocator.free(lows); var sizes = std.ArrayList(i64).init(self.allocator); defer sizes.deinit(); for (lows) |l| { try sizes.append(try self.basinSize(l)); } std.sort.sort(i64, sizes.items, {}, comptime std.sort.desc(i64)); return sizes.items[0] * sizes.items[1] * sizes.items[2]; } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const str = @embedFile("../input.txt"); var h = try HeightMap.load(allocator, str); defer h.deinit(); const stdout = std.io.getStdOut().writer(); const part1 = try h.riskLevelSum(); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = try h.largestBasins(); try stdout.print("Part 2: {d}\n", .{part2}); } test "part1 test" { const str = @embedFile("../test.txt"); var h = try HeightMap.load(test_allocator, str); defer h.deinit(); const score = try h.riskLevelSum(); std.debug.print("\nScore={d}\n", .{score}); try expect(15 == score); } test "part2 test" { const str = @embedFile("../test.txt"); var h = try HeightMap.load(test_allocator, str); defer h.deinit(); const score = try h.largestBasins(); std.debug.print("\nScore={d}\n", .{score}); try expect(1134 == score); }
day09/src/main.zig
usingnamespace @import("core.zig"); const panic = std.debug.panic; const glfw = @import("glfw"); const MouseButtonCount: usize = @enumToInt(glfw.mouse_button.last); const KeyboardButtonCount: usize = @enumToInt(glfw.Key.last()); pub const TextInput = std.ArrayList(u16); const ButtonInput = struct { current_state: bool = false, prev_state: bool = false, }; fn key_callback(window: glfw.Window, key: glfw.Key, scancode: isize, action: glfw.Action, mods: glfw.Mods) void { _ = scancode; _ = mods; var internal_result = window.getUserPointer(*InputData); if (internal_result) |internal| { if (key != glfw.Key.unknown) { var key_int = @intCast(usize, @enumToInt(key)); if (action == glfw.Action.press) { internal.keyboard_buttons[key_int].current_state = true; } else if (action == glfw.Action.release) { internal.keyboard_buttons[key_int].current_state = false; } } } } fn mouse_button_callback(window: glfw.Window, button: glfw.mouse_button.MouseButton, action: glfw.Action, mods: glfw.Mods) void { _ = mods; var internal_result = window.getUserPointer(*InputData); if (internal_result) |internal| { var button_int = @intCast(usize, @enumToInt(button)); if (action == glfw.Action.press) { internal.mouse_buttons[button_int].current_state = true; } else if (action == glfw.Action.release) { internal.mouse_buttons[button_int].current_state = false; } } } fn mouse_move_button(window: glfw.Window, xpos: f64, ypos: f64) void { var internal_result = window.getUserPointer(*InputData); if (internal_result) |internal| { internal.mouse_pos = [2]f32{ @floatCast(f32, xpos), @floatCast(f32, ypos) }; } } fn mouse_entered(window: glfw.Window, entered: bool) void { var internal_result = window.getUserPointer(*InputData); if (internal_result) |internal| { if (!entered) { internal.mouse_pos = null; } } } fn text_entered(window: glfw.Window, character_u21: u21) void { var internal_result = window.getUserPointer(*InputData); if (internal_result) |internal| { var character = @intCast(u16, character_u21); internal.text_input.append(character) catch { panic("Failed to append text_input!", .{}); }; } } const InputData = struct { mouse_buttons: [MouseButtonCount]ButtonInput = [_]ButtonInput{.{}} ** MouseButtonCount, keyboard_buttons: [KeyboardButtonCount]ButtonInput = [_]ButtonInput{.{}} ** KeyboardButtonCount, mouse_pos: ?[2]f32 = null, text_input: TextInput, }; pub const Input = struct { const Self = @This(); allocator: *Allocator, window: glfw.Window, internal: *InputData, pub fn init(window: glfw.Window, allocator: *Allocator) !Self { var internal = try allocator.create(InputData); internal.text_input = TextInput.init(allocator); window.setUserPointer(*InputData, internal); window.setKeyCallback(key_callback); window.setMouseButtonCallback(mouse_button_callback); window.setCursorPosCallback(mouse_move_button); window.setCursorEnterCallback(mouse_entered); window.setCharCallback(text_entered); return Self{ .allocator = allocator, .window = window, .internal = internal, }; } pub fn deinit(self: *Self) void { self.window.setKeyCallback(null); self.window.setMouseButtonCallback(null); self.window.setCursorPosCallback(null); self.window.setCursorEnterCallback(null); //Clear Window User Pointer var internal = self.window.getInternal(); internal.user_pointer = null; self.internal.text_input.deinit(); self.allocator.destroy(self.internal); } pub fn update(self: *Self) void { for (self.internal.mouse_buttons) |*button| { button.prev_state = button.current_state; } for (self.internal.keyboard_buttons) |*button| { button.prev_state = button.current_state; } } pub fn getMouseDown(self: *Self, mouse_button: glfw.mouse_button.MouseButton) bool { var button_int = @intCast(usize, @enumToInt(mouse_button)); return self.internal.mouse_buttons[button_int].current_state == true; } pub fn getMousePressed(self: *Self, mouse_button: glfw.mouse_button.MouseButton) bool { var button_int = @intCast(usize, @enumToInt(mouse_button)); var button = self.internal.mouse_buttons[button_int]; return button.current_state == true and button.prev_state == false; } pub fn getMousePos(self: *Self) ?[2]f32 { return self.internal.mouse_pos; } pub fn getKeyDown(self: *Self, key: glfw.Key) bool { var key_int = @intCast(usize, @enumToInt(key)); return self.internal.keyboard_buttons[key_int].current_state == true; } pub fn getKeyPressed(self: *Self, key: glfw.Key) bool { var key_int = @intCast(usize, @enumToInt(key)); var button = self.internal.keyboard_buttons[key_int]; return button.current_state == true and button.prev_state == false; } pub fn getAndClearTextInput(self: *Self) TextInput { var temp = self.internal.text_input; self.internal.text_input = TextInput.init(self.allocator); return temp; } };
src/input.zig
const std = @import("std"); const print = std.debug.print; const nanoid = @import("nanoid.zig"); const app_name = "nanoid"; const app_version = "0.1.0"; fn version() void { print("{s} version {s}\n", .{ app_name, app_version }); } fn usage() void { print("Usage:\n", .{}); print(" {s} \tGenerate a nanoid with the default size (21) and default alphabet\n", .{ app_name }); print(" {s} -s | --size <size> \tGenerate a nanoid with a custom size and default alphabet\n", .{ app_name }); print(" {s} -a | --alphabet <alphabet>\tGenerate a nanoid with a custom alphabet (requires the size)\n", .{ app_name }); print(" {s} -h | --help \tDisplay this help\n", .{ app_name }); print(" {s} -v | --version \tPrint the version\n", .{ app_name }); print("Examples:\n", .{}); print(" {s}\n", .{ app_name }); print(" {s} -s 42\n", .{ app_name }); print(" {s} -s 42 -a 0123456789\n", .{ app_name }); } pub fn main() !void { var id: [21]u8 = undefined; // ========= // CLI const args = try std.process.argsAlloc(std.heap.page_allocator); defer std.process.argsFree(std.heap.page_allocator, args); //var option_index: usize = 1; var size: u32 = 0; var alphabet: []u8 = ""; if (args.len > 1) { for (args) |arg, i| { // Executable name if (i == 0) { continue; } if (std.mem.eql(u8, "--help", arg) or std.mem.eql(u8, "-h", arg)) { usage(); return; } if (std.mem.eql(u8, "--version", arg) or std.mem.eql(u8, "-v", arg)) { version(); return; } if (std.mem.eql(u8, "--size", arg) or std.mem.eql(u8, "-s", arg)) { if (i+1 < args.len) { var input = std.fmt.parseInt(i64, args[i+1], 10) catch |err| { print("error parsing size {s}: {s}\n", .{args[i+1], err}); std.process.exit(1); }; size = @intCast(u32, input); if (size == 0) { print("error: size should be greater than 0\n", .{}); std.process.exit(1); } } else { print("error: size is missing\n", .{}); usage(); std.process.exit(1); } } if (std.mem.eql(u8, "--alphabet", arg) or std.mem.eql(u8, "-a", arg)) { if (i+1 < args.len) { alphabet = args[i+1]; } else { print("error: alphabet is missing\n", .{}); usage(); std.process.exit(1); } } } var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator(); // Generate an id with a custom size and alphabet if (size > 0 and alphabet.len > 0) { var id_with_size_alphabet = nanoid.customAlphabet(allocator, size, alphabet) catch |err| { std.debug.print("error creating a nanoid with len {d} and alphabet {s}: {s}\n", .{size, alphabet, err}); std.process.exit(1); }; std.debug.print("{s}\n", .{id_with_size_alphabet}); return; } // Generate an id with a custom size and default alphabet if (size > 0) { var id_with_size = nanoid.customLen(allocator, size) catch |err| { std.debug.print("error creating a nanoid with len {d} {s}\n", .{size, err}); std.process.exit(1); }; std.debug.print("{s}\n", .{id_with_size}); return; } // Custom alphabet was provided without a custom size if (alphabet.len > 0) { std.debug.print("error: size option is missing\n", .{}); usage(); std.process.exit(1); } print("error: unexpected arguments {s}\n", .{args}); usage(); std.process.exit(1); } // No argument => generate a nanoid with default len 21 and default alphabet id = nanoid.default() catch |err| { std.debug.print("error creating a nanoid {s}\n", .{err}); std.process.exit(1); }; std.debug.print("{s}\n", .{id}); }
main.zig
const std = @import("std"); const os = @import("root").os; /// SingleListener is a helper that allows one thread /// to listen for events triggered by many producers pub const SingleListener = struct { /// Value that will be used for blocking const BLOCK_VAL: usize = @divFloor(std.math.maxInt(usize), 2); /// Index of last event that was aknowledged by the consumer last_ack: usize, /// Index of last event that was triggered last_triggered: usize, /// Last event captured after the queue was cancelled last_captured: usize, /// Get the number of not aknowledged events pub fn diff(self: *const @This()) usize { const triggered = @atomicLoad(usize, &self.last_triggered, .Acquire); if (triggered >= BLOCK_VAL) { return self.last_captured - self.last_ack; } return triggered - self.last_ack; } /// Aknowledge one event if present pub fn try_ack(self: *@This()) bool { if (self.diff() > 0) { self.last_ack += 1; return true; } return false; } /// Wait for events without actually acknowledging them pub fn wait(self: *const @This()) void { while (self.diff() == 0) { // TODO: Rewrite with sleep support os.thread.scheduler.yield(); } } /// Aknowledge one event or wait for one pub fn ack(self: *@This()) void { self.wait(); last_ack += 1; } /// Trigger one event pub fn trigger(self: *@This()) bool { const ticket = @atomicRmw(usize, &self.last_triggered, .Add, 1, .AcqRel); return ticket < BLOCK_VAL; } /// Block new events pub fn block(self: *@This()) void { self.last_captured = @atomicRmw(usize, &self.last_triggered, .Xchg, BLOCK_VAL, .AcqRel); } /// Create SingleListener object pub fn init() @This() { return .{ .last_ack = 0, .last_triggered = 0, .last_captured = 0, }; } };
src/thread/single_listener.zig
const std = @import("std"); const platform = @import("../platform.zig"); const uefiConsole = @import("console.zig"); const L = std.unicode.utf8ToUtf16LeStringLiteral; const uefi = std.os.uefi; const NO_PROTECT = "Protected mode not enabled, UEFI specification violation!\r\n"; const PAGING_ENABLED = "Paging is enabled\r\n"; const PAE_ENABLED = "PAE is enabled\r\n"; const PSE_ENABLED = "PSE is enabled\r\n"; const WARN_TSS_SET = "WARNING: task switch flag is set\r\n"; const WARN_EM_SET = "WARNING: x87 emulation is enabled\r\n"; const LONG_MODE_ENABLED = "Long mode is enabled\r\n"; const WARN_LONG_MODE_UNSUPPORTED = "Long mode is not enabled\r\n"; const WARN_NO_CPUID = "No CPUID instruction was detected, prepare for unforeseen consequences.\r\n"; pub fn dumpAndAssertPlatformState() void { if (!platform.isProtectedMode()) { uefiConsole.puts(NO_PROTECT); platform.hang(); } if (platform.isPagingEnabled()) { uefiConsole.puts(PAGING_ENABLED); } if (platform.isPAEEnabled()) { uefiConsole.puts(PAE_ENABLED); } if (platform.isPSEEnabled()) { uefiConsole.puts(PSE_ENABLED); } if (platform.isTSSSet()) { uefiConsole.puts(WARN_TSS_SET); } if (platform.isX87EmulationEnabled()) { uefiConsole.puts(WARN_EM_SET); } // FIXME(Ryan): find out a way to detect CPUID. //if (!platform.hasCPUID()) { // _ = conOut.outputString(WARN_NO_CPUID); //} if (platform.isLongModeEnabled()) { uefiConsole.puts(LONG_MODE_ENABLED); } else { uefiConsole.puts(WARN_LONG_MODE_UNSUPPORTED); } // Handle Loaded Image Protocol and print driverpoint. var loadedImage: *uefi.protocols.LoadedImageProtocol = undefined; var retCode = uefi.system_table.boot_services.?.handleProtocol(uefi.handle, &uefi.protocols.LoadedImageProtocol.guid, @ptrCast(*?*c_void, &loadedImage)); if (retCode != uefi.Status.Success) { platform.hang(); } var buf: [4096]u8 = undefined; uefiConsole.printf(buf[0..], "Loaded image: base={x}\r\n", .{@ptrToInt(loadedImage.image_base)}); }
src/kernel/uefi/systeminfo.zig
const std = @import("std"); const builtin = @import("builtin"); fn isProgramAvailable(builder: *std.build.Builder, program_name: []const u8) !bool { const env_map = try std.process.getEnvMap(builder.allocator); const path_var = env_map.get("PATH") orelse return false; var path_iter = std.mem.tokenize(u8, path_var, if (builtin.os.tag == .windows) ";" else ":"); while (path_iter.next()) |path| { var dir = try std.fs.cwd().openDir(path, .{ .iterate = true }); defer dir.close(); var dir_iterator = dir.iterate(); while (try dir_iterator.next()) |dir_item| { if (std.mem.eql(u8, dir_item.name, program_name)) return true; } } return false; } fn isLibreSslConfigured(library_location: []const u8) !bool { var libre_ssl_dir = try std.fs.cwd().openDir(library_location, .{}); _ = libre_ssl_dir.openFile("configure", .{ .read = false, .write = false }) catch return false; return true; } fn buildLibreSsl(builder: *std.build.Builder, input_step: *std.build.LibExeObjStep, library_location: []const u8) !void { var libre_ssl_dir = try std.fs.cwd().openDir(library_location, .{}); var libre_ssl_absolute_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const libre_ssl_absolute_dir = try libre_ssl_dir.realpath(".", &libre_ssl_absolute_dir_buf); const autogen_step = std.build.RunStep.create(builder, "autogen LibreSSL"); autogen_step.cwd = library_location; autogen_step.addArg("./autogen.sh"); const configure_step = std.build.RunStep.create(builder, "configure LibreSSL"); configure_step.cwd = library_location; configure_step.addArg("./configure"); libre_ssl_dir.makeDir("build") catch |e| switch (e) { std.os.MakeDirError.PathAlreadyExists => {}, else => return e, }; var build_dir_path = try std.fs.path.join(builder.allocator, &[_][]const u8{ library_location, "build" }); var build_results_dir_path = try std.fs.path.join(builder.allocator, &[_][]const u8{ build_dir_path, "out" }); if (!try isLibreSslConfigured(library_location)) { configure_step.step.dependOn(&autogen_step.step); } const ninja_available = isProgramAvailable(builder, "ninja") catch false; const make_step = std.build.RunStep.create(builder, "make LibreSSL"); make_step.cwd = build_dir_path; make_step.setEnvironmentVariable("DESTDIR", "out"); if (ninja_available) { make_step.addArgs(&[_][]const u8{ "ninja", "install" }); } else { make_step.addArgs(&[_][]const u8{ "make", "install" }); } const cmake_available = isProgramAvailable(builder, "cmake") catch false; if (cmake_available) { const cmake_step = std.build.RunStep.create(builder, "configure LibreSSL"); cmake_step.cwd = build_dir_path; if (ninja_available) { cmake_step.addArgs(&[_][]const u8{ "cmake", "-GNinja", libre_ssl_absolute_dir }); } else { cmake_step.addArgs(&[_][]const u8{ "cmake", libre_ssl_absolute_dir }); } cmake_step.step.dependOn(&configure_step.step); make_step.step.dependOn(&cmake_step.step); } // check if we even need to build anything _ = std.fs.cwd().openDir(build_results_dir_path, .{}) catch { // ensure that we build if there was no dir found // TODO(haze): stricten to "dir not found" input_step.step.dependOn(&make_step.step); }; const libre_ssl_include_dir_path = try std.fs.path.join(builder.allocator, &[_][]const u8{ build_results_dir_path, "usr", "local", "include" }); input_step.addIncludeDir(libre_ssl_include_dir_path); const libre_ssl_lib_dir_path = try std.fs.path.join(builder.allocator, &[_][]const u8{ build_results_dir_path, "usr", "local", "lib" }); input_step.addLibPath(libre_ssl_lib_dir_path); input_step.linkSystemLibraryName("tls"); input_step.linkSystemLibraryName("ssl"); input_step.linkSystemLibraryName("crypto"); } const required_programs = [_][]const u8{ "automake", "autoconf", "git", "libtool", "perl", "make", }; fn addIncludeDirsFromPkgConfigForLibrary(builder: *std.build.Builder, step: *std.build.LibExeObjStep, name: []const u8) !void { var out_code: u8 = 0; const stdout = try builder.execAllowFail(&[_][]const u8{ "pkg-config", "--cflags", name }, &out_code, .Ignore); var c_flag_iter = std.mem.tokenize(u8, stdout, " "); while (c_flag_iter.next()) |c_flag| { if (std.mem.startsWith(u8, c_flag, "-I")) { var path = std.mem.trimRight(u8, c_flag[2..], "\t\r\n "); // std.debug.print("Adding '{s}' to the include dirs", .{path}); step.addIncludeDir(path); } } } pub fn useLibreSslForStep(builder: *std.build.Builder, step: *std.build.LibExeObjStep, libressl_location: []const u8) void { const use_system_libressl = builder.option(bool, "use-system-libressl", "Link and build from the system installed copy of LibreSSL instead of building it from source") orelse false; if (use_system_libressl) { addIncludeDirsFromPkgConfigForLibrary(builder, step, "libtls") catch |why| { std.debug.print("Failed to get include directory for libtls: {}", .{why}); return; }; step.linkSystemLibrary("tls"); step.linkSystemLibrary("ssl"); step.linkSystemLibrary("crypto"); } else { inline for (required_programs) |program| { const available = isProgramAvailable(builder, program) catch false; if (!available) { std.debug.print("{s} is required to build LibreSSL\n", .{program}); return; } } buildLibreSsl(builder, step, libressl_location) catch |e| { std.debug.print("Failed to configure libreSSL build steps: {}\n", .{e}); return; }; } } pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); var lib = b.addStaticLibrary("zig-libressl", "src/main.zig"); lib.linkLibC(); lib.setBuildMode(mode); lib.install(); var main_tests = b.addTest("src/main.zig"); main_tests.setBuildMode(mode); useLibreSslForStep(b, main_tests, "libressl"); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); }
build.zig
const std = @import("std"); const zap = @import("zap"); const hyperia = @import("hyperia.zig"); const os = std.os; const mem = std.mem; const math = std.math; const builtin = std.builtin; const testing = std.testing; const assert = std.debug.assert; pub const cache_line_length = switch (builtin.cpu.arch) { .x86_64, .aarch64, .powerpc64 => 128, .arm, .mips, .mips64, .riscv64 => 32, .s390x => 256, else => 64, }; pub const AsyncAutoResetEvent = struct { const Self = @This(); const Waiter = struct { runnable: zap.Pool.Runnable = .{ .runFn = run }, frame: anyframe, next: ?*Waiter = null, refs: u32 = 2, pub fn run(runnable: *zap.Pool.Runnable) void { const self = @fieldParentPtr(Waiter, "runnable", runnable); resume self.frame; } }; const setter_increment: u64 = 1; const waiter_increment: u64 = @as(u64, 1) << 32; state: u64 = 0, waiters: ?*Waiter = null, new_waiters: ?*Waiter = null, fn getSetterCount(state: u64) callconv(.Inline) u32 { return @truncate(u32, state); } fn getWaiterCount(state: u64) callconv(.Inline) u32 { return @intCast(u32, state >> 32); } pub fn wait(self: *Self) void { var state = @atomicLoad(u64, &self.state, .Monotonic); if (getSetterCount(state) > getWaiterCount(state)) { if (@cmpxchgStrong( u64, &self.state, state, state - setter_increment, .Acquire, .Monotonic, ) == null) return; } self.park(); } /// Cancels a waiter so that the waiter may be manually resumed. /// Returns true if the waiter may be manually resumed, and false /// otherwise because a setter appears to have already resumed /// the waiter. pub fn cancel(self: *Self) bool { var state = @atomicLoad(u64, &self.state, .Monotonic); while (true) { if (getSetterCount(state) >= getWaiterCount(state)) return false; state = @cmpxchgWeak( u64, &self.state, state, state - waiter_increment, .AcqRel, .Acquire, ) orelse return true; } } pub fn set(self: *Self) zap.Pool.Batch { var state = @atomicLoad(u64, &self.state, .Monotonic); while (true) { if (getSetterCount(state) > getWaiterCount(state)) return .{}; state = @cmpxchgWeak( u64, &self.state, state, state + setter_increment, .AcqRel, .Acquire, ) orelse break; } if (getSetterCount(state) == 0 and getWaiterCount(state) > 0) { return self.unpark(state + setter_increment); } return .{}; } fn park(self: *Self) void { var waiter: Waiter = .{ .frame = @frame() }; suspend { var head = @atomicLoad(?*Waiter, &self.new_waiters, .Monotonic); while (true) { waiter.next = head; head = @cmpxchgWeak( ?*Waiter, &self.new_waiters, head, &waiter, .Release, .Monotonic, ) orelse break; } var batch: zap.Pool.Batch = .{}; defer hyperia.pool.schedule(.{}, batch); var state = @atomicRmw(u64, &self.state, .Add, waiter_increment, .AcqRel); if (getSetterCount(state) > 0 and getWaiterCount(state) == 0) { batch.push(self.unpark(state + waiter_increment)); } if (@atomicRmw(u32, &waiter.refs, .Sub, 1, .Acquire) == 1) { batch.push(&waiter.runnable); } } } fn unpark(self: *Self, state: u64) zap.Pool.Batch { var batch: zap.Pool.Batch = .{}; var waiters_to_resume: ?*Waiter = null; var waiters_to_resume_tail: *?*Waiter = &waiters_to_resume; var num_waiters_to_resume: u64 = math.min(getWaiterCount(state), getSetterCount(state)); assert(num_waiters_to_resume > 0); while (num_waiters_to_resume != 0) { var i: usize = 0; while (i < num_waiters_to_resume) : (i += 1) { if (self.waiters == null) { var new_waiters = @atomicRmw(?*Waiter, &self.new_waiters, .Xchg, null, .Acquire); assert(new_waiters != null); while (new_waiters) |new_waiter| { const next = new_waiter.next; new_waiter.next = self.waiters; self.waiters = new_waiter; new_waiters = next; } } const waiter_to_resume = self.waiters orelse unreachable; self.waiters = waiter_to_resume.next; waiter_to_resume.next = null; waiters_to_resume_tail.* = waiter_to_resume; waiters_to_resume_tail = &waiter_to_resume.next; } const delta = num_waiters_to_resume | (num_waiters_to_resume << 32); const new_state = @atomicRmw(u64, &self.state, .Sub, delta, .AcqRel) - delta; num_waiters_to_resume = math.min(getWaiterCount(new_state), getSetterCount(new_state)); } assert(waiters_to_resume != null); while (waiters_to_resume) |waiter| { const next = waiter.next; if (@atomicRmw(u32, &waiter.refs, .Sub, 1, .Release) == 1) { batch.push(&waiter.runnable); } waiters_to_resume = next; } return batch; } }; pub const Semaphore = struct { const Self = @This(); pub const Waiter = struct { runnable: zap.Pool.Runnable = .{ .runFn = run }, frame: anyframe, parent: *Self, prev: ?*Waiter = null, next: ?*Waiter = null, cancelled: bool = false, }; tokens: usize = 0, lock: hyperia.sync.SpinLock = .{}, waiters: ?*Waiter = null, pub fn init(tokens: usize) Self { return .{ .tokens = tokens }; } pub fn signal(self: *Self) void { var tokens = @atomicLoad(usize, &self.tokens, .Monotonic); while (true) { while (tokens == 0) { if (self.signalSlow()) return; tokens = @atomicLoad(usize, &self.tokens, .Acquire); } tokens = @cmpxchgWeak( usize, &self.tokens, tokens, tokens + 1, .Release, .Acquire, ) orelse return; } } fn signalSlow(self: *Self) bool { var waiter: *Waiter = wake: { const held = self.lock.acquire(); defer held.release(); const tokens = @atomicLoad(usize, &self.tokens, .Acquire); if (tokens != 0) return false; const waiter = self.waiters orelse { assert(@cmpxchgStrong( usize, &self.tokens, tokens, tokens + 1, .Monotonic, .Monotonic, ) == null); return true; }; if (waiter.next) |next| { next.prev = null; } self.waiters = waiter.next; break :wake waiter; }; hyperia.pool.schedule(.{}, &waiter.runnable); return true; } pub fn wait(self: *Self, waiter: *Waiter) void { var tokens = @atomicLoad(usize, &self.tokens, .Acquire); while (true) { while (tokens == 0) { suspend { waiter.frame = @frame(); if (!self.waitSlow(waiter)) { hyperia.pool.schedule(.{}, &waiter.runnable); } } tokens = @atomicLoad(usize, &self.tokens, .Acquire); } tokens = @cmpxchgWeak( usize, &self.tokens, tokens, tokens - 1, .Release, .Acquire, ) orelse return; } } fn waitSlow(self: *Self, waiter: *Waiter) bool { const held = self.lock.acquire(); defer held.release(); const tokens = @atomicLoad(usize, &self.tokens, .Acquire); if (tokens != 0) return false; if (self.waiters) |head| { head.prev = waiter; } waiter.next = self.waiters; self.waiters = waiter; return true; } }; pub const Event = struct { const Self = @This(); pub const State = enum { unset, set, }; pub const Waiter = struct { runnable: zap.Pool.Runnable = .{ .runFn = run }, frame: anyframe, parent: *Event, prev: ?*Waiter = null, next: ?*Waiter = null, cancelled: bool = false, fn run(runnable: *zap.Pool.Runnable) void { const self = @fieldParentPtr(Waiter, "runnable", runnable); resume self.frame; } pub fn cancel(self: *Waiter) ?*zap.Pool.Runnable { const runnable = collect: { const held = self.parent.lock.acquire(); defer held.release(); if (self.cancelled) return null; self.cancelled = true; if (self.prev == null and self.next == null) return null; if (self.parent.waiters == self) return null; if (self.prev) |prev| { prev.next = self.next; self.prev = null; } else { self.parent.waiters = self.next; } if (self.next) |next| { next.prev = self.prev; self.next = null; } break :collect &self.runnable; }; return runnable; } /// Waits until the parenting event is set. It returns true /// if this waiter was not cancelled, and false otherwise. pub fn wait(self: *Waiter) bool { const held = self.parent.lock.acquire(); if (self.cancelled) { held.release(); return false; } if (self.parent.state == .set) { self.parent.state = .unset; held.release(); return true; } suspend { self.frame = @frame(); if (self.parent.waiters) |waiter| { waiter.prev = self; } self.next = self.parent.waiters; self.parent.waiters = self; held.release(); } assert(self.prev == null); assert(self.next == null); return !self.cancelled; } }; lock: hyperia.sync.SpinLock = .{}, state: State = .unset, waiters: ?*Waiter = null, pub fn set(self: *Self) ?*zap.Pool.Runnable { const runnable: ?*zap.Pool.Runnable = collect: { const held = self.lock.acquire(); defer held.release(); if (self.state == .set) { break :collect null; } if (self.waiters) |waiter| { self.waiters = waiter.next; waiter.next = null; waiter.prev = null; break :collect &waiter.runnable; } else { self.state = .set; break :collect null; } }; return runnable; } pub fn createWaiter(self: *Self) Waiter { return Waiter{ .parent = self, .frame = undefined }; } }; pub fn AsyncQueue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); queue: Queue(T, capacity), closed: bool = false, producer_event: Event = .{}, consumer_event: Event = .{}, pub fn init(allocator: *mem.Allocator) !Self { return Self{ .queue = try Queue(T, capacity).init(allocator) }; } pub fn deinit(self: *Self, allocator: *mem.Allocator) void { self.queue.deinit(allocator); } pub fn tryPush(self: *Self, item: T) bool { return self.queue.tryPush(item); } pub fn tryPop(self: *Self) ?T { return self.queue.tryPop(); } pub fn count(self: *Self) usize { return self.queue.count(); } pub fn close(self: *Self) void { @atomicStore(bool, &self.closed, true, .Monotonic); while (true) { var batch: zap.Pool.Batch = .{}; batch.push(self.producer_event.set()); batch.push(self.consumer_event.set()); if (batch.isEmpty()) break; hyperia.pool.schedule(.{}, batch); } } pub const Pusher = struct { parent: *Self, waiter: Event.Waiter, pub fn cancel(self: *Pusher) ?*zap.Pool.Runnable { return self.waiter.cancel(); } pub fn push(self: *Pusher, item: T) bool { while (!@atomicLoad(bool, &self.parent.closed, .Monotonic)) { if (self.parent.tryPush(item)) { hyperia.pool.schedule(.{}, self.parent.consumer_event.set()); return true; } if (!self.waiter.wait()) return false; } return false; } }; pub const Popper = struct { parent: *Self, waiter: Event.Waiter, pub fn cancel(self: *Popper) ?*zap.Pool.Runnable { return self.waiter.cancel(); } pub fn pop(self: *Popper) ?T { while (!@atomicLoad(bool, &self.parent.closed, .Monotonic)) { if (self.parent.tryPop()) |item| { hyperia.pool.schedule(.{}, self.parent.producer_event.set()); return item; } if (!self.waiter.wait()) return null; } return null; } }; pub fn pusher(self: *Self) Pusher { return Pusher{ .parent = self, .waiter = self.producer_event.createWaiter() }; } pub fn popper(self: *Self) Popper { return Popper{ .parent = self, .waiter = self.consumer_event.createWaiter() }; } }; } pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); pub const Entry = struct { sequence: usize align(cache_line_length), item: T, }; entries: [*]Entry align(cache_line_length), enqueue_pos: usize align(cache_line_length), dequeue_pos: usize align(cache_line_length), pub fn init(allocator: *mem.Allocator) !Self { const entries = try allocator.create([capacity]Entry); for (entries) |*entry, i| entry.sequence = i; return Self{ .entries = entries, .enqueue_pos = 0, .dequeue_pos = 0, }; } pub fn deinit(self: *Self, allocator: *mem.Allocator) void { allocator.destroy(@ptrCast(*const [capacity]Entry, self.entries)); } pub fn count(self: *Self) usize { const tail = @atomicLoad(usize, &self.dequeue_pos, .Monotonic); const head = @atomicLoad(usize, &self.enqueue_pos, .Monotonic); return (tail -% head) % (capacity - 1); } pub fn tryPush(self: *Self, item: T) bool { var entry: *Entry = undefined; var pos = @atomicLoad(usize, &self.enqueue_pos, .Monotonic); while (true) : (os.sched_yield() catch {}) { entry = &self.entries[pos & (capacity - 1)]; const seq = @atomicLoad(usize, &entry.sequence, .Acquire); const diff = @intCast(isize, seq) -% @intCast(isize, pos); if (diff == 0) { pos = @cmpxchgWeak(usize, &self.enqueue_pos, pos, pos +% 1, .Monotonic, .Monotonic) orelse { break; }; } else if (diff < 0) { return false; } else { pos = @atomicLoad(usize, &self.enqueue_pos, .Monotonic); } } entry.item = item; @atomicStore(usize, &entry.sequence, pos +% 1, .Release); return true; } pub fn tryPop(self: *Self) ?T { var entry: *Entry = undefined; var pos = @atomicLoad(usize, &self.dequeue_pos, .Monotonic); while (true) : (os.sched_yield() catch {}) { entry = &self.entries[pos & (capacity - 1)]; const seq = @atomicLoad(usize, &entry.sequence, .Acquire); const diff = @intCast(isize, seq) -% @intCast(isize, pos +% 1); if (diff == 0) { pos = @cmpxchgWeak(usize, &self.dequeue_pos, pos, pos +% 1, .Monotonic, .Monotonic) orelse { break; }; } else if (diff < 0) { return null; } else { pos = @atomicLoad(usize, &self.dequeue_pos, .Monotonic); } } const item = entry.item; @atomicStore(usize, &entry.sequence, pos +% (capacity - 1) +% 1, .Release); return item; } }; } test { testing.refAllDecls(@This()); testing.refAllDecls(Event); testing.refAllDecls(Semaphore); testing.refAllDecls(Queue(u64, 128)); testing.refAllDecls(AsyncQueue(u64, 128)); } test "mpmc/auto_reset_event: set and wait" { hyperia.init(); defer hyperia.deinit(); var event: AsyncAutoResetEvent = .{}; testing.expect(event.set().isEmpty()); testing.expect(event.set().isEmpty()); testing.expect(event.set().isEmpty()); testing.expect(AsyncAutoResetEvent.getSetterCount(event.state) == 1); nosuspend event.wait(); testing.expect(AsyncAutoResetEvent.getSetterCount(event.state) == 0); var a = async event.wait(); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 1); var b = async event.wait(); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 2); var c = async event.wait(); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 3); event.set().pop().?.run(); testing.expect(AsyncAutoResetEvent.getSetterCount(event.state) == 0); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 2); nosuspend await a; event.set().pop().?.run(); testing.expect(AsyncAutoResetEvent.getSetterCount(event.state) == 0); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 1); nosuspend await b; event.set().pop().?.run(); testing.expect(AsyncAutoResetEvent.getSetterCount(event.state) == 0); testing.expect(AsyncAutoResetEvent.getWaiterCount(event.state) == 0); nosuspend await c; } test "mpmc/queue: push and pop 60,000 u64s with 4 producers and 4 consumers" { const NUM_ITEMS = 60_000; const NUM_PRODUCERS = 4; const NUM_CONSUMERS = 4; const TestQueue = Queue(u64, 2048); const Context = struct { queue: *TestQueue, fn runProducer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_PRODUCERS) : (i += 1) { while (true) { if (self.queue.tryPush(@intCast(u64, i))) { break; } } } } fn runConsumer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_CONSUMERS) : (i += 1) { while (true) { if (self.queue.tryPop() != null) { break; } } } } }; const allocator = testing.allocator; var queue = try TestQueue.init(allocator); defer queue.deinit(allocator); var producers: [NUM_PRODUCERS]*std.Thread = undefined; defer for (producers) |producer| producer.wait(); var consumers: [NUM_CONSUMERS]*std.Thread = undefined; defer for (consumers) |consumer| consumer.wait(); for (consumers) |*consumer| consumer.* = try std.Thread.spawn(Context.runConsumer, Context{ .queue = &queue }); for (producers) |*producer| producer.* = try std.Thread.spawn(Context.runProducer, Context{ .queue = &queue }); }
mpmc.zig
const std = @import("std"); const testing = std.testing; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const mustache = @import("../mustache.zig"); const TemplateOptions = mustache.options.TemplateOptions; const ref_counter = @import("ref_counter.zig"); const parsing = @import("parsing.zig"); const PartType = parsing.PartType; const Delimiters = parsing.Delimiters; pub fn TextPart(comptime options: TemplateOptions) type { const RefCountedSlice = ref_counter.RefCountedSlice(options); const TrimmingIndex = parsing.TrimmingIndex(options); return struct { const Self = @This(); part_type: PartType, is_stand_alone: bool, /// Slice containing the content for this TextPart /// When parsing from streams, RefCounter holds a reference to the underlying read buffer, otherwise the RefCounter is a no-op. content: RefCountedSlice, /// Slice containing the indentation for this TextPart /// When parsing from streams, RefCounter holds a reference to the underlying read buffer, otherwise the RefCounter is a no-op. indentation: ?RefCountedSlice = null, /// The line and column on the template source /// Used mostly for error messages source: struct { lin: u32, col: u32, }, /// Trimming rules trimming: struct { left: TrimmingIndex = .PreserveWhitespaces, right: TrimmingIndex = .PreserveWhitespaces, } = .{}, pub inline fn unRef(self: *Self, allocator: Allocator) void { self.content.ref_counter.unRef(allocator); if (self.indentation) |*indentation| { indentation.ref_counter.unRef(allocator); } } /// Determines if this TextPart is empty pub fn isEmpty(self: *const Self) bool { return self.content.slice.len == 0; } /// Processes the trimming rules for the right side of the slice pub fn trimRight(self: *Self) ?RefCountedSlice { return switch (self.trimming.right) { .PreserveWhitespaces, .Trimmed => null, .AllowTrimming => |right_trimming| indentation: { const content = self.content.slice; if (right_trimming.index == 0) { self.content.slice = &.{}; } else if (right_trimming.index < content.len) { self.content.slice = content[0..right_trimming.index]; } self.trimming.right = .Trimmed; if (right_trimming.index + 1 >= content.len) { break :indentation null; } else { break :indentation RefCountedSlice{ .slice = content[right_trimming.index..], .ref_counter = self.content.ref_counter.ref(), }; } }, }; } /// Processes the trimming rules for the left side of the slice pub fn trimLeft(self: *Self) void { switch (self.trimming.left) { .PreserveWhitespaces, .Trimmed => {}, .AllowTrimming => |left_trimming| { const content = self.content.slice; // Update the trim-right index and indentation after trimming left // BEFORE: // 2 7 // ↓ ↓ //const value = " \nABC\n " // // AFTER: // 4 // ↓ //const value = "ABC\n " switch (self.trimming.right) { .AllowTrimming => |right_trimming| { self.trimming.right = .{ .AllowTrimming = .{ .index = right_trimming.index - left_trimming.index - 1, .stand_alone = right_trimming.stand_alone, }, }; }, else => {}, } if (left_trimming.index >= content.len - 1) { self.content.slice = &.{}; } else { self.content.slice = content[left_trimming.index + 1 ..]; } self.trimming.left = .Trimmed; }, } } pub fn parseDelimiters(self: *const Self) ?Delimiters { // Delimiters are the only case of match closing tags {{= and =}} // Validate if the content ends with the proper "=" symbol before parsing the delimiters var content = self.content.slice; const last_index = content.len - 1; if (content[last_index] != @enumToInt(PartType.delimiters)) return null; content = content[0..last_index]; var iterator = std.mem.tokenize(u8, content, " \t"); const starting_delimiter = iterator.next() orelse return null; const ending_delimiter = iterator.next() orelse return null; if (iterator.next() != null) return null; return Delimiters{ .starting_delimiter = starting_delimiter, .ending_delimiter = ending_delimiter, }; } }; }
src/parsing/text_part.zig
pub const ZigGrammar = \\Program { TopLevelStmt* } \\TopLevelStmt @inline { StructMember | Statement } \\VModifier { 'pub' } \\Modifier { 'const' | 'var' } \\ExternModifier { 'extern' StringLiteral? } \\Statement @inline { \\ FunctionDecl | VariableDecl | IfStatement | LabeledStatement | \\ TestDecl | DeferStatement | ErrDeferStatement | ExternFunctionDecl | ExternVariableDecl | \\ UsingNamespaceStmt | NosuspendBlock | SuspendBlock | BlockStmt | (AssignExpr ';') | (Expression ';') \\} \\BlockStmt @inline { BlockExpr | WhileStatement | ForStatement | SwitchExpr } \\LabeledExpr { Identifier ':' (BlockExpr | WhileExpr) } \\LabeledStatement { Identifier ':' BlockStmt } \\LabeledTypeExpr { Identifier ':' BlockExpr } \\ErrDeferStatement { 'errdefer' (BlockExpr | (AssignExpr ';') | (Expression ';')) } \\DeferStatement { 'defer' (BlockExpr | (AssignExpr ';') | (Expression ';')) } \\ForStatement { 'inline'? 'for' '(' Expression ')' '|' CaptureParam (',' (Identifier | '_'))? '|' ((BlockExpr ElseStmt?) | (AssignOrExpr (';' | ElseStmt))) } \\ForExpr { 'inline'? 'for' '(' Expression ')' '|' CaptureParam (',' (Identifier | '_'))? '|' (BlockExpr | AssignOrExpr ) ElseExpr? } \\CaptureParam @inline { ('*'? Identifier) | '_' } \\CaptureClause { '|' CaptureParam '|' } \\WhileStatement { 'inline'? 'while' '(' Expression ')' CaptureClause? (':' '(' AssignOrExpr ')')? ((AssignOrExpr (';' | ElseIfStmt | ElseStmt)) | (BlockExpr ElseIfStmt?)) } \\WhileExpr { 'inline'? 'while' '(' Expression ')' CaptureClause? (':' '(' AssignOrExpr ')')? (BlockExpr | AssignOrExpr) ElseExpr? } \\SwitchExpr { 'switch' '(' Expression ')' '{' CaseBranch? (',' CaseBranch)* ','? '}' } \\CaseBranch { CaseMatcher '=>' (BlockExpr | AssignOrExpr) } \\CaseMatcher { 'else' | (CaseArg (',' CaseArg)* ','?) } \\CaseArg { Expression ('...' Expression)? } \\IfStatement { 'if' '(' Expression ')' CaptureClause? ((BlockExpr (ElseIfStmt | ElseStmt)?) | (AssignOrExpr (';' | ElseIfStmt | ElseStmt))) } \\ElseIfStmt { 'else' CaptureClause? 'if' '(' Expression ')' CaptureClause? ((BlockExpr (ElseIfStmt | ElseStmt)?) | (AssignOrExpr (';' | ElseIfStmt | ElseStmt))) } \\ElseStmt { 'else' CaptureClause? (BlockStmt | (AssignOrExpr ';')) } \\IfExpr { 'if' '(' Expression ')' CaptureClause? ((BlockExpr (ElseIfExpr | ElseExpr)) | (Expression (ElseIfExpr | ElseExpr)?)) } \\ElseIfExpr { 'else' 'if' '(' Expression ')' ((BlockExpr (ElseIfExpr | ElseExpr)) | (Expression (ElseIfExpr | ElseExpr)?)) } \\ElseExpr { 'else' Expression } \\TryExpr { 'try' Expression } \\TestDecl { 'test' StringLiteral? '{' Statement* '}' } \\ExternFunctionDecl { VModifier? ExternModifier FunctionType ';' } \\FunctionDecl { VModifier? 'export'? 'inline'? 'fn' Identifier '(' Parameters ')' ReturnSignature '{' Statement* '}' } \\ExternVariableDecl { VModifier? ExternModifier 'threadlocal'? Modifier Identifier (':' TypeExpr)? ';'} \\VariableDecl { VModifier? 'export'? ('comptime' | 'threadlocal')? Modifier Identifier (':' TypeExpr)? LinkSection? Align? '=' Expression ';' } \\LinkSection { 'linksection' '(' StringLiteral ')' } \\AssignOrExpr @inline { AssignExpr | Expression } \\AssignExpr { Expression AssignOp Expression } \\ReturnExpr { 'return' Expression? } \\BreakExpr { 'break' (':' Identifier)? Expression? } \\ContinueExpr { 'continue' (':' Identifier)? } \\Expression @inline { \\ LabeledExpr | BlockExpr | Identifier | AddressExpr | PropertyAccessExpr | CallExpr | BuiltinCallExpr | ImportExpr | NumberLiteral | FloatLiteral | \\ StringLiteral | CharLiteral | TupleLiteral | ErrorLiteral | EnumLiteral | ArrayInitExpr | TupleInitExpr | TypeExpr | BinaryExpr | StructInitExpr | ElementAccessExpr | CatchExpr | \\ ComptimeExpr | AsyncExpr | AwaitExpr | ResumeExpr | NosuspendExpr | DereferenceExpr | StructLiteral | IfExpr | WhileExpr | GroupExpr | SwitchExpr | ReturnExpr | \\ UnaryExpr | OrElseExpr | LineStringGroup | 'undefined' | 'unreachable' | ContinueExpr | BreakExpr | TryExpr | '_' | ForExpr | AssemblyExpr \\} \\TypeExpr @inline { 'void' | 'anytype' | 'anyerror' | 'type' | LabeledTypeExpr | FunctionType | ErrorType | Identifier | PointerType | DoublePointerType | PropertyAccessTypeExpr | \\ CallTypeExpr | SliceType | StructTypeExpr | BuiltinCallExpr | OptionalType | ManyItemPointerType | CPointerType | ArrayType | EnumType | \\ NumberLiteral | UnionType | GroupTypeExpr | BinaryExpr | SwitchExpr | ErrorSetType | IfExpr | ElementAccessExpr \\} \\ResumeExpr { 'resume' Expression } \\AwaitExpr { 'await' Expression } \\AsyncExpr { 'async' Expression } \\NosuspendBlock { 'nosuspend' '{' Statement* '}' } \\NosuspendExpr { 'nosuspend' Expression } \\ComptimeExpr { 'comptime' Expression } \\OrElseExpr { Expression 'orelse' Expression } \\ElementAccessExpr { Expression '[' Expression ('..' Expression?)? (':' Expression)? ']' } \\ArrayInitExpr { '[' ('_' | NumberLiteral) ']' TypeExpr '{' Args '}' } \\StructInitExpr { Expression '{' StructMemberInits '}' } \\StructMemberInits { StructMemberInit? (',' StructMemberInit)* ','? } \\StructMemberInit { '.' Identifier '=' Expression } \\AddressExpr { '&' Expression } \\SuspendBlock { 'suspend' '{' Statement* '}' } \\BlockExpr { 'comptime'? (Identifier ':')? '{' Statement* '}' } \\UnaryExpr { ('!' | '-' | '~') Expression } \\BinaryExpr { Expression (BinOperator | 'and' | 'or') Expression } \\PropertyAccessExpr { Expression '.' (Identifier | '?' | 'type' | 'void' | 'anyerror') } \\PropertyAccessTypeExpr { TypeExpr '.' Identifier } \\DereferenceExpr { Expression '.*' } \\CallTypeExpr { TypeExpr '(' Args ')' } \\NumberLiteral { DecLiteral | HexLiteral | OctLiteral | BinLiteral } \\ErrorSetType { 'error' '{' EnumMember* '}' } \\EnumType { 'enum' ('(' Identifier ')')? '{' EnumMember* '}' } \\EnumMember { EnumField | FunctionDecl | VariableDecl | ExternVariableDecl } \\EnumField { (((Identifier | 'type') ('=' Expression)?) | '_') ','? } \\OptionalType { '?' TypeExpr } \\DoublePointerType { '**' 'allowzero'? 'volatile'? Align? 'const'? 'volatile'? TypeExpr } \\PointerType { '*' 'allowzero'? 'volatile'? Align? 'const'? 'volatile'? TypeExpr } \\Align { 'align' '(' Expression ')' } \\SliceType { '[' SentinelTerminated? ']' 'allowzero'? 'volatile'? Align? 'const'? TypeExpr } \\ArrayType { '[' Expression SentinelTerminated? ']' 'const'? TypeExpr } \\ManyItemPointerType { '[' '*' SentinelTerminated? ']' 'allowzero'? 'volatile'? Align? 'const'? TypeExpr } \\CPointerType { '[' '*' IdentifierToken='c' ']' 'allowzero'? Align? 'const'? 'volatile'? TypeExpr } \\SentinelTerminated { ':' TypeExpr } \\FunctionType { 'fn' Identifier? '(' TypeParameters ')' ReturnSignature } \\TypeParameters { TypeParameter? (',' TypeParameter)* ','? } \\TypeParameter { (((Comptime | 'noalias')? Identifier ':')? TypeExpr) | '...' } \\BuiltinCallExpr { (AtIdentifier | BuiltinLiteral) '(' Args ')' } \\GroupExpr { '(' Expression ')' } \\GroupTypeExpr { '(' TypeExpr ')' } \\CallExpr { Expression '(' Args ')' } \\CatchExpr { Expression 'catch' CaptureClause? Expression } \\ImportExpr { '@import' '(' StringLiteral ')' } \\ReturnSignature { CallConvention? Align? TypeExpr } \\CallConvention { 'callconv' '(' Expression ')' } \\UnionType { 'extern'? 'packed'? 'union' ('(' ('enum' | TypeExpr) ')')? '{' UnionMember* '}' Align? } \\UnionMember @inline { FunctionDecl | ExternFunctionDecl | VariableDecl | ExternVariableDecl | StructField | EnumField } \\StructTypeExpr { ('extern' | 'packed')? 'struct' '{' StructMember* '}' } \\StructMember @inline { UsingNamespaceStmt | FunctionDecl | ExternFunctionDecl | VariableDecl | ExternVariableDecl | StructField | (&'comptime' BlockExpr) } \\StructField { 'comptime'? (Identifier | 'type' | '_') ':' TypeExpr Align? ('=' Expression)? ','? } \\AssemblyExpr { 'asm' 'volatile'? '(' AsmCode (':' AsmOutputs? (':' AsmInputs? (':' AsmClobbers)?)?)? ')' } \\AsmCode { StringLiteral | LineStringGroup } \\AsmOutputs { AsmOutput (',' AsmOutput)* ','? } \\AsmOutput { '[' (Identifier | '_') ']' StringLiteral '(' (Identifier | ('->' Expression)) ')' } \\AsmInputs { AsmInput (',' AsmInput)* ','? } \\AsmInput { '[' (Identifier | '_') ']' StringLiteral '(' Expression ')' } \\AsmClobbers { StringLiteral (',' StringLiteral)* } \\UsingNamespaceStmt { VModifier? 'usingnamespace' Expression ';' } \\TupleInitExpr { Expression '{' Args '}' } \\TupleLiteral { '.' '{' Args '}' } \\StructLiteral { '.' '{' StructMemberInits '}' } \\EnumLiteral { '.' Identifier } \\ErrorLiteral { 'error' '.' Identifier } \\Args { Expression? (',' Expression)* ','? } \\Parameters { Parameter? (',' Parameter)* ','? } \\Parameter { ((Comptime | 'noalias')? (Identifier | '_') ':' TypeExpr) | '...' } \\ErrorType { ('anyerror' | ErrorSetType | ErrorLiteral | (!'!' Expression))? '!' TypeExpr } \\Comptime { 'comptime' } \\Identifier @inline { IdentifierToken | AtStringIdentifier } \\LineStringGroup { LineString+ } \\FloatLiteral { DecFloatLiteral | HexFloatLiteral } \\AssignOp { '=' | '+=' | '-=' | '*=' | '/=' | '|=' | '&=' | '%=' | '>>=' | '<<=' | '^=' } \\@tokens { \\ Comment @skip { '//' [^\n]* '\n' } \\ BinLiteral { '0b' ('_'? [0-1]+)+ } \\ HexFloatLiteral { HexLiteral (('.' [0-9a-fA-F]+ ([pP] [+\-]? DecLiteral)?) | ([pP] [+\-]? DecLiteral)) } \\ HexLiteral { '0x' ('_'? [0-9a-fA-F]+)+ } \\ OctLiteral { '0o' [0-7]+ } \\ DecFloatLiteral { DecLiteral (('.' DecLiteral ([eE] [+\-]? DecLiteral)?) | ([eE] [+\-]? DecLiteral)) } \\ DecLiteral { [0-9] ('_'? [0-9]+)* } \\ CharLiteral { '\'' ('\\\\' | '\\\'' | [^\n'])+ '\'' } \\ StringLiteral { '"' ('\\\\' | '\\"' | [^\n"])* '"' } \\ LineString { '\\\\' [^\n]* '\n' } \\ IdentifierToken { [a-zA-Z_] [a-zA-Z0-9_]* } \\ Keyword @literal @replace(IdentifierToken) { \\ 'fn' | 'return' | 'const' | 'var' | 'pub' | 'try' | 'comptime' | 'type' | 'struct' | 'anytype' | 'void' | \\ 'if' | 'else' | 'for' | 'break' | 'callconv' | 'catch' | 'unreachable' | '_' | 'while' | 'and' | 'or' | \\ 'usingnamespace' | 'inline' | 'test' | 'defer' | 'enum' | 'extern' | 'union' | 'switch' | 'align' | 'packed' | \\ 'orelse' | 'noalias' | 'threadlocal' | 'undefined' | 'errdefer' | 'error' | 'nosuspend' | 'anyerror' | 'async' | 'await' | \\ 'suspend' | 'resume' | 'continue' | 'asm' | 'volatile' | 'export' | 'linksection' | 'allowzero' \\ } \\ AtIdentifier { '@' IdentifierToken } \\ AtStringIdentifier { '@' StringLiteral } \\ BuiltinLiteral @literal @replace(AtIdentifier) { \\ '@import' | '@This' \\ } \\ BinOperator @literal { '+=' | '++' | '+' | '->' | '-=' | '-' | '*=' | '/=' | '|=' | '**' | '<=' | '>=' | '>>=' | '>>' | '<<=' | '<<' | '&=' | '%=' | \\ '==' | '!=' | '<' | '>' | '*' | '/' | '&' | '|' | '%' | '^=' | '^' | '~' \\ } \\ Operator @literal { '...' | '..' | '.*' | '=>' | '=' } \\ Punctuator @literal { '(' | ')' | '{' | '}' | ';' | ':' | '!' | '.' | ',' | '[' | ']' | \\ '?' \\ } \\} ; // https://github.com/tree-sitter/tree-sitter-javascript/blob/master/grammar.js // https://github.com/tree-sitter/tree-sitter-typescript/blob/master/common/define-grammar.js // https://github.com/lezer-parser/javascript/blob/main/src/javascript.grammar // https://ts-ast-viewer.com/ // TODO: Typescript/js grammar pub const TypescriptGrammar = \\ ;
parser/grammars.zig
const std = @import("../../std.zig"); const windows = std.os.windows; const WINAPI = windows.WINAPI; const DWORD = windows.DWORD; const HANDLE = windows.HANDLE; const PENUM_PAGE_FILE_CALLBACKW = windows.PENUM_PAGE_FILE_CALLBACKW; const HMODULE = windows.HMODULE; const BOOL = windows.BOOL; const BOOLEAN = windows.BOOLEAN; const CONDITION_VARIABLE = windows.CONDITION_VARIABLE; const CONSOLE_SCREEN_BUFFER_INFO = windows.CONSOLE_SCREEN_BUFFER_INFO; const COORD = windows.COORD; const FILE_INFO_BY_HANDLE_CLASS = windows.FILE_INFO_BY_HANDLE_CLASS; const HRESULT = windows.HRESULT; const LARGE_INTEGER = windows.LARGE_INTEGER; const LPCWSTR = windows.LPCWSTR; const LPTHREAD_START_ROUTINE = windows.LPTHREAD_START_ROUTINE; const LPVOID = windows.LPVOID; const LPWSTR = windows.LPWSTR; const MODULEINFO = windows.MODULEINFO; const OVERLAPPED = windows.OVERLAPPED; const PERFORMANCE_INFORMATION = windows.PERFORMANCE_INFORMATION; const PROCESS_MEMORY_COUNTERS = windows.PROCESS_MEMORY_COUNTERS; const PSAPI_WS_WATCH_INFORMATION = windows.PSAPI_WS_WATCH_INFORMATION; const PSAPI_WS_WATCH_INFORMATION_EX = windows.PSAPI_WS_WATCH_INFORMATION_EX; const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES; const SIZE_T = windows.SIZE_T; const SRWLOCK = windows.SRWLOCK; const UINT = windows.UINT; const VECTORED_EXCEPTION_HANDLER = windows.VECTORED_EXCEPTION_HANDLER; const WCHAR = windows.WCHAR; const WORD = windows.WORD; const Win32Error = windows.Win32Error; const va_list = windows.va_list; const HLOCAL = windows.HLOCAL; const FILETIME = windows.FILETIME; const STARTUPINFOW = windows.STARTUPINFOW; const PROCESS_INFORMATION = windows.PROCESS_INFORMATION; const OVERLAPPED_ENTRY = windows.OVERLAPPED_ENTRY; const LPHEAP_SUMMARY = windows.LPHEAP_SUMMARY; const ULONG_PTR = windows.ULONG_PTR; const FILE_NOTIFY_INFORMATION = windows.FILE_NOTIFY_INFORMATION; const HANDLER_ROUTINE = windows.HANDLER_ROUTINE; const ULONG = windows.ULONG; const PVOID = windows.PVOID; const LPSTR = windows.LPSTR; const PENUM_PAGE_FILE_CALLBACKA = windows.PENUM_PAGE_FILE_CALLBACKA; pub extern "psapi" fn EmptyWorkingSet(hProcess: HANDLE) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumDeviceDrivers(lpImageBase: [*]LPVOID, cb: DWORD, lpcbNeeded: *DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumPageFilesA(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKA, pContext: LPVOID) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumPageFilesW(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKW, pContext: LPVOID) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumProcessModules(hProcess: HANDLE, lphModule: [*]HMODULE, cb: DWORD, lpcbNeeded: *DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumProcessModulesEx(hProcess: HANDLE, lphModule: [*]HMODULE, cb: DWORD, lpcbNeeded: *DWORD, dwFilterFlag: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn EnumProcesses(lpidProcess: [*]DWORD, cb: DWORD, cbNeeded: *DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn GetDeviceDriverBaseNameA(ImageBase: LPVOID, lpBaseName: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetDeviceDriverBaseNameW(ImageBase: LPVOID, lpBaseName: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetDeviceDriverFileNameA(ImageBase: LPVOID, lpFilename: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetDeviceDriverFileNameW(ImageBase: LPVOID, lpFilename: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetMappedFileNameA(hProcess: HANDLE, lpv: ?LPVOID, lpFilename: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetMappedFileNameW(hProcess: HANDLE, lpv: ?LPVOID, lpFilename: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetModuleBaseNameA(hProcess: HANDLE, hModule: ?HMODULE, lpBaseName: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetModuleBaseNameW(hProcess: HANDLE, hModule: ?HMODULE, lpBaseName: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetModuleFileNameExA(hProcess: HANDLE, hModule: ?HMODULE, lpFilename: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetModuleFileNameExW(hProcess: HANDLE, hModule: ?HMODULE, lpFilename: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetModuleInformation(hProcess: HANDLE, hModule: HMODULE, lpmodinfo: *MODULEINFO, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn GetPerformanceInfo(pPerformanceInformation: *PERFORMANCE_INFORMATION, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn GetProcessImageFileNameA(hProcess: HANDLE, lpImageFileName: LPSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetProcessImageFileNameW(hProcess: HANDLE, lpImageFileName: LPWSTR, nSize: DWORD) callconv(WINAPI) DWORD; pub extern "psapi" fn GetProcessMemoryInfo(Process: HANDLE, ppsmemCounters: *PROCESS_MEMORY_COUNTERS, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn GetWsChanges(hProcess: HANDLE, lpWatchInfo: *PSAPI_WS_WATCH_INFORMATION, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn GetWsChangesEx(hProcess: HANDLE, lpWatchInfoEx: *PSAPI_WS_WATCH_INFORMATION_EX, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn InitializeProcessForWsWatch(hProcess: HANDLE) callconv(WINAPI) BOOL; pub extern "psapi" fn QueryWorkingSet(hProcess: HANDLE, pv: PVOID, cb: DWORD) callconv(WINAPI) BOOL; pub extern "psapi" fn QueryWorkingSetEx(hProcess: HANDLE, pv: PVOID, cb: DWORD) callconv(WINAPI) BOOL;
lib/std/os/windows/psapi.zig
const std = @import("std"); const assert = std.debug.assert; const ast = std.zig.ast; const Token = std.zig.Token; const clang = @import("clang.zig"); const ctok = std.c.tokenizer; const CToken = std.c.Token; const mem = std.mem; const math = std.math; const CallingConvention = std.builtin.CallingConvention; pub const ClangErrMsg = clang.Stage2ErrorMsg; pub const Error = error{OutOfMemory}; const TypeError = Error || error{UnsupportedType}; const TransError = TypeError || error{UnsupportedTranslation}; const SymbolTable = std.StringArrayHashMap(*ast.Node); const AliasList = std.ArrayList(struct { alias: []const u8, name: []const u8, }); const Scope = struct { id: Id, parent: ?*Scope, const Id = enum { Switch, Block, Root, Condition, Loop, }; /// Represents an in-progress ast.Node.Switch. This struct is stack-allocated. /// When it is deinitialized, it produces an ast.Node.Switch which is allocated /// into the main arena. const Switch = struct { base: Scope, pending_block: Block, cases: []*ast.Node, case_index: usize, switch_label: ?[]const u8, default_label: ?[]const u8, }; /// Used for the scope of condition expressions, for example `if (cond)`. /// The block is lazily initialised because it is only needed for rare /// cases of comma operators being used. const Condition = struct { base: Scope, block: ?Block = null, fn getBlockScope(self: *Condition, c: *Context) !*Block { if (self.block) |*b| return b; self.block = try Block.init(c, &self.base, true); return &self.block.?; } fn deinit(self: *Condition) void { if (self.block) |*b| b.deinit(); } }; /// Represents an in-progress ast.Node.Block. This struct is stack-allocated. /// When it is deinitialized, it produces an ast.Node.Block which is allocated /// into the main arena. const Block = struct { base: Scope, statements: std.ArrayList(*ast.Node), variables: AliasList, label: ?ast.TokenIndex, mangle_count: u32 = 0, lbrace: ast.TokenIndex, fn init(c: *Context, parent: *Scope, labeled: bool) !Block { var blk = Block{ .base = .{ .id = .Block, .parent = parent, }, .statements = std.ArrayList(*ast.Node).init(c.gpa), .variables = AliasList.init(c.gpa), .label = null, .lbrace = try appendToken(c, .LBrace, "{"), }; if (labeled) { blk.label = try appendIdentifier(c, try blk.makeMangledName(c, "blk")); _ = try appendToken(c, .Colon, ":"); } return blk; } fn deinit(self: *Block) void { self.statements.deinit(); self.variables.deinit(); self.* = undefined; } fn complete(self: *Block, c: *Context) !*ast.Node { // We reserve 1 extra statement if the parent is a Loop. This is in case of // do while, we want to put `if (cond) break;` at the end. const alloc_len = self.statements.items.len + @boolToInt(self.base.parent.?.id == .Loop); const rbrace = try appendToken(c, .RBrace, "}"); if (self.label) |label| { const node = try ast.Node.LabeledBlock.alloc(c.arena, alloc_len); node.* = .{ .statements_len = self.statements.items.len, .lbrace = self.lbrace, .rbrace = rbrace, .label = label, }; mem.copy(*ast.Node, node.statements(), self.statements.items); return &node.base; } else { const node = try ast.Node.Block.alloc(c.arena, alloc_len); node.* = .{ .statements_len = self.statements.items.len, .lbrace = self.lbrace, .rbrace = rbrace, }; mem.copy(*ast.Node, node.statements(), self.statements.items); return &node.base; } } /// Given the desired name, return a name that does not shadow anything from outer scopes. /// Inserts the returned name into the scope. fn makeMangledName(scope: *Block, c: *Context, name: []const u8) ![]const u8 { const name_copy = try c.arena.dupe(u8, name); var proposed_name = name_copy; while (scope.contains(proposed_name)) { scope.mangle_count += 1; proposed_name = try std.fmt.allocPrint(c.arena, "{}_{}", .{ name, scope.mangle_count }); } try scope.variables.append(.{ .name = name_copy, .alias = proposed_name }); return proposed_name; } fn getAlias(scope: *Block, name: []const u8) []const u8 { for (scope.variables.items) |p| { if (mem.eql(u8, p.name, name)) return p.alias; } return scope.base.parent.?.getAlias(name); } fn localContains(scope: *Block, name: []const u8) bool { for (scope.variables.items) |p| { if (mem.eql(u8, p.alias, name)) return true; } return false; } fn contains(scope: *Block, name: []const u8) bool { if (scope.localContains(name)) return true; return scope.base.parent.?.contains(name); } }; const Root = struct { base: Scope, sym_table: SymbolTable, macro_table: SymbolTable, context: *Context, fn init(c: *Context) Root { return .{ .base = .{ .id = .Root, .parent = null, }, .sym_table = SymbolTable.init(c.arena), .macro_table = SymbolTable.init(c.arena), .context = c, }; } /// Check if the global scope contains this name, without looking into the "future", e.g. /// ignore the preprocessed decl and macro names. fn containsNow(scope: *Root, name: []const u8) bool { return isZigPrimitiveType(name) or scope.sym_table.contains(name) or scope.macro_table.contains(name); } /// Check if the global scope contains the name, includes all decls that haven't been translated yet. fn contains(scope: *Root, name: []const u8) bool { return scope.containsNow(name) or scope.context.global_names.contains(name); } }; fn findBlockScope(inner: *Scope, c: *Context) !*Scope.Block { var scope = inner; while (true) { switch (scope.id) { .Root => unreachable, .Block => return @fieldParentPtr(Block, "base", scope), .Condition => return @fieldParentPtr(Condition, "base", scope).getBlockScope(c), else => scope = scope.parent.?, } } } fn getAlias(scope: *Scope, name: []const u8) []const u8 { return switch (scope.id) { .Root => return name, .Block => @fieldParentPtr(Block, "base", scope).getAlias(name), .Switch, .Loop, .Condition => scope.parent.?.getAlias(name), }; } fn contains(scope: *Scope, name: []const u8) bool { return switch (scope.id) { .Root => @fieldParentPtr(Root, "base", scope).contains(name), .Block => @fieldParentPtr(Block, "base", scope).contains(name), .Switch, .Loop, .Condition => scope.parent.?.contains(name), }; } fn getBreakableScope(inner: *Scope) *Scope { var scope = inner; while (true) { switch (scope.id) { .Root => unreachable, .Switch => return scope, .Loop => return scope, else => scope = scope.parent.?, } } } fn getSwitch(inner: *Scope) *Scope.Switch { var scope = inner; while (true) { switch (scope.id) { .Root => unreachable, .Switch => return @fieldParentPtr(Switch, "base", scope), else => scope = scope.parent.?, } } } }; pub const Context = struct { gpa: *mem.Allocator, arena: *mem.Allocator, token_ids: std.ArrayListUnmanaged(Token.Id) = .{}, token_locs: std.ArrayListUnmanaged(Token.Loc) = .{}, errors: std.ArrayListUnmanaged(ast.Error) = .{}, source_buffer: *std.ArrayList(u8), err: Error, source_manager: *clang.SourceManager, decl_table: std.AutoArrayHashMapUnmanaged(usize, []const u8) = .{}, alias_list: AliasList, global_scope: *Scope.Root, clang_context: *clang.ASTContext, mangle_count: u32 = 0, root_decls: std.ArrayListUnmanaged(*ast.Node) = .{}, opaque_demotes: std.AutoHashMapUnmanaged(usize, void) = .{}, /// This one is different than the root scope's name table. This contains /// a list of names that we found by visiting all the top level decls without /// translating them. The other maps are updated as we translate; this one is updated /// up front in a pre-processing step. global_names: std.StringArrayHashMapUnmanaged(void) = .{}, fn getMangle(c: *Context) u32 { c.mangle_count += 1; return c.mangle_count; } /// Convert a null-terminated C string to a slice allocated in the arena fn str(c: *Context, s: [*:0]const u8) ![]u8 { return mem.dupe(c.arena, u8, mem.spanZ(s)); } /// Convert a clang source location to a file:line:column string fn locStr(c: *Context, loc: clang.SourceLocation) ![]u8 { const spelling_loc = c.source_manager.getSpellingLoc(loc); const filename_c = c.source_manager.getFilename(spelling_loc); const filename = if (filename_c) |s| try c.str(s) else @as([]const u8, "(no file)"); const line = c.source_manager.getSpellingLineNumber(spelling_loc); const column = c.source_manager.getSpellingColumnNumber(spelling_loc); return std.fmt.allocPrint(c.arena, "{}:{}:{}", .{ filename, line, column }); } fn createCall(c: *Context, fn_expr: *ast.Node, params_len: ast.NodeIndex) !*ast.Node.Call { _ = try appendToken(c, .LParen, "("); const node = try ast.Node.Call.alloc(c.arena, params_len); node.* = .{ .lhs = fn_expr, .params_len = params_len, .async_token = null, .rtoken = undefined, // set after appending args }; return node; } fn createBuiltinCall(c: *Context, name: []const u8, params_len: ast.NodeIndex) !*ast.Node.BuiltinCall { const builtin_token = try appendToken(c, .Builtin, name); _ = try appendToken(c, .LParen, "("); const node = try ast.Node.BuiltinCall.alloc(c.arena, params_len); node.* = .{ .builtin_token = builtin_token, .params_len = params_len, .rparen_token = undefined, // set after appending args }; return node; } fn createBlock(c: *Context, statements_len: ast.NodeIndex) !*ast.Node.Block { const block_node = try ast.Node.Block.alloc(c.arena, statements_len); block_node.* = .{ .lbrace = try appendToken(c, .LBrace, "{"), .statements_len = statements_len, .rbrace = undefined, }; return block_node; } }; fn addCBuiltinsNamespace(c: *Context) Error!void { // pub usingnamespace @import("std").c.builtins; const pub_tok = try appendToken(c, .Keyword_pub, "pub"); const use_tok = try appendToken(c, .Keyword_usingnamespace, "usingnamespace"); const import_tok = try appendToken(c, .Builtin, "@import"); const lparen_tok = try appendToken(c, .LParen, "("); const std_tok = try appendToken(c, .StringLiteral, "\"std\""); const rparen_tok = try appendToken(c, .RParen, ")"); const std_node = try c.arena.create(ast.Node.OneToken); std_node.* = .{ .base = .{ .tag = .StringLiteral }, .token = std_tok, }; const call_node = try ast.Node.BuiltinCall.alloc(c.arena, 1); call_node.* = .{ .builtin_token = import_tok, .params_len = 1, .rparen_token = rparen_tok, }; call_node.params()[0] = &std_node.base; var access_chain = &call_node.base; access_chain = try transCreateNodeFieldAccess(c, access_chain, "c"); access_chain = try transCreateNodeFieldAccess(c, access_chain, "builtins"); const semi_tok = try appendToken(c, .Semicolon, ";"); const bytes = try c.gpa.alignedAlloc(u8, @alignOf(ast.Node.Use), @sizeOf(ast.Node.Use)); const using_node = @ptrCast(*ast.Node.Use, bytes.ptr); using_node.* = .{ .doc_comments = null, .visib_token = pub_tok, .use_token = use_tok, .expr = access_chain, .semicolon_token = semi_tok, }; try c.root_decls.append(c.gpa, &using_node.base); } pub fn translate( gpa: *mem.Allocator, args_begin: [*]?[*]const u8, args_end: [*]?[*]const u8, errors: *[]ClangErrMsg, resources_path: [*:0]const u8, ) !*ast.Tree { const ast_unit = clang.LoadFromCommandLine( args_begin, args_end, &errors.ptr, &errors.len, resources_path, ) orelse { if (errors.len == 0) return error.ASTUnitFailure; return error.SemanticAnalyzeFail; }; defer ast_unit.delete(); var source_buffer = std.ArrayList(u8).init(gpa); defer source_buffer.deinit(); // For memory that has the same lifetime as the Tree that we return // from this function. var arena = std.heap.ArenaAllocator.init(gpa); errdefer arena.deinit(); var context = Context{ .gpa = gpa, .arena = &arena.allocator, .source_buffer = &source_buffer, .source_manager = ast_unit.getSourceManager(), .err = undefined, .alias_list = AliasList.init(gpa), .global_scope = try arena.allocator.create(Scope.Root), .clang_context = ast_unit.getASTContext(), }; context.global_scope.* = Scope.Root.init(&context); defer { context.decl_table.deinit(gpa); context.alias_list.deinit(); context.token_ids.deinit(gpa); context.token_locs.deinit(gpa); context.errors.deinit(gpa); context.global_names.deinit(gpa); context.root_decls.deinit(gpa); context.opaque_demotes.deinit(gpa); } try addCBuiltinsNamespace(&context); try prepopulateGlobalNameTable(ast_unit, &context); if (!ast_unit.visitLocalTopLevelDecls(&context, declVisitorC)) { return context.err; } try transPreprocessorEntities(&context, ast_unit); try addMacros(&context); for (context.alias_list.items) |alias| { if (!context.global_scope.sym_table.contains(alias.alias)) { try createAlias(&context, alias); } } const eof_token = try appendToken(&context, .Eof, ""); const root_node = try ast.Node.Root.create(&arena.allocator, context.root_decls.items.len, eof_token); mem.copy(*ast.Node, root_node.decls(), context.root_decls.items); if (false) { std.debug.warn("debug source:\n{}\n==EOF==\ntokens:\n", .{source_buffer.items}); for (context.token_ids.items) |token| { std.debug.warn("{}\n", .{token}); } } const tree = try arena.allocator.create(ast.Tree); tree.* = .{ .gpa = gpa, .source = try arena.allocator.dupe(u8, source_buffer.items), .token_ids = context.token_ids.toOwnedSlice(gpa), .token_locs = context.token_locs.toOwnedSlice(gpa), .errors = context.errors.toOwnedSlice(gpa), .root_node = root_node, .arena = arena.state, .generated = true, }; return tree; } fn prepopulateGlobalNameTable(ast_unit: *clang.ASTUnit, c: *Context) !void { if (!ast_unit.visitLocalTopLevelDecls(c, declVisitorNamesOnlyC)) { return c.err; } // TODO if we see #undef, delete it from the table var it = ast_unit.getLocalPreprocessingEntities_begin(); const it_end = ast_unit.getLocalPreprocessingEntities_end(); while (it.I != it_end.I) : (it.I += 1) { const entity = it.deref(); switch (entity.getKind()) { .MacroDefinitionKind => { const macro = @ptrCast(*clang.MacroDefinitionRecord, entity); const raw_name = macro.getName_getNameStart(); const name = try c.str(raw_name); _ = try c.global_names.put(c.gpa, name, {}); }, else => {}, } } } fn declVisitorNamesOnlyC(context: ?*c_void, decl: *const clang.Decl) callconv(.C) bool { const c = @ptrCast(*Context, @alignCast(@alignOf(Context), context)); declVisitorNamesOnly(c, decl) catch |err| { c.err = err; return false; }; return true; } fn declVisitorC(context: ?*c_void, decl: *const clang.Decl) callconv(.C) bool { const c = @ptrCast(*Context, @alignCast(@alignOf(Context), context)); declVisitor(c, decl) catch |err| { c.err = err; return false; }; return true; } fn declVisitorNamesOnly(c: *Context, decl: *const clang.Decl) Error!void { if (decl.castToNamedDecl()) |named_decl| { const decl_name = try c.str(named_decl.getName_bytes_begin()); _ = try c.global_names.put(c.gpa, decl_name, {}); } } fn declVisitor(c: *Context, decl: *const clang.Decl) Error!void { switch (decl.getKind()) { .Function => { return visitFnDecl(c, @ptrCast(*const clang.FunctionDecl, decl)); }, .Typedef => { _ = try transTypeDef(c, @ptrCast(*const clang.TypedefNameDecl, decl), true); }, .Enum => { _ = try transEnumDecl(c, @ptrCast(*const clang.EnumDecl, decl)); }, .Record => { _ = try transRecordDecl(c, @ptrCast(*const clang.RecordDecl, decl)); }, .Var => { return visitVarDecl(c, @ptrCast(*const clang.VarDecl, decl), null); }, .Empty => { // Do nothing }, else => { const decl_name = try c.str(decl.getDeclKindName()); try emitWarning(c, decl.getLocation(), "ignoring {} declaration", .{decl_name}); }, } } fn visitFnDecl(c: *Context, fn_decl: *const clang.FunctionDecl) Error!void { const fn_name = try c.str(@ptrCast(*const clang.NamedDecl, fn_decl).getName_bytes_begin()); if (c.global_scope.sym_table.contains(fn_name)) return; // Avoid processing this decl twice // Skip this declaration if a proper definition exists if (!fn_decl.isThisDeclarationADefinition()) { if (fn_decl.getDefinition()) |def| return visitFnDecl(c, def); } const rp = makeRestorePoint(c); const fn_decl_loc = fn_decl.getLocation(); const has_body = fn_decl.hasBody(); const storage_class = fn_decl.getStorageClass(); const decl_ctx = FnDeclContext{ .fn_name = fn_name, .has_body = has_body, .storage_class = storage_class, .is_export = switch (storage_class) { .None => has_body and !fn_decl.isInlineSpecified(), .Extern, .Static => false, .PrivateExtern => return failDecl(c, fn_decl_loc, fn_name, "unsupported storage class: private extern", .{}), .Auto => unreachable, // Not legal on functions .Register => unreachable, // Not legal on functions }, }; var fn_qt = fn_decl.getType(); const fn_type = while (true) { const fn_type = fn_qt.getTypePtr(); switch (fn_type.getTypeClass()) { .Attributed => { const attr_type = @ptrCast(*const clang.AttributedType, fn_type); fn_qt = attr_type.getEquivalentType(); }, .Paren => { const paren_type = @ptrCast(*const clang.ParenType, fn_type); fn_qt = paren_type.getInnerType(); }, else => break fn_type, } } else unreachable; const proto_node = switch (fn_type.getTypeClass()) { .FunctionProto => blk: { const fn_proto_type = @ptrCast(*const clang.FunctionProtoType, fn_type); break :blk transFnProto(rp, fn_decl, fn_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{}); }, error.OutOfMemory => |e| return e, }; }, .FunctionNoProto => blk: { const fn_no_proto_type = @ptrCast(*const clang.FunctionType, fn_type); break :blk transFnNoProto(rp, fn_no_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{}); }, error.OutOfMemory => |e| return e, }; }, else => return failDecl(c, fn_decl_loc, fn_name, "unable to resolve function type {}", .{fn_type.getTypeClass()}), }; if (!decl_ctx.has_body) { const semi_tok = try appendToken(c, .Semicolon, ";"); return addTopLevelDecl(c, fn_name, &proto_node.base); } // actual function definition with body const body_stmt = fn_decl.getBody(); var block_scope = try Scope.Block.init(rp.c, &c.global_scope.base, false); defer block_scope.deinit(); var scope = &block_scope.base; var param_id: c_uint = 0; for (proto_node.params()) |*param, i| { const param_name = if (param.name_token) |name_tok| tokenSlice(c, name_tok) else return failDecl(c, fn_decl_loc, fn_name, "function {} parameter has no name", .{fn_name}); const c_param = fn_decl.getParamDecl(param_id); const qual_type = c_param.getOriginalType(); const is_const = qual_type.isConstQualified(); const mangled_param_name = try block_scope.makeMangledName(c, param_name); if (!is_const) { const bare_arg_name = try std.fmt.allocPrint(c.arena, "arg_{}", .{mangled_param_name}); const arg_name = try block_scope.makeMangledName(c, bare_arg_name); const mut_tok = try appendToken(c, .Keyword_var, "var"); const name_tok = try appendIdentifier(c, mangled_param_name); const eq_token = try appendToken(c, .Equal, "="); const init_node = try transCreateNodeIdentifier(c, arg_name); const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ .mut_token = mut_tok, .name_token = name_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&node.base); param.name_token = try appendIdentifier(c, arg_name); _ = try appendToken(c, .Colon, ":"); } param_id += 1; } const casted_body = @ptrCast(*const clang.CompoundStmt, body_stmt); transCompoundStmtInline(rp, &block_scope.base, casted_body, &block_scope) catch |err| switch (err) { error.OutOfMemory => |e| return e, error.UnsupportedTranslation, error.UnsupportedType, => return failDecl(c, fn_decl_loc, fn_name, "unable to translate function", .{}), }; // add return statement if the function didn't have one blk: { const fn_ty = @ptrCast(*const clang.FunctionType, fn_type); if (fn_ty.getNoReturnAttr()) break :blk; const return_qt = fn_ty.getReturnType(); if (isCVoid(return_qt)) break :blk; if (block_scope.statements.items.len > 0) { var last = block_scope.statements.items[block_scope.statements.items.len - 1]; while (true) { switch (last.tag) { .Block, .LabeledBlock => { const stmts = last.blockStatements(); if (stmts.len == 0) break; last = stmts[stmts.len - 1]; }, // no extra return needed .Return => break :blk, else => break, } } } const return_expr = try ast.Node.ControlFlowExpression.create(rp.c.arena, .{ .ltoken = try appendToken(rp.c, .Keyword_return, "return"), .tag = .Return, }, .{ .rhs = transZeroInitExpr(rp, scope, fn_decl_loc, return_qt.getTypePtr()) catch |err| switch (err) { error.OutOfMemory => |e| return e, error.UnsupportedTranslation, error.UnsupportedType, => return failDecl(c, fn_decl_loc, fn_name, "unable to create a return value for function", .{}), }, }); _ = try appendToken(rp.c, .Semicolon, ";"); try block_scope.statements.append(&return_expr.base); } const body_node = try block_scope.complete(rp.c); proto_node.setBodyNode(body_node); return addTopLevelDecl(c, fn_name, &proto_node.base); } /// if mangled_name is not null, this var decl was declared in a block scope. fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]const u8) Error!void { const var_name = mangled_name orelse try c.str(@ptrCast(*const clang.NamedDecl, var_decl).getName_bytes_begin()); if (c.global_scope.sym_table.contains(var_name)) return; // Avoid processing this decl twice const rp = makeRestorePoint(c); const visib_tok = if (mangled_name) |_| null else try appendToken(c, .Keyword_pub, "pub"); const thread_local_token = if (var_decl.getTLSKind() == .None) null else try appendToken(c, .Keyword_threadlocal, "threadlocal"); const scope = &c.global_scope.base; // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ var_name, c.getMangle() }) else var_name; const var_decl_loc = var_decl.getLocation(); const qual_type = var_decl.getTypeSourceInfo_getType(); const storage_class = var_decl.getStorageClass(); const is_const = qual_type.isConstQualified(); const has_init = var_decl.hasInit(); // In C extern variables with initializers behave like Zig exports. // extern int foo = 2; // does the same as: // extern int foo; // int foo = 2; const extern_tok = if (storage_class == .Extern and !has_init) try appendToken(c, .Keyword_extern, "extern") else if (storage_class != .Static) try appendToken(c, .Keyword_export, "export") else null; const mut_tok = if (is_const) try appendToken(c, .Keyword_const, "const") else try appendToken(c, .Keyword_var, "var"); const name_tok = try appendIdentifier(c, checked_name); _ = try appendToken(c, .Colon, ":"); const type_node = transQualType(rp, qual_type, var_decl_loc) catch |err| switch (err) { error.UnsupportedType => { return failDecl(c, var_decl_loc, checked_name, "unable to resolve variable type", .{}); }, error.OutOfMemory => |e| return e, }; var eq_tok: ast.TokenIndex = undefined; var init_node: ?*ast.Node = null; // If the initialization expression is not present, initialize with undefined. // If it is an integer literal, we can skip the @as since it will be redundant // with the variable type. if (has_init) { eq_tok = try appendToken(c, .Equal, "="); init_node = if (var_decl.getInit()) |expr| transExprCoercing(rp, &c.global_scope.base, expr, .used, .r_value) catch |err| switch (err) { error.UnsupportedTranslation, error.UnsupportedType, => { return failDecl(c, var_decl_loc, checked_name, "unable to translate initializer", .{}); }, error.OutOfMemory => |e| return e, } else try transCreateNodeUndefinedLiteral(c); } else if (storage_class != .Extern) { eq_tok = try appendToken(c, .Equal, "="); // The C language specification states that variables with static or threadlocal // storage without an initializer are initialized to a zero value. // @import("std").mem.zeroes(T) const import_fn_call = try c.createBuiltinCall("@import", 1); const std_node = try transCreateNodeStringLiteral(c, "\"std\""); import_fn_call.params()[0] = std_node; import_fn_call.rparen_token = try appendToken(c, .RParen, ")"); const inner_field_access = try transCreateNodeFieldAccess(c, &import_fn_call.base, "mem"); const outer_field_access = try transCreateNodeFieldAccess(c, inner_field_access, "zeroes"); const zero_init_call = try c.createCall(outer_field_access, 1); zero_init_call.params()[0] = type_node; zero_init_call.rtoken = try appendToken(c, .RParen, ")"); init_node = &zero_init_call.base; } const linksection_expr = blk: { var str_len: usize = undefined; if (var_decl.getSectionAttribute(&str_len)) |str_ptr| { _ = try appendToken(rp.c, .Keyword_linksection, "linksection"); _ = try appendToken(rp.c, .LParen, "("); const expr = try transCreateNodeStringLiteral( rp.c, try std.fmt.allocPrint(rp.c.arena, "\"{}\"", .{str_ptr[0..str_len]}), ); _ = try appendToken(rp.c, .RParen, ")"); break :blk expr; } break :blk null; }; const align_expr = blk: { const alignment = var_decl.getAlignedAttribute(rp.c.clang_context); if (alignment != 0) { _ = try appendToken(rp.c, .Keyword_align, "align"); _ = try appendToken(rp.c, .LParen, "("); // Clang reports the alignment in bits const expr = try transCreateNodeInt(rp.c, alignment / 8); _ = try appendToken(rp.c, .RParen, ")"); break :blk expr; } break :blk null; }; const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = try appendToken(c, .Semicolon, ";"), }, .{ .visib_token = visib_tok, .thread_local_token = thread_local_token, .eq_token = eq_tok, .extern_export_token = extern_tok, .type_node = type_node, .align_node = align_expr, .section_node = linksection_expr, .init_node = init_node, }); return addTopLevelDecl(c, checked_name, &node.base); } fn transTypeDefAsBuiltin(c: *Context, typedef_decl: *const clang.TypedefNameDecl, builtin_name: []const u8) !*ast.Node { _ = try c.decl_table.put(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), builtin_name); return transCreateNodeIdentifier(c, builtin_name); } fn checkForBuiltinTypedef(checked_name: []const u8) ?[]const u8 { const table = [_][2][]const u8{ .{ "uint8_t", "u8" }, .{ "int8_t", "i8" }, .{ "uint16_t", "u16" }, .{ "int16_t", "i16" }, .{ "uint32_t", "u32" }, .{ "int32_t", "i32" }, .{ "uint64_t", "u64" }, .{ "int64_t", "i64" }, .{ "intptr_t", "isize" }, .{ "uintptr_t", "usize" }, .{ "ssize_t", "isize" }, .{ "size_t", "usize" }, }; for (table) |entry| { if (mem.eql(u8, checked_name, entry[0])) { return entry[1]; } } return null; } fn transTypeDef(c: *Context, typedef_decl: *const clang.TypedefNameDecl, top_level_visit: bool) Error!?*ast.Node { if (c.decl_table.get(@ptrToInt(typedef_decl.getCanonicalDecl()))) |name| return transCreateNodeIdentifier(c, name); // Avoid processing this decl twice const rp = makeRestorePoint(c); const typedef_name = try c.str(@ptrCast(*const clang.NamedDecl, typedef_decl).getName_bytes_begin()); // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 const checked_name = if (isZigPrimitiveType(typedef_name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ typedef_name, c.getMangle() }) else typedef_name; if (checkForBuiltinTypedef(checked_name)) |builtin| { return transTypeDefAsBuiltin(c, typedef_decl, builtin); } if (!top_level_visit) { return transCreateNodeIdentifier(c, checked_name); } _ = try c.decl_table.put(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), checked_name); const node = (try transCreateNodeTypedef(rp, typedef_decl, true, checked_name)) orelse return null; try addTopLevelDecl(c, checked_name, node); return transCreateNodeIdentifier(c, checked_name); } fn transCreateNodeTypedef( rp: RestorePoint, typedef_decl: *const clang.TypedefNameDecl, toplevel: bool, checked_name: []const u8, ) Error!?*ast.Node { const visib_tok = if (toplevel) try appendToken(rp.c, .Keyword_pub, "pub") else null; const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, checked_name); const eq_token = try appendToken(rp.c, .Equal, "="); const child_qt = typedef_decl.getUnderlyingType(); const typedef_loc = typedef_decl.getLocation(); const init_node = transQualType(rp, child_qt, typedef_loc) catch |err| switch (err) { error.UnsupportedType => { try failDecl(rp.c, typedef_loc, checked_name, "unable to resolve typedef child type", .{}); return null; }, error.OutOfMemory => |e| return e, }; const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .visib_token = visib_tok, .eq_token = eq_token, .init_node = init_node, }); return &node.base; } fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*ast.Node { if (c.decl_table.get(@ptrToInt(record_decl.getCanonicalDecl()))) |name| return try transCreateNodeIdentifier(c, name); // Avoid processing this decl twice const record_loc = record_decl.getLocation(); var bare_name = try c.str(@ptrCast(*const clang.NamedDecl, record_decl).getName_bytes_begin()); var is_unnamed = false; // Record declarations such as `struct {...} x` have no name but they're not // anonymous hence here isAnonymousStructOrUnion is not needed if (bare_name.len == 0) { bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{c.getMangle()}); is_unnamed = true; } var container_kind_name: []const u8 = undefined; var container_kind: std.zig.Token.Id = undefined; if (record_decl.isUnion()) { container_kind_name = "union"; container_kind = .Keyword_union; } else if (record_decl.isStruct()) { container_kind_name = "struct"; container_kind = .Keyword_struct; } else { try emitWarning(c, record_loc, "record {} is not a struct or union", .{bare_name}); return null; } const name = try std.fmt.allocPrint(c.arena, "{}_{}", .{ container_kind_name, bare_name }); _ = try c.decl_table.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), name); const visib_tok = if (!is_unnamed) try appendToken(c, .Keyword_pub, "pub") else null; const mut_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendIdentifier(c, name); const eq_token = try appendToken(c, .Equal, "="); var semicolon: ast.TokenIndex = undefined; const init_node = blk: { const rp = makeRestorePoint(c); const record_def = record_decl.getDefinition() orelse { _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); break :blk opaque_type; }; const layout_tok = try if (record_decl.getPackedAttribute()) appendToken(c, .Keyword_packed, "packed") else appendToken(c, .Keyword_extern, "extern"); const container_tok = try appendToken(c, container_kind, container_kind_name); const lbrace_token = try appendToken(c, .LBrace, "{"); var fields_and_decls = std.ArrayList(*ast.Node).init(c.gpa); defer fields_and_decls.deinit(); var unnamed_field_count: u32 = 0; var it = record_def.field_begin(); const end_it = record_def.field_end(); while (it.neq(end_it)) : (it = it.next()) { const field_decl = it.deref(); const field_loc = field_decl.getLocation(); const field_qt = field_decl.getType(); if (field_decl.isBitField()) { _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); try emitWarning(c, field_loc, "{} demoted to opaque type - has bitfield", .{container_kind_name}); break :blk opaque_type; } if (qualTypeCanon(field_qt).isIncompleteOrZeroLengthArrayType(c.clang_context)) { _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); try emitWarning(c, field_loc, "{} demoted to opaque type - has variable length array", .{container_kind_name}); break :blk opaque_type; } var is_anon = false; var raw_name = try c.str(@ptrCast(*const clang.NamedDecl, field_decl).getName_bytes_begin()); if (field_decl.isAnonymousStructOrUnion() or raw_name.len == 0) { // Context.getMangle() is not used here because doing so causes unpredictable field names for anonymous fields. raw_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{unnamed_field_count}); unnamed_field_count += 1; is_anon = true; } const field_name = try appendIdentifier(c, raw_name); _ = try appendToken(c, .Colon, ":"); const field_type = transQualType(rp, field_qt, field_loc) catch |err| switch (err) { error.UnsupportedType => { _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); try emitWarning(c, record_loc, "{} demoted to opaque type - unable to translate type of field {}", .{ container_kind_name, raw_name }); break :blk opaque_type; }, else => |e| return e, }; const align_expr = blk_2: { const alignment = field_decl.getAlignedAttribute(c.clang_context); if (alignment != 0) { _ = try appendToken(c, .Keyword_align, "align"); _ = try appendToken(c, .LParen, "("); // Clang reports the alignment in bits const expr = try transCreateNodeInt(c, alignment / 8); _ = try appendToken(c, .RParen, ")"); break :blk_2 expr; } break :blk_2 null; }; const field_node = try c.arena.create(ast.Node.ContainerField); field_node.* = .{ .doc_comments = null, .comptime_token = null, .name_token = field_name, .type_expr = field_type, .value_expr = null, .align_expr = align_expr, }; if (is_anon) { _ = try c.decl_table.put( c.gpa, @ptrToInt(field_decl.getCanonicalDecl()), raw_name, ); } try fields_and_decls.append(&field_node.base); _ = try appendToken(c, .Comma, ","); } const container_node = try ast.Node.ContainerDecl.alloc(c.arena, fields_and_decls.items.len); container_node.* = .{ .layout_token = layout_tok, .kind_token = container_tok, .init_arg_expr = .None, .fields_and_decls_len = fields_and_decls.items.len, .lbrace_token = lbrace_token, .rbrace_token = try appendToken(c, .RBrace, "}"), }; mem.copy(*ast.Node, container_node.fieldsAndDecls(), fields_and_decls.items); semicolon = try appendToken(c, .Semicolon, ";"); break :blk &container_node.base; }; const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon, }, .{ .visib_token = visib_tok, .eq_token = eq_token, .init_node = init_node, }); try addTopLevelDecl(c, name, &node.base); if (!is_unnamed) try c.alias_list.append(.{ .alias = bare_name, .name = name }); return transCreateNodeIdentifier(c, name); } fn transEnumDecl(c: *Context, enum_decl: *const clang.EnumDecl) Error!?*ast.Node { if (c.decl_table.get(@ptrToInt(enum_decl.getCanonicalDecl()))) |name| return try transCreateNodeIdentifier(c, name); // Avoid processing this decl twice const rp = makeRestorePoint(c); const enum_loc = enum_decl.getLocation(); var bare_name = try c.str(@ptrCast(*const clang.NamedDecl, enum_decl).getName_bytes_begin()); var is_unnamed = false; if (bare_name.len == 0) { bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{c.getMangle()}); is_unnamed = true; } const name = try std.fmt.allocPrint(c.arena, "enum_{}", .{bare_name}); _ = try c.decl_table.put(c.gpa, @ptrToInt(enum_decl.getCanonicalDecl()), name); const visib_tok = if (!is_unnamed) try appendToken(c, .Keyword_pub, "pub") else null; const mut_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendIdentifier(c, name); const eq_token = try appendToken(c, .Equal, "="); const init_node = if (enum_decl.getDefinition()) |enum_def| blk: { var pure_enum = true; var it = enum_def.enumerator_begin(); var end_it = enum_def.enumerator_end(); while (it.neq(end_it)) : (it = it.next()) { const enum_const = it.deref(); if (enum_const.getInitExpr()) |_| { pure_enum = false; break; } } const extern_tok = try appendToken(c, .Keyword_extern, "extern"); const container_tok = try appendToken(c, .Keyword_enum, "enum"); var fields_and_decls = std.ArrayList(*ast.Node).init(c.gpa); defer fields_and_decls.deinit(); const int_type = enum_decl.getIntegerType(); // The underlying type may be null in case of forward-declared enum // types, while that's not ISO-C compliant many compilers allow this and // default to the usual integer type used for all the enums. // default to c_int since msvc and gcc default to different types _ = try appendToken(c, .LParen, "("); const init_arg_expr = ast.Node.ContainerDecl.InitArg{ .Type = if (int_type.ptr != null and !isCBuiltinType(int_type, .UInt) and !isCBuiltinType(int_type, .Int)) transQualType(rp, int_type, enum_loc) catch |err| switch (err) { error.UnsupportedType => { try failDecl(c, enum_loc, name, "unable to translate enum tag type", .{}); return null; }, else => |e| return e, } else try transCreateNodeIdentifier(c, "c_int"), }; _ = try appendToken(c, .RParen, ")"); const lbrace_token = try appendToken(c, .LBrace, "{"); it = enum_def.enumerator_begin(); end_it = enum_def.enumerator_end(); while (it.neq(end_it)) : (it = it.next()) { const enum_const = it.deref(); const enum_val_name = try c.str(@ptrCast(*const clang.NamedDecl, enum_const).getName_bytes_begin()); const field_name = if (!is_unnamed and mem.startsWith(u8, enum_val_name, bare_name)) enum_val_name[bare_name.len..] else enum_val_name; const field_name_tok = try appendIdentifier(c, field_name); const int_node = if (!pure_enum) blk_2: { _ = try appendToken(c, .Colon, "="); break :blk_2 try transCreateNodeAPInt(c, enum_const.getInitVal()); } else null; const field_node = try c.arena.create(ast.Node.ContainerField); field_node.* = .{ .doc_comments = null, .comptime_token = null, .name_token = field_name_tok, .type_expr = null, .value_expr = int_node, .align_expr = null, }; try fields_and_decls.append(&field_node.base); _ = try appendToken(c, .Comma, ","); // In C each enum value is in the global namespace. So we put them there too. // At this point we can rely on the enum emitting successfully. const tld_visib_tok = try appendToken(c, .Keyword_pub, "pub"); const tld_mut_tok = try appendToken(c, .Keyword_const, "const"); const tld_name_tok = try appendIdentifier(c, enum_val_name); const tld_eq_token = try appendToken(c, .Equal, "="); const cast_node = try rp.c.createBuiltinCall("@enumToInt", 1); const enum_ident = try transCreateNodeIdentifier(c, name); const period_tok = try appendToken(c, .Period, "."); const field_ident = try transCreateNodeIdentifier(c, field_name); const field_access_node = try c.arena.create(ast.Node.SimpleInfixOp); field_access_node.* = .{ .base = .{ .tag = .Period }, .op_token = period_tok, .lhs = enum_ident, .rhs = field_ident, }; cast_node.params()[0] = &field_access_node.base; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); const tld_init_node = &cast_node.base; const tld_semicolon_token = try appendToken(c, .Semicolon, ";"); const tld_node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = tld_name_tok, .mut_token = tld_mut_tok, .semicolon_token = tld_semicolon_token, }, .{ .visib_token = tld_visib_tok, .eq_token = tld_eq_token, .init_node = tld_init_node, }); try addTopLevelDecl(c, field_name, &tld_node.base); } // make non exhaustive const field_node = try c.arena.create(ast.Node.ContainerField); field_node.* = .{ .doc_comments = null, .comptime_token = null, .name_token = try appendIdentifier(c, "_"), .type_expr = null, .value_expr = null, .align_expr = null, }; try fields_and_decls.append(&field_node.base); _ = try appendToken(c, .Comma, ","); const container_node = try ast.Node.ContainerDecl.alloc(c.arena, fields_and_decls.items.len); container_node.* = .{ .layout_token = extern_tok, .kind_token = container_tok, .init_arg_expr = init_arg_expr, .fields_and_decls_len = fields_and_decls.items.len, .lbrace_token = lbrace_token, .rbrace_token = try appendToken(c, .RBrace, "}"), }; mem.copy(*ast.Node, container_node.fieldsAndDecls(), fields_and_decls.items); break :blk &container_node.base; } else blk: { _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(enum_decl.getCanonicalDecl()), {}); break :blk try transCreateNodeOpaqueType(c); }; const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .visib_token = visib_tok, .eq_token = eq_token, .init_node = init_node, }); try addTopLevelDecl(c, name, &node.base); if (!is_unnamed) try c.alias_list.append(.{ .alias = bare_name, .name = name }); return transCreateNodeIdentifier(c, name); } fn createAlias(c: *Context, alias: anytype) !void { const visib_tok = try appendToken(c, .Keyword_pub, "pub"); const mut_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendIdentifier(c, alias.alias); const eq_token = try appendToken(c, .Equal, "="); const init_node = try transCreateNodeIdentifier(c, alias.name); const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .visib_token = visib_tok, .eq_token = eq_token, .init_node = init_node, }); return addTopLevelDecl(c, alias.alias, &node.base); } const ResultUsed = enum { used, unused, }; const LRValue = enum { l_value, r_value, }; fn transStmt( rp: RestorePoint, scope: *Scope, stmt: *const clang.Stmt, result_used: ResultUsed, lrvalue: LRValue, ) TransError!*ast.Node { const sc = stmt.getStmtClass(); switch (sc) { .BinaryOperatorClass => return transBinaryOperator(rp, scope, @ptrCast(*const clang.BinaryOperator, stmt), result_used), .CompoundStmtClass => return transCompoundStmt(rp, scope, @ptrCast(*const clang.CompoundStmt, stmt)), .CStyleCastExprClass => return transCStyleCastExprClass(rp, scope, @ptrCast(*const clang.CStyleCastExpr, stmt), result_used, lrvalue), .DeclStmtClass => return transDeclStmt(rp, scope, @ptrCast(*const clang.DeclStmt, stmt)), .DeclRefExprClass => return transDeclRefExpr(rp, scope, @ptrCast(*const clang.DeclRefExpr, stmt), lrvalue), .ImplicitCastExprClass => return transImplicitCastExpr(rp, scope, @ptrCast(*const clang.ImplicitCastExpr, stmt), result_used), .IntegerLiteralClass => return transIntegerLiteral(rp, scope, @ptrCast(*const clang.IntegerLiteral, stmt), result_used, .with_as), .ReturnStmtClass => return transReturnStmt(rp, scope, @ptrCast(*const clang.ReturnStmt, stmt)), .StringLiteralClass => return transStringLiteral(rp, scope, @ptrCast(*const clang.StringLiteral, stmt), result_used), .ParenExprClass => { const expr = try transExpr(rp, scope, @ptrCast(*const clang.ParenExpr, stmt).getSubExpr(), .used, lrvalue); if (expr.tag == .GroupedExpression) return maybeSuppressResult(rp, scope, result_used, expr); const node = try rp.c.arena.create(ast.Node.GroupedExpression); node.* = .{ .lparen = try appendToken(rp.c, .LParen, "("), .expr = expr, .rparen = try appendToken(rp.c, .RParen, ")"), }; return maybeSuppressResult(rp, scope, result_used, &node.base); }, .InitListExprClass => return transInitListExpr(rp, scope, @ptrCast(*const clang.InitListExpr, stmt), result_used), .ImplicitValueInitExprClass => return transImplicitValueInitExpr(rp, scope, @ptrCast(*const clang.Expr, stmt), result_used), .IfStmtClass => return transIfStmt(rp, scope, @ptrCast(*const clang.IfStmt, stmt)), .WhileStmtClass => return transWhileLoop(rp, scope, @ptrCast(*const clang.WhileStmt, stmt)), .DoStmtClass => return transDoWhileLoop(rp, scope, @ptrCast(*const clang.DoStmt, stmt)), .NullStmtClass => { const block = try rp.c.createBlock(0); block.rbrace = try appendToken(rp.c, .RBrace, "}"); return &block.base; }, .ContinueStmtClass => return try transCreateNodeContinue(rp.c), .BreakStmtClass => return transBreak(rp, scope), .ForStmtClass => return transForLoop(rp, scope, @ptrCast(*const clang.ForStmt, stmt)), .FloatingLiteralClass => return transFloatingLiteral(rp, scope, @ptrCast(*const clang.FloatingLiteral, stmt), result_used), .ConditionalOperatorClass => { return transConditionalOperator(rp, scope, @ptrCast(*const clang.ConditionalOperator, stmt), result_used); }, .BinaryConditionalOperatorClass => { return transBinaryConditionalOperator(rp, scope, @ptrCast(*const clang.BinaryConditionalOperator, stmt), result_used); }, .SwitchStmtClass => return transSwitch(rp, scope, @ptrCast(*const clang.SwitchStmt, stmt)), .CaseStmtClass => return transCase(rp, scope, @ptrCast(*const clang.CaseStmt, stmt)), .DefaultStmtClass => return transDefault(rp, scope, @ptrCast(*const clang.DefaultStmt, stmt)), .ConstantExprClass => return transConstantExpr(rp, scope, @ptrCast(*const clang.Expr, stmt), result_used), .PredefinedExprClass => return transPredefinedExpr(rp, scope, @ptrCast(*const clang.PredefinedExpr, stmt), result_used), .CharacterLiteralClass => return transCharLiteral(rp, scope, @ptrCast(*const clang.CharacterLiteral, stmt), result_used, .with_as), .StmtExprClass => return transStmtExpr(rp, scope, @ptrCast(*const clang.StmtExpr, stmt), result_used), .MemberExprClass => return transMemberExpr(rp, scope, @ptrCast(*const clang.MemberExpr, stmt), result_used), .ArraySubscriptExprClass => return transArrayAccess(rp, scope, @ptrCast(*const clang.ArraySubscriptExpr, stmt), result_used), .CallExprClass => return transCallExpr(rp, scope, @ptrCast(*const clang.CallExpr, stmt), result_used), .UnaryExprOrTypeTraitExprClass => return transUnaryExprOrTypeTraitExpr(rp, scope, @ptrCast(*const clang.UnaryExprOrTypeTraitExpr, stmt), result_used), .UnaryOperatorClass => return transUnaryOperator(rp, scope, @ptrCast(*const clang.UnaryOperator, stmt), result_used), .CompoundAssignOperatorClass => return transCompoundAssignOperator(rp, scope, @ptrCast(*const clang.CompoundAssignOperator, stmt), result_used), .OpaqueValueExprClass => { const source_expr = @ptrCast(*const clang.OpaqueValueExpr, stmt).getSourceExpr().?; const expr = try transExpr(rp, scope, source_expr, .used, lrvalue); if (expr.tag == .GroupedExpression) return maybeSuppressResult(rp, scope, result_used, expr); const node = try rp.c.arena.create(ast.Node.GroupedExpression); node.* = .{ .lparen = try appendToken(rp.c, .LParen, "("), .expr = expr, .rparen = try appendToken(rp.c, .RParen, ")"), }; return maybeSuppressResult(rp, scope, result_used, &node.base); }, else => { return revertAndWarn( rp, error.UnsupportedTranslation, stmt.getBeginLoc(), "TODO implement translation of stmt class {}", .{@tagName(sc)}, ); }, } } fn transBinaryOperator( rp: RestorePoint, scope: *Scope, stmt: *const clang.BinaryOperator, result_used: ResultUsed, ) TransError!*ast.Node { const op = stmt.getOpcode(); const qt = stmt.getType(); var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (op) { .Assign => return try transCreateNodeAssign(rp, scope, result_used, stmt.getLHS(), stmt.getRHS()), .Comma => { const block_scope = try scope.findBlockScope(rp.c); const expr = block_scope.base.parent == scope; const lparen = if (expr) try appendToken(rp.c, .LParen, "(") else undefined; const lhs = try transExpr(rp, &block_scope.base, stmt.getLHS(), .unused, .r_value); try block_scope.statements.append(lhs); const rhs = try transExpr(rp, &block_scope.base, stmt.getRHS(), .used, .r_value); if (expr) { _ = try appendToken(rp.c, .Semicolon, ";"); const break_node = try transCreateNodeBreak(rp.c, block_scope.label, rhs); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen, .expr = block_node, .rparen = rparen, }; return maybeSuppressResult(rp, scope, result_used, &grouped_expr.base); } else { return maybeSuppressResult(rp, scope, result_used, rhs); } }, .Div => { if (cIsSignedInteger(qt)) { // signed integer division uses @divTrunc const div_trunc_node = try rp.c.createBuiltinCall("@divTrunc", 2); div_trunc_node.params()[0] = try transExpr(rp, scope, stmt.getLHS(), .used, .l_value); _ = try appendToken(rp.c, .Comma, ","); const rhs = try transExpr(rp, scope, stmt.getRHS(), .used, .r_value); div_trunc_node.params()[1] = rhs; div_trunc_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, result_used, &div_trunc_node.base); } }, .Rem => { if (cIsSignedInteger(qt)) { // signed integer division uses @rem const rem_node = try rp.c.createBuiltinCall("@rem", 2); rem_node.params()[0] = try transExpr(rp, scope, stmt.getLHS(), .used, .l_value); _ = try appendToken(rp.c, .Comma, ","); const rhs = try transExpr(rp, scope, stmt.getRHS(), .used, .r_value); rem_node.params()[1] = rhs; rem_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, result_used, &rem_node.base); } }, .Shl => { const node = try transCreateNodeShiftOp(rp, scope, stmt, .BitShiftLeft, .AngleBracketAngleBracketLeft, "<<"); return maybeSuppressResult(rp, scope, result_used, node); }, .Shr => { const node = try transCreateNodeShiftOp(rp, scope, stmt, .BitShiftRight, .AngleBracketAngleBracketRight, ">>"); return maybeSuppressResult(rp, scope, result_used, node); }, .LAnd => { const node = try transCreateNodeBoolInfixOp(rp, scope, stmt, .BoolAnd, result_used, true); return maybeSuppressResult(rp, scope, result_used, node); }, .LOr => { const node = try transCreateNodeBoolInfixOp(rp, scope, stmt, .BoolOr, result_used, true); return maybeSuppressResult(rp, scope, result_used, node); }, else => {}, } const lhs_node = try transExpr(rp, scope, stmt.getLHS(), .used, .l_value); switch (op) { .Add => { if (cIsUnsignedInteger(qt)) { op_token = try appendToken(rp.c, .PlusPercent, "+%"); op_id = .AddWrap; } else { op_token = try appendToken(rp.c, .Plus, "+"); op_id = .Add; } }, .Sub => { if (cIsUnsignedInteger(qt)) { op_token = try appendToken(rp.c, .MinusPercent, "-%"); op_id = .SubWrap; } else { op_token = try appendToken(rp.c, .Minus, "-"); op_id = .Sub; } }, .Mul => { if (cIsUnsignedInteger(qt)) { op_token = try appendToken(rp.c, .AsteriskPercent, "*%"); op_id = .MulWrap; } else { op_token = try appendToken(rp.c, .Asterisk, "*"); op_id = .Mul; } }, .Div => { // unsigned/float division uses the operator op_id = .Div; op_token = try appendToken(rp.c, .Slash, "/"); }, .Rem => { // unsigned/float division uses the operator op_id = .Mod; op_token = try appendToken(rp.c, .Percent, "%"); }, .LT => { op_id = .LessThan; op_token = try appendToken(rp.c, .AngleBracketLeft, "<"); }, .GT => { op_id = .GreaterThan; op_token = try appendToken(rp.c, .AngleBracketRight, ">"); }, .LE => { op_id = .LessOrEqual; op_token = try appendToken(rp.c, .AngleBracketLeftEqual, "<="); }, .GE => { op_id = .GreaterOrEqual; op_token = try appendToken(rp.c, .AngleBracketRightEqual, ">="); }, .EQ => { op_id = .EqualEqual; op_token = try appendToken(rp.c, .EqualEqual, "=="); }, .NE => { op_id = .BangEqual; op_token = try appendToken(rp.c, .BangEqual, "!="); }, .And => { op_id = .BitAnd; op_token = try appendToken(rp.c, .Ampersand, "&"); }, .Xor => { op_id = .BitXor; op_token = try appendToken(rp.c, .Caret, "^"); }, .Or => { op_id = .BitOr; op_token = try appendToken(rp.c, .Pipe, "|"); }, else => unreachable, } const rhs_node = try transExpr(rp, scope, stmt.getRHS(), .used, .r_value); const lhs = if (isBoolRes(lhs_node)) init: { const cast_node = try rp.c.createBuiltinCall("@boolToInt", 1); cast_node.params()[0] = lhs_node; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); break :init &cast_node.base; } else lhs_node; const rhs = if (isBoolRes(rhs_node)) init: { const cast_node = try rp.c.createBuiltinCall("@boolToInt", 1); cast_node.params()[0] = rhs_node; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); break :init &cast_node.base; } else rhs_node; return transCreateNodeInfixOp(rp, scope, lhs, op_id, op_token, rhs, result_used, true); } fn transCompoundStmtInline( rp: RestorePoint, parent_scope: *Scope, stmt: *const clang.CompoundStmt, block: *Scope.Block, ) TransError!void { var it = stmt.body_begin(); const end_it = stmt.body_end(); while (it != end_it) : (it += 1) { const result = try transStmt(rp, parent_scope, it[0], .unused, .r_value); try block.statements.append(result); } } fn transCompoundStmt(rp: RestorePoint, scope: *Scope, stmt: *const clang.CompoundStmt) TransError!*ast.Node { var block_scope = try Scope.Block.init(rp.c, scope, false); defer block_scope.deinit(); try transCompoundStmtInline(rp, &block_scope.base, stmt, &block_scope); return try block_scope.complete(rp.c); } fn transCStyleCastExprClass( rp: RestorePoint, scope: *Scope, stmt: *const clang.CStyleCastExpr, result_used: ResultUsed, lrvalue: LRValue, ) TransError!*ast.Node { const sub_expr = stmt.getSubExpr(); const cast_node = (try transCCast( rp, scope, stmt.getBeginLoc(), stmt.getType(), sub_expr.getType(), try transExpr(rp, scope, sub_expr, .used, lrvalue), )); return maybeSuppressResult(rp, scope, result_used, cast_node); } fn transDeclStmtOne( rp: RestorePoint, scope: *Scope, decl: *const clang.Decl, block_scope: *Scope.Block, ) TransError!*ast.Node { const c = rp.c; switch (decl.getKind()) { .Var => { const var_decl = @ptrCast(*const clang.VarDecl, decl); const qual_type = var_decl.getTypeSourceInfo_getType(); const name = try c.str(@ptrCast(*const clang.NamedDecl, var_decl).getName_bytes_begin()); const mangled_name = try block_scope.makeMangledName(c, name); switch (var_decl.getStorageClass()) { .Extern, .Static => { // This is actually a global variable, put it in the global scope and reference it. // `_ = mangled_name;` try visitVarDecl(rp.c, var_decl, mangled_name); return try maybeSuppressResult(rp, scope, .unused, try transCreateNodeIdentifier(rp.c, mangled_name)); }, else => {}, } const mut_tok = if (qual_type.isConstQualified()) try appendToken(c, .Keyword_const, "const") else try appendToken(c, .Keyword_var, "var"); const name_tok = try appendIdentifier(c, mangled_name); _ = try appendToken(c, .Colon, ":"); const loc = decl.getLocation(); const type_node = try transQualType(rp, qual_type, loc); const eq_token = try appendToken(c, .Equal, "="); var init_node = if (var_decl.getInit()) |expr| try transExprCoercing(rp, scope, expr, .used, .r_value) else try transCreateNodeUndefinedLiteral(c); if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node)) { const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = init_node; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); init_node = &builtin_node.base; } const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .type_node = type_node, .init_node = init_node, }); return &node.base; }, .Typedef => { const typedef_decl = @ptrCast(*const clang.TypedefNameDecl, decl); const name = try c.str(@ptrCast(*const clang.NamedDecl, typedef_decl).getName_bytes_begin()); const underlying_qual = typedef_decl.getUnderlyingType(); const underlying_type = underlying_qual.getTypePtr(); const mangled_name = try block_scope.makeMangledName(c, name); const node = (try transCreateNodeTypedef(rp, typedef_decl, false, mangled_name)) orelse return error.UnsupportedTranslation; return node; }, else => |kind| return revertAndWarn( rp, error.UnsupportedTranslation, decl.getLocation(), "TODO implement translation of DeclStmt kind {}", .{@tagName(kind)}, ), } } fn transDeclStmt(rp: RestorePoint, scope: *Scope, stmt: *const clang.DeclStmt) TransError!*ast.Node { const block_scope = scope.findBlockScope(rp.c) catch unreachable; var it = stmt.decl_begin(); const end_it = stmt.decl_end(); assert(it != end_it); while (true) : (it += 1) { const node = try transDeclStmtOne(rp, scope, it[0], block_scope); if (it + 1 == end_it) { return node; } else { try block_scope.statements.append(node); } } unreachable; } fn transDeclRefExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.DeclRefExpr, lrvalue: LRValue, ) TransError!*ast.Node { const value_decl = expr.getDecl(); const name = try rp.c.str(@ptrCast(*const clang.NamedDecl, value_decl).getName_bytes_begin()); const mangled_name = scope.getAlias(name); return transCreateNodeIdentifier(rp.c, mangled_name); } fn transImplicitCastExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.ImplicitCastExpr, result_used: ResultUsed, ) TransError!*ast.Node { const c = rp.c; const sub_expr = expr.getSubExpr(); const dest_type = getExprQualType(c, @ptrCast(*const clang.Expr, expr)); const src_type = getExprQualType(c, sub_expr); switch (expr.getCastKind()) { .BitCast, .FloatingCast, .FloatingToIntegral, .IntegralToFloating, .IntegralCast, .PointerToIntegral, .IntegralToPointer => { const sub_expr_node = try transExpr(rp, scope, sub_expr, .used, .r_value); return try transCCast(rp, scope, expr.getBeginLoc(), dest_type, src_type, sub_expr_node); }, .LValueToRValue, .NoOp, .FunctionToPointerDecay => { const sub_expr_node = try transExpr(rp, scope, sub_expr, .used, .r_value); return maybeSuppressResult(rp, scope, result_used, sub_expr_node); }, .ArrayToPointerDecay => { if (exprIsStringLiteral(sub_expr)) { const sub_expr_node = try transExpr(rp, scope, sub_expr, .used, .r_value); return maybeSuppressResult(rp, scope, result_used, sub_expr_node); } const prefix_op = try transCreateNodeSimplePrefixOp(rp.c, .AddressOf, .Ampersand, "&"); prefix_op.rhs = try transExpr(rp, scope, sub_expr, .used, .r_value); return maybeSuppressResult(rp, scope, result_used, &prefix_op.base); }, .NullToPointer => { return try transCreateNodeNullLiteral(rp.c); }, .PointerToBoolean => { // @ptrToInt(val) != 0 const ptr_to_int = try rp.c.createBuiltinCall("@ptrToInt", 1); ptr_to_int.params()[0] = try transExpr(rp, scope, sub_expr, .used, .r_value); ptr_to_int.rparen_token = try appendToken(rp.c, .RParen, ")"); const op_token = try appendToken(rp.c, .BangEqual, "!="); const rhs_node = try transCreateNodeInt(rp.c, 0); return transCreateNodeInfixOp(rp, scope, &ptr_to_int.base, .BangEqual, op_token, rhs_node, result_used, false); }, .IntegralToBoolean => { const sub_expr_node = try transExpr(rp, scope, sub_expr, .used, .r_value); // The expression is already a boolean one, return it as-is if (isBoolRes(sub_expr_node)) return sub_expr_node; // val != 0 const op_token = try appendToken(rp.c, .BangEqual, "!="); const rhs_node = try transCreateNodeInt(rp.c, 0); return transCreateNodeInfixOp(rp, scope, sub_expr_node, .BangEqual, op_token, rhs_node, result_used, false); }, .BuiltinFnToFnPtr => { return transExpr(rp, scope, sub_expr, .used, .r_value); }, else => |kind| return revertAndWarn( rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, expr).getBeginLoc(), "TODO implement translation of CastKind {}", .{@tagName(kind)}, ), } } fn transBoolExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.Expr, used: ResultUsed, lrvalue: LRValue, grouped: bool, ) TransError!*ast.Node { if (@ptrCast(*const clang.Stmt, expr).getStmtClass() == .IntegerLiteralClass) { var is_zero: bool = undefined; if (!(@ptrCast(*const clang.IntegerLiteral, expr).isZero(&is_zero, rp.c.clang_context))) { return revertAndWarn(rp, error.UnsupportedTranslation, expr.getBeginLoc(), "invalid integer literal", .{}); } return try transCreateNodeBoolLiteral(rp.c, !is_zero); } const lparen = if (grouped) try appendToken(rp.c, .LParen, "(") else undefined; var res = try transExpr(rp, scope, expr, used, lrvalue); if (isBoolRes(res)) { if (!grouped and res.tag == .GroupedExpression) { const group = @fieldParentPtr(ast.Node.GroupedExpression, "base", res); res = group.expr; // get zig fmt to work properly tokenSlice(rp.c, group.lparen)[0] = ')'; } return res; } const ty = getExprQualType(rp.c, expr).getTypePtr(); const node = try finishBoolExpr(rp, scope, expr.getBeginLoc(), ty, res, used); if (grouped) { const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen, .expr = node, .rparen = rparen, }; return maybeSuppressResult(rp, scope, used, &grouped_expr.base); } else { return maybeSuppressResult(rp, scope, used, node); } } fn exprIsBooleanType(expr: *const clang.Expr) bool { return qualTypeIsBoolean(expr.getType()); } fn exprIsStringLiteral(expr: *const clang.Expr) bool { switch (expr.getStmtClass()) { .StringLiteralClass => return true, .PredefinedExprClass => return true, .UnaryOperatorClass => { const op_expr = @ptrCast(*const clang.UnaryOperator, expr).getSubExpr(); return exprIsStringLiteral(op_expr); }, .ParenExprClass => { const op_expr = @ptrCast(*const clang.ParenExpr, expr).getSubExpr(); return exprIsStringLiteral(op_expr); }, else => return false, } } fn isBoolRes(res: *ast.Node) bool { switch (res.tag) { .BoolOr, .BoolAnd, .EqualEqual, .BangEqual, .LessThan, .GreaterThan, .LessOrEqual, .GreaterOrEqual, .BoolNot, .BoolLiteral, => return true, .GroupedExpression => return isBoolRes(@fieldParentPtr(ast.Node.GroupedExpression, "base", res).expr), else => return false, } } fn finishBoolExpr( rp: RestorePoint, scope: *Scope, loc: clang.SourceLocation, ty: *const clang.Type, node: *ast.Node, used: ResultUsed, ) TransError!*ast.Node { switch (ty.getTypeClass()) { .Builtin => { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); switch (builtin_ty.getKind()) { .Bool => return node, .Char_U, .UChar, .Char_S, .SChar, .UShort, .UInt, .ULong, .ULongLong, .Short, .Int, .Long, .LongLong, .UInt128, .Int128, .Float, .Double, .Float128, .LongDouble, .WChar_U, .Char8, .Char16, .Char32, .WChar_S, .Float16, => { const op_token = try appendToken(rp.c, .BangEqual, "!="); const rhs_node = try transCreateNodeInt(rp.c, 0); return transCreateNodeInfixOp(rp, scope, node, .BangEqual, op_token, rhs_node, used, false); }, .NullPtr => { const op_token = try appendToken(rp.c, .EqualEqual, "=="); const rhs_node = try transCreateNodeNullLiteral(rp.c); return transCreateNodeInfixOp(rp, scope, node, .EqualEqual, op_token, rhs_node, used, false); }, else => {}, } }, .Pointer => { const op_token = try appendToken(rp.c, .BangEqual, "!="); const rhs_node = try transCreateNodeNullLiteral(rp.c); return transCreateNodeInfixOp(rp, scope, node, .BangEqual, op_token, rhs_node, used, false); }, .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); const underlying_type = typedef_decl.getUnderlyingType(); return finishBoolExpr(rp, scope, loc, underlying_type.getTypePtr(), node, used); }, .Enum => { const op_token = try appendToken(rp.c, .BangEqual, "!="); const rhs_node = try transCreateNodeInt(rp.c, 0); return transCreateNodeInfixOp(rp, scope, node, .BangEqual, op_token, rhs_node, used, false); }, .Elaborated => { const elaborated_ty = @ptrCast(*const clang.ElaboratedType, ty); const named_type = elaborated_ty.getNamedType(); return finishBoolExpr(rp, scope, loc, named_type.getTypePtr(), node, used); }, else => {}, } return revertAndWarn(rp, error.UnsupportedType, loc, "unsupported bool expression type", .{}); } const SuppressCast = enum { with_as, no_as, }; fn transIntegerLiteral( rp: RestorePoint, scope: *Scope, expr: *const clang.IntegerLiteral, result_used: ResultUsed, suppress_as: SuppressCast, ) TransError!*ast.Node { var eval_result: clang.ExprEvalResult = undefined; if (!expr.EvaluateAsInt(&eval_result, rp.c.clang_context)) { const loc = expr.getBeginLoc(); return revertAndWarn(rp, error.UnsupportedTranslation, loc, "invalid integer literal", .{}); } if (suppress_as == .no_as) { const int_lit_node = try transCreateNodeAPInt(rp.c, eval_result.Val.getInt()); return maybeSuppressResult(rp, scope, result_used, int_lit_node); } // Integer literals in C have types, and this can matter for several reasons. // For example, this is valid C: // unsigned char y = 256; // How this gets evaluated is the 256 is an integer, which gets truncated to signed char, then bit-casted // to unsigned char, resulting in 0. In order for this to work, we have to emit this zig code: // var y = @bitCast(u8, @truncate(i8, @as(c_int, 256))); // Ideally in translate-c we could flatten this out to simply: // var y: u8 = 0; // But the first step is to be correct, and the next step is to make the output more elegant. // @as(T, x) const expr_base = @ptrCast(*const clang.Expr, expr); const as_node = try rp.c.createBuiltinCall("@as", 2); const ty_node = try transQualType(rp, expr_base.getType(), expr_base.getBeginLoc()); as_node.params()[0] = ty_node; _ = try appendToken(rp.c, .Comma, ","); as_node.params()[1] = try transCreateNodeAPInt(rp.c, eval_result.Val.getInt()); as_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, result_used, &as_node.base); } fn transReturnStmt( rp: RestorePoint, scope: *Scope, expr: *const clang.ReturnStmt, ) TransError!*ast.Node { const return_kw = try appendToken(rp.c, .Keyword_return, "return"); const rhs: ?*ast.Node = if (expr.getRetValue()) |val_expr| try transExprCoercing(rp, scope, val_expr, .used, .r_value) else null; const return_expr = try ast.Node.ControlFlowExpression.create(rp.c.arena, .{ .ltoken = return_kw, .tag = .Return, }, .{ .rhs = rhs, }); _ = try appendToken(rp.c, .Semicolon, ";"); return &return_expr.base; } fn transStringLiteral( rp: RestorePoint, scope: *Scope, stmt: *const clang.StringLiteral, result_used: ResultUsed, ) TransError!*ast.Node { const kind = stmt.getKind(); switch (kind) { .Ascii, .UTF8 => { var len: usize = undefined; const bytes_ptr = stmt.getString_bytes_begin_size(&len); const str = bytes_ptr[0..len]; const token = try appendTokenFmt(rp.c, .StringLiteral, "\"{Z}\"", .{str}); const node = try rp.c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .StringLiteral }, .token = token, }; return maybeSuppressResult(rp, scope, result_used, &node.base); }, .UTF16, .UTF32, .Wide => return revertAndWarn( rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), "TODO: support string literal kind {}", .{kind}, ), } } fn cIsEnum(qt: clang.QualType) bool { return qt.getCanonicalType().getTypeClass() == .Enum; } /// Get the underlying int type of an enum. The C compiler chooses a signed int /// type that is large enough to hold all of the enum's values. It is not required /// to be the smallest possible type that can hold all the values. fn cIntTypeForEnum(enum_qt: clang.QualType) clang.QualType { assert(cIsEnum(enum_qt)); const ty = enum_qt.getCanonicalType().getTypePtr(); const enum_ty = @ptrCast(*const clang.EnumType, ty); const enum_decl = enum_ty.getDecl(); return enum_decl.getIntegerType(); } fn transCCast( rp: RestorePoint, scope: *Scope, loc: clang.SourceLocation, dst_type: clang.QualType, src_type: clang.QualType, expr: *ast.Node, ) !*ast.Node { if (qualTypeCanon(dst_type).isVoidType()) return expr; if (dst_type.eq(src_type)) return expr; if (qualTypeIsPtr(dst_type) and qualTypeIsPtr(src_type)) return transCPtrCast(rp, loc, dst_type, src_type, expr); if (cIsInteger(dst_type) and (cIsInteger(src_type) or cIsEnum(src_type))) { // 1. If src_type is an enum, determine the underlying signed int type // 2. Extend or truncate without changing signed-ness. // 3. Bit-cast to correct signed-ness const src_type_is_signed = cIsSignedInteger(src_type) or cIsEnum(src_type); const src_int_type = if (cIsInteger(src_type)) src_type else cIntTypeForEnum(src_type); const src_int_expr = if (cIsInteger(src_type)) expr else try transEnumToInt(rp.c, expr); // @bitCast(dest_type, intermediate_value) const cast_node = try rp.c.createBuiltinCall("@bitCast", 2); cast_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); switch (cIntTypeCmp(dst_type, src_int_type)) { .lt => { // @truncate(SameSignSmallerInt, src_int_expr) const trunc_node = try rp.c.createBuiltinCall("@truncate", 2); const ty_node = try transQualTypeIntWidthOf(rp.c, dst_type, src_type_is_signed); trunc_node.params()[0] = ty_node; _ = try appendToken(rp.c, .Comma, ","); trunc_node.params()[1] = src_int_expr; trunc_node.rparen_token = try appendToken(rp.c, .RParen, ")"); cast_node.params()[1] = &trunc_node.base; }, .gt => { // @as(SameSignBiggerInt, src_int_expr) const as_node = try rp.c.createBuiltinCall("@as", 2); const ty_node = try transQualTypeIntWidthOf(rp.c, dst_type, src_type_is_signed); as_node.params()[0] = ty_node; _ = try appendToken(rp.c, .Comma, ","); as_node.params()[1] = src_int_expr; as_node.rparen_token = try appendToken(rp.c, .RParen, ")"); cast_node.params()[1] = &as_node.base; }, .eq => { cast_node.params()[1] = src_int_expr; }, } cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } if (cIsInteger(dst_type) and qualTypeIsPtr(src_type)) { // @intCast(dest_type, @ptrToInt(val)) const cast_node = try rp.c.createBuiltinCall("@intCast", 2); cast_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); const builtin_node = try rp.c.createBuiltinCall("@ptrToInt", 1); builtin_node.params()[0] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); cast_node.params()[1] = &builtin_node.base; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } if (cIsInteger(src_type) and qualTypeIsPtr(dst_type)) { // @intToPtr(dest_type, val) const builtin_node = try rp.c.createBuiltinCall("@intToPtr", 2); builtin_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } if (cIsFloating(src_type) and cIsFloating(dst_type)) { const builtin_node = try rp.c.createBuiltinCall("@floatCast", 2); builtin_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } if (cIsFloating(src_type) and !cIsFloating(dst_type)) { const builtin_node = try rp.c.createBuiltinCall("@floatToInt", 2); builtin_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } if (!cIsFloating(src_type) and cIsFloating(dst_type)) { const builtin_node = try rp.c.createBuiltinCall("@intToFloat", 2); builtin_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } if (qualTypeIsBoolean(src_type) and !qualTypeIsBoolean(dst_type)) { // @boolToInt returns either a comptime_int or a u1 const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); const inner_cast_node = try rp.c.createBuiltinCall("@intCast", 2); inner_cast_node.params()[0] = try transCreateNodeIdentifier(rp.c, "u1"); _ = try appendToken(rp.c, .Comma, ","); inner_cast_node.params()[1] = &builtin_node.base; inner_cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); const cast_node = try rp.c.createBuiltinCall("@intCast", 2); cast_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); if (cIsSignedInteger(dst_type)) { const bitcast_node = try rp.c.createBuiltinCall("@bitCast", 2); bitcast_node.params()[0] = try transCreateNodeIdentifier(rp.c, "i1"); _ = try appendToken(rp.c, .Comma, ","); bitcast_node.params()[1] = &inner_cast_node.base; bitcast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); cast_node.params()[1] = &bitcast_node.base; } else { cast_node.params()[1] = &inner_cast_node.base; } cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } if (cIsEnum(dst_type)) { const builtin_node = try rp.c.createBuiltinCall("@intToEnum", 2); builtin_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &builtin_node.base; } if (cIsEnum(src_type) and !cIsEnum(dst_type)) { return transEnumToInt(rp.c, expr); } const cast_node = try rp.c.createBuiltinCall("@as", 2); cast_node.params()[0] = try transQualType(rp, dst_type, loc); _ = try appendToken(rp.c, .Comma, ","); cast_node.params()[1] = expr; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &cast_node.base; } fn transEnumToInt(c: *Context, enum_expr: *ast.Node) TypeError!*ast.Node { const builtin_node = try c.createBuiltinCall("@enumToInt", 1); builtin_node.params()[0] = enum_expr; builtin_node.rparen_token = try appendToken(c, .RParen, ")"); return &builtin_node.base; } fn transExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.Expr, used: ResultUsed, lrvalue: LRValue, ) TransError!*ast.Node { return transStmt(rp, scope, @ptrCast(*const clang.Stmt, expr), used, lrvalue); } /// Same as `transExpr` but with the knowledge that the operand will be type coerced, and therefore /// an `@as` would be redundant. This is used to prevent redundant `@as` in integer literals. fn transExprCoercing( rp: RestorePoint, scope: *Scope, expr: *const clang.Expr, used: ResultUsed, lrvalue: LRValue, ) TransError!*ast.Node { switch (@ptrCast(*const clang.Stmt, expr).getStmtClass()) { .IntegerLiteralClass => { return transIntegerLiteral(rp, scope, @ptrCast(*const clang.IntegerLiteral, expr), .used, .no_as); }, .CharacterLiteralClass => { return transCharLiteral(rp, scope, @ptrCast(*const clang.CharacterLiteral, expr), .used, .no_as); }, .UnaryOperatorClass => { const un_expr = @ptrCast(*const clang.UnaryOperator, expr); if (un_expr.getOpcode() == .Extension) { return transExprCoercing(rp, scope, un_expr.getSubExpr(), used, lrvalue); } }, else => {}, } return transExpr(rp, scope, expr, .used, .r_value); } fn transInitListExprRecord( rp: RestorePoint, scope: *Scope, loc: clang.SourceLocation, expr: *const clang.InitListExpr, ty: *const clang.Type, used: ResultUsed, ) TransError!*ast.Node { var is_union_type = false; // Unions and Structs are both represented as RecordDecl const record_ty = ty.getAsRecordType() orelse blk: { is_union_type = true; break :blk ty.getAsUnionType(); } orelse unreachable; const record_decl = record_ty.getDecl(); const record_def = record_decl.getDefinition() orelse unreachable; const ty_node = try transType(rp, ty, loc); const init_count = expr.getNumInits(); var field_inits = std.ArrayList(*ast.Node).init(rp.c.gpa); defer field_inits.deinit(); _ = try appendToken(rp.c, .LBrace, "{"); var init_i: c_uint = 0; var it = record_def.field_begin(); const end_it = record_def.field_end(); while (it.neq(end_it)) : (it = it.next()) { const field_decl = it.deref(); // The initializer for a union type has a single entry only if (is_union_type and field_decl != expr.getInitializedFieldInUnion()) { continue; } assert(init_i < init_count); const elem_expr = expr.getInit(init_i); init_i += 1; // Generate the field assignment expression: // .field_name = expr const period_tok = try appendToken(rp.c, .Period, "."); var raw_name = try rp.c.str(@ptrCast(*const clang.NamedDecl, field_decl).getName_bytes_begin()); if (field_decl.isAnonymousStructOrUnion()) { const name = rp.c.decl_table.get(@ptrToInt(field_decl.getCanonicalDecl())).?; raw_name = try mem.dupe(rp.c.arena, u8, name); } const field_name_tok = try appendIdentifier(rp.c, raw_name); _ = try appendToken(rp.c, .Equal, "="); const field_init_node = try rp.c.arena.create(ast.Node.FieldInitializer); field_init_node.* = .{ .period_token = period_tok, .name_token = field_name_tok, .expr = try transExpr(rp, scope, elem_expr, .used, .r_value), }; try field_inits.append(&field_init_node.base); _ = try appendToken(rp.c, .Comma, ","); } const node = try ast.Node.StructInitializer.alloc(rp.c.arena, field_inits.items.len); node.* = .{ .lhs = ty_node, .rtoken = try appendToken(rp.c, .RBrace, "}"), .list_len = field_inits.items.len, }; mem.copy(*ast.Node, node.list(), field_inits.items); return &node.base; } fn transCreateNodeArrayType( rp: RestorePoint, source_loc: clang.SourceLocation, ty: *const clang.Type, len: anytype, ) !*ast.Node { const node = try rp.c.arena.create(ast.Node.ArrayType); const op_token = try appendToken(rp.c, .LBracket, "["); const len_expr = try transCreateNodeInt(rp.c, len); _ = try appendToken(rp.c, .RBracket, "]"); node.* = .{ .op_token = op_token, .rhs = try transType(rp, ty, source_loc), .len_expr = len_expr, }; return &node.base; } fn transInitListExprArray( rp: RestorePoint, scope: *Scope, loc: clang.SourceLocation, expr: *const clang.InitListExpr, ty: *const clang.Type, used: ResultUsed, ) TransError!*ast.Node { const arr_type = ty.getAsArrayTypeUnsafe(); const child_qt = arr_type.getElementType(); const init_count = expr.getNumInits(); assert(@ptrCast(*const clang.Type, arr_type).isConstantArrayType()); const const_arr_ty = @ptrCast(*const clang.ConstantArrayType, arr_type); const size_ap_int = const_arr_ty.getSize(); const all_count = size_ap_int.getLimitedValue(math.maxInt(usize)); const leftover_count = all_count - init_count; var init_node: *ast.Node.ArrayInitializer = undefined; var cat_tok: ast.TokenIndex = undefined; if (init_count != 0) { const ty_node = try transCreateNodeArrayType( rp, loc, child_qt.getTypePtr(), init_count, ); _ = try appendToken(rp.c, .LBrace, "{"); init_node = try ast.Node.ArrayInitializer.alloc(rp.c.arena, init_count); init_node.* = .{ .lhs = ty_node, .rtoken = undefined, .list_len = init_count, }; const init_list = init_node.list(); var i: c_uint = 0; while (i < init_count) : (i += 1) { const elem_expr = expr.getInit(i); init_list[i] = try transExpr(rp, scope, elem_expr, .used, .r_value); _ = try appendToken(rp.c, .Comma, ","); } init_node.rtoken = try appendToken(rp.c, .RBrace, "}"); if (leftover_count == 0) { return &init_node.base; } cat_tok = try appendToken(rp.c, .PlusPlus, "++"); } const ty_node = try transCreateNodeArrayType(rp, loc, child_qt.getTypePtr(), 1); _ = try appendToken(rp.c, .LBrace, "{"); const filler_init_node = try ast.Node.ArrayInitializer.alloc(rp.c.arena, 1); filler_init_node.* = .{ .lhs = ty_node, .rtoken = undefined, .list_len = 1, }; const filler_val_expr = expr.getArrayFiller(); filler_init_node.list()[0] = try transExpr(rp, scope, filler_val_expr, .used, .r_value); filler_init_node.rtoken = try appendToken(rp.c, .RBrace, "}"); const rhs_node = if (leftover_count == 1) &filler_init_node.base else blk: { const mul_tok = try appendToken(rp.c, .AsteriskAsterisk, "**"); const mul_node = try rp.c.arena.create(ast.Node.SimpleInfixOp); mul_node.* = .{ .base = .{ .tag = .ArrayMult }, .op_token = mul_tok, .lhs = &filler_init_node.base, .rhs = try transCreateNodeInt(rp.c, leftover_count), }; break :blk &mul_node.base; }; if (init_count == 0) { return rhs_node; } const cat_node = try rp.c.arena.create(ast.Node.SimpleInfixOp); cat_node.* = .{ .base = .{ .tag = .ArrayCat }, .op_token = cat_tok, .lhs = &init_node.base, .rhs = rhs_node, }; return &cat_node.base; } fn transInitListExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.InitListExpr, used: ResultUsed, ) TransError!*ast.Node { const qt = getExprQualType(rp.c, @ptrCast(*const clang.Expr, expr)); var qual_type = qt.getTypePtr(); const source_loc = @ptrCast(*const clang.Expr, expr).getBeginLoc(); if (qual_type.isRecordType()) { return transInitListExprRecord( rp, scope, source_loc, expr, qual_type, used, ); } else if (qual_type.isArrayType()) { return transInitListExprArray( rp, scope, source_loc, expr, qual_type, used, ); } else { const type_name = rp.c.str(qual_type.getTypeClassName()); return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported initlist type: '{}'", .{type_name}); } } fn transZeroInitExpr( rp: RestorePoint, scope: *Scope, source_loc: clang.SourceLocation, ty: *const clang.Type, ) TransError!*ast.Node { switch (ty.getTypeClass()) { .Builtin => { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); switch (builtin_ty.getKind()) { .Bool => return try transCreateNodeBoolLiteral(rp.c, false), .Char_U, .UChar, .Char_S, .Char8, .SChar, .UShort, .UInt, .ULong, .ULongLong, .Short, .Int, .Long, .LongLong, .UInt128, .Int128, .Float, .Double, .Float128, .Float16, .LongDouble, => return transCreateNodeInt(rp.c, 0), else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported builtin type", .{}), } }, .Pointer => return transCreateNodeNullLiteral(rp.c), .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); return transZeroInitExpr( rp, scope, source_loc, typedef_decl.getUnderlyingType().getTypePtr(), ); }, else => {}, } return revertAndWarn(rp, error.UnsupportedType, source_loc, "type does not have an implicit init value", .{}); } fn transImplicitValueInitExpr( rp: RestorePoint, scope: *Scope, expr: *const clang.Expr, used: ResultUsed, ) TransError!*ast.Node { const source_loc = expr.getBeginLoc(); const qt = getExprQualType(rp.c, expr); const ty = qt.getTypePtr(); return transZeroInitExpr(rp, scope, source_loc, ty); } fn transIfStmt( rp: RestorePoint, scope: *Scope, stmt: *const clang.IfStmt, ) TransError!*ast.Node { // if (c) t // if (c) t else e const if_node = try transCreateNodeIf(rp.c); var cond_scope = Scope.Condition{ .base = .{ .parent = scope, .id = .Condition, }, }; defer cond_scope.deinit(); const cond_expr = @ptrCast(*const clang.Expr, stmt.getCond()); if_node.condition = try transBoolExpr(rp, &cond_scope.base, cond_expr, .used, .r_value, false); _ = try appendToken(rp.c, .RParen, ")"); if_node.body = try transStmt(rp, scope, stmt.getThen(), .unused, .r_value); if (stmt.getElse()) |expr| { if_node.@"else" = try transCreateNodeElse(rp.c); if_node.@"else".?.body = try transStmt(rp, scope, expr, .unused, .r_value); } _ = try appendToken(rp.c, .Semicolon, ";"); return &if_node.base; } fn transWhileLoop( rp: RestorePoint, scope: *Scope, stmt: *const clang.WhileStmt, ) TransError!*ast.Node { const while_node = try transCreateNodeWhile(rp.c); var cond_scope = Scope.Condition{ .base = .{ .parent = scope, .id = .Condition, }, }; defer cond_scope.deinit(); const cond_expr = @ptrCast(*const clang.Expr, stmt.getCond()); while_node.condition = try transBoolExpr(rp, &cond_scope.base, cond_expr, .used, .r_value, false); _ = try appendToken(rp.c, .RParen, ")"); var loop_scope = Scope{ .parent = scope, .id = .Loop, }; while_node.body = try transStmt(rp, &loop_scope, stmt.getBody(), .unused, .r_value); _ = try appendToken(rp.c, .Semicolon, ";"); return &while_node.base; } fn transDoWhileLoop( rp: RestorePoint, scope: *Scope, stmt: *const clang.DoStmt, ) TransError!*ast.Node { const while_node = try transCreateNodeWhile(rp.c); while_node.condition = try transCreateNodeBoolLiteral(rp.c, true); _ = try appendToken(rp.c, .RParen, ")"); var new = false; var loop_scope = Scope{ .parent = scope, .id = .Loop, }; // if (!cond) break; const if_node = try transCreateNodeIf(rp.c); var cond_scope = Scope.Condition{ .base = .{ .parent = scope, .id = .Condition, }, }; defer cond_scope.deinit(); const prefix_op = try transCreateNodeSimplePrefixOp(rp.c, .BoolNot, .Bang, "!"); prefix_op.rhs = try transBoolExpr(rp, &cond_scope.base, @ptrCast(*const clang.Expr, stmt.getCond()), .used, .r_value, true); _ = try appendToken(rp.c, .RParen, ")"); if_node.condition = &prefix_op.base; if_node.body = &(try transCreateNodeBreak(rp.c, null, null)).base; _ = try appendToken(rp.c, .Semicolon, ";"); const body_node = if (stmt.getBody().getStmtClass() == .CompoundStmtClass) blk: { // there's already a block in C, so we'll append our condition to it. // c: do { // c: a; // c: b; // c: } while(c); // zig: while (true) { // zig: a; // zig: b; // zig: if (!cond) break; // zig: } const node = try transStmt(rp, &loop_scope, stmt.getBody(), .unused, .r_value); break :blk node.castTag(.Block).?; } else blk: { // the C statement is without a block, so we need to create a block to contain it. // c: do // c: a; // c: while(c); // zig: while (true) { // zig: a; // zig: if (!cond) break; // zig: } new = true; const block = try rp.c.createBlock(2); block.statements_len = 1; // over-allocated so we can add another below block.statements()[0] = try transStmt(rp, &loop_scope, stmt.getBody(), .unused, .r_value); break :blk block; }; // In both cases above, we reserved 1 extra statement. body_node.statements_len += 1; body_node.statements()[body_node.statements_len - 1] = &if_node.base; if (new) body_node.rbrace = try appendToken(rp.c, .RBrace, "}"); while_node.body = &body_node.base; return &while_node.base; } fn transForLoop( rp: RestorePoint, scope: *Scope, stmt: *const clang.ForStmt, ) TransError!*ast.Node { var loop_scope = Scope{ .parent = scope, .id = .Loop, }; var block_scope: ?Scope.Block = null; defer if (block_scope) |*bs| bs.deinit(); if (stmt.getInit()) |init| { block_scope = try Scope.Block.init(rp.c, scope, false); loop_scope.parent = &block_scope.?.base; const init_node = try transStmt(rp, &block_scope.?.base, init, .unused, .r_value); try block_scope.?.statements.append(init_node); } var cond_scope = Scope.Condition{ .base = .{ .parent = &loop_scope, .id = .Condition, }, }; defer cond_scope.deinit(); const while_node = try transCreateNodeWhile(rp.c); while_node.condition = if (stmt.getCond()) |cond| try transBoolExpr(rp, &cond_scope.base, cond, .used, .r_value, false) else try transCreateNodeBoolLiteral(rp.c, true); _ = try appendToken(rp.c, .RParen, ")"); if (stmt.getInc()) |incr| { _ = try appendToken(rp.c, .Colon, ":"); _ = try appendToken(rp.c, .LParen, "("); while_node.continue_expr = try transExpr(rp, &cond_scope.base, incr, .unused, .r_value); _ = try appendToken(rp.c, .RParen, ")"); } while_node.body = try transStmt(rp, &loop_scope, stmt.getBody(), .unused, .r_value); if (block_scope) |*bs| { try bs.statements.append(&while_node.base); return try bs.complete(rp.c); } else { _ = try appendToken(rp.c, .Semicolon, ";"); return &while_node.base; } } fn getSwitchCaseCount(stmt: *const clang.SwitchStmt) usize { const body = stmt.getBody(); assert(body.getStmtClass() == .CompoundStmtClass); const comp = @ptrCast(*const clang.CompoundStmt, body); // TODO https://github.com/ziglang/zig/issues/1738 // return comp.body_end() - comp.body_begin(); const start_addr = @ptrToInt(comp.body_begin()); const end_addr = @ptrToInt(comp.body_end()); return (end_addr - start_addr) / @sizeOf(*clang.Stmt); } fn transSwitch( rp: RestorePoint, scope: *Scope, stmt: *const clang.SwitchStmt, ) TransError!*ast.Node { const switch_tok = try appendToken(rp.c, .Keyword_switch, "switch"); _ = try appendToken(rp.c, .LParen, "("); const cases_len = getSwitchCaseCount(stmt); var cond_scope = Scope.Condition{ .base = .{ .parent = scope, .id = .Condition, }, }; defer cond_scope.deinit(); const switch_expr = try transExpr(rp, &cond_scope.base, stmt.getCond(), .used, .r_value); _ = try appendToken(rp.c, .RParen, ")"); _ = try appendToken(rp.c, .LBrace, "{"); // reserve +1 case in case there is no default case const switch_node = try ast.Node.Switch.alloc(rp.c.arena, cases_len + 1); switch_node.* = .{ .switch_token = switch_tok, .expr = switch_expr, .cases_len = cases_len + 1, .rbrace = try appendToken(rp.c, .RBrace, "}"), }; var switch_scope = Scope.Switch{ .base = .{ .id = .Switch, .parent = scope, }, .cases = switch_node.cases(), .case_index = 0, .pending_block = undefined, .default_label = null, .switch_label = null, }; // tmp block that all statements will go before being picked up by a case or default var block_scope = try Scope.Block.init(rp.c, &switch_scope.base, false); defer block_scope.deinit(); // Note that we do not defer a deinit here; the switch_scope.pending_block field // has its own memory management. This resource is freed inside `transCase` and // then the final pending_block is freed at the bottom of this function with // pending_block.deinit(). switch_scope.pending_block = try Scope.Block.init(rp.c, scope, false); try switch_scope.pending_block.statements.append(&switch_node.base); const last = try transStmt(rp, &block_scope.base, stmt.getBody(), .unused, .r_value); _ = try appendToken(rp.c, .Semicolon, ";"); // take all pending statements const last_block_stmts = last.cast(ast.Node.Block).?.statements(); try switch_scope.pending_block.statements.ensureCapacity( switch_scope.pending_block.statements.items.len + last_block_stmts.len, ); for (last_block_stmts) |n| { switch_scope.pending_block.statements.appendAssumeCapacity(n); } if (switch_scope.default_label == null) { switch_scope.switch_label = try block_scope.makeMangledName(rp.c, "switch"); } if (switch_scope.switch_label) |l| { switch_scope.pending_block.label = try appendIdentifier(rp.c, l); _ = try appendToken(rp.c, .Colon, ":"); } if (switch_scope.default_label == null) { const else_prong = try transCreateNodeSwitchCase(rp.c, try transCreateNodeSwitchElse(rp.c)); else_prong.expr = blk: { var br = try CtrlFlow.init(rp.c, .Break, switch_scope.switch_label.?); break :blk &(try br.finish(null)).base; }; _ = try appendToken(rp.c, .Comma, ","); if (switch_scope.case_index >= switch_scope.cases.len) return revertAndWarn(rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), "TODO complex switch cases", .{}); switch_scope.cases[switch_scope.case_index] = &else_prong.base; switch_scope.case_index += 1; } // We overallocated in case there was no default, so now we correct // the number of cases in the AST node. switch_node.cases_len = switch_scope.case_index; const result_node = try switch_scope.pending_block.complete(rp.c); switch_scope.pending_block.deinit(); return result_node; } fn transCase( rp: RestorePoint, scope: *Scope, stmt: *const clang.CaseStmt, ) TransError!*ast.Node { const block_scope = scope.findBlockScope(rp.c) catch unreachable; const switch_scope = scope.getSwitch(); const label = try block_scope.makeMangledName(rp.c, "case"); _ = try appendToken(rp.c, .Semicolon, ";"); const expr = if (stmt.getRHS()) |rhs| blk: { const lhs_node = try transExpr(rp, scope, stmt.getLHS(), .used, .r_value); const ellips = try appendToken(rp.c, .Ellipsis3, "..."); const rhs_node = try transExpr(rp, scope, rhs, .used, .r_value); const node = try rp.c.arena.create(ast.Node.SimpleInfixOp); node.* = .{ .base = .{ .tag = .Range }, .op_token = ellips, .lhs = lhs_node, .rhs = rhs_node, }; break :blk &node.base; } else try transExpr(rp, scope, stmt.getLHS(), .used, .r_value); const switch_prong = try transCreateNodeSwitchCase(rp.c, expr); switch_prong.expr = blk: { var br = try CtrlFlow.init(rp.c, .Break, label); break :blk &(try br.finish(null)).base; }; _ = try appendToken(rp.c, .Comma, ","); if (switch_scope.case_index >= switch_scope.cases.len) return revertAndWarn(rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), "TODO complex switch cases", .{}); switch_scope.cases[switch_scope.case_index] = &switch_prong.base; switch_scope.case_index += 1; switch_scope.pending_block.label = try appendIdentifier(rp.c, label); _ = try appendToken(rp.c, .Colon, ":"); // take all pending statements try switch_scope.pending_block.statements.appendSlice(block_scope.statements.items); block_scope.statements.shrink(0); const pending_node = try switch_scope.pending_block.complete(rp.c); switch_scope.pending_block.deinit(); switch_scope.pending_block = try Scope.Block.init(rp.c, scope, false); try switch_scope.pending_block.statements.append(pending_node); return transStmt(rp, scope, stmt.getSubStmt(), .unused, .r_value); } fn transDefault( rp: RestorePoint, scope: *Scope, stmt: *const clang.DefaultStmt, ) TransError!*ast.Node { const block_scope = scope.findBlockScope(rp.c) catch unreachable; const switch_scope = scope.getSwitch(); switch_scope.default_label = try block_scope.makeMangledName(rp.c, "default"); _ = try appendToken(rp.c, .Semicolon, ";"); const else_prong = try transCreateNodeSwitchCase(rp.c, try transCreateNodeSwitchElse(rp.c)); else_prong.expr = blk: { var br = try CtrlFlow.init(rp.c, .Break, switch_scope.default_label.?); break :blk &(try br.finish(null)).base; }; _ = try appendToken(rp.c, .Comma, ","); if (switch_scope.case_index >= switch_scope.cases.len) return revertAndWarn(rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), "TODO complex switch cases", .{}); switch_scope.cases[switch_scope.case_index] = &else_prong.base; switch_scope.case_index += 1; switch_scope.pending_block.label = try appendIdentifier(rp.c, switch_scope.default_label.?); _ = try appendToken(rp.c, .Colon, ":"); // take all pending statements try switch_scope.pending_block.statements.appendSlice(block_scope.statements.items); block_scope.statements.shrink(0); const pending_node = try switch_scope.pending_block.complete(rp.c); switch_scope.pending_block.deinit(); switch_scope.pending_block = try Scope.Block.init(rp.c, scope, false); try switch_scope.pending_block.statements.append(pending_node); return transStmt(rp, scope, stmt.getSubStmt(), .unused, .r_value); } fn transConstantExpr(rp: RestorePoint, scope: *Scope, expr: *const clang.Expr, used: ResultUsed) TransError!*ast.Node { var result: clang.ExprEvalResult = undefined; if (!expr.EvaluateAsConstantExpr(&result, .EvaluateForCodeGen, rp.c.clang_context)) return revertAndWarn(rp, error.UnsupportedTranslation, expr.getBeginLoc(), "invalid constant expression", .{}); var val_node: ?*ast.Node = null; switch (result.Val.getKind()) { .Int => { // See comment in `transIntegerLiteral` for why this code is here. // @as(T, x) const expr_base = @ptrCast(*const clang.Expr, expr); const as_node = try rp.c.createBuiltinCall("@as", 2); const ty_node = try transQualType(rp, expr_base.getType(), expr_base.getBeginLoc()); as_node.params()[0] = ty_node; _ = try appendToken(rp.c, .Comma, ","); const int_lit_node = try transCreateNodeAPInt(rp.c, result.Val.getInt()); as_node.params()[1] = int_lit_node; as_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, used, &as_node.base); }, else => { return revertAndWarn(rp, error.UnsupportedTranslation, expr.getBeginLoc(), "unsupported constant expression kind", .{}); }, } } fn transPredefinedExpr(rp: RestorePoint, scope: *Scope, expr: *const clang.PredefinedExpr, used: ResultUsed) TransError!*ast.Node { return transStringLiteral(rp, scope, expr.getFunctionName(), used); } fn transCharLiteral( rp: RestorePoint, scope: *Scope, stmt: *const clang.CharacterLiteral, result_used: ResultUsed, suppress_as: SuppressCast, ) TransError!*ast.Node { const kind = stmt.getKind(); const int_lit_node = switch (kind) { .Ascii, .UTF8 => blk: { const val = stmt.getValue(); if (kind == .Ascii) { // C has a somewhat obscure feature called multi-character character // constant if (val > 255) break :blk try transCreateNodeInt(rp.c, val); } const token = try appendTokenFmt(rp.c, .CharLiteral, "'{Z}'", .{@intCast(u8, val)}); const node = try rp.c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .CharLiteral }, .token = token, }; break :blk &node.base; }, .UTF16, .UTF32, .Wide => return revertAndWarn( rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), "TODO: support character literal kind {}", .{kind}, ), }; if (suppress_as == .no_as) { return maybeSuppressResult(rp, scope, result_used, int_lit_node); } // See comment in `transIntegerLiteral` for why this code is here. // @as(T, x) const expr_base = @ptrCast(*const clang.Expr, stmt); const as_node = try rp.c.createBuiltinCall("@as", 2); const ty_node = try transQualType(rp, expr_base.getType(), expr_base.getBeginLoc()); as_node.params()[0] = ty_node; _ = try appendToken(rp.c, .Comma, ","); as_node.params()[1] = int_lit_node; as_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, result_used, &as_node.base); } fn transStmtExpr(rp: RestorePoint, scope: *Scope, stmt: *const clang.StmtExpr, used: ResultUsed) TransError!*ast.Node { const comp = stmt.getSubStmt(); if (used == .unused) { return transCompoundStmt(rp, scope, comp); } const lparen = try appendToken(rp.c, .LParen, "("); var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); var it = comp.body_begin(); const end_it = comp.body_end(); while (it != end_it - 1) : (it += 1) { const result = try transStmt(rp, &block_scope.base, it[0], .unused, .r_value); try block_scope.statements.append(result); } const break_node = blk: { var tmp = try CtrlFlow.init(rp.c, .Break, "blk"); const rhs = try transStmt(rp, &block_scope.base, it[0], .used, .r_value); break :blk try tmp.finish(rhs); }; _ = try appendToken(rp.c, .Semicolon, ";"); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen, .expr = block_node, .rparen = rparen, }; return maybeSuppressResult(rp, scope, used, &grouped_expr.base); } fn transMemberExpr(rp: RestorePoint, scope: *Scope, stmt: *const clang.MemberExpr, result_used: ResultUsed) TransError!*ast.Node { var container_node = try transExpr(rp, scope, stmt.getBase(), .used, .r_value); if (stmt.isArrow()) { container_node = try transCreateNodePtrDeref(rp.c, container_node); } const member_decl = stmt.getMemberDecl(); const name = blk: { const decl_kind = @ptrCast(*const clang.Decl, member_decl).getKind(); // If we're referring to a anonymous struct/enum find the bogus name // we've assigned to it during the RecordDecl translation if (decl_kind == .Field) { const field_decl = @ptrCast(*const clang.FieldDecl, member_decl); if (field_decl.isAnonymousStructOrUnion()) { const name = rp.c.decl_table.get(@ptrToInt(field_decl.getCanonicalDecl())).?; break :blk try mem.dupe(rp.c.arena, u8, name); } } const decl = @ptrCast(*const clang.NamedDecl, member_decl); break :blk try rp.c.str(decl.getName_bytes_begin()); }; const node = try transCreateNodeFieldAccess(rp.c, container_node, name); return maybeSuppressResult(rp, scope, result_used, node); } fn transArrayAccess(rp: RestorePoint, scope: *Scope, stmt: *const clang.ArraySubscriptExpr, result_used: ResultUsed) TransError!*ast.Node { var base_stmt = stmt.getBase(); // Unwrap the base statement if it's an array decayed to a bare pointer type // so that we index the array itself if (@ptrCast(*const clang.Stmt, base_stmt).getStmtClass() == .ImplicitCastExprClass) { const implicit_cast = @ptrCast(*const clang.ImplicitCastExpr, base_stmt); if (implicit_cast.getCastKind() == .ArrayToPointerDecay) { base_stmt = implicit_cast.getSubExpr(); } } const container_node = try transExpr(rp, scope, base_stmt, .used, .r_value); const node = try transCreateNodeArrayAccess(rp.c, container_node); // cast if the index is long long or signed const subscr_expr = stmt.getIdx(); const qt = getExprQualType(rp.c, subscr_expr); const is_longlong = cIsLongLongInteger(qt); const is_signed = cIsSignedInteger(qt); if (is_longlong or is_signed) { const cast_node = try rp.c.createBuiltinCall("@intCast", 2); // check if long long first so that signed long long doesn't just become unsigned long long var typeid_node = if (is_longlong) try transCreateNodeIdentifier(rp.c, "usize") else try transQualTypeIntWidthOf(rp.c, qt, false); cast_node.params()[0] = typeid_node; _ = try appendToken(rp.c, .Comma, ","); cast_node.params()[1] = try transExpr(rp, scope, subscr_expr, .used, .r_value); cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); node.rtoken = try appendToken(rp.c, .RBrace, "]"); node.index_expr = &cast_node.base; } else { node.index_expr = try transExpr(rp, scope, subscr_expr, .used, .r_value); node.rtoken = try appendToken(rp.c, .RBrace, "]"); } return maybeSuppressResult(rp, scope, result_used, &node.base); } fn transCallExpr(rp: RestorePoint, scope: *Scope, stmt: *const clang.CallExpr, result_used: ResultUsed) TransError!*ast.Node { const callee = stmt.getCallee(); var raw_fn_expr = try transExpr(rp, scope, callee, .used, .r_value); var is_ptr = false; const fn_ty = qualTypeGetFnProto(callee.getType(), &is_ptr); const fn_expr = if (is_ptr and fn_ty != null) blk: { if (callee.getStmtClass() == .ImplicitCastExprClass) { const implicit_cast = @ptrCast(*const clang.ImplicitCastExpr, callee); const cast_kind = implicit_cast.getCastKind(); if (cast_kind == .BuiltinFnToFnPtr) break :blk raw_fn_expr; if (cast_kind == .FunctionToPointerDecay) { const subexpr = implicit_cast.getSubExpr(); if (subexpr.getStmtClass() == .DeclRefExprClass) { const decl_ref = @ptrCast(*const clang.DeclRefExpr, subexpr); const named_decl = decl_ref.getFoundDecl(); if (@ptrCast(*const clang.Decl, named_decl).getKind() == .Function) { break :blk raw_fn_expr; } } } } break :blk try transCreateNodeUnwrapNull(rp.c, raw_fn_expr); } else raw_fn_expr; const num_args = stmt.getNumArgs(); const node = try rp.c.createCall(fn_expr, num_args); const call_params = node.params(); const args = stmt.getArgs(); var i: usize = 0; while (i < num_args) : (i += 1) { if (i != 0) { _ = try appendToken(rp.c, .Comma, ","); } call_params[i] = try transExpr(rp, scope, args[i], .used, .r_value); } node.rtoken = try appendToken(rp.c, .RParen, ")"); if (fn_ty) |ty| { const canon = ty.getReturnType().getCanonicalType(); const ret_ty = canon.getTypePtr(); if (ret_ty.isVoidType()) { _ = try appendToken(rp.c, .Semicolon, ";"); return &node.base; } } return maybeSuppressResult(rp, scope, result_used, &node.base); } const ClangFunctionType = union(enum) { Proto: *const clang.FunctionProtoType, NoProto: *const clang.FunctionType, fn getReturnType(self: @This()) clang.QualType { switch (@as(@TagType(@This()), self)) { .Proto => return self.Proto.getReturnType(), .NoProto => return self.NoProto.getReturnType(), } } }; fn qualTypeGetFnProto(qt: clang.QualType, is_ptr: *bool) ?ClangFunctionType { const canon = qt.getCanonicalType(); var ty = canon.getTypePtr(); is_ptr.* = false; if (ty.getTypeClass() == .Pointer) { is_ptr.* = true; const child_qt = ty.getPointeeType(); ty = child_qt.getTypePtr(); } if (ty.getTypeClass() == .FunctionProto) { return ClangFunctionType{ .Proto = @ptrCast(*const clang.FunctionProtoType, ty) }; } if (ty.getTypeClass() == .FunctionNoProto) { return ClangFunctionType{ .NoProto = @ptrCast(*const clang.FunctionType, ty) }; } return null; } fn transUnaryExprOrTypeTraitExpr( rp: RestorePoint, scope: *Scope, stmt: *const clang.UnaryExprOrTypeTraitExpr, result_used: ResultUsed, ) TransError!*ast.Node { const loc = stmt.getBeginLoc(); const type_node = try transQualType( rp, stmt.getTypeOfArgument(), loc, ); const kind = stmt.getKind(); const kind_str = switch (kind) { .SizeOf => "@sizeOf", .AlignOf => "@alignOf", .PreferredAlignOf, .VecStep, .OpenMPRequiredSimdAlign, => return revertAndWarn( rp, error.UnsupportedTranslation, loc, "Unsupported type trait kind {}", .{kind}, ), }; const builtin_node = try rp.c.createBuiltinCall(kind_str, 1); builtin_node.params()[0] = type_node; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return maybeSuppressResult(rp, scope, result_used, &builtin_node.base); } fn qualTypeHasWrappingOverflow(qt: clang.QualType) bool { if (cIsUnsignedInteger(qt)) { // unsigned integer overflow wraps around. return true; } else { // float, signed integer, and pointer overflow is undefined behavior. return false; } } fn transUnaryOperator(rp: RestorePoint, scope: *Scope, stmt: *const clang.UnaryOperator, used: ResultUsed) TransError!*ast.Node { const op_expr = stmt.getSubExpr(); switch (stmt.getOpcode()) { .PostInc => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreatePostCrement(rp, scope, stmt, .AssignAddWrap, .PlusPercentEqual, "+%=", used) else return transCreatePostCrement(rp, scope, stmt, .AssignAdd, .PlusEqual, "+=", used), .PostDec => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreatePostCrement(rp, scope, stmt, .AssignSubWrap, .MinusPercentEqual, "-%=", used) else return transCreatePostCrement(rp, scope, stmt, .AssignSub, .MinusEqual, "-=", used), .PreInc => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreatePreCrement(rp, scope, stmt, .AssignAddWrap, .PlusPercentEqual, "+%=", used) else return transCreatePreCrement(rp, scope, stmt, .AssignAdd, .PlusEqual, "+=", used), .PreDec => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreatePreCrement(rp, scope, stmt, .AssignSubWrap, .MinusPercentEqual, "-%=", used) else return transCreatePreCrement(rp, scope, stmt, .AssignSub, .MinusEqual, "-=", used), .AddrOf => { const op_node = try transCreateNodeSimplePrefixOp(rp.c, .AddressOf, .Ampersand, "&"); op_node.rhs = try transExpr(rp, scope, op_expr, used, .r_value); return &op_node.base; }, .Deref => { const value_node = try transExpr(rp, scope, op_expr, used, .r_value); var is_ptr = false; const fn_ty = qualTypeGetFnProto(op_expr.getType(), &is_ptr); if (fn_ty != null and is_ptr) return value_node; const unwrapped = try transCreateNodeUnwrapNull(rp.c, value_node); return transCreateNodePtrDeref(rp.c, unwrapped); }, .Plus => return transExpr(rp, scope, op_expr, used, .r_value), .Minus => { if (!qualTypeHasWrappingOverflow(op_expr.getType())) { const op_node = try transCreateNodeSimplePrefixOp(rp.c, .Negation, .Minus, "-"); op_node.rhs = try transExpr(rp, scope, op_expr, .used, .r_value); return &op_node.base; } else if (cIsUnsignedInteger(op_expr.getType())) { // we gotta emit 0 -% x const zero = try transCreateNodeInt(rp.c, 0); const token = try appendToken(rp.c, .MinusPercent, "-%"); const expr = try transExpr(rp, scope, op_expr, .used, .r_value); return transCreateNodeInfixOp(rp, scope, zero, .SubWrap, token, expr, used, true); } else return revertAndWarn(rp, error.UnsupportedTranslation, stmt.getBeginLoc(), "C negation with non float non integer", .{}); }, .Not => { const op_node = try transCreateNodeSimplePrefixOp(rp.c, .BitNot, .Tilde, "~"); op_node.rhs = try transExpr(rp, scope, op_expr, .used, .r_value); return &op_node.base; }, .LNot => { const op_node = try transCreateNodeSimplePrefixOp(rp.c, .BoolNot, .Bang, "!"); op_node.rhs = try transBoolExpr(rp, scope, op_expr, .used, .r_value, true); return &op_node.base; }, .Extension => { return transExpr(rp, scope, stmt.getSubExpr(), used, .l_value); }, else => return revertAndWarn(rp, error.UnsupportedTranslation, stmt.getBeginLoc(), "unsupported C translation {}", .{stmt.getOpcode()}), } } fn transCreatePreCrement( rp: RestorePoint, scope: *Scope, stmt: *const clang.UnaryOperator, op: ast.Node.Tag, op_tok_id: std.zig.Token.Id, bytes: []const u8, used: ResultUsed, ) TransError!*ast.Node { const op_expr = stmt.getSubExpr(); if (used == .unused) { // common case // c: ++expr // zig: expr += 1 const expr = try transExpr(rp, scope, op_expr, .used, .r_value); const token = try appendToken(rp.c, op_tok_id, bytes); const one = try transCreateNodeInt(rp.c, 1); if (scope.id != .Condition) _ = try appendToken(rp.c, .Semicolon, ";"); return transCreateNodeInfixOp(rp, scope, expr, op, token, one, .used, false); } // worst case // c: ++expr // zig: (blk: { // zig: const _ref = &expr; // zig: _ref.* += 1; // zig: break :blk _ref.* // zig: }) var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); const ref = try block_scope.makeMangledName(rp.c, "ref"); const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, ref); const eq_token = try appendToken(rp.c, .Equal, "="); const rhs_node = try transCreateNodeSimplePrefixOp(rp.c, .AddressOf, .Ampersand, "&"); rhs_node.rhs = try transExpr(rp, scope, op_expr, .used, .r_value); const init_node = &rhs_node.base; const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&node.base); const lhs_node = try transCreateNodeIdentifier(rp.c, ref); const ref_node = try transCreateNodePtrDeref(rp.c, lhs_node); _ = try appendToken(rp.c, .Semicolon, ";"); const token = try appendToken(rp.c, op_tok_id, bytes); const one = try transCreateNodeInt(rp.c, 1); _ = try appendToken(rp.c, .Semicolon, ";"); const assign = try transCreateNodeInfixOp(rp, scope, ref_node, op, token, one, .used, false); try block_scope.statements.append(assign); const break_node = try transCreateNodeBreak(rp.c, block_scope.label, ref_node); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); // semicolon must immediately follow rbrace because it is the last token in a block _ = try appendToken(rp.c, .Semicolon, ";"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = try appendToken(rp.c, .LParen, "("), .expr = block_node, .rparen = try appendToken(rp.c, .RParen, ")"), }; return &grouped_expr.base; } fn transCreatePostCrement( rp: RestorePoint, scope: *Scope, stmt: *const clang.UnaryOperator, op: ast.Node.Tag, op_tok_id: std.zig.Token.Id, bytes: []const u8, used: ResultUsed, ) TransError!*ast.Node { const op_expr = stmt.getSubExpr(); if (used == .unused) { // common case // c: ++expr // zig: expr += 1 const expr = try transExpr(rp, scope, op_expr, .used, .r_value); const token = try appendToken(rp.c, op_tok_id, bytes); const one = try transCreateNodeInt(rp.c, 1); if (scope.id != .Condition) _ = try appendToken(rp.c, .Semicolon, ";"); return transCreateNodeInfixOp(rp, scope, expr, op, token, one, .used, false); } // worst case // c: expr++ // zig: (blk: { // zig: const _ref = &expr; // zig: const _tmp = _ref.*; // zig: _ref.* += 1; // zig: break :blk _tmp // zig: }) var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); const ref = try block_scope.makeMangledName(rp.c, "ref"); const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, ref); const eq_token = try appendToken(rp.c, .Equal, "="); const rhs_node = try transCreateNodeSimplePrefixOp(rp.c, .AddressOf, .Ampersand, "&"); rhs_node.rhs = try transExpr(rp, scope, op_expr, .used, .r_value); const init_node = &rhs_node.base; const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&node.base); const lhs_node = try transCreateNodeIdentifier(rp.c, ref); const ref_node = try transCreateNodePtrDeref(rp.c, lhs_node); _ = try appendToken(rp.c, .Semicolon, ";"); const tmp = try block_scope.makeMangledName(rp.c, "tmp"); const tmp_mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const tmp_name_tok = try appendIdentifier(rp.c, tmp); const tmp_eq_token = try appendToken(rp.c, .Equal, "="); const tmp_init_node = ref_node; const tmp_semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const tmp_node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = tmp_name_tok, .mut_token = tmp_mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = tmp_eq_token, .init_node = tmp_init_node, }); try block_scope.statements.append(&tmp_node.base); const token = try appendToken(rp.c, op_tok_id, bytes); const one = try transCreateNodeInt(rp.c, 1); _ = try appendToken(rp.c, .Semicolon, ";"); const assign = try transCreateNodeInfixOp(rp, scope, ref_node, op, token, one, .used, false); try block_scope.statements.append(assign); const break_node = blk: { var tmp_ctrl_flow = try CtrlFlow.initToken(rp.c, .Break, block_scope.label); const rhs = try transCreateNodeIdentifier(rp.c, tmp); break :blk try tmp_ctrl_flow.finish(rhs); }; try block_scope.statements.append(&break_node.base); _ = try appendToken(rp.c, .Semicolon, ";"); const block_node = try block_scope.complete(rp.c); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = try appendToken(rp.c, .LParen, "("), .expr = block_node, .rparen = try appendToken(rp.c, .RParen, ")"), }; return &grouped_expr.base; } fn transCompoundAssignOperator(rp: RestorePoint, scope: *Scope, stmt: *const clang.CompoundAssignOperator, used: ResultUsed) TransError!*ast.Node { switch (stmt.getOpcode()) { .MulAssign => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreateCompoundAssign(rp, scope, stmt, .AssignMulWrap, .AsteriskPercentEqual, "*%=", .MulWrap, .AsteriskPercent, "*%", used) else return transCreateCompoundAssign(rp, scope, stmt, .AssignMul, .AsteriskEqual, "*=", .Mul, .Asterisk, "*", used), .AddAssign => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreateCompoundAssign(rp, scope, stmt, .AssignAddWrap, .PlusPercentEqual, "+%=", .AddWrap, .PlusPercent, "+%", used) else return transCreateCompoundAssign(rp, scope, stmt, .AssignAdd, .PlusEqual, "+=", .Add, .Plus, "+", used), .SubAssign => if (qualTypeHasWrappingOverflow(stmt.getType())) return transCreateCompoundAssign(rp, scope, stmt, .AssignSubWrap, .MinusPercentEqual, "-%=", .SubWrap, .MinusPercent, "-%", used) else return transCreateCompoundAssign(rp, scope, stmt, .AssignSub, .MinusPercentEqual, "-=", .Sub, .Minus, "-", used), .DivAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignDiv, .SlashEqual, "/=", .Div, .Slash, "/", used), .RemAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignMod, .PercentEqual, "%=", .Mod, .Percent, "%", used), .ShlAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignBitShiftLeft, .AngleBracketAngleBracketLeftEqual, "<<=", .BitShiftLeft, .AngleBracketAngleBracketLeft, "<<", used), .ShrAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignBitShiftRight, .AngleBracketAngleBracketRightEqual, ">>=", .BitShiftRight, .AngleBracketAngleBracketRight, ">>", used), .AndAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignBitAnd, .AmpersandEqual, "&=", .BitAnd, .Ampersand, "&", used), .XorAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignBitXor, .CaretEqual, "^=", .BitXor, .Caret, "^", used), .OrAssign => return transCreateCompoundAssign(rp, scope, stmt, .AssignBitOr, .PipeEqual, "|=", .BitOr, .Pipe, "|", used), else => return revertAndWarn( rp, error.UnsupportedTranslation, stmt.getBeginLoc(), "unsupported C translation {}", .{stmt.getOpcode()}, ), } } fn transCreateCompoundAssign( rp: RestorePoint, scope: *Scope, stmt: *const clang.CompoundAssignOperator, assign_op: ast.Node.Tag, assign_tok_id: std.zig.Token.Id, assign_bytes: []const u8, bin_op: ast.Node.Tag, bin_tok_id: std.zig.Token.Id, bin_bytes: []const u8, used: ResultUsed, ) TransError!*ast.Node { const is_shift = bin_op == .BitShiftLeft or bin_op == .BitShiftRight; const is_div = bin_op == .Div; const is_mod = bin_op == .Mod; const lhs = stmt.getLHS(); const rhs = stmt.getRHS(); const loc = stmt.getBeginLoc(); const lhs_qt = getExprQualType(rp.c, lhs); const rhs_qt = getExprQualType(rp.c, rhs); const is_signed = cIsSignedInteger(lhs_qt); const requires_int_cast = blk: { const are_integers = cIsInteger(lhs_qt) and cIsInteger(rhs_qt); const are_same_sign = cIsSignedInteger(lhs_qt) == cIsSignedInteger(rhs_qt); break :blk are_integers and !are_same_sign; }; if (used == .unused) { // common case // c: lhs += rhs // zig: lhs += rhs if ((is_mod or is_div) and is_signed) { const op_token = try appendToken(rp.c, .Equal, "="); const op_node = try rp.c.arena.create(ast.Node.SimpleInfixOp); const builtin = if (is_mod) "@rem" else "@divTrunc"; const builtin_node = try rp.c.createBuiltinCall(builtin, 2); const lhs_node = try transExpr(rp, scope, lhs, .used, .l_value); builtin_node.params()[0] = lhs_node; _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = try transExpr(rp, scope, rhs, .used, .r_value); builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); op_node.* = .{ .base = .{ .tag = .Assign }, .op_token = op_token, .lhs = lhs_node, .rhs = &builtin_node.base, }; _ = try appendToken(rp.c, .Semicolon, ";"); return &op_node.base; } const lhs_node = try transExpr(rp, scope, lhs, .used, .l_value); const eq_token = try appendToken(rp.c, assign_tok_id, assign_bytes); var rhs_node = if (is_shift or requires_int_cast) try transExprCoercing(rp, scope, rhs, .used, .r_value) else try transExpr(rp, scope, rhs, .used, .r_value); if (is_shift or requires_int_cast) { const cast_node = try rp.c.createBuiltinCall("@intCast", 2); const cast_to_type = if (is_shift) try qualTypeToLog2IntRef(rp, getExprQualType(rp.c, rhs), loc) else try transQualType(rp, getExprQualType(rp.c, lhs), loc); cast_node.params()[0] = cast_to_type; _ = try appendToken(rp.c, .Comma, ","); cast_node.params()[1] = rhs_node; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); rhs_node = &cast_node.base; } if (scope.id != .Condition) _ = try appendToken(rp.c, .Semicolon, ";"); return transCreateNodeInfixOp(rp, scope, lhs_node, assign_op, eq_token, rhs_node, .used, false); } // worst case // c: lhs += rhs // zig: (blk: { // zig: const _ref = &lhs; // zig: _ref.* = _ref.* + rhs; // zig: break :blk _ref.* // zig: }) var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); const ref = try block_scope.makeMangledName(rp.c, "ref"); const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, ref); const eq_token = try appendToken(rp.c, .Equal, "="); const addr_node = try transCreateNodeSimplePrefixOp(rp.c, .AddressOf, .Ampersand, "&"); addr_node.rhs = try transExpr(rp, scope, lhs, .used, .l_value); const init_node = &addr_node.base; const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&node.base); const lhs_node = try transCreateNodeIdentifier(rp.c, ref); const ref_node = try transCreateNodePtrDeref(rp.c, lhs_node); _ = try appendToken(rp.c, .Semicolon, ";"); if ((is_mod or is_div) and is_signed) { const op_token = try appendToken(rp.c, .Equal, "="); const op_node = try rp.c.arena.create(ast.Node.SimpleInfixOp); const builtin = if (is_mod) "@rem" else "@divTrunc"; const builtin_node = try rp.c.createBuiltinCall(builtin, 2); builtin_node.params()[0] = try transCreateNodePtrDeref(rp.c, lhs_node); _ = try appendToken(rp.c, .Comma, ","); builtin_node.params()[1] = try transExpr(rp, scope, rhs, .used, .r_value); builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); _ = try appendToken(rp.c, .Semicolon, ";"); op_node.* = .{ .base = .{ .tag = .Assign }, .op_token = op_token, .lhs = ref_node, .rhs = &builtin_node.base, }; _ = try appendToken(rp.c, .Semicolon, ";"); try block_scope.statements.append(&op_node.base); } else { const bin_token = try appendToken(rp.c, bin_tok_id, bin_bytes); var rhs_node = try transExpr(rp, scope, rhs, .used, .r_value); if (is_shift or requires_int_cast) { const cast_node = try rp.c.createBuiltinCall("@intCast", 2); const cast_to_type = if (is_shift) try qualTypeToLog2IntRef(rp, getExprQualType(rp.c, rhs), loc) else try transQualType(rp, getExprQualType(rp.c, lhs), loc); cast_node.params()[0] = cast_to_type; _ = try appendToken(rp.c, .Comma, ","); cast_node.params()[1] = rhs_node; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); rhs_node = &cast_node.base; } const rhs_bin = try transCreateNodeInfixOp(rp, scope, ref_node, bin_op, bin_token, rhs_node, .used, false); _ = try appendToken(rp.c, .Semicolon, ";"); const ass_eq_token = try appendToken(rp.c, .Equal, "="); const assign = try transCreateNodeInfixOp(rp, scope, ref_node, .Assign, ass_eq_token, rhs_bin, .used, false); try block_scope.statements.append(assign); } const break_node = try transCreateNodeBreak(rp.c, block_scope.label, ref_node); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = try appendToken(rp.c, .LParen, "("), .expr = block_node, .rparen = try appendToken(rp.c, .RParen, ")"), }; return &grouped_expr.base; } fn transCPtrCast( rp: RestorePoint, loc: clang.SourceLocation, dst_type: clang.QualType, src_type: clang.QualType, expr: *ast.Node, ) !*ast.Node { const ty = dst_type.getTypePtr(); const child_type = ty.getPointeeType(); const src_ty = src_type.getTypePtr(); const src_child_type = src_ty.getPointeeType(); if ((src_child_type.isConstQualified() and !child_type.isConstQualified()) or (src_child_type.isVolatileQualified() and !child_type.isVolatileQualified())) { // Casting away const or volatile requires us to use @intToPtr const inttoptr_node = try rp.c.createBuiltinCall("@intToPtr", 2); const dst_type_node = try transType(rp, ty, loc); inttoptr_node.params()[0] = dst_type_node; _ = try appendToken(rp.c, .Comma, ","); const ptrtoint_node = try rp.c.createBuiltinCall("@ptrToInt", 1); ptrtoint_node.params()[0] = expr; ptrtoint_node.rparen_token = try appendToken(rp.c, .RParen, ")"); inttoptr_node.params()[1] = &ptrtoint_node.base; inttoptr_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &inttoptr_node.base; } else { // Implicit downcasting from higher to lower alignment values is forbidden, // use @alignCast to side-step this problem const ptrcast_node = try rp.c.createBuiltinCall("@ptrCast", 2); const dst_type_node = try transType(rp, ty, loc); ptrcast_node.params()[0] = dst_type_node; _ = try appendToken(rp.c, .Comma, ","); if (qualTypeCanon(child_type).isVoidType()) { // void has 1-byte alignment, so @alignCast is not needed ptrcast_node.params()[1] = expr; } else if (typeIsOpaque(rp.c, qualTypeCanon(child_type), loc)) { // For opaque types a ptrCast is enough ptrcast_node.params()[1] = expr; } else { const aligncast_node = try rp.c.createBuiltinCall("@alignCast", 2); const alignof_node = try rp.c.createBuiltinCall("@alignOf", 1); const child_type_node = try transQualType(rp, child_type, loc); alignof_node.params()[0] = child_type_node; alignof_node.rparen_token = try appendToken(rp.c, .RParen, ")"); aligncast_node.params()[0] = &alignof_node.base; _ = try appendToken(rp.c, .Comma, ","); aligncast_node.params()[1] = expr; aligncast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); ptrcast_node.params()[1] = &aligncast_node.base; } ptrcast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); return &ptrcast_node.base; } } fn transBreak(rp: RestorePoint, scope: *Scope) TransError!*ast.Node { const break_scope = scope.getBreakableScope(); const label_text: ?[]const u8 = if (break_scope.id == .Switch) blk: { const swtch = @fieldParentPtr(Scope.Switch, "base", break_scope); const block_scope = try scope.findBlockScope(rp.c); swtch.switch_label = try block_scope.makeMangledName(rp.c, "switch"); break :blk swtch.switch_label; } else null; var cf = try CtrlFlow.init(rp.c, .Break, label_text); const br = try cf.finish(null); _ = try appendToken(rp.c, .Semicolon, ";"); return &br.base; } fn transFloatingLiteral(rp: RestorePoint, scope: *Scope, stmt: *const clang.FloatingLiteral, used: ResultUsed) TransError!*ast.Node { // TODO use something more accurate const dbl = stmt.getValueAsApproximateDouble(); const node = try rp.c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .FloatLiteral }, .token = try appendTokenFmt(rp.c, .FloatLiteral, "{d}", .{dbl}), }; return maybeSuppressResult(rp, scope, used, &node.base); } fn transBinaryConditionalOperator(rp: RestorePoint, scope: *Scope, stmt: *const clang.BinaryConditionalOperator, used: ResultUsed) TransError!*ast.Node { // GNU extension of the ternary operator where the middle expression is // omitted, the conditition itself is returned if it evaluates to true const casted_stmt = @ptrCast(*const clang.AbstractConditionalOperator, stmt); const cond_expr = casted_stmt.getCond(); const true_expr = casted_stmt.getTrueExpr(); const false_expr = casted_stmt.getFalseExpr(); // c: (cond_expr)?:(false_expr) // zig: (blk: { // const _cond_temp = (cond_expr); // break :blk if (_cond_temp) _cond_temp else (false_expr); // }) const lparen = try appendToken(rp.c, .LParen, "("); var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); const mangled_name = try block_scope.makeMangledName(rp.c, "cond_temp"); const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, mangled_name); const eq_token = try appendToken(rp.c, .Equal, "="); const init_node = try transExpr(rp, &block_scope.base, cond_expr, .used, .r_value); const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const tmp_var = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&tmp_var.base); var break_node_tmp = try CtrlFlow.initToken(rp.c, .Break, block_scope.label); const if_node = try transCreateNodeIf(rp.c); var cond_scope = Scope.Condition{ .base = .{ .parent = &block_scope.base, .id = .Condition, }, }; defer cond_scope.deinit(); const tmp_var_node = try transCreateNodeIdentifier(rp.c, mangled_name); const ty = getExprQualType(rp.c, cond_expr).getTypePtr(); const cond_node = try finishBoolExpr(rp, &cond_scope.base, cond_expr.getBeginLoc(), ty, tmp_var_node, used); if_node.condition = cond_node; _ = try appendToken(rp.c, .RParen, ")"); if_node.body = try transCreateNodeIdentifier(rp.c, mangled_name); if_node.@"else" = try transCreateNodeElse(rp.c); if_node.@"else".?.body = try transExpr(rp, &block_scope.base, false_expr, .used, .r_value); _ = try appendToken(rp.c, .Semicolon, ";"); const break_node = try break_node_tmp.finish(&if_node.base); _ = try appendToken(rp.c, .Semicolon, ";"); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen, .expr = block_node, .rparen = try appendToken(rp.c, .RParen, ")"), }; return maybeSuppressResult(rp, scope, used, &grouped_expr.base); } fn transConditionalOperator(rp: RestorePoint, scope: *Scope, stmt: *const clang.ConditionalOperator, used: ResultUsed) TransError!*ast.Node { const grouped = scope.id == .Condition; const lparen = if (grouped) try appendToken(rp.c, .LParen, "(") else undefined; const if_node = try transCreateNodeIf(rp.c); var cond_scope = Scope.Condition{ .base = .{ .parent = scope, .id = .Condition, }, }; defer cond_scope.deinit(); const casted_stmt = @ptrCast(*const clang.AbstractConditionalOperator, stmt); const cond_expr = casted_stmt.getCond(); const true_expr = casted_stmt.getTrueExpr(); const false_expr = casted_stmt.getFalseExpr(); if_node.condition = try transBoolExpr(rp, &cond_scope.base, cond_expr, .used, .r_value, false); _ = try appendToken(rp.c, .RParen, ")"); if_node.body = try transExpr(rp, scope, true_expr, .used, .r_value); if_node.@"else" = try transCreateNodeElse(rp.c); if_node.@"else".?.body = try transExpr(rp, scope, false_expr, .used, .r_value); if (grouped) { const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen, .expr = &if_node.base, .rparen = rparen, }; return maybeSuppressResult(rp, scope, used, &grouped_expr.base); } else { return maybeSuppressResult(rp, scope, used, &if_node.base); } } fn maybeSuppressResult( rp: RestorePoint, scope: *Scope, used: ResultUsed, result: *ast.Node, ) TransError!*ast.Node { if (used == .used) return result; if (scope.id != .Condition) { // NOTE: This is backwards, but the semicolon must immediately follow the node. _ = try appendToken(rp.c, .Semicolon, ";"); } else { // TODO is there a way to avoid this hack? // this parenthesis must come immediately following the node _ = try appendToken(rp.c, .RParen, ")"); // these need to come before _ _ = try appendToken(rp.c, .Colon, ":"); _ = try appendToken(rp.c, .LParen, "("); } const lhs = try transCreateNodeIdentifier(rp.c, "_"); const op_token = try appendToken(rp.c, .Equal, "="); const op_node = try rp.c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .Assign }, .op_token = op_token, .lhs = lhs, .rhs = result, }; return &op_node.base; } fn addTopLevelDecl(c: *Context, name: []const u8, decl_node: *ast.Node) !void { try c.root_decls.append(c.gpa, decl_node); _ = try c.global_scope.sym_table.put(name, decl_node); } fn transQualType(rp: RestorePoint, qt: clang.QualType, source_loc: clang.SourceLocation) TypeError!*ast.Node { return transType(rp, qt.getTypePtr(), source_loc); } /// Produces a Zig AST node by translating a Clang QualType, respecting the width, but modifying the signed-ness. /// Asserts the type is an integer. fn transQualTypeIntWidthOf(c: *Context, ty: clang.QualType, is_signed: bool) TypeError!*ast.Node { return transTypeIntWidthOf(c, qualTypeCanon(ty), is_signed); } /// Produces a Zig AST node by translating a Clang Type, respecting the width, but modifying the signed-ness. /// Asserts the type is an integer. fn transTypeIntWidthOf(c: *Context, ty: *const clang.Type, is_signed: bool) TypeError!*ast.Node { assert(ty.getTypeClass() == .Builtin); const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); return transCreateNodeIdentifier(c, switch (builtin_ty.getKind()) { .Char_U, .Char_S, .UChar, .SChar, .Char8 => if (is_signed) "i8" else "u8", .UShort, .Short => if (is_signed) "c_short" else "c_ushort", .UInt, .Int => if (is_signed) "c_int" else "c_uint", .ULong, .Long => if (is_signed) "c_long" else "c_ulong", .ULongLong, .LongLong => if (is_signed) "c_longlong" else "c_ulonglong", .UInt128, .Int128 => if (is_signed) "i128" else "u128", .Char16 => if (is_signed) "i16" else "u16", .Char32 => if (is_signed) "i32" else "u32", else => unreachable, // only call this function when it has already been determined the type is int }); } fn isCBuiltinType(qt: clang.QualType, kind: clang.BuiltinTypeKind) bool { const c_type = qualTypeCanon(qt); if (c_type.getTypeClass() != .Builtin) return false; const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return builtin_ty.getKind() == kind; } fn qualTypeIsPtr(qt: clang.QualType) bool { return qualTypeCanon(qt).getTypeClass() == .Pointer; } fn qualTypeIsBoolean(qt: clang.QualType) bool { return qualTypeCanon(qt).isBooleanType(); } fn qualTypeIntBitWidth(rp: RestorePoint, qt: clang.QualType, source_loc: clang.SourceLocation) !u32 { const ty = qt.getTypePtr(); switch (ty.getTypeClass()) { .Builtin => { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); switch (builtin_ty.getKind()) { .Char_U, .UChar, .Char_S, .SChar, => return 8, .UInt128, .Int128, => return 128, else => return 0, } unreachable; }, .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); const type_name = try rp.c.str(@ptrCast(*const clang.NamedDecl, typedef_decl).getName_bytes_begin()); if (mem.eql(u8, type_name, "uint8_t") or mem.eql(u8, type_name, "int8_t")) { return 8; } else if (mem.eql(u8, type_name, "uint16_t") or mem.eql(u8, type_name, "int16_t")) { return 16; } else if (mem.eql(u8, type_name, "uint32_t") or mem.eql(u8, type_name, "int32_t")) { return 32; } else if (mem.eql(u8, type_name, "uint64_t") or mem.eql(u8, type_name, "int64_t")) { return 64; } else { return 0; } }, else => return 0, } unreachable; } fn qualTypeToLog2IntRef(rp: RestorePoint, qt: clang.QualType, source_loc: clang.SourceLocation) !*ast.Node { const int_bit_width = try qualTypeIntBitWidth(rp, qt, source_loc); if (int_bit_width != 0) { // we can perform the log2 now. const cast_bit_width = math.log2_int(u64, int_bit_width); const node = try rp.c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, .token = try appendTokenFmt(rp.c, .Identifier, "u{}", .{cast_bit_width}), }; return &node.base; } const zig_type_node = try transQualType(rp, qt, source_loc); // @import("std").math.Log2Int(c_long); // // FnCall // FieldAccess // FieldAccess // FnCall (.builtin = true) // Symbol "import" // StringLiteral "std" // Symbol "math" // Symbol "Log2Int" // Symbol <zig_type_node> (var from above) const import_fn_call = try rp.c.createBuiltinCall("@import", 1); const std_token = try appendToken(rp.c, .StringLiteral, "\"std\""); const std_node = try rp.c.arena.create(ast.Node.OneToken); std_node.* = .{ .base = .{ .tag = .StringLiteral }, .token = std_token, }; import_fn_call.params()[0] = &std_node.base; import_fn_call.rparen_token = try appendToken(rp.c, .RParen, ")"); const inner_field_access = try transCreateNodeFieldAccess(rp.c, &import_fn_call.base, "math"); const outer_field_access = try transCreateNodeFieldAccess(rp.c, inner_field_access, "Log2Int"); const log2int_fn_call = try rp.c.createCall(outer_field_access, 1); log2int_fn_call.params()[0] = zig_type_node; log2int_fn_call.rtoken = try appendToken(rp.c, .RParen, ")"); return &log2int_fn_call.base; } fn qualTypeChildIsFnProto(qt: clang.QualType) bool { const ty = qualTypeCanon(qt); switch (ty.getTypeClass()) { .FunctionProto, .FunctionNoProto => return true, else => return false, } } fn qualTypeCanon(qt: clang.QualType) *const clang.Type { const canon = qt.getCanonicalType(); return canon.getTypePtr(); } fn getExprQualType(c: *Context, expr: *const clang.Expr) clang.QualType { blk: { // If this is a C `char *`, turn it into a `const char *` if (expr.getStmtClass() != .ImplicitCastExprClass) break :blk; const cast_expr = @ptrCast(*const clang.ImplicitCastExpr, expr); if (cast_expr.getCastKind() != .ArrayToPointerDecay) break :blk; const sub_expr = cast_expr.getSubExpr(); if (sub_expr.getStmtClass() != .StringLiteralClass) break :blk; const array_qt = sub_expr.getType(); const array_type = @ptrCast(*const clang.ArrayType, array_qt.getTypePtr()); var pointee_qt = array_type.getElementType(); pointee_qt.addConst(); return c.clang_context.getPointerType(pointee_qt); } return expr.getType(); } fn typeIsOpaque(c: *Context, ty: *const clang.Type, loc: clang.SourceLocation) bool { switch (ty.getTypeClass()) { .Builtin => { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); return builtin_ty.getKind() == .Void; }, .Record => { const record_ty = @ptrCast(*const clang.RecordType, ty); const record_decl = record_ty.getDecl(); const record_def = record_decl.getDefinition() orelse return true; var it = record_def.field_begin(); const end_it = record_def.field_end(); while (it.neq(end_it)) : (it = it.next()) { const field_decl = it.deref(); if (field_decl.isBitField()) { return true; } } return false; }, .Elaborated => { const elaborated_ty = @ptrCast(*const clang.ElaboratedType, ty); const qt = elaborated_ty.getNamedType(); return typeIsOpaque(c, qt.getTypePtr(), loc); }, .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); const underlying_type = typedef_decl.getUnderlyingType(); return typeIsOpaque(c, underlying_type.getTypePtr(), loc); }, else => return false, } } fn cIsInteger(qt: clang.QualType) bool { return cIsSignedInteger(qt) or cIsUnsignedInteger(qt); } fn cIsUnsignedInteger(qt: clang.QualType) bool { const c_type = qualTypeCanon(qt); if (c_type.getTypeClass() != .Builtin) return false; const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return switch (builtin_ty.getKind()) { .Char_U, .UChar, .Char_S, .UShort, .UInt, .ULong, .ULongLong, .UInt128, .WChar_U, => true, else => false, }; } fn cIntTypeToIndex(qt: clang.QualType) u8 { const c_type = qualTypeCanon(qt); assert(c_type.getTypeClass() == .Builtin); const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return switch (builtin_ty.getKind()) { .Bool, .Char_U, .Char_S, .UChar, .SChar, .Char8 => 1, .WChar_U, .WChar_S => 2, .UShort, .Short, .Char16 => 3, .UInt, .Int, .Char32 => 4, .ULong, .Long => 5, .ULongLong, .LongLong => 6, .UInt128, .Int128 => 7, else => unreachable, }; } fn cIntTypeCmp(a: clang.QualType, b: clang.QualType) math.Order { const a_index = cIntTypeToIndex(a); const b_index = cIntTypeToIndex(b); return math.order(a_index, b_index); } fn cIsSignedInteger(qt: clang.QualType) bool { const c_type = qualTypeCanon(qt); if (c_type.getTypeClass() != .Builtin) return false; const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return switch (builtin_ty.getKind()) { .SChar, .Short, .Int, .Long, .LongLong, .Int128, .WChar_S, => true, else => false, }; } fn cIsFloating(qt: clang.QualType) bool { const c_type = qualTypeCanon(qt); if (c_type.getTypeClass() != .Builtin) return false; const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return switch (builtin_ty.getKind()) { .Float, .Double, .Float128, .LongDouble, => true, else => false, }; } fn cIsLongLongInteger(qt: clang.QualType) bool { const c_type = qualTypeCanon(qt); if (c_type.getTypeClass() != .Builtin) return false; const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type); return switch (builtin_ty.getKind()) { .LongLong, .ULongLong, .Int128, .UInt128 => true, else => false, }; } fn transCreateNodeAssign( rp: RestorePoint, scope: *Scope, result_used: ResultUsed, lhs: *const clang.Expr, rhs: *const clang.Expr, ) !*ast.Node { // common case // c: lhs = rhs // zig: lhs = rhs if (result_used == .unused) { const lhs_node = try transExpr(rp, scope, lhs, .used, .l_value); const eq_token = try appendToken(rp.c, .Equal, "="); var rhs_node = try transExprCoercing(rp, scope, rhs, .used, .r_value); if (!exprIsBooleanType(lhs) and isBoolRes(rhs_node)) { const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = rhs_node; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); rhs_node = &builtin_node.base; } if (scope.id != .Condition) _ = try appendToken(rp.c, .Semicolon, ";"); return transCreateNodeInfixOp(rp, scope, lhs_node, .Assign, eq_token, rhs_node, .used, false); } // worst case // c: lhs = rhs // zig: (blk: { // zig: const _tmp = rhs; // zig: lhs = _tmp; // zig: break :blk _tmp // zig: }) var block_scope = try Scope.Block.init(rp.c, scope, true); defer block_scope.deinit(); const tmp = try block_scope.makeMangledName(rp.c, "tmp"); const mut_tok = try appendToken(rp.c, .Keyword_const, "const"); const name_tok = try appendIdentifier(rp.c, tmp); const eq_token = try appendToken(rp.c, .Equal, "="); var rhs_node = try transExpr(rp, &block_scope.base, rhs, .used, .r_value); if (!exprIsBooleanType(lhs) and isBoolRes(rhs_node)) { const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = rhs_node; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); rhs_node = &builtin_node.base; } const init_node = rhs_node; const semicolon_token = try appendToken(rp.c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(rp.c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .eq_token = eq_token, .init_node = init_node, }); try block_scope.statements.append(&node.base); const lhs_node = try transExpr(rp, &block_scope.base, lhs, .used, .l_value); const lhs_eq_token = try appendToken(rp.c, .Equal, "="); const ident = try transCreateNodeIdentifier(rp.c, tmp); _ = try appendToken(rp.c, .Semicolon, ";"); const assign = try transCreateNodeInfixOp(rp, &block_scope.base, lhs_node, .Assign, lhs_eq_token, ident, .used, false); try block_scope.statements.append(assign); const break_node = blk: { var tmp_ctrl_flow = try CtrlFlow.init(rp.c, .Break, tokenSlice(rp.c, block_scope.label.?)); const rhs_expr = try transCreateNodeIdentifier(rp.c, tmp); break :blk try tmp_ctrl_flow.finish(rhs_expr); }; _ = try appendToken(rp.c, .Semicolon, ";"); try block_scope.statements.append(&break_node.base); const block_node = try block_scope.complete(rp.c); // semicolon must immediately follow rbrace because it is the last token in a block _ = try appendToken(rp.c, .Semicolon, ";"); return block_node; } fn transCreateNodeFieldAccess(c: *Context, container: *ast.Node, field_name: []const u8) !*ast.Node { const field_access_node = try c.arena.create(ast.Node.SimpleInfixOp); field_access_node.* = .{ .base = .{ .tag = .Period }, .op_token = try appendToken(c, .Period, "."), .lhs = container, .rhs = try transCreateNodeIdentifier(c, field_name), }; return &field_access_node.base; } fn transCreateNodeSimplePrefixOp( c: *Context, comptime tag: ast.Node.Tag, op_tok_id: std.zig.Token.Id, bytes: []const u8, ) !*ast.Node.SimplePrefixOp { const node = try c.arena.create(ast.Node.SimplePrefixOp); node.* = .{ .base = .{ .tag = tag }, .op_token = try appendToken(c, op_tok_id, bytes), .rhs = undefined, // translate and set afterward }; return node; } fn transCreateNodeInfixOp( rp: RestorePoint, scope: *Scope, lhs_node: *ast.Node, op: ast.Node.Tag, op_token: ast.TokenIndex, rhs_node: *ast.Node, used: ResultUsed, grouped: bool, ) !*ast.Node { var lparen = if (grouped) try appendToken(rp.c, .LParen, "(") else null; const node = try rp.c.arena.create(ast.Node.SimpleInfixOp); node.* = .{ .base = .{ .tag = op }, .op_token = op_token, .lhs = lhs_node, .rhs = rhs_node, }; if (!grouped) return maybeSuppressResult(rp, scope, used, &node.base); const rparen = try appendToken(rp.c, .RParen, ")"); const grouped_expr = try rp.c.arena.create(ast.Node.GroupedExpression); grouped_expr.* = .{ .lparen = lparen.?, .expr = &node.base, .rparen = rparen, }; return maybeSuppressResult(rp, scope, used, &grouped_expr.base); } fn transCreateNodeBoolInfixOp( rp: RestorePoint, scope: *Scope, stmt: *const clang.BinaryOperator, op: ast.Node.Tag, used: ResultUsed, grouped: bool, ) !*ast.Node { std.debug.assert(op == .BoolAnd or op == .BoolOr); const lhs_hode = try transBoolExpr(rp, scope, stmt.getLHS(), .used, .l_value, true); const op_token = if (op == .BoolAnd) try appendToken(rp.c, .Keyword_and, "and") else try appendToken(rp.c, .Keyword_or, "or"); const rhs = try transBoolExpr(rp, scope, stmt.getRHS(), .used, .r_value, true); return transCreateNodeInfixOp( rp, scope, lhs_hode, op, op_token, rhs, used, grouped, ); } fn transCreateNodePtrType( c: *Context, is_const: bool, is_volatile: bool, op_tok_id: std.zig.Token.Id, ) !*ast.Node.PtrType { const node = try c.arena.create(ast.Node.PtrType); const op_token = switch (op_tok_id) { .LBracket => blk: { const lbracket = try appendToken(c, .LBracket, "["); _ = try appendToken(c, .Asterisk, "*"); _ = try appendToken(c, .RBracket, "]"); break :blk lbracket; }, .Identifier => blk: { const lbracket = try appendToken(c, .LBracket, "["); // Rendering checks if this token + 2 == .Identifier, so needs to return this token _ = try appendToken(c, .Asterisk, "*"); _ = try appendIdentifier(c, "c"); _ = try appendToken(c, .RBracket, "]"); break :blk lbracket; }, .Asterisk => try appendToken(c, .Asterisk, "*"), else => unreachable, }; node.* = .{ .op_token = op_token, .ptr_info = .{ .const_token = if (is_const) try appendToken(c, .Keyword_const, "const") else null, .volatile_token = if (is_volatile) try appendToken(c, .Keyword_volatile, "volatile") else null, }, .rhs = undefined, // translate and set afterward }; return node; } fn transCreateNodeAPInt(c: *Context, int: *const clang.APSInt) !*ast.Node { const num_limbs = math.cast(usize, int.getNumWords()) catch |err| switch (err) { error.Overflow => return error.OutOfMemory, }; var aps_int = int; const is_negative = int.isSigned() and int.isNegative(); if (is_negative) aps_int = aps_int.negate(); defer if (is_negative) { aps_int.free(); }; const limbs = try c.arena.alloc(math.big.Limb, num_limbs); defer c.arena.free(limbs); const data = aps_int.getRawData(); switch (@sizeOf(math.big.Limb)) { 8 => { var i: usize = 0; while (i < num_limbs) : (i += 1) { limbs[i] = data[i]; } }, 4 => { var limb_i: usize = 0; var data_i: usize = 0; while (limb_i < num_limbs) : ({ limb_i += 2; data_i += 1; }) { limbs[limb_i] = @truncate(u32, data[data_i]); limbs[limb_i + 1] = @truncate(u32, data[data_i] >> 32); } }, else => @compileError("unimplemented"), } const big: math.big.int.Const = .{ .limbs = limbs, .positive = !is_negative }; const str = big.toStringAlloc(c.arena, 10, false) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, }; defer c.arena.free(str); const token = try appendToken(c, .IntegerLiteral, str); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, .token = token, }; return &node.base; } fn transCreateNodeUndefinedLiteral(c: *Context) !*ast.Node { const token = try appendToken(c, .Keyword_undefined, "undefined"); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .UndefinedLiteral }, .token = token, }; return &node.base; } fn transCreateNodeNullLiteral(c: *Context) !*ast.Node { const token = try appendToken(c, .Keyword_null, "null"); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .NullLiteral }, .token = token, }; return &node.base; } fn transCreateNodeBoolLiteral(c: *Context, value: bool) !*ast.Node { const token = if (value) try appendToken(c, .Keyword_true, "true") else try appendToken(c, .Keyword_false, "false"); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .BoolLiteral }, .token = token, }; return &node.base; } fn transCreateNodeInt(c: *Context, int: anytype) !*ast.Node { const token = try appendTokenFmt(c, .IntegerLiteral, "{}", .{int}); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, .token = token, }; return &node.base; } fn transCreateNodeFloat(c: *Context, int: anytype) !*ast.Node { const token = try appendTokenFmt(c, .FloatLiteral, "{}", .{int}); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .FloatLiteral }, .token = token, }; return &node.base; } fn transCreateNodeOpaqueType(c: *Context) !*ast.Node { const container_tok = try appendToken(c, .Keyword_opaque, "opaque"); const lbrace_token = try appendToken(c, .LBrace, "{"); const container_node = try ast.Node.ContainerDecl.alloc(c.arena, 0); container_node.* = .{ .kind_token = container_tok, .layout_token = null, .lbrace_token = lbrace_token, .rbrace_token = try appendToken(c, .RBrace, "}"), .fields_and_decls_len = 0, .init_arg_expr = .None, }; return &container_node.base; } fn transCreateNodeMacroFn(c: *Context, name: []const u8, ref: *ast.Node, proto_alias: *ast.Node.FnProto) !*ast.Node { const scope = &c.global_scope.base; const pub_tok = try appendToken(c, .Keyword_pub, "pub"); const inline_tok = try appendToken(c, .Keyword_inline, "inline"); const fn_tok = try appendToken(c, .Keyword_fn, "fn"); const name_tok = try appendIdentifier(c, name); _ = try appendToken(c, .LParen, "("); var fn_params = std.ArrayList(ast.Node.FnProto.ParamDecl).init(c.gpa); defer fn_params.deinit(); for (proto_alias.params()) |param, i| { if (i != 0) { _ = try appendToken(c, .Comma, ","); } const param_name_tok = param.name_token orelse try appendTokenFmt(c, .Identifier, "arg_{}", .{c.getMangle()}); _ = try appendToken(c, .Colon, ":"); (try fn_params.addOne()).* = .{ .doc_comments = null, .comptime_token = null, .noalias_token = param.noalias_token, .name_token = param_name_tok, .param_type = param.param_type, }; } _ = try appendToken(c, .RParen, ")"); const block_lbrace = try appendToken(c, .LBrace, "{"); const return_kw = try appendToken(c, .Keyword_return, "return"); const unwrap_expr = try transCreateNodeUnwrapNull(c, ref.cast(ast.Node.VarDecl).?.getInitNode().?); const call_expr = try c.createCall(unwrap_expr, fn_params.items.len); const call_params = call_expr.params(); for (fn_params.items) |param, i| { if (i != 0) { _ = try appendToken(c, .Comma, ","); } call_params[i] = try transCreateNodeIdentifier(c, tokenSlice(c, param.name_token.?)); } call_expr.rtoken = try appendToken(c, .RParen, ")"); const return_expr = try ast.Node.ControlFlowExpression.create(c.arena, .{ .ltoken = return_kw, .tag = .Return, }, .{ .rhs = &call_expr.base, }); _ = try appendToken(c, .Semicolon, ";"); const block = try ast.Node.Block.alloc(c.arena, 1); block.* = .{ .lbrace = block_lbrace, .statements_len = 1, .rbrace = try appendToken(c, .RBrace, "}"), }; block.statements()[0] = &return_expr.base; const fn_proto = try ast.Node.FnProto.create(c.arena, .{ .params_len = fn_params.items.len, .fn_token = fn_tok, .return_type = proto_alias.return_type, }, .{ .visib_token = pub_tok, .name_token = name_tok, .extern_export_inline_token = inline_tok, .body_node = &block.base, }); mem.copy(ast.Node.FnProto.ParamDecl, fn_proto.params(), fn_params.items); return &fn_proto.base; } fn transCreateNodeUnwrapNull(c: *Context, wrapped: *ast.Node) !*ast.Node { _ = try appendToken(c, .Period, "."); const qm = try appendToken(c, .QuestionMark, "?"); const node = try c.arena.create(ast.Node.SimpleSuffixOp); node.* = .{ .base = .{ .tag = .UnwrapOptional }, .lhs = wrapped, .rtoken = qm, }; return &node.base; } fn transCreateNodeEnumLiteral(c: *Context, name: []const u8) !*ast.Node { const node = try c.arena.create(ast.Node.EnumLiteral); node.* = .{ .dot = try appendToken(c, .Period, "."), .name = try appendIdentifier(c, name), }; return &node.base; } fn transCreateNodeStringLiteral(c: *Context, str: []const u8) !*ast.Node { const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .StringLiteral }, .token = try appendToken(c, .StringLiteral, str), }; return &node.base; } fn transCreateNodeIf(c: *Context) !*ast.Node.If { const if_tok = try appendToken(c, .Keyword_if, "if"); _ = try appendToken(c, .LParen, "("); const node = try c.arena.create(ast.Node.If); node.* = .{ .if_token = if_tok, .condition = undefined, .payload = null, .body = undefined, .@"else" = null, }; return node; } fn transCreateNodeElse(c: *Context) !*ast.Node.Else { const node = try c.arena.create(ast.Node.Else); node.* = .{ .else_token = try appendToken(c, .Keyword_else, "else"), .payload = null, .body = undefined, }; return node; } fn transCreateNodeBreak( c: *Context, label: ?ast.TokenIndex, rhs: ?*ast.Node, ) !*ast.Node.ControlFlowExpression { var ctrl_flow = try CtrlFlow.init(c, .Break, if (label) |l| tokenSlice(c, l) else null); return ctrl_flow.finish(rhs); } const CtrlFlow = struct { c: *Context, ltoken: ast.TokenIndex, label_token: ?ast.TokenIndex, tag: ast.Node.Tag, /// Does everything except the RHS. fn init(c: *Context, tag: ast.Node.Tag, label: ?[]const u8) !CtrlFlow { const kw: Token.Id = switch (tag) { .Break => .Keyword_break, .Continue => .Keyword_continue, .Return => .Keyword_return, else => unreachable, }; const kw_text = switch (tag) { .Break => "break", .Continue => "continue", .Return => "return", else => unreachable, }; const ltoken = try appendToken(c, kw, kw_text); const label_token = if (label) |l| blk: { _ = try appendToken(c, .Colon, ":"); break :blk try appendIdentifier(c, l); } else null; return CtrlFlow{ .c = c, .ltoken = ltoken, .label_token = label_token, .tag = tag, }; } fn initToken(c: *Context, tag: ast.Node.Tag, label: ?ast.TokenIndex) !CtrlFlow { const other_token = label orelse return init(c, tag, null); const loc = c.token_locs.items[other_token]; const label_name = c.source_buffer.items[loc.start..loc.end]; return init(c, tag, label_name); } fn finish(self: *CtrlFlow, rhs: ?*ast.Node) !*ast.Node.ControlFlowExpression { return ast.Node.ControlFlowExpression.create(self.c.arena, .{ .ltoken = self.ltoken, .tag = self.tag, }, .{ .label = self.label_token, .rhs = rhs, }); } }; fn transCreateNodeWhile(c: *Context) !*ast.Node.While { const while_tok = try appendToken(c, .Keyword_while, "while"); _ = try appendToken(c, .LParen, "("); const node = try c.arena.create(ast.Node.While); node.* = .{ .label = null, .inline_token = null, .while_token = while_tok, .condition = undefined, .payload = null, .continue_expr = null, .body = undefined, .@"else" = null, }; return node; } fn transCreateNodeContinue(c: *Context) !*ast.Node { const ltoken = try appendToken(c, .Keyword_continue, "continue"); const node = try ast.Node.ControlFlowExpression.create(c.arena, .{ .ltoken = ltoken, .tag = .Continue, }, .{}); _ = try appendToken(c, .Semicolon, ";"); return &node.base; } fn transCreateNodeSwitchCase(c: *Context, lhs: *ast.Node) !*ast.Node.SwitchCase { const arrow_tok = try appendToken(c, .EqualAngleBracketRight, "=>"); const node = try ast.Node.SwitchCase.alloc(c.arena, 1); node.* = .{ .items_len = 1, .arrow_token = arrow_tok, .payload = null, .expr = undefined, }; node.items()[0] = lhs; return node; } fn transCreateNodeSwitchElse(c: *Context) !*ast.Node { const node = try c.arena.create(ast.Node.SwitchElse); node.* = .{ .token = try appendToken(c, .Keyword_else, "else"), }; return &node.base; } fn transCreateNodeShiftOp( rp: RestorePoint, scope: *Scope, stmt: *const clang.BinaryOperator, op: ast.Node.Tag, op_tok_id: std.zig.Token.Id, bytes: []const u8, ) !*ast.Node { std.debug.assert(op == .BitShiftLeft or op == .BitShiftRight); const lhs_expr = stmt.getLHS(); const rhs_expr = stmt.getRHS(); const rhs_location = rhs_expr.getBeginLoc(); // lhs >> @as(u5, rh) const lhs = try transExpr(rp, scope, lhs_expr, .used, .l_value); const op_token = try appendToken(rp.c, op_tok_id, bytes); const cast_node = try rp.c.createBuiltinCall("@intCast", 2); const rhs_type = try qualTypeToLog2IntRef(rp, stmt.getType(), rhs_location); cast_node.params()[0] = rhs_type; _ = try appendToken(rp.c, .Comma, ","); const rhs = try transExprCoercing(rp, scope, rhs_expr, .used, .r_value); cast_node.params()[1] = rhs; cast_node.rparen_token = try appendToken(rp.c, .RParen, ")"); const node = try rp.c.arena.create(ast.Node.SimpleInfixOp); node.* = .{ .base = .{ .tag = op }, .op_token = op_token, .lhs = lhs, .rhs = &cast_node.base, }; return &node.base; } fn transCreateNodePtrDeref(c: *Context, lhs: *ast.Node) !*ast.Node { const node = try c.arena.create(ast.Node.SimpleSuffixOp); node.* = .{ .base = .{ .tag = .Deref }, .lhs = lhs, .rtoken = try appendToken(c, .PeriodAsterisk, ".*"), }; return &node.base; } fn transCreateNodeArrayAccess(c: *Context, lhs: *ast.Node) !*ast.Node.ArrayAccess { _ = try appendToken(c, .LBrace, "["); const node = try c.arena.create(ast.Node.ArrayAccess); node.* = .{ .lhs = lhs, .index_expr = undefined, .rtoken = undefined, }; return node; } const RestorePoint = struct { c: *Context, token_index: ast.TokenIndex, src_buf_index: usize, fn activate(self: RestorePoint) void { self.c.token_ids.shrink(self.c.gpa, self.token_index); self.c.token_locs.shrink(self.c.gpa, self.token_index); self.c.source_buffer.shrink(self.src_buf_index); } }; fn makeRestorePoint(c: *Context) RestorePoint { return RestorePoint{ .c = c, .token_index = c.token_ids.items.len, .src_buf_index = c.source_buffer.items.len, }; } fn transType(rp: RestorePoint, ty: *const clang.Type, source_loc: clang.SourceLocation) TypeError!*ast.Node { switch (ty.getTypeClass()) { .Builtin => { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); return transCreateNodeIdentifier(rp.c, switch (builtin_ty.getKind()) { .Void => "c_void", .Bool => "bool", .Char_U, .UChar, .Char_S, .Char8 => "u8", .SChar => "i8", .UShort => "c_ushort", .UInt => "c_uint", .ULong => "c_ulong", .ULongLong => "c_ulonglong", .Short => "c_short", .Int => "c_int", .Long => "c_long", .LongLong => "c_longlong", .UInt128 => "u128", .Int128 => "i128", .Float => "f32", .Double => "f64", .Float128 => "f128", .Float16 => "f16", .LongDouble => "c_longdouble", else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported builtin type", .{}), }); }, .FunctionProto => { const fn_proto_ty = @ptrCast(*const clang.FunctionProtoType, ty); const fn_proto = try transFnProto(rp, null, fn_proto_ty, source_loc, null, false); return &fn_proto.base; }, .FunctionNoProto => { const fn_no_proto_ty = @ptrCast(*const clang.FunctionType, ty); const fn_proto = try transFnNoProto(rp, fn_no_proto_ty, source_loc, null, false); return &fn_proto.base; }, .Paren => { const paren_ty = @ptrCast(*const clang.ParenType, ty); return transQualType(rp, paren_ty.getInnerType(), source_loc); }, .Pointer => { const child_qt = ty.getPointeeType(); if (qualTypeChildIsFnProto(child_qt)) { const optional_node = try transCreateNodeSimplePrefixOp(rp.c, .OptionalType, .QuestionMark, "?"); optional_node.rhs = try transQualType(rp, child_qt, source_loc); return &optional_node.base; } if (typeIsOpaque(rp.c, child_qt.getTypePtr(), source_loc) or qualTypeWasDemotedToOpaque(rp.c, child_qt)) { const optional_node = try transCreateNodeSimplePrefixOp(rp.c, .OptionalType, .QuestionMark, "?"); const pointer_node = try transCreateNodePtrType( rp.c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), .Asterisk, ); optional_node.rhs = &pointer_node.base; pointer_node.rhs = try transQualType(rp, child_qt, source_loc); return &optional_node.base; } const pointer_node = try transCreateNodePtrType( rp.c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), .Identifier, ); pointer_node.rhs = try transQualType(rp, child_qt, source_loc); return &pointer_node.base; }, .ConstantArray => { const const_arr_ty = @ptrCast(*const clang.ConstantArrayType, ty); const size_ap_int = const_arr_ty.getSize(); const size = size_ap_int.getLimitedValue(math.maxInt(usize)); const elem_ty = const_arr_ty.getElementType().getTypePtr(); return try transCreateNodeArrayType(rp, source_loc, elem_ty, size); }, .IncompleteArray => { const incomplete_array_ty = @ptrCast(*const clang.IncompleteArrayType, ty); const child_qt = incomplete_array_ty.getElementType(); var node = try transCreateNodePtrType( rp.c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), .Identifier, ); node.rhs = try transQualType(rp, child_qt, source_loc); return &node.base; }, .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); return (try transTypeDef(rp.c, typedef_decl, false)) orelse revertAndWarn(rp, error.UnsupportedType, source_loc, "unable to translate typedef declaration", .{}); }, .Record => { const record_ty = @ptrCast(*const clang.RecordType, ty); const record_decl = record_ty.getDecl(); return (try transRecordDecl(rp.c, record_decl)) orelse revertAndWarn(rp, error.UnsupportedType, source_loc, "unable to resolve record declaration", .{}); }, .Enum => { const enum_ty = @ptrCast(*const clang.EnumType, ty); const enum_decl = enum_ty.getDecl(); return (try transEnumDecl(rp.c, enum_decl)) orelse revertAndWarn(rp, error.UnsupportedType, source_loc, "unable to translate enum declaration", .{}); }, .Elaborated => { const elaborated_ty = @ptrCast(*const clang.ElaboratedType, ty); return transQualType(rp, elaborated_ty.getNamedType(), source_loc); }, .Decayed => { const decayed_ty = @ptrCast(*const clang.DecayedType, ty); return transQualType(rp, decayed_ty.getDecayedType(), source_loc); }, .Attributed => { const attributed_ty = @ptrCast(*const clang.AttributedType, ty); return transQualType(rp, attributed_ty.getEquivalentType(), source_loc); }, .MacroQualified => { const macroqualified_ty = @ptrCast(*const clang.MacroQualifiedType, ty); return transQualType(rp, macroqualified_ty.getModifiedType(), source_loc); }, else => { const type_name = rp.c.str(ty.getTypeClassName()); return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{}'", .{type_name}); }, } } fn qualTypeWasDemotedToOpaque(c: *Context, qt: clang.QualType) bool { const ty = qt.getTypePtr(); switch (qt.getTypeClass()) { .Typedef => { const typedef_ty = @ptrCast(*const clang.TypedefType, ty); const typedef_decl = typedef_ty.getDecl(); const underlying_type = typedef_decl.getUnderlyingType(); return qualTypeWasDemotedToOpaque(c, underlying_type); }, .Record => { const record_ty = @ptrCast(*const clang.RecordType, ty); const record_decl = record_ty.getDecl(); const canonical = @ptrToInt(record_decl.getCanonicalDecl()); return c.opaque_demotes.contains(canonical); }, .Enum => { const enum_ty = @ptrCast(*const clang.EnumType, ty); const enum_decl = enum_ty.getDecl(); const canonical = @ptrToInt(enum_decl.getCanonicalDecl()); return c.opaque_demotes.contains(canonical); }, .Elaborated => { const elaborated_ty = @ptrCast(*const clang.ElaboratedType, ty); return qualTypeWasDemotedToOpaque(c, elaborated_ty.getNamedType()); }, .Decayed => { const decayed_ty = @ptrCast(*const clang.DecayedType, ty); return qualTypeWasDemotedToOpaque(c, decayed_ty.getDecayedType()); }, .Attributed => { const attributed_ty = @ptrCast(*const clang.AttributedType, ty); return qualTypeWasDemotedToOpaque(c, attributed_ty.getEquivalentType()); }, .MacroQualified => { const macroqualified_ty = @ptrCast(*const clang.MacroQualifiedType, ty); return qualTypeWasDemotedToOpaque(c, macroqualified_ty.getModifiedType()); }, else => return false, } } fn isCVoid(qt: clang.QualType) bool { const ty = qt.getTypePtr(); if (ty.getTypeClass() == .Builtin) { const builtin_ty = @ptrCast(*const clang.BuiltinType, ty); return builtin_ty.getKind() == .Void; } return false; } const FnDeclContext = struct { fn_name: []const u8, has_body: bool, storage_class: clang.StorageClass, is_export: bool, }; fn transCC( rp: RestorePoint, fn_ty: *const clang.FunctionType, source_loc: clang.SourceLocation, ) !CallingConvention { const clang_cc = fn_ty.getCallConv(); switch (clang_cc) { .C => return CallingConvention.C, .X86StdCall => return CallingConvention.Stdcall, .X86FastCall => return CallingConvention.Fastcall, .X86VectorCall, .AArch64VectorCall => return CallingConvention.Vectorcall, .X86ThisCall => return CallingConvention.Thiscall, .AAPCS => return CallingConvention.AAPCS, .AAPCS_VFP => return CallingConvention.AAPCSVFP, else => return revertAndWarn( rp, error.UnsupportedType, source_loc, "unsupported calling convention: {}", .{@tagName(clang_cc)}, ), } } fn transFnProto( rp: RestorePoint, fn_decl: ?*const clang.FunctionDecl, fn_proto_ty: *const clang.FunctionProtoType, source_loc: clang.SourceLocation, fn_decl_context: ?FnDeclContext, is_pub: bool, ) !*ast.Node.FnProto { const fn_ty = @ptrCast(*const clang.FunctionType, fn_proto_ty); const cc = try transCC(rp, fn_ty, source_loc); const is_var_args = fn_proto_ty.isVariadic(); return finishTransFnProto(rp, fn_decl, fn_proto_ty, fn_ty, source_loc, fn_decl_context, is_var_args, cc, is_pub); } fn transFnNoProto( rp: RestorePoint, fn_ty: *const clang.FunctionType, source_loc: clang.SourceLocation, fn_decl_context: ?FnDeclContext, is_pub: bool, ) !*ast.Node.FnProto { const cc = try transCC(rp, fn_ty, source_loc); const is_var_args = if (fn_decl_context) |ctx| !ctx.is_export else true; return finishTransFnProto(rp, null, null, fn_ty, source_loc, fn_decl_context, is_var_args, cc, is_pub); } fn finishTransFnProto( rp: RestorePoint, fn_decl: ?*const clang.FunctionDecl, fn_proto_ty: ?*const clang.FunctionProtoType, fn_ty: *const clang.FunctionType, source_loc: clang.SourceLocation, fn_decl_context: ?FnDeclContext, is_var_args: bool, cc: CallingConvention, is_pub: bool, ) !*ast.Node.FnProto { const is_export = if (fn_decl_context) |ctx| ctx.is_export else false; const is_extern = if (fn_decl_context) |ctx| !ctx.has_body else false; // TODO check for always_inline attribute // TODO check for align attribute // pub extern fn name(...) T const pub_tok = if (is_pub) try appendToken(rp.c, .Keyword_pub, "pub") else null; const extern_export_inline_tok = if (is_export) try appendToken(rp.c, .Keyword_export, "export") else if (is_extern) try appendToken(rp.c, .Keyword_extern, "extern") else null; const fn_tok = try appendToken(rp.c, .Keyword_fn, "fn"); const name_tok = if (fn_decl_context) |ctx| try appendIdentifier(rp.c, ctx.fn_name) else null; const lparen_tok = try appendToken(rp.c, .LParen, "("); var fn_params = std.ArrayList(ast.Node.FnProto.ParamDecl).init(rp.c.gpa); defer fn_params.deinit(); const param_count: usize = if (fn_proto_ty != null) fn_proto_ty.?.getNumParams() else 0; try fn_params.ensureCapacity(param_count + 1); // +1 for possible var args node var i: usize = 0; while (i < param_count) : (i += 1) { const param_qt = fn_proto_ty.?.getParamType(@intCast(c_uint, i)); const noalias_tok = if (param_qt.isRestrictQualified()) try appendToken(rp.c, .Keyword_noalias, "noalias") else null; const param_name_tok: ?ast.TokenIndex = blk: { if (fn_decl) |decl| { const param = decl.getParamDecl(@intCast(c_uint, i)); const param_name: []const u8 = try rp.c.str(@ptrCast(*const clang.NamedDecl, param).getName_bytes_begin()); if (param_name.len < 1) break :blk null; const result = try appendIdentifier(rp.c, param_name); _ = try appendToken(rp.c, .Colon, ":"); break :blk result; } break :blk null; }; const type_node = try transQualType(rp, param_qt, source_loc); fn_params.addOneAssumeCapacity().* = .{ .doc_comments = null, .comptime_token = null, .noalias_token = noalias_tok, .name_token = param_name_tok, .param_type = .{ .type_expr = type_node }, }; if (i + 1 < param_count) { _ = try appendToken(rp.c, .Comma, ","); } } const var_args_token: ?ast.TokenIndex = if (is_var_args) blk: { if (param_count > 0) { _ = try appendToken(rp.c, .Comma, ","); } break :blk try appendToken(rp.c, .Ellipsis3, "..."); } else null; const rparen_tok = try appendToken(rp.c, .RParen, ")"); const linksection_expr = blk: { if (fn_decl) |decl| { var str_len: usize = undefined; if (decl.getSectionAttribute(&str_len)) |str_ptr| { _ = try appendToken(rp.c, .Keyword_linksection, "linksection"); _ = try appendToken(rp.c, .LParen, "("); const expr = try transCreateNodeStringLiteral( rp.c, try std.fmt.allocPrint(rp.c.arena, "\"{}\"", .{str_ptr[0..str_len]}), ); _ = try appendToken(rp.c, .RParen, ")"); break :blk expr; } } break :blk null; }; const align_expr = blk: { if (fn_decl) |decl| { const alignment = decl.getAlignedAttribute(rp.c.clang_context); if (alignment != 0) { _ = try appendToken(rp.c, .Keyword_align, "align"); _ = try appendToken(rp.c, .LParen, "("); // Clang reports the alignment in bits const expr = try transCreateNodeInt(rp.c, alignment / 8); _ = try appendToken(rp.c, .RParen, ")"); break :blk expr; } } break :blk null; }; const callconv_expr = if ((is_export or is_extern) and cc == .C) null else blk: { _ = try appendToken(rp.c, .Keyword_callconv, "callconv"); _ = try appendToken(rp.c, .LParen, "("); const expr = try transCreateNodeEnumLiteral(rp.c, @tagName(cc)); _ = try appendToken(rp.c, .RParen, ")"); break :blk expr; }; const return_type_node = blk: { if (fn_ty.getNoReturnAttr()) { break :blk try transCreateNodeIdentifier(rp.c, "noreturn"); } else { const return_qt = fn_ty.getReturnType(); if (isCVoid(return_qt)) { // convert primitive c_void to actual void (only for return type) break :blk try transCreateNodeIdentifier(rp.c, "void"); } else { break :blk transQualType(rp, return_qt, source_loc) catch |err| switch (err) { error.UnsupportedType => { try emitWarning(rp.c, source_loc, "unsupported function proto return type", .{}); return err; }, error.OutOfMemory => |e| return e, }; } } }; // We need to reserve an undefined (but non-null) body node to set later. var body_node: ?*ast.Node = null; if (fn_decl_context) |ctx| { if (ctx.has_body) { // TODO: we should be able to use undefined here but // it causes a bug. This is undefined without zig language // being aware of it. body_node = @intToPtr(*ast.Node, 0x08); } } const fn_proto = try ast.Node.FnProto.create(rp.c.arena, .{ .params_len = fn_params.items.len, .return_type = .{ .Explicit = return_type_node }, .fn_token = fn_tok, }, .{ .visib_token = pub_tok, .name_token = name_tok, .extern_export_inline_token = extern_export_inline_tok, .align_expr = align_expr, .section_expr = linksection_expr, .callconv_expr = callconv_expr, .body_node = body_node, .var_args_token = var_args_token, }); mem.copy(ast.Node.FnProto.ParamDecl, fn_proto.params(), fn_params.items); return fn_proto; } fn revertAndWarn( rp: RestorePoint, err: anytype, source_loc: clang.SourceLocation, comptime format: []const u8, args: anytype, ) (@TypeOf(err) || error{OutOfMemory}) { rp.activate(); try emitWarning(rp.c, source_loc, format, args); return err; } fn emitWarning(c: *Context, loc: clang.SourceLocation, comptime format: []const u8, args: anytype) !void { const args_prefix = .{c.locStr(loc)}; _ = try appendTokenFmt(c, .LineComment, "// {}: warning: " ++ format, args_prefix ++ args); } pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, comptime format: []const u8, args: anytype) !void { // pub const name = @compileError(msg); const pub_tok = try appendToken(c, .Keyword_pub, "pub"); const const_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendIdentifier(c, name); const eq_tok = try appendToken(c, .Equal, "="); const builtin_tok = try appendToken(c, .Builtin, "@compileError"); const lparen_tok = try appendToken(c, .LParen, "("); const msg_tok = try appendTokenFmt(c, .StringLiteral, "\"" ++ format ++ "\"", args); const rparen_tok = try appendToken(c, .RParen, ")"); const semi_tok = try appendToken(c, .Semicolon, ";"); _ = try appendTokenFmt(c, .LineComment, "// {}", .{c.locStr(loc)}); const msg_node = try c.arena.create(ast.Node.OneToken); msg_node.* = .{ .base = .{ .tag = .StringLiteral }, .token = msg_tok, }; const call_node = try ast.Node.BuiltinCall.alloc(c.arena, 1); call_node.* = .{ .builtin_token = builtin_tok, .params_len = 1, .rparen_token = rparen_tok, }; call_node.params()[0] = &msg_node.base; const var_decl_node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = const_tok, .semicolon_token = semi_tok, }, .{ .visib_token = pub_tok, .eq_token = eq_tok, .init_node = &call_node.base, }); try addTopLevelDecl(c, name, &var_decl_node.base); } fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenIndex { std.debug.assert(token_id != .Identifier); // use appendIdentifier return appendTokenFmt(c, token_id, "{}", .{bytes}); } fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: anytype) !ast.TokenIndex { assert(token_id != .Invalid); try c.token_ids.ensureCapacity(c.gpa, c.token_ids.items.len + 1); try c.token_locs.ensureCapacity(c.gpa, c.token_locs.items.len + 1); const start_index = c.source_buffer.items.len; try c.source_buffer.outStream().print(format ++ " ", args); c.token_ids.appendAssumeCapacity(token_id); c.token_locs.appendAssumeCapacity(.{ .start = start_index, .end = c.source_buffer.items.len - 1, // back up before the space }); return c.token_ids.items.len - 1; } // TODO hook up with codegen fn isZigPrimitiveType(name: []const u8) bool { if (name.len > 1 and (name[0] == 'u' or name[0] == 'i')) { for (name[1..]) |c| { switch (c) { '0'...'9' => {}, else => return false, } } return true; } // void is invalid in c so it doesn't need to be checked. return mem.eql(u8, name, "comptime_float") or mem.eql(u8, name, "comptime_int") or mem.eql(u8, name, "bool") or mem.eql(u8, name, "isize") or mem.eql(u8, name, "usize") or mem.eql(u8, name, "f16") or mem.eql(u8, name, "f32") or mem.eql(u8, name, "f64") or mem.eql(u8, name, "f128") or mem.eql(u8, name, "c_longdouble") or mem.eql(u8, name, "noreturn") or mem.eql(u8, name, "type") or mem.eql(u8, name, "anyerror") or mem.eql(u8, name, "c_short") or mem.eql(u8, name, "c_ushort") or mem.eql(u8, name, "c_int") or mem.eql(u8, name, "c_uint") or mem.eql(u8, name, "c_long") or mem.eql(u8, name, "c_ulong") or mem.eql(u8, name, "c_longlong") or mem.eql(u8, name, "c_ulonglong"); } fn appendIdentifier(c: *Context, name: []const u8) !ast.TokenIndex { return appendTokenFmt(c, .Identifier, "{z}", .{name}); } fn transCreateNodeIdentifier(c: *Context, name: []const u8) !*ast.Node { const token_index = try appendIdentifier(c, name); const identifier = try c.arena.create(ast.Node.OneToken); identifier.* = .{ .base = .{ .tag = .Identifier }, .token = token_index, }; return &identifier.base; } fn transCreateNodeIdentifierUnchecked(c: *Context, name: []const u8) !*ast.Node { const token_index = try appendTokenFmt(c, .Identifier, "{}", .{name}); const identifier = try c.arena.create(ast.Node.OneToken); identifier.* = .{ .base = .{ .tag = .Identifier }, .token = token_index, }; return &identifier.base; } pub fn freeErrors(errors: []ClangErrMsg) void { errors.ptr.delete(errors.len); } const MacroCtx = struct { source: []const u8, list: []const CToken, i: usize = 0, loc: clang.SourceLocation, name: []const u8, fn peek(self: *MacroCtx) ?CToken.Id { if (self.i >= self.list.len) return null; return self.list[self.i + 1].id; } fn next(self: *MacroCtx) ?CToken.Id { if (self.i >= self.list.len) return null; self.i += 1; return self.list[self.i].id; } fn slice(self: *MacroCtx) []const u8 { const tok = self.list[self.i]; return self.source[tok.start..tok.end]; } fn fail(self: *MacroCtx, c: *Context, comptime fmt: []const u8, args: anytype) !void { return failDecl(c, self.loc, self.name, fmt, args); } }; fn transPreprocessorEntities(c: *Context, unit: *clang.ASTUnit) Error!void { // TODO if we see #undef, delete it from the table var it = unit.getLocalPreprocessingEntities_begin(); const it_end = unit.getLocalPreprocessingEntities_end(); var tok_list = std.ArrayList(CToken).init(c.gpa); defer tok_list.deinit(); const scope = c.global_scope; while (it.I != it_end.I) : (it.I += 1) { const entity = it.deref(); tok_list.items.len = 0; switch (entity.getKind()) { .MacroDefinitionKind => { const macro = @ptrCast(*clang.MacroDefinitionRecord, entity); const raw_name = macro.getName_getNameStart(); const begin_loc = macro.getSourceRange_getBegin(); const name = try c.str(raw_name); // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ name, c.getMangle() }) else name; if (scope.containsNow(mangled_name)) { continue; } const begin_c = c.source_manager.getCharacterData(begin_loc); const slice = begin_c[0..mem.len(begin_c)]; var tokenizer = std.c.Tokenizer{ .buffer = slice, }; while (true) { const tok = tokenizer.next(); switch (tok.id) { .Nl, .Eof => { try tok_list.append(tok); break; }, .LineComment, .MultiLineComment => continue, else => {}, } try tok_list.append(tok); } var macro_ctx = MacroCtx{ .source = slice, .list = tok_list.items, .name = mangled_name, .loc = begin_loc, }; assert(mem.eql(u8, macro_ctx.slice(), name)); var macro_fn = false; switch (macro_ctx.peek().?) { .Identifier => { // if it equals itself, ignore. for example, from stdio.h: // #define stdin stdin const tok = macro_ctx.list[1]; if (mem.eql(u8, name, slice[tok.start..tok.end])) { continue; } }, .Nl, .Eof => { // this means it is a macro without a value // we don't care about such things continue; }, .LParen => { // if the name is immediately followed by a '(' then it is a function macro_fn = macro_ctx.list[0].end == macro_ctx.list[1].start; }, else => {}, } (if (macro_fn) transMacroFnDefine(c, &macro_ctx) else transMacroDefine(c, &macro_ctx)) catch |err| switch (err) { error.ParseError => continue, error.OutOfMemory => |e| return e, }; }, else => {}, } } } fn transMacroDefine(c: *Context, m: *MacroCtx) ParseError!void { const scope = &c.global_scope.base; const visib_tok = try appendToken(c, .Keyword_pub, "pub"); const mut_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendIdentifier(c, m.name); const eq_token = try appendToken(c, .Equal, "="); const init_node = try parseCExpr(c, m, scope); const last = m.next().?; if (last != .Eof and last != .Nl) return m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(last)}); const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ .name_token = name_tok, .mut_token = mut_tok, .semicolon_token = semicolon_token, }, .{ .visib_token = visib_tok, .eq_token = eq_token, .init_node = init_node, }); _ = try c.global_scope.macro_table.put(m.name, &node.base); } fn transMacroFnDefine(c: *Context, m: *MacroCtx) ParseError!void { var block_scope = try Scope.Block.init(c, &c.global_scope.base, false); defer block_scope.deinit(); const scope = &block_scope.base; const pub_tok = try appendToken(c, .Keyword_pub, "pub"); const inline_tok = try appendToken(c, .Keyword_inline, "inline"); const fn_tok = try appendToken(c, .Keyword_fn, "fn"); const name_tok = try appendIdentifier(c, m.name); _ = try appendToken(c, .LParen, "("); if (m.next().? != .LParen) { return m.fail(c, "unable to translate C expr: expected '('", .{}); } var fn_params = std.ArrayList(ast.Node.FnProto.ParamDecl).init(c.gpa); defer fn_params.deinit(); while (true) { if (m.peek().? != .Identifier) break; _ = m.next(); const mangled_name = try block_scope.makeMangledName(c, m.slice()); const param_name_tok = try appendIdentifier(c, mangled_name); _ = try appendToken(c, .Colon, ":"); const any_type = try c.arena.create(ast.Node.OneToken); any_type.* = .{ .base = .{ .tag = .AnyType }, .token = try appendToken(c, .Keyword_anytype, "anytype"), }; (try fn_params.addOne()).* = .{ .doc_comments = null, .comptime_token = null, .noalias_token = null, .name_token = param_name_tok, .param_type = .{ .any_type = &any_type.base }, }; if (m.peek().? != .Comma) break; _ = m.next(); _ = try appendToken(c, .Comma, ","); } if (m.next().? != .RParen) { return m.fail(c, "unable to translate C expr: expected ')'", .{}); } _ = try appendToken(c, .RParen, ")"); const type_of = try c.createBuiltinCall("@TypeOf", 1); const return_kw = try appendToken(c, .Keyword_return, "return"); const expr = try parseCExpr(c, m, scope); const last = m.next().?; if (last != .Eof and last != .Nl) return m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(last)}); _ = try appendToken(c, .Semicolon, ";"); const type_of_arg = if (!expr.tag.isBlock()) expr else blk: { const stmts = expr.blockStatements(); const blk_last = stmts[stmts.len - 1]; const br = blk_last.cast(ast.Node.ControlFlowExpression).?; break :blk br.getRHS().?; }; type_of.params()[0] = type_of_arg; type_of.rparen_token = try appendToken(c, .RParen, ")"); const return_expr = try ast.Node.ControlFlowExpression.create(c.arena, .{ .ltoken = return_kw, .tag = .Return, }, .{ .rhs = expr, }); try block_scope.statements.append(&return_expr.base); const block_node = try block_scope.complete(c); const fn_proto = try ast.Node.FnProto.create(c.arena, .{ .fn_token = fn_tok, .params_len = fn_params.items.len, .return_type = .{ .Explicit = &type_of.base }, }, .{ .visib_token = pub_tok, .extern_export_inline_token = inline_tok, .name_token = name_tok, .body_node = block_node, }); mem.copy(ast.Node.FnProto.ParamDecl, fn_proto.params(), fn_params.items); _ = try c.global_scope.macro_table.put(m.name, &fn_proto.base); } const ParseError = Error || error{ParseError}; fn parseCExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { // TODO parseCAssignExpr here const node = try parseCCondExpr(c, m, scope); if (m.next().? != .Comma) { m.i -= 1; return node; } _ = try appendToken(c, .Semicolon, ";"); var block_scope = try Scope.Block.init(c, scope, true); defer block_scope.deinit(); var last = node; while (true) { // suppress result const lhs = try transCreateNodeIdentifier(c, "_"); const op_token = try appendToken(c, .Equal, "="); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .Assign }, .op_token = op_token, .lhs = lhs, .rhs = last, }; try block_scope.statements.append(&op_node.base); last = try parseCCondExpr(c, m, scope); _ = try appendToken(c, .Semicolon, ";"); if (m.next().? != .Comma) { m.i -= 1; break; } } const break_node = try transCreateNodeBreak(c, block_scope.label, last); try block_scope.statements.append(&break_node.base); return try block_scope.complete(c); } fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!*ast.Node { var lit_bytes = m.slice(); switch (m.list[m.i].id) { .IntegerLiteral => |suffix| { if (lit_bytes.len > 2 and lit_bytes[0] == '0') { switch (lit_bytes[1]) { '0'...'7' => { // Octal lit_bytes = try std.fmt.allocPrint(c.arena, "0o{}", .{lit_bytes}); }, 'X' => { // Hexadecimal with capital X, valid in C but not in Zig lit_bytes = try std.fmt.allocPrint(c.arena, "0x{}", .{lit_bytes[2..]}); }, else => {}, } } if (suffix == .none) { return transCreateNodeInt(c, lit_bytes); } const cast_node = try c.createBuiltinCall("@as", 2); cast_node.params()[0] = try transCreateNodeIdentifier(c, switch (suffix) { .u => "c_uint", .l => "c_long", .lu => "c_ulong", .ll => "c_longlong", .llu => "c_ulonglong", else => unreachable, }); lit_bytes = lit_bytes[0 .. lit_bytes.len - switch (suffix) { .u, .l => @as(u8, 1), .lu, .ll => 2, .llu => 3, else => unreachable, }]; _ = try appendToken(c, .Comma, ","); cast_node.params()[1] = try transCreateNodeInt(c, lit_bytes); cast_node.rparen_token = try appendToken(c, .RParen, ")"); return &cast_node.base; }, .FloatLiteral => |suffix| { if (lit_bytes[0] == '.') lit_bytes = try std.fmt.allocPrint(c.arena, "0{}", .{lit_bytes}); if (suffix == .none) { return transCreateNodeFloat(c, lit_bytes); } const cast_node = try c.createBuiltinCall("@as", 2); cast_node.params()[0] = try transCreateNodeIdentifier(c, switch (suffix) { .f => "f32", .l => "c_longdouble", else => unreachable, }); _ = try appendToken(c, .Comma, ","); cast_node.params()[1] = try transCreateNodeFloat(c, lit_bytes[0 .. lit_bytes.len - 1]); cast_node.rparen_token = try appendToken(c, .RParen, ")"); return &cast_node.base; }, else => unreachable, } } fn zigifyEscapeSequences(ctx: *Context, m: *MacroCtx) ![]const u8 { var source = m.slice(); for (source) |c, i| { if (c == '\"' or c == '\'') { source = source[i..]; break; } } for (source) |c| { if (c == '\\') { break; } } else return source; var bytes = try ctx.arena.alloc(u8, source.len * 2); var state: enum { Start, Escape, Hex, Octal, } = .Start; var i: usize = 0; var count: u8 = 0; var num: u8 = 0; for (source) |c| { switch (state) { .Escape => { switch (c) { 'n', 'r', 't', '\\', '\'', '\"' => { bytes[i] = c; }, '0'...'7' => { count += 1; num += c - '0'; state = .Octal; bytes[i] = 'x'; }, 'x' => { state = .Hex; bytes[i] = 'x'; }, 'a' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = '7'; }, 'b' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = '8'; }, 'f' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = 'C'; }, 'v' => { bytes[i] = 'x'; i += 1; bytes[i] = '0'; i += 1; bytes[i] = 'B'; }, '?' => { i -= 1; bytes[i] = '?'; }, 'u', 'U' => { try m.fail(ctx, "macro tokenizing failed: TODO unicode escape sequences", .{}); return error.ParseError; }, else => { try m.fail(ctx, "macro tokenizing failed: unknown escape sequence", .{}); return error.ParseError; }, } i += 1; if (state == .Escape) state = .Start; }, .Start => { if (c == '\\') { state = .Escape; } bytes[i] = c; i += 1; }, .Hex => { switch (c) { '0'...'9' => { num = std.math.mul(u8, num, 16) catch { try m.fail(ctx, "macro tokenizing failed: hex literal overflowed", .{}); return error.ParseError; }; num += c - '0'; }, 'a'...'f' => { num = std.math.mul(u8, num, 16) catch { try m.fail(ctx, "macro tokenizing failed: hex literal overflowed", .{}); return error.ParseError; }; num += c - 'a' + 10; }, 'A'...'F' => { num = std.math.mul(u8, num, 16) catch { try m.fail(ctx, "macro tokenizing failed: hex literal overflowed", .{}); return error.ParseError; }; num += c - 'A' + 10; }, else => { i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{ .fill = '0', .width = 2 }); num = 0; if (c == '\\') state = .Escape else state = .Start; bytes[i] = c; i += 1; }, } }, .Octal => { const accept_digit = switch (c) { // The maximum length of a octal literal is 3 digits '0'...'7' => count < 3, else => false, }; if (accept_digit) { count += 1; num = std.math.mul(u8, num, 8) catch { try m.fail(ctx, "macro tokenizing failed: octal literal overflowed", .{}); return error.ParseError; }; num += c - '0'; } else { i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{ .fill = '0', .width = 2 }); num = 0; count = 0; if (c == '\\') state = .Escape else state = .Start; bytes[i] = c; i += 1; } }, } } if (state == .Hex or state == .Octal) i += std.fmt.formatIntBuf(bytes[i..], num, 16, false, std.fmt.FormatOptions{ .fill = '0', .width = 2 }); return bytes[0..i]; } fn parseCPrimaryExprInner(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { const tok = m.next().?; const slice = m.slice(); switch (tok) { .CharLiteral => { if (slice[0] != '\'' or slice[1] == '\\' or slice.len == 3) { const token = try appendToken(c, .CharLiteral, try zigifyEscapeSequences(c, m)); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .CharLiteral }, .token = token, }; return &node.base; } else { const token = try appendTokenFmt(c, .IntegerLiteral, "0x{x}", .{slice[1 .. slice.len - 1]}); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, .token = token, }; return &node.base; } }, .StringLiteral => { const token = try appendToken(c, .StringLiteral, try zigifyEscapeSequences(c, m)); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .StringLiteral }, .token = token, }; return &node.base; }, .IntegerLiteral, .FloatLiteral => { return parseCNumLit(c, m); }, // eventually this will be replaced by std.c.parse which will handle these correctly .Keyword_void => return transCreateNodeIdentifierUnchecked(c, "c_void"), .Keyword_bool => return transCreateNodeIdentifierUnchecked(c, "bool"), .Keyword_double => return transCreateNodeIdentifierUnchecked(c, "f64"), .Keyword_long => return transCreateNodeIdentifierUnchecked(c, "c_long"), .Keyword_int => return transCreateNodeIdentifierUnchecked(c, "c_int"), .Keyword_float => return transCreateNodeIdentifierUnchecked(c, "f32"), .Keyword_short => return transCreateNodeIdentifierUnchecked(c, "c_short"), .Keyword_char => return transCreateNodeIdentifierUnchecked(c, "u8"), .Keyword_unsigned => if (m.next()) |t| switch (t) { .Keyword_char => return transCreateNodeIdentifierUnchecked(c, "u8"), .Keyword_short => return transCreateNodeIdentifierUnchecked(c, "c_ushort"), .Keyword_int => return transCreateNodeIdentifierUnchecked(c, "c_uint"), .Keyword_long => if (m.peek() != null and m.peek().? == .Keyword_long) { _ = m.next(); return transCreateNodeIdentifierUnchecked(c, "c_ulonglong"); } else return transCreateNodeIdentifierUnchecked(c, "c_ulong"), else => { m.i -= 1; return transCreateNodeIdentifierUnchecked(c, "c_uint"); }, } else { return transCreateNodeIdentifierUnchecked(c, "c_uint"); }, .Keyword_signed => if (m.next()) |t| switch (t) { .Keyword_char => return transCreateNodeIdentifierUnchecked(c, "i8"), .Keyword_short => return transCreateNodeIdentifierUnchecked(c, "c_short"), .Keyword_int => return transCreateNodeIdentifierUnchecked(c, "c_int"), .Keyword_long => if (m.peek() != null and m.peek().? == .Keyword_long) { _ = m.next(); return transCreateNodeIdentifierUnchecked(c, "c_longlong"); } else return transCreateNodeIdentifierUnchecked(c, "c_long"), else => { m.i -= 1; return transCreateNodeIdentifierUnchecked(c, "c_int"); }, } else { return transCreateNodeIdentifierUnchecked(c, "c_int"); }, .Keyword_enum, .Keyword_struct, .Keyword_union => { // struct Foo will be declared as struct_Foo by transRecordDecl const next_id = m.next().?; if (next_id != .Identifier) { try m.fail(c, "unable to translate C expr: expected Identifier instead got: {}", .{@tagName(next_id)}); return error.ParseError; } const ident_token = try appendTokenFmt(c, .Identifier, "{}_{}", .{ slice, m.slice() }); const identifier = try c.arena.create(ast.Node.OneToken); identifier.* = .{ .base = .{ .tag = .Identifier }, .token = ident_token, }; return &identifier.base; }, .Identifier => { const mangled_name = scope.getAlias(slice); return transCreateNodeIdentifier(c, checkForBuiltinTypedef(mangled_name) orelse mangled_name); }, .LParen => { const inner_node = try parseCExpr(c, m, scope); const next_id = m.next().?; if (next_id != .RParen) { try m.fail(c, "unable to translate C expr: expected ')' instead got: {}", .{@tagName(next_id)}); return error.ParseError; } var saw_l_paren = false; var saw_integer_literal = false; switch (m.peek().?) { // (type)(to_cast) .LParen => { saw_l_paren = true; _ = m.next(); }, // (type)sizeof(x) .Keyword_sizeof, // (type)alignof(x) .Keyword_alignof, // (type)identifier .Identifier => {}, // (type)integer .IntegerLiteral => { saw_integer_literal = true; }, else => return inner_node, } // hack to get zig fmt to render a comma in builtin calls _ = try appendToken(c, .Comma, ","); const node_to_cast = try parseCExpr(c, m, scope); if (saw_l_paren and m.next().? != .RParen) { try m.fail(c, "unable to translate C expr: expected ')'", .{}); return error.ParseError; } const lparen = try appendToken(c, .LParen, "("); //(@import("std").meta.cast(dest, x)) const import_fn_call = try c.createBuiltinCall("@import", 1); const std_node = try transCreateNodeStringLiteral(c, "\"std\""); import_fn_call.params()[0] = std_node; import_fn_call.rparen_token = try appendToken(c, .RParen, ")"); const inner_field_access = try transCreateNodeFieldAccess(c, &import_fn_call.base, "meta"); const outer_field_access = try transCreateNodeFieldAccess(c, inner_field_access, "cast"); const cast_fn_call = try c.createCall(outer_field_access, 2); cast_fn_call.params()[0] = inner_node; cast_fn_call.params()[1] = node_to_cast; cast_fn_call.rtoken = try appendToken(c, .RParen, ")"); const group_node = try c.arena.create(ast.Node.GroupedExpression); group_node.* = .{ .lparen = lparen, .expr = &cast_fn_call.base, .rparen = try appendToken(c, .RParen, ")"), }; return &group_node.base; }, else => { try m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(tok)}); return error.ParseError; }, } } fn parseCPrimaryExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCPrimaryExprInner(c, m, scope); // In C the preprocessor would handle concatting strings while expanding macros. // This should do approximately the same by concatting any strings and identifiers // after a primary expression. while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.peek().?) { .StringLiteral, .Identifier => {}, else => break, } const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .ArrayCat }, .op_token = try appendToken(c, .PlusPlus, "++"), .lhs = node, .rhs = try parseCPrimaryExprInner(c, m, scope), }; node = &op_node.base; } return node; } fn nodeIsInfixOp(tag: ast.Node.Tag) bool { return switch (tag) { .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, .UnwrapOptional, .Catch, => true, else => false, }; } fn macroBoolToInt(c: *Context, node: *ast.Node) !*ast.Node { if (!isBoolRes(node)) { if (!nodeIsInfixOp(node.tag)) return node; const group_node = try c.arena.create(ast.Node.GroupedExpression); group_node.* = .{ .lparen = try appendToken(c, .LParen, "("), .expr = node, .rparen = try appendToken(c, .RParen, ")"), }; return &group_node.base; } const builtin_node = try c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = node; builtin_node.rparen_token = try appendToken(c, .RParen, ")"); return &builtin_node.base; } fn macroIntToBool(c: *Context, node: *ast.Node) !*ast.Node { if (isBoolRes(node)) { if (!nodeIsInfixOp(node.tag)) return node; const group_node = try c.arena.create(ast.Node.GroupedExpression); group_node.* = .{ .lparen = try appendToken(c, .LParen, "("), .expr = node, .rparen = try appendToken(c, .RParen, ")"), }; return &group_node.base; } const op_token = try appendToken(c, .BangEqual, "!="); const zero = try transCreateNodeInt(c, 0); const res = try c.arena.create(ast.Node.SimpleInfixOp); res.* = .{ .base = .{ .tag = .BangEqual }, .op_token = op_token, .lhs = node, .rhs = zero, }; const group_node = try c.arena.create(ast.Node.GroupedExpression); group_node.* = .{ .lparen = try appendToken(c, .LParen, "("), .expr = &res.base, .rparen = try appendToken(c, .RParen, ")"), }; return &group_node.base; } fn macroGroup(c: *Context, node: *ast.Node) !*ast.Node { if (!nodeIsInfixOp(node.tag)) return node; const group_node = try c.arena.create(ast.Node.GroupedExpression); group_node.* = .{ .lparen = try appendToken(c, .LParen, "("), .expr = node, .rparen = try appendToken(c, .RParen, ")"), }; return &group_node.base; } fn parseCCondExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { const node = try parseCOrExpr(c, m, scope); if (m.peek().? != .QuestionMark) { return node; } _ = m.next(); // must come immediately after expr _ = try appendToken(c, .RParen, ")"); const if_node = try transCreateNodeIf(c); if_node.condition = node; if_node.body = try parseCOrExpr(c, m, scope); if (m.next().? != .Colon) { try m.fail(c, "unable to translate C expr: expected ':'", .{}); return error.ParseError; } if_node.@"else" = try transCreateNodeElse(c); if_node.@"else".?.body = try parseCCondExpr(c, m, scope); return &if_node.base; } fn parseCOrExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCAndExpr(c, m, scope); while (m.next().? == .PipePipe) { const lhs_node = try macroIntToBool(c, node); const op_token = try appendToken(c, .Keyword_or, "or"); const rhs_node = try parseCAndExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .BoolOr }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroIntToBool(c, rhs_node), }; node = &op_node.base; } m.i -= 1; return node; } fn parseCAndExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCBitOrExpr(c, m, scope); while (m.next().? == .AmpersandAmpersand) { const lhs_node = try macroIntToBool(c, node); const op_token = try appendToken(c, .Keyword_and, "and"); const rhs_node = try parseCBitOrExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .BoolAnd }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroIntToBool(c, rhs_node), }; node = &op_node.base; } m.i -= 1; return node; } fn parseCBitOrExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCBitXorExpr(c, m, scope); while (m.next().? == .Pipe) { const lhs_node = try macroBoolToInt(c, node); const op_token = try appendToken(c, .Pipe, "|"); const rhs_node = try parseCBitXorExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .BitOr }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } m.i -= 1; return node; } fn parseCBitXorExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCBitAndExpr(c, m, scope); while (m.next().? == .Caret) { const lhs_node = try macroBoolToInt(c, node); const op_token = try appendToken(c, .Caret, "^"); const rhs_node = try parseCBitAndExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .BitXor }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } m.i -= 1; return node; } fn parseCBitAndExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCEqExpr(c, m, scope); while (m.next().? == .Ampersand) { const lhs_node = try macroBoolToInt(c, node); const op_token = try appendToken(c, .Ampersand, "&"); const rhs_node = try parseCEqExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = .BitAnd }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } m.i -= 1; return node; } fn parseCEqExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCRelExpr(c, m, scope); while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.peek().?) { .BangEqual => { op_token = try appendToken(c, .BangEqual, "!="); op_id = .BangEqual; }, .EqualEqual => { op_token = try appendToken(c, .EqualEqual, "=="); op_id = .EqualEqual; }, else => return node, } _ = m.next(); const lhs_node = try macroBoolToInt(c, node); const rhs_node = try parseCRelExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = op_id }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } } fn parseCRelExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCShiftExpr(c, m, scope); while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.peek().?) { .AngleBracketRight => { op_token = try appendToken(c, .AngleBracketRight, ">"); op_id = .GreaterThan; }, .AngleBracketRightEqual => { op_token = try appendToken(c, .AngleBracketRightEqual, ">="); op_id = .GreaterOrEqual; }, .AngleBracketLeft => { op_token = try appendToken(c, .AngleBracketLeft, "<"); op_id = .LessThan; }, .AngleBracketLeftEqual => { op_token = try appendToken(c, .AngleBracketLeftEqual, "<="); op_id = .LessOrEqual; }, else => return node, } _ = m.next(); const lhs_node = try macroBoolToInt(c, node); const rhs_node = try parseCShiftExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = op_id }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } } fn parseCShiftExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCAddSubExpr(c, m, scope); while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.peek().?) { .AngleBracketAngleBracketLeft => { op_token = try appendToken(c, .AngleBracketAngleBracketLeft, "<<"); op_id = .BitShiftLeft; }, .AngleBracketAngleBracketRight => { op_token = try appendToken(c, .AngleBracketAngleBracketRight, ">>"); op_id = .BitShiftRight; }, else => return node, } _ = m.next(); const lhs_node = try macroBoolToInt(c, node); const rhs_node = try parseCAddSubExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = op_id }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } } fn parseCAddSubExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCMulExpr(c, m, scope); while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.peek().?) { .Plus => { op_token = try appendToken(c, .Plus, "+"); op_id = .Add; }, .Minus => { op_token = try appendToken(c, .Minus, "-"); op_id = .Sub; }, else => return node, } _ = m.next(); const lhs_node = try macroBoolToInt(c, node); const rhs_node = try parseCMulExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = op_id }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } } fn parseCMulExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCUnaryExpr(c, m, scope); while (true) { var op_token: ast.TokenIndex = undefined; var op_id: ast.Node.Tag = undefined; switch (m.next().?) { .Asterisk => { if (m.peek().? == .RParen) { // type *) // hack to get zig fmt to render a comma in builtin calls _ = try appendToken(c, .Comma, ","); // last token of `node` const prev_id = m.list[m.i - 1].id; if (prev_id == .Keyword_void) { const ptr = try transCreateNodePtrType(c, false, false, .Asterisk); ptr.rhs = node; const optional_node = try transCreateNodeSimplePrefixOp(c, .OptionalType, .QuestionMark, "?"); optional_node.rhs = &ptr.base; return &optional_node.base; } else { const ptr = try transCreateNodePtrType(c, false, false, Token.Id.Identifier); ptr.rhs = node; return &ptr.base; } } else { // expr * expr op_token = try appendToken(c, .Asterisk, "*"); op_id = .BitShiftLeft; } }, .Slash => { op_id = .Div; op_token = try appendToken(c, .Slash, "/"); }, .Percent => { op_id = .Mod; op_token = try appendToken(c, .Percent, "%"); }, else => { m.i -= 1; return node; }, } const lhs_node = try macroBoolToInt(c, node); const rhs_node = try parseCUnaryExpr(c, m, scope); const op_node = try c.arena.create(ast.Node.SimpleInfixOp); op_node.* = .{ .base = .{ .tag = op_id }, .op_token = op_token, .lhs = lhs_node, .rhs = try macroBoolToInt(c, rhs_node), }; node = &op_node.base; } } fn parseCPostfixExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { var node = try parseCPrimaryExpr(c, m, scope); while (true) { switch (m.next().?) { .Period => { if (m.next().? != .Identifier) { try m.fail(c, "unable to translate C expr: expected identifier", .{}); return error.ParseError; } node = try transCreateNodeFieldAccess(c, node, m.slice()); continue; }, .Arrow => { if (m.next().? != .Identifier) { try m.fail(c, "unable to translate C expr: expected identifier", .{}); return error.ParseError; } const deref = try transCreateNodePtrDeref(c, node); node = try transCreateNodeFieldAccess(c, deref, m.slice()); continue; }, .LBracket => { const arr_node = try transCreateNodeArrayAccess(c, node); arr_node.index_expr = try parseCExpr(c, m, scope); arr_node.rtoken = try appendToken(c, .RBracket, "]"); node = &arr_node.base; if (m.next().? != .RBracket) { try m.fail(c, "unable to translate C expr: expected ']'", .{}); return error.ParseError; } continue; }, .LParen => { _ = try appendToken(c, .LParen, "("); var call_params = std.ArrayList(*ast.Node).init(c.gpa); defer call_params.deinit(); while (true) { const arg = try parseCCondExpr(c, m, scope); try call_params.append(arg); switch (m.next().?) { .Comma => _ = try appendToken(c, .Comma, ","), .RParen => break, else => { try m.fail(c, "unable to translate C expr: expected ',' or ')'", .{}); return error.ParseError; }, } } const call_node = try ast.Node.Call.alloc(c.arena, call_params.items.len); call_node.* = .{ .lhs = node, .params_len = call_params.items.len, .async_token = null, .rtoken = try appendToken(c, .RParen, ")"), }; mem.copy(*ast.Node, call_node.params(), call_params.items); node = &call_node.base; continue; }, .LBrace => { // must come immediately after `node` _ = try appendToken(c, .Comma, ","); const dot = try appendToken(c, .Period, "."); _ = try appendToken(c, .LBrace, "{"); var init_vals = std.ArrayList(*ast.Node).init(c.gpa); defer init_vals.deinit(); while (true) { const val = try parseCCondExpr(c, m, scope); try init_vals.append(val); switch (m.next().?) { .Comma => _ = try appendToken(c, .Comma, ","), .RBrace => break, else => { try m.fail(c, "unable to translate C expr: expected ',' or '}}'", .{}); return error.ParseError; }, } } const tuple_node = try ast.Node.StructInitializerDot.alloc(c.arena, init_vals.items.len); tuple_node.* = .{ .dot = dot, .list_len = init_vals.items.len, .rtoken = try appendToken(c, .RBrace, "}"), }; mem.copy(*ast.Node, tuple_node.list(), init_vals.items); //(@import("std").mem.zeroInit(T, .{x})) const import_fn_call = try c.createBuiltinCall("@import", 1); const std_node = try transCreateNodeStringLiteral(c, "\"std\""); import_fn_call.params()[0] = std_node; import_fn_call.rparen_token = try appendToken(c, .RParen, ")"); const inner_field_access = try transCreateNodeFieldAccess(c, &import_fn_call.base, "mem"); const outer_field_access = try transCreateNodeFieldAccess(c, inner_field_access, "zeroInit"); const zero_init_call = try c.createCall(outer_field_access, 2); zero_init_call.params()[0] = node; zero_init_call.params()[1] = &tuple_node.base; zero_init_call.rtoken = try appendToken(c, .RParen, ")"); node = &zero_init_call.base; continue; }, .PlusPlus, .MinusMinus => { try m.fail(c, "TODO postfix inc/dec expr", .{}); return error.ParseError; }, else => { m.i -= 1; return node; }, } } } fn parseCUnaryExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!*ast.Node { switch (m.next().?) { .Bang => { const node = try transCreateNodeSimplePrefixOp(c, .BoolNot, .Bang, "!"); node.rhs = try macroIntToBool(c, try parseCUnaryExpr(c, m, scope)); return &node.base; }, .Minus => { const node = try transCreateNodeSimplePrefixOp(c, .Negation, .Minus, "-"); node.rhs = try macroBoolToInt(c, try parseCUnaryExpr(c, m, scope)); return &node.base; }, .Plus => return try parseCUnaryExpr(c, m, scope), .Tilde => { const node = try transCreateNodeSimplePrefixOp(c, .BitNot, .Tilde, "~"); node.rhs = try macroBoolToInt(c, try parseCUnaryExpr(c, m, scope)); return &node.base; }, .Asterisk => { const node = try macroGroup(c, try parseCUnaryExpr(c, m, scope)); return try transCreateNodePtrDeref(c, node); }, .Ampersand => { const node = try transCreateNodeSimplePrefixOp(c, .AddressOf, .Ampersand, "&"); node.rhs = try macroGroup(c, try parseCUnaryExpr(c, m, scope)); return &node.base; }, .Keyword_sizeof => { const inner = if (m.peek().? == .LParen) blk: { _ = m.next(); // C grammar says this should be 'type-name' but we have to // use parseCMulExpr to correctly handle pointer types. const inner = try parseCMulExpr(c, m, scope); if (m.next().? != .RParen) { try m.fail(c, "unable to translate C expr: expected ')'", .{}); return error.ParseError; } break :blk inner; } else try parseCUnaryExpr(c, m, scope); //(@import("std").meta.sizeof(dest, x)) const import_fn_call = try c.createBuiltinCall("@import", 1); const std_node = try transCreateNodeStringLiteral(c, "\"std\""); import_fn_call.params()[0] = std_node; import_fn_call.rparen_token = try appendToken(c, .RParen, ")"); const inner_field_access = try transCreateNodeFieldAccess(c, &import_fn_call.base, "meta"); const outer_field_access = try transCreateNodeFieldAccess(c, inner_field_access, "sizeof"); const sizeof_call = try c.createCall(outer_field_access, 1); sizeof_call.params()[0] = inner; sizeof_call.rtoken = try appendToken(c, .RParen, ")"); return &sizeof_call.base; }, .Keyword_alignof => { // TODO this won't work if using <stdalign.h>'s // #define alignof _Alignof if (m.next().? != .LParen) { try m.fail(c, "unable to translate C expr: expected '('", .{}); return error.ParseError; } // C grammar says this should be 'type-name' but we have to // use parseCMulExpr to correctly handle pointer types. const inner = try parseCMulExpr(c, m, scope); if (m.next().? != .RParen) { try m.fail(c, "unable to translate C expr: expected ')'", .{}); return error.ParseError; } const builtin_call = try c.createBuiltinCall("@alignOf", 1); builtin_call.params()[0] = inner; builtin_call.rparen_token = try appendToken(c, .RParen, ")"); return &builtin_call.base; }, .PlusPlus, .MinusMinus => { try m.fail(c, "TODO unary inc/dec expr", .{}); return error.ParseError; }, else => { m.i -= 1; return try parseCPostfixExpr(c, m, scope); }, } } fn tokenSlice(c: *Context, token: ast.TokenIndex) []u8 { const tok = c.token_locs.items[token]; const slice = c.source_buffer.items[tok.start..tok.end]; return if (mem.startsWith(u8, slice, "@\"")) slice[2 .. slice.len - 1] else slice; } fn getContainer(c: *Context, node: *ast.Node) ?*ast.Node { switch (node.tag) { .ContainerDecl, .AddressOf, .Await, .BitNot, .BoolNot, .OptionalType, .Negation, .NegationWrap, .Resume, .Try, .ArrayType, .ArrayTypeSentinel, .PtrType, .SliceType, => return node, .Identifier => { const ident = node.castTag(.Identifier).?; if (c.global_scope.sym_table.get(tokenSlice(c, ident.token))) |value| { if (value.cast(ast.Node.VarDecl)) |var_decl| return getContainer(c, var_decl.getInitNode().?); } }, .Period => { const infix = node.castTag(.Period).?; if (getContainerTypeOf(c, infix.lhs)) |ty_node| { if (ty_node.cast(ast.Node.ContainerDecl)) |container| { for (container.fieldsAndDecls()) |field_ref| { const field = field_ref.cast(ast.Node.ContainerField).?; const ident = infix.rhs.castTag(.Identifier).?; if (mem.eql(u8, tokenSlice(c, field.name_token), tokenSlice(c, ident.token))) { return getContainer(c, field.type_expr.?); } } } } }, else => {}, } return null; } fn getContainerTypeOf(c: *Context, ref: *ast.Node) ?*ast.Node { if (ref.castTag(.Identifier)) |ident| { if (c.global_scope.sym_table.get(tokenSlice(c, ident.token))) |value| { if (value.cast(ast.Node.VarDecl)) |var_decl| { if (var_decl.getTypeNode()) |ty| return getContainer(c, ty); } } } else if (ref.castTag(.Period)) |infix| { if (getContainerTypeOf(c, infix.lhs)) |ty_node| { if (ty_node.cast(ast.Node.ContainerDecl)) |container| { for (container.fieldsAndDecls()) |field_ref| { const field = field_ref.cast(ast.Node.ContainerField).?; const ident = infix.rhs.castTag(.Identifier).?; if (mem.eql(u8, tokenSlice(c, field.name_token), tokenSlice(c, ident.token))) { return getContainer(c, field.type_expr.?); } } } else return ty_node; } } return null; } fn getFnProto(c: *Context, ref: *ast.Node) ?*ast.Node.FnProto { const init = if (ref.cast(ast.Node.VarDecl)) |v| v.getInitNode().? else return null; if (getContainerTypeOf(c, init)) |ty_node| { if (ty_node.castTag(.OptionalType)) |prefix| { if (prefix.rhs.cast(ast.Node.FnProto)) |fn_proto| { return fn_proto; } } } return null; } fn addMacros(c: *Context) !void { var it = c.global_scope.macro_table.iterator(); while (it.next()) |kv| { if (getFnProto(c, kv.value)) |proto_node| { // If a macro aliases a global variable which is a function pointer, we conclude that // the macro is intended to represent a function that assumes the function pointer // variable is non-null and calls it. try addTopLevelDecl(c, kv.key, try transCreateNodeMacroFn(c, kv.key, kv.value, proto_node)); } else { try addTopLevelDecl(c, kv.key, kv.value); } } }
src/translate_c.zig
const std = @import("std"); const liu = @import("liu"); const erlang = @import("./erlang.zig"); const ext = erlang.ext; const BBox = erlang.BBox; const Vec2 = liu.Vec2; const KeyCode = liu.gamescreen.KeyCode; pub const camera: *Camera = &camera_; var camera_: Camera = .{}; pub const rows: [3]liu.gamescreen.KeyRow = .{ .{ .leftX = 5, .keys = &[_]KeyCode{ .key_q, .key_w, .key_e, .key_r, .key_t, .key_y, .key_u, .key_i, .key_o, .key_p, }, }, .{ .leftX = 11, .keys = &[_]KeyCode{ .key_a, .key_s, .key_d, .key_f, .key_g, .key_h, .key_j, .key_k, .key_l, .semicolon, }, }, .{ .leftX = 27, .keys = &[_]KeyCode{ .key_z, .key_x, .key_c, .key_v, .key_b, .key_n, .key_m, .comma, .period, .slash, }, }, }; pub fn moveCamera(pos: Vec2) void { camera.pos = pos - Vec2{ camera.width / 2, camera.height / 2 }; } // multiple cameras at once? LOL you can addd a CameraC to ECS registry: // // const CameraC = struct { // world_to_pixel: f32 = 1, // }; // // Unclear how it would interact with setDims, especially if there's multiple // cameras active pub const Camera = struct { pos: Vec2 = Vec2{ 0, 0 }, height: f32 = 30, width: f32 = 10, world_to_pixel: f32 = 1, const Self = @This(); pub fn init() Self { return .{}; } pub fn setDims(self: *Self, pix_width: u32, pix_height: u32) void { self.world_to_pixel = @intToFloat(f32, pix_height) / self.height; self.width = @intToFloat(f32, pix_width) / self.world_to_pixel; } pub fn screenToWorldCoordinates(self: *const Self, pos: Vec2) Vec2 { const pos_translated = pos / @splat(2, self.world_to_pixel); const pos_camera = Vec2{ pos_translated[0], self.height - pos_translated[1] }; return pos_camera + self.pos; } pub fn screenSpaceCoordinates(self: *const Self, pos: Vec2) Vec2 { const pos_camera = pos - self.pos; const pos_canvas = Vec2{ pos_camera[0] * self.world_to_pixel, (self.height - pos_camera[1]) * self.world_to_pixel, }; return pos_canvas; } pub fn getScreenBoundingBox(self: *const Self, bbox: BBox) BBox { const coords = self.screenSpaceCoordinates(bbox.pos); const screen_height = bbox.height * self.world_to_pixel; return BBox{ .pos = Vec2{ coords[0], coords[1] - screen_height }, .width = bbox.width * self.world_to_pixel, .height = screen_height, }; } };
src/routes/erlang/util.zig
const std = @import("std"); const Codegen = @import("../Codegen.zig"); const Tree = @import("../Tree.zig"); const NodeIndex = Tree.NodeIndex; const x86_64 = @import("zig").codegen.x86_64; const Register = x86_64.Register; const RegisterManager = @import("zig").RegisterManager; const Fn = @This(); const Value = union(enum) { symbol: []const u8, immediate: i64, register: Register, none, }; register_manager: RegisterManager(Fn, Register, &x86_64.callee_preserved_regs) = .{}, data: *std.ArrayList(u8), c: *Codegen, pub fn deinit(func: *Fn) void { func.* = undefined; } pub fn genFn(c: *Codegen, decl: NodeIndex, data: *std.ArrayList(u8)) Codegen.Error!void { var func = Fn{ .data = data, .c = c }; defer func.deinit(); // function prologue try func.data.appendSlice(&.{ 0x55, // push rbp 0x48, 0x89, 0xe5, // mov rbp,rsp }); _ = try func.genNode(c.node_data[@enumToInt(decl)].decl.node); // all functions are guaranteed to end in a return statement so no extra work required here } pub fn spillInst(f: *Fn, reg: Register, inst: u32) !void { _ = inst; _ = reg; _ = f; } fn setReg(func: *Fn, val: Value, reg: Register) !void { switch (val) { .none => unreachable, .symbol => |sym| { // lea address with 0 and add relocation const encoder = try x86_64.Encoder.init(func.data, 8); encoder.rex(.{ .w = true }); encoder.opcode_1byte(0x8D); encoder.modRm_RIPDisp32(reg.low_id()); const offset = func.data.items.len; encoder.imm32(0); try func.c.obj.addRelocation(sym, .func, offset, -4); }, .immediate => |x| if (x == 0) { // 32-bit moves zero-extend to 64-bit, so xoring the 32-bit // register is the fastest way to zero a register. // The encoding for `xor r32, r32` is `0x31 /r`. const encoder = try x86_64.Encoder.init(func.data, 3); // If we're accessing e.g. r8d, we need to use a REX prefix before the actual operation. Since // this is a 32-bit operation, the W flag is set to zero. X is also zero, as we're not using a SIB. // Both R and B are set, as we're extending, in effect, the register bits *and* the operand. encoder.rex(.{ .r = reg.isExtended(), .b = reg.isExtended() }); encoder.opcode_1byte(0x31); // Section 3.1.1.1 of the Intel x64 Manual states that "/r indicates that the // ModR/M byte of the instruction contains a register operand and an r/m operand." encoder.modRm_direct(reg.low_id(), reg.low_id()); } else if (x <= std.math.maxInt(i32)) { // Next best case: if we set the lower four bytes, the upper four will be zeroed. // // The encoding for `mov IMM32 -> REG` is (0xB8 + R) IMM. const encoder = try x86_64.Encoder.init(func.data, 6); // Just as with XORing, we need a REX prefix. This time though, we only // need the B bit set, as we're extending the opcode's register field, // and there is no Mod R/M byte. encoder.rex(.{ .b = reg.isExtended() }); encoder.opcode_withReg(0xB8, reg.low_id()); // no ModR/M byte // IMM encoder.imm32(@intCast(i32, x)); } else { // Worst case: we need to load the 64-bit register with the IMM. GNU's assemblers calls // this `movabs`, though this is officially just a different variant of the plain `mov` // instruction. // // This encoding is, in fact, the *same* as the one used for 32-bit loads. The only // difference is that we set REX.W before the instruction, which extends the load to // 64-bit and uses the full bit-width of the register. { const encoder = try x86_64.Encoder.init(func.data, 10); encoder.rex(.{ .w = true, .b = reg.isExtended() }); encoder.opcode_withReg(0xB8, reg.low_id()); encoder.imm64(@bitCast(u64, x)); } }, .register => |src_reg| { // If the registers are the same, nothing to do. if (src_reg.id() == reg.id()) return; // This is a variant of 8B /r. const encoder = try x86_64.Encoder.init(func.data, 3); encoder.rex(.{ .w = true, .r = reg.isExtended(), .b = src_reg.isExtended(), }); encoder.opcode_1byte(0x8B); encoder.modRm_direct(reg.low_id(), src_reg.low_id()); }, } } fn genNode(func: *Fn, node: NodeIndex) Codegen.Error!Value { if (func.c.tree.value_map.get(node)) |some| { if (some.tag == .int) return Value{ .immediate = @bitCast(i64, some.data.int) }; } const data = func.c.node_data[@enumToInt(node)]; switch (func.c.node_tag[@enumToInt(node)]) { .static_assert => return Value{ .none = {} }, .compound_stmt_two => { if (data.bin.lhs != .none) _ = try func.genNode(data.bin.lhs); if (data.bin.rhs != .none) _ = try func.genNode(data.bin.rhs); return Value{ .none = {} }; }, .compound_stmt => { for (func.c.tree.data[data.range.start..data.range.end]) |stmt| { _ = try func.genNode(stmt); } return Value{ .none = {} }; }, .call_expr_one => if (data.bin.rhs != .none) return func.genCall(data.bin.lhs, &.{data.bin.rhs}) else return func.genCall(data.bin.lhs, &.{}), .call_expr => return func.genCall(func.c.tree.data[data.range.start], func.c.tree.data[data.range.start + 1 .. data.range.end]), .function_to_pointer => return func.genNode(data.un), // no-op .array_to_pointer => return func.genNode(data.un), // no-op .decl_ref_expr => { // TODO locals and arguments return Value{ .symbol = func.c.tree.tokSlice(data.decl_ref) }; }, .return_stmt => { const value = try func.genNode(data.un); try func.setReg(value, x86_64.c_abi_int_return_regs[0]); try func.data.appendSlice(&.{ 0x5d, // pop rbp 0xc3, // ret }); return Value{ .none = {} }; }, .implicit_return => { try func.setReg(.{ .immediate = 0 }, x86_64.c_abi_int_return_regs[0]); try func.data.appendSlice(&.{ 0x5d, // pop rbp 0xc3, // ret }); return Value{ .none = {} }; }, .int_literal => return Value{ .immediate = @bitCast(i64, data.int) }, .string_literal_expr => { const str_bytes = func.c.tree.value_map.get(node).?.data.bytes; const section = try func.c.obj.getSection(.strings); const start = section.items.len; try section.appendSlice(str_bytes); const symbol_name = try func.c.obj.declareSymbol(.strings, null, .Internal, .variable, start, str_bytes.len); return Value{ .symbol = symbol_name }; }, else => return func.c.comp.diag.fatalNoSrc("TODO x86_64 genNode {}\n", .{func.c.node_tag[@enumToInt(node)]}), } } fn genCall(func: *Fn, lhs: NodeIndex, args: []const NodeIndex) Codegen.Error!Value { if (args.len > x86_64.c_abi_int_param_regs.len) return func.c.comp.diag.fatalNoSrc("TODO more than args {d}\n", .{x86_64.c_abi_int_param_regs.len}); const func_value = try func.genNode(lhs); for (args) |arg, i| { const value = try func.genNode(arg); try func.setReg(value, x86_64.c_abi_int_param_regs[i]); } switch (func_value) { .none => unreachable, .symbol => |sym| { const encoder = try x86_64.Encoder.init(func.data, 5); encoder.opcode_1byte(0xe8); const offset = func.data.items.len; encoder.imm32(0); try func.c.obj.addRelocation(sym, .func, offset, -4); }, .immediate => return func.c.comp.diag.fatalNoSrc("TODO call immediate\n", .{}), .register => return func.c.comp.diag.fatalNoSrc("TODO call reg\n", .{}), } return Value{ .register = x86_64.c_abi_int_return_regs[0] }; } pub fn genVar(c: *Codegen, decl: NodeIndex) Codegen.Error!void { _ = c; _ = decl; }
src/codegen/x86_64.zig
const Version = @import("builtin").Version; pub const version = Version{ .major = 1, .minor = 5, .patch = 4 }; pub const magic_number: u32 = 0x07230203; pub const Opcode = extern enum(u16) { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpExecutionModeId = 331, OpDecorateId = 332, OpGroupNonUniformElect = 333, OpGroupNonUniformAll = 334, OpGroupNonUniformAny = 335, OpGroupNonUniformAllEqual = 336, OpGroupNonUniformBroadcast = 337, OpGroupNonUniformBroadcastFirst = 338, OpGroupNonUniformBallot = 339, OpGroupNonUniformInverseBallot = 340, OpGroupNonUniformBallotBitExtract = 341, OpGroupNonUniformBallotBitCount = 342, OpGroupNonUniformBallotFindLSB = 343, OpGroupNonUniformBallotFindMSB = 344, OpGroupNonUniformShuffle = 345, OpGroupNonUniformShuffleXor = 346, OpGroupNonUniformShuffleUp = 347, OpGroupNonUniformShuffleDown = 348, OpGroupNonUniformIAdd = 349, OpGroupNonUniformFAdd = 350, OpGroupNonUniformIMul = 351, OpGroupNonUniformFMul = 352, OpGroupNonUniformSMin = 353, OpGroupNonUniformUMin = 354, OpGroupNonUniformFMin = 355, OpGroupNonUniformSMax = 356, OpGroupNonUniformUMax = 357, OpGroupNonUniformFMax = 358, OpGroupNonUniformBitwiseAnd = 359, OpGroupNonUniformBitwiseOr = 360, OpGroupNonUniformBitwiseXor = 361, OpGroupNonUniformLogicalAnd = 362, OpGroupNonUniformLogicalOr = 363, OpGroupNonUniformLogicalXor = 364, OpGroupNonUniformQuadBroadcast = 365, OpGroupNonUniformQuadSwap = 366, OpCopyLogical = 400, OpPtrEqual = 401, OpPtrNotEqual = 402, OpPtrDiff = 403, OpTerminateInvocation = 4416, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpTraceRayKHR = 4445, OpExecuteCallableKHR = 4446, OpConvertUToAccelerationStructureKHR = 4447, OpIgnoreIntersectionKHR = 4448, OpTerminateRayKHR = 4449, OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, OpRayQueryConfirmIntersectionKHR = 4476, OpRayQueryProceedKHR = 4477, OpRayQueryGetIntersectionTypeKHR = 4479, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpReadClockKHR = 5056, OpImageSampleFootprintNV = 5283, OpGroupNonUniformPartitionNV = 5296, OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionNV = 5334, OpReportIntersectionKHR = 5334, OpIgnoreIntersectionNV = 5335, OpTerminateRayNV = 5336, OpTraceNV = 5337, OpTypeAccelerationStructureNV = 5341, OpTypeAccelerationStructureKHR = 5341, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, OpCooperativeMatrixStoreNV = 5360, OpCooperativeMatrixMulAddNV = 5361, OpCooperativeMatrixLengthNV = 5362, OpBeginInvocationInterlockEXT = 5364, OpEndInvocationInterlockEXT = 5365, OpDemoteToHelperInvocationEXT = 5380, OpIsHelperInvocationEXT = 5381, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpSubgroupImageMediaBlockReadINTEL = 5580, OpSubgroupImageMediaBlockWriteINTEL = 5581, OpUCountLeadingZerosINTEL = 5585, OpUCountTrailingZerosINTEL = 5586, OpAbsISubINTEL = 5587, OpAbsUSubINTEL = 5588, OpIAddSatINTEL = 5589, OpUAddSatINTEL = 5590, OpIAverageINTEL = 5591, OpUAverageINTEL = 5592, OpIAverageRoundedINTEL = 5593, OpUAverageRoundedINTEL = 5594, OpISubSatINTEL = 5595, OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, OpAsmTargetINTEL = 5609, OpAsmINTEL = 5610, OpAsmCallINTEL = 5611, OpAtomicFMinEXT = 5614, OpAtomicFMaxEXT = 5615, OpAssumeTrueKHR = 5630, OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, OpMemberDecorateStringGOOGLE = 5633, OpVmeImageINTEL = 5699, OpTypeVmeImageINTEL = 5700, OpTypeAvcImePayloadINTEL = 5701, OpTypeAvcRefPayloadINTEL = 5702, OpTypeAvcSicPayloadINTEL = 5703, OpTypeAvcMcePayloadINTEL = 5704, OpTypeAvcMceResultINTEL = 5705, OpTypeAvcImeResultINTEL = 5706, OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707, OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708, OpTypeAvcImeSingleReferenceStreaminINTEL = 5709, OpTypeAvcImeDualReferenceStreaminINTEL = 5710, OpTypeAvcRefResultINTEL = 5711, OpTypeAvcSicResultINTEL = 5712, OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713, OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714, OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715, OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716, OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717, OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718, OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719, OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720, OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721, OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722, OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723, OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724, OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725, OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726, OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727, OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728, OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729, OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730, OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731, OpSubgroupAvcMceConvertToImePayloadINTEL = 5732, OpSubgroupAvcMceConvertToImeResultINTEL = 5733, OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734, OpSubgroupAvcMceConvertToRefResultINTEL = 5735, OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736, OpSubgroupAvcMceConvertToSicResultINTEL = 5737, OpSubgroupAvcMceGetMotionVectorsINTEL = 5738, OpSubgroupAvcMceGetInterDistortionsINTEL = 5739, OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740, OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741, OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742, OpSubgroupAvcMceGetInterDirectionsINTEL = 5743, OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744, OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745, OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746, OpSubgroupAvcImeInitializeINTEL = 5747, OpSubgroupAvcImeSetSingleReferenceINTEL = 5748, OpSubgroupAvcImeSetDualReferenceINTEL = 5749, OpSubgroupAvcImeRefWindowSizeINTEL = 5750, OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751, OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752, OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753, OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754, OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755, OpSubgroupAvcImeSetWeightedSadINTEL = 5756, OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757, OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758, OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759, OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760, OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761, OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762, OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763, OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764, OpSubgroupAvcImeConvertToMceResultINTEL = 5765, OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766, OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767, OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768, OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771, OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774, OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775, OpSubgroupAvcImeGetBorderReachedINTEL = 5776, OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777, OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778, OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779, OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780, OpSubgroupAvcFmeInitializeINTEL = 5781, OpSubgroupAvcBmeInitializeINTEL = 5782, OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783, OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784, OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785, OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786, OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787, OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788, OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789, OpSubgroupAvcRefConvertToMceResultINTEL = 5790, OpSubgroupAvcSicInitializeINTEL = 5791, OpSubgroupAvcSicConfigureSkcINTEL = 5792, OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793, OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794, OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795, OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796, OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797, OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798, OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799, OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800, OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801, OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802, OpSubgroupAvcSicEvaluateIpeINTEL = 5803, OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804, OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805, OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806, OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807, OpSubgroupAvcSicConvertToMceResultINTEL = 5808, OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809, OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810, OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811, OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812, OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813, OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, OpVariableLengthArrayINTEL = 5818, OpSaveMemoryINTEL = 5819, OpRestoreMemoryINTEL = 5820, OpLoopControlINTEL = 5887, OpPtrCastToCrossWorkgroupINTEL = 5934, OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, OpRayQueryGetRayTMinKHR = 6016, OpRayQueryGetRayFlagsKHR = 6017, OpRayQueryGetIntersectionTKHR = 6018, OpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019, OpRayQueryGetIntersectionInstanceIdKHR = 6020, OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021, OpRayQueryGetIntersectionGeometryIndexKHR = 6022, OpRayQueryGetIntersectionPrimitiveIndexKHR = 6023, OpRayQueryGetIntersectionBarycentricsKHR = 6024, OpRayQueryGetIntersectionFrontFaceKHR = 6025, OpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026, OpRayQueryGetIntersectionObjectRayDirectionKHR = 6027, OpRayQueryGetIntersectionObjectRayOriginKHR = 6028, OpRayQueryGetWorldRayDirectionKHR = 6029, OpRayQueryGetWorldRayOriginKHR = 6030, OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, OpTypeBufferSurfaceINTEL = 6086, OpTypeStructContinuedINTEL = 6090, OpConstantCompositeContinuedINTEL = 6091, OpSpecConstantCompositeContinuedINTEL = 6092, _, }; pub const ImageOperands = packed struct { Bias: bool align(@alignOf(u32)) = false, Lod: bool = false, Grad: bool = false, ConstOffset: bool = false, Offset: bool = false, ConstOffsets: bool = false, Sample: bool = false, MinLod: bool = false, MakeTexelAvailable: bool = false, MakeTexelVisible: bool = false, NonPrivateTexel: bool = false, VolatileTexel: bool = false, SignExtend: bool = false, ZeroExtend: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const FPFastMathMode = packed struct { NotNaN: bool align(@alignOf(u32)) = false, NotInf: bool = false, NSZ: bool = false, AllowRecip: bool = false, Fast: bool = false, _reserved_bit_5: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, AllowContractFastINTEL: bool = false, AllowReassocINTEL: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const SelectionControl = packed struct { Flatten: bool align(@alignOf(u32)) = false, DontFlatten: bool = false, _reserved_bit_2: bool = false, _reserved_bit_3: bool = false, _reserved_bit_4: bool = false, _reserved_bit_5: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const LoopControl = packed struct { Unroll: bool align(@alignOf(u32)) = false, DontUnroll: bool = false, DependencyInfinite: bool = false, DependencyLength: bool = false, MinIterations: bool = false, MaxIterations: bool = false, IterationMultiple: bool = false, PeelCount: bool = false, PartialCount: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, InitiationIntervalINTEL: bool = false, MaxConcurrencyINTEL: bool = false, DependencyArrayINTEL: bool = false, PipelineEnableINTEL: bool = false, LoopCoalesceINTEL: bool = false, MaxInterleavingINTEL: bool = false, SpeculatedIterationsINTEL: bool = false, NoFusionINTEL: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const FunctionControl = packed struct { Inline: bool align(@alignOf(u32)) = false, DontInline: bool = false, Pure: bool = false, Const: bool = false, _reserved_bit_4: bool = false, _reserved_bit_5: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const MemorySemantics = packed struct { _reserved_bit_0: bool align(@alignOf(u32)) = false, Acquire: bool = false, Release: bool = false, AcquireRelease: bool = false, SequentiallyConsistent: bool = false, _reserved_bit_5: bool = false, UniformMemory: bool = false, SubgroupMemory: bool = false, WorkgroupMemory: bool = false, CrossWorkgroupMemory: bool = false, AtomicCounterMemory: bool = false, ImageMemory: bool = false, OutputMemory: bool = false, MakeAvailable: bool = false, MakeVisible: bool = false, Volatile: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const MemoryAccess = packed struct { Volatile: bool align(@alignOf(u32)) = false, Aligned: bool = false, Nontemporal: bool = false, MakePointerAvailable: bool = false, MakePointerVisible: bool = false, NonPrivatePointer: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const KernelProfilingInfo = packed struct { CmdExecTime: bool align(@alignOf(u32)) = false, _reserved_bit_1: bool = false, _reserved_bit_2: bool = false, _reserved_bit_3: bool = false, _reserved_bit_4: bool = false, _reserved_bit_5: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const RayFlags = packed struct { OpaqueKHR: bool align(@alignOf(u32)) = false, NoOpaqueKHR: bool = false, TerminateOnFirstHitKHR: bool = false, SkipClosestHitShaderKHR: bool = false, CullBackFacingTrianglesKHR: bool = false, CullFrontFacingTrianglesKHR: bool = false, CullOpaqueKHR: bool = false, CullNoOpaqueKHR: bool = false, SkipTrianglesKHR: bool = false, SkipAABBsKHR: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const FragmentShadingRate = packed struct { Vertical2Pixels: bool align(@alignOf(u32)) = false, Vertical4Pixels: bool = false, Horizontal2Pixels: bool = false, Horizontal4Pixels: bool = false, _reserved_bit_4: bool = false, _reserved_bit_5: bool = false, _reserved_bit_6: bool = false, _reserved_bit_7: bool = false, _reserved_bit_8: bool = false, _reserved_bit_9: bool = false, _reserved_bit_10: bool = false, _reserved_bit_11: bool = false, _reserved_bit_12: bool = false, _reserved_bit_13: bool = false, _reserved_bit_14: bool = false, _reserved_bit_15: bool = false, _reserved_bit_16: bool = false, _reserved_bit_17: bool = false, _reserved_bit_18: bool = false, _reserved_bit_19: bool = false, _reserved_bit_20: bool = false, _reserved_bit_21: bool = false, _reserved_bit_22: bool = false, _reserved_bit_23: bool = false, _reserved_bit_24: bool = false, _reserved_bit_25: bool = false, _reserved_bit_26: bool = false, _reserved_bit_27: bool = false, _reserved_bit_28: bool = false, _reserved_bit_29: bool = false, _reserved_bit_30: bool = false, _reserved_bit_31: bool = false, }; pub const SourceLanguage = extern enum(u32) { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, _, }; pub const ExecutionModel = extern enum(u32) { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, TaskNV = 5267, MeshNV = 5268, RayGenerationNV = 5313, RayGenerationKHR = 5313, IntersectionNV = 5314, IntersectionKHR = 5314, AnyHitNV = 5315, AnyHitKHR = 5315, ClosestHitNV = 5316, ClosestHitKHR = 5316, MissNV = 5317, MissKHR = 5317, CallableNV = 5318, CallableKHR = 5318, _, }; pub const AddressingModel = extern enum(u32) { Logical = 0, Physical32 = 1, Physical64 = 2, PhysicalStorageBuffer64 = 5348, PhysicalStorageBuffer64EXT = 5348, _, }; pub const MemoryModel = extern enum(u32) { Simple = 0, GLSL450 = 1, OpenCL = 2, Vulkan = 3, VulkanKHR = 3, _, }; pub const ExecutionMode = extern enum(u32) { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, SignedZeroInfNanPreserve = 4461, RoundingModeRTE = 4462, RoundingModeRTZ = 4463, StencilRefReplacingEXT = 5027, OutputLinesNV = 5269, OutputPrimitivesNV = 5270, DerivativeGroupQuadsNV = 5289, DerivativeGroupLinearNV = 5290, OutputTrianglesNV = 5298, PixelInterlockOrderedEXT = 5366, PixelInterlockUnorderedEXT = 5367, SampleInterlockOrderedEXT = 5368, SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, SharedLocalMemorySizeINTEL = 5618, RoundingModeRTPINTEL = 5620, RoundingModeRTNINTEL = 5621, FloatingPointModeALTINTEL = 5622, FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, SchedulerTargetFmaxMhzINTEL = 5903, _, }; pub const StorageClass = extern enum(u32) { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, CallableDataNV = 5328, CallableDataKHR = 5328, IncomingCallableDataNV = 5329, IncomingCallableDataKHR = 5329, RayPayloadNV = 5338, RayPayloadKHR = 5338, HitAttributeNV = 5339, HitAttributeKHR = 5339, IncomingRayPayloadNV = 5342, IncomingRayPayloadKHR = 5342, ShaderRecordBufferNV = 5343, ShaderRecordBufferKHR = 5343, PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, CodeSectionINTEL = 5605, DeviceOnlyINTEL = 5936, HostOnlyINTEL = 5937, _, }; pub const Dim = extern enum(u32) { @"1D" = 0, @"2D" = 1, @"3D" = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, _, }; pub const SamplerAddressingMode = extern enum(u32) { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, _, }; pub const SamplerFilterMode = extern enum(u32) { Nearest = 0, Linear = 1, _, }; pub const ImageFormat = extern enum(u32) { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, R64ui = 40, R64i = 41, _, }; pub const ImageChannelOrder = extern enum(u32) { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, _, }; pub const ImageChannelDataType = extern enum(u32) { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, _, }; pub const FPRoundingMode = extern enum(u32) { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, _, }; pub const FPDenormMode = extern enum(u32) { Preserve = 0, FlushToZero = 1, _, }; pub const FPOperationMode = extern enum(u32) { IEEE = 0, ALT = 1, _, }; pub const LinkageType = extern enum(u32) { Export = 0, Import = 1, LinkOnceODR = 2, _, }; pub const AccessQualifier = extern enum(u32) { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, _, }; pub const FunctionParameterAttribute = extern enum(u32) { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, _, }; pub const Decoration = extern enum(u32) { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, UniformId = 27, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, AlignmentId = 46, MaxByteOffsetId = 47, NoSignedWrap = 4469, NoUnsignedWrap = 4470, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, PerPrimitiveNV = 5271, PerViewNV = 5272, PerTaskNV = 5273, PerVertexNV = 5285, NonUniform = 5300, NonUniformEXT = 5300, RestrictPointer = 5355, RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, ClobberINTEL = 5607, SideEffectsINTEL = 5608, VectorComputeVariableINTEL = 5624, FuncParamIOKindINTEL = 5625, VectorComputeFunctionINTEL = 5626, StackCallINTEL = 5627, GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, UserSemantic = 5635, HlslSemanticGOOGLE = 5635, UserTypeGOOGLE = 5636, FunctionRoundingModeINTEL = 5822, FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, BankwidthINTEL = 5828, MaxPrivateCopiesINTEL = 5829, SinglepumpINTEL = 5830, DoublepumpINTEL = 5831, MaxReplicatesINTEL = 5832, SimpleDualPortINTEL = 5833, MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, BurstCoalesceINTEL = 5899, CacheSizeINTEL = 5900, DontStaticallyCoalesceINTEL = 5901, PrefetchINTEL = 5902, StallEnableINTEL = 5905, FuseLoopsInFunctionINTEL = 5907, BufferLocationINTEL = 5921, IOPipeStorageINTEL = 5944, FunctionFloatingPointModeINTEL = 6080, SingleElementVectorINTEL = 6085, VectorComputeCallableFunctionINTEL = 6087, _, }; pub const BuiltIn = extern enum(u32) { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMask = 4416, SubgroupEqMaskKHR = 4416, SubgroupGeMask = 4417, SubgroupGeMaskKHR = 4417, SubgroupGtMask = 4418, SubgroupGtMaskKHR = 4418, SubgroupLeMask = 4419, SubgroupLeMaskKHR = 4419, SubgroupLtMask = 4420, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, PrimitiveShadingRateKHR = 4432, DeviceIndex = 4438, ViewIndex = 4440, ShadingRateKHR = 4444, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, FullyCoveredEXT = 5264, TaskCountNV = 5274, PrimitiveCountNV = 5275, PrimitiveIndicesNV = 5276, ClipDistancePerViewNV = 5277, CullDistancePerViewNV = 5278, LayerPerViewNV = 5279, MeshViewCountNV = 5280, MeshViewIndicesNV = 5281, BaryCoordNV = 5286, BaryCoordNoPerspNV = 5287, FragSizeEXT = 5292, FragmentSizeNV = 5292, FragInvocationCountEXT = 5293, InvocationsPerPixelNV = 5293, LaunchIdNV = 5319, LaunchIdKHR = 5319, LaunchSizeNV = 5320, LaunchSizeKHR = 5320, WorldRayOriginNV = 5321, WorldRayOriginKHR = 5321, WorldRayDirectionNV = 5322, WorldRayDirectionKHR = 5322, ObjectRayOriginNV = 5323, ObjectRayOriginKHR = 5323, ObjectRayDirectionNV = 5324, ObjectRayDirectionKHR = 5324, RayTminNV = 5325, RayTminKHR = 5325, RayTmaxNV = 5326, RayTmaxKHR = 5326, InstanceCustomIndexNV = 5327, InstanceCustomIndexKHR = 5327, ObjectToWorldNV = 5330, ObjectToWorldKHR = 5330, WorldToObjectNV = 5331, WorldToObjectKHR = 5331, HitTNV = 5332, HitKindNV = 5333, HitKindKHR = 5333, IncomingRayFlagsNV = 5351, IncomingRayFlagsKHR = 5351, RayGeometryIndexKHR = 5352, WarpsPerSMNV = 5374, SMCountNV = 5375, WarpIDNV = 5376, SMIDNV = 5377, _, }; pub const Scope = extern enum(u32) { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, QueueFamily = 5, QueueFamilyKHR = 5, ShaderCallKHR = 6, _, }; pub const GroupOperation = extern enum(u32) { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, ClusteredReduce = 3, PartitionedReduceNV = 6, PartitionedInclusiveScanNV = 7, PartitionedExclusiveScanNV = 8, _, }; pub const KernelEnqueueFlags = extern enum(u32) { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, _, }; pub const Capability = extern enum(u32) { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, GroupNonUniform = 61, GroupNonUniformVote = 62, GroupNonUniformArithmetic = 63, GroupNonUniformBallot = 64, GroupNonUniformShuffle = 65, GroupNonUniformShuffleRelative = 66, GroupNonUniformClustered = 67, GroupNonUniformQuad = 68, ShaderLayer = 69, ShaderViewportIndex = 70, FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, WorkgroupMemoryExplicitLayoutKHR = 4428, WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, UniformAndStorageBuffer16BitAccess = 4434, StorageUniform16 = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, StorageBuffer8BitAccess = 4448, UniformAndStorageBuffer8BitAccess = 4449, StoragePushConstant8 = 4450, DenormPreserve = 4464, DenormFlushToZero = 4465, SignedZeroInfNanPreserve = 4466, RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, RayQueryKHR = 4472, RayTraversalPrimitiveCullingKHR = 4478, RayTracingKHR = 4479, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, Int64ImageEXT = 5016, ShaderClockKHR = 5055, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, FragmentFullyCoveredEXT = 5265, MeshShadingNV = 5266, ImageFootprintNV = 5282, FragmentBarycentricNV = 5284, ComputeDerivativeGroupQuadsNV = 5288, FragmentDensityEXT = 5291, ShadingRateNV = 5291, GroupNonUniformPartitionedNV = 5297, ShaderNonUniform = 5301, ShaderNonUniformEXT = 5301, RuntimeDescriptorArray = 5302, RuntimeDescriptorArrayEXT = 5302, InputAttachmentArrayDynamicIndexing = 5303, InputAttachmentArrayDynamicIndexingEXT = 5303, UniformTexelBufferArrayDynamicIndexing = 5304, UniformTexelBufferArrayDynamicIndexingEXT = 5304, StorageTexelBufferArrayDynamicIndexing = 5305, StorageTexelBufferArrayDynamicIndexingEXT = 5305, UniformBufferArrayNonUniformIndexing = 5306, UniformBufferArrayNonUniformIndexingEXT = 5306, SampledImageArrayNonUniformIndexing = 5307, SampledImageArrayNonUniformIndexingEXT = 5307, StorageBufferArrayNonUniformIndexing = 5308, StorageBufferArrayNonUniformIndexingEXT = 5308, StorageImageArrayNonUniformIndexing = 5309, StorageImageArrayNonUniformIndexingEXT = 5309, InputAttachmentArrayNonUniformIndexing = 5310, InputAttachmentArrayNonUniformIndexingEXT = 5310, UniformTexelBufferArrayNonUniformIndexing = 5311, UniformTexelBufferArrayNonUniformIndexingEXT = 5311, StorageTexelBufferArrayNonUniformIndexing = 5312, StorageTexelBufferArrayNonUniformIndexingEXT = 5312, RayTracingNV = 5340, VulkanMemoryModel = 5345, VulkanMemoryModelKHR = 5345, VulkanMemoryModelDeviceScope = 5346, VulkanMemoryModelDeviceScopeKHR = 5346, PhysicalStorageBufferAddresses = 5347, PhysicalStorageBufferAddressesEXT = 5347, ComputeDerivativeGroupLinearNV = 5350, RayTracingProvisionalKHR = 5353, CooperativeMatrixNV = 5357, FragmentShaderSampleInterlockEXT = 5363, FragmentShaderShadingRateInterlockEXT = 5372, ShaderSMBuiltinsNV = 5373, FragmentShaderPixelInterlockEXT = 5378, DemoteToHelperInvocationEXT = 5379, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, RoundToInfinityINTEL = 5582, FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, AsmINTEL = 5606, AtomicFloat32MinMaxEXT = 5612, AtomicFloat64MinMaxEXT = 5613, AtomicFloat16MinMaxEXT = 5616, VectorComputeINTEL = 5617, VectorAnyINTEL = 5619, ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, VariableLengthArrayINTEL = 5817, FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, FPFastMathModeINTEL = 5837, ArbitraryPrecisionIntegersINTEL = 5844, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, FPGAMemoryAccessesINTEL = 5898, FPGAClusterAttributesINTEL = 5904, LoopFuseINTEL = 5906, FPGABufferLocationINTEL = 5920, USMStorageClassesINTEL = 5935, IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, LongConstantCompositeINTEL = 6089, _, }; pub const RayQueryIntersection = extern enum(u32) { RayQueryCandidateIntersectionKHR = 0, RayQueryCommittedIntersectionKHR = 1, _, }; pub const RayQueryCommittedIntersectionType = extern enum(u32) { RayQueryCommittedIntersectionNoneKHR = 0, RayQueryCommittedIntersectionTriangleKHR = 1, RayQueryCommittedIntersectionGeneratedKHR = 2, _, }; pub const RayQueryCandidateIntersectionType = extern enum(u32) { RayQueryCandidateIntersectionTriangleKHR = 0, RayQueryCandidateIntersectionAABBKHR = 1, _, };
src/codegen/spirv/spec.zig
const mecha = @import("../mecha.zig"); const std = @import("std"); const math = std.math; const mem = std.mem; const testing = std.testing; const unicode = std.unicode; /// Constructs a parser that parses a single utf8 codepoint based on /// a `predicate`. If the `predicate` returns true, the parser will /// return the codepoint parsed and the rest of the string. Otherwise /// the parser will fail. pub fn wrap(comptime predicate: fn (u21) bool) mecha.Parser(u21) { const Res = mecha.Result(u21); return struct { fn func(_: *mem.Allocator, str: []const u8) mecha.Error!Res { if (str.len == 0) return error.ParserFailed; const cp_len = unicode.utf8ByteSequenceLength(str[0]) catch return error.ParserFailed; if (cp_len > str.len) return error.ParserFailed; const cp = unicode.utf8Decode(str[0..cp_len]) catch return error.ParserFailed; if (!predicate(cp)) return error.ParserFailed; return Res{ .value = cp, .rest = str[cp_len..] }; } }.func; } /// Constructs a parser that only succeeds if the string starts with `c`. pub fn char(comptime c: u21) mecha.Parser(void) { comptime { var array: [4]u8 = undefined; const len = unicode.utf8Encode(c, array[0..]) catch unreachable; return mecha.string(array[0..len]); } } test "char" { const allocator = testing.failing_allocator; mecha.expectResult(void, .{ .value = {}, .rest = "" }, char('a')(allocator, "a")); mecha.expectResult(void, .{ .value = {}, .rest = "a" }, char('a')(allocator, "aa")); mecha.expectResult(void, error.ParserFailed, char('a')(allocator, "ba")); mecha.expectResult(void, error.ParserFailed, char('a')(allocator, "")); mecha.expectResult(void, .{ .value = {}, .rest = "ā" }, char(0x100)(allocator, "Āā")); mecha.expectResult(void, error.ParserFailed, char(0x100)(allocator, "")); mecha.expectResult(void, error.ParserFailed, char(0x100)(allocator, "\xc0")); } /// Constructs a parser that only succeeds if the string starts with /// a codepoint that is in between `start` and `end` inclusively. /// The parser's result will be the codepoint parsed. pub fn range(comptime start: u21, comptime end: u21) mecha.Parser(u21) { return wrap(struct { fn pred(cp: u21) bool { return switch (cp) { start...end => true, else => false, }; } }.pred); } test "range" { const allocator = testing.failing_allocator; mecha.expectResult(u21, .{ .value = 'a', .rest = "" }, range('a', 'z')(allocator, "a")); mecha.expectResult(u21, .{ .value = 'c', .rest = "" }, range('a', 'z')(allocator, "c")); mecha.expectResult(u21, .{ .value = 'z', .rest = "" }, range('a', 'z')(allocator, "z")); mecha.expectResult(u21, .{ .value = 'a', .rest = "a" }, range('a', 'z')(allocator, "aa")); mecha.expectResult(u21, .{ .value = 'c', .rest = "a" }, range('a', 'z')(allocator, "ca")); mecha.expectResult(u21, .{ .value = 'z', .rest = "a" }, range('a', 'z')(allocator, "za")); mecha.expectResult(u21, error.ParserFailed, range('a', 'z')(allocator, "1")); mecha.expectResult(u21, error.ParserFailed, range('a', 'z')(allocator, "")); mecha.expectResult(u21, .{ .value = 0x100, .rest = "ā" }, range(0x100, 0x100)(allocator, "Āā")); mecha.expectResult(u21, error.ParserFailed, range(0x100, 0x100)(allocator, "aa")); mecha.expectResult(u21, error.ParserFailed, range(0x100, 0x100)(allocator, "\xc0")); } /// Creates a parser that succeeds and parses one utf8 codepoint if /// `parser` fails to parse the input string. pub fn not(comptime parser: anytype) mecha.Parser(u21) { const Res = mecha.Result(u21); return struct { fn res(allocator: *mem.Allocator, str: []const u8) mecha.Error!Res { if (str.len == 0) return error.ParserFailed; if (parser(allocator, str)) |_| { return error.ParserFailed; } else |e| switch (e) { error.ParserFailed => {}, else => return e, } const cp_len = unicode.utf8ByteSequenceLength(str[0]) catch return error.ParserFailed; if (cp_len > str.len) return error.ParserFailed; const cp = unicode.utf8Decode(str[0..cp_len]) catch return error.ParserFailed; return Res{ .value = cp, .rest = str[cp_len..] }; } }.res; } test "not" { const allocator = testing.failing_allocator; const p = not(comptime range('a', 'z')); var i: u16 = 0; while (i <= math.maxInt(u7)) : (i += 1) { const c = @intCast(u8, i); switch (c) { 'a'...'z' => mecha.expectResult(u21, error.ParserFailed, p(allocator, &[_]u8{c})), else => mecha.expectResult(u21, .{ .value = c, .rest = "" }, p(allocator, &[_]u8{c})), } } }
src/utf8.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const maxInt = std.math.maxInt; const iovec = std.os.iovec; const iovec_const = std.os.iovec_const; const timezone = std.c.timezone; const rusage = std.c.rusage; extern "c" fn __errno() *c_int; pub const _errno = __errno; pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*c_void) callconv(.C) c_int; pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int; pub extern "c" fn _lwp_self() lwpid_t; pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int; pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void; pub extern "c" fn __fstat50(fd: fd_t, buf: *Stat) c_int; pub const fstat = __fstat50; pub extern "c" fn __stat50(path: [*:0]const u8, buf: *Stat) c_int; pub const stat = __stat50; pub extern "c" fn __clock_gettime50(clk_id: c_int, tp: *timespec) c_int; pub const clock_gettime = __clock_gettime50; pub extern "c" fn __clock_getres50(clk_id: c_int, tp: *timespec) c_int; pub const clock_getres = __clock_getres50; pub extern "c" fn __getdents30(fd: c_int, buf_ptr: [*]u8, nbytes: usize) c_int; pub const getdents = __getdents30; pub extern "c" fn __sigaltstack14(ss: ?*stack_t, old_ss: ?*stack_t) c_int; pub const sigaltstack = __sigaltstack14; pub extern "c" fn __nanosleep50(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub const nanosleep = __nanosleep50; pub extern "c" fn __sigaction14(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int; pub const sigaction = __sigaction14; pub extern "c" fn __sigprocmask14(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; pub const sigprocmask = __sigaction14; pub extern "c" fn __socket30(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; pub const socket = __socket30; pub extern "c" fn __gettimeofday50(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; pub const gettimeofday = __gettimeofday50; pub extern "c" fn __getrusage50(who: c_int, usage: *rusage) c_int; pub const getrusage = __getrusage50; pub extern "c" fn __libc_thr_yield() c_int; pub const sched_yield = __libc_thr_yield; pub extern "c" fn posix_memalign(memptr: *?*c_void, alignment: usize, size: usize) c_int; pub const pthread_mutex_t = extern struct { magic: u32 = 0x33330003, errorcheck: padded_pthread_spin_t = 0, ceiling: padded_pthread_spin_t = 0, owner: usize = 0, waiters: ?*u8 = null, recursed: u32 = 0, spare2: ?*c_void = null, }; pub const pthread_cond_t = extern struct { magic: u32 = 0x55550005, lock: pthread_spin_t = 0, waiters_first: ?*u8 = null, waiters_last: ?*u8 = null, mutex: ?*pthread_mutex_t = null, private: ?*c_void = null, }; pub const pthread_rwlock_t = extern struct { magic: c_uint = 0x99990009, interlock: switch (builtin.cpu.arch) { .aarch64, .sparc, .x86_64, .i386 => u8, .arm, .powerpc => c_int, else => unreachable, } = 0, rblocked_first: ?*u8 = null, rblocked_last: ?*u8 = null, wblocked_first: ?*u8 = null, wblocked_last: ?*u8 = null, nreaders: c_uint = 0, owner: std.c.pthread_t = null, private: ?*c_void = null, }; const pthread_spin_t = switch (builtin.cpu.arch) { .aarch64, .aarch64_be, .aarch64_32 => u8, .mips, .mipsel, .mips64, .mips64el => u32, .powerpc, .powerpc64, .powerpc64le => i32, .i386, .x86_64 => u8, .arm, .armeb, .thumb, .thumbeb => i32, .sparc, .sparcel, .sparcv9 => u8, .riscv32, .riscv64 => u32, else => @compileError("undefined pthread_spin_t for this arch"), }; const padded_pthread_spin_t = switch (builtin.cpu.arch) { .i386, .x86_64 => u32, .sparc, .sparcel, .sparcv9 => u32, else => pthread_spin_t, }; pub const pthread_attr_t = extern struct { pta_magic: u32, pta_flags: i32, pta_private: ?*c_void, }; pub const sem_t = ?*opaque {}; pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*c_void) E; pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E; pub const blkcnt_t = i64; pub const blksize_t = i32; pub const clock_t = u32; pub const dev_t = u64; pub const fd_t = i32; pub const gid_t = u32; pub const ino_t = u64; pub const mode_t = u32; pub const nlink_t = u32; pub const off_t = i64; pub const pid_t = i32; pub const socklen_t = u32; pub const time_t = i64; pub const uid_t = u32; pub const lwpid_t = i32; pub const suseconds_t = c_int; /// Renamed from `kevent` to `Kevent` to avoid conflict with function name. pub const Kevent = extern struct { ident: usize, filter: i32, flags: u32, fflags: u32, data: i64, udata: usize, }; pub const RTLD = struct { pub const LAZY = 1; pub const NOW = 2; pub const GLOBAL = 0x100; pub const LOCAL = 0x200; pub const NODELETE = 0x01000; pub const NOLOAD = 0x02000; pub const NEXT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -1))); pub const DEFAULT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -2))); pub const SELF = @intToPtr(*c_void, @bitCast(usize, @as(isize, -3))); }; pub const dl_phdr_info = extern struct { dlpi_addr: usize, dlpi_name: ?[*:0]const u8, dlpi_phdr: [*]std.elf.Phdr, dlpi_phnum: u16, }; pub const Flock = extern struct { l_start: off_t, l_len: off_t, l_pid: pid_t, l_type: i16, l_whence: i16, }; pub const addrinfo = extern struct { flags: i32, family: i32, socktype: i32, protocol: i32, addrlen: socklen_t, canonname: ?[*:0]u8, addr: ?*sockaddr, next: ?*addrinfo, }; pub const EAI = enum(c_int) { /// address family for hostname not supported ADDRFAMILY = 1, /// name could not be resolved at this time AGAIN = 2, /// flags parameter had an invalid value BADFLAGS = 3, /// non-recoverable failure in name resolution FAIL = 4, /// address family not recognized FAMILY = 5, /// memory allocation failure MEMORY = 6, /// no address associated with hostname NODATA = 7, /// name does not resolve NONAME = 8, /// service not recognized for socket type SERVICE = 9, /// intended socket type was not recognized SOCKTYPE = 10, /// system error returned in errno SYSTEM = 11, /// invalid value for hints BADHINTS = 12, /// resolved protocol is unknown PROTOCOL = 13, /// argument buffer overflow OVERFLOW = 14, _, }; pub const EAI_MAX = 15; pub const msghdr = extern struct { /// optional address msg_name: ?*sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]iovec, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*c_void, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; pub const msghdr_const = extern struct { /// optional address msg_name: ?*const sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]iovec_const, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*c_void, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; /// The stat structure used by libc. pub const Stat = extern struct { dev: dev_t, mode: mode_t, ino: ino_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, atim: timespec, mtim: timespec, ctim: timespec, birthtim: timespec, size: off_t, blocks: blkcnt_t, blksize: blksize_t, flags: u32, gen: u32, __spare: [2]u32, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const timespec = extern struct { tv_sec: i64, tv_nsec: isize, }; pub const timeval = extern struct { /// seconds tv_sec: time_t, /// microseconds tv_usec: suseconds_t, }; pub const MAXNAMLEN = 511; pub const dirent = extern struct { d_fileno: ino_t, d_reclen: u16, d_namlen: u16, d_type: u8, d_name: [MAXNAMLEN:0]u8, pub fn reclen(self: dirent) u16 { return self.d_reclen; } }; pub const SOCK = struct { pub const STREAM = 1; pub const DGRAM = 2; pub const RAW = 3; pub const RDM = 4; pub const SEQPACKET = 5; pub const CONN_DGRAM = 6; pub const DCCP = CONN_DGRAM; pub const CLOEXEC = 0x10000000; pub const NONBLOCK = 0x20000000; pub const NOSIGPIPE = 0x40000000; pub const FLAGS_MASK = 0xf0000000; }; pub const SO = struct { pub const DEBUG = 0x0001; pub const ACCEPTCONN = 0x0002; pub const REUSEADDR = 0x0004; pub const KEEPALIVE = 0x0008; pub const DONTROUTE = 0x0010; pub const BROADCAST = 0x0020; pub const USELOOPBACK = 0x0040; pub const LINGER = 0x0080; pub const OOBINLINE = 0x0100; pub const REUSEPORT = 0x0200; pub const NOSIGPIPE = 0x0800; pub const ACCEPTFILTER = 0x1000; pub const TIMESTAMP = 0x2000; pub const RERROR = 0x4000; pub const SNDBUF = 0x1001; pub const RCVBUF = 0x1002; pub const SNDLOWAT = 0x1003; pub const RCVLOWAT = 0x1004; pub const ERROR = 0x1007; pub const TYPE = 0x1008; pub const OVERFLOWED = 0x1009; pub const NOHEADER = 0x100a; pub const SNDTIMEO = 0x100b; pub const RCVTIMEO = 0x100c; }; pub const SOL = struct { pub const SOCKET = 0xffff; }; pub const PF = struct { pub const UNSPEC = AF.UNSPEC; pub const LOCAL = AF.LOCAL; pub const UNIX = PF.LOCAL; pub const INET = AF.INET; pub const IMPLINK = AF.IMPLINK; pub const PUP = AF.PUP; pub const CHAOS = AF.CHAOS; pub const NS = AF.NS; pub const ISO = AF.ISO; pub const OSI = AF.ISO; pub const ECMA = AF.ECMA; pub const DATAKIT = AF.DATAKIT; pub const CCITT = AF.CCITT; pub const SNA = AF.SNA; pub const DECnet = AF.DECnet; pub const DLI = AF.DLI; pub const LAT = AF.LAT; pub const HYLINK = AF.HYLINK; pub const APPLETALK = AF.APPLETALK; pub const OROUTE = AF.OROUTE; pub const LINK = AF.LINK; pub const COIP = AF.COIP; pub const CNT = AF.CNT; pub const INET6 = AF.INET6; pub const IPX = AF.IPX; pub const ISDN = AF.ISDN; pub const E164 = AF.E164; pub const NATM = AF.NATM; pub const ARP = AF.ARP; pub const BLUETOOTH = AF.BLUETOOTH; pub const MPLS = AF.MPLS; pub const ROUTE = AF.ROUTE; pub const CAN = AF.CAN; pub const ETHER = AF.ETHER; pub const MAX = AF.MAX; }; pub const AF = struct { pub const UNSPEC = 0; pub const LOCAL = 1; pub const UNIX = LOCAL; pub const INET = 2; pub const IMPLINK = 3; pub const PUP = 4; pub const CHAOS = 5; pub const NS = 6; pub const ISO = 7; pub const OSI = ISO; pub const ECMA = 8; pub const DATAKIT = 9; pub const CCITT = 10; pub const SNA = 11; pub const DECnet = 12; pub const DLI = 13; pub const LAT = 14; pub const HYLINK = 15; pub const APPLETALK = 16; pub const OROUTE = 17; pub const LINK = 18; pub const COIP = 20; pub const CNT = 21; pub const IPX = 23; pub const INET6 = 24; pub const ISDN = 26; pub const E164 = ISDN; pub const NATM = 27; pub const ARP = 28; pub const BLUETOOTH = 31; pub const IEEE80211 = 32; pub const MPLS = 33; pub const ROUTE = 34; pub const CAN = 35; pub const ETHER = 36; pub const MAX = 37; }; pub const in_port_t = u16; pub const sa_family_t = u8; pub const sockaddr = extern struct { /// total length len: u8, /// address family family: sa_family_t, /// actually longer; address value data: [14]u8, pub const storage = std.x.os.Socket.Address.Native.Storage; pub const in = extern struct { len: u8 = @sizeOf(in), family: sa_family_t = AF.INET, port: in_port_t, addr: u32, zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }, }; pub const in6 = extern struct { len: u8 = @sizeOf(in6), family: sa_family_t = AF.INET6, port: in_port_t, flowinfo: u32, addr: [16]u8, scope_id: u32, }; /// Definitions for UNIX IPC domain. pub const un = extern struct { /// total sockaddr length len: u8 = @sizeOf(un), family: sa_family_t = AF.LOCAL, /// path name path: [104]u8, }; }; pub const AI = struct { /// get address to use bind() pub const PASSIVE = 0x00000001; /// fill ai_canonname pub const CANONNAME = 0x00000002; /// prevent host name resolution pub const NUMERICHOST = 0x00000004; /// prevent service name resolution pub const NUMERICSERV = 0x00000008; /// only if any address is assigned pub const ADDRCONFIG = 0x00000400; }; pub const CTL = struct { pub const KERN = 1; pub const DEBUG = 5; }; pub const KERN = struct { pub const PROC_ARGS = 48; // struct: process argv/env pub const PROC_PATHNAME = 5; // path to executable pub const IOV_MAX = 38; }; pub const PATH_MAX = 1024; pub const IOV_MAX = KERN.IOV_MAX; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const PROT = struct { pub const NONE = 0; pub const READ = 1; pub const WRITE = 2; pub const EXEC = 4; }; pub const CLOCK = struct { pub const REALTIME = 0; pub const VIRTUAL = 1; pub const PROF = 2; pub const MONOTONIC = 3; pub const THREAD_CPUTIME_ID = 0x20000000; pub const PROCESS_CPUTIME_ID = 0x40000000; }; pub const MAP = struct { pub const FAILED = @intToPtr(*c_void, maxInt(usize)); pub const SHARED = 0x0001; pub const PRIVATE = 0x0002; pub const REMAPDUP = 0x0004; pub const FIXED = 0x0010; pub const RENAME = 0x0020; pub const NORESERVE = 0x0040; pub const INHERIT = 0x0080; pub const HASSEMAPHORE = 0x0200; pub const TRYFIXED = 0x0400; pub const WIRED = 0x0800; pub const FILE = 0x0000; pub const NOSYNC = 0x0800; pub const ANON = 0x1000; pub const ANONYMOUS = ANON; pub const STACK = 0x2000; }; pub const W = struct { pub const NOHANG = 0x00000001; pub const UNTRACED = 0x00000002; pub const STOPPED = UNTRACED; pub const CONTINUED = 0x00000010; pub const NOWAIT = 0x00010000; pub const EXITED = 0x00000020; pub const TRAPPED = 0x00000040; pub fn EXITSTATUS(s: u32) u8 { return @intCast(u8, (s >> 8) & 0xff); } pub fn TERMSIG(s: u32) u32 { return s & 0x7f; } pub fn STOPSIG(s: u32) u32 { return EXITSTATUS(s); } pub fn IFEXITED(s: u32) bool { return TERMSIG(s) == 0; } pub fn IFCONTINUED(s: u32) bool { return ((s & 0x7f) == 0xffff); } pub fn IFSTOPPED(s: u32) bool { return ((s & 0x7f != 0x7f) and !IFCONTINUED(s)); } pub fn IFSIGNALED(s: u32) bool { return !IFSTOPPED(s) and !IFCONTINUED(s) and !IFEXITED(s); } }; pub const SA = struct { pub const ONSTACK = 0x0001; pub const RESTART = 0x0002; pub const RESETHAND = 0x0004; pub const NOCLDSTOP = 0x0008; pub const NODEFER = 0x0010; pub const NOCLDWAIT = 0x0020; pub const SIGINFO = 0x0040; }; // access function pub const F_OK = 0; // test for existence of file pub const X_OK = 1; // test for execute or search permission pub const W_OK = 2; // test for write permission pub const R_OK = 4; // test for read permission pub const O = struct { /// open for reading only pub const RDONLY = 0x00000000; /// open for writing only pub const WRONLY = 0x00000001; /// open for reading and writing pub const RDWR = 0x00000002; /// mask for above modes pub const ACCMODE = 0x00000003; /// no delay pub const NONBLOCK = 0x00000004; /// set append mode pub const APPEND = 0x00000008; /// open with shared file lock pub const SHLOCK = 0x00000010; /// open with exclusive file lock pub const EXLOCK = 0x00000020; /// signal pgrp when data ready pub const ASYNC = 0x00000040; /// synchronous writes pub const SYNC = 0x00000080; /// don't follow symlinks on the last pub const NOFOLLOW = 0x00000100; /// create if nonexistent pub const CREAT = 0x00000200; /// truncate to zero length pub const TRUNC = 0x00000400; /// error if already exists pub const EXCL = 0x00000800; /// don't assign controlling terminal pub const NOCTTY = 0x00008000; /// write: I/O data completion pub const DSYNC = 0x00010000; /// read: I/O completion as for write pub const RSYNC = 0x00020000; /// use alternate i/o semantics pub const ALT_IO = 0x00040000; /// direct I/O hint pub const DIRECT = 0x00080000; /// fail if not a directory pub const DIRECTORY = 0x00200000; /// set close on exec pub const CLOEXEC = 0x00400000; /// skip search permission checks pub const SEARCH = 0x00800000; }; pub const F = struct { pub const DUPFD = 0; pub const GETFD = 1; pub const SETFD = 2; pub const GETFL = 3; pub const SETFL = 4; pub const GETOWN = 5; pub const SETOWN = 6; pub const GETLK = 7; pub const SETLK = 8; pub const SETLKW = 9; pub const RDLCK = 1; pub const WRLCK = 3; pub const UNLCK = 2; }; pub const LOCK = struct { pub const SH = 1; pub const EX = 2; pub const UN = 8; pub const NB = 4; }; pub const FD_CLOEXEC = 1; pub const SEEK = struct { pub const SET = 0; pub const CUR = 1; pub const END = 2; }; pub const DT = struct { pub const UNKNOWN = 0; pub const FIFO = 1; pub const CHR = 2; pub const DIR = 4; pub const BLK = 6; pub const REG = 8; pub const LNK = 10; pub const SOCK = 12; pub const WHT = 14; }; /// add event to kq (implies enable) pub const EV_ADD = 0x0001; /// delete event from kq pub const EV_DELETE = 0x0002; /// enable event pub const EV_ENABLE = 0x0004; /// disable event (not reported) pub const EV_DISABLE = 0x0008; /// only report one occurrence pub const EV_ONESHOT = 0x0010; /// clear event state after reporting pub const EV_CLEAR = 0x0020; /// force immediate event output /// ... with or without EV_ERROR /// ... use KEVENT_FLAG_ERROR_EVENTS /// on syscalls supporting flags pub const EV_RECEIPT = 0x0040; /// disable event after reporting pub const EV_DISPATCH = 0x0080; pub const EVFILT_READ = 0; pub const EVFILT_WRITE = 1; /// attached to aio requests pub const EVFILT_AIO = 2; /// attached to vnodes pub const EVFILT_VNODE = 3; /// attached to struct proc pub const EVFILT_PROC = 4; /// attached to struct proc pub const EVFILT_SIGNAL = 5; /// timers pub const EVFILT_TIMER = 6; /// Filesystem events pub const EVFILT_FS = 7; /// User events pub const EVFILT_USER = 1; /// On input, NOTE_TRIGGER causes the event to be triggered for output. pub const NOTE_TRIGGER = 0x08000000; /// low water mark pub const NOTE_LOWAT = 0x00000001; /// vnode was removed pub const NOTE_DELETE = 0x00000001; /// data contents changed pub const NOTE_WRITE = 0x00000002; /// size increased pub const NOTE_EXTEND = 0x00000004; /// attributes changed pub const NOTE_ATTRIB = 0x00000008; /// link count changed pub const NOTE_LINK = 0x00000010; /// vnode was renamed pub const NOTE_RENAME = 0x00000020; /// vnode access was revoked pub const NOTE_REVOKE = 0x00000040; /// process exited pub const NOTE_EXIT = 0x80000000; /// process forked pub const NOTE_FORK = 0x40000000; /// process exec'd pub const NOTE_EXEC = 0x20000000; /// mask for signal & exit status pub const NOTE_PDATAMASK = 0x000fffff; pub const NOTE_PCTRLMASK = 0xf0000000; pub const T = struct { pub const IOCCBRK = 0x2000747a; pub const IOCCDTR = 0x20007478; pub const IOCCONS = 0x80047462; pub const IOCDCDTIMESTAMP = 0x40107458; pub const IOCDRAIN = 0x2000745e; pub const IOCEXCL = 0x2000740d; pub const IOCEXT = 0x80047460; pub const IOCFLAG_CDTRCTS = 0x10; pub const IOCFLAG_CLOCAL = 0x2; pub const IOCFLAG_CRTSCTS = 0x4; pub const IOCFLAG_MDMBUF = 0x8; pub const IOCFLAG_SOFTCAR = 0x1; pub const IOCFLUSH = 0x80047410; pub const IOCGETA = 0x402c7413; pub const IOCGETD = 0x4004741a; pub const IOCGFLAGS = 0x4004745d; pub const IOCGLINED = 0x40207442; pub const IOCGPGRP = 0x40047477; pub const IOCGQSIZE = 0x40047481; pub const IOCGRANTPT = 0x20007447; pub const IOCGSID = 0x40047463; pub const IOCGSIZE = 0x40087468; pub const IOCGWINSZ = 0x40087468; pub const IOCMBIC = 0x8004746b; pub const IOCMBIS = 0x8004746c; pub const IOCMGET = 0x4004746a; pub const IOCMSET = 0x8004746d; pub const IOCM_CAR = 0x40; pub const IOCM_CD = 0x40; pub const IOCM_CTS = 0x20; pub const IOCM_DSR = 0x100; pub const IOCM_DTR = 0x2; pub const IOCM_LE = 0x1; pub const IOCM_RI = 0x80; pub const IOCM_RNG = 0x80; pub const IOCM_RTS = 0x4; pub const IOCM_SR = 0x10; pub const IOCM_ST = 0x8; pub const IOCNOTTY = 0x20007471; pub const IOCNXCL = 0x2000740e; pub const IOCOUTQ = 0x40047473; pub const IOCPKT = 0x80047470; pub const IOCPKT_DATA = 0x0; pub const IOCPKT_DOSTOP = 0x20; pub const IOCPKT_FLUSHREAD = 0x1; pub const IOCPKT_FLUSHWRITE = 0x2; pub const IOCPKT_IOCTL = 0x40; pub const IOCPKT_NOSTOP = 0x10; pub const IOCPKT_START = 0x8; pub const IOCPKT_STOP = 0x4; pub const IOCPTMGET = 0x40287446; pub const IOCPTSNAME = 0x40287448; pub const IOCRCVFRAME = 0x80087445; pub const IOCREMOTE = 0x80047469; pub const IOCSBRK = 0x2000747b; pub const IOCSCTTY = 0x20007461; pub const IOCSDTR = 0x20007479; pub const IOCSETA = 0x802c7414; pub const IOCSETAF = 0x802c7416; pub const IOCSETAW = 0x802c7415; pub const IOCSETD = 0x8004741b; pub const IOCSFLAGS = 0x8004745c; pub const IOCSIG = 0x2000745f; pub const IOCSLINED = 0x80207443; pub const IOCSPGRP = 0x80047476; pub const IOCSQSIZE = 0x80047480; pub const IOCSSIZE = 0x80087467; pub const IOCSTART = 0x2000746e; pub const IOCSTAT = 0x80047465; pub const IOCSTI = 0x80017472; pub const IOCSTOP = 0x2000746f; pub const IOCSWINSZ = 0x80087467; pub const IOCUCNTL = 0x80047466; pub const IOCXMTFRAME = 0x80087444; }; pub const winsize = extern struct { ws_row: u16, ws_col: u16, ws_xpixel: u16, ws_ypixel: u16, }; const NSIG = 32; pub const SIG = struct { pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0); pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1); pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize)); pub const WORDS = 4; pub const MAXSIG = 128; pub const BLOCK = 1; pub const UNBLOCK = 2; pub const SETMASK = 3; pub const HUP = 1; pub const INT = 2; pub const QUIT = 3; pub const ILL = 4; pub const TRAP = 5; pub const ABRT = 6; pub const IOT = ABRT; pub const EMT = 7; pub const FPE = 8; pub const KILL = 9; pub const BUS = 10; pub const SEGV = 11; pub const SYS = 12; pub const PIPE = 13; pub const ALRM = 14; pub const TERM = 15; pub const URG = 16; pub const STOP = 17; pub const TSTP = 18; pub const CONT = 19; pub const CHLD = 20; pub const TTIN = 21; pub const TTOU = 22; pub const IO = 23; pub const XCPU = 24; pub const XFSZ = 25; pub const VTALRM = 26; pub const PROF = 27; pub const WINCH = 28; pub const INFO = 29; pub const USR1 = 30; pub const USR2 = 31; pub const PWR = 32; pub const RTMIN = 33; pub const RTMAX = 63; pub inline fn IDX(sig: usize) usize { return sig - 1; } pub inline fn WORD(sig: usize) usize { return IDX(sig) >> 5; } pub inline fn BIT(sig: usize) usize { return 1 << (IDX(sig) & 31); } pub inline fn VALID(sig: usize) usize { return sig <= MAXSIG and sig > 0; } }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { pub const handler_fn = fn (c_int) callconv(.C) void; pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const c_void) callconv(.C) void; /// signal handler handler: extern union { handler: ?handler_fn, sigaction: ?sigaction_fn, }, /// signal mask to apply mask: sigset_t, /// signal options flags: c_uint, }; pub const sigval_t = extern union { int: i32, ptr: ?*c_void, }; pub const siginfo_t = extern union { pad: [128]u8, info: _ksiginfo, }; pub const _ksiginfo = extern struct { signo: i32, code: i32, errno: i32, // 64bit architectures insert 4bytes of padding here, this is done by // correctly aligning the reason field reason: extern union { rt: extern struct { pid: pid_t, uid: uid_t, value: sigval_t, }, child: extern struct { pid: pid_t, uid: uid_t, status: i32, utime: clock_t, stime: clock_t, }, fault: extern struct { addr: ?*c_void, trap: i32, trap2: i32, trap3: i32, }, poll: extern struct { band: i32, fd: i32, }, syscall: extern struct { sysnum: i32, retval: [2]i32, @"error": i32, args: [8]u64, }, ptrace_state: extern struct { pe_report_event: i32, option: extern union { pe_other_pid: pid_t, pe_lwp: lwpid_t, }, }, } align(@sizeOf(usize)), }; pub const sigset_t = extern struct { __bits: [SIG.WORDS]u32, }; pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** SIG.WORDS }; // XXX x86_64 specific pub const mcontext_t = extern struct { gregs: [26]u64, mc_tlsbase: u64, fpregs: [512]u8 align(8), }; pub const REG = struct { pub const RBP = 12; pub const RIP = 21; pub const RSP = 24; }; pub const ucontext_t = extern struct { flags: u32, link: ?*ucontext_t, sigmask: sigset_t, stack: stack_t, mcontext: mcontext_t, __pad: [ switch (builtin.cpu.arch) { .i386 => 4, .mips, .mipsel, .mips64, .mips64el => 14, .arm, .armeb, .thumb, .thumbeb => 1, .sparc, .sparcel, .sparcv9 => if (@sizeOf(usize) == 4) 43 else 8, else => 0, } ]u32, }; pub const E = enum(u16) { /// No error occurred. SUCCESS = 0, PERM = 1, // Operation not permitted NOENT = 2, // No such file or directory SRCH = 3, // No such process INTR = 4, // Interrupted system call IO = 5, // Input/output error NXIO = 6, // Device not configured @"2BIG" = 7, // Argument list too long NOEXEC = 8, // Exec format error BADF = 9, // Bad file descriptor CHILD = 10, // No child processes DEADLK = 11, // Resource deadlock avoided // 11 was AGAIN NOMEM = 12, // Cannot allocate memory ACCES = 13, // Permission denied FAULT = 14, // Bad address NOTBLK = 15, // Block device required BUSY = 16, // Device busy EXIST = 17, // File exists XDEV = 18, // Cross-device link NODEV = 19, // Operation not supported by device NOTDIR = 20, // Not a directory ISDIR = 21, // Is a directory INVAL = 22, // Invalid argument NFILE = 23, // Too many open files in system MFILE = 24, // Too many open files NOTTY = 25, // Inappropriate ioctl for device TXTBSY = 26, // Text file busy FBIG = 27, // File too large NOSPC = 28, // No space left on device SPIPE = 29, // Illegal seek ROFS = 30, // Read-only file system MLINK = 31, // Too many links PIPE = 32, // Broken pipe // math software DOM = 33, // Numerical argument out of domain RANGE = 34, // Result too large or too small // non-blocking and interrupt i/o // also: WOULDBLOCK: operation would block AGAIN = 35, // Resource temporarily unavailable INPROGRESS = 36, // Operation now in progress ALREADY = 37, // Operation already in progress // ipc/network software -- argument errors NOTSOCK = 38, // Socket operation on non-socket DESTADDRREQ = 39, // Destination address required MSGSIZE = 40, // Message too long PROTOTYPE = 41, // Protocol wrong type for socket NOPROTOOPT = 42, // Protocol option not available PROTONOSUPPORT = 43, // Protocol not supported SOCKTNOSUPPORT = 44, // Socket type not supported OPNOTSUPP = 45, // Operation not supported PFNOSUPPORT = 46, // Protocol family not supported AFNOSUPPORT = 47, // Address family not supported by protocol family ADDRINUSE = 48, // Address already in use ADDRNOTAVAIL = 49, // Can't assign requested address // ipc/network software -- operational errors NETDOWN = 50, // Network is down NETUNREACH = 51, // Network is unreachable NETRESET = 52, // Network dropped connection on reset CONNABORTED = 53, // Software caused connection abort CONNRESET = 54, // Connection reset by peer NOBUFS = 55, // No buffer space available ISCONN = 56, // Socket is already connected NOTCONN = 57, // Socket is not connected SHUTDOWN = 58, // Can't send after socket shutdown TOOMANYREFS = 59, // Too many references: can't splice TIMEDOUT = 60, // Operation timed out CONNREFUSED = 61, // Connection refused LOOP = 62, // Too many levels of symbolic links NAMETOOLONG = 63, // File name too long // should be rearranged HOSTDOWN = 64, // Host is down HOSTUNREACH = 65, // No route to host NOTEMPTY = 66, // Directory not empty // quotas & mush PROCLIM = 67, // Too many processes USERS = 68, // Too many users DQUOT = 69, // Disc quota exceeded // Network File System STALE = 70, // Stale NFS file handle REMOTE = 71, // Too many levels of remote in path BADRPC = 72, // RPC struct is bad RPCMISMATCH = 73, // RPC version wrong PROGUNAVAIL = 74, // RPC prog. not avail PROGMISMATCH = 75, // Program version wrong PROCUNAVAIL = 76, // Bad procedure for program NOLCK = 77, // No locks available NOSYS = 78, // Function not implemented FTYPE = 79, // Inappropriate file type or format AUTH = 80, // Authentication error NEEDAUTH = 81, // Need authenticator // SystemV IPC IDRM = 82, // Identifier removed NOMSG = 83, // No message of desired type OVERFLOW = 84, // Value too large to be stored in data type // Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995 ILSEQ = 85, // Illegal byte sequence // From IEEE Std 1003.1-2001 // Base, Realtime, Threads or Thread Priority Scheduling option errors NOTSUP = 86, // Not supported // Realtime option errors CANCELED = 87, // Operation canceled // Realtime, XSI STREAMS option errors BADMSG = 88, // Bad or Corrupt message // XSI STREAMS option errors NODATA = 89, // No message available NOSR = 90, // No STREAM resources NOSTR = 91, // Not a STREAM TIME = 92, // STREAM ioctl timeout // File system extended attribute errors NOATTR = 93, // Attribute not found // Realtime, XSI STREAMS option errors MULTIHOP = 94, // Multihop attempted NOLINK = 95, // Link has been severed PROTO = 96, // Protocol error _, }; pub const MINSIGSTKSZ = 8192; pub const SIGSTKSZ = MINSIGSTKSZ + 32768; pub const SS_ONSTACK = 1; pub const SS_DISABLE = 4; pub const stack_t = extern struct { sp: [*]u8, size: isize, flags: i32, }; pub const S = struct { pub const IFMT = 0o170000; pub const IFIFO = 0o010000; pub const IFCHR = 0o020000; pub const IFDIR = 0o040000; pub const IFBLK = 0o060000; pub const IFREG = 0o100000; pub const IFLNK = 0o120000; pub const IFSOCK = 0o140000; pub const IFWHT = 0o160000; pub const ISUID = 0o4000; pub const ISGID = 0o2000; pub const ISVTX = 0o1000; pub const IRWXU = 0o700; pub const IRUSR = 0o400; pub const IWUSR = 0o200; pub const IXUSR = 0o100; pub const IRWXG = 0o070; pub const IRGRP = 0o040; pub const IWGRP = 0o020; pub const IXGRP = 0o010; pub const IRWXO = 0o007; pub const IROTH = 0o004; pub const IWOTH = 0o002; pub const IXOTH = 0o001; pub fn ISFIFO(m: u32) bool { return m & IFMT == IFIFO; } pub fn ISCHR(m: u32) bool { return m & IFMT == IFCHR; } pub fn ISDIR(m: u32) bool { return m & IFMT == IFDIR; } pub fn ISBLK(m: u32) bool { return m & IFMT == IFBLK; } pub fn ISREG(m: u32) bool { return m & IFMT == IFREG; } pub fn ISLNK(m: u32) bool { return m & IFMT == IFLNK; } pub fn ISSOCK(m: u32) bool { return m & IFMT == IFSOCK; } pub fn IWHT(m: u32) bool { return m & IFMT == IFWHT; } }; pub const AT = struct { /// Magic value that specify the use of the current working directory /// to determine the target of relative file paths in the openat() and /// similar syscalls. pub const FDCWD = -100; /// Check access using effective user and group ID pub const EACCESS = 0x0100; /// Do not follow symbolic links pub const SYMLINK_NOFOLLOW = 0x0200; /// Follow symbolic link pub const SYMLINK_FOLLOW = 0x0400; /// Remove directory instead of file pub const REMOVEDIR = 0x0800; }; pub const HOST_NAME_MAX = 255; pub const IPPROTO = struct { /// dummy for IP pub const IP = 0; /// IP6 hop-by-hop options pub const HOPOPTS = 0; /// control message protocol pub const ICMP = 1; /// group mgmt protocol pub const IGMP = 2; /// gateway^2 (deprecated) pub const GGP = 3; /// IP header pub const IPV4 = 4; /// IP inside IP pub const IPIP = 4; /// tcp pub const TCP = 6; /// exterior gateway protocol pub const EGP = 8; /// pup pub const PUP = 12; /// user datagram protocol pub const UDP = 17; /// xns idp pub const IDP = 22; /// tp-4 w/ class negotiation pub const TP = 29; /// DCCP pub const DCCP = 33; /// IP6 header pub const IPV6 = 41; /// IP6 routing header pub const ROUTING = 43; /// IP6 fragmentation header pub const FRAGMENT = 44; /// resource reservation pub const RSVP = 46; /// GRE encaps RFC 1701 pub const GRE = 47; /// encap. security payload pub const ESP = 50; /// authentication header pub const AH = 51; /// IP Mobility RFC 2004 pub const MOBILE = 55; /// IPv6 ICMP pub const IPV6_ICMP = 58; /// ICMP6 pub const ICMPV6 = 58; /// IP6 no next header pub const NONE = 59; /// IP6 destination option pub const DSTOPTS = 60; /// ISO cnlp pub const EON = 80; /// Ethernet-in-IP pub const ETHERIP = 97; /// encapsulation header pub const ENCAP = 98; /// Protocol indep. multicast pub const PIM = 103; /// IP Payload Comp. Protocol pub const IPCOMP = 108; /// VRRP RFC 2338 pub const VRRP = 112; /// Common Address Resolution Protocol pub const CARP = 112; /// L2TPv3 pub const L2TP = 115; /// SCTP pub const SCTP = 132; /// PFSYNC pub const PFSYNC = 240; /// raw IP packet pub const RAW = 255; }; pub const rlimit_resource = enum(c_int) { CPU = 0, FSIZE = 1, DATA = 2, STACK = 3, CORE = 4, RSS = 5, MEMLOCK = 6, NPROC = 7, NOFILE = 8, SBSIZE = 9, VMEM = 10, NTHR = 11, _, pub const AS: rlimit_resource = .VMEM; }; pub const rlim_t = u64; pub const RLIM = struct { /// No limit pub const INFINITY: rlim_t = (1 << 63) - 1; pub const SAVED_MAX = INFINITY; pub const SAVED_CUR = INFINITY; }; pub const rlimit = extern struct { /// Soft limit cur: rlim_t, /// Hard limit max: rlim_t, }; pub const SHUT = struct { pub const RD = 0; pub const WR = 1; pub const RDWR = 2; }; pub const nfds_t = u32; pub const pollfd = extern struct { fd: fd_t, events: i16, revents: i16, }; pub const POLL = struct { /// Testable events (may be specified in events field). pub const IN = 0x0001; pub const PRI = 0x0002; pub const OUT = 0x0004; pub const RDNORM = 0x0040; pub const WRNORM = OUT; pub const RDBAND = 0x0080; pub const WRBAND = 0x0100; /// Non-testable events (may not be specified in events field). pub const ERR = 0x0008; pub const HUP = 0x0010; pub const NVAL = 0x0020; };
lib/std/c/netbsd.zig
const std = @import("std"); const mem = std.mem; const os = std.os; const debug = std.debug; const io = std.io; const json = std.json; const fs = std.fs; const fmtDuration = std.fmt.fmtDuration; const bin_file = @import("bin_file.zig"); const Float = f32; const Dataset = @import("csv_img_dataset.zig").forData(Float, .{ 28, 28 }, 10); const TestCase = Dataset.TestCase; const nnet = @import("nnet.zig").typed(Float); const LogCtx = @import("log.zig"); const Options = struct { workers: usize = 0, load: ?[]const u8 = null, save: ?[]const u8 = null, img_dir_out: ?[]const u8 = null, epoches: usize = 1, learn_rate: Float = 0.1, batch_size: usize = 16, }; var options: Options = .{}; const rlog = LogCtx.scoped(.raw); const mlog = LogCtx.scoped(.main); // setup logging system pub const log_level = LogCtx.log_level; pub const log = LogCtx.log; const NNet2 = struct { li: nnet.Layer(28 * 28, 64) = .{}, l1: nnet.Layer(64, 10) = .{}, lo: nnet.Layer(10, 0) = .{}, }; const NNet = struct { const Self = @This(); pub const ValType = Float; // neural net layer sizes //const sizes = [4]usize{ 28 * 28, 128, 64, 10 }; // TODO: layer 1 is skipped right now pub const sizes = [4]usize{ 28 * 28, 28 * 28, 256, 10 }; pub const input_len = sizes[0]; pub const output_len = sizes[sizes.len - 1]; // activation functions pub const a1 = nnet.func.relu_leaky; pub const a2 = nnet.func.relu_leaky; pub const a3 = nnet.func.softmax; pub const err_fn = nnet.func.logLoss; pub const TrainResult = struct { correct: u32 = 0, // was answer correct, in case of batch: how many? loss: Float = 0, // for merges: how may tests this struct represent // after merge is finalized this is inversed to negative number to prevent accidental wrong merges etc. test_cases: Float = 0, // Backprop bias derivatives d_b1: @Vector(sizes[1], Float) = std.mem.zeroes(@Vector(sizes[1], Float)), d_b2: @Vector(sizes[2], Float) = std.mem.zeroes(@Vector(sizes[2], Float)), d_bo: @Vector(sizes[3], Float) = std.mem.zeroes(@Vector(sizes[3], Float)), // Backprop weight derivatives d_w0: [sizes[0]]@Vector(sizes[1], Float) = [_]@Vector(sizes[1], Float){@splat(sizes[1], @as(Float, 0))} ** sizes[0], d_w1: [sizes[1]]@Vector(sizes[2], Float) = [_]@Vector(sizes[2], Float){@splat(sizes[2], @as(Float, 0))} ** sizes[1], d_w2: [sizes[2]]@Vector(sizes[3], Float) = [_]@Vector(sizes[3], Float){@splat(sizes[3], @as(Float, 0))} ** sizes[2], // merges training results for batch training // derivatives are summed, call finalizeMerge() before applying to average them pub fn merge(self: *TrainResult, b: TrainResult) void { @setFloatMode(std.builtin.FloatMode.Optimized); if (b.test_cases == 0) return; if (self.test_cases == 0) { self.* = b; return; } std.debug.assert(self.test_cases >= 1); std.debug.assert(b.test_cases >= 1); self.correct += b.correct; self.loss += b.loss; self.test_cases += b.test_cases; for (self.d_w0) |*w, nidx| { w.* += b.d_w0[nidx]; } for (self.d_w1) |*w, nidx| { w.* += b.d_w1[nidx]; } for (self.d_w2) |*w, nidx| { w.* += b.d_w2[nidx]; } } pub fn average(self: *TrainResult) void { @setFloatMode(std.builtin.FloatMode.Optimized); std.debug.assert(self.test_cases >= 1); if (self.test_cases == 1) return; const n: Float = 1.0 / self.test_cases; if (!std.math.isFinite(n)) debug.panic("Not finite: {} / {} = {}", .{ 1.0, self.test_cases, n }); self.loss *= n; for (self.d_w0) |*w| { w.* *= @splat(@typeInfo(@TypeOf(w.*)).Vector.len, n); } for (self.d_w1) |*w| { w.* *= @splat(@typeInfo(@TypeOf(w.*)).Vector.len, n); } for (self.d_w2) |*w| { w.* *= @splat(@typeInfo(@TypeOf(w.*)).Vector.len, n); } self.test_cases *= -1; } pub fn print(self : *@This()) void { mlog.info("b1: {d:.2}", .{self.d_b1}); mlog.info("b2: {d:.2}", .{self.d_b2}); mlog.info("bo: {d:.2}", .{self.d_bo}); mlog.info("w0: {d:.2}", .{self.d_w0}); mlog.info("w1: {d:.2}", .{self.d_w1}); mlog.info("w2: {d:.2}", .{self.d_w2}); } }; // Member variables: // variables that contain index, its from 0 .., where 0 = input layer, and 1 is first hidden layer etc. // Neurons: // hidden layers h1: @Vector(sizes[1], Float) = undefined, h2: @Vector(sizes[2], Float) = undefined, // output non activated and activated //out: @Vector(sizes[3], Float) = undefined, out_activated: @Vector(sizes[3], Float) = undefined, // Biases b1: @Vector(sizes[1], Float) = undefined, b2: @Vector(sizes[2], Float) = undefined, bo: @Vector(sizes[3], Float) = undefined, // Weights w0: [sizes[0]]@Vector(sizes[1], Float) = undefined, w1: [sizes[1]]@Vector(sizes[2], Float) = undefined, w2: [sizes[2]]@Vector(sizes[3], Float) = undefined, pub fn randomize(self: *Self, rnd: *std.rand.Random) void { @setFloatMode(std.builtin.FloatMode.Optimized); nnet.randomize(rnd, &self.w0); nnet.randomize(rnd, &self.w1); nnet.randomize(rnd, &self.w2); // nnet.randomize(rnd, &self.b1); // nnet.randomize(rnd, &self.b2); // nnet.randomize(rnd, &self.bo); self.b1 = @splat(sizes[1], @as(Float, 0.1)); self.b2 = @splat(sizes[2], @as(Float, 0.1)); self.bo = @splat(sizes[3], @as(Float, 0.1)); //nnet.randomize(rnd, &self.b4); //self.bo = std.mem.zeroes(@TypeOf(self.bo)); nnet.assertFinite(self.b1, "b1"); nnet.assertFinite(self.b2, "b2"); nnet.assertFinite(self.bo, "b3"); } pub fn feedForward(self: *Self, input: *const @Vector(sizes[0], Float)) void { @setFloatMode(std.builtin.FloatMode.Optimized); self.h1 = input.*; // nnet.forward(self.i, self.w0, Self.a1, self.b1, void, &self.h1); nnet.forward(self.h1, self.w1, Self.a2, self.b2, &self.h2); nnet.forward(self.h2, self.w2, Self.a3, self.bo, &self.out_activated); nnet.assertFinite(self.out_activated, "out_activated"); } // train to get derivatives pub fn trainDeriv(self: *Self, test_case: TestCase, train_result: *TrainResult) void { @setFloatMode(std.builtin.FloatMode.Optimized); //var timer = try std.time.Timer.start(); debug.assert(std.mem.len(test_case.input) == sizes[0]); self.feedForward(&test_case.input); const predicted_confidence: Float = @reduce(.Max, self.out_activated); //mlog.debug("output layer: {}", .{self.out_activated}); var answer_vector = test_case.answer; const answer: u8 = ablk: { var i: u8 = 0; while (i < output_len) : (i += 1) { if (answer_vector[i] == 1) { break :ablk i; } } @panic("Wrongly formated answer!"); }; const o_err = err_fn.f(answer_vector, self.out_activated); const total_err: Float = @reduce(.Add, o_err); const predicted_correct = predicted_confidence == self.out_activated[answer] and predicted_confidence > 0.2 and total_err < 0.5; // BACKPROP: // from: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ // Last/Output layer: // how much total error change with respect to the activated output: // 𝝏err_total / 𝝏out_activated const d_err_oa = -err_fn.deriv(answer_vector, self.out_activated); nnet.assertFinite(d_err_oa, "backprop out: d_err_oa"); // how much activated output change with respect to the (non activated) output: // 𝝏out_activated / 𝝏out const d_oa_o = a3.derivZ(self.out_activated); nnet.assertFinite(d_oa_o, "backprop out: d_oa_o"); // how much Output error changes with respect to output (non activated): // 𝝏err_o / 𝝏h2_na const d_oerr_o_na = d_err_oa * d_oa_o; { // how much (non activated) output change with respect to the weights: // 𝝏out / 𝝏w const d_o_w = self.h2; // last hidden layer train_result.d_bo += d_oerr_o_na; // store result // iterate last hidden layer neurons and update its weights for (self.w2) |_, nidx| { // how much total error change with respect to the weights: // 𝝏total_err / 𝝏w const d_err_w = d_oerr_o_na * @splat(sizes[3], d_o_w[nidx]); nnet.assertFinite(d_err_w, "backprop out: d_err_w"); train_result.d_w2[nidx] += d_err_w; // store result } } { // Hidden layer const h_len = @typeInfo(@TypeOf(self.h2)).Vector.len; // how much total error changes with respect to output (activated) of hidden layer // 𝝏err_total / 𝝏h var d_err_h: @Vector(h_len, Float) = undefined; for (self.w2) |w, nidx| { // how much error of output (not activated) changes with respect to hidden layer output (activated) // 𝝏err_o_na / 𝝏err_h const d_err_o_na__err_h = d_oerr_o_na * w; // 𝝏err_total / 𝝏h d_err_h[nidx] = @reduce(.Add, d_err_o_na__err_h); nnet.assertFinite(d_err_h, "backprop hidden out->current: d_err_h"); } // how much output of hidden_activated changes with respect to hidden non activated // 𝝏h2 / 𝝏h2_na const d_h2_h2na = a1.derivZ(self.h2); nnet.assertFinite(d_h2_h2na, "backprop a1.derivZ( d_h2_h2na )"); { // how much hidden layer (non activated) output change with respect to the weights: // 𝝏out / 𝝏w const d_o_w = self.h1; const d_tmp = d_err_h * d_h2_h2na; train_result.d_b2 += d_tmp; // store result for (self.w1) |_, nidx| { // how much total error change with respect to the weights: // 𝝏total_err / 𝝏w const d_err_w = d_tmp * @splat(h_len, d_o_w[nidx]); nnet.assertFinite(d_err_w, "backprop hidden: d_err_w"); // store result train_result.d_w1[nidx] += d_err_w; } } } train_result.correct += @as(u32, if (predicted_correct) 1 else 0); train_result.loss += total_err; train_result.test_cases += 1; } pub fn learn(self: *Self, train_results: TrainResult, learn_rate: Float) void { @setFloatMode(std.builtin.FloatMode.Optimized); self.bo += train_results.d_bo * @splat(@typeInfo(@TypeOf(self.bo)).Vector.len, learn_rate); self.b2 += train_results.d_b2 * @splat(@typeInfo(@TypeOf(self.b2)).Vector.len, learn_rate); for (self.w1) |*w, nidx| { w.* -= train_results.d_w1[nidx] * @splat(@typeInfo(@TypeOf(w.*)).Vector.len, learn_rate); } for (self.w2) |*w, nidx| { w.* -= train_results.d_w2[nidx] * @splat(@typeInfo(@TypeOf(w.*)).Vector.len, learn_rate); } } }; pub fn doTest(alloc: *mem.Allocator) !void { var net: NNet = undefined; if (options.load) |p| { var in_file = std.fs.cwd().openFile(p, .{}) catch |err| debug.panic("Can't open nnet: '{s}' Error:{}", .{ p, err }); defer in_file.close(); bin_file.readFile(NNet, &net, &in_file) catch |err| debug.panic("Can't open nnet: '{s}' Error:{}", .{ p, err }); } else std.debug.panic("Can't test, network not specified! Use '--load' to specify network!", .{}); var td = Dataset.init(alloc); const img_dir_path = "./data/digits/Images/test/"; try td.load("./data/digits/test.csv", img_dir_path, "data/test.batch", false); mlog.info("Test data loaded: {} entries", .{td.test_cases.items.len}); const in_dir = try fs.cwd().openDir(img_dir_path, .{}); const out_dir: ?fs.Dir = odo: { if (options.img_dir_out) |p| { if (fs.cwd().openDir(p, .{})) |pdir| { pdir.makeDir("0") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("1") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("2") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("3") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("4") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("5") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("6") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("7") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("8") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); pdir.makeDir("9") catch |err| mlog.warn("Can't create directory for output! {}", .{err}); break :odo pdir; } else |err| { mlog.err("Can't opon img_dir_out: '{s}' err: {}", .{ p, err }); } } break :odo null; }; { // iterate and test var of = try std.fs.cwd().createFile("res.csv", .{}); defer of.close(); const writer = of.writer(); try writer.print("filename,label\n", .{}); for (td.test_cases.items) |*test_case, i| { net.feedForward(&test_case.input); var best: u8 = 0; var best_confidence: Float = 0; var ti: usize = 0; while (ti < 10) : (ti += 1) { if (best_confidence < net.out_activated[ti]) { best = @intCast(u8, ti); best_confidence = net.out_activated[ti]; } } if (out_dir) |od| { var out_name_buf = [_]u8{0} ** 32; const out_name = std.fmt.bufPrint(out_name_buf[0..], "{}/{d:.0}%_{}#.png", .{best, best_confidence*100, i}) catch unreachable; in_dir.copyFile(td.getTestName(i), od, out_name, .{}) catch |err| mlog.err("Cant copy test output '{s}' err:{}", .{out_name, err}); } const test_name = td.test_names.items[i]; try of.writer().print("{s},{}\n", .{ test_name, best }); mlog.info("{s} , {} , {d:.1}%\t[{d:.2}]", .{ test_name, best, best_confidence * 100.0, net.out_activated * @splat(10, @as(Float, 100)) }); } } } pub fn train(alloc: *mem.Allocator) !void { var td = Dataset.init(alloc); defer td.deinit(); try td.load("./data/digits/train.csv", "./data/digits/Images/train/", "data/train.batch", false); const seed = 364123; var rnd = std.rand.Sfc64.init(seed); const Trainer = @import("nnet_trainer.zig").forNet(NNet); var trainer = Trainer.init(alloc, &rnd.random); trainer.batch_size = options.batch_size; trainer.workers = options.workers; trainer.learn_rate = options.learn_rate; // load or initialise new net var net: NNet = undefined; if (options.load) |p| { var in_file = std.fs.cwd().openFile(p, .{}) catch |err| debug.panic("Can't open nnet: '{s}' Error:{}", .{ p, err }); defer in_file.close(); bin_file.readFile(NNet, &net, &in_file) catch |err| debug.panic("Can't open nnet: '{s}' Error:{}", .{ p, err }); } else net.randomize(&rnd.random); // train var timer = try std.time.Timer.start(); try trainer.trainEpoches(&net, &td.accessor, @intCast(u32, options.epoches)); mlog.notice("\nTotal train time: {}\n", .{fmtDuration(timer.lap())}); // save net if (options.save) |p| { var in_file = std.fs.cwd().createFile(p, .{}) catch |err| debug.panic("Can't open file for storing nnet: '{s}' Error:{}", .{ p, err }); defer in_file.close(); bin_file.writeFile(NNet, &net, &in_file) catch |err| debug.panic("Can't write nnet to file: '{s}' Error:{}", .{ p, err }); } } pub fn main() !void { LogCtx.init(); defer LogCtx.deinit() catch debug.print("Can't flush!", .{}); //LogCtx.testOut(); options.workers = try std.Thread.getCpuCount(); var galloc = std.heap.GeneralPurposeAllocator(.{}){}; defer if (galloc.deinit()) { debug.panic("GeneralPurposeAllocator had leaks!", .{}); }; var lalloc = std.heap.LoggingAllocator(std.log.Level.debug, std.log.Level.info).init(&galloc.allocator); var alloc = &lalloc.allocator; { // ARGS const args = (try std.process.argsAlloc(&galloc.allocator))[1..]; // skip first arg as it points to current executable defer std.process.argsFree(&galloc.allocator, args); const printHelp = struct { pub fn print() void { var cwd_path_buff: [512]u8 = undefined; const cwd_path: []const u8 = fs.cwd().realpath("", cwd_path_buff[0..]) catch "<ERROR>"; debug.print("cwd = {s}\n", .{cwd_path}); debug.print("Commands:\n", .{}); debug.print("\tpreprocess\t - saves batch of all input images in single file for faster loading\n", .{}); debug.print("\ttrain\t- trains network, optional arguments before command:\n", .{}); debug.print("\t\t--load {{relative_path - instead of initialising random net, load existing}}\n", .{}); debug.print("\t\t--save {{relative_path - after training save net}}\n", .{}); debug.print("\t\t--learn-rate {{float}}\n", .{}); debug.print("\t\t--batch-size {{int}}\n", .{}); debug.print("\t\t--epoches {{how many epoches to train}}\n", .{}); debug.print("\t\t--workers {{path - after training save net}}\n", .{}); } }.print; if (args.len < 1) printHelp(); // commands var skip: i32 = 0; for (args) |argv, ai| { if (skip > 0) { skip -= 1; continue; } if (std.cstr.cmp(argv, "--workers") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by value!", .{argv}); options.workers = try std.fmt.parseUnsigned(usize, args[ai + 1], 0); skip = 1; } else if (std.cstr.cmp(argv, "--epoches") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by value!", .{argv}); options.epoches = try std.fmt.parseUnsigned(usize, args[ai + 1], 0); skip = 1; } else if (std.cstr.cmp(argv, "--learn-rate") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by value!", .{argv}); options.learn_rate = try std.fmt.parseFloat(Float, args[ai + 1]); skip = 1; } else if (std.cstr.cmp(argv, "--load") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by path!", .{argv}); options.load = args[ai + 1]; skip = 1; } else if (std.cstr.cmp(argv, "--save") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by path!", .{argv}); options.save = args[ai + 1]; skip = 1; } else if (std.cstr.cmp(argv, "--batch-size") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by path!", .{argv}); options.batch_size = try std.fmt.parseUnsigned(usize, args[ai + 1], 0); skip = 1; } else if (std.cstr.cmp(argv, "--epoches") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by path!", .{argv}); options.epoches = try std.fmt.parseUnsigned(usize, args[ai + 1], 0); skip = 1; } else if (std.cstr.cmp(argv, "--img-dir-out") == 0) { if (ai + 1 >= args.len) std.debug.panic("Argument '{s}' needs to be followed by path!", .{argv}); options.img_dir_out = args[ai + 1]; skip = 1; } else if (std.cstr.cmp(argv, "preprocess") == 0) { { mlog.notice("Preprocessing training data...", .{}); var td = Dataset.init(alloc); defer td.deinit(); td.load("./data/digits/train.csv", "./data/digits/Images/train/", "data/train.batch", true) catch |err| debug.panic("Error: {}", .{err}); td.saveBatch("data/train.batch") catch |err| debug.panic("Error: {}", .{err}); } { mlog.notice("Preprocessing test data...", .{}); var td = Dataset.init(alloc); defer td.deinit(); td.load("./data/digits/test.csv", "./data/digits/Images/test/", "data/test.batch", true) catch |err| debug.panic("Error: {}", .{err}); td.saveBatch("data/test.batch") catch |err| debug.panic("Error: {}", .{err}); } } else if (std.cstr.cmp(argv, "train") == 0) { train(alloc) catch |err| debug.panic("Error: {}", .{err}); } else if (std.cstr.cmp(argv, "test") == 0) { try doTest(alloc); } else if (std.cstr.cmp(argv, "help") == 0) { printHelp(); } else std.debug.panic("Unknown argument: {s}", .{argv}); } } }
src/main.zig
const std = @import("../std.zig"); const testing = std.testing; /// Performs multiple async functions in parallel, without heap allocation. /// Async function frames are managed externally to this abstraction, and /// passed in via the `add` function. Once all the jobs are added, call `wait`. /// This API is *not* thread-safe. The object must be accessed from one thread at /// a time, however, it need not be the same thread. pub fn Batch( /// The return value for each job. /// If a job slot was re-used due to maxed out concurrency, then its result /// value will be overwritten. The values can be accessed with the `results` field. comptime Result: type, /// How many jobs to run in parallel. comptime max_jobs: comptime_int, /// Controls whether the `add` and `wait` functions will be async functions. comptime async_behavior: enum { /// Observe the value of `std.io.is_async` to decide whether `add` /// and `wait` will be async functions. Asserts that the jobs do not suspend when /// `std.io.mode == .blocking`. This is a generally safe assumption, and the /// usual recommended option for this parameter. auto_async, /// Always uses the `nosuspend` keyword when using `await` on the jobs, /// making `add` and `wait` non-async functions. Asserts that the jobs do not suspend. never_async, /// `add` and `wait` use regular `await` keyword, making them async functions. always_async, }, ) type { return struct { jobs: [max_jobs]Job, next_job_index: usize, collected_result: CollectedResult, const Job = struct { frame: ?anyframe->Result, result: Result, }; const Self = @This(); const CollectedResult = switch (@typeInfo(Result)) { .ErrorUnion => Result, else => void, }; const async_ok = switch (async_behavior) { .auto_async => std.io.is_async, .never_async => false, .always_async => true, }; pub fn init() Self { return Self{ .jobs = [1]Job{ .{ .frame = null, .result = undefined, }, } ** max_jobs, .next_job_index = 0, .collected_result = {}, }; } /// Add a frame to the Batch. If all jobs are in-flight, then this function /// waits until one completes. /// This function is *not* thread-safe. It must be called from one thread at /// a time, however, it need not be the same thread. /// TODO: "select" language feature to use the next available slot, rather than /// awaiting the next index. pub fn add(self: *Self, frame: anyframe->Result) void { const job = &self.jobs[self.next_job_index]; self.next_job_index = (self.next_job_index + 1) % max_jobs; if (job.frame) |existing| { job.result = if (async_ok) await existing else nosuspend await existing; if (CollectedResult != void) { job.result catch |err| { self.collected_result = err; }; } } job.frame = frame; } /// Wait for all the jobs to complete. /// Safe to call any number of times. /// If `Result` is an error union, this function returns the last error that occurred, if any. /// Unlike the `results` field, the return value of `wait` will report any error that occurred; /// hitting max parallelism will not compromise the result. /// This function is *not* thread-safe. It must be called from one thread at /// a time, however, it need not be the same thread. pub fn wait(self: *Self) CollectedResult { for (self.jobs) |*job| if (job.frame) |f| { job.result = if (async_ok) await f else nosuspend await f; if (CollectedResult != void) { job.result catch |err| { self.collected_result = err; }; } job.frame = null; }; return self.collected_result; } }; } test "std.event.Batch" { if (@import("builtin").zig_backend != .stage1) return error.SkipZigTest; var count: usize = 0; var batch = Batch(void, 2, .auto_async).init(); batch.add(&async sleepALittle(&count)); batch.add(&async increaseByTen(&count)); batch.wait(); try testing.expect(count == 11); var another = Batch(anyerror!void, 2, .auto_async).init(); another.add(&async somethingElse()); another.add(&async doSomethingThatFails()); try testing.expectError(error.ItBroke, another.wait()); } fn sleepALittle(count: *usize) void { std.time.sleep(1 * std.time.ns_per_ms); _ = @atomicRmw(usize, count, .Add, 1, .SeqCst); } fn increaseByTen(count: *usize) void { var i: usize = 0; while (i < 10) : (i += 1) { _ = @atomicRmw(usize, count, .Add, 1, .SeqCst); } } fn doSomethingThatFails() anyerror!void {} fn somethingElse() anyerror!void { return error.ItBroke; }
lib/std/event/batch.zig
const std = @import("std"); const wal_ns = @import("./wal.zig"); const pointer = @import("./pointer.zig"); const record_ns = @import("./record.zig"); const dm_ns = @import("./disk_manager.zig"); const header = @import("./header.zig"); const serialize = @import("serialize"); const Pointer = pointer.Pointer; const Wal = wal_ns.Wal; const Record = record_ns.Record; const DiskManager = dm_ns.DiskManager; const Header = header.Header; const Op = @import("./ops.zig").Op; /// A SST or Sorted String Table is created from a Wal object. The structure is the following: /// /// HEADER: Check the header.zig file for details /// /// DATA CHUNK: /// Contiguous array of records /// /// KEYS CHUNK /// Contiguous array of keys only with pointers to values in the data chunk pub fn Sst(comptime WalType: type) type { return struct { const Self = @This(); header: Header, file: *std.fs.File, wal: *WalType, pub fn init(w: *WalType, f: *std.fs.File) Self { var h = Header.init(WalType, w); return Self{ .wal = w, .file = f, .header = h, }; } /// writes into provided file the contents of the sst. Including pointers /// and the header. The allocator is required as a temporary buffer for /// data but it's freed inside the function pub fn persist(self: *Self, allocator: *std.mem.Allocator) !usize { var iter = self.wal.iterator(); var written: usize = 0; // TODO remove hardcoding on the next line var buf = try allocator.alloc(u8, 4096); defer allocator.free(buf); var head_offset: usize = header.headerSize(); var tail_offset: usize = self.wal.current_size; var pointer_total_bytes: usize = 0; // Write the data and pointers chunks while (iter.next()) |record| { // record var record_total_bytes = try serialize.record.toBytes(record, buf); written += try self.file.pwrite(buf[0..record_total_bytes], head_offset); head_offset += record_total_bytes; // pointer var pointer_ = pointer.Pointer{ .op = record.op, .key = record.key, .byte_offset = tail_offset, }; pointer_total_bytes = try serialize.pointer.toBytes(pointer_, buf); written += try self.file.pwrite(buf[0..pointer_total_bytes], tail_offset); tail_offset += pointer_total_bytes; } // update last unknown data on the header self.header.last_key_offset = tail_offset - pointer_total_bytes; // Write the header written += try self.writeHeader(); return written; } fn writeHeader(self: *Self) !usize { var header_buf: [header.headerSize()]u8 = undefined; _ = try serialize.header.toBytes(&self.header, &header_buf); return try self.file.pwrite(&header_buf, 0); } }; } test "sst.persist" { var allocator = std.testing.allocator; const WalType = Wal(4098); var wal = try WalType.init(&allocator); defer wal.deinit_cascade(); var r = try Record.init("hell0", "world1", Op.Update, &allocator); try wal.add_record(r); try wal.add_record(try Record.init("hell1", "world2", Op.Delete, &allocator)); try wal.add_record(try Record.init("hell2", "world3", Op.Delete, &allocator)); wal.sort(); try std.testing.expectEqual(@as(usize, 22), r.bytesLen()); std.debug.print("\nrecord size: {d}\n", .{r.bytesLen()}); std.debug.print("wal size in bytes {d}\n", .{wal.current_size}); std.debug.print("wal total records {d}\n", .{wal.total_records}); var dm = try DiskManager(WalType).init("/tmp"); var file = try dm.new_sst_file(&allocator); const SstType = Sst(WalType); var sst = SstType.init(wal, &file); std.debug.print("Header length {d}\n", .{header.headerSize()}); const bytes = try sst.persist(&allocator); std.debug.print("{d} bytes written into sst file\n", .{bytes}); // Close file and open it again with write permissions file.close(); file = try std.fs.openFileAbsolute("/tmp/1.sst", std.fs.File.OpenFlags{}); defer file.close(); var headerBuf: [header.headerSize()]u8 = undefined; _ = try file.read(&headerBuf); defer std.fs.deleteFileAbsolute("/tmp/1.sst") catch unreachable; // var i: usize = sst.wal.total_records; // var file_bytes: [512]u8 = undefined; // try file.seekTo(sst.header.first_key_offset); // _ = try file.readAll(&file_bytes); }
src/sst.zig
const std = @import("std"); const debug = std.debug; const testing = std.testing; const ArrayList = std.ArrayList; const global_allocator = debug.global_allocator; fn mergeT(comptime T: type) type { return struct { const Self = @This(); const LT = fn (T, T) bool; fn init() Self { return Self{}; } pub const Iterator = struct { list1: ArrayList(T).Iterator, list2: ArrayList(T).Iterator, less: LT, elem1: ?T, elem2: ?T, first: bool, pub fn reset(self: *Iterator) void { self.list1.reset(); self.list2.reset(); self.elem1 = null; self.elem2 = null; self.first = true; } pub fn next(self: *Iterator) ?T { if (self.first) { self.first = false; self.elem1 = self.list1.next(); self.elem2 = self.list2.next(); } var a: ?T = null; if ((self.elem1 == null) and (self.elem2 == null)) { return null; } else if (self.elem1 == null) { a = self.elem2; self.elem2 = self.list2.next(); } else if (self.elem2 == null) { a = self.elem1; self.elem1 = self.list1.next(); } else if (self.less(self.elem1.?, self.elem2.?)) { a = self.elem1; self.elem1 = self.list1.next(); } else { a = self.elem2; self.elem2 = self.list2.next(); } return a; } }; pub fn iterator(self: *Self, l1: ArrayList(T), l2: ArrayList(T), less: LT) Iterator { var iter1 = l1.iterator(); var iter2 = l2.iterator(); return Iterator{ .list1 = iter1, .list2 = iter2, .less = less, .elem1 = null, .elem2 = null, .first = true, }; } }; } fn elemOf(comptime t: type) type { return std.meta.Child(t.Slice); } fn merge(list1: var, list2: var, less: fn (elemOf(@typeOf(list1)), elemOf(@typeOf(list2))) bool) mergeT(elemOf(@typeOf(list1))).Iterator { return mergeT(elemOf(@typeOf(list1))).init().iterator(list1, list2, less); } fn lt(a: i32, b: i32) bool { return a < b; } test "merge.iterator" { var list1 = std.ArrayList(i32).init(global_allocator); defer list1.deinit(); var list2 = std.ArrayList(i32).init(global_allocator); defer list2.deinit(); try list1.append(1); try list1.append(2); try list1.append(3); try list2.append(2); try list2.append(6); try list2.append(7); var iter = merge(list1, list2, lt); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next().? == 2); testing.expect(iter.next().? == 3); testing.expect(iter.next().? == 6); testing.expect(iter.next().? == 7); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "merge.first_null" { var list1 = std.ArrayList(i32).init(global_allocator); defer list1.deinit(); var list2 = std.ArrayList(i32).init(global_allocator); defer list2.deinit(); try list2.append(1); try list2.append(2); var iter = merge(list1, list2, lt); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "merge.second_null" { var list1 = std.ArrayList(i32).init(global_allocator); defer list1.deinit(); var list2 = std.ArrayList(i32).init(global_allocator); defer list2.deinit(); try list1.append(1); try list1.append(2); var iter = merge(list1, list2, lt); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "merge.both_null" { var list1 = std.ArrayList(i32).init(global_allocator); defer list1.deinit(); var list2 = std.ArrayList(i32).init(global_allocator); defer list2.deinit(); var iter = merge(list1, list2, lt); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "merge.reset" { var list1 = std.ArrayList(i32).init(global_allocator); defer list1.deinit(); var list2 = std.ArrayList(i32).init(global_allocator); defer list2.deinit(); try list1.append(1); try list1.append(3); try list2.append(2); try list2.append(4); var iter = merge(list1, list2, lt); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next().? == 3); testing.expect(iter.next().? == 4); testing.expect(iter.next() == null); iter.reset(); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); iter.reset(); testing.expect(iter.next().? == 1); }
src/merge.zig
const std = @import("std"); pub fn FCFS(comptime K: type, comptime V: type) type { return struct { seed: u32 = 0xc70f6907, alloc: std.mem.Allocator, max_load_factor: f16 = 0.70, map_buf: []?K = undefined, value_buf: []?V = undefined, load: usize = 0, iter_off: usize = 0, const Self = @This(); /// Cell represents a key value pair. pub const Cell = struct { key: K, val: V, }; pub fn init(alloc: std.mem.Allocator) !Self { return Self{ .seed = std.crypto.random.int(u32), .alloc = alloc, .map_buf = try alloc.alloc(?K, 64), .value_buf = try alloc.alloc(?V, 64), }; } /// deinit the map's memory pub fn deinit(self: *Self) void { self.alloc.free(self.map_buf); self.alloc.free(self.value_buf); } /// puts a new value in the map, overwriting any existing value /// returns the old value if any existed pub fn put(self: *Self, key: K, value: V) std.mem.Allocator.Error!?V { if (@intToFloat(f16, self.load) / @intToFloat(f16, self.map_buf.len) > self.max_load_factor) try self.rehash(self.map_buf.len * 2); var kh = std.hash.Murmur3_32.hashWithSeed(std.mem.asBytes(&key), self.seed) % self.map_buf.len; var old: ?V = null; // If there's already a key here, we need to move aside until there's no more key there while (self.map_buf[kh]) |val| : (kh = (kh + 1) % self.map_buf.len) { if (std.mem.eql(u8, std.mem.asBytes(&val), std.mem.asBytes(&key))) { old = self.value_buf[kh].?; break; } } self.map_buf[kh] = key; self.value_buf[kh] = value; if (old == null) self.load += 1; return old; } /// creates a new internal buffer, and copies the cells over /// resets all other properties such that iterators are invalidated fn rehash(self: *Self, new_size: usize) std.mem.Allocator.Error!void { var nm = try self.alloc.alloc(?K, new_size); errdefer self.alloc.free(nm); var vm = try self.alloc.alloc(?V, new_size); errdefer self.alloc.free(vm); var new = Self{ .seed = self.seed, .alloc = self.alloc, .map_buf = nm, .value_buf = vm, }; for (self.map_buf) |v, i| { if (v) |val| _ = try new.put(val, self.value_buf[i].?); } self.alloc.free(self.map_buf); self.alloc.free(self.value_buf); self.* = new; } /// delete a key from the map /// returns the old value if any existed pub fn delete(self: *Self, key: K) ?V { const old_index = null; const keyBytes = std.mem.asBytes(&key); var kh = std.hash.Murmur2_32ur3_32.hashWithSeed(keyBytes, self.seed) % self.map_buf.len; while (self.map_buf[kh]) |val| : (kh = (kh + 1) % self.map_buf.len) { if (std.mem.eql(u8, std.mem.asBytes(&val), keyBytes)) old_index = kh; } const val = if (old_index != null) self.value_buf[old_index] else return; std.mem.copy(K, self.map_buf[old_index..kh], self.map_buf[old_index + 1 .. kh]); std.mem.copy(K, self.value_buf[old_index..kh], self.value_buf[old_index + 1 .. kh]); self.map_buf[kh] = undefined; self.value_buf[kh] = undefined; self.load -= 1; return val; } /// lookup the index of a key in the map fn lookup(self: *Self, key: K) ?usize { const keyBytes = std.mem.asBytes(&key); var kh = std.hash.Murmur3_32.hashWithSeed(keyBytes, self.seed) % self.map_buf.len; while (self.map_buf[kh]) |val| : (kh = (kh + 1) % self.map_buf.len) { if (std.mem.eql(u8, std.mem.asBytes(&val), keyBytes)) return kh; } return null; } /// get returns the value associated with the key, or null if it doesn't exist pub fn get(self: *Self, key: K) ?V { return if (self.lookup(key)) |i| self.value_buf[i].? else null; } /// next returns the next value in the map /// iteration is unordered. /// if the map grows, the iterator is invalidated pub fn next(self: *Self) ?Cell { if (self.load == 0) return null; if (self.iter_off >= self.map_buf.len) return null; while (self.iter_off < self.map_buf.len) : (self.iter_off += 1) { if (self.map_buf[self.iter_off]) |k| { defer self.iter_off += 1; return Cell{ .key = k, .val = self.value_buf[self.iter_off].? }; } } return null; } /// reset the iterator pub fn reset(self: *Self) void { self.iter_off = 0; } }; } test "fcfs" { if (std.os.getenv("BENCH") == null) return; const op_count = 10000; var map = try FCFS(f32, u32).init(std.testing.allocator); defer map.deinit(); // this should grow the map a few times. var key: f32 = 24.5; var i: u32 = 0; const insert_start_t = std.time.nanoTimestamp(); while (i < op_count) : (i += 1) { _ = try map.put(key, i); key += 0.5; } const insert_end_t = std.time.nanoTimestamp(); var j: usize = 0; const iter_start_t = std.time.nanoTimestamp(); while (map.next()) |_| j += 1; const iter_end_t = std.time.nanoTimestamp(); if (j != i) std.log.err("got {} values expected {}", .{ j, i }); std.debug.print("bench:\n", .{}); std.debug.print( "fcfs insert: {} ns/op\tfcfs iter: {} ns/op\n", .{ @divTrunc(insert_end_t - insert_start_t, @intCast(i128, i)), @divTrunc(iter_end_t - iter_start_t, @intCast(i128, i)), }, ); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const python = @cImport({ @cDefine("_NO_CRT_STDIO_INLINE", "1"); @cDefine("PY_SSIZE_T_CLEAN", {}); @cInclude("Python.h"); }); const TypeInfo = std.builtin.TypeInfo; pub const PyObject = struct { ref: Ptr, const Ptr = [*c]python.PyObject; const Self = @This(); const nullptr = Self{ .ref = null }; fn new(r: Ptr) Self { return Self{ .ref = r }; } pub fn parseTuple(self: Self, comptime T: type) ?T { const info = @typeInfo(T); if (info != .Struct) @compileError("parseTuple expects a struct type"); const fields = info.Struct.fields; comptime var argsFieldList: [fields.len + 2]TypeInfo.StructField = undefined; // TODO: Some types will need to be unpacked into an intermediate variable (e.g. bool -> c_int) // TODO: Some types require multiple characters comptime var fmt: [fields.len + 1]u8 = undefined; comptime { // Input PyObject to parse argsFieldList[0] = TypeInfo.StructField{ .name = "0", .field_type = Ptr, .default_value = null, .is_comptime = false, .alignment = @alignOf([*c]u8), }; // Format string argsFieldList[1] = TypeInfo.StructField{ .name = "1", .field_type = [*c]const u8, .default_value = null, .is_comptime = false, .alignment = @alignOf([*c]u8), }; fmt[fields.len] = 0; inline for (fields) |field, i| { switch (field.field_type) { // TODO: Map standard Zig Int types to c_* types used by Python u8 => fmt[i] = 'B', f32 => fmt[i] = 'f', f64 => fmt[i] = 'd', else => @compileError("Unhandled type" ++ field), } var numBuf: [8]u8 = undefined; argsFieldList[i + 2] = TypeInfo.StructField{ .name = std.fmt.bufPrint(&numBuf, "{d}", .{i + 2}) catch unreachable, .field_type = CPointer(field.field_type), .default_value = null, .is_comptime = false, .alignment = @alignOf([*c]u8), }; } } const Args = @Type(TypeInfo{ .Struct = TypeInfo.Struct{ .is_tuple = true, .layout = .Auto, .decls = &[_]std.builtin.TypeInfo.Declaration{}, .fields = &argsFieldList, }, }); var args: Args = undefined; args[0] = self.ref; args[1] = &fmt[0]; var result: T = undefined; inline for (fields) |field, i| { args[i + 2] = &@field(result, field.name); } if (@call(.{}, python.PyArg_ParseTuple, args) == 0) { return null; } return result; } pub fn parse(self: Self, comptime T: type) ?T { const TupleT = std.meta.Tuple(&[_]type{T}); return if (self.parseTuple(TupleT)) |tuple| tuple[0] else null; } pub fn build(value: anytype) Self { const info = @typeInfo(@TypeOf(value)); const args = switch (@TypeOf(value)) { u8 => .{ "b", value }, f32 => .{ "f", value }, f64 => .{ "d", value }, void => .{""}, else => @compileError("unhandled type" ++ @Type(value)), }; return if (@call(.{}, python.Py_BuildValue, args)) |o| Self.new(o) else Self.nullptr; } }; fn CPointer(comptime T: type) type { return @Type(TypeInfo{ .Pointer = TypeInfo.Pointer{ .size = .C, .is_const = false, .is_volatile = false, .alignment = @alignOf(T), .child = T, .is_allowzero = true, .sentinel = null, } }); } fn makeMethod(comptime Module: anytype, comptime decl: TypeInfo.Declaration) ?python.PyMethodDef { if (!decl.is_pub or decl.data != .Fn) return null; const fnDecl = decl.data.Fn; if (fnDecl.is_var_args) return null; const ArgsTuple = std.meta.ArgsTuple(fnDecl.fn_type); const fnInfo = @typeInfo(fnDecl.fn_type); if (fnInfo != .Fn or fnInfo.Fn.is_generic) return null; const fnWrapper = struct { fn f(self: PyObject.Ptr, args: PyObject.Ptr) callconv(.C) PyObject.Ptr { const fnArgs = PyObject.new(args).parseTuple(ArgsTuple); if (fnArgs == null) { python.PyErr_SetString(python.PyExc_ValueError, "Incorrect function argument types/arity"); return null; } const ret = @call(.{}, @field(Module, decl.name), fnArgs.?); return PyObject.build(ret).ref; } }.f; return python.PyMethodDef{ .ml_name = &decl.name[0], .ml_meth = fnWrapper, .ml_flags = python.METH_VARARGS, // TODO: Generate docstring with argument types .ml_doc = null, }; } pub fn createModule(comptime name: []const u8, comptime Module: anytype) void { const moduleDecls = std.meta.declarations(Module); var i = 0; var pyMethods = [1]python.PyMethodDef{.{ .ml_name = null, .ml_meth = null, .ml_flags = 0, .ml_doc = null }} ** (moduleDecls.len + 1); inline for (moduleDecls) |decl| { if (makeMethod(Module, decl)) |m| { pyMethods[i] = m; i += 1; } } var pyModule = python.PyModuleDef{ .m_base = .{ .ob_base = .{ .ob_refcnt = 1, .ob_type = null, }, .m_init = null, .m_index = 0, .m_copy = null, }, .m_name = &name[0], .m_doc = null, .m_size = -1, .m_methods = &pyMethods[0], .m_slots = null, .m_traverse = null, .m_clear = null, .m_free = null, }; const initFn = struct { fn f() callconv(.C) [*c]python.PyObject { // Leak this copy of `pyModule` // It would be much nicer if this could go in the .data section? var mod_unconst = std.heap.page_allocator.dupe(python.PyModuleDef, &[_]python.PyModuleDef{pyModule}) catch |e| @panic("failed to allocate"); return python.PyModule_Create(&mod_unconst[0]); } }.f; @export(initFn, .{ .name = "PyInit_" ++ name, .linkage = .Strong }); }
src/pymodule.zig
pub const MAX_COUNTER_PATH = @as(u32, 256); pub const PDH_MAX_COUNTER_NAME = @as(u32, 1024); pub const PDH_MAX_INSTANCE_NAME = @as(u32, 1024); pub const PDH_MAX_COUNTER_PATH = @as(u32, 2048); pub const PDH_MAX_DATASOURCE_PATH = @as(u32, 1024); pub const H_WBEM_DATASOURCE = @as(i32, -1); pub const PDH_MAX_SCALE = @as(i32, 7); pub const PDH_MIN_SCALE = @as(i32, -7); pub const PDH_NOEXPANDCOUNTERS = @as(u32, 1); pub const PDH_NOEXPANDINSTANCES = @as(u32, 2); pub const PDH_REFRESHCOUNTERS = @as(u32, 4); pub const PDH_LOG_TYPE_RETIRED_BIN = @as(u32, 3); pub const PDH_LOG_TYPE_TRACE_KERNEL = @as(u32, 4); pub const PDH_LOG_TYPE_TRACE_GENERIC = @as(u32, 5); pub const PERF_PROVIDER_USER_MODE = @as(u32, 0); pub const PERF_PROVIDER_KERNEL_MODE = @as(u32, 1); pub const PERF_PROVIDER_DRIVER = @as(u32, 2); pub const PERF_COUNTERSET_FLAG_MULTIPLE = @as(u32, 2); pub const PERF_COUNTERSET_FLAG_AGGREGATE = @as(u32, 4); pub const PERF_COUNTERSET_FLAG_HISTORY = @as(u32, 8); pub const PERF_COUNTERSET_FLAG_INSTANCE = @as(u32, 16); pub const PERF_COUNTERSET_SINGLE_INSTANCE = @as(u32, 0); pub const PERF_COUNTERSET_MULTI_INSTANCES = @as(u32, 2); pub const PERF_COUNTERSET_SINGLE_AGGREGATE = @as(u32, 4); pub const PERF_AGGREGATE_MAX = @as(u32, 4); pub const PERF_ATTRIB_BY_REFERENCE = @as(u64, 1); pub const PERF_ATTRIB_NO_DISPLAYABLE = @as(u64, 2); pub const PERF_ATTRIB_NO_GROUP_SEPARATOR = @as(u64, 4); pub const PERF_ATTRIB_DISPLAY_AS_REAL = @as(u64, 8); pub const PERF_ATTRIB_DISPLAY_AS_HEX = @as(u64, 16); pub const PERF_WILDCARD_COUNTER = @as(u32, 4294967295); pub const PERF_MAX_INSTANCE_NAME = @as(u32, 1024); pub const PERF_ADD_COUNTER = @as(u32, 1); pub const PERF_REMOVE_COUNTER = @as(u32, 2); pub const PERF_ENUM_INSTANCES = @as(u32, 3); pub const PERF_COLLECT_START = @as(u32, 5); pub const PERF_COLLECT_END = @as(u32, 6); pub const PERF_FILTER = @as(u32, 9); pub const PERF_DATA_VERSION = @as(u32, 1); pub const PERF_DATA_REVISION = @as(u32, 1); pub const PERF_NO_INSTANCES = @as(i32, -1); pub const PERF_METADATA_MULTIPLE_INSTANCES = @as(i32, -2); pub const PERF_METADATA_NO_INSTANCES = @as(i32, -3); pub const PERF_SIZE_DWORD = @as(u32, 0); pub const PERF_SIZE_LARGE = @as(u32, 256); pub const PERF_SIZE_ZERO = @as(u32, 512); pub const PERF_SIZE_VARIABLE_LEN = @as(u32, 768); pub const PERF_TYPE_NUMBER = @as(u32, 0); pub const PERF_TYPE_COUNTER = @as(u32, 1024); pub const PERF_TYPE_TEXT = @as(u32, 2048); pub const PERF_TYPE_ZERO = @as(u32, 3072); pub const PERF_NUMBER_HEX = @as(u32, 0); pub const PERF_NUMBER_DECIMAL = @as(u32, 65536); pub const PERF_NUMBER_DEC_1000 = @as(u32, 131072); pub const PERF_COUNTER_VALUE = @as(u32, 0); pub const PERF_COUNTER_RATE = @as(u32, 65536); pub const PERF_COUNTER_FRACTION = @as(u32, 131072); pub const PERF_COUNTER_BASE = @as(u32, 196608); pub const PERF_COUNTER_ELAPSED = @as(u32, 262144); pub const PERF_COUNTER_QUEUELEN = @as(u32, 327680); pub const PERF_COUNTER_HISTOGRAM = @as(u32, 393216); pub const PERF_COUNTER_PRECISION = @as(u32, 458752); pub const PERF_TEXT_UNICODE = @as(u32, 0); pub const PERF_TEXT_ASCII = @as(u32, 65536); pub const PERF_TIMER_TICK = @as(u32, 0); pub const PERF_TIMER_100NS = @as(u32, 1048576); pub const PERF_OBJECT_TIMER = @as(u32, 2097152); pub const PERF_DELTA_COUNTER = @as(u32, 4194304); pub const PERF_DELTA_BASE = @as(u32, 8388608); pub const PERF_INVERSE_COUNTER = @as(u32, 16777216); pub const PERF_MULTI_COUNTER = @as(u32, 33554432); pub const PERF_DISPLAY_NO_SUFFIX = @as(u32, 0); pub const PERF_DISPLAY_PER_SEC = @as(u32, 268435456); pub const PERF_DISPLAY_PERCENT = @as(u32, 536870912); pub const PERF_DISPLAY_SECONDS = @as(u32, 805306368); pub const PERF_DISPLAY_NOSHOW = @as(u32, 1073741824); pub const PERF_COUNTER_HISTOGRAM_TYPE = @as(u32, 2147483648); pub const PERF_NO_UNIQUE_ID = @as(i32, -1); pub const MAX_PERF_OBJECTS_IN_QUERY_FUNCTION = @as(i32, 64); pub const WINPERF_LOG_NONE = @as(u32, 0); pub const WINPERF_LOG_USER = @as(u32, 1); pub const WINPERF_LOG_DEBUG = @as(u32, 2); pub const WINPERF_LOG_VERBOSE = @as(u32, 3); pub const LIBID_SystemMonitor = Guid.initString("1b773e42-2509-11cf-942f-008029004347"); pub const DIID_DICounterItem = Guid.initString("c08c4ff2-0e2e-11cf-942c-008029004347"); pub const DIID_DILogFileItem = Guid.initString("8d093ffc-f777-4917-82d1-833fbc54c58f"); pub const DIID_DISystemMonitor = Guid.initString("13d73d81-c32e-11cf-9398-00aa00a3ddea"); pub const DIID_DISystemMonitorInternal = Guid.initString("194eb242-c32c-11cf-9398-00aa00a3ddea"); pub const DIID_DISystemMonitorEvents = Guid.initString("84979930-4ab3-11cf-943a-008029004347"); pub const PDH_CSTATUS_VALID_DATA = @as(i32, 0); pub const PDH_CSTATUS_NEW_DATA = @as(i32, 1); pub const PDH_CSTATUS_NO_MACHINE = @as(i32, -2147481648); pub const PDH_CSTATUS_NO_INSTANCE = @as(i32, -2147481647); pub const PDH_MORE_DATA = @as(i32, -2147481646); pub const PDH_CSTATUS_ITEM_NOT_VALIDATED = @as(i32, -2147481645); pub const PDH_RETRY = @as(i32, -2147481644); pub const PDH_NO_DATA = @as(i32, -2147481643); pub const PDH_CALC_NEGATIVE_DENOMINATOR = @as(i32, -2147481642); pub const PDH_CALC_NEGATIVE_TIMEBASE = @as(i32, -2147481641); pub const PDH_CALC_NEGATIVE_VALUE = @as(i32, -2147481640); pub const PDH_DIALOG_CANCELLED = @as(i32, -2147481639); pub const PDH_END_OF_LOG_FILE = @as(i32, -2147481638); pub const PDH_ASYNC_QUERY_TIMEOUT = @as(i32, -2147481637); pub const PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE = @as(i32, -2147481636); pub const PDH_UNABLE_MAP_NAME_FILES = @as(i32, -2147480619); pub const PDH_PLA_VALIDATION_WARNING = @as(i32, -2147480589); pub const PDH_CSTATUS_NO_OBJECT = @as(i32, -1073738824); pub const PDH_CSTATUS_NO_COUNTER = @as(i32, -1073738823); pub const PDH_CSTATUS_INVALID_DATA = @as(i32, -1073738822); pub const PDH_MEMORY_ALLOCATION_FAILURE = @as(i32, -1073738821); pub const PDH_INVALID_HANDLE = @as(i32, -1073738820); pub const PDH_INVALID_ARGUMENT = @as(i32, -1073738819); pub const PDH_FUNCTION_NOT_FOUND = @as(i32, -1073738818); pub const PDH_CSTATUS_NO_COUNTERNAME = @as(i32, -1073738817); pub const PDH_CSTATUS_BAD_COUNTERNAME = @as(i32, -1073738816); pub const PDH_INVALID_BUFFER = @as(i32, -1073738815); pub const PDH_INSUFFICIENT_BUFFER = @as(i32, -1073738814); pub const PDH_CANNOT_CONNECT_MACHINE = @as(i32, -1073738813); pub const PDH_INVALID_PATH = @as(i32, -1073738812); pub const PDH_INVALID_INSTANCE = @as(i32, -1073738811); pub const PDH_INVALID_DATA = @as(i32, -1073738810); pub const PDH_NO_DIALOG_DATA = @as(i32, -1073738809); pub const PDH_CANNOT_READ_NAME_STRINGS = @as(i32, -1073738808); pub const PDH_LOG_FILE_CREATE_ERROR = @as(i32, -1073738807); pub const PDH_LOG_FILE_OPEN_ERROR = @as(i32, -1073738806); pub const PDH_LOG_TYPE_NOT_FOUND = @as(i32, -1073738805); pub const PDH_NO_MORE_DATA = @as(i32, -1073738804); pub const PDH_ENTRY_NOT_IN_LOG_FILE = @as(i32, -1073738803); pub const PDH_DATA_SOURCE_IS_LOG_FILE = @as(i32, -1073738802); pub const PDH_DATA_SOURCE_IS_REAL_TIME = @as(i32, -1073738801); pub const PDH_UNABLE_READ_LOG_HEADER = @as(i32, -1073738800); pub const PDH_FILE_NOT_FOUND = @as(i32, -1073738799); pub const PDH_FILE_ALREADY_EXISTS = @as(i32, -1073738798); pub const PDH_NOT_IMPLEMENTED = @as(i32, -1073738797); pub const PDH_STRING_NOT_FOUND = @as(i32, -1073738796); pub const PDH_UNKNOWN_LOG_FORMAT = @as(i32, -1073738794); pub const PDH_UNKNOWN_LOGSVC_COMMAND = @as(i32, -1073738793); pub const PDH_LOGSVC_QUERY_NOT_FOUND = @as(i32, -1073738792); pub const PDH_LOGSVC_NOT_OPENED = @as(i32, -1073738791); pub const PDH_WBEM_ERROR = @as(i32, -1073738790); pub const PDH_ACCESS_DENIED = @as(i32, -1073738789); pub const PDH_LOG_FILE_TOO_SMALL = @as(i32, -1073738788); pub const PDH_INVALID_DATASOURCE = @as(i32, -1073738787); pub const PDH_INVALID_SQLDB = @as(i32, -1073738786); pub const PDH_NO_COUNTERS = @as(i32, -1073738785); pub const PDH_SQL_ALLOC_FAILED = @as(i32, -1073738784); pub const PDH_SQL_ALLOCCON_FAILED = @as(i32, -1073738783); pub const PDH_SQL_EXEC_DIRECT_FAILED = @as(i32, -1073738782); pub const PDH_SQL_FETCH_FAILED = @as(i32, -1073738781); pub const PDH_SQL_ROWCOUNT_FAILED = @as(i32, -1073738780); pub const PDH_SQL_MORE_RESULTS_FAILED = @as(i32, -1073738779); pub const PDH_SQL_CONNECT_FAILED = @as(i32, -1073738778); pub const PDH_SQL_BIND_FAILED = @as(i32, -1073738777); pub const PDH_CANNOT_CONNECT_WMI_SERVER = @as(i32, -1073738776); pub const PDH_PLA_COLLECTION_ALREADY_RUNNING = @as(i32, -1073738775); pub const PDH_PLA_ERROR_SCHEDULE_OVERLAP = @as(i32, -1073738774); pub const PDH_PLA_COLLECTION_NOT_FOUND = @as(i32, -1073738773); pub const PDH_PLA_ERROR_SCHEDULE_ELAPSED = @as(i32, -1073738772); pub const PDH_PLA_ERROR_NOSTART = @as(i32, -1073738771); pub const PDH_PLA_ERROR_ALREADY_EXISTS = @as(i32, -1073738770); pub const PDH_PLA_ERROR_TYPE_MISMATCH = @as(i32, -1073738769); pub const PDH_PLA_ERROR_FILEPATH = @as(i32, -1073738768); pub const PDH_PLA_SERVICE_ERROR = @as(i32, -1073738767); pub const PDH_PLA_VALIDATION_ERROR = @as(i32, -1073738766); pub const PDH_PLA_ERROR_NAME_TOO_LONG = @as(i32, -1073738764); pub const PDH_INVALID_SQL_LOG_FORMAT = @as(i32, -1073738763); pub const PDH_COUNTER_ALREADY_IN_QUERY = @as(i32, -1073738762); pub const PDH_BINARY_LOG_CORRUPT = @as(i32, -1073738761); pub const PDH_LOG_SAMPLE_TOO_SMALL = @as(i32, -1073738760); pub const PDH_OS_LATER_VERSION = @as(i32, -1073738759); pub const PDH_OS_EARLIER_VERSION = @as(i32, -1073738758); pub const PDH_INCORRECT_APPEND_TIME = @as(i32, -1073738757); pub const PDH_UNMATCHED_APPEND_COUNTER = @as(i32, -1073738756); pub const PDH_SQL_ALTER_DETAIL_FAILED = @as(i32, -1073738755); pub const PDH_QUERY_PERF_DATA_TIMEOUT = @as(i32, -1073738754); pub const PLA_CAPABILITY_LOCAL = @as(u32, 268435456); pub const PLA_CAPABILITY_V1_SVC = @as(u32, 1); pub const PLA_CAPABILITY_V1_SESSION = @as(u32, 2); pub const PLA_CAPABILITY_V1_SYSTEM = @as(u32, 4); pub const PLA_CAPABILITY_LEGACY_SESSION = @as(u32, 8); pub const PLA_CAPABILITY_LEGACY_SVC = @as(u32, 16); pub const PLA_CAPABILITY_AUTOLOGGER = @as(u32, 32); pub const S_PDH = Guid.initString("04d66358-c4a1-419b-8023-23b73902de2c"); //-------------------------------------------------------------------------------- // Section: Types (144) //-------------------------------------------------------------------------------- pub const PERF_DETAIL = enum(u32) { NOVICE = 100, ADVANCED = 200, EXPERT = 300, WIZARD = 400, }; pub const PERF_DETAIL_NOVICE = PERF_DETAIL.NOVICE; pub const PERF_DETAIL_ADVANCED = PERF_DETAIL.ADVANCED; pub const PERF_DETAIL_EXPERT = PERF_DETAIL.EXPERT; pub const PERF_DETAIL_WIZARD = PERF_DETAIL.WIZARD; pub const REAL_TIME_DATA_SOURCE_ID_FLAGS = enum(u32) { REGISTRY = 1, WBEM = 4, }; pub const DATA_SOURCE_REGISTRY = REAL_TIME_DATA_SOURCE_ID_FLAGS.REGISTRY; pub const DATA_SOURCE_WBEM = REAL_TIME_DATA_SOURCE_ID_FLAGS.WBEM; pub const PDH_PATH_FLAGS = enum(u32) { RESULT = 1, INPUT = 2, NONE = 0, }; pub const PDH_PATH_WBEM_RESULT = PDH_PATH_FLAGS.RESULT; pub const PDH_PATH_WBEM_INPUT = PDH_PATH_FLAGS.INPUT; pub const PDH_PATH_WBEM_NONE = PDH_PATH_FLAGS.NONE; pub const PDH_FMT = enum(u32) { DOUBLE = 512, LARGE = 1024, LONG = 256, }; pub const PDH_FMT_DOUBLE = PDH_FMT.DOUBLE; pub const PDH_FMT_LARGE = PDH_FMT.LARGE; pub const PDH_FMT_LONG = PDH_FMT.LONG; pub const PDH_LOG_TYPE = enum(u32) { UNDEFINED = 0, CSV = 1, SQL = 7, TSV = 2, BINARY = 8, PERFMON = 6, }; pub const PDH_LOG_TYPE_UNDEFINED = PDH_LOG_TYPE.UNDEFINED; pub const PDH_LOG_TYPE_CSV = PDH_LOG_TYPE.CSV; pub const PDH_LOG_TYPE_SQL = PDH_LOG_TYPE.SQL; pub const PDH_LOG_TYPE_TSV = PDH_LOG_TYPE.TSV; pub const PDH_LOG_TYPE_BINARY = PDH_LOG_TYPE.BINARY; pub const PDH_LOG_TYPE_PERFMON = PDH_LOG_TYPE.PERFMON; pub const PDH_LOG = enum(u32) { READ_ACCESS = 65536, WRITE_ACCESS = 131072, UPDATE_ACCESS = 262144, }; pub const PDH_LOG_READ_ACCESS = PDH_LOG.READ_ACCESS; pub const PDH_LOG_WRITE_ACCESS = PDH_LOG.WRITE_ACCESS; pub const PDH_LOG_UPDATE_ACCESS = PDH_LOG.UPDATE_ACCESS; pub const PDH_SELECT_DATA_SOURCE_FLAGS = enum(u32) { FILE_BROWSER_ONLY = 1, NONE = 0, }; pub const PDH_FLAGS_FILE_BROWSER_ONLY = PDH_SELECT_DATA_SOURCE_FLAGS.FILE_BROWSER_ONLY; pub const PDH_FLAGS_NONE = PDH_SELECT_DATA_SOURCE_FLAGS.NONE; pub const PDH_DLL_VERSION = enum(u32) { CVERSION_WIN50 = 1280, VERSION = 1283, }; pub const PDH_CVERSION_WIN50 = PDH_DLL_VERSION.CVERSION_WIN50; pub const PDH_VERSION = PDH_DLL_VERSION.VERSION; pub const PERF_COUNTER_AGGREGATE_FUNC = enum(u32) { UNDEFINED = 0, TOTAL = 1, AVG = 2, MIN = 3, }; pub const PERF_AGGREGATE_UNDEFINED = PERF_COUNTER_AGGREGATE_FUNC.UNDEFINED; pub const PERF_AGGREGATE_TOTAL = PERF_COUNTER_AGGREGATE_FUNC.TOTAL; pub const PERF_AGGREGATE_AVG = PERF_COUNTER_AGGREGATE_FUNC.AVG; pub const PERF_AGGREGATE_MIN = PERF_COUNTER_AGGREGATE_FUNC.MIN; // TODO: this type has a FreeFunc 'PerfStopProvider', what can Zig do with this information? pub const PerfProviderHandle = isize; // TODO: this type has a FreeFunc 'PerfCloseQueryHandle', what can Zig do with this information? pub const PerfQueryHandle = isize; const CLSID_DataCollectorSet_Value = Guid.initString("03837521-098b-11d8-9414-505054503030"); pub const CLSID_DataCollectorSet = &CLSID_DataCollectorSet_Value; const CLSID_TraceSession_Value = Guid.initString("0383751c-098b-11d8-9414-505054503030"); pub const CLSID_TraceSession = &CLSID_TraceSession_Value; const CLSID_TraceSessionCollection_Value = Guid.initString("03837530-098b-11d8-9414-505054503030"); pub const CLSID_TraceSessionCollection = &CLSID_TraceSessionCollection_Value; const CLSID_TraceDataProvider_Value = Guid.initString("03837513-098b-11d8-9414-505054503030"); pub const CLSID_TraceDataProvider = &CLSID_TraceDataProvider_Value; const CLSID_TraceDataProviderCollection_Value = Guid.initString("03837511-098b-11d8-9414-505054503030"); pub const CLSID_TraceDataProviderCollection = &CLSID_TraceDataProviderCollection_Value; const CLSID_DataCollectorSetCollection_Value = Guid.initString("03837525-098b-11d8-9414-505054503030"); pub const CLSID_DataCollectorSetCollection = &CLSID_DataCollectorSetCollection_Value; const CLSID_LegacyDataCollectorSet_Value = Guid.initString("03837526-098b-11d8-9414-505054503030"); pub const CLSID_LegacyDataCollectorSet = &CLSID_LegacyDataCollectorSet_Value; const CLSID_LegacyDataCollectorSetCollection_Value = Guid.initString("03837527-098b-11d8-9414-505054503030"); pub const CLSID_LegacyDataCollectorSetCollection = &CLSID_LegacyDataCollectorSetCollection_Value; const CLSID_LegacyTraceSession_Value = Guid.initString("03837528-098b-11d8-9414-505054503030"); pub const CLSID_LegacyTraceSession = &CLSID_LegacyTraceSession_Value; const CLSID_LegacyTraceSessionCollection_Value = Guid.initString("03837529-098b-11d8-9414-505054503030"); pub const CLSID_LegacyTraceSessionCollection = &CLSID_LegacyTraceSessionCollection_Value; const CLSID_ServerDataCollectorSet_Value = Guid.initString("03837531-098b-11d8-9414-505054503030"); pub const CLSID_ServerDataCollectorSet = &CLSID_ServerDataCollectorSet_Value; const CLSID_ServerDataCollectorSetCollection_Value = Guid.initString("03837532-098b-11d8-9414-505054503030"); pub const CLSID_ServerDataCollectorSetCollection = &CLSID_ServerDataCollectorSetCollection_Value; const CLSID_SystemDataCollectorSet_Value = Guid.initString("03837546-098b-11d8-9414-505054503030"); pub const CLSID_SystemDataCollectorSet = &CLSID_SystemDataCollectorSet_Value; const CLSID_SystemDataCollectorSetCollection_Value = Guid.initString("03837547-098b-11d8-9414-505054503030"); pub const CLSID_SystemDataCollectorSetCollection = &CLSID_SystemDataCollectorSetCollection_Value; const CLSID_BootTraceSession_Value = Guid.initString("03837538-098b-11d8-9414-505054503030"); pub const CLSID_BootTraceSession = &CLSID_BootTraceSession_Value; const CLSID_BootTraceSessionCollection_Value = Guid.initString("03837539-098b-11d8-9414-505054503030"); pub const CLSID_BootTraceSessionCollection = &CLSID_BootTraceSessionCollection_Value; pub const DataCollectorType = enum(i32) { PerformanceCounter = 0, Trace = 1, Configuration = 2, Alert = 3, ApiTrace = 4, }; pub const plaPerformanceCounter = DataCollectorType.PerformanceCounter; pub const plaTrace = DataCollectorType.Trace; pub const plaConfiguration = DataCollectorType.Configuration; pub const plaAlert = DataCollectorType.Alert; pub const plaApiTrace = DataCollectorType.ApiTrace; pub const FileFormat = enum(i32) { CommaSeparated = 0, TabSeparated = 1, Sql = 2, Binary = 3, }; pub const plaCommaSeparated = FileFormat.CommaSeparated; pub const plaTabSeparated = FileFormat.TabSeparated; pub const plaSql = FileFormat.Sql; pub const plaBinary = FileFormat.Binary; pub const AutoPathFormat = enum(i32) { None = 0, Pattern = 1, Computer = 2, MonthDayHour = 256, SerialNumber = 512, YearDayOfYear = 1024, YearMonth = 2048, YearMonthDay = 4096, YearMonthDayHour = 8192, MonthDayHourMinute = 16384, }; pub const plaNone = AutoPathFormat.None; pub const plaPattern = AutoPathFormat.Pattern; pub const plaComputer = AutoPathFormat.Computer; pub const plaMonthDayHour = AutoPathFormat.MonthDayHour; pub const plaSerialNumber = AutoPathFormat.SerialNumber; pub const plaYearDayOfYear = AutoPathFormat.YearDayOfYear; pub const plaYearMonth = AutoPathFormat.YearMonth; pub const plaYearMonthDay = AutoPathFormat.YearMonthDay; pub const plaYearMonthDayHour = AutoPathFormat.YearMonthDayHour; pub const plaMonthDayHourMinute = AutoPathFormat.MonthDayHourMinute; pub const DataCollectorSetStatus = enum(i32) { Stopped = 0, Running = 1, Compiling = 2, Pending = 3, Undefined = 4, }; pub const plaStopped = DataCollectorSetStatus.Stopped; pub const plaRunning = DataCollectorSetStatus.Running; pub const plaCompiling = DataCollectorSetStatus.Compiling; pub const plaPending = DataCollectorSetStatus.Pending; pub const plaUndefined = DataCollectorSetStatus.Undefined; pub const ClockType = enum(i32) { TimeStamp = 0, Performance = 1, System = 2, Cycle = 3, }; pub const plaTimeStamp = ClockType.TimeStamp; pub const plaPerformance = ClockType.Performance; pub const plaSystem = ClockType.System; pub const plaCycle = ClockType.Cycle; pub const StreamMode = enum(i32) { File = 1, RealTime = 2, Both = 3, Buffering = 4, }; pub const plaFile = StreamMode.File; pub const plaRealTime = StreamMode.RealTime; pub const plaBoth = StreamMode.Both; pub const plaBuffering = StreamMode.Buffering; pub const CommitMode = enum(i32) { CreateNew = 1, Modify = 2, CreateOrModify = 3, UpdateRunningInstance = 16, FlushTrace = 32, ValidateOnly = 4096, }; pub const plaCreateNew = CommitMode.CreateNew; pub const plaModify = CommitMode.Modify; pub const plaCreateOrModify = CommitMode.CreateOrModify; pub const plaUpdateRunningInstance = CommitMode.UpdateRunningInstance; pub const plaFlushTrace = CommitMode.FlushTrace; pub const plaValidateOnly = CommitMode.ValidateOnly; pub const ValueMapType = enum(i32) { Index = 1, Flag = 2, FlagArray = 3, Validation = 4, }; pub const plaIndex = ValueMapType.Index; pub const plaFlag = ValueMapType.Flag; pub const plaFlagArray = ValueMapType.FlagArray; pub const plaValidation = ValueMapType.Validation; pub const WeekDays = enum(i32) { RunOnce = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Everyday = 127, }; pub const plaRunOnce = WeekDays.RunOnce; pub const plaSunday = WeekDays.Sunday; pub const plaMonday = WeekDays.Monday; pub const plaTuesday = WeekDays.Tuesday; pub const plaWednesday = WeekDays.Wednesday; pub const plaThursday = WeekDays.Thursday; pub const plaFriday = WeekDays.Friday; pub const plaSaturday = WeekDays.Saturday; pub const plaEveryday = WeekDays.Everyday; pub const ResourcePolicy = enum(i32) { Largest = 0, Oldest = 1, }; pub const plaDeleteLargest = ResourcePolicy.Largest; pub const plaDeleteOldest = ResourcePolicy.Oldest; pub const DataManagerSteps = enum(i32) { CreateReport = 1, RunRules = 2, CreateHtml = 4, FolderActions = 8, ResourceFreeing = 16, }; pub const plaCreateReport = DataManagerSteps.CreateReport; pub const plaRunRules = DataManagerSteps.RunRules; pub const plaCreateHtml = DataManagerSteps.CreateHtml; pub const plaFolderActions = DataManagerSteps.FolderActions; pub const plaResourceFreeing = DataManagerSteps.ResourceFreeing; pub const FolderActionSteps = enum(i32) { CreateCab = 1, DeleteData = 2, SendCab = 4, DeleteCab = 8, DeleteReport = 16, }; pub const plaCreateCab = FolderActionSteps.CreateCab; pub const plaDeleteData = FolderActionSteps.DeleteData; pub const plaSendCab = FolderActionSteps.SendCab; pub const plaDeleteCab = FolderActionSteps.DeleteCab; pub const plaDeleteReport = FolderActionSteps.DeleteReport; pub const PLA_CABEXTRACT_CALLBACK = fn( FileName: ?[*:0]const u16, Context: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDataCollectorSet_Value = Guid.initString("03837520-098b-11d8-9414-505054503030"); pub const IID_IDataCollectorSet = &IID_IDataCollectorSet_Value; pub const IDataCollectorSet = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataCollectors: fn( self: *const IDataCollectorSet, collectors: ?*?*IDataCollectorCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Duration: fn( self: *const IDataCollectorSet, seconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Duration: fn( self: *const IDataCollectorSet, seconds: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IDataCollectorSet, description: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IDataCollectorSet, description: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DescriptionUnresolved: fn( self: *const IDataCollectorSet, Descr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IDataCollectorSet, DisplayName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayName: fn( self: *const IDataCollectorSet, DisplayName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayNameUnresolved: fn( self: *const IDataCollectorSet, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Keywords: fn( self: *const IDataCollectorSet, keywords: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Keywords: fn( self: *const IDataCollectorSet, keywords: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LatestOutputLocation: fn( self: *const IDataCollectorSet, path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LatestOutputLocation: fn( self: *const IDataCollectorSet, path: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IDataCollectorSet, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OutputLocation: fn( self: *const IDataCollectorSet, path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RootPath: fn( self: *const IDataCollectorSet, folder: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RootPath: fn( self: *const IDataCollectorSet, folder: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Segment: fn( self: *const IDataCollectorSet, segment: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Segment: fn( self: *const IDataCollectorSet, segment: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SegmentMaxDuration: fn( self: *const IDataCollectorSet, seconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SegmentMaxDuration: fn( self: *const IDataCollectorSet, seconds: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SegmentMaxSize: fn( self: *const IDataCollectorSet, size: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SegmentMaxSize: fn( self: *const IDataCollectorSet, size: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SerialNumber: fn( self: *const IDataCollectorSet, index: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SerialNumber: fn( self: *const IDataCollectorSet, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Server: fn( self: *const IDataCollectorSet, server: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IDataCollectorSet, status: ?*DataCollectorSetStatus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Subdirectory: fn( self: *const IDataCollectorSet, folder: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Subdirectory: fn( self: *const IDataCollectorSet, folder: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubdirectoryFormat: fn( self: *const IDataCollectorSet, format: ?*AutoPathFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubdirectoryFormat: fn( self: *const IDataCollectorSet, format: AutoPathFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubdirectoryFormatPattern: fn( self: *const IDataCollectorSet, pattern: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubdirectoryFormatPattern: fn( self: *const IDataCollectorSet, pattern: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Task: fn( self: *const IDataCollectorSet, task: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Task: fn( self: *const IDataCollectorSet, task: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskRunAsSelf: fn( self: *const IDataCollectorSet, RunAsSelf: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskRunAsSelf: fn( self: *const IDataCollectorSet, RunAsSelf: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskArguments: fn( self: *const IDataCollectorSet, task: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskArguments: fn( self: *const IDataCollectorSet, task: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskUserTextArguments: fn( self: *const IDataCollectorSet, UserText: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskUserTextArguments: fn( self: *const IDataCollectorSet, UserText: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Schedules: fn( self: *const IDataCollectorSet, ppSchedules: ?*?*IScheduleCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SchedulesEnabled: fn( self: *const IDataCollectorSet, enabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SchedulesEnabled: fn( self: *const IDataCollectorSet, enabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserAccount: fn( self: *const IDataCollectorSet, user: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Xml: fn( self: *const IDataCollectorSet, xml: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Security: fn( self: *const IDataCollectorSet, pbstrSecurity: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Security: fn( self: *const IDataCollectorSet, bstrSecurity: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StopOnCompletion: fn( self: *const IDataCollectorSet, Stop: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StopOnCompletion: fn( self: *const IDataCollectorSet, Stop: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataManager: fn( self: *const IDataCollectorSet, DataManager: ?*?*IDataManager, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCredentials: fn( self: *const IDataCollectorSet, user: ?BSTR, password: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Query: fn( self: *const IDataCollectorSet, name: ?BSTR, server: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const IDataCollectorSet, name: ?BSTR, server: ?BSTR, mode: CommitMode, validation: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IDataCollectorSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Start: fn( self: *const IDataCollectorSet, Synchronous: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IDataCollectorSet, Synchronous: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetXml: fn( self: *const IDataCollectorSet, xml: ?BSTR, validation: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetValue: fn( self: *const IDataCollectorSet, key: ?BSTR, value: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const IDataCollectorSet, key: ?BSTR, value: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_DataCollectors(self: *const T, collectors: ?*?*IDataCollectorCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DataCollectors(@ptrCast(*const IDataCollectorSet, self), collectors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Duration(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Duration(@ptrCast(*const IDataCollectorSet, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Duration(self: *const T, seconds: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Duration(@ptrCast(*const IDataCollectorSet, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Description(@ptrCast(*const IDataCollectorSet, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Description(@ptrCast(*const IDataCollectorSet, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_DescriptionUnresolved(self: *const T, Descr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DescriptionUnresolved(@ptrCast(*const IDataCollectorSet, self), Descr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_DisplayName(self: *const T, DisplayName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DisplayName(@ptrCast(*const IDataCollectorSet, self), DisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_DisplayName(self: *const T, DisplayName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_DisplayName(@ptrCast(*const IDataCollectorSet, self), DisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_DisplayNameUnresolved(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DisplayNameUnresolved(@ptrCast(*const IDataCollectorSet, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Keywords(self: *const T, keywords: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Keywords(@ptrCast(*const IDataCollectorSet, self), keywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Keywords(self: *const T, keywords: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Keywords(@ptrCast(*const IDataCollectorSet, self), keywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_LatestOutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_LatestOutputLocation(@ptrCast(*const IDataCollectorSet, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_LatestOutputLocation(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_LatestOutputLocation(@ptrCast(*const IDataCollectorSet, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Name(@ptrCast(*const IDataCollectorSet, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_OutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_OutputLocation(@ptrCast(*const IDataCollectorSet, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_RootPath(self: *const T, folder: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_RootPath(@ptrCast(*const IDataCollectorSet, self), folder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_RootPath(self: *const T, folder: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_RootPath(@ptrCast(*const IDataCollectorSet, self), folder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Segment(self: *const T, segment: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Segment(@ptrCast(*const IDataCollectorSet, self), segment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Segment(self: *const T, segment: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Segment(@ptrCast(*const IDataCollectorSet, self), segment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SegmentMaxDuration(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SegmentMaxDuration(@ptrCast(*const IDataCollectorSet, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SegmentMaxDuration(self: *const T, seconds: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SegmentMaxDuration(@ptrCast(*const IDataCollectorSet, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SegmentMaxSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SegmentMaxSize(@ptrCast(*const IDataCollectorSet, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SegmentMaxSize(self: *const T, size: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SegmentMaxSize(@ptrCast(*const IDataCollectorSet, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SerialNumber(self: *const T, index: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SerialNumber(@ptrCast(*const IDataCollectorSet, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SerialNumber(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SerialNumber(@ptrCast(*const IDataCollectorSet, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Server(self: *const T, server: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Server(@ptrCast(*const IDataCollectorSet, self), server); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Status(self: *const T, status: ?*DataCollectorSetStatus) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Status(@ptrCast(*const IDataCollectorSet, self), status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Subdirectory(self: *const T, folder: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Subdirectory(@ptrCast(*const IDataCollectorSet, self), folder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Subdirectory(self: *const T, folder: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Subdirectory(@ptrCast(*const IDataCollectorSet, self), folder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SubdirectoryFormat(self: *const T, format: ?*AutoPathFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SubdirectoryFormat(@ptrCast(*const IDataCollectorSet, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SubdirectoryFormat(self: *const T, format: AutoPathFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SubdirectoryFormat(@ptrCast(*const IDataCollectorSet, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SubdirectoryFormatPattern(self: *const T, pattern: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SubdirectoryFormatPattern(@ptrCast(*const IDataCollectorSet, self), pattern); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SubdirectoryFormatPattern(self: *const T, pattern: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SubdirectoryFormatPattern(@ptrCast(*const IDataCollectorSet, self), pattern); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Task(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Task(@ptrCast(*const IDataCollectorSet, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Task(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Task(@ptrCast(*const IDataCollectorSet, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_TaskRunAsSelf(self: *const T, RunAsSelf: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskRunAsSelf(@ptrCast(*const IDataCollectorSet, self), RunAsSelf); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_TaskRunAsSelf(self: *const T, RunAsSelf: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskRunAsSelf(@ptrCast(*const IDataCollectorSet, self), RunAsSelf); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_TaskArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskArguments(@ptrCast(*const IDataCollectorSet, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_TaskArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskArguments(@ptrCast(*const IDataCollectorSet, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_TaskUserTextArguments(self: *const T, UserText: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskUserTextArguments(@ptrCast(*const IDataCollectorSet, self), UserText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_TaskUserTextArguments(self: *const T, UserText: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskUserTextArguments(@ptrCast(*const IDataCollectorSet, self), UserText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Schedules(self: *const T, ppSchedules: ?*?*IScheduleCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Schedules(@ptrCast(*const IDataCollectorSet, self), ppSchedules); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_SchedulesEnabled(self: *const T, enabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SchedulesEnabled(@ptrCast(*const IDataCollectorSet, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_SchedulesEnabled(self: *const T, enabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SchedulesEnabled(@ptrCast(*const IDataCollectorSet, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_UserAccount(self: *const T, user: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_UserAccount(@ptrCast(*const IDataCollectorSet, self), user); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Xml(self: *const T, xml: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Xml(@ptrCast(*const IDataCollectorSet, self), xml); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_Security(self: *const T, pbstrSecurity: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Security(@ptrCast(*const IDataCollectorSet, self), pbstrSecurity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_Security(self: *const T, bstrSecurity: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Security(@ptrCast(*const IDataCollectorSet, self), bstrSecurity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_StopOnCompletion(self: *const T, Stop: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_StopOnCompletion(@ptrCast(*const IDataCollectorSet, self), Stop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_put_StopOnCompletion(self: *const T, Stop: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_StopOnCompletion(@ptrCast(*const IDataCollectorSet, self), Stop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_get_DataManager(self: *const T, DataManager: ?*?*IDataManager) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DataManager(@ptrCast(*const IDataCollectorSet, self), DataManager); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_SetCredentials(self: *const T, user: ?BSTR, password: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetCredentials(@ptrCast(*const IDataCollectorSet, self), user, password); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_Query(self: *const T, name: ?BSTR, server: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Query(@ptrCast(*const IDataCollectorSet, self), name, server); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_Commit(self: *const T, name: ?BSTR, server: ?BSTR, mode: CommitMode, validation: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Commit(@ptrCast(*const IDataCollectorSet, self), name, server, mode, validation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_Delete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Delete(@ptrCast(*const IDataCollectorSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_Start(self: *const T, Synchronous: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Start(@ptrCast(*const IDataCollectorSet, self), Synchronous); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_Stop(self: *const T, Synchronous: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Stop(@ptrCast(*const IDataCollectorSet, self), Synchronous); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_SetXml(self: *const T, xml: ?BSTR, validation: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetXml(@ptrCast(*const IDataCollectorSet, self), xml, validation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_SetValue(self: *const T, key: ?BSTR, value: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetValue(@ptrCast(*const IDataCollectorSet, self), key, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSet_GetValue(self: *const T, key: ?BSTR, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).GetValue(@ptrCast(*const IDataCollectorSet, self), key, value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDataManager_Value = Guid.initString("03837541-098b-11d8-9414-505054503030"); pub const IID_IDataManager = &IID_IDataManager_Value; pub const IDataManager = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const IDataManager, pfEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enabled: fn( self: *const IDataManager, fEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CheckBeforeRunning: fn( self: *const IDataManager, pfCheck: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CheckBeforeRunning: fn( self: *const IDataManager, fCheck: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinFreeDisk: fn( self: *const IDataManager, MinFreeDisk: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinFreeDisk: fn( self: *const IDataManager, MinFreeDisk: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxSize: fn( self: *const IDataManager, pulMaxSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxSize: fn( self: *const IDataManager, ulMaxSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxFolderCount: fn( self: *const IDataManager, pulMaxFolderCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxFolderCount: fn( self: *const IDataManager, ulMaxFolderCount: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ResourcePolicy: fn( self: *const IDataManager, pPolicy: ?*ResourcePolicy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ResourcePolicy: fn( self: *const IDataManager, Policy: ResourcePolicy, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FolderActions: fn( self: *const IDataManager, Actions: ?*?*IFolderActionCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportSchema: fn( self: *const IDataManager, ReportSchema: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportSchema: fn( self: *const IDataManager, ReportSchema: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportFileName: fn( self: *const IDataManager, pbstrFilename: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportFileName: fn( self: *const IDataManager, pbstrFilename: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RuleTargetFileName: fn( self: *const IDataManager, Filename: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RuleTargetFileName: fn( self: *const IDataManager, Filename: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventsFileName: fn( self: *const IDataManager, pbstrFilename: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventsFileName: fn( self: *const IDataManager, pbstrFilename: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Rules: fn( self: *const IDataManager, pbstrXml: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Rules: fn( self: *const IDataManager, bstrXml: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Run: fn( self: *const IDataManager, Steps: DataManagerSteps, bstrFolder: ?BSTR, Errors: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Extract: fn( self: *const IDataManager, CabFilename: ?BSTR, DestinationPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_Enabled(self: *const T, pfEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_Enabled(@ptrCast(*const IDataManager, self), pfEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_Enabled(self: *const T, fEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_Enabled(@ptrCast(*const IDataManager, self), fEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_CheckBeforeRunning(self: *const T, pfCheck: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_CheckBeforeRunning(@ptrCast(*const IDataManager, self), pfCheck); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_CheckBeforeRunning(self: *const T, fCheck: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_CheckBeforeRunning(@ptrCast(*const IDataManager, self), fCheck); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_MinFreeDisk(self: *const T, MinFreeDisk: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_MinFreeDisk(@ptrCast(*const IDataManager, self), MinFreeDisk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_MinFreeDisk(self: *const T, MinFreeDisk: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_MinFreeDisk(@ptrCast(*const IDataManager, self), MinFreeDisk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_MaxSize(self: *const T, pulMaxSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_MaxSize(@ptrCast(*const IDataManager, self), pulMaxSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_MaxSize(self: *const T, ulMaxSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_MaxSize(@ptrCast(*const IDataManager, self), ulMaxSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_MaxFolderCount(self: *const T, pulMaxFolderCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_MaxFolderCount(@ptrCast(*const IDataManager, self), pulMaxFolderCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_MaxFolderCount(self: *const T, ulMaxFolderCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_MaxFolderCount(@ptrCast(*const IDataManager, self), ulMaxFolderCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_ResourcePolicy(self: *const T, pPolicy: ?*ResourcePolicy) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_ResourcePolicy(@ptrCast(*const IDataManager, self), pPolicy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_ResourcePolicy(self: *const T, Policy: ResourcePolicy) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_ResourcePolicy(@ptrCast(*const IDataManager, self), Policy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_FolderActions(self: *const T, Actions: ?*?*IFolderActionCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_FolderActions(@ptrCast(*const IDataManager, self), Actions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_ReportSchema(self: *const T, ReportSchema: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_ReportSchema(@ptrCast(*const IDataManager, self), ReportSchema); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_ReportSchema(self: *const T, ReportSchema: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_ReportSchema(@ptrCast(*const IDataManager, self), ReportSchema); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_ReportFileName(self: *const T, pbstrFilename: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_ReportFileName(@ptrCast(*const IDataManager, self), pbstrFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_ReportFileName(self: *const T, pbstrFilename: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_ReportFileName(@ptrCast(*const IDataManager, self), pbstrFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_RuleTargetFileName(self: *const T, Filename: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_RuleTargetFileName(@ptrCast(*const IDataManager, self), Filename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_RuleTargetFileName(self: *const T, Filename: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_RuleTargetFileName(@ptrCast(*const IDataManager, self), Filename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_EventsFileName(self: *const T, pbstrFilename: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_EventsFileName(@ptrCast(*const IDataManager, self), pbstrFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_EventsFileName(self: *const T, pbstrFilename: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_EventsFileName(@ptrCast(*const IDataManager, self), pbstrFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_get_Rules(self: *const T, pbstrXml: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).get_Rules(@ptrCast(*const IDataManager, self), pbstrXml); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_put_Rules(self: *const T, bstrXml: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).put_Rules(@ptrCast(*const IDataManager, self), bstrXml); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_Run(self: *const T, Steps: DataManagerSteps, bstrFolder: ?BSTR, Errors: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).Run(@ptrCast(*const IDataManager, self), Steps, bstrFolder, Errors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataManager_Extract(self: *const T, CabFilename: ?BSTR, DestinationPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataManager.VTable, self.vtable).Extract(@ptrCast(*const IDataManager, self), CabFilename, DestinationPath); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFolderAction_Value = Guid.initString("03837543-098b-11d8-9414-505054503030"); pub const IID_IFolderAction = &IID_IFolderAction_Value; pub const IFolderAction = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Age: fn( self: *const IFolderAction, pulAge: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Age: fn( self: *const IFolderAction, ulAge: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Size: fn( self: *const IFolderAction, pulAge: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Size: fn( self: *const IFolderAction, ulAge: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Actions: fn( self: *const IFolderAction, Steps: ?*FolderActionSteps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Actions: fn( self: *const IFolderAction, Steps: FolderActionSteps, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SendCabTo: fn( self: *const IFolderAction, pbstrDestination: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SendCabTo: fn( self: *const IFolderAction, bstrDestination: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_get_Age(self: *const T, pulAge: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Age(@ptrCast(*const IFolderAction, self), pulAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_put_Age(self: *const T, ulAge: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Age(@ptrCast(*const IFolderAction, self), ulAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_get_Size(self: *const T, pulAge: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Size(@ptrCast(*const IFolderAction, self), pulAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_put_Size(self: *const T, ulAge: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Size(@ptrCast(*const IFolderAction, self), ulAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_get_Actions(self: *const T, Steps: ?*FolderActionSteps) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Actions(@ptrCast(*const IFolderAction, self), Steps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_put_Actions(self: *const T, Steps: FolderActionSteps) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Actions(@ptrCast(*const IFolderAction, self), Steps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_get_SendCabTo(self: *const T, pbstrDestination: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).get_SendCabTo(@ptrCast(*const IFolderAction, self), pbstrDestination); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderAction_put_SendCabTo(self: *const T, bstrDestination: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderAction.VTable, self.vtable).put_SendCabTo(@ptrCast(*const IFolderAction, self), bstrDestination); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IFolderActionCollection_Value = Guid.initString("03837544-098b-11d8-9414-505054503030"); pub const IID_IFolderActionCollection = &IID_IFolderActionCollection_Value; pub const IFolderActionCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IFolderActionCollection, Count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IFolderActionCollection, Index: VARIANT, Action: ?*?*IFolderAction, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IFolderActionCollection, Enum: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IFolderActionCollection, Action: ?*IFolderAction, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IFolderActionCollection, Index: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IFolderActionCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const IFolderActionCollection, Actions: ?*IFolderActionCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFolderAction: fn( self: *const IFolderActionCollection, FolderAction: ?*?*IFolderAction, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_get_Count(self: *const T, Count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get_Count(@ptrCast(*const IFolderActionCollection, self), Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_get_Item(self: *const T, Index: VARIANT, Action: ?*?*IFolderAction) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get_Item(@ptrCast(*const IFolderActionCollection, self), Index, Action); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_get__NewEnum(self: *const T, Enum: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IFolderActionCollection, self), Enum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_Add(self: *const T, Action: ?*IFolderAction) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Add(@ptrCast(*const IFolderActionCollection, self), Action); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_Remove(self: *const T, Index: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Remove(@ptrCast(*const IFolderActionCollection, self), Index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Clear(@ptrCast(*const IFolderActionCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_AddRange(self: *const T, Actions: ?*IFolderActionCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).AddRange(@ptrCast(*const IFolderActionCollection, self), Actions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IFolderActionCollection_CreateFolderAction(self: *const T, FolderAction: ?*?*IFolderAction) callconv(.Inline) HRESULT { return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).CreateFolderAction(@ptrCast(*const IFolderActionCollection, self), FolderAction); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDataCollector_Value = Guid.initString("038374ff-098b-11d8-9414-505054503030"); pub const IID_IDataCollector = &IID_IDataCollector_Value; pub const IDataCollector = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataCollectorSet: fn( self: *const IDataCollector, group: ?*?*IDataCollectorSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataCollectorSet: fn( self: *const IDataCollector, group: ?*IDataCollectorSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataCollectorType: fn( self: *const IDataCollector, type: ?*DataCollectorType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileName: fn( self: *const IDataCollector, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileName: fn( self: *const IDataCollector, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileNameFormat: fn( self: *const IDataCollector, format: ?*AutoPathFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileNameFormat: fn( self: *const IDataCollector, format: AutoPathFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileNameFormatPattern: fn( self: *const IDataCollector, pattern: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileNameFormatPattern: fn( self: *const IDataCollector, pattern: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LatestOutputLocation: fn( self: *const IDataCollector, path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LatestOutputLocation: fn( self: *const IDataCollector, path: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogAppend: fn( self: *const IDataCollector, append: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogAppend: fn( self: *const IDataCollector, append: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogCircular: fn( self: *const IDataCollector, circular: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogCircular: fn( self: *const IDataCollector, circular: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogOverwrite: fn( self: *const IDataCollector, overwrite: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogOverwrite: fn( self: *const IDataCollector, overwrite: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IDataCollector, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IDataCollector, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OutputLocation: fn( self: *const IDataCollector, path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Index: fn( self: *const IDataCollector, index: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Index: fn( self: *const IDataCollector, index: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Xml: fn( self: *const IDataCollector, Xml: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetXml: fn( self: *const IDataCollector, Xml: ?BSTR, Validation: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateOutputLocation: fn( self: *const IDataCollector, Latest: i16, Location: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_DataCollectorSet(self: *const T, group: ?*?*IDataCollectorSet) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_DataCollectorSet(@ptrCast(*const IDataCollector, self), group); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_DataCollectorSet(self: *const T, group: ?*IDataCollectorSet) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_DataCollectorSet(@ptrCast(*const IDataCollector, self), group); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_DataCollectorType(self: *const T, type_: ?*DataCollectorType) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_DataCollectorType(@ptrCast(*const IDataCollector, self), type_); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_FileName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileName(@ptrCast(*const IDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_FileName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileName(@ptrCast(*const IDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_FileNameFormat(self: *const T, format: ?*AutoPathFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileNameFormat(@ptrCast(*const IDataCollector, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_FileNameFormat(self: *const T, format: AutoPathFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileNameFormat(@ptrCast(*const IDataCollector, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_FileNameFormatPattern(self: *const T, pattern: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileNameFormatPattern(@ptrCast(*const IDataCollector, self), pattern); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_FileNameFormatPattern(self: *const T, pattern: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileNameFormatPattern(@ptrCast(*const IDataCollector, self), pattern); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_LatestOutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LatestOutputLocation(@ptrCast(*const IDataCollector, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_LatestOutputLocation(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LatestOutputLocation(@ptrCast(*const IDataCollector, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_LogAppend(self: *const T, append: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogAppend(@ptrCast(*const IDataCollector, self), append); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_LogAppend(self: *const T, append: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogAppend(@ptrCast(*const IDataCollector, self), append); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_LogCircular(self: *const T, circular: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogCircular(@ptrCast(*const IDataCollector, self), circular); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_LogCircular(self: *const T, circular: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogCircular(@ptrCast(*const IDataCollector, self), circular); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_LogOverwrite(self: *const T, overwrite: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogOverwrite(@ptrCast(*const IDataCollector, self), overwrite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_LogOverwrite(self: *const T, overwrite: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogOverwrite(@ptrCast(*const IDataCollector, self), overwrite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_Name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Name(@ptrCast(*const IDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_Name(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_Name(@ptrCast(*const IDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_OutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_OutputLocation(@ptrCast(*const IDataCollector, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_Index(self: *const T, index: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Index(@ptrCast(*const IDataCollector, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_put_Index(self: *const T, index: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).put_Index(@ptrCast(*const IDataCollector, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_get_Xml(self: *const T, Xml: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Xml(@ptrCast(*const IDataCollector, self), Xml); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_SetXml(self: *const T, Xml: ?BSTR, Validation: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).SetXml(@ptrCast(*const IDataCollector, self), Xml, Validation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollector_CreateOutputLocation(self: *const T, Latest: i16, Location: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollector.VTable, self.vtable).CreateOutputLocation(@ptrCast(*const IDataCollector, self), Latest, Location); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPerformanceCounterDataCollector_Value = Guid.initString("03837506-098b-11d8-9414-505054503030"); pub const IID_IPerformanceCounterDataCollector = &IID_IPerformanceCounterDataCollector_Value; pub const IPerformanceCounterDataCollector = extern struct { pub const VTable = extern struct { base: IDataCollector.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataSourceName: fn( self: *const IPerformanceCounterDataCollector, dsn: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataSourceName: fn( self: *const IPerformanceCounterDataCollector, dsn: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PerformanceCounters: fn( self: *const IPerformanceCounterDataCollector, counters: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PerformanceCounters: fn( self: *const IPerformanceCounterDataCollector, counters: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFileFormat: fn( self: *const IPerformanceCounterDataCollector, format: ?*FileFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogFileFormat: fn( self: *const IPerformanceCounterDataCollector, format: FileFormat, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SampleInterval: fn( self: *const IPerformanceCounterDataCollector, interval: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SampleInterval: fn( self: *const IPerformanceCounterDataCollector, interval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SegmentMaxRecords: fn( self: *const IPerformanceCounterDataCollector, records: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SegmentMaxRecords: fn( self: *const IPerformanceCounterDataCollector, records: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDataCollector.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_get_DataSourceName(self: *const T, dsn: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_DataSourceName(@ptrCast(*const IPerformanceCounterDataCollector, self), dsn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_put_DataSourceName(self: *const T, dsn: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_DataSourceName(@ptrCast(*const IPerformanceCounterDataCollector, self), dsn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_get_PerformanceCounters(self: *const T, counters: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_PerformanceCounters(@ptrCast(*const IPerformanceCounterDataCollector, self), counters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_put_PerformanceCounters(self: *const T, counters: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_PerformanceCounters(@ptrCast(*const IPerformanceCounterDataCollector, self), counters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_get_LogFileFormat(self: *const T, format: ?*FileFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_LogFileFormat(@ptrCast(*const IPerformanceCounterDataCollector, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_put_LogFileFormat(self: *const T, format: FileFormat) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_LogFileFormat(@ptrCast(*const IPerformanceCounterDataCollector, self), format); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_get_SampleInterval(self: *const T, interval: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_SampleInterval(@ptrCast(*const IPerformanceCounterDataCollector, self), interval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_put_SampleInterval(self: *const T, interval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_SampleInterval(@ptrCast(*const IPerformanceCounterDataCollector, self), interval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_get_SegmentMaxRecords(self: *const T, records: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_SegmentMaxRecords(@ptrCast(*const IPerformanceCounterDataCollector, self), records); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPerformanceCounterDataCollector_put_SegmentMaxRecords(self: *const T, records: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_SegmentMaxRecords(@ptrCast(*const IPerformanceCounterDataCollector, self), records); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITraceDataCollector_Value = Guid.initString("0383750b-098b-11d8-9414-505054503030"); pub const IID_ITraceDataCollector = &IID_ITraceDataCollector_Value; pub const ITraceDataCollector = extern struct { pub const VTable = extern struct { base: IDataCollector.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BufferSize: fn( self: *const ITraceDataCollector, size: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BufferSize: fn( self: *const ITraceDataCollector, size: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BuffersLost: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BuffersLost: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BuffersWritten: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BuffersWritten: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ClockType: fn( self: *const ITraceDataCollector, clock: ?*ClockType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ClockType: fn( self: *const ITraceDataCollector, clock: ClockType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventsLost: fn( self: *const ITraceDataCollector, events: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventsLost: fn( self: *const ITraceDataCollector, events: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExtendedModes: fn( self: *const ITraceDataCollector, mode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ExtendedModes: fn( self: *const ITraceDataCollector, mode: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FlushTimer: fn( self: *const ITraceDataCollector, seconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FlushTimer: fn( self: *const ITraceDataCollector, seconds: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FreeBuffers: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FreeBuffers: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Guid: fn( self: *const ITraceDataCollector, guid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Guid: fn( self: *const ITraceDataCollector, guid: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsKernelTrace: fn( self: *const ITraceDataCollector, kernel: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaximumBuffers: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaximumBuffers: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinimumBuffers: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinimumBuffers: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NumberOfBuffers: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NumberOfBuffers: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PreallocateFile: fn( self: *const ITraceDataCollector, allocate: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PreallocateFile: fn( self: *const ITraceDataCollector, allocate: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ProcessMode: fn( self: *const ITraceDataCollector, process: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ProcessMode: fn( self: *const ITraceDataCollector, process: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RealTimeBuffersLost: fn( self: *const ITraceDataCollector, buffers: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RealTimeBuffersLost: fn( self: *const ITraceDataCollector, buffers: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SessionId: fn( self: *const ITraceDataCollector, id: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SessionId: fn( self: *const ITraceDataCollector, id: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SessionName: fn( self: *const ITraceDataCollector, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SessionName: fn( self: *const ITraceDataCollector, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SessionThreadId: fn( self: *const ITraceDataCollector, tid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SessionThreadId: fn( self: *const ITraceDataCollector, tid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StreamMode: fn( self: *const ITraceDataCollector, mode: ?*StreamMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StreamMode: fn( self: *const ITraceDataCollector, mode: StreamMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TraceDataProviders: fn( self: *const ITraceDataCollector, providers: ?*?*ITraceDataProviderCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDataCollector.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_BufferSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BufferSize(@ptrCast(*const ITraceDataCollector, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_BufferSize(self: *const T, size: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BufferSize(@ptrCast(*const ITraceDataCollector, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_BuffersLost(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_BuffersLost(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_BuffersWritten(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BuffersWritten(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_BuffersWritten(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BuffersWritten(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_ClockType(self: *const T, clock: ?*ClockType) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ClockType(@ptrCast(*const ITraceDataCollector, self), clock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_ClockType(self: *const T, clock: ClockType) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ClockType(@ptrCast(*const ITraceDataCollector, self), clock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_EventsLost(self: *const T, events: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_EventsLost(@ptrCast(*const ITraceDataCollector, self), events); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_EventsLost(self: *const T, events: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_EventsLost(@ptrCast(*const ITraceDataCollector, self), events); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_ExtendedModes(self: *const T, mode: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ExtendedModes(@ptrCast(*const ITraceDataCollector, self), mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_ExtendedModes(self: *const T, mode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ExtendedModes(@ptrCast(*const ITraceDataCollector, self), mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_FlushTimer(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_FlushTimer(@ptrCast(*const ITraceDataCollector, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_FlushTimer(self: *const T, seconds: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_FlushTimer(@ptrCast(*const ITraceDataCollector, self), seconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_FreeBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_FreeBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_FreeBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_FreeBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_Guid(self: *const T, guid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_Guid(@ptrCast(*const ITraceDataCollector, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_Guid(self: *const T, guid: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_Guid(@ptrCast(*const ITraceDataCollector, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_IsKernelTrace(self: *const T, kernel: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_IsKernelTrace(@ptrCast(*const ITraceDataCollector, self), kernel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_MaximumBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_MaximumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_MaximumBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_MaximumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_MinimumBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_MinimumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_MinimumBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_MinimumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_NumberOfBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_NumberOfBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_NumberOfBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_NumberOfBuffers(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_PreallocateFile(self: *const T, allocate: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_PreallocateFile(@ptrCast(*const ITraceDataCollector, self), allocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_PreallocateFile(self: *const T, allocate: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_PreallocateFile(@ptrCast(*const ITraceDataCollector, self), allocate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_ProcessMode(self: *const T, process: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ProcessMode(@ptrCast(*const ITraceDataCollector, self), process); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_ProcessMode(self: *const T, process: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ProcessMode(@ptrCast(*const ITraceDataCollector, self), process); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_RealTimeBuffersLost(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_RealTimeBuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_RealTimeBuffersLost(self: *const T, buffers: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_RealTimeBuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_SessionId(self: *const T, id: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionId(@ptrCast(*const ITraceDataCollector, self), id); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_SessionId(self: *const T, id: u64) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionId(@ptrCast(*const ITraceDataCollector, self), id); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_SessionName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionName(@ptrCast(*const ITraceDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_SessionName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionName(@ptrCast(*const ITraceDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_SessionThreadId(self: *const T, tid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionThreadId(@ptrCast(*const ITraceDataCollector, self), tid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_SessionThreadId(self: *const T, tid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionThreadId(@ptrCast(*const ITraceDataCollector, self), tid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_StreamMode(self: *const T, mode: ?*StreamMode) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_StreamMode(@ptrCast(*const ITraceDataCollector, self), mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_put_StreamMode(self: *const T, mode: StreamMode) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_StreamMode(@ptrCast(*const ITraceDataCollector, self), mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataCollector_get_TraceDataProviders(self: *const T, providers: ?*?*ITraceDataProviderCollection) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_TraceDataProviders(@ptrCast(*const ITraceDataCollector, self), providers); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConfigurationDataCollector_Value = Guid.initString("03837514-098b-11d8-9414-505054503030"); pub const IID_IConfigurationDataCollector = &IID_IConfigurationDataCollector_Value; pub const IConfigurationDataCollector = extern struct { pub const VTable = extern struct { base: IDataCollector.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileMaxCount: fn( self: *const IConfigurationDataCollector, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileMaxCount: fn( self: *const IConfigurationDataCollector, count: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileMaxRecursiveDepth: fn( self: *const IConfigurationDataCollector, depth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileMaxRecursiveDepth: fn( self: *const IConfigurationDataCollector, depth: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FileMaxTotalSize: fn( self: *const IConfigurationDataCollector, size: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FileMaxTotalSize: fn( self: *const IConfigurationDataCollector, size: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Files: fn( self: *const IConfigurationDataCollector, Files: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Files: fn( self: *const IConfigurationDataCollector, Files: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ManagementQueries: fn( self: *const IConfigurationDataCollector, Queries: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ManagementQueries: fn( self: *const IConfigurationDataCollector, Queries: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_QueryNetworkAdapters: fn( self: *const IConfigurationDataCollector, network: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_QueryNetworkAdapters: fn( self: *const IConfigurationDataCollector, network: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RegistryKeys: fn( self: *const IConfigurationDataCollector, query: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RegistryKeys: fn( self: *const IConfigurationDataCollector, query: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RegistryMaxRecursiveDepth: fn( self: *const IConfigurationDataCollector, depth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RegistryMaxRecursiveDepth: fn( self: *const IConfigurationDataCollector, depth: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SystemStateFile: fn( self: *const IConfigurationDataCollector, FileName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SystemStateFile: fn( self: *const IConfigurationDataCollector, FileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDataCollector.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_FileMaxCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxCount(@ptrCast(*const IConfigurationDataCollector, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_FileMaxCount(self: *const T, count: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxCount(@ptrCast(*const IConfigurationDataCollector, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_FileMaxRecursiveDepth(self: *const T, depth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_FileMaxRecursiveDepth(self: *const T, depth: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_FileMaxTotalSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxTotalSize(@ptrCast(*const IConfigurationDataCollector, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_FileMaxTotalSize(self: *const T, size: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxTotalSize(@ptrCast(*const IConfigurationDataCollector, self), size); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_Files(self: *const T, Files: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_Files(@ptrCast(*const IConfigurationDataCollector, self), Files); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_Files(self: *const T, Files: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_Files(@ptrCast(*const IConfigurationDataCollector, self), Files); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_ManagementQueries(self: *const T, Queries: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_ManagementQueries(@ptrCast(*const IConfigurationDataCollector, self), Queries); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_ManagementQueries(self: *const T, Queries: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_ManagementQueries(@ptrCast(*const IConfigurationDataCollector, self), Queries); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_QueryNetworkAdapters(self: *const T, network: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_QueryNetworkAdapters(@ptrCast(*const IConfigurationDataCollector, self), network); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_QueryNetworkAdapters(self: *const T, network: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_QueryNetworkAdapters(@ptrCast(*const IConfigurationDataCollector, self), network); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_RegistryKeys(self: *const T, query: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_RegistryKeys(@ptrCast(*const IConfigurationDataCollector, self), query); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_RegistryKeys(self: *const T, query: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_RegistryKeys(@ptrCast(*const IConfigurationDataCollector, self), query); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_RegistryMaxRecursiveDepth(self: *const T, depth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_RegistryMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_RegistryMaxRecursiveDepth(self: *const T, depth: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_RegistryMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_get_SystemStateFile(self: *const T, FileName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_SystemStateFile(@ptrCast(*const IConfigurationDataCollector, self), FileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConfigurationDataCollector_put_SystemStateFile(self: *const T, FileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_SystemStateFile(@ptrCast(*const IConfigurationDataCollector, self), FileName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IAlertDataCollector_Value = Guid.initString("03837516-098b-11d8-9414-505054503030"); pub const IID_IAlertDataCollector = &IID_IAlertDataCollector_Value; pub const IAlertDataCollector = extern struct { pub const VTable = extern struct { base: IDataCollector.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AlertThresholds: fn( self: *const IAlertDataCollector, alerts: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AlertThresholds: fn( self: *const IAlertDataCollector, alerts: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventLog: fn( self: *const IAlertDataCollector, log: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventLog: fn( self: *const IAlertDataCollector, log: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SampleInterval: fn( self: *const IAlertDataCollector, interval: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SampleInterval: fn( self: *const IAlertDataCollector, interval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Task: fn( self: *const IAlertDataCollector, task: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Task: fn( self: *const IAlertDataCollector, task: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskRunAsSelf: fn( self: *const IAlertDataCollector, RunAsSelf: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskRunAsSelf: fn( self: *const IAlertDataCollector, RunAsSelf: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskArguments: fn( self: *const IAlertDataCollector, task: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskArguments: fn( self: *const IAlertDataCollector, task: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TaskUserTextArguments: fn( self: *const IAlertDataCollector, task: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TaskUserTextArguments: fn( self: *const IAlertDataCollector, task: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TriggerDataCollectorSet: fn( self: *const IAlertDataCollector, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TriggerDataCollectorSet: fn( self: *const IAlertDataCollector, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDataCollector.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_AlertThresholds(self: *const T, alerts: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_AlertThresholds(@ptrCast(*const IAlertDataCollector, self), alerts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_AlertThresholds(self: *const T, alerts: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_AlertThresholds(@ptrCast(*const IAlertDataCollector, self), alerts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_EventLog(self: *const T, log: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_EventLog(@ptrCast(*const IAlertDataCollector, self), log); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_EventLog(self: *const T, log: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_EventLog(@ptrCast(*const IAlertDataCollector, self), log); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_SampleInterval(self: *const T, interval: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_SampleInterval(@ptrCast(*const IAlertDataCollector, self), interval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_SampleInterval(self: *const T, interval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_SampleInterval(@ptrCast(*const IAlertDataCollector, self), interval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_Task(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_Task(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_Task(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_Task(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_TaskRunAsSelf(self: *const T, RunAsSelf: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskRunAsSelf(@ptrCast(*const IAlertDataCollector, self), RunAsSelf); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_TaskRunAsSelf(self: *const T, RunAsSelf: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskRunAsSelf(@ptrCast(*const IAlertDataCollector, self), RunAsSelf); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_TaskArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskArguments(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_TaskArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskArguments(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_TaskUserTextArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskUserTextArguments(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_TaskUserTextArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskUserTextArguments(@ptrCast(*const IAlertDataCollector, self), task); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_get_TriggerDataCollectorSet(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TriggerDataCollectorSet(@ptrCast(*const IAlertDataCollector, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAlertDataCollector_put_TriggerDataCollectorSet(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TriggerDataCollectorSet(@ptrCast(*const IAlertDataCollector, self), name); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IApiTracingDataCollector_Value = Guid.initString("0383751a-098b-11d8-9414-505054503030"); pub const IID_IApiTracingDataCollector = &IID_IApiTracingDataCollector_Value; pub const IApiTracingDataCollector = extern struct { pub const VTable = extern struct { base: IDataCollector.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogApiNamesOnly: fn( self: *const IApiTracingDataCollector, logapinames: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogApiNamesOnly: fn( self: *const IApiTracingDataCollector, logapinames: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogApisRecursively: fn( self: *const IApiTracingDataCollector, logrecursively: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogApisRecursively: fn( self: *const IApiTracingDataCollector, logrecursively: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExePath: fn( self: *const IApiTracingDataCollector, exepath: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ExePath: fn( self: *const IApiTracingDataCollector, exepath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFilePath: fn( self: *const IApiTracingDataCollector, logfilepath: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogFilePath: fn( self: *const IApiTracingDataCollector, logfilepath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IncludeModules: fn( self: *const IApiTracingDataCollector, includemodules: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_IncludeModules: fn( self: *const IApiTracingDataCollector, includemodules: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IncludeApis: fn( self: *const IApiTracingDataCollector, includeapis: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_IncludeApis: fn( self: *const IApiTracingDataCollector, includeapis: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExcludeApis: fn( self: *const IApiTracingDataCollector, excludeapis: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ExcludeApis: fn( self: *const IApiTracingDataCollector, excludeapis: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDataCollector.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_LogApiNamesOnly(self: *const T, logapinames: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogApiNamesOnly(@ptrCast(*const IApiTracingDataCollector, self), logapinames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_LogApiNamesOnly(self: *const T, logapinames: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogApiNamesOnly(@ptrCast(*const IApiTracingDataCollector, self), logapinames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_LogApisRecursively(self: *const T, logrecursively: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogApisRecursively(@ptrCast(*const IApiTracingDataCollector, self), logrecursively); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_LogApisRecursively(self: *const T, logrecursively: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogApisRecursively(@ptrCast(*const IApiTracingDataCollector, self), logrecursively); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_ExePath(self: *const T, exepath: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_ExePath(@ptrCast(*const IApiTracingDataCollector, self), exepath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_ExePath(self: *const T, exepath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_ExePath(@ptrCast(*const IApiTracingDataCollector, self), exepath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_LogFilePath(self: *const T, logfilepath: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogFilePath(@ptrCast(*const IApiTracingDataCollector, self), logfilepath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_LogFilePath(self: *const T, logfilepath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogFilePath(@ptrCast(*const IApiTracingDataCollector, self), logfilepath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_IncludeModules(self: *const T, includemodules: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_IncludeModules(@ptrCast(*const IApiTracingDataCollector, self), includemodules); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_IncludeModules(self: *const T, includemodules: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_IncludeModules(@ptrCast(*const IApiTracingDataCollector, self), includemodules); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_IncludeApis(self: *const T, includeapis: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_IncludeApis(@ptrCast(*const IApiTracingDataCollector, self), includeapis); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_IncludeApis(self: *const T, includeapis: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_IncludeApis(@ptrCast(*const IApiTracingDataCollector, self), includeapis); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_get_ExcludeApis(self: *const T, excludeapis: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_ExcludeApis(@ptrCast(*const IApiTracingDataCollector, self), excludeapis); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IApiTracingDataCollector_put_ExcludeApis(self: *const T, excludeapis: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_ExcludeApis(@ptrCast(*const IApiTracingDataCollector, self), excludeapis); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDataCollectorCollection_Value = Guid.initString("03837502-098b-11d8-9414-505054503030"); pub const IID_IDataCollectorCollection = &IID_IDataCollectorCollection_Value; pub const IDataCollectorCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IDataCollectorCollection, retVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IDataCollectorCollection, index: VARIANT, collector: ?*?*IDataCollector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IDataCollectorCollection, retVal: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IDataCollectorCollection, collector: ?*IDataCollector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IDataCollectorCollection, collector: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IDataCollectorCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const IDataCollectorCollection, collectors: ?*IDataCollectorCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDataCollectorFromXml: fn( self: *const IDataCollectorCollection, bstrXml: ?BSTR, pValidation: ?*?*IValueMap, pCollector: ?*?*IDataCollector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDataCollector: fn( self: *const IDataCollectorCollection, Type: DataCollectorType, Collector: ?*?*IDataCollector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get_Count(@ptrCast(*const IDataCollectorCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_get_Item(self: *const T, index: VARIANT, collector: ?*?*IDataCollector) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get_Item(@ptrCast(*const IDataCollectorCollection, self), index, collector); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IDataCollectorCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_Add(self: *const T, collector: ?*IDataCollector) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Add(@ptrCast(*const IDataCollectorCollection, self), collector); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_Remove(self: *const T, collector: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Remove(@ptrCast(*const IDataCollectorCollection, self), collector); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Clear(@ptrCast(*const IDataCollectorCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_AddRange(self: *const T, collectors: ?*IDataCollectorCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).AddRange(@ptrCast(*const IDataCollectorCollection, self), collectors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_CreateDataCollectorFromXml(self: *const T, bstrXml: ?BSTR, pValidation: ?*?*IValueMap, pCollector: ?*?*IDataCollector) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).CreateDataCollectorFromXml(@ptrCast(*const IDataCollectorCollection, self), bstrXml, pValidation, pCollector); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorCollection_CreateDataCollector(self: *const T, Type: DataCollectorType, Collector: ?*?*IDataCollector) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).CreateDataCollector(@ptrCast(*const IDataCollectorCollection, self), Type, Collector); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDataCollectorSetCollection_Value = Guid.initString("03837524-098b-11d8-9414-505054503030"); pub const IID_IDataCollectorSetCollection = &IID_IDataCollectorSetCollection_Value; pub const IDataCollectorSetCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IDataCollectorSetCollection, retVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IDataCollectorSetCollection, index: VARIANT, set: ?*?*IDataCollectorSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IDataCollectorSetCollection, retVal: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IDataCollectorSetCollection, set: ?*IDataCollectorSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IDataCollectorSetCollection, set: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IDataCollectorSetCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const IDataCollectorSetCollection, sets: ?*IDataCollectorSetCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataCollectorSets: fn( self: *const IDataCollectorSetCollection, server: ?BSTR, filter: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get_Count(@ptrCast(*const IDataCollectorSetCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_get_Item(self: *const T, index: VARIANT, set: ?*?*IDataCollectorSet) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get_Item(@ptrCast(*const IDataCollectorSetCollection, self), index, set); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IDataCollectorSetCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_Add(self: *const T, set: ?*IDataCollectorSet) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Add(@ptrCast(*const IDataCollectorSetCollection, self), set); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_Remove(self: *const T, set: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Remove(@ptrCast(*const IDataCollectorSetCollection, self), set); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Clear(@ptrCast(*const IDataCollectorSetCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_AddRange(self: *const T, sets: ?*IDataCollectorSetCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).AddRange(@ptrCast(*const IDataCollectorSetCollection, self), sets); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDataCollectorSetCollection_GetDataCollectorSets(self: *const T, server: ?BSTR, filter: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).GetDataCollectorSets(@ptrCast(*const IDataCollectorSetCollection, self), server, filter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITraceDataProvider_Value = Guid.initString("03837512-098b-11d8-9414-505054503030"); pub const IID_ITraceDataProvider = &IID_ITraceDataProvider_Value; pub const ITraceDataProvider = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const ITraceDataProvider, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayName: fn( self: *const ITraceDataProvider, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Guid: fn( self: *const ITraceDataProvider, guid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Guid: fn( self: *const ITraceDataProvider, guid: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Level: fn( self: *const ITraceDataProvider, ppLevel: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_KeywordsAny: fn( self: *const ITraceDataProvider, ppKeywords: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_KeywordsAll: fn( self: *const ITraceDataProvider, ppKeywords: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Properties: fn( self: *const ITraceDataProvider, ppProperties: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FilterEnabled: fn( self: *const ITraceDataProvider, FilterEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FilterEnabled: fn( self: *const ITraceDataProvider, FilterEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FilterType: fn( self: *const ITraceDataProvider, pulType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FilterType: fn( self: *const ITraceDataProvider, ulType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FilterData: fn( self: *const ITraceDataProvider, ppData: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FilterData: fn( self: *const ITraceDataProvider, pData: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Query: fn( self: *const ITraceDataProvider, bstrName: ?BSTR, bstrServer: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Resolve: fn( self: *const ITraceDataProvider, pFrom: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurity: fn( self: *const ITraceDataProvider, Sddl: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecurity: fn( self: *const ITraceDataProvider, SecurityInfo: u32, Sddl: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegisteredProcesses: fn( self: *const ITraceDataProvider, Processes: ?*?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_DisplayName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_DisplayName(@ptrCast(*const ITraceDataProvider, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_put_DisplayName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_DisplayName(@ptrCast(*const ITraceDataProvider, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_Guid(self: *const T, guid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Guid(@ptrCast(*const ITraceDataProvider, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_put_Guid(self: *const T, guid: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_Guid(@ptrCast(*const ITraceDataProvider, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_Level(self: *const T, ppLevel: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Level(@ptrCast(*const ITraceDataProvider, self), ppLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_KeywordsAny(self: *const T, ppKeywords: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_KeywordsAny(@ptrCast(*const ITraceDataProvider, self), ppKeywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_KeywordsAll(self: *const T, ppKeywords: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_KeywordsAll(@ptrCast(*const ITraceDataProvider, self), ppKeywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_Properties(self: *const T, ppProperties: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Properties(@ptrCast(*const ITraceDataProvider, self), ppProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_FilterEnabled(self: *const T, FilterEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterEnabled(@ptrCast(*const ITraceDataProvider, self), FilterEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_put_FilterEnabled(self: *const T, FilterEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterEnabled(@ptrCast(*const ITraceDataProvider, self), FilterEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_FilterType(self: *const T, pulType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterType(@ptrCast(*const ITraceDataProvider, self), pulType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_put_FilterType(self: *const T, ulType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterType(@ptrCast(*const ITraceDataProvider, self), ulType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_get_FilterData(self: *const T, ppData: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterData(@ptrCast(*const ITraceDataProvider, self), ppData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_put_FilterData(self: *const T, pData: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterData(@ptrCast(*const ITraceDataProvider, self), pData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_Query(self: *const T, bstrName: ?BSTR, bstrServer: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).Query(@ptrCast(*const ITraceDataProvider, self), bstrName, bstrServer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_Resolve(self: *const T, pFrom: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).Resolve(@ptrCast(*const ITraceDataProvider, self), pFrom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_SetSecurity(self: *const T, Sddl: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).SetSecurity(@ptrCast(*const ITraceDataProvider, self), Sddl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_GetSecurity(self: *const T, SecurityInfo: u32, Sddl: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).GetSecurity(@ptrCast(*const ITraceDataProvider, self), SecurityInfo, Sddl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProvider_GetRegisteredProcesses(self: *const T, Processes: ?*?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).GetRegisteredProcesses(@ptrCast(*const ITraceDataProvider, self), Processes); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITraceDataProviderCollection_Value = Guid.initString("03837510-098b-11d8-9414-505054503030"); pub const IID_ITraceDataProviderCollection = &IID_ITraceDataProviderCollection_Value; pub const ITraceDataProviderCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const ITraceDataProviderCollection, retVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const ITraceDataProviderCollection, index: VARIANT, ppProvider: ?*?*ITraceDataProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const ITraceDataProviderCollection, retVal: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const ITraceDataProviderCollection, pProvider: ?*ITraceDataProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const ITraceDataProviderCollection, vProvider: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const ITraceDataProviderCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const ITraceDataProviderCollection, providers: ?*ITraceDataProviderCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateTraceDataProvider: fn( self: *const ITraceDataProviderCollection, Provider: ?*?*ITraceDataProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTraceDataProviders: fn( self: *const ITraceDataProviderCollection, server: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTraceDataProvidersByProcess: fn( self: *const ITraceDataProviderCollection, Server: ?BSTR, Pid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get_Count(@ptrCast(*const ITraceDataProviderCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_get_Item(self: *const T, index: VARIANT, ppProvider: ?*?*ITraceDataProvider) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get_Item(@ptrCast(*const ITraceDataProviderCollection, self), index, ppProvider); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const ITraceDataProviderCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_Add(self: *const T, pProvider: ?*ITraceDataProvider) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Add(@ptrCast(*const ITraceDataProviderCollection, self), pProvider); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_Remove(self: *const T, vProvider: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Remove(@ptrCast(*const ITraceDataProviderCollection, self), vProvider); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Clear(@ptrCast(*const ITraceDataProviderCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_AddRange(self: *const T, providers: ?*ITraceDataProviderCollection) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).AddRange(@ptrCast(*const ITraceDataProviderCollection, self), providers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_CreateTraceDataProvider(self: *const T, Provider: ?*?*ITraceDataProvider) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).CreateTraceDataProvider(@ptrCast(*const ITraceDataProviderCollection, self), Provider); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_GetTraceDataProviders(self: *const T, server: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).GetTraceDataProviders(@ptrCast(*const ITraceDataProviderCollection, self), server); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceDataProviderCollection_GetTraceDataProvidersByProcess(self: *const T, Server: ?BSTR, Pid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).GetTraceDataProvidersByProcess(@ptrCast(*const ITraceDataProviderCollection, self), Server, Pid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISchedule_Value = Guid.initString("0383753a-098b-11d8-9414-505054503030"); pub const IID_ISchedule = &IID_ISchedule_Value; pub const ISchedule = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartDate: fn( self: *const ISchedule, start: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartDate: fn( self: *const ISchedule, start: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EndDate: fn( self: *const ISchedule, end: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EndDate: fn( self: *const ISchedule, end: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartTime: fn( self: *const ISchedule, start: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartTime: fn( self: *const ISchedule, start: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Days: fn( self: *const ISchedule, days: ?*WeekDays, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Days: fn( self: *const ISchedule, days: WeekDays, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_get_StartDate(self: *const T, start: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).get_StartDate(@ptrCast(*const ISchedule, self), start); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_put_StartDate(self: *const T, start: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).put_StartDate(@ptrCast(*const ISchedule, self), start); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_get_EndDate(self: *const T, end: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).get_EndDate(@ptrCast(*const ISchedule, self), end); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_put_EndDate(self: *const T, end: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).put_EndDate(@ptrCast(*const ISchedule, self), end); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_get_StartTime(self: *const T, start: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).get_StartTime(@ptrCast(*const ISchedule, self), start); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_put_StartTime(self: *const T, start: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).put_StartTime(@ptrCast(*const ISchedule, self), start); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_get_Days(self: *const T, days: ?*WeekDays) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).get_Days(@ptrCast(*const ISchedule, self), days); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISchedule_put_Days(self: *const T, days: WeekDays) callconv(.Inline) HRESULT { return @ptrCast(*const ISchedule.VTable, self.vtable).put_Days(@ptrCast(*const ISchedule, self), days); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IScheduleCollection_Value = Guid.initString("0383753d-098b-11d8-9414-505054503030"); pub const IID_IScheduleCollection = &IID_IScheduleCollection_Value; pub const IScheduleCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IScheduleCollection, retVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IScheduleCollection, index: VARIANT, ppSchedule: ?*?*ISchedule, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IScheduleCollection, ienum: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IScheduleCollection, pSchedule: ?*ISchedule, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IScheduleCollection, vSchedule: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IScheduleCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const IScheduleCollection, pSchedules: ?*IScheduleCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSchedule: fn( self: *const IScheduleCollection, Schedule: ?*?*ISchedule, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get_Count(@ptrCast(*const IScheduleCollection, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_get_Item(self: *const T, index: VARIANT, ppSchedule: ?*?*ISchedule) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get_Item(@ptrCast(*const IScheduleCollection, self), index, ppSchedule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_get__NewEnum(self: *const T, ienum: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IScheduleCollection, self), ienum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_Add(self: *const T, pSchedule: ?*ISchedule) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Add(@ptrCast(*const IScheduleCollection, self), pSchedule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_Remove(self: *const T, vSchedule: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Remove(@ptrCast(*const IScheduleCollection, self), vSchedule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Clear(@ptrCast(*const IScheduleCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_AddRange(self: *const T, pSchedules: ?*IScheduleCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).AddRange(@ptrCast(*const IScheduleCollection, self), pSchedules); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IScheduleCollection_CreateSchedule(self: *const T, Schedule: ?*?*ISchedule) callconv(.Inline) HRESULT { return @ptrCast(*const IScheduleCollection.VTable, self.vtable).CreateSchedule(@ptrCast(*const IScheduleCollection, self), Schedule); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IValueMapItem_Value = Guid.initString("03837533-098b-11d8-9414-505054503030"); pub const IID_IValueMapItem = &IID_IValueMapItem_Value; pub const IValueMapItem = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IValueMapItem, description: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IValueMapItem, description: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const IValueMapItem, enabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enabled: fn( self: *const IValueMapItem, enabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Key: fn( self: *const IValueMapItem, key: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Key: fn( self: *const IValueMapItem, key: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const IValueMapItem, Value: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Value: fn( self: *const IValueMapItem, Value: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ValueMapType: fn( self: *const IValueMapItem, type: ?*ValueMapType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ValueMapType: fn( self: *const IValueMapItem, type: ValueMapType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Description(@ptrCast(*const IValueMapItem, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Description(@ptrCast(*const IValueMapItem, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_get_Enabled(self: *const T, enabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Enabled(@ptrCast(*const IValueMapItem, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_put_Enabled(self: *const T, enabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Enabled(@ptrCast(*const IValueMapItem, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_get_Key(self: *const T, key: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Key(@ptrCast(*const IValueMapItem, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_put_Key(self: *const T, key: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Key(@ptrCast(*const IValueMapItem, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_get_Value(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Value(@ptrCast(*const IValueMapItem, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_put_Value(self: *const T, Value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Value(@ptrCast(*const IValueMapItem, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_get_ValueMapType(self: *const T, type_: ?*ValueMapType) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_ValueMapType(@ptrCast(*const IValueMapItem, self), type_); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMapItem_put_ValueMapType(self: *const T, type_: ValueMapType) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_ValueMapType(@ptrCast(*const IValueMapItem, self), type_); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IValueMap_Value = Guid.initString("03837534-098b-11d8-9414-505054503030"); pub const IID_IValueMap = &IID_IValueMap_Value; pub const IValueMap = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IValueMap, retVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IValueMap, index: VARIANT, value: ?*?*IValueMapItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IValueMap, retVal: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IValueMap, description: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IValueMap, description: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const IValueMap, Value: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Value: fn( self: *const IValueMap, Value: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ValueMapType: fn( self: *const IValueMap, type: ?*ValueMapType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ValueMapType: fn( self: *const IValueMap, type: ValueMapType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IValueMap, value: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IValueMap, value: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRange: fn( self: *const IValueMap, map: ?*IValueMap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateValueMapItem: fn( self: *const IValueMap, Item: ?*?*IValueMapItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get_Count(@ptrCast(*const IValueMap, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get_Item(self: *const T, index: VARIANT, value: ?*?*IValueMapItem) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get_Item(@ptrCast(*const IValueMap, self), index, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get__NewEnum(@ptrCast(*const IValueMap, self), retVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get_Description(@ptrCast(*const IValueMap, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).put_Description(@ptrCast(*const IValueMap, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get_Value(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get_Value(@ptrCast(*const IValueMap, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_put_Value(self: *const T, Value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).put_Value(@ptrCast(*const IValueMap, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_get_ValueMapType(self: *const T, type_: ?*ValueMapType) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).get_ValueMapType(@ptrCast(*const IValueMap, self), type_); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_put_ValueMapType(self: *const T, type_: ValueMapType) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).put_ValueMapType(@ptrCast(*const IValueMap, self), type_); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_Add(self: *const T, value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).Add(@ptrCast(*const IValueMap, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_Remove(self: *const T, value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).Remove(@ptrCast(*const IValueMap, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).Clear(@ptrCast(*const IValueMap, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_AddRange(self: *const T, map: ?*IValueMap) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).AddRange(@ptrCast(*const IValueMap, self), map); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IValueMap_CreateValueMapItem(self: *const T, Item: ?*?*IValueMapItem) callconv(.Inline) HRESULT { return @ptrCast(*const IValueMap.VTable, self.vtable).CreateValueMapItem(@ptrCast(*const IValueMap, self), Item); } };} pub usingnamespace MethodMixin(@This()); }; pub const PERF_COUNTERSET_INFO = extern struct { CounterSetGuid: Guid, ProviderGuid: Guid, NumCounters: u32, InstanceType: u32, }; pub const PERF_COUNTER_INFO = extern struct { CounterId: u32, Type: u32, Attrib: u64, Size: u32, DetailLevel: u32, Scale: i32, Offset: u32, }; pub const PERF_COUNTERSET_INSTANCE = extern struct { CounterSetGuid: Guid, dwSize: u32, InstanceId: u32, InstanceNameOffset: u32, InstanceNameSize: u32, }; pub const PERF_COUNTER_IDENTITY = extern struct { CounterSetGuid: Guid, BufferSize: u32, CounterId: u32, InstanceId: u32, MachineOffset: u32, NameOffset: u32, Reserved: u32, }; pub const PERFLIBREQUEST = fn( RequestCode: u32, Buffer: ?*anyopaque, BufferSize: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PERF_MEM_ALLOC = fn( AllocSize: usize, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PERF_MEM_FREE = fn( pBuffer: ?*anyopaque, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const PERF_PROVIDER_CONTEXT = extern struct { ContextSize: u32, Reserved: u32, ControlCallback: ?PERFLIBREQUEST, MemAllocRoutine: ?PERF_MEM_ALLOC, MemFreeRoutine: ?PERF_MEM_FREE, pMemContext: ?*anyopaque, }; pub const PERF_INSTANCE_HEADER = extern struct { Size: u32, InstanceId: u32, }; pub const PerfRegInfoType = enum(i32) { COUNTERSET_STRUCT = 1, COUNTER_STRUCT = 2, COUNTERSET_NAME_STRING = 3, COUNTERSET_HELP_STRING = 4, COUNTER_NAME_STRINGS = 5, COUNTER_HELP_STRINGS = 6, PROVIDER_NAME = 7, PROVIDER_GUID = 8, COUNTERSET_ENGLISH_NAME = 9, COUNTER_ENGLISH_NAMES = 10, }; pub const PERF_REG_COUNTERSET_STRUCT = PerfRegInfoType.COUNTERSET_STRUCT; pub const PERF_REG_COUNTER_STRUCT = PerfRegInfoType.COUNTER_STRUCT; pub const PERF_REG_COUNTERSET_NAME_STRING = PerfRegInfoType.COUNTERSET_NAME_STRING; pub const PERF_REG_COUNTERSET_HELP_STRING = PerfRegInfoType.COUNTERSET_HELP_STRING; pub const PERF_REG_COUNTER_NAME_STRINGS = PerfRegInfoType.COUNTER_NAME_STRINGS; pub const PERF_REG_COUNTER_HELP_STRINGS = PerfRegInfoType.COUNTER_HELP_STRINGS; pub const PERF_REG_PROVIDER_NAME = PerfRegInfoType.PROVIDER_NAME; pub const PERF_REG_PROVIDER_GUID = PerfRegInfoType.PROVIDER_GUID; pub const PERF_REG_COUNTERSET_ENGLISH_NAME = PerfRegInfoType.COUNTERSET_ENGLISH_NAME; pub const PERF_REG_COUNTER_ENGLISH_NAMES = PerfRegInfoType.COUNTER_ENGLISH_NAMES; pub const PERF_COUNTERSET_REG_INFO = extern struct { CounterSetGuid: Guid, CounterSetType: u32, DetailLevel: u32, NumCounters: u32, InstanceType: u32, }; pub const PERF_COUNTER_REG_INFO = extern struct { CounterId: u32, Type: u32, Attrib: u64, DetailLevel: u32, DefaultScale: i32, BaseCounterId: u32, PerfTimeId: u32, PerfFreqId: u32, MultiId: u32, AggregateFunc: PERF_COUNTER_AGGREGATE_FUNC, Reserved: u32, }; pub const PERF_STRING_BUFFER_HEADER = extern struct { dwSize: u32, dwCounters: u32, }; pub const PERF_STRING_COUNTER_HEADER = extern struct { dwCounterId: u32, dwOffset: u32, }; pub const PERF_COUNTER_IDENTIFIER = extern struct { CounterSetGuid: Guid, Status: u32, Size: u32, CounterId: u32, InstanceId: u32, Index: u32, Reserved: u32, }; pub const PERF_DATA_HEADER = extern struct { dwTotalSize: u32, dwNumCounters: u32, PerfTimeStamp: i64, PerfTime100NSec: i64, PerfFreq: i64, SystemTime: SYSTEMTIME, }; pub const PerfCounterDataType = enum(i32) { ERROR_RETURN = 0, SINGLE_COUNTER = 1, MULTIPLE_COUNTERS = 2, MULTIPLE_INSTANCES = 4, COUNTERSET = 6, }; pub const PERF_ERROR_RETURN = PerfCounterDataType.ERROR_RETURN; pub const PERF_SINGLE_COUNTER = PerfCounterDataType.SINGLE_COUNTER; pub const PERF_MULTIPLE_COUNTERS = PerfCounterDataType.MULTIPLE_COUNTERS; pub const PERF_MULTIPLE_INSTANCES = PerfCounterDataType.MULTIPLE_INSTANCES; pub const PERF_COUNTERSET = PerfCounterDataType.COUNTERSET; pub const PERF_COUNTER_HEADER = extern struct { dwStatus: u32, dwType: PerfCounterDataType, dwSize: u32, Reserved: u32, }; pub const PERF_MULTI_INSTANCES = extern struct { dwTotalSize: u32, dwInstances: u32, }; pub const PERF_MULTI_COUNTERS = extern struct { dwSize: u32, dwCounters: u32, }; pub const PERF_COUNTER_DATA = extern struct { dwDataSize: u32, dwSize: u32, }; pub const PERF_DATA_BLOCK = extern struct { Signature: [4]u16, LittleEndian: u32, Version: u32, Revision: u32, TotalByteLength: u32, HeaderLength: u32, NumObjectTypes: u32, DefaultObject: i32, SystemTime: SYSTEMTIME, PerfTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, PerfTime100nSec: LARGE_INTEGER, SystemNameLength: u32, SystemNameOffset: u32, }; pub const PERF_INSTANCE_DEFINITION = extern struct { ByteLength: u32, ParentObjectTitleIndex: u32, ParentObjectInstance: u32, UniqueID: i32, NameOffset: u32, NameLength: u32, }; pub const PERF_COUNTER_BLOCK = extern struct { ByteLength: u32, }; pub const PM_OPEN_PROC = fn( pContext: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PM_COLLECT_PROC = fn( pValueName: ?PWSTR, ppData: ?*?*anyopaque, pcbTotalBytes: ?*u32, pNumObjectTypes: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PM_CLOSE_PROC = fn( ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDH_RAW_COUNTER = extern struct { CStatus: u32, TimeStamp: FILETIME, FirstValue: i64, SecondValue: i64, MultiCount: u32, }; pub const PDH_RAW_COUNTER_ITEM_A = extern struct { szName: ?PSTR, RawValue: PDH_RAW_COUNTER, }; pub const PDH_RAW_COUNTER_ITEM_W = extern struct { szName: ?PWSTR, RawValue: PDH_RAW_COUNTER, }; pub const PDH_FMT_COUNTERVALUE = extern struct { CStatus: u32, Anonymous: extern union { longValue: i32, doubleValue: f64, largeValue: i64, AnsiStringValue: ?[*:0]const u8, WideStringValue: ?[*:0]const u16, }, }; pub const PDH_FMT_COUNTERVALUE_ITEM_A = extern struct { szName: ?PSTR, FmtValue: PDH_FMT_COUNTERVALUE, }; pub const PDH_FMT_COUNTERVALUE_ITEM_W = extern struct { szName: ?PWSTR, FmtValue: PDH_FMT_COUNTERVALUE, }; pub const PDH_STATISTICS = extern struct { dwFormat: u32, count: u32, min: PDH_FMT_COUNTERVALUE, max: PDH_FMT_COUNTERVALUE, mean: PDH_FMT_COUNTERVALUE, }; pub const PDH_COUNTER_PATH_ELEMENTS_A = extern struct { szMachineName: ?PSTR, szObjectName: ?PSTR, szInstanceName: ?PSTR, szParentInstance: ?PSTR, dwInstanceIndex: u32, szCounterName: ?PSTR, }; pub const PDH_COUNTER_PATH_ELEMENTS_W = extern struct { szMachineName: ?PWSTR, szObjectName: ?PWSTR, szInstanceName: ?PWSTR, szParentInstance: ?PWSTR, dwInstanceIndex: u32, szCounterName: ?PWSTR, }; pub const PDH_DATA_ITEM_PATH_ELEMENTS_A = extern struct { szMachineName: ?PSTR, ObjectGUID: Guid, dwItemId: u32, szInstanceName: ?PSTR, }; pub const PDH_DATA_ITEM_PATH_ELEMENTS_W = extern struct { szMachineName: ?PWSTR, ObjectGUID: Guid, dwItemId: u32, szInstanceName: ?PWSTR, }; pub const PDH_COUNTER_INFO_A = extern struct { dwLength: u32, dwType: u32, CVersion: u32, CStatus: u32, lScale: i32, lDefaultScale: i32, dwUserData: usize, dwQueryUserData: usize, szFullPath: ?PSTR, Anonymous: extern union { DataItemPath: PDH_DATA_ITEM_PATH_ELEMENTS_A, CounterPath: PDH_COUNTER_PATH_ELEMENTS_A, Anonymous: extern struct { szMachineName: ?PSTR, szObjectName: ?PSTR, szInstanceName: ?PSTR, szParentInstance: ?PSTR, dwInstanceIndex: u32, szCounterName: ?PSTR, }, }, szExplainText: ?PSTR, DataBuffer: [1]u32, }; pub const PDH_COUNTER_INFO_W = extern struct { dwLength: u32, dwType: u32, CVersion: u32, CStatus: u32, lScale: i32, lDefaultScale: i32, dwUserData: usize, dwQueryUserData: usize, szFullPath: ?PWSTR, Anonymous: extern union { DataItemPath: PDH_DATA_ITEM_PATH_ELEMENTS_W, CounterPath: PDH_COUNTER_PATH_ELEMENTS_W, Anonymous: extern struct { szMachineName: ?PWSTR, szObjectName: ?PWSTR, szInstanceName: ?PWSTR, szParentInstance: ?PWSTR, dwInstanceIndex: u32, szCounterName: ?PWSTR, }, }, szExplainText: ?PWSTR, DataBuffer: [1]u32, }; pub const PDH_TIME_INFO = extern struct { StartTime: i64, EndTime: i64, SampleCount: u32, }; pub const PDH_RAW_LOG_RECORD = extern struct { dwStructureSize: u32, dwRecordType: PDH_LOG_TYPE, dwItems: u32, RawBytes: [1]u8, }; pub const PDH_LOG_SERVICE_QUERY_INFO_A = extern struct { dwSize: u32, dwFlags: u32, dwLogQuota: u32, szLogFileCaption: ?PSTR, szDefaultDir: ?PSTR, szBaseFileName: ?PSTR, dwFileType: u32, dwReserved: u32, Anonymous: extern union { Anonymous1: extern struct { PdlAutoNameInterval: u32, PdlAutoNameUnits: u32, PdlCommandFilename: ?PSTR, PdlCounterList: ?PSTR, PdlAutoNameFormat: u32, PdlSampleInterval: u32, PdlLogStartTime: FILETIME, PdlLogEndTime: FILETIME, }, Anonymous2: extern struct { TlNumberOfBuffers: u32, TlMinimumBuffers: u32, TlMaximumBuffers: u32, TlFreeBuffers: u32, TlBufferSize: u32, TlEventsLost: u32, TlLoggerThreadId: u32, TlBuffersWritten: u32, TlLogHandle: u32, TlLogFileName: ?PSTR, }, }, }; pub const PDH_LOG_SERVICE_QUERY_INFO_W = extern struct { dwSize: u32, dwFlags: u32, dwLogQuota: u32, szLogFileCaption: ?PWSTR, szDefaultDir: ?PWSTR, szBaseFileName: ?PWSTR, dwFileType: u32, dwReserved: u32, Anonymous: extern union { Anonymous1: extern struct { PdlAutoNameInterval: u32, PdlAutoNameUnits: u32, PdlCommandFilename: ?PWSTR, PdlCounterList: ?PWSTR, PdlAutoNameFormat: u32, PdlSampleInterval: u32, PdlLogStartTime: FILETIME, PdlLogEndTime: FILETIME, }, Anonymous2: extern struct { TlNumberOfBuffers: u32, TlMinimumBuffers: u32, TlMaximumBuffers: u32, TlFreeBuffers: u32, TlBufferSize: u32, TlEventsLost: u32, TlLoggerThreadId: u32, TlBuffersWritten: u32, TlLogHandle: u32, TlLogFileName: ?PWSTR, }, }, }; pub const CounterPathCallBack = fn( param0: usize, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PDH_BROWSE_DLG_CONFIG_HW = extern struct { _bitfield: u32, hWndOwner: ?HWND, hDataSource: isize, szReturnPathBuffer: ?PWSTR, cchReturnPathLength: u32, pCallBack: ?CounterPathCallBack, dwCallBackArg: usize, CallBackStatus: i32, dwDefaultDetailLevel: PERF_DETAIL, szDialogBoxCaption: ?PWSTR, }; pub const PDH_BROWSE_DLG_CONFIG_HA = extern struct { _bitfield: u32, hWndOwner: ?HWND, hDataSource: isize, szReturnPathBuffer: ?PSTR, cchReturnPathLength: u32, pCallBack: ?CounterPathCallBack, dwCallBackArg: usize, CallBackStatus: i32, dwDefaultDetailLevel: PERF_DETAIL, szDialogBoxCaption: ?PSTR, }; pub const PDH_BROWSE_DLG_CONFIG_W = extern struct { _bitfield: u32, hWndOwner: ?HWND, szDataSource: ?PWSTR, szReturnPathBuffer: ?PWSTR, cchReturnPathLength: u32, pCallBack: ?CounterPathCallBack, dwCallBackArg: usize, CallBackStatus: i32, dwDefaultDetailLevel: PERF_DETAIL, szDialogBoxCaption: ?PWSTR, }; pub const PDH_BROWSE_DLG_CONFIG_A = extern struct { _bitfield: u32, hWndOwner: ?HWND, szDataSource: ?PSTR, szReturnPathBuffer: ?PSTR, cchReturnPathLength: u32, pCallBack: ?CounterPathCallBack, dwCallBackArg: usize, CallBackStatus: i32, dwDefaultDetailLevel: PERF_DETAIL, szDialogBoxCaption: ?PSTR, }; const CLSID_SystemMonitor_Value = Guid.initString("c4d2d8e0-d1dd-11ce-940f-008029004347"); pub const CLSID_SystemMonitor = &CLSID_SystemMonitor_Value; const CLSID_CounterItem_Value = Guid.initString("c4d2d8e0-d1dd-11ce-940f-008029004348"); pub const CLSID_CounterItem = &CLSID_CounterItem_Value; const CLSID_Counters_Value = Guid.initString("b2b066d2-2aac-11cf-942f-008029004347"); pub const CLSID_Counters = &CLSID_Counters_Value; const CLSID_LogFileItem_Value = Guid.initString("16ec5be8-df93-4237-94e4-9ee918111d71"); pub const CLSID_LogFileItem = &CLSID_LogFileItem_Value; const CLSID_LogFiles_Value = Guid.initString("2735d9fd-f6b9-4f19-a5d9-e2d068584bc5"); pub const CLSID_LogFiles = &CLSID_LogFiles_Value; const CLSID_CounterItem2_Value = Guid.initString("43196c62-c31f-4ce3-a02e-79efe0f6a525"); pub const CLSID_CounterItem2 = &CLSID_CounterItem2_Value; const CLSID_SystemMonitor2_Value = Guid.initString("7f30578c-5f38-4612-acfe-6ed04c7b7af8"); pub const CLSID_SystemMonitor2 = &CLSID_SystemMonitor2_Value; const CLSID_AppearPropPage_Value = Guid.initString("e49741e9-93a8-4ab1-8e96-bf4482282e9c"); pub const CLSID_AppearPropPage = &CLSID_AppearPropPage_Value; const CLSID_GeneralPropPage_Value = Guid.initString("c3e5d3d2-1a03-11cf-942d-008029004347"); pub const CLSID_GeneralPropPage = &CLSID_GeneralPropPage_Value; const CLSID_GraphPropPage_Value = Guid.initString("c3e5d3d3-1a03-11cf-942d-008029004347"); pub const CLSID_GraphPropPage = &CLSID_GraphPropPage_Value; const CLSID_SourcePropPage_Value = Guid.initString("0cf32aa1-7571-11d0-93c4-00aa00a3ddea"); pub const CLSID_SourcePropPage = &CLSID_SourcePropPage_Value; const CLSID_CounterPropPage_Value = Guid.initString("cf948561-ede8-11ce-941e-008029004347"); pub const CLSID_CounterPropPage = &CLSID_CounterPropPage_Value; pub const DisplayTypeConstants = enum(i32) { LineGraph = 1, Histogram = 2, Report = 3, ChartArea = 4, ChartStackedArea = 5, }; pub const sysmonLineGraph = DisplayTypeConstants.LineGraph; pub const sysmonHistogram = DisplayTypeConstants.Histogram; pub const sysmonReport = DisplayTypeConstants.Report; pub const sysmonChartArea = DisplayTypeConstants.ChartArea; pub const sysmonChartStackedArea = DisplayTypeConstants.ChartStackedArea; pub const ReportValueTypeConstants = enum(i32) { DefaultValue = 0, CurrentValue = 1, Average = 2, Minimum = 3, Maximum = 4, }; pub const sysmonDefaultValue = ReportValueTypeConstants.DefaultValue; pub const sysmonCurrentValue = ReportValueTypeConstants.CurrentValue; pub const sysmonAverage = ReportValueTypeConstants.Average; pub const sysmonMinimum = ReportValueTypeConstants.Minimum; pub const sysmonMaximum = ReportValueTypeConstants.Maximum; pub const DataSourceTypeConstants = enum(i32) { NullDataSource = -1, CurrentActivity = 1, LogFiles = 2, SqlLog = 3, }; pub const sysmonNullDataSource = DataSourceTypeConstants.NullDataSource; pub const sysmonCurrentActivity = DataSourceTypeConstants.CurrentActivity; pub const sysmonLogFiles = DataSourceTypeConstants.LogFiles; pub const sysmonSqlLog = DataSourceTypeConstants.SqlLog; pub const SysmonFileType = enum(i32) { Html = 1, Report = 2, Csv = 3, Tsv = 4, Blg = 5, RetiredBlg = 6, Gif = 7, }; pub const sysmonFileHtml = SysmonFileType.Html; pub const sysmonFileReport = SysmonFileType.Report; pub const sysmonFileCsv = SysmonFileType.Csv; pub const sysmonFileTsv = SysmonFileType.Tsv; pub const sysmonFileBlg = SysmonFileType.Blg; pub const sysmonFileRetiredBlg = SysmonFileType.RetiredBlg; pub const sysmonFileGif = SysmonFileType.Gif; pub const SysmonDataType = enum(i32) { Avg = 1, Min = 2, Max = 3, Time = 4, Count = 5, }; pub const sysmonDataAvg = SysmonDataType.Avg; pub const sysmonDataMin = SysmonDataType.Min; pub const sysmonDataMax = SysmonDataType.Max; pub const sysmonDataTime = SysmonDataType.Time; pub const sysmonDataCount = SysmonDataType.Count; pub const SysmonBatchReason = enum(i32) { None = 0, AddFiles = 1, AddCounters = 2, AddFilesAutoCounters = 3, }; pub const sysmonBatchNone = SysmonBatchReason.None; pub const sysmonBatchAddFiles = SysmonBatchReason.AddFiles; pub const sysmonBatchAddCounters = SysmonBatchReason.AddCounters; pub const sysmonBatchAddFilesAutoCounters = SysmonBatchReason.AddFilesAutoCounters; const IID_ICounterItem_Value = Guid.initString("771a9520-ee28-11ce-941e-008029004347"); pub const IID_ICounterItem = &IID_ICounterItem_Value; pub const ICounterItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const ICounterItem, pdblValue: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Color: fn( self: *const ICounterItem, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Color: fn( self: *const ICounterItem, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Width: fn( self: *const ICounterItem, iWidth: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Width: fn( self: *const ICounterItem, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LineStyle: fn( self: *const ICounterItem, iLineStyle: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LineStyle: fn( self: *const ICounterItem, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ScaleFactor: fn( self: *const ICounterItem, iScale: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScaleFactor: fn( self: *const ICounterItem, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const ICounterItem, pstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const ICounterItem, Value: ?*f64, Status: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatistics: fn( self: *const ICounterItem, Max: ?*f64, Min: ?*f64, Avg: ?*f64, Status: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_Value(self: *const T, pdblValue: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_Value(@ptrCast(*const ICounterItem, self), pdblValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_put_Color(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).put_Color(@ptrCast(*const ICounterItem, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_Color(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_Color(@ptrCast(*const ICounterItem, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_put_Width(self: *const T, iWidth: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).put_Width(@ptrCast(*const ICounterItem, self), iWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_Width(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_Width(@ptrCast(*const ICounterItem, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_put_LineStyle(self: *const T, iLineStyle: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).put_LineStyle(@ptrCast(*const ICounterItem, self), iLineStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_LineStyle(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_LineStyle(@ptrCast(*const ICounterItem, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_put_ScaleFactor(self: *const T, iScale: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).put_ScaleFactor(@ptrCast(*const ICounterItem, self), iScale); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_ScaleFactor(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_ScaleFactor(@ptrCast(*const ICounterItem, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_get_Path(self: *const T, pstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).get_Path(@ptrCast(*const ICounterItem, self), pstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_GetValue(self: *const T, Value: ?*f64, Status: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).GetValue(@ptrCast(*const ICounterItem, self), Value, Status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem_GetStatistics(self: *const T, Max: ?*f64, Min: ?*f64, Avg: ?*f64, Status: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem.VTable, self.vtable).GetStatistics(@ptrCast(*const ICounterItem, self), Max, Min, Avg, Status); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICounterItem2_Value = Guid.initString("eefcd4e1-ea1c-4435-b7f4-e341ba03b4f9"); pub const IID_ICounterItem2 = &IID_ICounterItem2_Value; pub const ICounterItem2 = extern struct { pub const VTable = extern struct { base: ICounterItem.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Selected: fn( self: *const ICounterItem2, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Selected: fn( self: *const ICounterItem2, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Visible: fn( self: *const ICounterItem2, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Visible: fn( self: *const ICounterItem2, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataAt: fn( self: *const ICounterItem2, iIndex: i32, iWhich: SysmonDataType, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ICounterItem.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem2_put_Selected(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem2.VTable, self.vtable).put_Selected(@ptrCast(*const ICounterItem2, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem2_get_Selected(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem2.VTable, self.vtable).get_Selected(@ptrCast(*const ICounterItem2, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem2_put_Visible(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem2.VTable, self.vtable).put_Visible(@ptrCast(*const ICounterItem2, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem2_get_Visible(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem2.VTable, self.vtable).get_Visible(@ptrCast(*const ICounterItem2, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounterItem2_GetDataAt(self: *const T, iIndex: i32, iWhich: SysmonDataType, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICounterItem2.VTable, self.vtable).GetDataAt(@ptrCast(*const ICounterItem2, self), iIndex, iWhich, pVariant); } };} pub usingnamespace MethodMixin(@This()); }; const IID__ICounterItemUnion_Value = Guid.initString("de1a6b74-9182-4c41-8e2c-24c2cd30ee83"); pub const IID__ICounterItemUnion = &IID__ICounterItemUnion_Value; pub const _ICounterItemUnion = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const _ICounterItemUnion, pdblValue: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Color: fn( self: *const _ICounterItemUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Color: fn( self: *const _ICounterItemUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Width: fn( self: *const _ICounterItemUnion, iWidth: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Width: fn( self: *const _ICounterItemUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LineStyle: fn( self: *const _ICounterItemUnion, iLineStyle: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LineStyle: fn( self: *const _ICounterItemUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ScaleFactor: fn( self: *const _ICounterItemUnion, iScale: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScaleFactor: fn( self: *const _ICounterItemUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const _ICounterItemUnion, pstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const _ICounterItemUnion, Value: ?*f64, Status: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatistics: fn( self: *const _ICounterItemUnion, Max: ?*f64, Min: ?*f64, Avg: ?*f64, Status: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Selected: fn( self: *const _ICounterItemUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Selected: fn( self: *const _ICounterItemUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Visible: fn( self: *const _ICounterItemUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Visible: fn( self: *const _ICounterItemUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataAt: fn( self: *const _ICounterItemUnion, iIndex: i32, iWhich: SysmonDataType, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Value(self: *const T, pdblValue: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Value(@ptrCast(*const _ICounterItemUnion, self), pdblValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_Color(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_Color(@ptrCast(*const _ICounterItemUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Color(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Color(@ptrCast(*const _ICounterItemUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_Width(self: *const T, iWidth: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_Width(@ptrCast(*const _ICounterItemUnion, self), iWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Width(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Width(@ptrCast(*const _ICounterItemUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_LineStyle(self: *const T, iLineStyle: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_LineStyle(@ptrCast(*const _ICounterItemUnion, self), iLineStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_LineStyle(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_LineStyle(@ptrCast(*const _ICounterItemUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_ScaleFactor(self: *const T, iScale: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_ScaleFactor(@ptrCast(*const _ICounterItemUnion, self), iScale); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_ScaleFactor(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_ScaleFactor(@ptrCast(*const _ICounterItemUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Path(self: *const T, pstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Path(@ptrCast(*const _ICounterItemUnion, self), pstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_GetValue(self: *const T, Value: ?*f64, Status: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).GetValue(@ptrCast(*const _ICounterItemUnion, self), Value, Status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_GetStatistics(self: *const T, Max: ?*f64, Min: ?*f64, Avg: ?*f64, Status: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).GetStatistics(@ptrCast(*const _ICounterItemUnion, self), Max, Min, Avg, Status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_Selected(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_Selected(@ptrCast(*const _ICounterItemUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Selected(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Selected(@ptrCast(*const _ICounterItemUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_put_Visible(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).put_Visible(@ptrCast(*const _ICounterItemUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_get_Visible(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).get_Visible(@ptrCast(*const _ICounterItemUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ICounterItemUnion_GetDataAt(self: *const T, iIndex: i32, iWhich: SysmonDataType, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const _ICounterItemUnion.VTable, self.vtable).GetDataAt(@ptrCast(*const _ICounterItemUnion, self), iIndex, iWhich, pVariant); } };} pub usingnamespace MethodMixin(@This()); }; const IID_DICounterItem_Value = Guid.initString("c08c4ff2-0e2e-11cf-942c-008029004347"); pub const IID_DICounterItem = &IID_DICounterItem_Value; pub const DICounterItem = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_ICounters_Value = Guid.initString("79167962-28fc-11cf-942f-008029004347"); pub const IID_ICounters = &IID_ICounters_Value; pub const ICounters = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const ICounters, pLong: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const ICounters, ppIunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const ICounters, index: VARIANT, ppI: ?*?*DICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const ICounters, pathname: ?BSTR, ppI: ?*?*DICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const ICounters, index: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounters_get_Count(self: *const T, pLong: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICounters.VTable, self.vtable).get_Count(@ptrCast(*const ICounters, self), pLong); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounters_get__NewEnum(self: *const T, ppIunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ICounters.VTable, self.vtable).get__NewEnum(@ptrCast(*const ICounters, self), ppIunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounters_get_Item(self: *const T, index: VARIANT, ppI: ?*?*DICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const ICounters.VTable, self.vtable).get_Item(@ptrCast(*const ICounters, self), index, ppI); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounters_Add(self: *const T, pathname: ?BSTR, ppI: ?*?*DICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const ICounters.VTable, self.vtable).Add(@ptrCast(*const ICounters, self), pathname, ppI); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICounters_Remove(self: *const T, index: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICounters.VTable, self.vtable).Remove(@ptrCast(*const ICounters, self), index); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ILogFileItem_Value = Guid.initString("d6b518dd-05c7-418a-89e6-4f9ce8c6841e"); pub const IID_ILogFileItem = &IID_ILogFileItem_Value; pub const ILogFileItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const ILogFileItem, pstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFileItem_get_Path(self: *const T, pstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFileItem.VTable, self.vtable).get_Path(@ptrCast(*const ILogFileItem, self), pstrValue); } };} pub usingnamespace MethodMixin(@This()); }; const IID_DILogFileItem_Value = Guid.initString("8d093ffc-f777-4917-82d1-833fbc54c58f"); pub const IID_DILogFileItem = &IID_DILogFileItem_Value; pub const DILogFileItem = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_ILogFiles_Value = Guid.initString("6a2a97e6-6851-41ea-87ad-2a8225335865"); pub const IID_ILogFiles = &IID_ILogFiles_Value; pub const ILogFiles = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const ILogFiles, pLong: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const ILogFiles, ppIunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const ILogFiles, index: VARIANT, ppI: ?*?*DILogFileItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const ILogFiles, pathname: ?BSTR, ppI: ?*?*DILogFileItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const ILogFiles, index: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFiles_get_Count(self: *const T, pLong: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFiles.VTable, self.vtable).get_Count(@ptrCast(*const ILogFiles, self), pLong); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFiles_get__NewEnum(self: *const T, ppIunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFiles.VTable, self.vtable).get__NewEnum(@ptrCast(*const ILogFiles, self), ppIunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFiles_get_Item(self: *const T, index: VARIANT, ppI: ?*?*DILogFileItem) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFiles.VTable, self.vtable).get_Item(@ptrCast(*const ILogFiles, self), index, ppI); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFiles_Add(self: *const T, pathname: ?BSTR, ppI: ?*?*DILogFileItem) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFiles.VTable, self.vtable).Add(@ptrCast(*const ILogFiles, self), pathname, ppI); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILogFiles_Remove(self: *const T, index: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ILogFiles.VTable, self.vtable).Remove(@ptrCast(*const ILogFiles, self), index); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISystemMonitor_Value = Guid.initString("194eb241-c32c-11cf-9398-00aa00a3ddea"); pub const IID_ISystemMonitor = &IID_ISystemMonitor_Value; pub const ISystemMonitor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Appearance: fn( self: *const ISystemMonitor, iAppearance: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Appearance: fn( self: *const ISystemMonitor, iAppearance: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackColor: fn( self: *const ISystemMonitor, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BackColor: fn( self: *const ISystemMonitor, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BorderStyle: fn( self: *const ISystemMonitor, iBorderStyle: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BorderStyle: fn( self: *const ISystemMonitor, iBorderStyle: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ForeColor: fn( self: *const ISystemMonitor, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ForeColor: fn( self: *const ISystemMonitor, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Font: fn( self: *const ISystemMonitor, ppFont: ?*?*IFontDisp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, putref_Font: fn( self: *const ISystemMonitor, pFont: ?*IFontDisp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Counters: fn( self: *const ISystemMonitor, ppICounters: ?*?*ICounters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowVerticalGrid: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowVerticalGrid: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowHorizontalGrid: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowHorizontalGrid: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowLegend: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowLegend: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowScaleLabels: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowScaleLabels: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowValueBar: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowValueBar: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaximumScale: fn( self: *const ISystemMonitor, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaximumScale: fn( self: *const ISystemMonitor, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinimumScale: fn( self: *const ISystemMonitor, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinimumScale: fn( self: *const ISystemMonitor, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UpdateInterval: fn( self: *const ISystemMonitor, fValue: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UpdateInterval: fn( self: *const ISystemMonitor, pfValue: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayType: fn( self: *const ISystemMonitor, eDisplayType: DisplayTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayType: fn( self: *const ISystemMonitor, peDisplayType: ?*DisplayTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ManualUpdate: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ManualUpdate: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GraphTitle: fn( self: *const ISystemMonitor, bsTitle: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GraphTitle: fn( self: *const ISystemMonitor, pbsTitle: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_YAxisLabel: fn( self: *const ISystemMonitor, bsTitle: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_YAxisLabel: fn( self: *const ISystemMonitor, pbsTitle: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollectSample: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateGraph: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BrowseCounters: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisplayProperties: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Counter: fn( self: *const ISystemMonitor, iIndex: i32, ppICounter: ?*?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddCounter: fn( self: *const ISystemMonitor, bsPath: ?BSTR, ppICounter: ?*?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteCounter: fn( self: *const ISystemMonitor, pCtr: ?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackColorCtl: fn( self: *const ISystemMonitor, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BackColorCtl: fn( self: *const ISystemMonitor, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogFileName: fn( self: *const ISystemMonitor, bsFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFileName: fn( self: *const ISystemMonitor, bsFileName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogViewStart: fn( self: *const ISystemMonitor, StartTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogViewStart: fn( self: *const ISystemMonitor, StartTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogViewStop: fn( self: *const ISystemMonitor, StopTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogViewStop: fn( self: *const ISystemMonitor, StopTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GridColor: fn( self: *const ISystemMonitor, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GridColor: fn( self: *const ISystemMonitor, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TimeBarColor: fn( self: *const ISystemMonitor, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TimeBarColor: fn( self: *const ISystemMonitor, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Highlight: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Highlight: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowToolbar: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowToolbar: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Paste: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Copy: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const ISystemMonitor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReadOnly: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReadOnly: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportValueType: fn( self: *const ISystemMonitor, eReportValueType: ReportValueTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportValueType: fn( self: *const ISystemMonitor, peReportValueType: ?*ReportValueTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MonitorDuplicateInstances: fn( self: *const ISystemMonitor, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MonitorDuplicateInstances: fn( self: *const ISystemMonitor, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayFilter: fn( self: *const ISystemMonitor, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayFilter: fn( self: *const ISystemMonitor, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFiles: fn( self: *const ISystemMonitor, ppILogFiles: ?*?*ILogFiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataSourceType: fn( self: *const ISystemMonitor, eDataSourceType: DataSourceTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataSourceType: fn( self: *const ISystemMonitor, peDataSourceType: ?*DataSourceTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SqlDsnName: fn( self: *const ISystemMonitor, bsSqlDsnName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SqlDsnName: fn( self: *const ISystemMonitor, bsSqlDsnName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SqlLogSetName: fn( self: *const ISystemMonitor, bsSqlLogSetName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SqlLogSetName: fn( self: *const ISystemMonitor, bsSqlLogSetName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_Appearance(self: *const T, iAppearance: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_Appearance(@ptrCast(*const ISystemMonitor, self), iAppearance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_Appearance(self: *const T, iAppearance: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_Appearance(@ptrCast(*const ISystemMonitor, self), iAppearance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_BackColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_BackColor(@ptrCast(*const ISystemMonitor, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_BackColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_BackColor(@ptrCast(*const ISystemMonitor, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_BorderStyle(self: *const T, iBorderStyle: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_BorderStyle(@ptrCast(*const ISystemMonitor, self), iBorderStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_BorderStyle(self: *const T, iBorderStyle: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_BorderStyle(@ptrCast(*const ISystemMonitor, self), iBorderStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ForeColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ForeColor(@ptrCast(*const ISystemMonitor, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ForeColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ForeColor(@ptrCast(*const ISystemMonitor, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_Font(self: *const T, ppFont: ?*?*IFontDisp) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_Font(@ptrCast(*const ISystemMonitor, self), ppFont); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_putref_Font(self: *const T, pFont: ?*IFontDisp) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).putref_Font(@ptrCast(*const ISystemMonitor, self), pFont); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_Counters(self: *const T, ppICounters: ?*?*ICounters) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_Counters(@ptrCast(*const ISystemMonitor, self), ppICounters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowVerticalGrid(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowVerticalGrid(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowVerticalGrid(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowVerticalGrid(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowHorizontalGrid(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowHorizontalGrid(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowHorizontalGrid(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowHorizontalGrid(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowLegend(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowLegend(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowLegend(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowLegend(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowScaleLabels(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowScaleLabels(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowScaleLabels(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowScaleLabels(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowValueBar(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowValueBar(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowValueBar(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowValueBar(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_MaximumScale(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_MaximumScale(@ptrCast(*const ISystemMonitor, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_MaximumScale(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_MaximumScale(@ptrCast(*const ISystemMonitor, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_MinimumScale(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_MinimumScale(@ptrCast(*const ISystemMonitor, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_MinimumScale(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_MinimumScale(@ptrCast(*const ISystemMonitor, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_UpdateInterval(self: *const T, fValue: f32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_UpdateInterval(@ptrCast(*const ISystemMonitor, self), fValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_UpdateInterval(self: *const T, pfValue: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_UpdateInterval(@ptrCast(*const ISystemMonitor, self), pfValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_DisplayType(self: *const T, eDisplayType: DisplayTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_DisplayType(@ptrCast(*const ISystemMonitor, self), eDisplayType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_DisplayType(self: *const T, peDisplayType: ?*DisplayTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_DisplayType(@ptrCast(*const ISystemMonitor, self), peDisplayType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ManualUpdate(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ManualUpdate(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ManualUpdate(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ManualUpdate(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_GraphTitle(self: *const T, bsTitle: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_GraphTitle(@ptrCast(*const ISystemMonitor, self), bsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_GraphTitle(self: *const T, pbsTitle: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_GraphTitle(@ptrCast(*const ISystemMonitor, self), pbsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_YAxisLabel(self: *const T, bsTitle: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_YAxisLabel(@ptrCast(*const ISystemMonitor, self), bsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_YAxisLabel(self: *const T, pbsTitle: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_YAxisLabel(@ptrCast(*const ISystemMonitor, self), pbsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_CollectSample(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).CollectSample(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_UpdateGraph(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).UpdateGraph(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_BrowseCounters(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).BrowseCounters(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_DisplayProperties(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).DisplayProperties(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_Counter(self: *const T, iIndex: i32, ppICounter: ?*?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).Counter(@ptrCast(*const ISystemMonitor, self), iIndex, ppICounter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_AddCounter(self: *const T, bsPath: ?BSTR, ppICounter: ?*?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).AddCounter(@ptrCast(*const ISystemMonitor, self), bsPath, ppICounter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_DeleteCounter(self: *const T, pCtr: ?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).DeleteCounter(@ptrCast(*const ISystemMonitor, self), pCtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_BackColorCtl(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_BackColorCtl(@ptrCast(*const ISystemMonitor, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_BackColorCtl(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_BackColorCtl(@ptrCast(*const ISystemMonitor, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_LogFileName(self: *const T, bsFileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_LogFileName(@ptrCast(*const ISystemMonitor, self), bsFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_LogFileName(self: *const T, bsFileName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_LogFileName(@ptrCast(*const ISystemMonitor, self), bsFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_LogViewStart(self: *const T, StartTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_LogViewStart(@ptrCast(*const ISystemMonitor, self), StartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_LogViewStart(self: *const T, StartTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_LogViewStart(@ptrCast(*const ISystemMonitor, self), StartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_LogViewStop(self: *const T, StopTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_LogViewStop(@ptrCast(*const ISystemMonitor, self), StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_LogViewStop(self: *const T, StopTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_LogViewStop(@ptrCast(*const ISystemMonitor, self), StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_GridColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_GridColor(@ptrCast(*const ISystemMonitor, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_GridColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_GridColor(@ptrCast(*const ISystemMonitor, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_TimeBarColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_TimeBarColor(@ptrCast(*const ISystemMonitor, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_TimeBarColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_TimeBarColor(@ptrCast(*const ISystemMonitor, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_Highlight(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_Highlight(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_Highlight(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_Highlight(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ShowToolbar(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ShowToolbar(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ShowToolbar(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ShowToolbar(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_Paste(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).Paste(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_Copy(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).Copy(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).Reset(@ptrCast(*const ISystemMonitor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ReadOnly(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ReadOnly(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ReadOnly(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ReadOnly(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_ReportValueType(self: *const T, eReportValueType: ReportValueTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_ReportValueType(@ptrCast(*const ISystemMonitor, self), eReportValueType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_ReportValueType(self: *const T, peReportValueType: ?*ReportValueTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_ReportValueType(@ptrCast(*const ISystemMonitor, self), peReportValueType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_MonitorDuplicateInstances(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_MonitorDuplicateInstances(@ptrCast(*const ISystemMonitor, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_MonitorDuplicateInstances(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_MonitorDuplicateInstances(@ptrCast(*const ISystemMonitor, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_DisplayFilter(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_DisplayFilter(@ptrCast(*const ISystemMonitor, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_DisplayFilter(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_DisplayFilter(@ptrCast(*const ISystemMonitor, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_LogFiles(self: *const T, ppILogFiles: ?*?*ILogFiles) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_LogFiles(@ptrCast(*const ISystemMonitor, self), ppILogFiles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_DataSourceType(self: *const T, eDataSourceType: DataSourceTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_DataSourceType(@ptrCast(*const ISystemMonitor, self), eDataSourceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_DataSourceType(self: *const T, peDataSourceType: ?*DataSourceTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_DataSourceType(@ptrCast(*const ISystemMonitor, self), peDataSourceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_SqlDsnName(self: *const T, bsSqlDsnName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_SqlDsnName(@ptrCast(*const ISystemMonitor, self), bsSqlDsnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_SqlDsnName(self: *const T, bsSqlDsnName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_SqlDsnName(@ptrCast(*const ISystemMonitor, self), bsSqlDsnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_put_SqlLogSetName(self: *const T, bsSqlLogSetName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).put_SqlLogSetName(@ptrCast(*const ISystemMonitor, self), bsSqlLogSetName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor_get_SqlLogSetName(self: *const T, bsSqlLogSetName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor.VTable, self.vtable).get_SqlLogSetName(@ptrCast(*const ISystemMonitor, self), bsSqlLogSetName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISystemMonitor2_Value = Guid.initString("08e3206a-5fd2-4fde-a8a5-8cb3b63d2677"); pub const IID_ISystemMonitor2 = &IID_ISystemMonitor2_Value; pub const ISystemMonitor2 = extern struct { pub const VTable = extern struct { base: ISystemMonitor.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnableDigitGrouping: fn( self: *const ISystemMonitor2, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnableDigitGrouping: fn( self: *const ISystemMonitor2, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnableToolTips: fn( self: *const ISystemMonitor2, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnableToolTips: fn( self: *const ISystemMonitor2, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowTimeAxisLabels: fn( self: *const ISystemMonitor2, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowTimeAxisLabels: fn( self: *const ISystemMonitor2, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ChartScroll: fn( self: *const ISystemMonitor2, bScroll: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ChartScroll: fn( self: *const ISystemMonitor2, pbScroll: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataPointCount: fn( self: *const ISystemMonitor2, iNewCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataPointCount: fn( self: *const ISystemMonitor2, piDataPointCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ScaleToFit: fn( self: *const ISystemMonitor2, bSelectedCountersOnly: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveAs: fn( self: *const ISystemMonitor2, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Relog: fn( self: *const ISystemMonitor2, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, iFilter: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearData: fn( self: *const ISystemMonitor2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogSourceStartTime: fn( self: *const ISystemMonitor2, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogSourceStopTime: fn( self: *const ISystemMonitor2, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLogViewRange: fn( self: *const ISystemMonitor2, StartTime: f64, StopTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLogViewRange: fn( self: *const ISystemMonitor2, StartTime: ?*f64, StopTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BatchingLock: fn( self: *const ISystemMonitor2, fLock: i16, eBatchReason: SysmonBatchReason, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadSettings: fn( self: *const ISystemMonitor2, bstrSettingFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ISystemMonitor.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_put_EnableDigitGrouping(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).put_EnableDigitGrouping(@ptrCast(*const ISystemMonitor2, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_EnableDigitGrouping(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_EnableDigitGrouping(@ptrCast(*const ISystemMonitor2, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_put_EnableToolTips(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).put_EnableToolTips(@ptrCast(*const ISystemMonitor2, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_EnableToolTips(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_EnableToolTips(@ptrCast(*const ISystemMonitor2, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_put_ShowTimeAxisLabels(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).put_ShowTimeAxisLabels(@ptrCast(*const ISystemMonitor2, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_ShowTimeAxisLabels(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_ShowTimeAxisLabels(@ptrCast(*const ISystemMonitor2, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_put_ChartScroll(self: *const T, bScroll: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).put_ChartScroll(@ptrCast(*const ISystemMonitor2, self), bScroll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_ChartScroll(self: *const T, pbScroll: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_ChartScroll(@ptrCast(*const ISystemMonitor2, self), pbScroll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_put_DataPointCount(self: *const T, iNewCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).put_DataPointCount(@ptrCast(*const ISystemMonitor2, self), iNewCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_DataPointCount(self: *const T, piDataPointCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_DataPointCount(@ptrCast(*const ISystemMonitor2, self), piDataPointCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_ScaleToFit(self: *const T, bSelectedCountersOnly: i16) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).ScaleToFit(@ptrCast(*const ISystemMonitor2, self), bSelectedCountersOnly); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_SaveAs(self: *const T, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).SaveAs(@ptrCast(*const ISystemMonitor2, self), bstrFileName, eSysmonFileType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_Relog(self: *const T, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, iFilter: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).Relog(@ptrCast(*const ISystemMonitor2, self), bstrFileName, eSysmonFileType, iFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_ClearData(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).ClearData(@ptrCast(*const ISystemMonitor2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_LogSourceStartTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_LogSourceStartTime(@ptrCast(*const ISystemMonitor2, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_get_LogSourceStopTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).get_LogSourceStopTime(@ptrCast(*const ISystemMonitor2, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_SetLogViewRange(self: *const T, StartTime: f64, StopTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).SetLogViewRange(@ptrCast(*const ISystemMonitor2, self), StartTime, StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_GetLogViewRange(self: *const T, StartTime: ?*f64, StopTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).GetLogViewRange(@ptrCast(*const ISystemMonitor2, self), StartTime, StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_BatchingLock(self: *const T, fLock: i16, eBatchReason: SysmonBatchReason) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).BatchingLock(@ptrCast(*const ISystemMonitor2, self), fLock, eBatchReason); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitor2_LoadSettings(self: *const T, bstrSettingFileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISystemMonitor2.VTable, self.vtable).LoadSettings(@ptrCast(*const ISystemMonitor2, self), bstrSettingFileName); } };} pub usingnamespace MethodMixin(@This()); }; const IID__ISystemMonitorUnion_Value = Guid.initString("c8a77338-265f-4de5-aa25-c7da1ce5a8f4"); pub const IID__ISystemMonitorUnion = &IID__ISystemMonitorUnion_Value; pub const _ISystemMonitorUnion = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Appearance: fn( self: *const _ISystemMonitorUnion, iAppearance: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Appearance: fn( self: *const _ISystemMonitorUnion, iAppearance: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackColor: fn( self: *const _ISystemMonitorUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BackColor: fn( self: *const _ISystemMonitorUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BorderStyle: fn( self: *const _ISystemMonitorUnion, iBorderStyle: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BorderStyle: fn( self: *const _ISystemMonitorUnion, iBorderStyle: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ForeColor: fn( self: *const _ISystemMonitorUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ForeColor: fn( self: *const _ISystemMonitorUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Font: fn( self: *const _ISystemMonitorUnion, ppFont: ?*?*IFontDisp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, putref_Font: fn( self: *const _ISystemMonitorUnion, pFont: ?*IFontDisp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Counters: fn( self: *const _ISystemMonitorUnion, ppICounters: ?*?*ICounters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowVerticalGrid: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowVerticalGrid: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowHorizontalGrid: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowHorizontalGrid: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowLegend: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowLegend: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowScaleLabels: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowScaleLabels: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowValueBar: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowValueBar: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaximumScale: fn( self: *const _ISystemMonitorUnion, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaximumScale: fn( self: *const _ISystemMonitorUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinimumScale: fn( self: *const _ISystemMonitorUnion, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinimumScale: fn( self: *const _ISystemMonitorUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UpdateInterval: fn( self: *const _ISystemMonitorUnion, fValue: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UpdateInterval: fn( self: *const _ISystemMonitorUnion, pfValue: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayType: fn( self: *const _ISystemMonitorUnion, eDisplayType: DisplayTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayType: fn( self: *const _ISystemMonitorUnion, peDisplayType: ?*DisplayTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ManualUpdate: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ManualUpdate: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GraphTitle: fn( self: *const _ISystemMonitorUnion, bsTitle: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GraphTitle: fn( self: *const _ISystemMonitorUnion, pbsTitle: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_YAxisLabel: fn( self: *const _ISystemMonitorUnion, bsTitle: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_YAxisLabel: fn( self: *const _ISystemMonitorUnion, pbsTitle: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollectSample: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateGraph: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BrowseCounters: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisplayProperties: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Counter: fn( self: *const _ISystemMonitorUnion, iIndex: i32, ppICounter: ?*?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddCounter: fn( self: *const _ISystemMonitorUnion, bsPath: ?BSTR, ppICounter: ?*?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteCounter: fn( self: *const _ISystemMonitorUnion, pCtr: ?*ICounterItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BackColorCtl: fn( self: *const _ISystemMonitorUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BackColorCtl: fn( self: *const _ISystemMonitorUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogFileName: fn( self: *const _ISystemMonitorUnion, bsFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFileName: fn( self: *const _ISystemMonitorUnion, bsFileName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogViewStart: fn( self: *const _ISystemMonitorUnion, StartTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogViewStart: fn( self: *const _ISystemMonitorUnion, StartTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LogViewStop: fn( self: *const _ISystemMonitorUnion, StopTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogViewStop: fn( self: *const _ISystemMonitorUnion, StopTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GridColor: fn( self: *const _ISystemMonitorUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GridColor: fn( self: *const _ISystemMonitorUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TimeBarColor: fn( self: *const _ISystemMonitorUnion, pColor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TimeBarColor: fn( self: *const _ISystemMonitorUnion, Color: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Highlight: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Highlight: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowToolbar: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowToolbar: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Paste: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Copy: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReadOnly: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReadOnly: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportValueType: fn( self: *const _ISystemMonitorUnion, eReportValueType: ReportValueTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportValueType: fn( self: *const _ISystemMonitorUnion, peReportValueType: ?*ReportValueTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MonitorDuplicateInstances: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MonitorDuplicateInstances: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayFilter: fn( self: *const _ISystemMonitorUnion, iValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayFilter: fn( self: *const _ISystemMonitorUnion, piValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogFiles: fn( self: *const _ISystemMonitorUnion, ppILogFiles: ?*?*ILogFiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataSourceType: fn( self: *const _ISystemMonitorUnion, eDataSourceType: DataSourceTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataSourceType: fn( self: *const _ISystemMonitorUnion, peDataSourceType: ?*DataSourceTypeConstants, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SqlDsnName: fn( self: *const _ISystemMonitorUnion, bsSqlDsnName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SqlDsnName: fn( self: *const _ISystemMonitorUnion, bsSqlDsnName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SqlLogSetName: fn( self: *const _ISystemMonitorUnion, bsSqlLogSetName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SqlLogSetName: fn( self: *const _ISystemMonitorUnion, bsSqlLogSetName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnableDigitGrouping: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnableDigitGrouping: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnableToolTips: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnableToolTips: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ShowTimeAxisLabels: fn( self: *const _ISystemMonitorUnion, bState: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ShowTimeAxisLabels: fn( self: *const _ISystemMonitorUnion, pbState: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ChartScroll: fn( self: *const _ISystemMonitorUnion, bScroll: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ChartScroll: fn( self: *const _ISystemMonitorUnion, pbScroll: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DataPointCount: fn( self: *const _ISystemMonitorUnion, iNewCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataPointCount: fn( self: *const _ISystemMonitorUnion, piDataPointCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ScaleToFit: fn( self: *const _ISystemMonitorUnion, bSelectedCountersOnly: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveAs: fn( self: *const _ISystemMonitorUnion, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Relog: fn( self: *const _ISystemMonitorUnion, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, iFilter: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearData: fn( self: *const _ISystemMonitorUnion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogSourceStartTime: fn( self: *const _ISystemMonitorUnion, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LogSourceStopTime: fn( self: *const _ISystemMonitorUnion, pDate: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLogViewRange: fn( self: *const _ISystemMonitorUnion, StartTime: f64, StopTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLogViewRange: fn( self: *const _ISystemMonitorUnion, StartTime: ?*f64, StopTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BatchingLock: fn( self: *const _ISystemMonitorUnion, fLock: i16, eBatchReason: SysmonBatchReason, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadSettings: fn( self: *const _ISystemMonitorUnion, bstrSettingFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_Appearance(self: *const T, iAppearance: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_Appearance(@ptrCast(*const _ISystemMonitorUnion, self), iAppearance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_Appearance(self: *const T, iAppearance: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_Appearance(@ptrCast(*const _ISystemMonitorUnion, self), iAppearance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_BackColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_BackColor(@ptrCast(*const _ISystemMonitorUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_BackColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_BackColor(@ptrCast(*const _ISystemMonitorUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_BorderStyle(self: *const T, iBorderStyle: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_BorderStyle(@ptrCast(*const _ISystemMonitorUnion, self), iBorderStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_BorderStyle(self: *const T, iBorderStyle: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_BorderStyle(@ptrCast(*const _ISystemMonitorUnion, self), iBorderStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ForeColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ForeColor(@ptrCast(*const _ISystemMonitorUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ForeColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ForeColor(@ptrCast(*const _ISystemMonitorUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_Font(self: *const T, ppFont: ?*?*IFontDisp) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_Font(@ptrCast(*const _ISystemMonitorUnion, self), ppFont); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_putref_Font(self: *const T, pFont: ?*IFontDisp) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).putref_Font(@ptrCast(*const _ISystemMonitorUnion, self), pFont); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_Counters(self: *const T, ppICounters: ?*?*ICounters) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_Counters(@ptrCast(*const _ISystemMonitorUnion, self), ppICounters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowVerticalGrid(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowVerticalGrid(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowVerticalGrid(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowVerticalGrid(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowHorizontalGrid(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowHorizontalGrid(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowHorizontalGrid(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowHorizontalGrid(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowLegend(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowLegend(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowLegend(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowLegend(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowScaleLabels(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowScaleLabels(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowScaleLabels(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowScaleLabels(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowValueBar(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowValueBar(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowValueBar(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowValueBar(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_MaximumScale(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_MaximumScale(@ptrCast(*const _ISystemMonitorUnion, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_MaximumScale(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_MaximumScale(@ptrCast(*const _ISystemMonitorUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_MinimumScale(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_MinimumScale(@ptrCast(*const _ISystemMonitorUnion, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_MinimumScale(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_MinimumScale(@ptrCast(*const _ISystemMonitorUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_UpdateInterval(self: *const T, fValue: f32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_UpdateInterval(@ptrCast(*const _ISystemMonitorUnion, self), fValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_UpdateInterval(self: *const T, pfValue: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_UpdateInterval(@ptrCast(*const _ISystemMonitorUnion, self), pfValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_DisplayType(self: *const T, eDisplayType: DisplayTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_DisplayType(@ptrCast(*const _ISystemMonitorUnion, self), eDisplayType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_DisplayType(self: *const T, peDisplayType: ?*DisplayTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_DisplayType(@ptrCast(*const _ISystemMonitorUnion, self), peDisplayType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ManualUpdate(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ManualUpdate(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ManualUpdate(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ManualUpdate(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_GraphTitle(self: *const T, bsTitle: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_GraphTitle(@ptrCast(*const _ISystemMonitorUnion, self), bsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_GraphTitle(self: *const T, pbsTitle: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_GraphTitle(@ptrCast(*const _ISystemMonitorUnion, self), pbsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_YAxisLabel(self: *const T, bsTitle: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_YAxisLabel(@ptrCast(*const _ISystemMonitorUnion, self), bsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_YAxisLabel(self: *const T, pbsTitle: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_YAxisLabel(@ptrCast(*const _ISystemMonitorUnion, self), pbsTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_CollectSample(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).CollectSample(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_UpdateGraph(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).UpdateGraph(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_BrowseCounters(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).BrowseCounters(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_DisplayProperties(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).DisplayProperties(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_Counter(self: *const T, iIndex: i32, ppICounter: ?*?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).Counter(@ptrCast(*const _ISystemMonitorUnion, self), iIndex, ppICounter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_AddCounter(self: *const T, bsPath: ?BSTR, ppICounter: ?*?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).AddCounter(@ptrCast(*const _ISystemMonitorUnion, self), bsPath, ppICounter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_DeleteCounter(self: *const T, pCtr: ?*ICounterItem) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).DeleteCounter(@ptrCast(*const _ISystemMonitorUnion, self), pCtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_BackColorCtl(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_BackColorCtl(@ptrCast(*const _ISystemMonitorUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_BackColorCtl(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_BackColorCtl(@ptrCast(*const _ISystemMonitorUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_LogFileName(self: *const T, bsFileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_LogFileName(@ptrCast(*const _ISystemMonitorUnion, self), bsFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogFileName(self: *const T, bsFileName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogFileName(@ptrCast(*const _ISystemMonitorUnion, self), bsFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_LogViewStart(self: *const T, StartTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_LogViewStart(@ptrCast(*const _ISystemMonitorUnion, self), StartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogViewStart(self: *const T, StartTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogViewStart(@ptrCast(*const _ISystemMonitorUnion, self), StartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_LogViewStop(self: *const T, StopTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_LogViewStop(@ptrCast(*const _ISystemMonitorUnion, self), StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogViewStop(self: *const T, StopTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogViewStop(@ptrCast(*const _ISystemMonitorUnion, self), StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_GridColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_GridColor(@ptrCast(*const _ISystemMonitorUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_GridColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_GridColor(@ptrCast(*const _ISystemMonitorUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_TimeBarColor(self: *const T, pColor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_TimeBarColor(@ptrCast(*const _ISystemMonitorUnion, self), pColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_TimeBarColor(self: *const T, Color: u32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_TimeBarColor(@ptrCast(*const _ISystemMonitorUnion, self), Color); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_Highlight(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_Highlight(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_Highlight(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_Highlight(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowToolbar(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowToolbar(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowToolbar(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowToolbar(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_Paste(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).Paste(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_Copy(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).Copy(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).Reset(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ReadOnly(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ReadOnly(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ReadOnly(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ReadOnly(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ReportValueType(self: *const T, eReportValueType: ReportValueTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ReportValueType(@ptrCast(*const _ISystemMonitorUnion, self), eReportValueType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ReportValueType(self: *const T, peReportValueType: ?*ReportValueTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ReportValueType(@ptrCast(*const _ISystemMonitorUnion, self), peReportValueType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_MonitorDuplicateInstances(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_MonitorDuplicateInstances(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_MonitorDuplicateInstances(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_MonitorDuplicateInstances(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_DisplayFilter(self: *const T, iValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_DisplayFilter(@ptrCast(*const _ISystemMonitorUnion, self), iValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_DisplayFilter(self: *const T, piValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_DisplayFilter(@ptrCast(*const _ISystemMonitorUnion, self), piValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogFiles(self: *const T, ppILogFiles: ?*?*ILogFiles) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogFiles(@ptrCast(*const _ISystemMonitorUnion, self), ppILogFiles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_DataSourceType(self: *const T, eDataSourceType: DataSourceTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_DataSourceType(@ptrCast(*const _ISystemMonitorUnion, self), eDataSourceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_DataSourceType(self: *const T, peDataSourceType: ?*DataSourceTypeConstants) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_DataSourceType(@ptrCast(*const _ISystemMonitorUnion, self), peDataSourceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_SqlDsnName(self: *const T, bsSqlDsnName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_SqlDsnName(@ptrCast(*const _ISystemMonitorUnion, self), bsSqlDsnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_SqlDsnName(self: *const T, bsSqlDsnName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_SqlDsnName(@ptrCast(*const _ISystemMonitorUnion, self), bsSqlDsnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_SqlLogSetName(self: *const T, bsSqlLogSetName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_SqlLogSetName(@ptrCast(*const _ISystemMonitorUnion, self), bsSqlLogSetName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_SqlLogSetName(self: *const T, bsSqlLogSetName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_SqlLogSetName(@ptrCast(*const _ISystemMonitorUnion, self), bsSqlLogSetName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_EnableDigitGrouping(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_EnableDigitGrouping(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_EnableDigitGrouping(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_EnableDigitGrouping(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_EnableToolTips(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_EnableToolTips(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_EnableToolTips(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_EnableToolTips(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ShowTimeAxisLabels(self: *const T, bState: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ShowTimeAxisLabels(@ptrCast(*const _ISystemMonitorUnion, self), bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ShowTimeAxisLabels(self: *const T, pbState: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ShowTimeAxisLabels(@ptrCast(*const _ISystemMonitorUnion, self), pbState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_ChartScroll(self: *const T, bScroll: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_ChartScroll(@ptrCast(*const _ISystemMonitorUnion, self), bScroll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_ChartScroll(self: *const T, pbScroll: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_ChartScroll(@ptrCast(*const _ISystemMonitorUnion, self), pbScroll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_put_DataPointCount(self: *const T, iNewCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).put_DataPointCount(@ptrCast(*const _ISystemMonitorUnion, self), iNewCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_DataPointCount(self: *const T, piDataPointCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_DataPointCount(@ptrCast(*const _ISystemMonitorUnion, self), piDataPointCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_ScaleToFit(self: *const T, bSelectedCountersOnly: i16) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).ScaleToFit(@ptrCast(*const _ISystemMonitorUnion, self), bSelectedCountersOnly); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_SaveAs(self: *const T, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).SaveAs(@ptrCast(*const _ISystemMonitorUnion, self), bstrFileName, eSysmonFileType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_Relog(self: *const T, bstrFileName: ?BSTR, eSysmonFileType: SysmonFileType, iFilter: i32) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).Relog(@ptrCast(*const _ISystemMonitorUnion, self), bstrFileName, eSysmonFileType, iFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_ClearData(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).ClearData(@ptrCast(*const _ISystemMonitorUnion, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogSourceStartTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogSourceStartTime(@ptrCast(*const _ISystemMonitorUnion, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_get_LogSourceStopTime(self: *const T, pDate: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).get_LogSourceStopTime(@ptrCast(*const _ISystemMonitorUnion, self), pDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_SetLogViewRange(self: *const T, StartTime: f64, StopTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).SetLogViewRange(@ptrCast(*const _ISystemMonitorUnion, self), StartTime, StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_GetLogViewRange(self: *const T, StartTime: ?*f64, StopTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).GetLogViewRange(@ptrCast(*const _ISystemMonitorUnion, self), StartTime, StopTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_BatchingLock(self: *const T, fLock: i16, eBatchReason: SysmonBatchReason) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).BatchingLock(@ptrCast(*const _ISystemMonitorUnion, self), fLock, eBatchReason); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _ISystemMonitorUnion_LoadSettings(self: *const T, bstrSettingFileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _ISystemMonitorUnion.VTable, self.vtable).LoadSettings(@ptrCast(*const _ISystemMonitorUnion, self), bstrSettingFileName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_DISystemMonitor_Value = Guid.initString("13d73d81-c32e-11cf-9398-00aa00a3ddea"); pub const IID_DISystemMonitor = &IID_DISystemMonitor_Value; pub const DISystemMonitor = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_DISystemMonitorInternal_Value = Guid.initString("194eb242-c32c-11cf-9398-00aa00a3ddea"); pub const IID_DISystemMonitorInternal = &IID_DISystemMonitorInternal_Value; pub const DISystemMonitorInternal = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_ISystemMonitorEvents_Value = Guid.initString("ee660ea0-4abd-11cf-943a-008029004347"); pub const IID_ISystemMonitorEvents = &IID_ISystemMonitorEvents_Value; pub const ISystemMonitorEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnCounterSelected: fn( self: *const ISystemMonitorEvents, Index: i32, ) callconv(@import("std").os.windows.WINAPI) void, OnCounterAdded: fn( self: *const ISystemMonitorEvents, Index: i32, ) callconv(@import("std").os.windows.WINAPI) void, OnCounterDeleted: fn( self: *const ISystemMonitorEvents, Index: i32, ) callconv(@import("std").os.windows.WINAPI) void, OnSampleCollected: fn( self: *const ISystemMonitorEvents, ) callconv(@import("std").os.windows.WINAPI) void, OnDblClick: fn( self: *const ISystemMonitorEvents, Index: i32, ) callconv(@import("std").os.windows.WINAPI) void, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitorEvents_OnCounterSelected(self: *const T, Index: i32) callconv(.Inline) void { return @ptrCast(*const ISystemMonitorEvents.VTable, self.vtable).OnCounterSelected(@ptrCast(*const ISystemMonitorEvents, self), Index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitorEvents_OnCounterAdded(self: *const T, Index: i32) callconv(.Inline) void { return @ptrCast(*const ISystemMonitorEvents.VTable, self.vtable).OnCounterAdded(@ptrCast(*const ISystemMonitorEvents, self), Index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitorEvents_OnCounterDeleted(self: *const T, Index: i32) callconv(.Inline) void { return @ptrCast(*const ISystemMonitorEvents.VTable, self.vtable).OnCounterDeleted(@ptrCast(*const ISystemMonitorEvents, self), Index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitorEvents_OnSampleCollected(self: *const T) callconv(.Inline) void { return @ptrCast(*const ISystemMonitorEvents.VTable, self.vtable).OnSampleCollected(@ptrCast(*const ISystemMonitorEvents, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISystemMonitorEvents_OnDblClick(self: *const T, Index: i32) callconv(.Inline) void { return @ptrCast(*const ISystemMonitorEvents.VTable, self.vtable).OnDblClick(@ptrCast(*const ISystemMonitorEvents, self), Index); } };} pub usingnamespace MethodMixin(@This()); }; const IID_DISystemMonitorEvents_Value = Guid.initString("84979930-4ab3-11cf-943a-008029004347"); pub const IID_DISystemMonitorEvents = &IID_DISystemMonitorEvents_Value; pub const DISystemMonitorEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; pub const PERF_OBJECT_TYPE = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { TotalByteLength: u32, DefinitionLength: u32, HeaderLength: u32, ObjectNameTitleIndex: u32, ObjectNameTitle: u32, ObjectHelpTitleIndex: u32, ObjectHelpTitle: u32, DetailLevel: u32, NumCounters: u32, DefaultCounter: i32, NumInstances: i32, CodePage: u32, PerfTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, }, .X86 => extern struct { TotalByteLength: u32, DefinitionLength: u32, HeaderLength: u32, ObjectNameTitleIndex: u32, ObjectNameTitle: ?PWSTR, ObjectHelpTitleIndex: u32, ObjectHelpTitle: ?PWSTR, DetailLevel: u32, NumCounters: u32, DefaultCounter: i32, NumInstances: i32, CodePage: u32, PerfTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, }, }; pub const PERF_COUNTER_DEFINITION = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { ByteLength: u32, CounterNameTitleIndex: u32, CounterNameTitle: u32, CounterHelpTitleIndex: u32, CounterHelpTitle: u32, DefaultScale: i32, DetailLevel: u32, CounterType: u32, CounterSize: u32, CounterOffset: u32, }, .X86 => extern struct { ByteLength: u32, CounterNameTitleIndex: u32, CounterNameTitle: ?PWSTR, CounterHelpTitleIndex: u32, CounterHelpTitle: ?PWSTR, DefaultScale: i32, DetailLevel: u32, CounterType: u32, CounterSize: u32, CounterOffset: u32, }, }; //-------------------------------------------------------------------------------- // Section: Functions (135) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn QueryPerformanceCounter( lpPerformanceCount: ?*LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn QueryPerformanceFrequency( lpFrequency: ?*LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "loadperf" fn InstallPerfDllW( szComputerName: ?[*:0]const u16, lpIniFile: ?[*:0]const u16, dwFlags: usize, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn InstallPerfDllA( szComputerName: ?[*:0]const u8, lpIniFile: ?[*:0]const u8, dwFlags: usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "loadperf" fn LoadPerfCounterTextStringsA( lpCommandLine: ?PSTR, bQuietModeArg: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "loadperf" fn LoadPerfCounterTextStringsW( lpCommandLine: ?PWSTR, bQuietModeArg: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "loadperf" fn UnloadPerfCounterTextStringsW( lpCommandLine: ?PWSTR, bQuietModeArg: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "loadperf" fn UnloadPerfCounterTextStringsA( lpCommandLine: ?PSTR, bQuietModeArg: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn UpdatePerfNameFilesA( szNewCtrFilePath: ?[*:0]const u8, szNewHlpFilePath: ?[*:0]const u8, szLanguageID: ?PSTR, dwFlags: usize, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn UpdatePerfNameFilesW( szNewCtrFilePath: ?[*:0]const u16, szNewHlpFilePath: ?[*:0]const u16, szLanguageID: ?PWSTR, dwFlags: usize, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn SetServiceAsTrustedA( szReserved: ?[*:0]const u8, szServiceName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn SetServiceAsTrustedW( szReserved: ?[*:0]const u16, szServiceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn BackupPerfRegistryToFileW( szFileName: ?[*:0]const u16, szCommentString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "loadperf" fn RestorePerfRegistryFromFileW( szFileName: ?[*:0]const u16, szLangId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfStartProvider( ProviderGuid: ?*Guid, ControlCallback: ?PERFLIBREQUEST, phProvider: ?*PerfProviderHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfStartProviderEx( ProviderGuid: ?*Guid, ProviderContext: ?*PERF_PROVIDER_CONTEXT, Provider: ?*PerfProviderHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfStopProvider( ProviderHandle: PerfProviderHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfSetCounterSetInfo( ProviderHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? Template: ?*PERF_COUNTERSET_INFO, TemplateSize: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfCreateInstance( ProviderHandle: PerfProviderHandle, CounterSetGuid: ?*const Guid, Name: ?[*:0]const u16, Id: u32, ) callconv(@import("std").os.windows.WINAPI) ?*PERF_COUNTERSET_INSTANCE; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfDeleteInstance( Provider: PerfProviderHandle, InstanceBlock: ?*PERF_COUNTERSET_INSTANCE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfQueryInstance( ProviderHandle: ?HANDLE, CounterSetGuid: ?*const Guid, Name: ?[*:0]const u16, Id: u32, ) callconv(@import("std").os.windows.WINAPI) ?*PERF_COUNTERSET_INSTANCE; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfSetCounterRefValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Address: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfSetULongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfSetULongLongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfIncrementULongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfIncrementULongLongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfDecrementULongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn PerfDecrementULongLongCounterValue( Provider: ?HANDLE, Instance: ?*PERF_COUNTERSET_INSTANCE, CounterId: u32, Value: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfEnumerateCounterSet( szMachine: ?[*:0]const u16, pCounterSetIds: ?[*]Guid, cCounterSetIds: u32, pcCounterSetIdsActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfEnumerateCounterSetInstances( szMachine: ?[*:0]const u16, pCounterSetId: ?*const Guid, // TODO: what to do with BytesParamIndex 3? pInstances: ?*PERF_INSTANCE_HEADER, cbInstances: u32, pcbInstancesActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfQueryCounterSetRegistrationInfo( szMachine: ?[*:0]const u16, pCounterSetId: ?*const Guid, requestCode: PerfRegInfoType, requestLangId: u32, // TODO: what to do with BytesParamIndex 5? pbRegInfo: ?*u8, cbRegInfo: u32, pcbRegInfoActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfOpenQueryHandle( szMachine: ?[*:0]const u16, phQuery: ?*PerfQueryHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfCloseQueryHandle( hQuery: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfQueryCounterInfo( hQuery: PerfQueryHandle, // TODO: what to do with BytesParamIndex 2? pCounters: ?*PERF_COUNTER_IDENTIFIER, cbCounters: u32, pcbCountersActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfQueryCounterData( hQuery: PerfQueryHandle, // TODO: what to do with BytesParamIndex 2? pCounterBlock: ?*PERF_DATA_HEADER, cbCounterBlock: u32, pcbCounterBlockActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfAddCounters( hQuery: PerfQueryHandle, // TODO: what to do with BytesParamIndex 2? pCounters: ?*PERF_COUNTER_IDENTIFIER, cbCounters: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.14393' pub extern "ADVAPI32" fn PerfDeleteCounters( hQuery: PerfQueryHandle, // TODO: what to do with BytesParamIndex 2? pCounters: ?*PERF_COUNTER_IDENTIFIER, cbCounters: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDllVersion( lpdwVersion: ?*PDH_DLL_VERSION, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhOpenQueryW( szDataSource: ?[*:0]const u16, dwUserData: usize, phQuery: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhOpenQueryA( szDataSource: ?[*:0]const u8, dwUserData: usize, phQuery: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhAddCounterW( hQuery: isize, szFullCounterPath: ?[*:0]const u16, dwUserData: usize, phCounter: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhAddCounterA( hQuery: isize, szFullCounterPath: ?[*:0]const u8, dwUserData: usize, phCounter: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "pdh" fn PdhAddEnglishCounterW( hQuery: isize, szFullCounterPath: ?[*:0]const u16, dwUserData: usize, phCounter: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "pdh" fn PdhAddEnglishCounterA( hQuery: isize, szFullCounterPath: ?[*:0]const u8, dwUserData: usize, phCounter: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "pdh" fn PdhCollectQueryDataWithTime( hQuery: isize, pllTimeStamp: ?*i64, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "pdh" fn PdhValidatePathExW( hDataSource: isize, szFullPathBuffer: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "pdh" fn PdhValidatePathExA( hDataSource: isize, szFullPathBuffer: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhRemoveCounter( hCounter: isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhCollectQueryData( hQuery: isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhCloseQuery( hQuery: isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetFormattedCounterValue( hCounter: isize, dwFormat: PDH_FMT, lpdwType: ?*u32, pValue: ?*PDH_FMT_COUNTERVALUE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetFormattedCounterArrayA( hCounter: isize, dwFormat: PDH_FMT, lpdwBufferSize: ?*u32, lpdwItemCount: ?*u32, ItemBuffer: ?*PDH_FMT_COUNTERVALUE_ITEM_A, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetFormattedCounterArrayW( hCounter: isize, dwFormat: PDH_FMT, lpdwBufferSize: ?*u32, lpdwItemCount: ?*u32, ItemBuffer: ?*PDH_FMT_COUNTERVALUE_ITEM_W, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetRawCounterValue( hCounter: isize, lpdwType: ?*u32, pValue: ?*PDH_RAW_COUNTER, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetRawCounterArrayA( hCounter: isize, lpdwBufferSize: ?*u32, lpdwItemCount: ?*u32, ItemBuffer: ?*PDH_RAW_COUNTER_ITEM_A, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetRawCounterArrayW( hCounter: isize, lpdwBufferSize: ?*u32, lpdwItemCount: ?*u32, ItemBuffer: ?*PDH_RAW_COUNTER_ITEM_W, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhCalculateCounterFromRawValue( hCounter: isize, dwFormat: PDH_FMT, rawValue1: ?*PDH_RAW_COUNTER, rawValue2: ?*PDH_RAW_COUNTER, fmtValue: ?*PDH_FMT_COUNTERVALUE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhComputeCounterStatistics( hCounter: isize, dwFormat: PDH_FMT, dwFirstEntry: u32, dwNumEntries: u32, lpRawValueArray: ?*PDH_RAW_COUNTER, data: ?*PDH_STATISTICS, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetCounterInfoW( hCounter: isize, bRetrieveExplainText: BOOLEAN, pdwBufferSize: ?*u32, lpBuffer: ?*PDH_COUNTER_INFO_W, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetCounterInfoA( hCounter: isize, bRetrieveExplainText: BOOLEAN, pdwBufferSize: ?*u32, lpBuffer: ?*PDH_COUNTER_INFO_A, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhSetCounterScaleFactor( hCounter: isize, lFactor: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhConnectMachineW( szMachineName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhConnectMachineA( szMachineName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumMachinesW( szDataSource: ?[*:0]const u16, mszMachineList: ?[*]u16, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumMachinesA( szDataSource: ?[*:0]const u8, mszMachineList: ?[*]u8, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectsW( szDataSource: ?[*:0]const u16, szMachineName: ?[*:0]const u16, mszObjectList: ?[*]u16, pcchBufferSize: ?*u32, dwDetailLevel: PERF_DETAIL, bRefresh: BOOL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectsA( szDataSource: ?[*:0]const u8, szMachineName: ?[*:0]const u8, mszObjectList: ?[*]u8, pcchBufferSize: ?*u32, dwDetailLevel: PERF_DETAIL, bRefresh: BOOL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectItemsW( szDataSource: ?[*:0]const u16, szMachineName: ?[*:0]const u16, szObjectName: ?[*:0]const u16, mszCounterList: ?[*]u16, pcchCounterListLength: ?*u32, mszInstanceList: ?[*]u16, pcchInstanceListLength: ?*u32, dwDetailLevel: PERF_DETAIL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectItemsA( szDataSource: ?[*:0]const u8, szMachineName: ?[*:0]const u8, szObjectName: ?[*:0]const u8, mszCounterList: ?[*]u8, pcchCounterListLength: ?*u32, mszInstanceList: ?[*]u8, pcchInstanceListLength: ?*u32, dwDetailLevel: PERF_DETAIL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhMakeCounterPathW( pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_W, szFullPathBuffer: ?PWSTR, pcchBufferSize: ?*u32, dwFlags: PDH_PATH_FLAGS, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhMakeCounterPathA( pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_A, szFullPathBuffer: ?PSTR, pcchBufferSize: ?*u32, dwFlags: PDH_PATH_FLAGS, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhParseCounterPathW( szFullPathBuffer: ?[*:0]const u16, pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_W, pdwBufferSize: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhParseCounterPathA( szFullPathBuffer: ?[*:0]const u8, pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_A, pdwBufferSize: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhParseInstanceNameW( szInstanceString: ?[*:0]const u16, szInstanceName: ?PWSTR, pcchInstanceNameLength: ?*u32, szParentName: ?PWSTR, pcchParentNameLength: ?*u32, lpIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhParseInstanceNameA( szInstanceString: ?[*:0]const u8, szInstanceName: ?PSTR, pcchInstanceNameLength: ?*u32, szParentName: ?PSTR, pcchParentNameLength: ?*u32, lpIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhValidatePathW( szFullPathBuffer: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhValidatePathA( szFullPathBuffer: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfObjectW( szDataSource: ?[*:0]const u16, szMachineName: ?[*:0]const u16, szDefaultObjectName: ?PWSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfObjectA( szDataSource: ?[*:0]const u8, szMachineName: ?[*:0]const u8, szDefaultObjectName: ?PSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfCounterW( szDataSource: ?[*:0]const u16, szMachineName: ?[*:0]const u16, szObjectName: ?[*:0]const u16, szDefaultCounterName: ?PWSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfCounterA( szDataSource: ?[*:0]const u8, szMachineName: ?[*:0]const u8, szObjectName: ?[*:0]const u8, szDefaultCounterName: ?PSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBrowseCountersW( pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_W, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBrowseCountersA( pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_A, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandCounterPathW( szWildCardPath: ?[*:0]const u16, mszExpandedPathList: ?[*]u16, pcchPathListLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandCounterPathA( szWildCardPath: ?[*:0]const u8, mszExpandedPathList: ?[*]u8, pcchPathListLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhLookupPerfNameByIndexW( szMachineName: ?[*:0]const u16, dwNameIndex: u32, szNameBuffer: ?PWSTR, pcchNameBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhLookupPerfNameByIndexA( szMachineName: ?[*:0]const u8, dwNameIndex: u32, szNameBuffer: ?PSTR, pcchNameBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhLookupPerfIndexByNameW( szMachineName: ?[*:0]const u16, szNameBuffer: ?[*:0]const u16, pdwIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhLookupPerfIndexByNameA( szMachineName: ?[*:0]const u8, szNameBuffer: ?[*:0]const u8, pdwIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandWildCardPathA( szDataSource: ?[*:0]const u8, szWildCardPath: ?[*:0]const u8, mszExpandedPathList: ?[*]u8, pcchPathListLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandWildCardPathW( szDataSource: ?[*:0]const u16, szWildCardPath: ?[*:0]const u16, mszExpandedPathList: ?[*]u16, pcchPathListLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhOpenLogW( szLogFileName: ?[*:0]const u16, dwAccessFlags: PDH_LOG, lpdwLogType: ?*PDH_LOG_TYPE, hQuery: isize, dwMaxSize: u32, szUserCaption: ?[*:0]const u16, phLog: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhOpenLogA( szLogFileName: ?[*:0]const u8, dwAccessFlags: PDH_LOG, lpdwLogType: ?*PDH_LOG_TYPE, hQuery: isize, dwMaxSize: u32, szUserCaption: ?[*:0]const u8, phLog: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhUpdateLogW( hLog: isize, szUserString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhUpdateLogA( hLog: isize, szUserString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhUpdateLogFileCatalog( hLog: isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetLogFileSize( hLog: isize, llSize: ?*i64, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhCloseLog( hLog: isize, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhSelectDataSourceW( hWndOwner: ?HWND, dwFlags: PDH_SELECT_DATA_SOURCE_FLAGS, szDataSource: ?PWSTR, pcchBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhSelectDataSourceA( hWndOwner: ?HWND, dwFlags: PDH_SELECT_DATA_SOURCE_FLAGS, szDataSource: ?PSTR, pcchBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhIsRealTimeQuery( hQuery: isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhSetQueryTimeRange( hQuery: isize, pInfo: ?*PDH_TIME_INFO, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDataSourceTimeRangeW( szDataSource: ?[*:0]const u16, pdwNumEntries: ?*u32, pInfo: ?*PDH_TIME_INFO, pdwBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDataSourceTimeRangeA( szDataSource: ?[*:0]const u8, pdwNumEntries: ?*u32, pInfo: ?*PDH_TIME_INFO, pdwBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhCollectQueryDataEx( hQuery: isize, dwIntervalTime: u32, hNewDataEvent: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhFormatFromRawValue( dwCounterType: u32, dwFormat: PDH_FMT, pTimeBase: ?*i64, pRawValue1: ?*PDH_RAW_COUNTER, pRawValue2: ?*PDH_RAW_COUNTER, pFmtValue: ?*PDH_FMT_COUNTERVALUE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetCounterTimeBase( hCounter: isize, pTimeBase: ?*i64, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhReadRawLogRecord( hLog: isize, ftRecord: FILETIME, pRawLogRecord: ?*PDH_RAW_LOG_RECORD, pdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhSetDefaultRealTimeDataSource( dwDataSourceId: REAL_TIME_DATA_SOURCE_ID_FLAGS, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBindInputDataSourceW( phDataSource: ?*isize, LogFileNameList: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBindInputDataSourceA( phDataSource: ?*isize, LogFileNameList: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhOpenQueryH( hDataSource: isize, dwUserData: usize, phQuery: ?*isize, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumMachinesHW( hDataSource: isize, mszMachineList: ?[*]u16, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumMachinesHA( hDataSource: isize, mszMachineList: ?[*]u8, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectsHW( hDataSource: isize, szMachineName: ?[*:0]const u16, mszObjectList: ?[*]u16, pcchBufferSize: ?*u32, dwDetailLevel: PERF_DETAIL, bRefresh: BOOL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectsHA( hDataSource: isize, szMachineName: ?[*:0]const u8, mszObjectList: ?[*]u8, pcchBufferSize: ?*u32, dwDetailLevel: PERF_DETAIL, bRefresh: BOOL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectItemsHW( hDataSource: isize, szMachineName: ?[*:0]const u16, szObjectName: ?[*:0]const u16, mszCounterList: ?[*]u16, pcchCounterListLength: ?*u32, mszInstanceList: ?[*]u16, pcchInstanceListLength: ?*u32, dwDetailLevel: PERF_DETAIL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumObjectItemsHA( hDataSource: isize, szMachineName: ?[*:0]const u8, szObjectName: ?[*:0]const u8, mszCounterList: ?[*]u8, pcchCounterListLength: ?*u32, mszInstanceList: ?[*]u8, pcchInstanceListLength: ?*u32, dwDetailLevel: PERF_DETAIL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandWildCardPathHW( hDataSource: isize, szWildCardPath: ?[*:0]const u16, mszExpandedPathList: ?[*]u16, pcchPathListLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhExpandWildCardPathHA( hDataSource: isize, szWildCardPath: ?[*:0]const u8, mszExpandedPathList: ?[*]u8, pcchPathListLength: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDataSourceTimeRangeH( hDataSource: isize, pdwNumEntries: ?*u32, pInfo: ?*PDH_TIME_INFO, pdwBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfObjectHW( hDataSource: isize, szMachineName: ?[*:0]const u16, szDefaultObjectName: ?PWSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfObjectHA( hDataSource: isize, szMachineName: ?[*:0]const u8, szDefaultObjectName: ?PSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfCounterHW( hDataSource: isize, szMachineName: ?[*:0]const u16, szObjectName: ?[*:0]const u16, szDefaultCounterName: ?PWSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhGetDefaultPerfCounterHA( hDataSource: isize, szMachineName: ?[*:0]const u8, szObjectName: ?[*:0]const u8, szDefaultCounterName: ?PSTR, pcchBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBrowseCountersHW( pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_HW, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhBrowseCountersHA( pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_HA, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhVerifySQLDBW( szDataSource: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhVerifySQLDBA( szDataSource: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhCreateSQLTablesW( szDataSource: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhCreateSQLTablesA( szDataSource: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumLogSetNamesW( szDataSource: ?[*:0]const u16, mszDataSetNameList: ?[*]u16, pcchBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "pdh" fn PdhEnumLogSetNamesA( szDataSource: ?[*:0]const u8, mszDataSetNameList: ?[*]u8, pcchBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhGetLogSetGUID( hLog: isize, pGuid: ?*Guid, pRunId: ?*i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "pdh" fn PdhSetLogSetRunID( hLog: isize, RunId: i32, ) callconv(@import("std").os.windows.WINAPI) i32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (50) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const PDH_RAW_COUNTER_ITEM_ = thismodule.PDH_RAW_COUNTER_ITEM_A; pub const PDH_FMT_COUNTERVALUE_ITEM_ = thismodule.PDH_FMT_COUNTERVALUE_ITEM_A; pub const PDH_COUNTER_PATH_ELEMENTS_ = thismodule.PDH_COUNTER_PATH_ELEMENTS_A; pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = thismodule.PDH_DATA_ITEM_PATH_ELEMENTS_A; pub const PDH_COUNTER_INFO_ = thismodule.PDH_COUNTER_INFO_A; pub const PDH_LOG_SERVICE_QUERY_INFO_ = thismodule.PDH_LOG_SERVICE_QUERY_INFO_A; pub const PDH_BROWSE_DLG_CONFIG_H = thismodule.PDH_BROWSE_DLG_CONFIG_HA; pub const PDH_BROWSE_DLG_CONFIG_ = thismodule.PDH_BROWSE_DLG_CONFIG_A; pub const InstallPerfDll = thismodule.InstallPerfDllA; pub const LoadPerfCounterTextStrings = thismodule.LoadPerfCounterTextStringsA; pub const UnloadPerfCounterTextStrings = thismodule.UnloadPerfCounterTextStringsA; pub const UpdatePerfNameFiles = thismodule.UpdatePerfNameFilesA; pub const SetServiceAsTrusted = thismodule.SetServiceAsTrustedA; pub const PdhOpenQuery = thismodule.PdhOpenQueryA; pub const PdhAddCounter = thismodule.PdhAddCounterA; pub const PdhAddEnglishCounter = thismodule.PdhAddEnglishCounterA; pub const PdhValidatePathEx = thismodule.PdhValidatePathExA; pub const PdhGetFormattedCounterArray = thismodule.PdhGetFormattedCounterArrayA; pub const PdhGetRawCounterArray = thismodule.PdhGetRawCounterArrayA; pub const PdhGetCounterInfo = thismodule.PdhGetCounterInfoA; pub const PdhConnectMachine = thismodule.PdhConnectMachineA; pub const PdhEnumMachines = thismodule.PdhEnumMachinesA; pub const PdhEnumObjects = thismodule.PdhEnumObjectsA; pub const PdhEnumObjectItems = thismodule.PdhEnumObjectItemsA; pub const PdhMakeCounterPath = thismodule.PdhMakeCounterPathA; pub const PdhParseCounterPath = thismodule.PdhParseCounterPathA; pub const PdhParseInstanceName = thismodule.PdhParseInstanceNameA; pub const PdhValidatePath = thismodule.PdhValidatePathA; pub const PdhGetDefaultPerfObject = thismodule.PdhGetDefaultPerfObjectA; pub const PdhGetDefaultPerfCounter = thismodule.PdhGetDefaultPerfCounterA; pub const PdhBrowseCounters = thismodule.PdhBrowseCountersA; pub const PdhExpandCounterPath = thismodule.PdhExpandCounterPathA; pub const PdhLookupPerfNameByIndex = thismodule.PdhLookupPerfNameByIndexA; pub const PdhLookupPerfIndexByName = thismodule.PdhLookupPerfIndexByNameA; pub const PdhExpandWildCardPath = thismodule.PdhExpandWildCardPathA; pub const PdhOpenLog = thismodule.PdhOpenLogA; pub const PdhUpdateLog = thismodule.PdhUpdateLogA; pub const PdhSelectDataSource = thismodule.PdhSelectDataSourceA; pub const PdhGetDataSourceTimeRange = thismodule.PdhGetDataSourceTimeRangeA; pub const PdhBindInputDataSource = thismodule.PdhBindInputDataSourceA; pub const PdhEnumMachinesH = thismodule.PdhEnumMachinesHA; pub const PdhEnumObjectsH = thismodule.PdhEnumObjectsHA; pub const PdhEnumObjectItemsH = thismodule.PdhEnumObjectItemsHA; pub const PdhExpandWildCardPathH = thismodule.PdhExpandWildCardPathHA; pub const PdhGetDefaultPerfObjectH = thismodule.PdhGetDefaultPerfObjectHA; pub const PdhGetDefaultPerfCounterH = thismodule.PdhGetDefaultPerfCounterHA; pub const PdhBrowseCountersH = thismodule.PdhBrowseCountersHA; pub const PdhVerifySQLDB = thismodule.PdhVerifySQLDBA; pub const PdhCreateSQLTables = thismodule.PdhCreateSQLTablesA; pub const PdhEnumLogSetNames = thismodule.PdhEnumLogSetNamesA; }, .wide => struct { pub const PDH_RAW_COUNTER_ITEM_ = thismodule.PDH_RAW_COUNTER_ITEM_W; pub const PDH_FMT_COUNTERVALUE_ITEM_ = thismodule.PDH_FMT_COUNTERVALUE_ITEM_W; pub const PDH_COUNTER_PATH_ELEMENTS_ = thismodule.PDH_COUNTER_PATH_ELEMENTS_W; pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = thismodule.PDH_DATA_ITEM_PATH_ELEMENTS_W; pub const PDH_COUNTER_INFO_ = thismodule.PDH_COUNTER_INFO_W; pub const PDH_LOG_SERVICE_QUERY_INFO_ = thismodule.PDH_LOG_SERVICE_QUERY_INFO_W; pub const PDH_BROWSE_DLG_CONFIG_H = thismodule.PDH_BROWSE_DLG_CONFIG_HW; pub const PDH_BROWSE_DLG_CONFIG_ = thismodule.PDH_BROWSE_DLG_CONFIG_W; pub const InstallPerfDll = thismodule.InstallPerfDllW; pub const LoadPerfCounterTextStrings = thismodule.LoadPerfCounterTextStringsW; pub const UnloadPerfCounterTextStrings = thismodule.UnloadPerfCounterTextStringsW; pub const UpdatePerfNameFiles = thismodule.UpdatePerfNameFilesW; pub const SetServiceAsTrusted = thismodule.SetServiceAsTrustedW; pub const PdhOpenQuery = thismodule.PdhOpenQueryW; pub const PdhAddCounter = thismodule.PdhAddCounterW; pub const PdhAddEnglishCounter = thismodule.PdhAddEnglishCounterW; pub const PdhValidatePathEx = thismodule.PdhValidatePathExW; pub const PdhGetFormattedCounterArray = thismodule.PdhGetFormattedCounterArrayW; pub const PdhGetRawCounterArray = thismodule.PdhGetRawCounterArrayW; pub const PdhGetCounterInfo = thismodule.PdhGetCounterInfoW; pub const PdhConnectMachine = thismodule.PdhConnectMachineW; pub const PdhEnumMachines = thismodule.PdhEnumMachinesW; pub const PdhEnumObjects = thismodule.PdhEnumObjectsW; pub const PdhEnumObjectItems = thismodule.PdhEnumObjectItemsW; pub const PdhMakeCounterPath = thismodule.PdhMakeCounterPathW; pub const PdhParseCounterPath = thismodule.PdhParseCounterPathW; pub const PdhParseInstanceName = thismodule.PdhParseInstanceNameW; pub const PdhValidatePath = thismodule.PdhValidatePathW; pub const PdhGetDefaultPerfObject = thismodule.PdhGetDefaultPerfObjectW; pub const PdhGetDefaultPerfCounter = thismodule.PdhGetDefaultPerfCounterW; pub const PdhBrowseCounters = thismodule.PdhBrowseCountersW; pub const PdhExpandCounterPath = thismodule.PdhExpandCounterPathW; pub const PdhLookupPerfNameByIndex = thismodule.PdhLookupPerfNameByIndexW; pub const PdhLookupPerfIndexByName = thismodule.PdhLookupPerfIndexByNameW; pub const PdhExpandWildCardPath = thismodule.PdhExpandWildCardPathW; pub const PdhOpenLog = thismodule.PdhOpenLogW; pub const PdhUpdateLog = thismodule.PdhUpdateLogW; pub const PdhSelectDataSource = thismodule.PdhSelectDataSourceW; pub const PdhGetDataSourceTimeRange = thismodule.PdhGetDataSourceTimeRangeW; pub const PdhBindInputDataSource = thismodule.PdhBindInputDataSourceW; pub const PdhEnumMachinesH = thismodule.PdhEnumMachinesHW; pub const PdhEnumObjectsH = thismodule.PdhEnumObjectsHW; pub const PdhEnumObjectItemsH = thismodule.PdhEnumObjectItemsHW; pub const PdhExpandWildCardPathH = thismodule.PdhExpandWildCardPathHW; pub const PdhGetDefaultPerfObjectH = thismodule.PdhGetDefaultPerfObjectHW; pub const PdhGetDefaultPerfCounterH = thismodule.PdhGetDefaultPerfCounterHW; pub const PdhBrowseCountersH = thismodule.PdhBrowseCountersHW; pub const PdhVerifySQLDB = thismodule.PdhVerifySQLDBW; pub const PdhCreateSQLTables = thismodule.PdhCreateSQLTablesW; pub const PdhEnumLogSetNames = thismodule.PdhEnumLogSetNamesW; }, .unspecified => if (@import("builtin").is_test) struct { pub const PDH_RAW_COUNTER_ITEM_ = *opaque{}; pub const PDH_FMT_COUNTERVALUE_ITEM_ = *opaque{}; pub const PDH_COUNTER_PATH_ELEMENTS_ = *opaque{}; pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = *opaque{}; pub const PDH_COUNTER_INFO_ = *opaque{}; pub const PDH_LOG_SERVICE_QUERY_INFO_ = *opaque{}; pub const PDH_BROWSE_DLG_CONFIG_H = *opaque{}; pub const PDH_BROWSE_DLG_CONFIG_ = *opaque{}; pub const InstallPerfDll = *opaque{}; pub const LoadPerfCounterTextStrings = *opaque{}; pub const UnloadPerfCounterTextStrings = *opaque{}; pub const UpdatePerfNameFiles = *opaque{}; pub const SetServiceAsTrusted = *opaque{}; pub const PdhOpenQuery = *opaque{}; pub const PdhAddCounter = *opaque{}; pub const PdhAddEnglishCounter = *opaque{}; pub const PdhValidatePathEx = *opaque{}; pub const PdhGetFormattedCounterArray = *opaque{}; pub const PdhGetRawCounterArray = *opaque{}; pub const PdhGetCounterInfo = *opaque{}; pub const PdhConnectMachine = *opaque{}; pub const PdhEnumMachines = *opaque{}; pub const PdhEnumObjects = *opaque{}; pub const PdhEnumObjectItems = *opaque{}; pub const PdhMakeCounterPath = *opaque{}; pub const PdhParseCounterPath = *opaque{}; pub const PdhParseInstanceName = *opaque{}; pub const PdhValidatePath = *opaque{}; pub const PdhGetDefaultPerfObject = *opaque{}; pub const PdhGetDefaultPerfCounter = *opaque{}; pub const PdhBrowseCounters = *opaque{}; pub const PdhExpandCounterPath = *opaque{}; pub const PdhLookupPerfNameByIndex = *opaque{}; pub const PdhLookupPerfIndexByName = *opaque{}; pub const PdhExpandWildCardPath = *opaque{}; pub const PdhOpenLog = *opaque{}; pub const PdhUpdateLog = *opaque{}; pub const PdhSelectDataSource = *opaque{}; pub const PdhGetDataSourceTimeRange = *opaque{}; pub const PdhBindInputDataSource = *opaque{}; pub const PdhEnumMachinesH = *opaque{}; pub const PdhEnumObjectsH = *opaque{}; pub const PdhEnumObjectItemsH = *opaque{}; pub const PdhExpandWildCardPathH = *opaque{}; pub const PdhGetDefaultPerfObjectH = *opaque{}; pub const PdhGetDefaultPerfCounterH = *opaque{}; pub const PdhBrowseCountersH = *opaque{}; pub const PdhVerifySQLDB = *opaque{}; pub const PdhCreateSQLTables = *opaque{}; pub const PdhEnumLogSetNames = *opaque{}; } else struct { pub const PDH_RAW_COUNTER_ITEM_ = @compileError("'PDH_RAW_COUNTER_ITEM_' requires that UNICODE be set to true or false in the root module"); pub const PDH_FMT_COUNTERVALUE_ITEM_ = @compileError("'PDH_FMT_COUNTERVALUE_ITEM_' requires that UNICODE be set to true or false in the root module"); pub const PDH_COUNTER_PATH_ELEMENTS_ = @compileError("'PDH_COUNTER_PATH_ELEMENTS_' requires that UNICODE be set to true or false in the root module"); pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = @compileError("'PDH_DATA_ITEM_PATH_ELEMENTS_' requires that UNICODE be set to true or false in the root module"); pub const PDH_COUNTER_INFO_ = @compileError("'PDH_COUNTER_INFO_' requires that UNICODE be set to true or false in the root module"); pub const PDH_LOG_SERVICE_QUERY_INFO_ = @compileError("'PDH_LOG_SERVICE_QUERY_INFO_' requires that UNICODE be set to true or false in the root module"); pub const PDH_BROWSE_DLG_CONFIG_H = @compileError("'PDH_BROWSE_DLG_CONFIG_H' requires that UNICODE be set to true or false in the root module"); pub const PDH_BROWSE_DLG_CONFIG_ = @compileError("'PDH_BROWSE_DLG_CONFIG_' requires that UNICODE be set to true or false in the root module"); pub const InstallPerfDll = @compileError("'InstallPerfDll' requires that UNICODE be set to true or false in the root module"); pub const LoadPerfCounterTextStrings = @compileError("'LoadPerfCounterTextStrings' requires that UNICODE be set to true or false in the root module"); pub const UnloadPerfCounterTextStrings = @compileError("'UnloadPerfCounterTextStrings' requires that UNICODE be set to true or false in the root module"); pub const UpdatePerfNameFiles = @compileError("'UpdatePerfNameFiles' requires that UNICODE be set to true or false in the root module"); pub const SetServiceAsTrusted = @compileError("'SetServiceAsTrusted' requires that UNICODE be set to true or false in the root module"); pub const PdhOpenQuery = @compileError("'PdhOpenQuery' requires that UNICODE be set to true or false in the root module"); pub const PdhAddCounter = @compileError("'PdhAddCounter' requires that UNICODE be set to true or false in the root module"); pub const PdhAddEnglishCounter = @compileError("'PdhAddEnglishCounter' requires that UNICODE be set to true or false in the root module"); pub const PdhValidatePathEx = @compileError("'PdhValidatePathEx' requires that UNICODE be set to true or false in the root module"); pub const PdhGetFormattedCounterArray = @compileError("'PdhGetFormattedCounterArray' requires that UNICODE be set to true or false in the root module"); pub const PdhGetRawCounterArray = @compileError("'PdhGetRawCounterArray' requires that UNICODE be set to true or false in the root module"); pub const PdhGetCounterInfo = @compileError("'PdhGetCounterInfo' requires that UNICODE be set to true or false in the root module"); pub const PdhConnectMachine = @compileError("'PdhConnectMachine' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumMachines = @compileError("'PdhEnumMachines' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumObjects = @compileError("'PdhEnumObjects' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumObjectItems = @compileError("'PdhEnumObjectItems' requires that UNICODE be set to true or false in the root module"); pub const PdhMakeCounterPath = @compileError("'PdhMakeCounterPath' requires that UNICODE be set to true or false in the root module"); pub const PdhParseCounterPath = @compileError("'PdhParseCounterPath' requires that UNICODE be set to true or false in the root module"); pub const PdhParseInstanceName = @compileError("'PdhParseInstanceName' requires that UNICODE be set to true or false in the root module"); pub const PdhValidatePath = @compileError("'PdhValidatePath' requires that UNICODE be set to true or false in the root module"); pub const PdhGetDefaultPerfObject = @compileError("'PdhGetDefaultPerfObject' requires that UNICODE be set to true or false in the root module"); pub const PdhGetDefaultPerfCounter = @compileError("'PdhGetDefaultPerfCounter' requires that UNICODE be set to true or false in the root module"); pub const PdhBrowseCounters = @compileError("'PdhBrowseCounters' requires that UNICODE be set to true or false in the root module"); pub const PdhExpandCounterPath = @compileError("'PdhExpandCounterPath' requires that UNICODE be set to true or false in the root module"); pub const PdhLookupPerfNameByIndex = @compileError("'PdhLookupPerfNameByIndex' requires that UNICODE be set to true or false in the root module"); pub const PdhLookupPerfIndexByName = @compileError("'PdhLookupPerfIndexByName' requires that UNICODE be set to true or false in the root module"); pub const PdhExpandWildCardPath = @compileError("'PdhExpandWildCardPath' requires that UNICODE be set to true or false in the root module"); pub const PdhOpenLog = @compileError("'PdhOpenLog' requires that UNICODE be set to true or false in the root module"); pub const PdhUpdateLog = @compileError("'PdhUpdateLog' requires that UNICODE be set to true or false in the root module"); pub const PdhSelectDataSource = @compileError("'PdhSelectDataSource' requires that UNICODE be set to true or false in the root module"); pub const PdhGetDataSourceTimeRange = @compileError("'PdhGetDataSourceTimeRange' requires that UNICODE be set to true or false in the root module"); pub const PdhBindInputDataSource = @compileError("'PdhBindInputDataSource' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumMachinesH = @compileError("'PdhEnumMachinesH' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumObjectsH = @compileError("'PdhEnumObjectsH' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumObjectItemsH = @compileError("'PdhEnumObjectItemsH' requires that UNICODE be set to true or false in the root module"); pub const PdhExpandWildCardPathH = @compileError("'PdhExpandWildCardPathH' requires that UNICODE be set to true or false in the root module"); pub const PdhGetDefaultPerfObjectH = @compileError("'PdhGetDefaultPerfObjectH' requires that UNICODE be set to true or false in the root module"); pub const PdhGetDefaultPerfCounterH = @compileError("'PdhGetDefaultPerfCounterH' requires that UNICODE be set to true or false in the root module"); pub const PdhBrowseCountersH = @compileError("'PdhBrowseCountersH' requires that UNICODE be set to true or false in the root module"); pub const PdhVerifySQLDB = @compileError("'PdhVerifySQLDB' requires that UNICODE be set to true or false in the root module"); pub const PdhCreateSQLTables = @compileError("'PdhCreateSQLTables' requires that UNICODE be set to true or false in the root module"); pub const PdhEnumLogSetNames = @compileError("'PdhEnumLogSetNames' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (17) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const BSTR = @import("../foundation.zig").BSTR; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IFontDisp = @import("../system/ole.zig").IFontDisp; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SAFEARRAY = @import("../system/com.zig").SAFEARRAY; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; const VARIANT = @import("../system/com.zig").VARIANT; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PLA_CABEXTRACT_CALLBACK")) { _ = PLA_CABEXTRACT_CALLBACK; } if (@hasDecl(@This(), "PERFLIBREQUEST")) { _ = PERFLIBREQUEST; } if (@hasDecl(@This(), "PERF_MEM_ALLOC")) { _ = PERF_MEM_ALLOC; } if (@hasDecl(@This(), "PERF_MEM_FREE")) { _ = PERF_MEM_FREE; } if (@hasDecl(@This(), "PM_OPEN_PROC")) { _ = PM_OPEN_PROC; } if (@hasDecl(@This(), "PM_COLLECT_PROC")) { _ = PM_COLLECT_PROC; } if (@hasDecl(@This(), "PM_CLOSE_PROC")) { _ = PM_CLOSE_PROC; } if (@hasDecl(@This(), "CounterPathCallBack")) { _ = CounterPathCallBack; } @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; } } } //-------------------------------------------------------------------------------- // Section: SubModules (1) //-------------------------------------------------------------------------------- pub const hardware_counter_profiling = @import("performance/hardware_counter_profiling.zig");
win32/system/performance.zig
const std = @import("std"); const Location = @import("location.zig").Location; pub const UnaryOperator = enum { negate, boolean_not, }; pub const BinaryOperator = enum { add, subtract, multiply, divide, modulus, boolean_or, boolean_and, less_than, greater_than, greater_or_equal_than, less_or_equal_than, equal, different, }; pub const Expression = struct { const Self = @This(); pub const Type = std.meta.Tag(ExprValue); /// Starting location of the statement location: Location, /// kind of the expression as well as associated child nodes. /// child expressions memory is stored in the `Program` structure. type: ExprValue, /// Returns true when the expression allows an assignment similar to /// Cs `lvalue`. pub fn isAssignable(self: Self) bool { return switch (self.type) { .array_indexer, .variable_expr => true, else => false, }; } const ExprValue = union(enum) { array_indexer: struct { value: *Expression, index: *Expression, }, variable_expr: []const u8, array_literal: []Expression, function_call: struct { // this must be a expression of type `variable_expr` function: *Expression, arguments: []Expression, }, method_call: struct { object: *Expression, name: []const u8, arguments: []Expression, }, number_literal: f64, string_literal: []const u8, unary_operator: struct { operator: UnaryOperator, value: *Expression, }, binary_operator: struct { operator: BinaryOperator, lhs: *Expression, rhs: *Expression, }, }; }; pub const Statement = struct { const Self = @This(); pub const Type = std.meta.Tag(StmtValue); /// Starting location of the statement location: Location, /// kind of the statement as well as associated child nodes. /// child statements and expressions memory is stored in the /// `Program` structure. type: StmtValue, const StmtValue = union(enum) { empty: void, // Just a single, flat ';' /// Top level assignment as in `lvalue = value`. assignment: struct { target: Expression, value: Expression, }, /// Top-level function call like `Foo()` discard_value: Expression, return_void: void, return_expr: Expression, while_loop: struct { condition: Expression, body: *Statement, }, for_loop: struct { variable: []const u8, source: Expression, body: *Statement, }, if_statement: struct { condition: Expression, true_body: *Statement, false_body: ?*Statement, }, declaration: struct { variable: []const u8, initial_value: ?Expression, is_const: bool, }, block: []Statement, @"break": void, @"continue": void, }; }; pub const Function = struct { /// Starting location of the function location: Location, name: []const u8, parameters: [][]const u8, body: Statement, }; /// Root node of the abstract syntax tree, /// contains a whole LoLa file. pub const Program = struct { const Self = @This(); /// Arena storing all associated memory with the AST. /// Each node, string or array is stored here. arena: std.heap.ArenaAllocator, /// The sequence of statements that are not contained in functions. root_script: []Statement, /// All declared functions in the script. functions: []Function, /// Releases all resources associated with this syntax tree. pub fn deinit(self: *Self) void { self.arena.deinit(); self.* = undefined; } }; pub fn dumpExpression(writer: anytype, expr: Expression) @TypeOf(writer).Error!void { switch (expr.type) { .array_indexer => |val| { try dumpExpression(writer, val.value.*); try writer.writeAll("["); try dumpExpression(writer, val.index.*); try writer.writeAll("]"); }, .variable_expr => |val| try writer.writeAll(val), .array_literal => |val| { try writer.writeAll("[ "); for (val) |item, index| { if (index > 0) { try writer.writeAll(", "); } try dumpExpression(writer, item); } try writer.writeAll("]"); }, .function_call => unreachable, .method_call => unreachable, .number_literal => |val| try writer.print("{d}", .{val}), .string_literal => |val| try writer.print("\"{}\"", .{val}), .unary_operator => |val| { try writer.writeAll(switch (val.operator) { .negate => "-", .boolean_not => "not", }); try dumpExpression(writer, val.value.*); }, .binary_operator => |val| { try writer.writeAll("("); try dumpExpression(writer, val.lhs.*); try writer.writeAll(" "); try writer.writeAll(switch (val.operator) { .add => "+", .subtract => "-", .multiply => "*", .divide => "/", .modulus => "%", .boolean_or => "or", .boolean_and => "and", .less_than => "<", .greater_than => ">", .greater_or_equal_than => ">=", .less_or_equal_than => "<=", .equal => "==", .different => "!=", }); try writer.writeAll(" "); try dumpExpression(writer, val.rhs.*); try writer.writeAll(")"); }, } }
src/library/compiler/ast.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "static eval list init" { try expect(static_vec3.data[2] == 1.0); try expect(vec3(0.0, 0.0, 3.0).data[2] == 3.0); } const static_vec3 = vec3(0.0, 0.0, 1.0); pub const Vec3 = struct { data: [3]f32, }; pub fn vec3(x: f32, y: f32, z: f32) Vec3 { return Vec3{ .data = [_]f32{ x, y, z }, }; } test "inlined loop has array literal with elided runtime scope on first iteration but not second iteration" { var runtime = [1]i32{3}; comptime var i: usize = 0; inline while (i < 2) : (i += 1) { const result = if (i == 0) [1]i32{2} else runtime; _ = result; } comptime { try expect(i == 2); } } test "eval @setFloatMode at compile-time" { const result = comptime fnWithFloatMode(); try expect(result == 1234.0); } fn fnWithFloatMode() f32 { @setFloatMode(std.builtin.FloatMode.Strict); return 1234.0; } const SimpleStruct = struct { field: i32, fn method(self: *const SimpleStruct) i32 { return self.field + 3; } }; var simple_struct = SimpleStruct{ .field = 1234 }; const bound_fn = simple_struct.method; test "call method on bound fn referring to var instance" { try expect(bound_fn() == 1237); } test "ptr to local array argument at comptime" { comptime { var bytes: [10]u8 = undefined; modifySomeBytes(bytes[0..]); try expect(bytes[0] == 'a'); try expect(bytes[9] == 'b'); } } fn modifySomeBytes(bytes: []u8) void { bytes[0] = 'a'; bytes[9] = 'b'; } test "comparisons 0 <= uint and 0 > uint should be comptime" { testCompTimeUIntComparisons(1234); } fn testCompTimeUIntComparisons(x: u32) void { if (!(0 <= x)) { @compileError("this condition should be comptime known"); } if (0 > x) { @compileError("this condition should be comptime known"); } if (!(x >= 0)) { @compileError("this condition should be comptime known"); } if (x < 0) { @compileError("this condition should be comptime known"); } } test "const ptr to variable data changes at runtime" { try expect(foo_ref.name[0] == 'a'); foo_ref.name = "b"; try expect(foo_ref.name[0] == 'b'); } const Foo = struct { name: []const u8, }; var foo_contents = Foo{ .name = "a" }; const foo_ref = &foo_contents; const hi1 = "hi"; const hi2 = hi1; test "const global shares pointer with other same one" { try assertEqualPtrs(&hi1[0], &hi2[0]); comptime try expect(&hi1[0] == &hi2[0]); } fn assertEqualPtrs(ptr1: *const u8, ptr2: *const u8) !void { try expect(ptr1 == ptr2); } test "float literal at compile time not lossy" { try expect(16777216.0 + 1.0 == 16777217.0); try expect(9007199254740992.0 + 1.0 == 9007199254740993.0); } test "f128 at compile time is lossy" { try expect(@as(f128, 10384593717069655257060992658440192.0) + 1 == 10384593717069655257060992658440192.0); } pub fn TypeWithCompTimeSlice(comptime field_name: []const u8) type { _ = field_name; return struct { pub const Node = struct {}; }; } test "string literal used as comptime slice is memoized" { const a = "link"; const b = "link"; comptime try expect(TypeWithCompTimeSlice(a).Node == TypeWithCompTimeSlice(b).Node); comptime try expect(TypeWithCompTimeSlice("link").Node == TypeWithCompTimeSlice("link").Node); } test "comptime function with mutable pointer is not memoized" { comptime { var x: i32 = 1; const ptr = &x; increment(ptr); increment(ptr); try expect(x == 3); } } fn increment(value: *i32) void { value.* += 1; } const SingleFieldStruct = struct { x: i32, fn read_x(self: *const SingleFieldStruct) i32 { return self.x; } }; test "const ptr to comptime mutable data is not memoized" { comptime { var foo = SingleFieldStruct{ .x = 1 }; try expect(foo.read_x() == 1); foo.x = 2; try expect(foo.read_x() == 2); } } test "runtime 128 bit integer division" { var a: u128 = 152313999999999991610955792383; var b: u128 = 10000000000000000000; var c = a / b; try expect(c == 15231399999); } const Wrapper = struct { T: type, }; fn wrap(comptime T: type) Wrapper { return Wrapper{ .T = T }; } test "function which returns struct with type field causes implicit comptime" { const ty = wrap(i32).T; try expect(ty == i32); } test "call method with comptime pass-by-non-copying-value self parameter" { const S = struct { a: u8, fn b(comptime s: @This()) u8 { return s.a; } }; const s = S{ .a = 2 }; var b = s.b(); try expect(b == 2); } test "@tagName of @typeInfo" { const str = @tagName(@typeInfo(u8)); try expect(std.mem.eql(u8, str, "Int")); } test "setting backward branch quota just before a generic fn call" { @setEvalBranchQuota(1001); loopNTimes(1001); } fn loopNTimes(comptime n: usize) void { comptime var i = 0; inline while (i < n) : (i += 1) {} } test "variable inside inline loop that has different types on different iterations" { try testVarInsideInlineLoop(.{ true, @as(u32, 42) }); } fn testVarInsideInlineLoop(args: anytype) !void { comptime var i = 0; inline while (i < args.len) : (i += 1) { const x = args[i]; if (i == 0) try expect(x); if (i == 1) try expect(x == 42); } } test "bit shift a u1" { var x: u1 = 1; var y = x << 0; try expect(y == 1); } test "*align(1) u16 is the same as *align(1:0:2) u16" { comptime { try expect(*align(1:0:2) u16 == *align(1) u16); try expect(*align(2:0:2) u16 == *u16); } } test "array concatenation forces comptime" { var a = oneItem(3) ++ oneItem(4); try expect(std.mem.eql(i32, &a, &[_]i32{ 3, 4 })); } test "array multiplication forces comptime" { var a = oneItem(3) ** scalar(2); try expect(std.mem.eql(i32, &a, &[_]i32{ 3, 3 })); } fn oneItem(x: i32) [1]i32 { return [_]i32{x}; } fn scalar(x: u32) u32 { return x; } test "comptime assign int to optional int" { comptime { var x: ?i32 = null; x = 2; x.? *= 10; try expectEqual(20, x.?); } } test "two comptime calls with array default initialized to undefined" { const S = struct { const CrossTarget = struct { dynamic_linker: DynamicLinker = DynamicLinker{}, pub fn parse() void { var result: CrossTarget = .{}; result.getCpuArch(); } pub fn getCpuArch(self: CrossTarget) void { _ = self; } }; const DynamicLinker = struct { buffer: [255]u8 = undefined, }; }; comptime { S.CrossTarget.parse(); S.CrossTarget.parse(); } }
test/behavior/eval_stage1.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const data = @embedFile("data/day19.txt"); const EntriesList = std.ArrayList(Record); const Found = error { MatchFound }; const Rest = struct { remain: std.ArrayList(u8), search: []const u8 = undefined, fn init(allocator: *Allocator) !Rest { var remain = std.ArrayList(u8).init(allocator); try remain.ensureCapacity(400); return Rest{ .remain = remain }; } pub fn match(self: *Rest, search: []const u8) bool { self.remain.items.len = 0; self.search = search; self.matchRecord(records[0], 0) catch return true; return false; } fn push(self: *Rest, val: u8) void { self.remain.append(val) catch unreachable; } fn pop(self: *Rest, val: u8) void { assert(self.remain.pop() == val); } inline fn matchRest(self: *Rest, pos: u8) Found!void { if (self.remain.items.len == 0) { if (pos == self.search.len) { return error.MatchFound; } return; // no match found, try again } if (pos >= self.search.len) { return; // no match found, try again } // try to match the rest of the string const next = self.remain.pop(); try self.matchRecord(records[next], pos); // match failed, put it back. self.remain.append(next) catch unreachable; } fn matchRecord(self: *Rest, record: Record, pos: u8) Found!void { return switch (record) { .none => unreachable, .pair => |pair| try self.matchPair(pair, pos), .choice => |choice| { switch (choice.first) { .pair => |pair| try self.matchPair(pair, pos), .indirect => |idx| try self.matchRecord(records[idx], pos), } switch (choice.second) { .pair => |pair| try self.matchPair(pair, pos), .indirect => |idx| try self.matchRecord(records[idx], pos), } }, .literal => |lit| { if (pos < self.search.len and self.search[pos] == lit.char) { try self.matchRest(pos + 1); } }, .indirect => |ind| try self.matchRecord(records[ind], pos), }; } inline fn matchPair(self: *Rest, pair: Pair, pos: u8) Found!void { self.push(pair.second); try self.matchRecord(records[pair.first], pos); self.pop(pair.second); } }; const Literal = struct { char: u8, }; const Pair = struct { first: u8, second: u8, }; const ChoiceElem = union(enum) { pair: Pair, indirect: u8, }; const Choice = struct { first: ChoiceElem, second: ChoiceElem, }; const Record = union(enum) { none: void, pair: Pair, choice: Choice, literal: Literal, indirect: u8, }; var records = [_]Record{ .{ .none={} } } ** 256; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var lines = std.mem.split(data, "\n"); var entries = EntriesList.init(ally); try entries.ensureCapacity(400); var result: usize = 0; while (lines.next()) |line| { if (line.len == 0) break; var parts = std.mem.tokenize(line, ": "); const index = std.fmt.parseUnsigned(u8, parts.next().?, 10) catch unreachable; var rec: Record = .none; const first = parts.next().?; if (first[0] == '"') { rec = .{ .literal = .{ .char = first[1] }}; } else { const part0 = std.fmt.parseUnsigned(u8, first, 10) catch unreachable; if (parts.next()) |str1| { if (str1[0] == '|') { const part1 = std.fmt.parseUnsigned(u8, parts.next().?, 10) catch unreachable; if (parts.next()) |str2| { const part2 = std.fmt.parseUnsigned(u8, str2, 10) catch unreachable; rec = .{ .choice = .{ .first = .{ .indirect = part0 }, .second = .{ .pair = .{ .first = part1, .second = part2 }}, }}; assert(parts.next() == null); } else { rec = .{ .choice = .{ .first = .{ .indirect = part0 }, .second = .{ .indirect = part1 }, }}; } } else { const part1 = std.fmt.parseUnsigned(u8, str1, 10) catch unreachable; if (parts.next()) |str2| { assert(std.mem.eql(u8, str2, "|")); const part2 = std.fmt.parseUnsigned(u8, parts.next().?, 10) catch unreachable; const part3 = std.fmt.parseUnsigned(u8, parts.next().?, 10) catch unreachable; rec = .{ .choice = .{ .first = .{ .pair = .{ .first = part0, .second = part1 }}, .second = .{ .pair = .{ .first = part2, .second = part3 }}, }}; } else { rec = .{ .pair = .{ .first = part0, .second = part1 }}; } } } else { rec = .{ .indirect = part0 }; } } records[index] = rec; } var rest = try Rest.init(ally); while (lines.next()) |line| { if (line.len == 0) continue; if (rest.match(line)) { result += 1; print("matched: {}\n", .{line}); } } print("Result: {}\n", .{result}); }
src/day19.zig
const std = @import("std"); const utils = @import("../util.zig"); const Ansi = @import("./code.zig").Ansi; const Style = @import("./style.zig").Style; const control_code = std.ascii.control_code; const os = std.os; const io = std.io; const fmt = std.fmt; const print = std.debug.print; const reader = io.getStdIn().reader(); const writer = io.getStdIn().writer(); /// Struct Version of the escape sequence with pub const Color = enum(u8) { black = 0, red = 1, green = 2, yellow = 3, blue = 4, magenta = 5, cyan = 6, white = 7, rgb = 8, const Self = @This(); pub fn toCode(comptime self: Self, spec: Spec) []const u8 { const scode = spec.toCode(); return scode ++ switch (self) { .black => "0", .red => "1", .green => "2", .yellow => "3", .blue => "4", .magenta => "5", .cyan => "6", .white => "7", .rgb => "8", }; } pub fn index() []const u8 { return "\x1B[38;5m"; } pub fn fg(comptime self: Self) []const u8 { const colcode = comptime self.toCode(Spec.normal_fg); return Spec.prefix() ++ colcode ++ Style.none(); } pub fn bg(comptime self: Self) []const u8 { const colcode = comptime self.toCode(Spec.normal_bg); return Spec.prefix() ++ colcode ++ Style.none(); } pub fn bfg(comptime self: Self) []const u8 { const colcode = comptime self.toCode(Spec.bright_bg); return Spec.prefix() ++ colcode ++ Style.none(); } pub fn bbg(comptime self: Self) []const u8 { const colcode = comptime self.toCode(Spec.bright_bg); return Spec.prefix() ++ colcode ++ Style.none(); } pub fn toPre(comptime self: Self, comptime spec: Spec) []const u8 { return Spec.prefix() ++ self.toCode(spec); } pub fn toPreParams(comptime self: Self, comptime bri: Spec.Brightness, comptime loc: Spec.Location) []const u8 { return Color.toPre(self, comptime Spec.init(bri, loc)); } pub fn toInt(self: Self) u8 { return @enumToInt(self); } pub fn styled(self: Self, comptime style: Style, comptime spec: ?Spec) []const u8 { const seq = comptime self.toPre(spec orelse Spec.default()); return seq ++ style.toCode(); } pub fn finish(self: Self, comptime spec: ?Spec) []const u8 { return comptime self.toPre(spec orelse Spec.default()) ++ "m"; } pub fn bold(comptime self: Self, comptime spec: ?Spec) []const u8 { return self.styled(Style.bold, spec); } pub fn dim(comptime self: Self, comptime spec: ?Spec) []const u8 { return self.styled(Style.dim, spec); } pub fn underline(comptime self: Self, comptime spec: ?Spec) []const u8 { return self.styled(Style.underline, spec); } pub fn italic(comptime self: Self, comptime spec: ?Spec) []const u8 { return self.styled(Style.italic, spec); } pub fn blink(comptime self: Self, comptime spec: ?Spec) []const u8 { return self.styled(Style.blink, spec); } pub fn write(comptime self: Self, comptime spec: ?Spec, comptime style: ?Style) void { const sp = spec orelse Spec.default(); const sty = style orelse Style.none(); try std.io.getStdOut().writer().writeAll(self.styled(comptime sty, comptime sp)); } pub const Spec = enum(u8) { normal_fg = 3, normal_bg = 4, bright_fg = 9, bright_bg = 10, const Self = @This(); pub fn default() Spec { return .normal_fg; } pub fn toCode(self: Spec) []const u8 { return switch (self) { .normal_fg => "3", .normal_bg => "4", .bright_fg => "9", .bright_bg => "10", }; } pub fn init(bri: Brightness, loc: Location) Spec { return switch (bri) { Brightness.normal => switch (loc) { Location.fg => Spec.normal_fg, Location.bg => Spec.normal_bg, }, Brightness.bright => switch (loc) { Location.fg => Spec.bright_fg, Location.bg => Spec.bright_bg, }, }; } pub fn len(comptime self: Spec) u8 { return comptime switch (self) { .bright_bg => 2, else => 1, } + Ansi.esc().len; } pub fn prefix() []const u8 { return Ansi.esc() ++ "["; // length 2, or 3 if bright_bg } pub fn toInt(self: Spec) u8 { return @enumToInt(self); } pub fn fmtAnsi(comptime self: Spec, ansi: Ansi) []const u8 { return Ansi.toNumString(ansi) ++ self.toNumString(); } pub fn expandAnsi(self: Spec, asc: []u8) []const u8 { return asc ++ self.toCode(); } pub const Location = enum { fg, bg, }; pub const Brightness = enum { bright, normal }; }; }; pub fn reset() []const u8 { return Ansi.esc() ++ "[0m"; } pub fn writeReset() void { try std.io.getStdOut().writer().writeAll("\x1B[0m"); } pub const Fg = packed struct { pub const Br = struct { pub const gray = "\x1B[30;1m"; pub const red = "\x1B[31;1m"; pub const green = "\x1B[32;1m"; pub const yellow = "\x1B[33;1m"; pub const blue = "\x1B[34;1m"; pub const magenta = "\x1B[35;1m"; pub const cyan = "\x1B[36;1m"; pub const white = "\x1B[37;1m"; }; pub const black = "\x1B[30m"; pub const red = "\x1B[31m"; pub const green = "\x1B[32m"; pub const yellow = "\x1B[33m"; pub const blue = "\x1B[34m"; pub const magenta = "\x1B[35m"; pub const cyan = "\x1B[36m"; pub const white = "\x1B[37m"; }; pub const Bg = packed struct { pub const Br = struct { pub const gray = "\x1B[40;1m"; pub const red = "\x1B[41;1m"; pub const green = "\x1B[42;1m"; pub const yellow = "\x1B[43;1m"; pub const blue = "\x1B[44;1m"; pub const magenta = "\x1B[45;1m"; pub const cyan = "\x1B[46;1m"; pub const white = "\x1B[47;1m"; }; pub const black = "\x1B[40m"; pub const red = "\x1B[41m"; pub const green = "\x1B[42m"; pub const yellow = "\x1B[43m"; pub const blue = "\x1B[44m"; pub const magenta = "\x1B[45m"; pub const cyan = "\x1B[46m"; pub const white = "\x1B[47m"; }; const expect = std.testing.expect; test "Spec init" { const spec = Color.Spec.init(.normal, .fg); std.log.warn(" {s}: {d}", .{ spec, spec.toInt() }); try expect(spec.toInt() == 3); } test "Color init" { const col = Color.blue; std.log.warn(" {s}: {d}", .{ col, col.toInt() }); try expect(Color.toInt(.blue) == 4); } test "Color toCode" { const spec = comptime Color.Spec.init(.normal, .bg); const col = comptime Color.red; const code = comptime col.toCode(spec); const pre = comptime col.toPre(spec); std.log.warn(" {s} + {s}: {s}", .{ col, spec, code }); // try expect(std.mem.eql(u8, code, "102")); std.log.warn("Prefix len: {d}", .{spec.len()}); std.log.warn("{s}m This should have bright red bg{s} and now reset", .{ pre, reset() }); std.log.warn("{s} This should have bright red bg{s} and now reset", .{ Color.blue.bg(), reset() }); try expect(std.mem.eql(u8, code, "41") and std.mem.eql(u8, pre, "\x1B[41")); } test "Color toPre" { const bgrfg = comptime Color.toPre(.green, .bright_fg); std.log.warn("{s}m This should have bright green fg{s} and now reset", .{ bgrfg, reset() }); try expect(std.mem.eql(u8, bgrfg, "\x1B[92")); } test "Color bold" { const col = comptime Color.bold(.yellow, .bright_fg); std.log.warn("{s} This should be bright green fg and bold{s} and now reset", .{ col, reset() }); }
src/term/colors.zig
const std = @import("std"); const c = @cImport({ @cInclude("src/cursesflags.h"); @cInclude("curses.h"); }); const Error = error.CursesError; fn checkError(res: c_int) !c_int { if (res == c.ERR) { return Error; } return res; } pub const KEY_RESIZE: c_int = c.KEY_RESIZE; pub const KEY_LEFT: c_int = c.KEY_LEFT; pub const KEY_RIGHT: c_int = c.KEY_RIGHT; pub const KEY_UP: c_int = c.KEY_UP; pub const KEY_DOWN: c_int = c.KEY_DOWN; pub const Window = struct { win: *c.WINDOW, allocator: *std.mem.Allocator, // TODO: change more things to Window methods pub fn erase(self: Window) !void { _ = try checkError(c.werase(self.win)); } pub fn mvaddstr(self: Window, y: u16, x: u16, str: []const u8) !void { const cstr: []u8 = try self.allocator.alloc(u8, str.len + 1); defer self.allocator.free(cstr); std.mem.copy(u8, cstr, str); cstr[str.len] = 0; _ = try checkError(c.mvwaddstr(self.win, y, x, cstr.ptr)); } // TODO: don't use "legacy" functions like getmaxy()? pub fn getmaxy(self: Window) u16 { return @intCast(u16, c.getmaxy(self.win)); } pub fn getmaxx(self: Window) u16 { return @intCast(u16, c.getmaxx(self.win)); } pub fn attron(self: Window, attr: c_int) !void { _ = try checkError(c.wattron(self.win, attr)); } pub fn attroff(self: Window, attr: c_int) !void { _ = try checkError(c.wattroff(self.win, attr)); } pub fn keypad(self: Window, bf: bool) !c_int { return checkError(c.keypad(self.win, bf)); } pub fn getch(self: Window) !c_int { return checkError(c.wgetch(self.win)); } }; pub const A_STANDOUT = c.MY_A_STANDOUT; pub fn initscr(allocator: *std.mem.Allocator) !Window { const res = c.initscr(); if (@ptrToInt(res) == 0) { return Error; } return Window{ .win = res, .allocator = allocator }; } pub fn endwin() !void { _ = try checkError(c.endwin()); } pub fn curs_set(visibility: c_int) !c_int { return try checkError(c.curs_set(visibility)); } pub fn has_colors() bool { return c.has_colors(); } pub fn start_color() !void { _ = try checkError(c.start_color()); } const color_pair_attrs = comptime[_]c_int{ -1, // 0 doesn't seem to be a valid color pair number, curses returns ERR for it c.MY_COLOR_PAIR_1, c.MY_COLOR_PAIR_2, c.MY_COLOR_PAIR_3, c.MY_COLOR_PAIR_4, c.MY_COLOR_PAIR_5, c.MY_COLOR_PAIR_6, c.MY_COLOR_PAIR_7, c.MY_COLOR_PAIR_8, c.MY_COLOR_PAIR_9, c.MY_COLOR_PAIR_10, }; pub const ColorPair = struct { id: c_short, pub fn init(id: c_short, front: c_short, back: c_short) !ColorPair { std.debug.assert(1 <= id and id < @intCast(c_short, color_pair_attrs.len)); _ = try checkError(c.init_pair(id, front, back)); return ColorPair{ .id = id }; } pub fn attr(self: ColorPair) c_int { return color_pair_attrs[@intCast(usize, self.id)]; } }; // listed in init_pair man page pub const COLOR_BLACK = c.COLOR_BLACK; pub const COLOR_RED = c.COLOR_RED; pub const COLOR_GREEN = c.COLOR_GREEN; pub const COLOR_YELLOW = c.COLOR_YELLOW; pub const COLOR_BLUE = c.COLOR_BLUE; pub const COLOR_MAGENTA = c.COLOR_MAGENTA; pub const COLOR_CYAN = c.COLOR_CYAN; pub const COLOR_WHITE = c.COLOR_WHITE;
src/curses.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; pub usingnamespace sf.window; }; const RenderWindow = @This(); // Constructor/destructor /// Inits a render window with a size, a bits per pixel (most put 32) a title, a style and context settings pub fn create(size: sf.Vector2u, bpp: usize, title: [:0]const u8, style: u32, settings: ?sf.ContextSettings) !RenderWindow { var ret: RenderWindow = undefined; var mode: sf.c.sfVideoMode = .{ .width = @intCast(c_uint, size.x), .height = @intCast(c_uint, size.y), .bitsPerPixel = @intCast(c_uint, bpp), }; const c_settings = if (settings) |s| s._toCSFML() else null; var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), style, if (c_settings) |s| &s else null); if (window) |w| { ret._ptr = w; } else return sf.Error.windowCreationFailed; return ret; } /// Inits a render window with a size and a title /// The window will have the default style pub fn createDefault(size: sf.Vector2u, title: [:0]const u8) !RenderWindow { var ret: RenderWindow = undefined; var mode: sf.c.sfVideoMode = .{ .width = @intCast(c_uint, size.x), .height = @intCast(c_uint, size.y), .bitsPerPixel = 32, }; var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), sf.window.Style.defaultStyle, null); if (window) |w| { ret._ptr = w; } else return sf.Error.windowCreationFailed; return ret; } /// Inits a rendering plane from a window handle. The handle can actually be to any drawing surface. pub fn createFromHandle(handle: sf.WindowHandle, settings: ?sf.ContextSettings) !RenderWindow { const c_settings = if (settings) |s| s._toCSFML() else null; const window = sf.c.sfRenderWindow_createFromHandle(handle, if (c_settings) |s| &s else null); if (window) |w| { return .{ ._ptr = w }; } else return sf.Error.windowCreationFailed; } /// Destroys this window object pub fn destroy(self: *RenderWindow) void { sf.c.sfRenderWindow_destroy(self._ptr); self._ptr = undefined; } // Event related /// Returns true if this window is still open pub fn isOpen(self: RenderWindow) bool { return sf.c.sfRenderWindow_isOpen(self._ptr) != 0; } /// Closes this window pub fn close(self: *RenderWindow) void { sf.c.sfRenderWindow_close(self._ptr); } /// Gets an event from the queue, returns null is theres none /// Use while on this to get all the events in your game loop pub fn pollEvent(self: *RenderWindow) ?sf.window.Event { var event: sf.c.sfEvent = undefined; if (sf.c.sfRenderWindow_pollEvent(self._ptr, &event) == 0) return null; // Skip sfEvtMouseWheelMoved to avoid sending mouseWheelScrolled twice if (event.type == sf.c.sfEvtMouseWheelMoved) { return self.pollEvent(); } return sf.window.Event._fromCSFML(event); } // Drawing functions /// Clears the drawing screen with a color pub fn clear(self: *RenderWindow, color: sf.Color) void { sf.c.sfRenderWindow_clear(self._ptr, color._toCSFML()); } /// Displays what has been drawn on the render area pub fn display(self: *RenderWindow) void { sf.c.sfRenderWindow_display(self._ptr); } /// Draw something on the screen (won't be visible until display is called) /// Object must have a sfDraw function (look at CircleShape for reference) /// You can pass a render state or null for default pub fn draw(self: *RenderWindow, to_draw: anytype, states: ?sf.RenderStates) void { const T = @TypeOf(to_draw); if (comptime @import("std").meta.trait.hasFn("sfDraw")(T)) { // Inline call of object's draw function if (states) |s| { var cstates = s._toCSFML(); @call(.{ .modifier = .always_inline }, T.sfDraw, .{ to_draw, self.*, &cstates }); } else @call(.{ .modifier = .always_inline }, T.sfDraw, .{ to_draw, self.*, null }); // to_draw.sfDraw(self, states); } else @compileError("You must provide a drawable object (struct with \"sfDraw\" method)."); } // Getters/setters /// Gets the current view of the window /// Unlike in SFML, you don't get a const pointer but a copy pub fn getView(self: RenderWindow) sf.View { return sf.View._fromCSFML(sf.c.sfRenderWindow_getView(self._ptr).?); } /// Gets the default view of this window /// Unlike in SFML, you don't get a const pointer but a copy pub fn getDefaultView(self: RenderWindow) sf.View { return sf.View._fromCSFML(sf.c.sfRenderWindow_getDefaultView(self._ptr).?); } /// Sets the view of this window pub fn setView(self: *RenderWindow, view: sf.View) void { var cview = view._toCSFML(); defer sf.c.sfView_destroy(cview); sf.c.sfRenderWindow_setView(self._ptr, cview); } /// Gets the viewport of this render target pub fn getViewport(self: RenderWindow, view: sf.View) sf.IntRect { return sf.IntRect._fromCSFML(sf.c.sfRenderWindow_getViewPort(self._ptr, view._ptr)); } /// Set mouse cursor grabbing pub fn setMouseCursorGrabbed(self: *RenderWindow, grab: bool) void { sf.c.sfRenderWindow_setMouseCursorGrabbed(self._ptr, @boolToInt(grab)); } /// Set mouse cursor visibility pub fn setMouseCursorVisible(self: *RenderWindow, visible: bool) void { sf.c.sfRenderWindow_setMouseCursorVisible(self._ptr, @boolToInt(visible)); } /// Gets the size of this window pub fn getSize(self: RenderWindow) sf.Vector2u { return sf.Vector2u._fromCSFML(sf.c.sfRenderWindow_getSize(self._ptr)); } /// Sets the size of this window pub fn setSize(self: *RenderWindow, size: sf.Vector2u) void { sf.c.sfRenderWindow_setSize(self._ptr, size._toCSFML()); } /// Gets the position of this window pub fn getPosition(self: RenderWindow) sf.Vector2i { return sf.Vector2i._fromCSFML(sf.c.sfRenderWindow_getPosition(self._ptr)); } /// Sets the position of this window pub fn setPosition(self: *RenderWindow, pos: sf.Vector2i) void { sf.c.sfRenderWindow_setPosition(self._ptr, pos._toCSFML()); } /// Sets the title of this window pub fn setTitle(self: *RenderWindow, title: [:0]const u8) void { sf.c.sfRenderWindow_setTitle(self._ptr, title); } /// Sets the title of this window, in unicode pub fn setUnicodeTitle(self: *RenderWindow, comptime title_utf8: []const u8) void { const utils = @import("../utils.zig"); const u32string = utils.utf8toUnicode(title_utf8); sf.c.sfRenderWindow_setUnicodeTitle(self._ptr, u32string.ptr); } /// Sets the windows's framerate limit pub fn setFramerateLimit(self: *RenderWindow, fps: c_uint) void { sf.c.sfRenderWindow_setFramerateLimit(self._ptr, fps); } /// Enables or disables vertical sync pub fn setVerticalSyncEnabled(self: *RenderWindow, enabled: bool) void { sf.c.sfRenderWindow_setVerticalSyncEnabled(self._ptr, @boolToInt(enabled)); } /// Convert a point from target coordinates to world coordinates, using the current view (or the specified view) pub fn mapPixelToCoords(self: RenderWindow, pixel: sf.Vector2i, view: ?sf.View) sf.Vector2f { if (view) |v| { var cview = v._toCSFML(); defer sf.c.sfView_destroy(cview); return sf.Vector2f._fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self._ptr, pixel._toCSFML(), cview)); } else return sf.Vector2f._fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self._ptr, pixel._toCSFML(), null)); } /// Convert a point from world coordinates to target coordinates, using the current view (or the specified view) pub fn mapCoordsToPixel(self: RenderWindow, coords: sf.Vector2f, view: ?sf.View) sf.Vector2i { if (view) |v| { var cview = v._toCSFML(); defer sf.c.sfView_destroy(cview); return sf.Vector2i._fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self._ptr, coords._toCSFML(), cview)); } else return sf.Vector2i._fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self._ptr, coords._toCSFML(), null)); } /// Pointer to the csfml structure _ptr: *sf.c.sfRenderWindow
src/sfml/graphics/RenderWindow.zig
const std = @import("std"); const mem = std.mem; const assert = std.debug.assert; const print = std.debug.print; const err = std.log.err; const warn = std.log.warn; // Helper functions /// Initialize registers pub fn init_reg() [4]u32 { return [1]u32{ 0 } ** 4; } /// Warn that an operator is currently in todo fn todo() void { warn("TODO", .{}); } /// Opcodes /// This is not written in the code, but documented here instead. /// Here is the list of opcodes: /// 0000: HALT /// 1xkk: SET Vx, kk /// 2ab[1-5]: [ADD, SUB, MUL, DIV, MOD] a, b -> a /// 3x01: WRITE Vx /// 3x02: READ Vx /// 40nn: JMP nn /// 5xy[1-6]: Comparison operators /// PC (Program counter) var pc: u32 = undefined; /// Running flag (runs the program until this is false) var running: bool = true; /// VM pub const VM = struct { reg: [4]u32, // Registers program: []u32, // Program /// Fetch the instruction from the program at PC fn fetch(self: VM) u32 { const instr = self.program[pc]; pc = pc + 1; return instr; } /// Decode instruction fn decode(instr: u32) [4]u32 { var opcode = (instr & 0xF000) >> 12; var reg1 = (instr & 0xF00 ) >> 8; var reg2 = (instr & 0xF0 ) >> 4; var val = (instr & 0xFF ); return [4]u32{opcode, reg1, reg2, val}; } /// Debugging pub fn debug(self: VM) void { print("Registers: {X:0>4} ", .{self.reg}); print("PC: {d}\n", .{pc}); } /// Evaluate the decoded instruction fn eval(self: *VM) void { var instr = self.fetch(); var decoded = decode(instr); var opcode = decoded[0]; var reg1 = decoded[1]; var reg2 = decoded[2]; var val = decoded[3]; switch (opcode) { 0 => { running = false; print("halt\n", .{}); }, 1 => { self.reg[reg1] = val; print("set r{d}, #{X} ({d})\n", .{reg1, val, val}); }, 2 => { var mode = (val & 0xF); switch (mode) { 1 => { self.reg[reg1] = self.reg[reg1] + self.reg[reg2]; print("add r{d}, r{d} -> r{d}\n", .{reg1, reg2, reg1}); }, 2 => { self.reg[reg1] = self.reg[reg1] - self.reg[reg2]; print("sub r{d}, r{d} -> r{d}\n", .{reg1, reg2, reg1}); }, 3 => { self.reg[reg1] = self.reg[reg1] * self.reg[reg2]; print("mul r{d}, r{d} -> r{d}\n", .{reg1, reg2, reg1}); }, 4 => { self.reg[reg1] = self.reg[reg1] / self.reg[reg2]; print("div r{d}, r{d} -> r{d}\n", .{reg1, reg2, reg1}); }, 5 => { self.reg[reg1] = self.reg[reg1] % self.reg[reg2]; print("mod r{d}, r{d} -> r{d}\n", .{reg1, reg2, reg1}); }, else => err("Unknown mode for opcode 2 => {d:0>2}", .{mode}), } }, 3 => { var mode = val; switch (mode) { 1 => { print("{d}\n", .{self.reg[reg1]}); print("write r{d}\n", .{reg1}); }, 2 => todo(), else => err("Unknown mode for opcode 3 => {d:0>2}", .{mode}), } }, 4 => { pc = val; print("jmp #{X:0>2} ({d})\n", .{val, val}); }, else => err("Unknown opcode => {x}", .{opcode}), } self.debug(); // Print debug info after eval } /// Run the program pub fn run(self: *VM) void { while (running) { self.eval(); } } }; pub fn main() !void { // There will be CLI in here, but it is empty for now. var program = [_]u32{ 0x4002, 0x0000, 0x1064, 0x3001, 0x4001 }; const sliced = program[0..program.len]; var vm = VM{ .reg = init_reg(), .program = sliced, }; vm.run(); }
src/main.zig
pub const WasiHandle = i32; pub const Char8 = u8; pub const Char32 = u32; pub fn WasiPtr(comptime T: type) type { return [*c]const T; } pub fn WasiMutPtr(comptime T: type) type { return [*c]T; } pub const WasiStringBytesPtr = WasiPtr(Char8); pub const WasiString = extern struct { ptr: WasiStringBytesPtr, len: usize, fn from_slice(slice: []const u8) WasiString { return WasiString{ .ptr = slice.ptr, .len = slice.len }; } fn as_slice(wasi_string: WasiString) []const u8 { return wasi_string.ptr[wasi_string.len]; } }; pub fn WasiSlice(comptime T: type) type { return extern struct { ptr: WasiPtr(T), len: usize, fn from_slice(slice: []const u8) WasiSlice { return WasiSlice{ .ptr = slice.ptr, .len = slice.len }; } fn as_slice(wasi_slice: WasiSlice) []const u8 { return wasi_slice.ptr[wasi_slice.len]; } }; } pub fn WasiMutSlice(comptime T: type) type { return extern struct { ptr: WasiMutPtr(T), len: usize, fn from_slice(slice: []u8) WasiMutSlice { return WasiMutSlice{ .ptr = slice.ptr, .len = slice.len }; } fn as_slice(wasi_slice: WasiMutSlice) []u8 { return wasi_slice.ptr[wasi_slice.len]; } }; } // ---------------------- Module: [wasi_ephemeral_crypto_symmetric] ---------------------- /// Error codes. pub const CryptoErrno = enum(u16) { SUCCESS = 0, GUEST_ERROR = 1, NOT_IMPLEMENTED = 2, UNSUPPORTED_FEATURE = 3, PROHIBITED_OPERATION = 4, UNSUPPORTED_ENCODING = 5, UNSUPPORTED_ALGORITHM = 6, UNSUPPORTED_OPTION = 7, INVALID_KEY = 8, INVALID_LENGTH = 9, VERIFICATION_FAILED = 10, RNG_ERROR = 11, ALGORITHM_FAILURE = 12, INVALID_SIGNATURE = 13, CLOSED = 14, INVALID_HANDLE = 15, OVERFLOW = 16, INTERNAL_ERROR = 17, TOO_MANY_HANDLES = 18, KEY_NOT_SUPPORTED = 19, KEY_REQUIRED = 20, INVALID_TAG = 21, INVALID_OPERATION = 22, NONCE_REQUIRED = 23, INVALID_NONCE = 24, OPTION_NOT_SET = 25, NOT_FOUND = 26, PARAMETERS_MISSING = 27, IN_PROGRESS = 28, INCOMPATIBLE_KEYS = 29, EXPIRED = 30, }; /// Encoding to use for importing or exporting a key pair. pub const KeypairEncoding = enum(u16) { RAW = 0, PKCS_8 = 1, PEM = 2, LOCAL = 3, }; /// Encoding to use for importing or exporting a public key. pub const PublickeyEncoding = enum(u16) { RAW = 0, PKCS_8 = 1, PEM = 2, SEC = 3, COMPRESSED_SEC = 4, LOCAL = 5, }; /// Encoding to use for importing or exporting a secret key. pub const SecretkeyEncoding = enum(u16) { RAW = 0, PKCS_8 = 1, PEM = 2, SEC = 3, COMPRESSED_SEC = 4, LOCAL = 5, }; /// Encoding to use for importing or exporting a signature. pub const SignatureEncoding = enum(u16) { RAW = 0, DER = 1, }; /// An algorithm category. pub const AlgorithmType = enum(u16) { SIGNATURES = 0, SYMMETRIC = 1, KEY_EXCHANGE = 2, }; /// Version of a managed key. /// /// A version can be an arbitrary `u64` integer, with the expection of some reserved values. pub const Version = u64; /// Size of a value. pub const Size = usize; /// A UNIX timestamp, in seconds since 01/01/1970. pub const Timestamp = u64; /// A 64-bit value pub const U64 = u64; /// Handle for functions returning output whose size may be large or not known in advance. /// /// An `array_output` object contains a host-allocated byte array. /// /// A guest can get the size of that array after a function returns in order to then allocate a buffer of the correct size. /// In addition, the content of such an object can be consumed by a guest in a streaming fashion. /// /// An `array_output` handle is automatically closed after its full content has been consumed. pub const ArrayOutput = WasiHandle; /// A set of options. /// /// This type is used to set non-default parameters. /// /// The exact set of allowed options depends on the algorithm being used. pub const Options = WasiHandle; /// A handle to the optional secrets management facilities offered by a host. /// /// This is used to generate, retrieve and invalidate managed keys. pub const SecretsManager = WasiHandle; /// A key pair. pub const Keypair = WasiHandle; /// A state to absorb data to be signed. /// /// After a signature has been computed or verified, the state remains valid for further operations. /// /// A subsequent signature would sign all the data accumulated since the creation of the state object. pub const SignatureState = WasiHandle; /// A signature. pub const Signature = WasiHandle; /// A public key, for key exchange and signature verification. pub const Publickey = WasiHandle; /// A secret key, for key exchange mechanisms. pub const Secretkey = WasiHandle; /// A state to absorb signed data to be verified. pub const SignatureVerificationState = WasiHandle; /// A state to perform symmetric operations. /// /// The state is not reset nor invalidated after an option has been performed. /// Incremental updates and sessions are thus supported. pub const SymmetricState = WasiHandle; /// A symmetric key. /// /// The key can be imported from raw bytes, or can be a reference to a managed key. /// /// If it was imported, the host will wipe it from memory as soon as the handle is closed. pub const SymmetricKey = WasiHandle; /// An authentication tag. /// /// This is an object returned by functions computing authentication tags. /// /// A tag can be compared against another tag (directly supplied as raw bytes) in constant time with the `symmetric_tag_verify()` function. /// /// This object type can't be directly created from raw bytes. They are only returned by functions computing MACs. /// /// The host is reponsible for securely wiping them from memory on close. pub const SymmetricTag = WasiHandle; /// Options index, only required by the Interface Types translation layer. pub const OptOptionsU = enum(u8) { SOME = 0, NONE = 1, }; /// An optional options set. /// /// This union simulates an `Option<Options>` type to make the `options` parameter of some functions optional. pub const OptOptions = extern struct { tag: enum(u8) { some = 0, none = 1, }, __pad8_0: u8 = undefined, __pad16_0: u16 = undefined, __pad32_0: u32 = undefined, member = extern union { some: Options, }, fn newSome(val: Options) OptOptions { return OptOptions{ .tag = .some, .member = .{ .some = val } }; } pub fn Some(self: OptOptions) Options { std.debug.assert(self.tag == .some); return self.member.some; } pub fn setSome(self: *OptOptions, val: Options) void { std.debug.assert(self.tag == .some); self.member.some = val; } fn isSome(self: OptOptions) bool { return self.tag == .some; } fn newNone() OptOptions { return OptOptions{ .tag = .none }; } fn isNone(self: OptOptions) bool { return self.tag == .none; } }; /// Symmetric key index, only required by the Interface Types translation layer. pub const OptSymmetricKeyU = enum(u8) { SOME = 0, NONE = 1, }; /// An optional symmetric key. /// /// This union simulates an `Option<SymmetricKey>` type to make the `symmetric_key` parameter of some functions optional. pub const OptSymmetricKey = extern struct { tag: enum(u8) { some = 0, none = 1, }, __pad8_0: u8 = undefined, __pad16_0: u16 = undefined, __pad32_0: u32 = undefined, member = extern union { some: SymmetricKey, }, fn newSome(val: SymmetricKey) OptSymmetricKey { return OptSymmetricKey{ .tag = .some, .member = .{ .some = val } }; } pub fn Some(self: OptSymmetricKey) SymmetricKey { std.debug.assert(self.tag == .some); return self.member.some; } pub fn setSome(self: *OptSymmetricKey, val: SymmetricKey) void { std.debug.assert(self.tag == .some); self.member.some = val; } fn isSome(self: OptSymmetricKey) bool { return self.tag == .some; } fn newNone() OptSymmetricKey { return OptSymmetricKey{ .tag = .none }; } fn isNone(self: OptSymmetricKey) bool { return self.tag == .none; } }; pub const WasiEphemeralCryptoSymmetric = struct { /// Generate a new symmetric key for a given algorithm. /// /// `options` can be `None` to use the default parameters, or an algoritm-specific set of parameters to override. /// /// This function may return `unsupported_feature` if key generation is not supported by the host for the chosen algorithm, or `unsupported_algorithm` if the algorithm is not supported by the host. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_generate( algorithm_ptr: WasiPtr(Char8), algorithm_len: usize, options: OptOptions, result_ptr: WasiMutPtr(SymmetricKey), ) callconv(.C) CryptoErrno; /// Create a symmetric key from raw material. /// /// The algorithm is internally stored along with the key, and trying to use the key with an operation expecting a different algorithm will return `invalid_key`. /// /// The function may also return `unsupported_algorithm` if the algorithm is not supported by the host. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_import( algorithm_ptr: WasiPtr(Char8), algorithm_len: usize, raw: WasiPtr(u8), raw_len: Size, result_ptr: WasiMutPtr(SymmetricKey), ) callconv(.C) CryptoErrno; /// Export a symmetric key as raw material. /// /// This is mainly useful to export a managed key. /// /// May return `prohibited_operation` if this operation is denied. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_export( symmetric_key: SymmetricKey, result_ptr: WasiMutPtr(ArrayOutput), ) callconv(.C) CryptoErrno; /// Destroy a symmetric key. /// /// Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_close( symmetric_key: SymmetricKey, ) callconv(.C) CryptoErrno; /// __(optional)__ /// Generate a new managed symmetric key. /// /// The key is generated and stored by the secrets management facilities. /// /// It may be used through its identifier, but the host may not allow it to be exported. /// /// The function returns the `unsupported_feature` error code if secrets management facilities are not supported by the host, /// or `unsupported_algorithm` if a key cannot be created for the chosen algorithm. /// /// The function may also return `unsupported_algorithm` if the algorithm is not supported by the host. /// /// This is also an optional import, meaning that the function may not even exist. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_generate_managed( secrets_manager: SecretsManager, algorithm_ptr: WasiPtr(Char8), algorithm_len: usize, options: OptOptions, result_ptr: WasiMutPtr(SymmetricKey), ) callconv(.C) CryptoErrno; /// __(optional)__ /// Store a symmetric key into the secrets manager. /// /// On success, the function stores the key identifier into `$symmetric_key_id`, /// into which up to `$symmetric_key_id_max_len` can be written. /// /// The function returns `overflow` if the supplied buffer is too small. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_store_managed( secrets_manager: SecretsManager, symmetric_key: SymmetricKey, symmetric_key_id: WasiMutPtr(u8), symmetric_key_id_max_len: Size, ) callconv(.C) CryptoErrno; /// __(optional)__ /// Replace a managed symmetric key. /// /// This function crates a new version of a managed symmetric key, by replacing `$kp_old` with `$kp_new`. /// /// It does several things: /// /// - The key identifier for `$symmetric_key_new` is set to the one of `$symmetric_key_old`. /// - A new, unique version identifier is assigned to `$kp_new`. This version will be equivalent to using `$version_latest` until the key is replaced. /// - The `$symmetric_key_old` handle is closed. /// /// Both keys must share the same algorithm and have compatible parameters. If this is not the case, `incompatible_keys` is returned. /// /// The function may also return the `unsupported_feature` error code if secrets management facilities are not supported by the host, /// or if keys cannot be rotated. /// /// Finally, `prohibited_operation` can be returned if `$symmetric_key_new` wasn't created by the secrets manager, and the secrets manager prohibits imported keys. /// /// If the operation succeeded, the new version is returned. /// /// This is an optional import, meaning that the function may not even exist. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_replace_managed( secrets_manager: SecretsManager, symmetric_key_old: SymmetricKey, symmetric_key_new: SymmetricKey, result_ptr: WasiMutPtr(Version), ) callconv(.C) CryptoErrno; /// __(optional)__ /// Return the key identifier and version of a managed symmetric key. /// /// If the key is not managed, `unsupported_feature` is returned instead. /// /// This is an optional import, meaning that the function may not even exist. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_id( symmetric_key: SymmetricKey, symmetric_key_id: WasiMutPtr(u8), symmetric_key_id_max_len: Size, result_0_ptr: WasiMutPtr(Size), result_1_ptr: WasiMutPtr(Version), ) callconv(.C) CryptoErrno; /// __(optional)__ /// Return a managed symmetric key from a key identifier. /// /// `kp_version` can be set to `version_latest` to retrieve the most recent version of a symmetric key. /// /// If no key matching the provided information is found, `not_found` is returned instead. /// /// This is an optional import, meaning that the function may not even exist. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_key_from_id( secrets_manager: SecretsManager, symmetric_key_id: WasiPtr(u8), symmetric_key_id_len: Size, symmetric_key_version: Version, result_ptr: WasiMutPtr(SymmetricKey), ) callconv(.C) CryptoErrno; /// Create a new state to aborb and produce data using symmetric operations. /// /// The state remains valid after every operation in order to support incremental updates. /// /// The function has two optional parameters: a key and an options set. /// /// It will fail with a `key_not_supported` error code if a key was provided but the chosen algorithm doesn't natively support keying. /// /// On the other hand, if a key is required, but was not provided, a `key_required` error will be thrown. /// /// Some algorithms may require additional parameters. They have to be supplied as an options set: /// /// ```rust /// let options_handle = ctx.options_open()?; /// ctx.options_set("context", b"My application")?; /// ctx.options_set_u64("fanout", 16)?; /// let state_handle = ctx.symmetric_state_open("BLAKE2b-512", None, Some(options_handle))?; /// ``` /// /// If some parameters are mandatory but were not set, the `parameters_missing` error code will be returned. /// /// A notable exception is the `nonce` parameter, that is common to most AEAD constructions. /// /// If a nonce is required but was not supplied: /// /// - If it is safe to do so, the host will automatically generate a nonce. This is true for nonces that are large enough to be randomly generated, or if the host is able to maintain a global counter. /// - If not, the function will fail and return the dedicated `nonce_required` error code. /// /// A nonce that was automatically generated can be retrieved after the function returns with `symmetric_state_get(state_handle, "nonce")`. /// /// **Sample usage patterns:** /// /// - **Hashing** /// /// ```rust /// let mut out = [0u8; 64]; /// let state_handle = ctx.symmetric_state_open("SHAKE-128", None, None)?; /// ctx.symmetric_state_absorb(state_handle, b"data")?; /// ctx.symmetric_state_absorb(state_handle, b"more_data")?; /// ctx.symmetric_state_squeeze(state_handle, &mut out)?; /// ``` /// /// - **MAC** /// /// ```rust /// let mut raw_tag = [0u8; 64]; /// let key_handle = ctx.symmetric_key_import("HMAC/SHA-512", b"key")?; /// let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"data")?; /// ctx.symmetric_state_absorb(state_handle, b"more_data")?; /// let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; /// ctx.symmetric_tag_pull(computed_tag_handle, &mut raw_tag)?; /// ``` /// /// Verification: /// /// ```rust /// let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"data")?; /// ctx.symmetric_state_absorb(state_handle, b"more_data")?; /// let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; /// ctx.symmetric_tag_verify(computed_tag_handle, expected_raw_tag)?; /// ``` /// /// - **Tuple hashing** /// /// ```rust /// let mut out = [0u8; 64]; /// let state_handle = ctx.symmetric_state_open("TupleHashXOF256", None, None)?; /// ctx.symmetric_state_absorb(state_handle, b"value 1")?; /// ctx.symmetric_state_absorb(state_handle, b"value 2")?; /// ctx.symmetric_state_absorb(state_handle, b"value 3")?; /// ctx.symmetric_state_squeeze(state_handle, &mut out)?; /// ``` /// Unlike MACs and regular hash functions, inputs are domain separated instead of being concatenated. /// /// - **Key derivation using extract-and-expand** /// /// Extract: /// /// ```rust /// let mut prk = vec![0u8; 64]; /// let key_handle = ctx.symmetric_key_import("HKDF-EXTRACT/SHA-512", b"key")?; /// let state_handle = ctx.symmetric_state_open("HKDF-EXTRACT/SHA-512", Some(key_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"salt")?; /// let prk_handle = ctx.symmetric_state_squeeze_key(state_handle, "HKDF-EXPAND/SHA-512")?; /// ``` /// /// Expand: /// /// ```rust /// let mut subkey = vec![0u8; 32]; /// let state_handle = ctx.symmetric_state_open("HKDF-EXPAND/SHA-512", Some(prk_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"info")?; /// ctx.symmetric_state_squeeze(state_handle, &mut subkey)?; /// ``` /// /// - **Key derivation using a XOF** /// /// ```rust /// let mut subkey1 = vec![0u8; 32]; /// let mut subkey2 = vec![0u8; 32]; /// let key_handle = ctx.symmetric_key_import("BLAKE3", b"key")?; /// let state_handle = ctx.symmetric_state_open("BLAKE3", Some(key_handle), None)?; /// ctx.symmetric_absorb(state_handle, b"context")?; /// ctx.squeeze(state_handle, &mut subkey1)?; /// ctx.squeeze(state_handle, &mut subkey2)?; /// ``` /// /// - **Password hashing** /// /// ```rust /// let mut memory = vec![0u8; 1_000_000_000]; /// let options_handle = ctx.symmetric_options_open()?; /// ctx.symmetric_options_set_guest_buffer(options_handle, "memory", &mut memory)?; /// ctx.symmetric_options_set_u64(options_handle, "opslimit", 5)?; /// ctx.symmetric_options_set_u64(options_handle, "parallelism", 8)?; /// /// let state_handle = ctx.symmetric_state_open("ARGON2-ID-13", None, Some(options))?; /// ctx.symmtric_state_absorb(state_handle, b"password")?; /// /// let pw_str_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; /// let mut pw_str = vec![0u8; ctx.symmetric_tag_len(pw_str_handle)?]; /// ctx.symmetric_tag_pull(pw_str_handle, &mut pw_str)?; /// ``` /// /// - **AEAD encryption with an explicit nonce** /// /// ```rust /// let key_handle = ctx.symmetric_key_generate("<KEY>", None)?; /// let message = b"test"; /// /// let options_handle = ctx.symmetric_options_open()?; /// ctx.symmetric_options_set(options_handle, "nonce", nonce)?; /// /// let state_handle = ctx.symmetric_state_open("AES-256-GCM", Some(key_handle), Some(options_handle))?; /// let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?]; /// ctx.symmetric_state_absorb(state_handle, "additional data")?; /// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?; /// ``` /// /// - **AEAD encryption with automatic nonce generation** /// /// ```rust /// let key_handle = ctx.symmetric_key_generate("<KEY>", None)?; /// let message = b"test"; /// let mut nonce = [0u8; 24]; /// /// let state_handle = ctx.symmetric_state_open("AES-256-GCM-SIV", Some(key_handle), None)?; /// /// let nonce_handle = ctx.symmetric_state_options_get(state_handle, "nonce")?; /// ctx.array_output_pull(nonce_handle, &mut nonce)?; /// /// let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?]; /// ctx.symmetric_state_absorb(state_handle, "additional data")?; /// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?; /// ``` /// /// - **Session authenticated modes** /// /// ```rust /// let mut out = [0u8; 16]; /// let mut out2 = [0u8; 16]; /// let mut ciphertext = [0u8; 20]; /// let key_handle = ctx.symmetric_key_generate("Xoodyak-128", None)?; /// let state_handle = ctx.symmetric_state_open("Xoodyak-128", Some(key_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"data")?; /// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, b"abcd")?; /// ctx.symmetric_state_absorb(state_handle, b"more data")?; /// ctx.symmetric_state_squeeze(state_handle, &mut out)?; /// ctx.symmetric_state_squeeze(state_handle, &mut out2)?; /// ctx.symmetric_state_ratchet(state_handle)?; /// ctx.symmetric_state_absorb(state_handle, b"more data")?; /// let next_key_handle = ctx.symmetric_state_squeeze_key(state_handle, "Xoodyak-128")?; /// // ... /// ``` pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_open( algorithm_ptr: WasiPtr(Char8), algorithm_len: usize, key: OptSymmetricKey, options: OptOptions, result_ptr: WasiMutPtr(SymmetricState), ) callconv(.C) CryptoErrno; /// Retrieve a parameter from the current state. /// /// In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated. /// /// The function may return `options_not_set` if an option was not set, which is different from an empty value. /// /// It may also return `unsupported_option` if the option doesn't exist for the chosen algorithm. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_options_get( handle: SymmetricState, name_ptr: WasiPtr(Char8), name_len: usize, value: WasiMutPtr(u8), value_max_len: Size, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Retrieve an integer parameter from the current state. /// /// In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated. /// /// The function may return `options_not_set` if an option was not set. /// /// It may also return `unsupported_option` if the option doesn't exist for the chosen algorithm. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_options_get_u64( handle: SymmetricState, name_ptr: WasiPtr(Char8), name_len: usize, result_ptr: WasiMutPtr(U64), ) callconv(.C) CryptoErrno; /// Destroy a symmetric state. /// /// Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_close( handle: SymmetricState, ) callconv(.C) CryptoErrno; /// Absorb data into the state. /// /// - **Hash functions:** adds data to be hashed. /// - **MAC functions:** adds data to be authenticated. /// - **Tuplehash-like constructions:** adds a new tuple to the state. /// - **Key derivation functions:** adds to the IKM or to the subkey information. /// - **AEAD constructions:** adds additional data to be authenticated. /// - **Stateful hash objects, permutation-based constructions:** absorbs. /// /// If the chosen algorithm doesn't accept input data, the `invalid_operation` error code is returned. /// /// If too much data has been fed for the algorithm, `overflow` may be thrown. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_absorb( handle: SymmetricState, data: WasiPtr(u8), data_len: Size, ) callconv(.C) CryptoErrno; /// Squeeze bytes from the state. /// /// - **Hash functions:** this tries to output an `out_len` bytes digest from the absorbed data. The hash function output will be truncated if necessary. If the requested size is too large, the `invalid_len` error code is returned. /// - **Key derivation functions:** : outputs an arbitrary-long derived key. /// - **RNGs, DRBGs, stream ciphers:**: outputs arbitrary-long data. /// - **Stateful hash objects, permutation-based constructions:** squeeze. /// /// Other kinds of algorithms may return `invalid_operation` instead. /// /// For password-stretching functions, the function may return `in_progress`. /// In that case, the guest should retry with the same parameters until the function completes. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_squeeze( handle: SymmetricState, out: WasiMutPtr(u8), out_len: Size, ) callconv(.C) CryptoErrno; /// Compute and return a tag for all the data injected into the state so far. /// /// - **MAC functions**: returns a tag authenticating the absorbed data. /// - **Tuplehash-like constructions:** returns a tag authenticating all the absorbed tuples. /// - **Password-hashing functions:** returns a standard string containing all the required parameters for password verification. /// /// Other kinds of algorithms may return `invalid_operation` instead. /// /// For password-stretching functions, the function may return `in_progress`. /// In that case, the guest should retry with the same parameters until the function completes. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_squeeze_tag( handle: SymmetricState, result_ptr: WasiMutPtr(SymmetricTag), ) callconv(.C) CryptoErrno; /// Use the current state to produce a key for a target algorithm. /// /// For extract-then-expand constructions, this returns the PRK. /// For session-base authentication encryption, this returns a key that can be used to resume a session without storing a nonce. /// /// `invalid_operation` is returned for algorithms not supporting this operation. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_squeeze_key( handle: SymmetricState, alg_str_ptr: WasiPtr(Char8), alg_str_len: usize, result_ptr: WasiMutPtr(SymmetricKey), ) callconv(.C) CryptoErrno; /// Return the maximum length of an authentication tag for the current algorithm. /// /// This allows guests to compute the size required to store a ciphertext along with its authentication tag. /// /// The returned length may include the encryption mode's padding requirements in addition to the actual tag. /// /// For an encryption operation, the size of the output buffer should be `input_len + symmetric_state_max_tag_len()`. /// /// For a decryption operation, the size of the buffer that will store the decrypted data must be `ciphertext_len - symmetric_state_max_tag_len()`. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_max_tag_len( handle: SymmetricState, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Encrypt data with an attached tag. /// /// - **Stream cipher:** adds the input to the stream cipher output. `out_len` and `data_len` can be equal, as no authentication tags will be added. /// - **AEAD:** encrypts `data` into `out`, including the authentication tag to the output. Additional data must have been previously absorbed using `symmetric_state_absorb()`. The `symmetric_state_max_tag_len()` function can be used to retrieve the overhead of adding the tag, as well as padding if necessary. /// - **SHOE, Xoodyak, Strobe:** encrypts data, squeezes a tag and appends it to the output. /// /// If `out` and `data` are the same address, encryption may happen in-place. /// /// The function returns the actual size of the ciphertext along with the tag. /// /// `invalid_operation` is returned for algorithms not supporting encryption. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_encrypt( handle: SymmetricState, out: WasiMutPtr(u8), out_len: Size, data: WasiPtr(u8), data_len: Size, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Encrypt data, with a detached tag. /// /// - **Stream cipher:** returns `invalid_operation` since stream ciphers do not include authentication tags. /// - **AEAD:** encrypts `data` into `out` and returns the tag separately. Additional data must have been previously absorbed using `symmetric_state_absorb()`. The output and input buffers must be of the same length. /// - **SHOE, Xoodyak, Strobe:** encrypts data and squeezes a tag. /// /// If `out` and `data` are the same address, encryption may happen in-place. /// /// The function returns the tag. /// /// `invalid_operation` is returned for algorithms not supporting encryption. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_encrypt_detached( handle: SymmetricState, out: WasiMutPtr(u8), out_len: Size, data: WasiPtr(u8), data_len: Size, result_ptr: WasiMutPtr(SymmetricTag), ) callconv(.C) CryptoErrno; /// - **Stream cipher:** adds the input to the stream cipher output. `out_len` and `data_len` can be equal, as no authentication tags will be added. /// - **AEAD:** decrypts `data` into `out`. Additional data must have been previously absorbed using `symmetric_state_absorb()`. /// - **SHOE, Xoodyak, Strobe:** decrypts data, squeezes a tag and verify that it matches the one that was appended to the ciphertext. /// /// If `out` and `data` are the same address, decryption may happen in-place. /// /// `out_len` must be exactly `data_len` + `max_tag_len` bytes. /// /// The function returns the actual size of the decrypted message, which can be smaller than `out_len` for modes that requires padding. /// /// `invalid_tag` is returned if the tag didn't verify. /// /// `invalid_operation` is returned for algorithms not supporting encryption. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_decrypt( handle: SymmetricState, out: WasiMutPtr(u8), out_len: Size, data: WasiPtr(u8), data_len: Size, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// - **Stream cipher:** returns `invalid_operation` since stream ciphers do not include authentication tags. /// - **AEAD:** decrypts `data` into `out`. Additional data must have been previously absorbed using `symmetric_state_absorb()`. /// - **SHOE, <NAME>:** decrypts data, squeezes a tag and verify that it matches the expected one. /// /// `raw_tag` is the expected tag, as raw bytes. /// /// `out` and `data` be must have the same length. /// If they also share the same address, decryption may happen in-place. /// /// The function returns the actual size of the decrypted message. /// /// `invalid_tag` is returned if the tag verification failed. /// /// `invalid_operation` is returned for algorithms not supporting encryption. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_decrypt_detached( handle: SymmetricState, out: WasiMutPtr(u8), out_len: Size, data: WasiPtr(u8), data_len: Size, raw_tag: WasiPtr(u8), raw_tag_len: Size, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Make it impossible to recover the previous state. /// /// This operation is supported by some systems keeping a rolling state over an entire session, for forward security. /// /// `invalid_operation` is returned for algorithms not supporting ratcheting. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_state_ratchet( handle: SymmetricState, ) callconv(.C) CryptoErrno; /// Return the length of an authentication tag. /// /// This function can be used by a guest to allocate the correct buffer size to copy a computed authentication tag. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_tag_len( symmetric_tag: SymmetricTag, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Copy an authentication tag into a guest-allocated buffer. /// /// The handle automatically becomes invalid after this operation. Manually closing it is not required. /// /// Example usage: /// /// ```rust /// let mut raw_tag = [0u8; 16]; /// ctx.symmetric_tag_pull(raw_tag_handle, &mut raw_tag)?; /// ``` /// /// The function returns `overflow` if the supplied buffer is too small to copy the tag. /// /// Otherwise, it returns the number of bytes that have been copied. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_tag_pull( symmetric_tag: SymmetricTag, buf: WasiMutPtr(u8), buf_len: Size, result_ptr: WasiMutPtr(Size), ) callconv(.C) CryptoErrno; /// Verify that a computed authentication tag matches the expected value, in constant-time. /// /// The expected tag must be provided as a raw byte string. /// /// The function returns `invalid_tag` if the tags don't match. /// /// Example usage: /// /// ```rust /// let key_handle = ctx.symmetric_key_import("HMAC/SHA-256", b"key")?; /// let state_handle = ctx.symmetric_state_open("HMAC/SHA-256", Some(key_handle), None)?; /// ctx.symmetric_state_absorb(state_handle, b"data")?; /// let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; /// ctx.symmetric_tag_verify(computed_tag_handle, expected_raw_tag)?; /// ``` pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_tag_verify( symmetric_tag: SymmetricTag, expected_raw_tag_ptr: WasiPtr(u8), expected_raw_tag_len: Size, ) callconv(.C) CryptoErrno; /// Explicitly destroy an unused authentication tag. /// /// This is usually not necessary, as `symmetric_tag_pull()` automatically closes a tag after it has been copied. /// /// Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. pub extern "wasi_ephemeral_crypto_symmetric" fn symmetric_tag_close( symmetric_tag: SymmetricTag, ) callconv(.C) CryptoErrno; };
example-output/zig.zig
const Object = @This(); const std = @import("std"); const assert = std.debug.assert; const elf = std.elf; const fs = std.fs; const log = std.log.scoped(.elf); const math = std.math; const mem = std.mem; const Allocator = mem.Allocator; const Atom = @import("Atom.zig"); const Elf = @import("../Elf.zig"); file: fs.File, name: []const u8, file_offset: ?u32 = null, header: ?elf.Elf64_Ehdr = null, shdrs: std.ArrayListUnmanaged(elf.Elf64_Shdr) = .{}, sections: std.ArrayListUnmanaged(u16) = .{}, relocs: std.AutoHashMapUnmanaged(u16, u16) = .{}, symtab: std.ArrayListUnmanaged(elf.Elf64_Sym) = .{}, strtab: std.ArrayListUnmanaged(u8) = .{}, symtab_index: ?u16 = null, pub fn deinit(self: *Object, allocator: *Allocator) void { self.shdrs.deinit(allocator); self.sections.deinit(allocator); self.relocs.deinit(allocator); self.symtab.deinit(allocator); self.strtab.deinit(allocator); allocator.free(self.name); } pub fn parse(self: *Object, allocator: *Allocator, target: std.Target) !void { const reader = self.file.reader(); if (self.file_offset) |offset| { try reader.context.seekTo(offset); } const header = try reader.readStruct(elf.Elf64_Ehdr); if (!mem.eql(u8, header.e_ident[0..4], "\x7fELF")) { log.debug("Invalid ELF magic {s}, expected \x7fELF", .{header.e_ident[0..4]}); return error.NotObject; } if (header.e_ident[elf.EI_VERSION] != 1) { log.debug("Unknown ELF version {d}, expected 1", .{header.e_ident[elf.EI_VERSION]}); return error.NotObject; } if (header.e_ident[elf.EI_DATA] != elf.ELFDATA2LSB) { log.err("TODO big endian support", .{}); return error.TODOBigEndianSupport; } if (header.e_ident[elf.EI_CLASS] != elf.ELFCLASS64) { log.err("TODO 32bit support", .{}); return error.TODOElf32bitSupport; } if (header.e_type != elf.ET.REL) { log.debug("Invalid file type {any}, expected ET.REL", .{header.e_type}); return error.NotObject; } if (header.e_machine != target.cpu.arch.toElfMachine()) { log.debug("Invalid architecture {any}, expected {any}", .{ header.e_machine, target.cpu.arch.toElfMachine(), }); return error.InvalidCpuArch; } if (header.e_version != 1) { log.debug("Invalid ELF version {d}, expected 1", .{header.e_version}); return error.NotObject; } assert(header.e_entry == 0); assert(header.e_phoff == 0); assert(header.e_phnum == 0); self.header = header; try self.parseShdrs(allocator, reader); try self.parseSymtab(allocator); } fn parseShdrs(self: *Object, allocator: *Allocator, reader: anytype) !void { const shnum = self.header.?.e_shnum; if (shnum == 0) return; const offset = self.file_offset orelse 0; try reader.context.seekTo(offset + self.header.?.e_shoff); try self.shdrs.ensureTotalCapacity(allocator, shnum); var i: u16 = 0; while (i < shnum) : (i += 1) { const shdr = try reader.readStruct(elf.Elf64_Shdr); self.shdrs.appendAssumeCapacity(shdr); switch (shdr.sh_type) { elf.SHT_SYMTAB => { self.symtab_index = i; }, elf.SHT_PROGBITS, elf.SHT_NOBITS => { try self.sections.append(allocator, i); }, elf.SHT_REL, elf.SHT_RELA => { try self.relocs.putNoClobber(allocator, @intCast(u16, shdr.sh_info), i); }, else => {}, } } // Parse shstrtab var buffer = try self.readShdrContents(allocator, self.header.?.e_shstrndx); defer allocator.free(buffer); try self.strtab.appendSlice(allocator, buffer); } fn parseSymtab(self: *Object, allocator: *Allocator) !void { if (self.symtab_index == null) return; const symtab_shdr = self.shdrs.items[self.symtab_index.?]; // We first read the contents of string table associated with this symbol table // noting the offset at which it is appended to the existing string table, which // we will then use to fixup st_name offset within each symbol. const strtab_offset = @intCast(u32, self.strtab.items.len); var str_buffer = try self.readShdrContents(allocator, @intCast(u16, symtab_shdr.sh_link)); defer allocator.free(str_buffer); try self.strtab.appendSlice(allocator, str_buffer); var sym_buffer = try self.readShdrContents(allocator, self.symtab_index.?); defer allocator.free(sym_buffer); const syms = @alignCast(@alignOf(elf.Elf64_Sym), mem.bytesAsSlice(elf.Elf64_Sym, sym_buffer)); try self.symtab.ensureTotalCapacity(allocator, syms.len); for (syms) |sym| { var out_sym = sym; if (sym.st_name > 0) { out_sym.st_name += strtab_offset; } else if (sym.st_info & 0xf == elf.STT_SECTION) { // If the symbol is pointing to a section header, copy the sh_name offset as the new // st_name offset. const shdr = self.shdrs.items[sym.st_shndx]; out_sym.st_name = shdr.sh_name; } self.symtab.appendAssumeCapacity(out_sym); } } fn sortBySeniority(aliases: []u32, object: *Object) void { const Context = struct { object: *Object, }; const SortFn = struct { fn lessThan(ctx: Context, lhs: u32, rhs: u32) bool { const lhs_sym = ctx.object.symtab.items[lhs]; const lhs_sym_bind = lhs_sym.st_info >> 4; const rhs_sym = ctx.object.symtab.items[rhs]; const rhs_sym_bind = rhs_sym.st_info >> 4; if (lhs_sym_bind == rhs_sym_bind) { return false; } if (lhs_sym_bind == elf.STB_GLOBAL) { return true; } else if (lhs_sym_bind == elf.STB_WEAK and rhs_sym_bind != elf.STB_GLOBAL) { return true; } return false; } }; std.sort.sort(u32, aliases, Context{ .object = object }, SortFn.lessThan); } pub fn parseIntoAtoms(self: *Object, allocator: *Allocator, object_id: u16, elf_file: *Elf) !void { log.debug("parsing '{s}' into atoms", .{self.name}); var symbols_by_shndx = std.AutoHashMap(u16, std.ArrayList(u32)).init(allocator); defer symbols_by_shndx.deinit(); for (self.sections.items) |ndx| { try symbols_by_shndx.putNoClobber(ndx, std.ArrayList(u32).init(allocator)); } for (self.symtab.items) |sym, sym_id| { if (sym.st_shndx == elf.SHN_UNDEF) continue; if (elf.SHN_LORESERVE <= sym.st_shndx and sym.st_shndx < elf.SHN_HIRESERVE) continue; const map = symbols_by_shndx.getPtr(sym.st_shndx) orelse continue; try map.append(@intCast(u32, sym_id)); } for (self.sections.items) |ndx| { const shdr = self.shdrs.items[ndx]; const shdr_name = self.getString(shdr.sh_name); log.debug(" parsing section '{s}'", .{shdr_name}); const syms = symbols_by_shndx.get(ndx).?; if (syms.items.len == 0) { if (shdr.sh_size != 0) { log.debug(" TODO handle non-empty sections with no symbols: {s}", .{shdr_name}); } continue; } const tshdr_ndx = (try elf_file.getMatchingSection(object_id, ndx)) orelse { log.debug("unhandled section", .{}); continue; }; const atom = try Atom.createEmpty(allocator); errdefer { atom.deinit(allocator); allocator.destroy(atom); } try elf_file.managed_atoms.append(allocator, atom); atom.file = object_id; atom.size = @intCast(u32, shdr.sh_size); atom.alignment = @intCast(u32, shdr.sh_addralign); for (syms.items) |sym_id| { const sym = self.symtab.items[sym_id]; if (sym.st_value > 0) { try atom.contained.append(allocator, .{ .local_sym_index = sym_id, .offset = sym.st_value, }); } else { try atom.aliases.append(allocator, sym_id); } } sortBySeniority(atom.aliases.items, self); atom.local_sym_index = atom.aliases.swapRemove(0); var code = if (shdr.sh_type == elf.SHT_NOBITS) blk: { var code = try allocator.alloc(u8, atom.size); mem.set(u8, code, 0); break :blk code; } else try self.readShdrContents(allocator, ndx); defer allocator.free(code); if (self.relocs.get(ndx)) |rel_ndx| { const rel_shdr = self.shdrs.items[rel_ndx]; var raw_relocs = try self.readShdrContents(allocator, rel_ndx); defer allocator.free(raw_relocs); const nrelocs = @divExact(rel_shdr.sh_size, rel_shdr.sh_entsize); try atom.relocs.ensureTotalCapacity(allocator, nrelocs); var count: usize = 0; while (count < nrelocs) : (count += 1) { const bytes = raw_relocs[count * rel_shdr.sh_entsize ..][0..rel_shdr.sh_entsize]; var rel = blk: { if (rel_shdr.sh_type == elf.SHT_REL) { const rel = @ptrCast(*const elf.Elf64_Rel, @alignCast(@alignOf(elf.Elf64_Rel), bytes)).*; // TODO parse addend from the placeholder // const addend = mem.readIntLittle(i32, code[rel.r_offset..][0..4]); // break :blk .{ // .r_offset = rel.r_offset, // .r_info = rel.r_info, // .r_addend = addend, // }; log.err("TODO need to parse addend embedded in the relocation placeholder for SHT_REL", .{}); log.err(" for relocation {}", .{rel}); return error.TODOParseAddendFromPlaceholder; } break :blk @ptrCast(*const elf.Elf64_Rela, @alignCast(@alignOf(elf.Elf64_Rela), bytes)).*; }; // While traversing relocations, synthesize any missing atom. // TODO synthesize PLT atoms, GOT atoms, etc. const tsym = self.symtab.items[rel.r_sym()]; const tsym_name = self.getString(tsym.st_name); switch (rel.r_type()) { elf.R_X86_64_REX_GOTPCRELX => blk: { // TODO optimize link-constant by rewriting opcodes. For example, // mov -> lea completely bypassing GOT. const global = elf_file.globals.get(tsym_name).?; const needs_got = inner: { const actual_tsym = if (global.file) |file| tsym: { const object = elf_file.objects.items[file]; log.debug("{s}", .{object.getString( object.symtab.items[global.sym_index].st_name, )}); break :tsym object.symtab.items[global.sym_index]; } else elf_file.locals.items[global.sym_index]; log.debug("{}", .{actual_tsym}); break :inner actual_tsym.st_info & 0xf == elf.STT_NOTYPE and actual_tsym.st_shndx == elf.SHN_UNDEF; }; log.debug("needs_got = {}", .{ needs_got, }); if (!needs_got) { log.debug("{x}", .{std.fmt.fmtSliceHexLower(code[rel.r_offset - 3 ..][0..3])}); // Link-time constant, try to optimize it away. if (code[rel.r_offset - 2] == 0x8b) { // MOVQ -> LEAQ code[rel.r_offset - 2] = 0x8d; const r_sym = rel.r_sym(); rel.r_info = (@intCast(u64, r_sym) << 32) | elf.R_X86_64_PC32; log.debug("R_X86_64_REX_GOTPCRELX -> R_X86_64_PC32: MOVQ -> LEAQ", .{}); log.debug("{x}", .{std.fmt.fmtSliceHexLower(code[rel.r_offset - 3 ..][0..3])}); break :blk; } if (code[rel.r_offset - 2] == 0x3b) inner: { const regs = code[rel.r_offset - 1]; log.debug("regs = 0x{x}, hmm = 0x{x}", .{ regs, @truncate(u3, regs) }); if (@truncate(u3, regs) != 0x5) break :inner; const reg = @intCast(u8, @truncate(u3, regs >> 3)); // CMP r64, r/m64 -> CMP r/m64, imm32 code[rel.r_offset - 2] = 0x81; code[rel.r_offset - 1] = 0xf8 | reg; const r_sym = rel.r_sym(); rel.r_info = (@intCast(u64, r_sym) << 32) | elf.R_X86_64_32; rel.r_addend = 0; log.debug("R_X86_64_REX_GOTPCRELX -> R_X86_64_32: CMP r64, r/m64 -> CMP r/m64, imm32", .{}); log.debug("{x}", .{std.fmt.fmtSliceHexLower(code[rel.r_offset - 3 ..][0..3])}); break :blk; } } if (elf_file.got_entries_map.contains(global)) break :blk; log.debug("R_X86_64_REX_GOTPCRELX: creating GOT atom: [() -> {s}]", .{ tsym_name, }); const got_atom = try elf_file.createGotAtom(global); try elf_file.got_entries_map.putNoClobber(allocator, global, got_atom); }, else => {}, } atom.relocs.appendAssumeCapacity(rel); } } try atom.code.appendSlice(allocator, code); // Update target section's metadata const tshdr = &elf_file.shdrs.items[tshdr_ndx]; tshdr.sh_addralign = math.max(tshdr.sh_addralign, atom.alignment); tshdr.sh_size = mem.alignForwardGeneric( u64, mem.alignForwardGeneric(u64, tshdr.sh_size, atom.alignment) + atom.size, tshdr.sh_addralign, ); if (elf_file.atoms.getPtr(tshdr_ndx)) |last| { last.*.next = atom; atom.prev = last.*; last.* = atom; } else { try elf_file.atoms.putNoClobber(allocator, tshdr_ndx, atom); } } } pub fn getString(self: Object, off: u32) []const u8 { assert(off < self.strtab.items.len); return mem.spanZ(@ptrCast([*:0]const u8, self.strtab.items.ptr + off)); } /// Caller owns the memory. fn readShdrContents(self: Object, allocator: *Allocator, shdr_index: u16) ![]u8 { const shdr = self.shdrs.items[shdr_index]; var buffer = try allocator.alloc(u8, shdr.sh_size); errdefer allocator.free(buffer); const offset = self.file_offset orelse 0; const amt = try self.file.preadAll(buffer, shdr.sh_offset + offset); if (amt != buffer.len) { return error.InputOutput; } return buffer; }
src/Elf/Object.zig
const std = @import( "std" ); usingnamespace @import( "../core/core.zig" ); usingnamespace @import( "../core/glz.zig" ); pub const VerticalCursor = struct { axis: *const Axis, cursor: f64, thickness_LPX: f64, rgba: [4]GLfloat, coords: [8]GLfloat, prog: VerticalCursorProgram, vbo: GLuint, vCount: GLsizei, vao: GLuint, painter: Painter, dragOffset: f64, dragger: Dragger = .{ .canHandlePressFn = canHandlePress, .handlePressFn = handlePress, .handleDragFn = handleDrag, .handleReleaseFn = handleRelease, }, pub fn init( name: []const u8, axis: *const Axis ) VerticalCursor { return VerticalCursor { .axis = axis, .cursor = 0.0, .thickness_LPX = 3.0, .rgba = [4]GLfloat { 0.3, 0.4, 1.0, 1.0 }, .coords = [8]GLfloat { -0.5,1.0, -0.5,-1.0, 0.5,1.0, 0.5,-1.0 }, .prog = undefined, .vbo = 0, .vCount = 4, .vao = 0, .dragOffset = undefined, .painter = Painter { .name = name, .glInitFn = glInit, .glPaintFn = glPaint, .glDeinitFn = glDeinit, }, }; } fn glInit( painter: *Painter, pc: *const PainterContext ) !void { const self = @fieldParentPtr( VerticalCursor, "painter", painter ); self.prog = try VerticalCursorProgram.glCreate( ); glGenBuffers( 1, &self.vbo ); glBindBuffer( GL_ARRAY_BUFFER, self.vbo ); glBufferData( GL_ARRAY_BUFFER, 2*self.vCount*@sizeOf( GLfloat ), @ptrCast( *const c_void, &self.coords ), GL_STATIC_DRAW ); glGenVertexArrays( 1, &self.vao ); glBindVertexArray( self.vao ); glEnableVertexAttribArray( self.prog.inCoords ); glVertexAttribPointer( self.prog.inCoords, 2, GL_FLOAT, GL_FALSE, 0, null ); } fn glPaint( painter: *Painter, pc: *const PainterContext ) !void { const self = @fieldParentPtr( VerticalCursor, "painter", painter ); const thickness_PX = @floatCast( GLfloat, self.thickness_LPX * pc.lpxToPx ); const bounds = self.axis.bounds( ); glzEnablePremultipliedAlphaBlending( ); glUseProgram( self.prog.program ); glzUniformInterval1( self.prog.VIEWPORT_PX, pc.viewport_PX[0] ); glzUniformInterval1( self.prog.BOUNDS, bounds ); glUniform1f( self.prog.CURSOR, @floatCast( GLfloat, self.cursor ) ); glUniform1f( self.prog.THICKNESS_PX, thickness_PX ); glUniform4fv( self.prog.RGBA, 1, &self.rgba ); glBindVertexArray( self.vao ); glDrawArrays( GL_TRIANGLE_STRIP, 0, self.vCount ); } fn glDeinit( painter: *Painter ) void { const self = @fieldParentPtr( VerticalCursor, "painter", painter ); glDeleteProgram( self.prog.program ); glDeleteVertexArrays( 1, &self.vao ); glDeleteBuffers( 1, &self.vbo ); } fn canHandlePress( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) bool { const self = @fieldParentPtr( VerticalCursor, "dragger", dragger ); if ( clickCount > 1 ) { return true; } else { const mouseFrac = self.axis.viewport_PX.valueToFrac( mouse_PX[0] ); const mouseCoord = self.axis.bounds( ).fracToValue( mouseFrac ); const offset = self.cursor - mouseCoord; return ( @fabs( offset * self.axis.scale ) <= self.thickness_LPX * context.lpxToPx ); } } fn handlePress( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) void { const self = @fieldParentPtr( VerticalCursor, "dragger", dragger ); const mouseFrac = self.axis.viewport_PX.valueToFrac( mouse_PX[0] ); const mouseCoord = self.axis.bounds( ).fracToValue( mouseFrac ); if ( clickCount == 1 ) { self.dragOffset = self.cursor - mouseCoord; } else if ( clickCount > 1 ) { self.cursor = mouseCoord; self.dragOffset = 0; } } fn handleDrag( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { const self = @fieldParentPtr( VerticalCursor, "dragger", dragger ); const mouseFrac = self.axis.viewport_PX.valueToFrac( mouse_PX[0] ); const mouseCoord = self.axis.bounds( ).fracToValue( mouseFrac ); self.cursor = mouseCoord - self.dragOffset; } fn handleRelease( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { const self = @fieldParentPtr( VerticalCursor, "dragger", dragger ); const mouseFrac = self.axis.viewport_PX.valueToFrac( mouse_PX[0] ); const mouseCoord = self.axis.bounds( ).fracToValue( mouseFrac ); self.cursor = mouseCoord - self.dragOffset; } }; const VerticalCursorProgram = struct { program: GLuint, VIEWPORT_PX: GLint, BOUNDS: GLint, CURSOR: GLint, THICKNESS_PX: GLint, RGBA: GLint, /// x_REL, y_NDC inCoords: GLuint, pub fn glCreate( ) !VerticalCursorProgram { const vertSource = \\#version 150 core \\ \\float start1( vec2 interval1 ) { \\ return interval1.x; \\} \\ \\float span1( vec2 interval1 ) { \\ return interval1.y; \\} \\ \\float coordsToNdc1( float coord, vec2 bounds ) { \\ float frac = ( coord - start1( bounds ) ) / span1( bounds ); \\ return ( -1.0 + 2.0*frac ); \\} \\ \\uniform vec2 VIEWPORT_PX; \\uniform vec2 BOUNDS; \\uniform float CURSOR; \\uniform float THICKNESS_PX; \\ \\// dxOffset, y_NDC \\in vec2 inCoords; \\ \\void main( void ) { \\ float xCenter_NDC = coordsToNdc1( CURSOR, BOUNDS ); \\ float dxOffset_NDC = ( 2.0 * inCoords.x * THICKNESS_PX ) / VIEWPORT_PX.y; \\ float x_NDC = xCenter_NDC + dxOffset_NDC; \\ float y_NDC = inCoords.y; \\ gl_Position = vec4( x_NDC, y_NDC, 0.0, 1.0 ); \\} ; const fragSource = \\#version 150 core \\precision lowp float; \\ \\uniform vec4 RGBA; \\ \\out vec4 outRgba; \\ \\void main( void ) { \\ float alpha = RGBA.a; \\ outRgba = vec4( alpha*RGBA.rgb, alpha ); \\} ; const program = try glzCreateProgram( vertSource, fragSource ); return VerticalCursorProgram { .program = program, .VIEWPORT_PX = glGetUniformLocation( program, "VIEWPORT_PX" ), .BOUNDS = glGetUniformLocation( program, "BOUNDS" ), .CURSOR = glGetUniformLocation( program, "CURSOR" ), .THICKNESS_PX = glGetUniformLocation( program, "THICKNESS_PX" ), .RGBA = glGetUniformLocation( program, "RGBA" ), .inCoords = @intCast( GLuint, glGetAttribLocation( program, "inCoords" ) ), }; } };
src/time/cursor.zig
const w4 = @import("../wasm4.zig"); const buttons = @import("button.zig"); const Situation = @import("../components/situation.zig").Situation; const std = @import("std"); const textWrap = @import("wrapping-text.zig").textWrap; const PROMPT_HEIGHT: u8 = 120; const SCREEN_SIZE: u8 = 160; const X_OFFSET: u8 = 2; pub const Prompt = struct { selection: u8 = 0, buttons: [3]buttons.Button = [_]buttons.Button{ buttons.Button{}, buttons.Button{}, buttons.Button{} }, order: [3]u8 = [_]u8{ 0, 1, 2 }, situation: *const Situation = undefined, disallow: u8 = 255, pub fn update(self: *@This()) void { // sanity if (self.selection == self.disallow) { self.selection += 1; } // draw colour for the outline of the prompt w4.DRAW_COLORS.* = 0x42; w4.rect(X_OFFSET, PROMPT_HEIGHT, SCREEN_SIZE - 2 * X_OFFSET, PROMPT_HEIGHT); textWrap(self.situation.prompt, X_OFFSET, PROMPT_HEIGHT - 5); var i: u8 = 0; for (self.order) |btn_index, index| { i = @intCast(u8, index); // set draw colour for the buttons if (i == self.disallow) { w4.DRAW_COLORS.* = 0x23; } else { w4.DRAW_COLORS.* = 0x24; } self.buttons[btn_index].draw( // button location fixed for now X_OFFSET * 4, PROMPT_HEIGHT + i * 10 + X_OFFSET * 4, i == self.selection); } } pub fn shuffleOrder(self: *@This(), rnd: *std.rand.Random) void { rnd.shuffle(u8, &self.order); } pub fn getSelection(self: *const @This()) u8 { return self.order[self.selection]; } pub fn setSituation(self: *@This(), situation: *const Situation) void { for (situation.options) |s, i| { self.buttons[i] = buttons.Button{ .text = s }; } self.situation = situation; } pub fn incSelection(self: *@This()) void { if (self.selection >= 2) { // maximum buttons magic // do nothing } else { if (self.selection + 1 == self.disallow) { if (self.selection + 2 < 3) { self.selection += 2; } // else do nothing } else { self.selection += 1; } } } pub fn decSelection(self: *@This()) void { if (self.selection <= 0) { // do nothing } else { if (self.selection - 1 == self.disallow) { if (self.selection - 2 >= 0 and self.selection - 2 != 255) { self.selection -= 2; } // else do nothing } else { self.selection -= 1; } } } }; pub fn buttonPrompt() Prompt { return Prompt{}; }
src/components/prompt.zig
const std = @import("std"); const task = @import("task.zig"); pub const Color = enum { Black, Blue, Green, Aqua, Red, Purple, Yellow, White, pub fn format( self: Color, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { if (fmt.len < 1) @compileError("invalid format specifier"); return switch (fmt[0]) { 'F', 'f' => switch (self) { .Black => std.fmt.format(context, FmtError, output, "\x1b[30m"), .Red => std.fmt.format(context, FmtError, output, "\x1b[31m"), .Green => std.fmt.format(context, FmtError, output, "\x1b[32m"), .Yellow => std.fmt.format(context, FmtError, output, "\x1b[33m"), .Blue => std.fmt.format(context, FmtError, output, "\x1b[34m"), .Purple => std.fmt.format(context, FmtError, output, "\x1b[35m"), .Aqua => std.fmt.format(context, FmtError, output, "\x1b[36m"), .White => std.fmt.format(context, FmtError, output, "\x1b[37m"), }, 'B', 'b' => switch (self) { .Black => std.fmt.format(context, FmtError, output, "\x1b[40m"), .Red => std.fmt.format(context, FmtError, output, "\x1b[41m"), .Green => std.fmt.format(context, FmtError, output, "\x1b[42m"), .Yellow => std.fmt.format(context, FmtError, output, "\x1b[43m"), .Blue => std.fmt.format(context, FmtError, output, "\x1b[44m"), .Purple => std.fmt.format(context, FmtError, output, "\x1b[45m"), .Aqua => std.fmt.format(context, FmtError, output, "\x1b[46m"), .White => std.fmt.format(context, FmtError, output, "\x1b[47m"), }, else => |s| @compileError("invalid format specifier: '" ++ fmt ++ "'"), }; } }; pub const ReturnCode = struct { ok: []const u8 = "", err: []const u8 = "[%?] ", }; pub const Command = union(enum) { Text: []const u8, ForeGround: Color, BackGround: Color, Bright, Underline, Italics, Reverse, Reset, ReturnCode: ReturnCode, HorizontalRule: u8, Tilde, AsyncTask, Task, pub fn format( self: Command, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { return switch (self) { .Text => |text| std.fmt.format(context, FmtError, output, "{}", text), .ForeGround => |color| std.fmt.format(context, FmtError, output, "%{{{f}%}}", color), .BackGround => |color| std.fmt.format(context, FmtError, output, "%{{{b}%}}", color), .Bright => std.fmt.format(context, FmtError, output, "%{{\x1b[1m%}}"), .Underline => std.fmt.format(context, FmtError, output, "%{{\x1b[4m%}}"), .Italics => std.fmt.format(context, FmtError, output, "%{{\x1b[3m%}}"), .Reverse => std.fmt.format(context, FmtError, output, "%{{\x1b[7m%}}"), .Reset => std.fmt.format(context, FmtError, output, "%{{\x1b[0m%}}"), .ReturnCode => |code| std.fmt.format(context, FmtError, output, "%(?.{}.{})", code.ok, code.err), else => { return std.fmt.format(context, FmtError, output, ""); }, }; } };
src/prompt.zig
const std = @import("std"); const fmt = std.fmt; const mem = std.mem; const Sha512 = std.crypto.hash.sha2.Sha512; /// Ed25519 (EdDSA) signatures. pub const Ed25519 = struct { /// The underlying elliptic curve. pub const Curve = @import("edwards25519.zig").Edwards25519; /// Length (in bytes) of a seed required to create a key pair. pub const seed_length = 32; /// Length (in bytes) of a compressed key pair. pub const keypair_length = 64; /// Length (in bytes) of a compressed public key. pub const public_length = 32; /// Length (in bytes) of a signature. pub const signature_length = 64; /// Length (in bytes) of optional random bytes, for non-deterministic signatures. pub const noise_length = 32; /// Derive a key pair from a secret seed. /// /// As in RFC 8032, an Ed25519 public key is generated by hashing /// the secret key using the SHA-512 function, and interpreting the /// bit-swapped, clamped lower-half of the output as the secret scalar. /// /// For this reason, an EdDSA secret key is commonly called a seed, /// from which the actual secret is derived. pub fn createKeyPair(seed: [seed_length]u8) ![keypair_length]u8 { var az: [Sha512.digest_length]u8 = undefined; var h = Sha512.init(.{}); h.update(&seed); h.final(&az); const p = try Curve.basePoint.clampedMul(az[0..32].*); var keypair: [keypair_length]u8 = undefined; mem.copy(u8, &keypair, &seed); mem.copy(u8, keypair[seed_length..], &p.toBytes()); return keypair; } /// Return the public key for a given key pair. pub fn publicKey(key_pair: [keypair_length]u8) [public_length]u8 { var public_key: [public_length]u8 = undefined; mem.copy(u8, public_key[0..], key_pair[seed_length..]); return public_key; } /// Sign a message using a key pair, and optional random noise. /// Having noise creates non-standard, non-deterministic signatures, /// but has been proven to increase resilience against fault attacks. pub fn sign(msg: []const u8, key_pair: [keypair_length]u8, noise: ?[noise_length]u8) ![signature_length]u8 { const public_key = key_pair[32..]; var az: [Sha512.digest_length]u8 = undefined; var h = Sha512.init(.{}); h.update(key_pair[0..seed_length]); h.final(&az); h = Sha512.init(.{}); if (noise) |*z| { h.update(z); } h.update(az[32..]); h.update(msg); var nonce64: [64]u8 = undefined; h.final(&nonce64); const nonce = Curve.scalar.reduce64(nonce64); const r = try Curve.basePoint.mul(nonce); var sig: [signature_length]u8 = undefined; mem.copy(u8, sig[0..32], &r.toBytes()); mem.copy(u8, sig[32..], public_key); h = Sha512.init(.{}); h.update(&sig); h.update(msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); var x = az[0..32]; Curve.scalar.clamp(x); const s = Curve.scalar.mulAdd(hram, x.*, nonce); mem.copy(u8, sig[32..], s[0..]); return sig; } /// Verify an Ed25519 signature given a message and a public key. /// Returns error.InvalidSignature is the signature verification failed. pub fn verify(sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8) !void { const r = sig[0..32]; const s = sig[32..64]; try Curve.scalar.rejectNonCanonical(s.*); try Curve.rejectNonCanonical(public_key); const a = try Curve.fromBytes(public_key); try a.rejectIdentity(); var h = Sha512.init(.{}); h.update(r); h.update(&public_key); h.update(msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); const p = try a.neg().mul(hram); const check = (try Curve.basePoint.mul(s.*)).add(p).toBytes(); if (mem.eql(u8, &check, r) == false) { return error.InvalidSignature; } } }; test "ed25519 key pair creation" { var seed: [32]u8 = undefined; try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519.createKeyPair(seed); var buf: [256]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{key_pair}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); const public_key = Ed25519.publicKey(key_pair); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{public_key}), "<KEY>"); } test "ed25519 signature" { var seed: [32]u8 = undefined; try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519.createKeyPair(seed); const sig = try Ed25519.sign("test", key_pair, null); var buf: [128]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{sig}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); const public_key = Ed25519.publicKey(key_pair); try Ed25519.verify(sig, "test", public_key); std.testing.expectError(error.InvalidSignature, Ed25519.verify(sig, "TEST", public_key)); }
lib/std/crypto/25519/ed25519.zig
const std = @import("std"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const global_allocator = &gpa.allocator; pub fn main() anyerror!void { var exa = EXA{ .memory = std.heap.ArenaAllocator.init(global_allocator), .code = undefined, }; } pub const EXA = struct { const Self = @This(); const Error = error{ DivideByZero, MathWithKeyword, InvalidFRegisterAccess, InvalidHardwareRegisterAccess, InvalidFileAccess, InvalidLinkTraversal, // Non-fatal error that will just let the RegisterAccessBlocking, }; memory: std.heap.ArenaAllocator, mode: CommunicationMode = .global, x: Value = 0, t: Value = 0, code: []Instruction, ip: usize = 0, pub fn step(self: *Self) Error!void { self.stepInteral() catch |err| switch (err) { error.RegisterAccessBlocking => {}, else => |e| return e, }; } fn stepInteral(self: *Self) !void { switch (self.code[self.ip]) { .COPY => |instr| { try self.writeRegister(instr[0], try instr[1].get(self)); }, else => @panic("TODO: Instruction not implemented yet!"), } } fn readRegister(self: *Self, reg: Register) !Value { return switch (reg) { .X => self.x, .T => self.t, .F => { @panic("TODO: Implement F reading!"); }, .M => { @panic("TODO: Implement M reading!"); }, }; } fn writeRegister(self: *Self, reg: Register, value: Value) !void { switch (reg) { .X => self.x = value, .T => self.t = value, .F => { @panic("TODO: Implement F writing!"); }, .F => { @panic("TODO: Implement M writing!"); }, } } }; pub const CommunicationMode = enum { local, global }; pub const Number = i32; pub const Keyword = *[]const u8; pub const Value = union(enum) { const Self = @This(); keyword: Keyword, number: Number, fn eql(lhs: Self, rhs: Self) bool { const Tag = @TagType(Self); if (@as(Tag, lhs) != @as(Tag, rhs)) return false; return switch (lhs) { .number => |n| rhs.number == n, .keyword => |k| rhs.keyword == k, }; } fn toNumber(self: Self) !Number { switch (self) { .number => |n| return n, else => return error.MathWithKeyword, } } }; pub const Register = enum { X, T, F, M, }; pub const Comparison = enum { @"=", @"<", @">", }; pub const Label = struct { name: []const u8, }; pub const RegisterOrNumber = union(enum) { register: Register, number: Number, fn get(self: @This(), exa: *EXA) !Number { return switch (self) { .number => |n| n, .register => |reg| blk: { const value = try exa.readRegister(reg); return try value.toNumber(); }, }; } }; pub const Instruction = union(enum) { // Manipulating Values COPY: Operands("R/N R"), ADDI: Operands("R/N R/N R"), SWIZ: Operands("R/N R/N R"), // Branching MARK: Operands("L"), JUMP: Operands("L"), TJMP: Operands("L"), FJMP: Operands("L"), // Testing values TEST: Operands("R/N EQ R/N"), // Lifecycle REPL: Operands("L"), HALT: Operands(""), KILL: Operands(""), // Movement LINK: Operands("R/N"), HOST: Operands("R"), // Communication MODE: Operands(""), @"VOID M": Operands(""), @"TEST MRD": Operands(""), // File Manipulation MAKE: Operands(""), GRAB: Operands("R/N"), FILE: Operands("R"), SEEK: Operands("R/N"), @"VOID F": Operands(""), DROP: Operands(""), WIPE: Operands(""), @"TEST EOF": Operands(""), // Miscellaneous NOTE: Operands("*"), NOOP: Operands(""), RAND: Operands("R/N R/N R"), fn Operands(comptime spec: []const u8) type { if (std.mem.eql(u8, spec, "")) return std.meta.Tuple(&[_]type{}); const length = blk: { var iter = std.mem.split(spec, " "); var i = 0; while (iter.next()) |_| { i += 1; } break :blk i; }; var types: [length]type = undefined; { var iter = std.mem.split(spec, " "); var i = 0; while (iter.next()) |item| : (i += 1) { types[i] = if (std.mem.eql(u8, item, "R/N")) RegisterOrNumber else if (std.mem.eql(u8, item, "R")) Register else if (std.mem.eql(u8, item, "L")) Label else if (std.mem.eql(u8, item, "EQ")) Comparison else if (std.mem.eql(u8, item, "*")) []const u8 else @compileError("Invalid operand specification: " ++ item); } } return std.meta.Tuple(&types); } }; pub const InstructionName = @TagType(Instruction);
src/main.zig
const std = @import("std"); const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; pub const PathComponent = struct { name: []const u8, path: []const u8, }; pub const PathComponentIterator = struct { path: []const u8, i: usize, const Self = @This(); /// Initialize a path component iterator pub fn init(path: []const u8) Self { return Self{ .path = path, .i = 0, }; } /// Returns the next path component pub fn next(self: *Self) ?PathComponent { if (self.i < self.path.len) { const old_i = self.i; while (self.i < self.path.len) : (self.i += 1) { if (std.fs.path.isSep(self.path[self.i])) { break; } } // Add trailing path separator if (self.i < self.path.len) { self.i += 1; } return PathComponent{ .name = self.path[old_i..self.i], .path = self.path[0..self.i], }; } else { return null; } } }; test "path components in absolute path" { var path = "/usr/local/bin/zig"; var iter = PathComponentIterator.init(path[0..]); var result: PathComponent = undefined; result = iter.next().?; try expectEqualSlices(u8, "/", result.path); try expectEqualSlices(u8, "/", result.name); result = iter.next().?; try expectEqualSlices(u8, "/usr/", result.path); try expectEqualSlices(u8, "usr/", result.name); result = iter.next().?; try expectEqualSlices(u8, "/usr/local/", result.path); try expectEqualSlices(u8, "local/", result.name); result = iter.next().?; try expectEqualSlices(u8, "/usr/local/bin/", result.path); try expectEqualSlices(u8, "bin/", result.name); result = iter.next().?; try expectEqualSlices(u8, "/usr/local/bin/zig", result.path); try expectEqualSlices(u8, "zig", result.name); try expectEqual(@as(?PathComponent, null), iter.next()); }
src/path_components.zig
const builtin = @import("builtin"); const std = @import("std"); const testing = std.testing; const FREE_SLOT = 0; // Use the provided function to re-seed the default PRNG implementation. var xoro = std.rand.Xoroshiro128.init(42); pub fn seed_default_prng(seed: u64) void { xoro.seed(seed); } // If you want to read the state of the default PRNG impl: pub fn get_default_prng_state() [2]u64 { return xoro.s; } // If you want to set the state of the default PRNG impl: pub fn set_default_prng_state(s: [2]u64) void { xoro.s = s; } // Default PRNG implementation. // By overriding .rand_fn you can provide your own custom PRNG implementation. // Useful in adversarial situations (CSPRNG) or when you need deterministic behavior // from the filter, as it requires to be able to save and restore the PRNG's state. // You can use Filter<X>.RandomFn to see the function type you need to fulfill. fn XoroRandFnImpl (comptime T: type) type { return struct { fn random () T { return xoro.random.int(T); } }; } // Supported CuckooFilter implementations. // Bucket size is chosen mainly to keep the bucket 64bit word-sized, or under. // This way reading a bucket requires a single memory fetch. // Filter8 does not have 8-fp wide buckets to keep the error rate under 3%, // as this is the cutoff point where Cuckoo Filters become more space-efficient // than Bloom. We also enforce memory alignment. pub const Filter8 = CuckooFilter(u8, 4); pub const Filter16 = CuckooFilter(u16, 4); pub const Filter32 = CuckooFilter(u32, 2); fn CuckooFilter(comptime Tfp: type, comptime buckSize: usize) type { return struct { homeless_fp: Tfp, homeless_bucket_idx: usize, buckets: [] align(Align) Bucket, fpcount: usize, broken: bool, rand_fn: ?RandomFn, pub const FPType = Tfp; pub const Align = std.math.min(@alignOf(usize), @alignOf(@IntType(false, buckSize * @typeInfo(Tfp).Int.bits))); pub const MaxError = 2.0 * @intToFloat(f32, buckSize) / @intToFloat(f32, 1 << @typeInfo(Tfp).Int.bits); pub const RandomFn = fn () BucketSizeType; const BucketSizeType = @IntType(false, comptime std.math.log2(buckSize)); const Bucket = [buckSize]Tfp; const MinSize = @sizeOf(Tfp) * buckSize * 2; const Self = @This(); const ScanMode = enum { Set, Force, Delete, Search, }; pub fn size_for(min_capacity: usize) usize { return size_for_exactly(min_capacity + @divTrunc(min_capacity, 5)); } pub fn size_for_exactly(min_capacity: usize) usize { var res = std.math.pow(usize, 2, std.math.log2(min_capacity)); if (res != min_capacity) res <<= 1; const requested_size = res * @sizeOf(Tfp); return if (MinSize > requested_size) MinSize else requested_size; } pub fn capacity(size: usize) usize { return size / @sizeOf(Tfp); } // Use bytesToBuckets when you have persisted the filter and need to restore it. // This will allow to cast back your bytes slice in the correct type for the .buckets // property. Make sure you still have the right alignment when loading the data back! pub fn bytesToBuckets(memory: [] align(Align) u8) ![] align(Align) Bucket { const not_pow2 = memory.len != std.math.pow(usize, 2, std.math.log2(memory.len)); if (not_pow2 or memory.len < MinSize) return error.BadLength; return @bytesToSlice(Bucket, memory); } pub fn init(memory: [] align(Align) u8) !Self { for (memory) |*x| x.* = 0; return Self { .homeless_fp = FREE_SLOT, .homeless_bucket_idx = undefined, .buckets = try bytesToBuckets(memory), .fpcount = 0, .broken = false, .rand_fn = null, }; } pub fn count(self: *Self) !usize { return if (self.broken) error.Broken else self.fpcount; } pub fn maybe_contains(self: *Self, hash: u64, fingerprint: Tfp) !bool { const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (fp == self.scan(bucket_idx, fp, .Search, FREE_SLOT)) return true; // Try alt bucket const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (fp == self.scan(alt_bucket_idx, fp, .Search, FREE_SLOT)) return true; // Try homeless slot if (self.is_homeless_fp(bucket_idx, alt_bucket_idx, fp)) return true else return if (self.broken) error.Broken else false; } pub fn remove(self: *Self, hash: u64, fingerprint: Tfp) !void { if (self.broken) return error.Broken; const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (fp == self.scan(bucket_idx, fp, .Delete, FREE_SLOT)) { self.fpcount -= 1; return; } // Try alt bucket const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (fp == self.scan(alt_bucket_idx, fp, .Delete, FREE_SLOT)) { self.fpcount -= 1; return; } // Try homeless slot if (self.is_homeless_fp(bucket_idx, alt_bucket_idx, fp)){ self.homeless_fp = FREE_SLOT; self.fpcount -= 1; return; } // Oh no... self.broken = true; return error.Broken; } pub fn add(self: *Self, hash: u64, fingerprint: Tfp) !void { if (self.broken) return error.Broken; const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (FREE_SLOT == self.scan(bucket_idx, FREE_SLOT, .Set, fp)) { self.fpcount += 1; return; } // If too tull already, try to add the fp to the secondary slot without forcing const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (FREE_SLOT != self.homeless_fp) { if (FREE_SLOT == self.scan(alt_bucket_idx, FREE_SLOT, .Set, fp)) { self.fpcount += 1; return; } else return error.TooFull; } // We are now willing to force the insertion self.homeless_bucket_idx = alt_bucket_idx; self.homeless_fp = fp; self.fpcount += 1; var i : usize = 0; while (i < 500) : (i += 1) { self.homeless_bucket_idx = self.compute_alt_bucket_idx(self.homeless_bucket_idx, self.homeless_fp); self.homeless_fp = self.scan(self.homeless_bucket_idx, FREE_SLOT, .Force, self.homeless_fp); if (FREE_SLOT == self.homeless_fp) return; } // If we went over the while loop, now the homeless slot is occupied. } pub fn is_broken(self: *Self) bool { return self.broken; } pub fn is_toofull(self: *Self) bool { return FREE_SLOT != self.homeless_fp; } pub fn fix_toofull(self: *Self) !void { if (FREE_SLOT == self.homeless_fp) return else { const homeless_fp = self.homeless_fp; self.homeless_fp = FREE_SLOT; try self.add(self.homeless_bucket_idx, homeless_fp); if (FREE_SLOT != self.homeless_fp) return error.TooFull; } } inline fn is_homeless_fp(self: *Self, bucket_idx: usize, alt_bucket_idx: usize, fp: Tfp) bool { const same_main = (self.homeless_bucket_idx == bucket_idx); const same_alt = (self.homeless_bucket_idx == alt_bucket_idx); const same_fp = (self.homeless_fp == fp); return (same_fp and (same_main or same_alt)); } inline fn compute_alt_bucket_idx(self: *Self, bucket_idx: usize, fp: Tfp) usize { const fpSize = @sizeOf(Tfp); const FNV_OFFSET = 14695981039346656037; const FNV_PRIME = 1099511628211; // Note: endianess const bytes = @ptrCast(*const [fpSize] u8, &fp).*; var res: usize = FNV_OFFSET; comptime var i = 0; inline while (i < fpSize) : (i += 1) { res ^= bytes[i]; res *%= FNV_PRIME; } return (bucket_idx ^ res) & (self.buckets.len - 1); } inline fn scan(self: *Self, bucket_idx: u64, fp: Tfp, comptime mode: ScanMode, val: Tfp) Tfp { comptime var i = 0; // Search the bucket var bucket = &self.buckets[bucket_idx]; inline while (i < buckSize) : (i += 1) { if (bucket[i] == fp) { switch (mode) { .Search => {}, .Delete => bucket[i] = FREE_SLOT, .Set => bucket[i] = val, .Force => bucket[i] = val, } return fp; } } switch (mode) { .Search => return FREE_SLOT, .Delete => return FREE_SLOT, .Set => return 1, .Force => { // We did not find any free slot, so we must now evict. const slot = if (self.rand_fn) |rfn| rfn() else XoroRandFnImpl(BucketSizeType).random(); const evicted = bucket[slot]; bucket[slot] = val; return evicted; }, } } }; } test "Hx == (Hy XOR hash(fp))" { var memory: [1<<20]u8 align(Filter8.Align) = undefined; var cf = Filter8.init(memory[0..]) catch unreachable; testing.expect(0 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(0, 'x'), 'x')); testing.expect(1 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(1, 'x'), 'x')); testing.expect(42 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(42, 'x'), 'x')); testing.expect(500 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(500, 'x'), 'x')); testing.expect(5000 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(5000, 'x'), 'x')); testing.expect(10585 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(10585, 'x'), 'x')); testing.expect(10586 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(10586, 'x'), 'x')); testing.expect(18028 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(18028, 'x'), 'x')); testing.expect((1<<15) - 1 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx((1<<15) - 1, 'x'), 'x')); } fn test_not_broken(cf: var) void { testing.expect(false == cf.maybe_contains(2, 'a') catch unreachable); testing.expect(0 == cf.count() catch unreachable); cf.add(2, 'a') catch unreachable; testing.expect(cf.maybe_contains(2, 'a') catch unreachable); testing.expect(false == cf.maybe_contains(0, 'a') catch unreachable); testing.expect(false == cf.maybe_contains(1, 'a') catch unreachable); testing.expect(1 == cf.count() catch unreachable); cf.remove(2, 'a') catch unreachable; testing.expect(false == cf.maybe_contains(2, 'a') catch unreachable); testing.expect(0 == cf.count() catch unreachable); } test "is not completely broken" { var memory: [16]u8 align(Filter8.Align) = undefined; var cf = Filter8.init(memory[0..]) catch unreachable; test_not_broken(&cf); } const Version = struct { Tfp: type, buckLen: usize, cftype: type, }; const SupportedVersions = []Version { Version { .Tfp = u8, .buckLen = 4, .cftype = Filter8}, Version { .Tfp = u16, .buckLen = 4, .cftype = Filter16}, Version { .Tfp = u32, .buckLen = 2, .cftype = Filter32}, }; test "generics are not completely broken" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; test_not_broken(&cf); } } test "too full when adding too many copies" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; var i: usize = 0; while (i < v.buckLen * 2) : (i += 1) { cf.add(0, 1) catch unreachable; } testing.expect(!cf.is_toofull()); // The first time we go over-board we can still occupy // the homeless slot, so this won't fail: cf.add(0, 1) catch unreachable; testing.expect(cf.is_toofull()); // We now are really full. testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); i = 0; while (i < v.buckLen * 2) : (i += 1) { cf.add(2, 1) catch unreachable; } // Homeless slot is already occupied. testing.expectError(error.TooFull, cf.add(2, 1)); testing.expectError(error.TooFull, cf.add(2, 1)); testing.expectError(error.TooFull, cf.add(2, 1)); // Try to fix the situation testing.expect(cf.is_toofull()); // This should fail testing.expectError(error.TooFull, cf.fix_toofull()); // Make it fixable cf.remove(0, 1) catch unreachable; cf.fix_toofull() catch unreachable; testing.expect(!cf.is_toofull()); cf.add(2, 1) catch unreachable; testing.expect(cf.is_toofull()); // Delete now all instances except the homeless one i = 0; while (i < v.buckLen * 2) : (i += 1) { cf.remove(2, 1) catch unreachable; } // Should be able to find the homeless fp testing.expect(cf.maybe_contains(2, 1) catch unreachable); // Delete it and try to find it cf.remove(2, 1) catch unreachable; testing.expect(false == cf.maybe_contains(2, 1) catch unreachable); } } test "properly breaks when misused" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; var fp = @intCast(v.Tfp, 1); testing.expectError(error.Broken, cf.remove(2, 1)); testing.expectError(error.Broken, cf.add(2, 1)); testing.expectError(error.Broken, cf.count()); testing.expectError(error.Broken, cf.maybe_contains(2, 1)); } } fn TestSet(comptime Tfp: type) type { const ItemSet = std.hash_map.AutoHashMap(u64, Tfp); return struct { items: ItemSet, false_positives: ItemSet, const Self = @This(); fn init(iterations: usize, false_positives: usize, allocator: *std.mem.Allocator) Self { var item_set = ItemSet.init(allocator); var false_set = ItemSet.init(allocator); return Self { .items = blk: { var i : usize = 0; while (i < iterations) : (i += 1) { var hash = xoro.random.int(u64); while (item_set.contains(hash)) { hash = xoro.random.int(u64); } _ = item_set.put(hash, xoro.random.int(Tfp)) catch unreachable; } break :blk item_set; }, .false_positives = blk: { var i : usize = 0; while (i < false_positives) : (i += 1) { var hash = xoro.random.int(u64); while (item_set.contains(hash) or false_set.contains(hash)) { hash = xoro.random.int(u64); } _ = false_set.put(hash, xoro.random.int(Tfp)) catch unreachable; } break :blk false_set; }, }; } }; } test "small stress test" { const iterations = 60000; const false_positives = 10000; var direct_allocator = std.heap.DirectAllocator.init(); //defer direct_allocator.deinit(); inline for (SupportedVersions) |v| { var test_cases = TestSet(v.Tfp).init(iterations, false_positives, &direct_allocator.allocator); var iit = test_cases.items.iterator(); var fit = test_cases.false_positives.iterator(); //defer test_cases.items.deinit(); //defer test_cases.false_positives.deinit(); // Build an appropriately-sized filter var memory: [v.cftype.size_for(iterations)]u8 align(v.cftype.Align)= undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; // Test all items for presence (should all be false) { iit.reset(); while (iit.next()) |item| { testing.expect(!(cf.maybe_contains(item.key, item.value) catch unreachable)); } } // Add all items (should not fail) { iit.reset(); var iters: usize = 0; while (iit.next()) |item| { testing.expect(iters == cf.count() catch unreachable); cf.add(item.key, item.value) catch unreachable; iters += 1; } testing.expect(iters == cf.count() catch unreachable); } // Test that memory contains the right number of elements { var count: usize = 0; for (@bytesToSlice(v.Tfp, memory)) |byte| { if (byte != 0) { count += 1; } } testing.expect(iterations == count); testing.expect(iterations == cf.count() catch unreachable); } // Test all items for presence (should all be true) { iit.reset(); while (iit.next()) |item| { testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); } } // Delete half the elements and ensure they are not found // (there could be false positives depending on fill lvl) { iit.reset(); const max = @divTrunc(iterations, 2); var count: usize = 0; var false_count: usize = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); cf.remove(item.key, item.value) catch unreachable; testing.expect(iterations - count == cf.count() catch unreachable); if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% iit.reset(); count = 0; false_count = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Test false positive elements { fit.reset(); var false_count: usize = 0; while (fit.next()) |item| { if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Add deleted elements back in and test that all are present { iit.reset(); const max = @divTrunc(iterations, 2); var count: usize = 0; var false_count: usize = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; cf.add(item.key, item.value) catch unreachable; testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); } } // Test false positive elements (again) { fit.reset(); var false_count: usize = 0; while (fit.next()) |item| { if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Delete all items { iit.reset(); var iters: usize = 0; while (iit.next()) |item| { cf.remove(item.key, item.value) catch unreachable; iters += 1; } } // Test that memory contains 0 elements { var count: usize = 0; for (@bytesToSlice(v.Tfp, memory)) |fprint| { if (fprint != 0) { count += 1; } } testing.expect(0 == count); testing.expect(0 == cf.count() catch unreachable); } // Test all items for presence (should all be false) { iit.reset(); while (iit.next()) |item| { testing.expect(!(cf.maybe_contains(item.key, item.value) catch unreachable)); } } } }
src/cuckoofilter.zig
const std = @import("std"); const pc_keyboard = @import("../../pc_keyboard.zig"); pub const EXTENDED_KEY_CODE: u8 = 0xE0; pub const KEY_RELEASE_CODE: u8 = 0xF0; /// Implements state logic for scancode set 2 /// /// Start: /// F0 => Release /// E0 => Extended /// xx => Key Down /// /// Release: /// xxx => Key Up /// /// Extended: /// F0 => Release Extended /// xx => Extended Key Down /// /// Release Extended: /// xxx => Extended Key Up pub fn advanceState(state: *pc_keyboard.DecodeState, code: u8) pc_keyboard.KeyboardError!?pc_keyboard.KeyEvent { switch (state.*) { .Start => switch (code) { EXTENDED_KEY_CODE => state.* = .Extended, KEY_RELEASE_CODE => state.* = .Release, else => return pc_keyboard.KeyEvent{ .code = try mapScancode(code), .state = .Down }, }, .Extended => switch (code) { KEY_RELEASE_CODE => state.* = .ExtendedRelease, else => { state.* = .Start; return pc_keyboard.KeyEvent{ .code = try mapExtendedScancode(code), .state = .Down }; }, }, .Release => { state.* = .Start; return pc_keyboard.KeyEvent{ .code = try mapScancode(code), .state = .Up }; }, .ExtendedRelease => { state.* = .Start; return pc_keyboard.KeyEvent{ .code = try mapExtendedScancode(code), .state = .Up }; }, } return null; } /// Implements the single byte codes for Set 2. fn mapScancode(code: u8) pc_keyboard.KeyboardError!pc_keyboard.KeyCode { return switch (code) { 0x01 => .F9, 0x03 => .F5, 0x04 => .F3, 0x05 => .F1, 0x06 => .F2, 0x07 => .F12, 0x09 => .F10, 0x0A => .F8, 0x0B => .F6, 0x0C => .F4, 0x0D => .Tab, 0x0E => .BackTick, 0x11 => .AltLeft, 0x12 => .ShiftLeft, 0x14 => .ControlLeft, 0x15 => .Q, 0x16 => .Key1, 0x1A => .Z, 0x1B => .S, 0x1C => .A, 0x1D => .W, 0x1e => .Key2, 0x21 => .C, 0x22 => .X, 0x23 => .D, 0x24 => .E, 0x25 => .Key4, 0x26 => .Key3, 0x29 => .Spacebar, 0x2A => .V, 0x2B => .F, 0x2C => .T, 0x2D => .R, 0x2E => .Key5, 0x31 => .N, 0x32 => .B, 0x33 => .H, 0x34 => .G, 0x35 => .Y, 0x36 => .Key6, 0x3A => .M, 0x3B => .J, 0x3C => .U, 0x3D => .Key7, 0x3E => .Key8, 0x41 => .Comma, 0x42 => .K, 0x43 => .I, 0x44 => .O, 0x45 => .Key0, 0x46 => .Key9, 0x49 => .Fullstop, 0x4A => .Slash, 0x4B => .L, 0x4C => .SemiColon, 0x4D => .P, 0x4E => .Minus, 0x52 => .Quote, 0x54 => .BracketSquareLeft, 0x55 => .Equals, 0x58 => .CapsLock, 0x59 => .ShiftRight, 0x5A => .Enter, 0x5B => .BracketSquareRight, 0x5D => .HashTilde, 0x61 => .BackSlash, 0x66 => .Backspace, 0x69 => .Numpad1, 0x6B => .Numpad4, 0x6C => .Numpad7, 0x70 => .Numpad0, 0x71 => .NumpadPeriod, 0x72 => .Numpad2, 0x73 => .Numpad5, 0x74 => .Numpad6, 0x75 => .Numpad8, 0x76 => .Escape, 0x77 => .NumpadLock, 0x78 => .F11, 0x79 => .NumpadPlus, 0x7A => .Numpad3, 0x7B => .NumpadMinus, 0x7C => .NumpadStar, 0x7D => .Numpad9, 0x7E => .ScrollLock, 0x83 => .F7, 0xAA => .PowerOnTestOk, else => pc_keyboard.KeyboardError.UnknownKeyCode, }; } /// Implements the extended byte codes for set 1 (prefixed with E0) fn mapExtendedScancode(code: u8) pc_keyboard.KeyboardError!pc_keyboard.KeyCode { return switch (code) { 0x11 => .AltRight, 0x14 => .ControlRight, 0x1F => .WindowsLeft, 0x27 => .WindowsRight, 0x2F => .Menus, 0x4A => .NumpadSlash, 0x5A => .NumpadEnter, 0x69 => .End, 0x6B => .ArrowLeft, 0x6C => .Home, 0x70 => .Insert, 0x71 => .Delete, 0x72 => .ArrowDown, 0x74 => .ArrowRight, 0x75 => .ArrowUp, 0x7A => .PageDown, 0x7D => .PageUp, else => pc_keyboard.KeyboardError.UnknownKeyCode, }; } comptime { @import("std").testing.refAllDecls(@This()); }
src/keycode/scancodes/scancode_set2.zig
const std = @import("std"); /// Sets whether or not buztd should daemonize /// itself. Don't use this if running buztd as a systemd /// service or something of the sort. pub const should_daemonize: bool = false; /// Free RAM percentage figures below this threshold are considered to be near terminal, meaning /// that buztd will start to check for Pressure Stall Information whenever the /// free RAM figures go below this. /// However, this free RAM amount is what the sysinfo syscall gives us, which does not take in consideration /// reclaimable or cached pages. The true free RAM amount available to the OS is bigger than what it indicates. pub const free_ram_threshold: u8 = 15; /// The Linux kernel presents canonical pressure metrics for memory, found in `/proc/pressure/memory`. /// Example: /// some avg10=0.00 avg60=0.00 avg300=0.00 total=11220657 /// full avg10=0.00 avg60=0.00 avg300=0.00 total=10947429 /// These ratios are percentages of recent trends over ten, sixty, and /// three hundred second windows. The `some` row indicates the percentage of time // in that given time frame in which _any_ process has stalled due to memory thrashing. /// /// This value configured here is the value of `some avg10` in which, if surpassed, some /// process will be killed. /// /// The ideal value for this cutoff varies a lot between systems. /// Try messing around with `tools/mem-eater.c` to guesstimate a value that works well for you. pub const cutoff_psi: f32 = 0.05; /// Sets processes that buztd must never kill. /// The values expected here are the `comm` values of the process you don't want to have terminated. /// A comm-value is the filename of the executable truncated to 16 characters.. /// /// Example: /// pub const unkillables = std.ComptimeStringMap(void, .{ /// .{ "firefox", void }, /// .{ "rustc", void }, /// .{ "electron", void }, /// }); pub const unkillables = std.ComptimeStringMap(void, .{ // Ideally, don't kill the oomkiller .{ "buztd", void }, }); /// If any error occurs, restarts the monitoring instead of exiting with an unsuccesful status code pub const retry: bool = true;
src/config.zig
const std = @import("std"); const expect = std.testing.expect; const minInt = std.math.minInt; test "@bitReverse" { comptime try testBitReverse(); try testBitReverse(); } fn testBitReverse() !void { // using comptime_ints, unsigned try expect(@bitReverse(u0, 0) == 0); try expect(@bitReverse(u5, 0x12) == 0x9); try expect(@bitReverse(u8, 0x12) == 0x48); try expect(@bitReverse(u16, 0x1234) == 0x2c48); try expect(@bitReverse(u24, 0x123456) == 0x6a2c48); try expect(@bitReverse(u32, 0x12345678) == 0x1e6a2c48); try expect(@bitReverse(u40, 0x123456789a) == 0x591e6a2c48); try expect(@bitReverse(u48, 0x123456789abc) == 0x3d591e6a2c48); try expect(@bitReverse(u56, 0x123456789abcde) == 0x7b3d591e6a2c48); try expect(@bitReverse(u64, 0x123456789abcdef1) == 0x8f7b3d591e6a2c48); try expect(@bitReverse(u128, 0x123456789abcdef11121314151617181) == 0x818e868a828c84888f7b3d591e6a2c48); // using runtime uints, unsigned var num0: u0 = 0; try expect(@bitReverse(u0, num0) == 0); var num5: u5 = 0x12; try expect(@bitReverse(u5, num5) == 0x9); var num8: u8 = 0x12; try expect(@bitReverse(u8, num8) == 0x48); var num16: u16 = 0x1234; try expect(@bitReverse(u16, num16) == 0x2c48); var num24: u24 = 0x123456; try expect(@bitReverse(u24, num24) == 0x6a2c48); var num32: u32 = 0x12345678; try expect(@bitReverse(u32, num32) == 0x1e6a2c48); var num40: u40 = 0x123456789a; try expect(@bitReverse(u40, num40) == 0x591e6a2c48); var num48: u48 = 0x123456789abc; try expect(@bitReverse(u48, num48) == 0x3d591e6a2c48); var num56: u56 = 0x123456789abcde; try expect(@bitReverse(u56, num56) == 0x7b3d591e6a2c48); var num64: u64 = 0x123456789abcdef1; try expect(@bitReverse(u64, num64) == 0x8f7b3d591e6a2c48); var num128: u128 = 0x123456789abcdef11121314151617181; try expect(@bitReverse(u128, num128) == 0x818e868a828c84888f7b3d591e6a2c48); // using comptime_ints, signed, positive try expect(@bitReverse(u8, @as(u8, 0)) == 0); try expect(@bitReverse(i8, @bitCast(i8, @as(u8, 0x92))) == @bitCast(i8, @as(u8, 0x49))); try expect(@bitReverse(i16, @bitCast(i16, @as(u16, 0x1234))) == @bitCast(i16, @as(u16, 0x2c48))); try expect(@bitReverse(i24, @bitCast(i24, @as(u24, 0x123456))) == @bitCast(i24, @as(u24, 0x6a2c48))); try expect(@bitReverse(i32, @bitCast(i32, @as(u32, 0x12345678))) == @bitCast(i32, @as(u32, 0x1e6a2c48))); try expect(@bitReverse(i40, @bitCast(i40, @as(u40, 0x123456789a))) == @bitCast(i40, @as(u40, 0x591e6a2c48))); try expect(@bitReverse(i48, @bitCast(i48, @as(u48, 0x123456789abc))) == @bitCast(i48, @as(u48, 0x3d591e6a2c48))); try expect(@bitReverse(i56, @bitCast(i56, @as(u56, 0x123456789abcde))) == @bitCast(i56, @as(u56, 0x7b3d591e6a2c48))); try expect(@bitReverse(i64, @bitCast(i64, @as(u64, 0x123456789abcdef1))) == @bitCast(i64, @as(u64, 0x8f7b3d591e6a2c48))); try expect(@bitReverse(i128, @bitCast(i128, @as(u128, 0x123456789abcdef11121314151617181))) == @bitCast(i128, @as(u128, 0x818e868a828c84888f7b3d591e6a2c48))); // using signed, negative. Compare to runtime ints returned from llvm. var neg8: i8 = -18; try expect(@bitReverse(i8, @as(i8, -18)) == @bitReverse(i8, neg8)); var neg16: i16 = -32694; try expect(@bitReverse(i16, @as(i16, -32694)) == @bitReverse(i16, neg16)); var neg24: i24 = -6773785; try expect(@bitReverse(i24, @as(i24, -6773785)) == @bitReverse(i24, neg24)); var neg32: i32 = -16773785; try expect(@bitReverse(i32, @as(i32, -16773785)) == @bitReverse(i32, neg32)); }
test/behavior/bitreverse.zig
const std = @import("std"); const assert = std.debug.assert; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; defer _ = gpa.deinit(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len != 2) { std.log.err("Please provide an input file path.", .{}); return; } const input_file = try std.fs.cwd().openFile(args[1], .{}); defer input_file.close(); const input_reader = input_file.reader(); const Pass = struct { row: u7 = 0, column: u3 = 0, pub fn seat_id(self: @This()) u32 { return @as(u32, self.row) * 8 + self.column; } pub fn setFromBSP(self: *@This(), bsp: []const u8) !void { var row_range = [_]u7{ 0, 127 }; var col_range = [_]u3{ 0, 7 }; for (bsp) |c| { switch (c) { // lower half of row range 'F' => row_range[1] = row_range[1] / 2 + row_range[0] / 2, // higher half of row range 'B' => row_range[0] = row_range[1] / 2 + row_range[0] / 2 + 1, // lower half of column range 'L' => col_range[1] = col_range[1] / 2 + col_range[0] / 2, // higher half of column range 'R' => col_range[0] = col_range[1] / 2 + col_range[0] / 2 + 1, else => return error.UnhandledCharacter, } } assert(row_range[0] == row_range[1]); assert(col_range[0] == col_range[1]); self.row = row_range[0]; self.column = col_range[0]; } }; var ids_present = std.AutoHashMap(usize, bool).init(allocator); defer ids_present.deinit(); var current = Pass{}; var highest_id: u32 = 0; var buf: [10]u8 = undefined; while (try input_reader.readUntilDelimiterOrEof(buf[0..], '\n')) |line| { try current.setFromBSP(line); var id = current.seat_id(); try ids_present.put(id, true); if (highest_id < id) { highest_id = id; } } var seat: u32 = 0; var i = highest_id; while (i > 0) : (i -= 1) { _ = ids_present.get(i) orelse break; } std.log.info("The highest seat ID on a pass is {}.", .{highest_id}); std.log.info("The seat ID is {}.", .{i}); }
src/day05.zig
const std = @import("std"); const testing = std.testing; const allocator = std.heap.page_allocator; pub const Game = struct { const SIZE = 10_000; pub const Mode = enum { Simple, Recursive, }; const Cards = struct { values: [SIZE]usize, top: usize, bot: usize, buf: [SIZE]u8, pub fn init() Cards { var self = Cards{ .values = [_]usize{0} ** SIZE, .top = 0, .bot = 0, .buf = undefined, }; return self; } pub fn clone(self: Cards, count: usize) Cards { var other = Cards.init(); var p: usize = self.top; while (p < self.top + count) : (p += 1) { other.values[other.bot] = self.values[p]; other.bot += 1; } return other; } pub fn empty(self: Cards) bool { return self.size() == 0; } pub fn size(self: Cards) usize { return self.bot - self.top; } pub fn state(self: *Cards) []const u8 { var p: usize = 0; var c: usize = self.top; while (c < self.bot) : (c += 1) { if (p > 0) { self.buf[p] = ','; p += 1; } const s = std.fmt.bufPrint(self.buf[p..], "{}", .{self.values[c]}) catch unreachable; p += s.len; } const s = self.buf[0..p]; return s; } pub fn score(self: Cards) usize { if (self.top > self.bot) @panic("WTF"); var total: usize = 0; var n: usize = 1; var p: usize = self.bot - 1; while (p >= self.top) : (p -= 1) { const points = n * self.values[p]; total += points; n += 1; } return total; } pub fn take_top(self: *Cards) usize { if (self.empty()) @panic("EMPTY"); const card = self.values[self.top]; self.top += 1; return card; } pub fn put_bottom(self: *Cards, card: usize) void { self.values[self.bot] = card; self.bot += 1; } }; mode: Mode, cards: [2]Cards, turn: usize, pub fn init(mode: Mode) Game { var self = Game{ .mode = mode, .cards = undefined, .turn = 0, }; self.cards[0] = Cards.init(); self.cards[1] = Cards.init(); return self; } pub fn deinit(self: *Game) void { _ = self; } pub fn add_line(self: *Game, line: []const u8) void { if (line.len == 0) return; if (std.mem.startsWith(u8, line, "Player ")) { var it = std.mem.tokenize(u8, line, " :"); _ = it.next().?; const player = std.fmt.parseInt(usize, it.next().?, 10) catch unreachable; self.turn = player - 1; return; } const card = std.fmt.parseInt(usize, line, 10) catch unreachable; self.cards[self.turn].put_bottom(card); } pub fn play(self: *Game) usize { const winner = self.play_recursive(0, &self.cards); const score = self.get_score(winner); return score; } pub fn play_recursive(self: *Game, level: usize, cards: *[2]Cards) usize { // std.debug.warn("GAME level {} - {} vs {} cards\n", .{ level, cards[0].size(), cards[1].size() }); var seen = std.StringHashMap(void).init(allocator); defer seen.deinit(); var round: usize = 0; var winner: usize = 0; while (true) : (round += 1) { if (self.mode == Mode.Recursive) { var state: [2][]const u8 = undefined; state[0] = cards[0].state(); state[1] = cards[1].state(); const label = std.mem.join(allocator, ":", state[0..]) catch unreachable; if (seen.contains(label)) { winner = 0; break; } _ = seen.put(label, {}) catch unreachable; } var round_winner: usize = 0; var card0 = cards[0].take_top(); var card1 = cards[1].take_top(); if (self.mode == Mode.Recursive and card0 <= cards[0].size() and card1 <= cards[1].size()) { // recursive play, new game var sub_cards: [2]Cards = undefined; sub_cards[0] = cards[0].clone(card0); sub_cards[1] = cards[1].clone(card1); round_winner = self.play_recursive(level + 1, &sub_cards); } else { // regular play if (card0 <= card1) { round_winner = 1; } } // winner card goes first if (round_winner == 1) { const t = card0; card0 = card1; card1 = t; } cards[round_winner].put_bottom(card0); cards[round_winner].put_bottom(card1); // std.debug.warn("<{}> ROUND {} WINNER {} -- {} {} -- {} {}\n", .{ level, round, round_winner, card0, card1, cards[0].empty(), cards[1].empty() }); if (cards[0].empty()) { winner = 1; break; } if (cards[1].empty()) { winner = 0; break; } } // std.debug.warn("<{}> WINNER {}\n", .{ level, winner }); return winner; } pub fn get_score(self: Game, winner: usize) usize { const score = self.cards[winner].score(); return score; } }; test "sample part a" { const data: []const u8 = \\Player 1: \\9 \\2 \\6 \\3 \\1 \\ \\Player 2: \\5 \\8 \\4 \\7 \\10 ; var game = Game.init(Game.Mode.Simple); defer game.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { game.add_line(line); } const score = game.play(); try testing.expect(score == 306); } test "sample part b" { const data: []const u8 = \\Player 1: \\9 \\2 \\6 \\3 \\1 \\ \\Player 2: \\5 \\8 \\4 \\7 \\10 ; var game = Game.init(Game.Mode.Recursive); defer game.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { game.add_line(line); } const score = game.play(); try testing.expect(score == 291); }
2020/p22/game.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const print = std.debug.print; const file = @embedFile("../input.txt"); const CellState = enum { floor, occupied, empty, }; var row_length: usize = undefined; const Coord = struct { row: i64, column: i64, pub fn toIndex(self: *const Coord) usize { return @intCast(usize, self.row * @intCast(i64, row_length) + self.column); } pub fn fromIndex(index: usize) Coord { return .{ .row = @intCast(i64, index / row_length), .column = @intCast(i64, index % row_length), }; } }; pub fn main() !void { // Make a memory allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; // Find how long a row is row_length = mem.indexOf(u8, file, "\n").?; // Parse the input into an array of CellStates const input_map = try parseInput(allocator, file); // Duplicate the map into a new array var current_map = try allocator.dupe(CellState, input_map); // Allocate and "zero out", another copy var last_map = try allocator.alloc(CellState, input_map.len); mem.set(CellState, last_map, .floor); // Run part 1 const occupied_1 = part1(last_map, current_map); // Reset the arrays mem.copy(CellState, current_map, input_map); mem.set(CellState, last_map, .floor); // Run part 2 const occupied_2 = part2(last_map, current_map); print("Part 1: {}, Part 2: {}\n", .{ occupied_1, occupied_2 }); } pub fn part1(last_map: []CellState, current_map: []CellState) usize { // While the map is not the same as the last one while (!mem.eql(CellState, last_map, current_map)) { // Overwrite the last map with the current one mem.copy(CellState, last_map, current_map); // Update each cell with the rules for (current_map) |*cell, index| { // Make a coordinate for the current index const coord = Coord.fromIndex(index); // Make a list of coordinates for the adjacent cells const check_coords = [_]Coord{ .{ .row = coord.row - 1, .column = coord.column - 1 }, .{ .row = coord.row - 1, .column = coord.column }, .{ .row = coord.row - 1, .column = coord.column + 1 }, .{ .row = coord.row, .column = coord.column - 1 }, .{ .row = coord.row, .column = coord.column + 1 }, .{ .row = coord.row + 1, .column = coord.column - 1 }, .{ .row = coord.row + 1, .column = coord.column }, .{ .row = coord.row + 1, .column = coord.column + 1 }, }; // Count all occupied seats var occupied_seats: usize = 0; for (check_coords) |check_coord| { // Get the possible cell for the given coord const other_cell = cellGet(last_map, check_coord); // If it's occupied, add it to the count if (other_cell != null and other_cell.? == .occupied) { occupied_seats += 1; } } // Apply the rules given if (cell.* == .empty and occupied_seats == 0) { cell.* = .occupied; } else if (cell.* == .occupied and occupied_seats >= 4) { cell.* = .empty; } } } // Count all occupied seats in the full map var occupied_seats: usize = 0; for (current_map) |cell| { if (cell == .occupied) occupied_seats += 1; } return occupied_seats; } pub fn part2(last_map: []CellState, current_map: []CellState) usize { // While the map is not the same as the last one while (!mem.eql(CellState, last_map, current_map)) { // Overwrite the last map with the current one mem.copy(CellState, last_map, current_map); // Update each cell with the rules for (current_map) |*cell, index| { // Make a coordinate for the current index const check_coord = Coord.fromIndex(index); // Make a list of possible cell states for each direction const first_seats = [_]?CellState{ checkDirection(last_map, check_coord, -1, -1), checkDirection(last_map, check_coord, -1, 0), checkDirection(last_map, check_coord, -1, 1), checkDirection(last_map, check_coord, 0, -1), checkDirection(last_map, check_coord, 0, 1), checkDirection(last_map, check_coord, 1, -1), checkDirection(last_map, check_coord, 1, 0), checkDirection(last_map, check_coord, 1, 1), }; // Count all the occupied seats var occupied_seats: usize = 0; for (first_seats) |seat| { if (seat != null and seat.? == .occupied) { occupied_seats += 1; } } // Apply the given rules if (cell.* == .empty and occupied_seats == 0) { cell.* = .occupied; } else if (cell.* == .occupied and occupied_seats >= 5) { cell.* = .empty; } } } // Count all the occupied seats for the full map var occupied_seats: usize = 0; for (current_map) |cell| { if (cell == .occupied) occupied_seats += 1; } return occupied_seats; } /// Parse the given string into a list of CellStates fn parseInput(allocator: *Allocator, input: []const u8) ![]CellState { // Init an array list with probably the correct capacity var array_list = try std.ArrayList(CellState).initCapacity(allocator, row_length * row_length); // Append the correct enum values, skipping newlines for (file) |char| { switch (char) { 'L' => { try array_list.append(.empty); }, '#' => { try array_list.append(.occupied); }, '.' => { try array_list.append(.floor); }, else => {}, } } // Return the actual slice, not an array list return array_list.toOwnedSlice(); } /// Given a coord, get the cell if it's within bounds, otherwise null fn cellGet(slice: []const CellState, coord: Coord) ?CellState { return if (coord.row >= 0 and coord.row < row_length and coord.column >= 0 and coord.column < row_length) slice[coord.toIndex()] else null; } /// Repeatedly check in a given direction until you find something that's not the floor (aka, Chair or null) fn checkDirection(map: []const CellState, start: Coord, row_change: i8, column_change: i8) ?CellState { // Move once in the direction var coord = .{ .row = start.row + row_change, .column = start.column + column_change }; // While we keep getting non-null values while (cellGet(map, coord)) |cell| { if (cell != .floor) return cell; coord = .{ .row = coord.row + row_change, .column = coord.column + column_change }; } return null; } /// More for debug, print out the current map fn printMap(map: []const CellState) void { for (map) |cell, index| { const cell_display: u8 = switch (cell) { .occupied => '#', .empty => 'L', .floor => '.', }; print("{c}", .{cell_display}); if (index % row_length == row_length - 1) print("\n", .{}); } }
2020/day11/zig/day11.zig
const os = @import("root").os; const std = @import("std"); const range = os.lib.range.range; const paging = os.memory.paging; const pmm = os.memory.pmm; const font_fixed_6x13 = .{ .width = 6, .height = 13, .base = 0x20, .data = @embedFile("fixed6x13.bin"), }; const font_fixed_8x13 = .{ .width = 8, .height = 13, .base = 0x20, .data = @embedFile("fixed8x13.bin"), }; const vesa_font = .{ .width = 8, .height = 8, .base = 0x20, .data = @embedFile("vesa_font.bin"), }; const font = font_fixed_6x13; comptime { std.debug.assert(is_printable('?')); } fn is_printable(c: u8) bool { return font.base <= c and c < font.base + font.data.len/8; } const bgcol = 0x20; const fgcol = 0xbf; const clear_screen = true; const Framebuffer = struct { pitch: usize, width: u32, height: u32, bpp: usize, pos_x: usize = 0, pos_y: usize = 0, yscroll: usize = 0, scrolling: bool = false, updater: Updater, updater_ctx: usize, backbuffer: []u8, bb_phys: usize, fn width_in_chars(self: *@This()) usize { return self.width / font.width; } fn height_in_chars(self: *@This()) usize { return self.height / font.height; } fn blit_impl(self: *@This(), comptime bpp: usize, ch: u8) void { @setRuntimeSafety(false); var y: u32 = 0; while (y < font.height) : (y += 1) { const chr_line = font.data[y + (@as(usize, ch) - font.base) * font.height * ((font.width + 7)/8)]; const ypx = self.pos_y * font.height + y; const xpx = self.pos_x * font.width; const bg_pixels = self.backbuffer[(self.pitch * ypx + xpx * bpp)..]; inline for(range(font.width)) |x| { const shift: u3 = font.width - 1 - x; const has_pixel_set = ((chr_line >> shift) & 1) == 1; if (has_pixel_set) { bg_pixels[0 + x * bpp] = fgcol; bg_pixels[1 + x * bpp] = fgcol; bg_pixels[2 + x * bpp] = fgcol; } else { bg_pixels[0 + x * bpp] = bgcol; bg_pixels[1 + x * bpp] = bgcol; bg_pixels[2 + x * bpp] = bgcol; } } } self.pos_x += 1; } fn blit_char(self: *@This(), ch: u8) void { switch (self.bpp) { 4 => self.blit_impl(4, ch), 3 => self.blit_impl(3, ch), else => @panic("VESAlog: Unimplemented BPP") } } fn feed_line(self: *@This()) void { self.pos_x = 0; if(self.pos_y == self.height_in_chars() - 1) { self.pos_y = 0; self.scrolling = true; } else { self.pos_y += 1; } if (self.scrolling) { self.yscroll += 1; if (self.yscroll == self.height_in_chars()) self.yscroll = 0; } @memset(self.backbuffer.ptr + self.pitch * font.height * self.pos_y, bgcol, self.pitch * font.height); // clean last line } fn update(self: *@This()) void { @setRuntimeSafety(false); const yoff = self.yscroll * font.height; const used_h = self.height_in_chars() * font.height; if (yoff > 0) self.updater(self.backbuffer.ptr, 0, used_h - yoff, yoff - font.height, self.pitch, self.updater_ctx); self.updater(self.backbuffer.ptr, yoff, 0, used_h - yoff, self.pitch, self.updater_ctx); } pub fn putch(self: *@This(), ch: u8) void { if (ch == '\n') { self.feed_line(); self.update(); return; } if (self.pos_x == framebuffer.?.width_in_chars()) self.feed_line(); self.blit_char(if (is_printable(ch)) ch else '?'); } }; pub fn lfb_updater(bb: [*]u8, yoff_src: usize, yoff_dest: usize, ysize: usize, pitch: usize, ctx: usize) void { @setRuntimeSafety(false); const virt = pmm.phys_to_write_combining_virt(ctx); @memcpy(@intToPtr([*]u8, virt + pitch * yoff_dest), bb + pitch * yoff_src, ysize * pitch); } pub var framebuffer: ?Framebuffer = null; pub const Updater = fn(bb: [*]u8, yoff_src: usize, yoff_dest: usize, ysize: usize, pitch: usize, ctx: usize) void; pub const FBInfo = struct { width: u32, height: u32 }; pub fn get_info() ?FBInfo { if (framebuffer) |fb| { var i = .{ .width = fb.width, .height = fb.height }; return i; } else return null; } pub fn set_updater(u: Updater, ctx: usize) void { if (framebuffer) |*fb| { fb.updater = u; fb.updater_ctx = ctx; } } pub fn get_backbuffer_phy() usize { return framebuffer.?.bb_phys; } pub fn register_fb(updater: Updater, updater_ctx: usize, fb_pitch: u16, fb_width: u16, fb_height: u16, fb_bpp_in: u16) void { std.debug.assert(fb_bpp_in == 24 or fb_bpp_in == 32); const fb_bpp = fb_bpp_in / 8; const fb_size = @as(usize, fb_pitch) * @as(usize, fb_height); const bb_phys = os.memory.pmm.alloc_phys(fb_size) catch |err| { os.log("VESAlog: Could not allocate backbuffer: {s}\n", .{@errorName(err)}); return; }; const bb_virt = os.memory.paging.kernel_context.phys_to_write_back_virt(bb_phys); framebuffer = Framebuffer { .pitch = fb_pitch, .width = fb_width, .height = fb_height, .bpp = fb_bpp, .updater = updater, .updater_ctx = updater_ctx, .backbuffer = @intToPtr([*]u8, bb_virt)[0..fb_size], .bb_phys = bb_phys, }; if(clear_screen) { @memset(framebuffer.?.backbuffer.ptr, bgcol, fb_size); os.log("VESAlog: Screen cleared.\n", .{}); } os.log("VESAlog: width={}, height={}, pitch={}, bpp={}\n", .{fb_width, fb_height, fb_pitch, fb_bpp}); } pub fn putch(ch: u8) void { if(framebuffer) |*fb| { fb.putch(ch); } } pub fn disable() void { framebuffer = null; }
src/drivers/io/vesa_log.zig
const std = @import("std"); const builtin = @import("builtin"); const Builder = @import("std").build.Builder; pub fn build(b: *Builder) !void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("demo", "src/main.zig"); // https://github.com/ziglang/zig/issues/855 exe.addPackagePath("smithy", "smithy/src/smithy.zig"); // This bitfield workaround will end up requiring a bunch of headers that // currently mean building in the docker container is the best way to build // TODO: Determine if it's a good idea to copy these files out of our // docker container to the local fs so we can just build even outside // the container. And maybe, just maybe these even get committed to // source control? exe.addCSourceFile("src/bitfield-workaround.c", &[_][]const u8{"-std=c99"}); const c_include_dirs = .{ "./src/", "/usr/local/include", }; inline for (c_include_dirs) |dir| exe.addIncludeDir(dir); const dependent_objects = .{ "/usr/local/lib64/libs2n.a", "/usr/local/lib64/libcrypto.a", "/usr/local/lib64/libssl.a", "/usr/local/lib64/libaws-c-auth.a", "/usr/local/lib64/libaws-c-cal.a", "/usr/local/lib64/libaws-c-common.a", "/usr/local/lib64/libaws-c-compression.a", "/usr/local/lib64/libaws-c-http.a", "/usr/local/lib64/libaws-c-io.a", }; inline for (dependent_objects) |obj| exe.addObjectFile(obj); exe.linkSystemLibrary("c"); exe.setTarget(target); exe.setBuildMode(mode); exe.override_dest_dir = .{ .custom = ".." }; exe.linkage = .static; // TODO: Strip doesn't actually fully strip the executable. If we're on // linux we can run strip on the result, probably at the expense // of busting cache logic const is_strip = b.option(bool, "strip", "strip exe [true]") orelse true; exe.strip = is_strip; const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const test_step = b.step("test", "Run library tests"); var build_dir = try std.fs.openDirAbsolute(b.build_root, .{}); defer build_dir.close(); var src_dir = try build_dir.openDir("src", .{ .iterate = true }); defer src_dir.close(); var iterator = src_dir.iterate(); while (try iterator.next()) |entry| { if (std.mem.endsWith(u8, entry.name, ".zig")) { const name = try std.fmt.allocPrint(b.allocator, "src/{s}", .{entry.name}); defer b.allocator.free(name); const t = b.addTest(name); t.addPackagePath("smithy", "smithy/src/smithy.zig"); t.setBuildMode(mode); test_step.dependOn(&t.step); } } // TODO: Support > linux if (builtin.os.tag == .linux) { const codegen = b.step("gen", "Generate zig service code from smithy models"); codegen.dependOn(&b.addSystemCommand(&.{ "/bin/sh", "-c", "cd codegen && zig build" }).step); // Since codegen binary is built every time, if it's newer than our // service manifest we know it needs to be regenerated. So this step // will remove the service manifest if codegen has been touched, thereby // triggering the re-gen codegen.dependOn(&b.addSystemCommand(&.{ "/bin/sh", "-c", \\ [ ! -f src/models/service_manifest.zig ] || \ \\ [ src/models/service_manifest.zig -nt codegen/codegen ] || \ \\ rm src/models/service_manifest.zig }).step); codegen.dependOn(&b.addSystemCommand(&.{ "/bin/sh", "-c", \\ mkdir -p src/models/ && \ \\ [ -f src/models/service_manifest.zig ] || \ \\ ( cd codegen/models && ../codegen *.json && mv *.zig ../../src/models ) }).step); b.getInstallStep().dependOn(codegen); test_step.dependOn(codegen); } exe.install(); }
build.zig
const clap = @import("clap"); const SDL = @import("sdl2"); const std = @import("std"); const Machine = @import("Machine.zig"); const DEFAULT_EXE_ARG = "pacman"; const COINAGE = std.ComptimeStringMap(u8, .{ .{ "free", 0x00 }, .{ "1:1", 0x01 }, .{ "1:2", 0x02 }, .{ "2:1", 0x03 }, }); const LIVES = std.ComptimeStringMap(u8, .{ .{ "1", 0x00 }, .{ "2", 0x04 }, .{ "3", 0x08 }, .{ "5", 0x0c }, }); const BONUS = std.ComptimeStringMap(u8, .{ .{ "10k", 0x00 }, .{ "15k", 0x10 }, .{ "20k", 0x20 }, .{ "none", 0x30 }, }); fn stderr() std.fs.File.Writer { return std.io.getStdErr().writer(); } fn parseParam(comptime str: []const u8) clap.Param(clap.Help) { return clap.parseParam(str) catch unreachable; } const params = [_]clap.Param(clap.Help){ parseParam("-h, --help display help and exit"), parseParam("-t, --cocktail cocktail mode - for tabletop play"), parseParam("-c, --coinage <ratio> coins to credits ratio - free, 1:1, 1:2, or 2:1\ndefault: free"), parseParam("-l, --lives <num> number of lives - 1, 2, 3, or 5\ndefault: 3"), parseParam("-b, --bonus <points> extra life bonus - 10k, 15k, 20k, or none\ndefault: 10k"), parseParam("-d, --hard hard mode"), parseParam("-a, --alt-ghost-names alternate ghost names"), parseParam("<rom directory>"), }; fn printHelp(exe_arg: []const u8) !void { try stderr().print("usage: {s} ", .{exe_arg}); try clap.usage(stderr(), &params); try stderr().writeAll("\n"); try clap.help(stderr(), &params); try stderr().writeAll("controls:\n" ++ "\tarrow keys move\n" ++ "\twasd move (player two, cocktail mode)\n" ++ "\tc insert coin\n" ++ "\t1 start one player game\n" ++ "\t2 start two player game\n" ++ "\tp pause game\n" ++ "\tf1 toggle rack test\n" ++ "\tf2 toggle service mode\n"); } pub fn main() u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var diag = clap.Diagnostic{}; var args = clap.parse(clap.Help, &params, .{ .diagnostic = &diag }) catch |err| { var iter = std.process.args(); defer iter.deinit(); diag.report(std.io.getStdErr().writer(), err) catch {}; return 1; }; defer args.deinit(); if (args.flag("--help")) { printHelp(args.exe_arg orelse DEFAULT_EXE_ARG) catch {}; return 0; } const positionals = args.positionals(); if (positionals.len < 1) { stderr().writeAll("missing path to roms\n") catch {}; return 1; } SDL.init(.{ .video = true, .audio = true, .events = true }) catch return 1; defer SDL.quit(); var machine = Machine.init(allocator, positionals[0]) catch |err| { stderr().print("failed to set up machine: {s}\n", .{@errorName(err)}) catch {}; return 1; }; defer machine.deinit(allocator); if (args.flag("--cocktail")) { machine.inputs.cocktailMode(); } machine.dips |= COINAGE.get(args.option("--coinage") orelse "free") orelse { stderr().writeAll("invalid setting for '--coinage'\n") catch {}; return 1; }; machine.dips |= LIVES.get(args.option("--lives") orelse "3") orelse { stderr().writeAll("invalid setting for --lives\n") catch {}; return 1; }; machine.dips |= BONUS.get(args.option("--bonus") orelse "10k") orelse { stderr().writeAll("invalid setting for --bonus\n") catch {}; return 1; }; if (!args.flag("--hard")) { machine.dips |= 0x40; } if (!args.flag("--alt-ghost-names")) { machine.dips |= 0x80; } machine.run() catch |err| { stderr().print("game crashed: {s}\n", .{@errorName(err)}) catch {}; return 1; }; return 0; }
src/main.zig
const std = @import("std"); const info = std.log.info; const warn = std.log.warn; const bus = @import("bus.zig"); const cop0 = @import("cop0.zig"); const cop1 = @import("cop1.zig"); /// Sign extend 8-bit data fn exts8(data: u8) u64 { return @bitCast(u64, @intCast(i64, @bitCast(i8, data))); } /// Sign extend 16-bit data fn exts16(data: u16) u64 { return @bitCast(u64, @intCast(i64, @bitCast(i16, data))); } /// Sign extend 32-bit data fn exts32(data: u32) u64 { return @bitCast(u64, @intCast(i64, @bitCast(i32, data))); } /// Register aliases const CPUReg = enum(u32) { R0 = 0, AT = 1, V0 = 2, V1 = 3, A0 = 4, A1 = 5, A2 = 6, A3 = 7, T0 = 8, T1 = 9, T2 = 10, T3 = 11, T4 = 12, T5 = 13, T6 = 14, T7 = 15, S0 = 16, S1 = 17, S2 = 18, S3 = 19, S4 = 20, S5 = 21, S6 = 22, S7 = 23, T8 = 24, T9 = 25, K0 = 26, K1 = 27, GP = 28, SP = 29, S8 = 30, RA = 31, }; /// OPCODE field const Opcode = enum(u32) { SPECIAL = 0x00, REGIMM = 0x01, J = 0x02, JAL = 0x03, BEQ = 0x04, BNE = 0x05, BLEZ = 0x06, BGTZ = 0x07, ADDI = 0x08, ADDIU = 0x09, SLTI = 0x0A, SLTIU = 0x0B, ANDI = 0x0C, ORI = 0x0D, XORI = 0x0E, LUI = 0x0F, COP0 = 0x10, COP1 = 0x11, BEQL = 0x14, BNEL = 0x15, BLEZL = 0x16, BGTZL = 0x17, DADDI = 0x18, DADDIU = 0x19, LDL = 0x1A, LDR = 0x1B, LB = 0x20, LH = 0x21, LWL = 0x22, LW = 0x23, LBU = 0x24, LHU = 0x25, LWR = 0x26, LWU = 0x27, SB = 0x28, SH = 0x29, SWL = 0x2A, SW = 0x2B, SWR = 0x2E, CACHE = 0x2F, LWC1 = 0x31, LDC1 = 0x35, LD = 0x37, SWC1 = 0x39, SDC1 = 0x3D, SD = 0x3F, }; /// SPECIAL const Special = enum(u32) { SLL = 0x00, SRL = 0x02, SRA = 0x03, SLLV = 0x04, SRLV = 0x06, SRAV = 0x07, JR = 0x08, JALR = 0x09, MFHI = 0x10, MTHI = 0x11, MFLO = 0x12, MTLO = 0x13, MULT = 0x18, MULTU = 0x19, DIV = 0x1A, DIVU = 0x1B, DMULTU = 0x1D, DDIV = 0x1E, DDIVU = 0x1F, ADD = 0x20, ADDU = 0x21, SUBU = 0x23, SUB = 0x22, AND = 0x24, OR = 0x25, XOR = 0x26, NOR = 0x27, SLT = 0x2A, SLTU = 0x2B, DADD = 0x2C, DADDU = 0x2D, DSLL = 0x38, DSLL32 = 0x3C, DSRA32 = 0x3F, }; /// REGIMM const Regimm = enum(u32) { BLTZ = 0x00, BGEZ = 0x01, BLTZL = 0x02, BGEZL = 0x03, BGEZAL = 0x11, }; /// COP opcode const COP = enum(u32) { MF = 0x00, CF = 0x02, MT = 0x04, CT = 0x06, BC = 0x08, CO = 0x10, }; /// BC opcode const BC = enum(u32) { BCF, BCT, BCFL, BCTL, }; /// COP1 Opcode const COP1 = enum(u32) { S = 0x10, D = 0x11, W = 0x14, }; /// CO function const CO = enum(u32) { TLBR = 0x01, TLBWI = 0x02, TLBP = 0x08, ERET = 0x18, }; /// COP1 function const CO1 = enum(u32) { ADD = 0x00, SUB = 0x01, MUL = 0x02, DIV = 0x03, SQRT = 0x04, MOV = 0x06, NEG = 0x07, TRUNC_W = 0x0D, CVT_S = 0x20, CVT_D = 0x21, CVT_W = 0x24, C = 0x30, }; /// VR4300i register file const RegFile = struct { gprs: [32]u64 = undefined, lo: u64 = undefined, hi: u64 = undefined, pc : u64 = undefined, cpc: u64 = undefined, npc: u64 = undefined, /// Reads GPR (64-bit) pub fn get(self: RegFile, idx: u32) u64 { //if (idx == 26) isDisasm = true; return self.gprs[idx]; } /// Sets GPR (32-bit), optionally sign extends it pub fn set32(self: *RegFile, idx: u32, data: u32, isSignExtend: bool) void { var data_ = @intCast(u64, data); if (isSignExtend) { data_ = exts32(data); } self.gprs[idx] = data_; self.gprs[@enumToInt(CPUReg.R0)] = 0; // if (idx == 26) isDisasm = true; } /// Sets PC (32-bit), sign extends it pub fn setPC32(self: *RegFile, data: u32) void { if ((data & 3) != 0) @panic("unaligned pc"); self.pc = exts32(data); self.npc = self.pc +% 4; } /// Sets GPR (64-bit) pub fn set64(self: *RegFile, idx: u32, data: u64) void { self.gprs[idx] = data; self.gprs[@enumToInt(CPUReg.R0)] = 0; // if (idx == 26) isDisasm = true; } /// Sets PC (64-bit) pub fn setPC64(self: *RegFile, data: u64) void { if ((data & 3) != 0) @panic("unaligned pc"); self.pc = data; self.npc = self.pc +% 4; } }; /// RegFile instance var regs = RegFile{}; /// Are we in a branch delay slot? var isBranchDelay = false; pub var isRunning = true; pub var isDisasm = false; /// Initializes the VR4300i module pub fn init(isFastBoot: bool) void { if (isFastBoot) { info("[CPU] Fast boot.", .{}); // Simulate PIF ROM regs.set64(@enumToInt(CPUReg.T3), 0xFFFFFFFF_A4000040); regs.set64(@enumToInt(CPUReg.S4), 0x00000000_00000001); regs.set64(@enumToInt(CPUReg.S6), 0x00000000_0000003F); regs.set64(@enumToInt(CPUReg.SP), 0xFFFFFFFF_A4001FF0); regs.setPC32(0xA4000040); } else { info("[CPU] PIF boot.", .{}); regs.setPC32(0xBFC00000); } cop0.init(); } // Instruction field decoders fn getImm16(instr: u32) u16 { return @truncate(u16, instr); } fn getRd(instr: u32) u32 { return (instr >> 11) & 0x1F; } fn getRs(instr: u32) u32 { return (instr >> 21) & 0x1F; } fn getRt(instr: u32) u32 { return (instr >> 16) & 0x1F; } fn getSa(instr: u32) u32 { return (instr >> 6) & 0x1F; } fn getTarget(instr: u32) u32 { return (instr << 2) & 0xFFF_FFFF; } fn translateAddress(addr: u64) u64 { switch ((addr >> 28) & 0xF) { 0x0 ... 0x7 => { info("PC: {X}h", .{regs.cpc}); return cop0.tlbTranslate(addr & 0xFFFF_FFFF); }, 0x8 ... 0xB => return addr & 0x1FFF_FFFF, 0xC ... 0xF => return cop0.tlbTranslate(addr & 0xFFFF_FFFF), else => unreachable, } } /// Reads an 8-bit byte from memory fn read8(addr: u64) u8 { return bus.read8(translateAddress(addr)); } /// Reads a 16-bit halfword from memory fn read16(addr: u64) u16 { return bus.read16(translateAddress(addr)); } /// Reads a 32-bit word from memory fn read32(addr: u64) u32 { return bus.read32(translateAddress(addr)); } /// Reads a 64-bit word from memory fn read64(addr: u64) u64 { return bus.read64(translateAddress(addr)); } /// Writes an 8-bit byte to memory fn store8(addr: u64, data: u8) void { bus.write8(translateAddress(addr), data); } /// Writes a 16-bit halfword to memory fn store16(addr: u64, data: u16) void { bus.write16(translateAddress(addr), data); } /// Writes a 32-bit word to memory fn store32(addr: u64, data: u32) void { bus.write32(translateAddress(addr), data); } /// Writes a 64-bit doubleword to memory fn store64(addr: u64, data: u64) void { bus.write64(translateAddress(addr), data); } /// Reads an instruction, increments PC fn fetchInstr() u32 { const data = read32(regs.pc); if (isDisasm) info("{X}h", .{regs.pc}); regs.pc = regs.npc; regs.npc +%= 4; isBranchDelay = false; return data; } const ExceptionCode = cop0.ExceptionCode; pub fn raiseException(excCode: ExceptionCode) void { const vectorBase: u32 = 0x8000_0180; info("[CPU] {s} exception @ {X}h!", .{@tagName(excCode), regs.cpc}); cop0.cause.excCode = @enumToInt(excCode); const epc = regs.cpc; if (!cop0.status.exl) { cop0.cause.bd = isBranchDelay; if (isBranchDelay) { cop0.epc = @truncate(u32, epc -% 4); } else { cop0.epc = @truncate(u32, epc); } info("EPC: {X}h, BD: {}", .{cop0.epc, isBranchDelay}); } cop0.status.exl = true; info("Status: {X}h, Cause: {X}h", .{@bitCast(u32, cop0.status), @bitCast(u32, cop0.cause)}); regs.setPC32(vectorBase); } fn checkCOPUsable(comptime copN: comptime_int) bool { if ((cop0.status.cu & (1 << copN)) == 0) { cop0.cause.ce = copN; raiseException(ExceptionCode.CoprocessorUnusable); return false; } return true; } /// Decodes and executes an instruction fn decodeInstr(instr: u32) void { const opcode = instr >> 26; switch (opcode) { @enumToInt(Opcode.SPECIAL) => { const funct = instr & 0x3F; switch (funct) { @enumToInt(Special.SLL ) => iSLL (instr), @enumToInt(Special.SRL ) => iSRL (instr), @enumToInt(Special.SRA ) => iSRA (instr), @enumToInt(Special.SLLV ) => iSLLV (instr), @enumToInt(Special.SRLV ) => iSRLV (instr), @enumToInt(Special.SRAV ) => iSRAV (instr), @enumToInt(Special.JR ) => iJR (instr), @enumToInt(Special.JALR ) => iJALR (instr), @enumToInt(Special.MFHI ) => iMFHI (instr), @enumToInt(Special.MTHI ) => iMTHI (instr), @enumToInt(Special.MFLO ) => iMFLO (instr), @enumToInt(Special.MTLO ) => iMTLO (instr), @enumToInt(Special.MULT ) => iMULT (instr), @enumToInt(Special.MULTU ) => iMULTU (instr), @enumToInt(Special.DIV ) => iDIV (instr), @enumToInt(Special.DIVU ) => iDIVU (instr), @enumToInt(Special.DMULTU) => iDMULTU(instr), @enumToInt(Special.DDIV ) => iDDIV (instr), @enumToInt(Special.DDIVU ) => iDDIVU (instr), @enumToInt(Special.ADD ) => iADD (instr), @enumToInt(Special.ADDU ) => iADDU (instr), @enumToInt(Special.SUB ) => iSUB (instr), @enumToInt(Special.SUBU ) => iSUBU (instr), @enumToInt(Special.AND ) => iAND (instr), @enumToInt(Special.OR ) => iOR (instr), @enumToInt(Special.XOR ) => iXOR (instr), @enumToInt(Special.NOR ) => iNOR (instr), @enumToInt(Special.SLT ) => iSLT (instr), @enumToInt(Special.SLTU ) => iSLTU (instr), @enumToInt(Special.DADD ) => iDADD (instr), @enumToInt(Special.DADDU ) => iDADDU (instr), @enumToInt(Special.DSLL ) => iDSLL (instr), @enumToInt(Special.DSLL32) => iDSLL32(instr), @enumToInt(Special.DSRA32) => iDSRA32(instr), else => { warn("[CPU] Unhandled function {X}h ({X}h).", .{funct, instr}); unreachable; } } }, @enumToInt(Opcode.REGIMM) => { const regimm = getRt(instr); switch (regimm) { @enumToInt(Regimm.BLTZ ) => iBLTZ (instr), @enumToInt(Regimm.BGEZ ) => iBGEZ (instr), @enumToInt(Regimm.BLTZL ) => iBLTZL (instr), @enumToInt(Regimm.BGEZL ) => iBGEZL (instr), @enumToInt(Regimm.BGEZAL) => iBGEZAL(instr), else => { warn("[CPU] Unhandled REGIMM opcode {X}h ({X}h).", .{regimm, instr}); unreachable; } } }, @enumToInt(Opcode.J ) => iJ (instr), @enumToInt(Opcode.JAL ) => iJAL (instr), @enumToInt(Opcode.BEQ ) => iBEQ (instr), @enumToInt(Opcode.BNE ) => iBNE (instr), @enumToInt(Opcode.BLEZ ) => iBLEZ (instr), @enumToInt(Opcode.BGTZ ) => iBGTZ (instr), @enumToInt(Opcode.ADDI ) => iADDI (instr), @enumToInt(Opcode.ADDIU ) => iADDIU (instr), @enumToInt(Opcode.SLTI ) => iSLTI (instr), @enumToInt(Opcode.SLTIU ) => iSLTIU (instr), @enumToInt(Opcode.ANDI ) => iANDI (instr), @enumToInt(Opcode.ORI ) => iORI (instr), @enumToInt(Opcode.XORI ) => iXORI (instr), @enumToInt(Opcode.LUI ) => iLUI (instr), @enumToInt(Opcode.COP0 ) => { switch (getRs(instr)) { @enumToInt(COP.MF) => iMFC(instr, 0), @enumToInt(COP.MT) => iMTC(instr, 0), @enumToInt(COP.CO) => { const funct = instr & 0x3F; switch (funct) { @enumToInt(CO.TLBR ) => iTLBR(), @enumToInt(CO.TLBWI) => iTLBWI(), @enumToInt(CO.TLBP ) => iTLBP(), @enumToInt(CO.ERET ) => iERET(), else => { warn("[CPU] Unhandled CO function {X}h ({X}h).", .{funct, instr}); @panic("unhandled CO function"); } } }, else => { warn("[CPU] Unhandled COP0 opcode {X}h ({X}h).", .{getRs(instr), instr}); unreachable; } } }, @enumToInt(Opcode.COP1 ) => { if (!checkCOPUsable(1)) return; switch (getRs(instr)) { @enumToInt(COP.MF) => iMFC(instr, 1), @enumToInt(COP.CF) => iCFC(instr, 1), @enumToInt(COP.MT) => iMTC(instr, 1), @enumToInt(COP.CT) => iCTC(instr, 1), @enumToInt(COP.BC) => { const funct = getRt(instr); switch (funct) { @enumToInt(BC.BCF ) => iBC(instr, false, false, 1), @enumToInt(BC.BCT ) => iBC(instr, true , false, 1), @enumToInt(BC.BCFL) => iBC(instr, false, true , 1), @enumToInt(BC.BCTL) => iBC(instr, true , true , 1), else => { warn("[CPU] Unhandled BC1 opcode {X}h ({X}h).", .{funct, instr}); @panic("unhandled BC1 opcode"); } } }, @enumToInt(COP1.S) => { const Fmt = cop1.Fmt; const funct = instr & 0x3F; switch (funct) { @enumToInt(CO1.ADD ) => cop1.fADD (instr, Fmt.S), @enumToInt(CO1.SUB ) => cop1.fSUB (instr, Fmt.S), @enumToInt(CO1.MUL ) => cop1.fMUL (instr, Fmt.S), @enumToInt(CO1.DIV ) => cop1.fDIV (instr, Fmt.S), @enumToInt(CO1.SQRT ) => cop1.fSQRT (instr, Fmt.S), @enumToInt(CO1.MOV ) => cop1.fMOV (instr, Fmt.S), @enumToInt(CO1.NEG ) => cop1.fNEG (instr, Fmt.S), @enumToInt(CO1.TRUNC_W) => cop1.fTRUNC_W(instr, Fmt.S), // @enumToInt(CO1.CVT_S ) => cop1.fCVT_S (instr, Fmt.S), @enumToInt(CO1.CVT_D ) => cop1.fCVT_D (instr, Fmt.S), @enumToInt(CO1.CVT_W ) => cop1.fCVT_W (instr, Fmt.S), @enumToInt(CO1.C) ... @enumToInt(CO1.C) + 0xF => { cop1.fC(instr, @truncate(u4, instr), Fmt.S); }, else => { warn("[CPU] Unhandled CO1(S) function {X}h ({X}h).", .{funct, instr}); @panic("unhandled CO1(S) function"); } } }, @enumToInt(COP1.D) => { const Fmt = cop1.Fmt; const funct = instr & 0x3F; switch (funct) { @enumToInt(CO1.ADD ) => cop1.fADD (instr, Fmt.D), @enumToInt(CO1.SUB ) => cop1.fSUB (instr, Fmt.D), @enumToInt(CO1.MUL ) => cop1.fMUL (instr, Fmt.D), @enumToInt(CO1.DIV ) => cop1.fDIV (instr, Fmt.D), @enumToInt(CO1.MOV ) => cop1.fMOV (instr, Fmt.D), @enumToInt(CO1.TRUNC_W) => cop1.fTRUNC_W(instr, Fmt.D), @enumToInt(CO1.CVT_S ) => cop1.fCVT_S (instr, Fmt.D), @enumToInt(CO1.CVT_W ) => cop1.fCVT_W (instr, Fmt.D), // @enumToInt(CO1.CVT_D) => cop1.fCVT_D(instr, Fmt.D), @enumToInt(CO1.C) ... @enumToInt(CO1.C) + 0xF => { cop1.fC(instr, @truncate(u4, instr), Fmt.D); }, else => { warn("[CPU] Unhandled CO1(D) function {X}h ({X}h).", .{funct, instr}); @panic("unhandled CO1(D) function"); } } }, @enumToInt(COP1.W) => { const Fmt = cop1.Fmt; const funct = instr & 0x3F; switch (funct) { @enumToInt(CO1.CVT_S) => cop1.fCVT_S(instr, Fmt.W), @enumToInt(CO1.CVT_D) => cop1.fCVT_D(instr, Fmt.W), else => { warn("[CPU] Unhandled CO1(W) function {X}h ({X}h).", .{funct, instr}); @panic("unhandled CO1(W) function"); } } }, else => { warn("[CPU] Unhandled COP1 opcode {X}h ({X}h).", .{getRs(instr), instr}); unreachable; } } }, @enumToInt(Opcode.BEQL ) => iBEQL (instr), @enumToInt(Opcode.BNEL ) => iBNEL (instr), @enumToInt(Opcode.BLEZL ) => iBLEZL (instr), @enumToInt(Opcode.BGTZL ) => iBGTZL (instr), @enumToInt(Opcode.DADDI ) => iDADDI (instr), @enumToInt(Opcode.DADDIU) => iDADDIU(instr), @enumToInt(Opcode.LDL ) => iLDL (instr), @enumToInt(Opcode.LDR ) => iLDR (instr), @enumToInt(Opcode.LB ) => iLB (instr), @enumToInt(Opcode.LH ) => iLH (instr), @enumToInt(Opcode.LWL ) => iLWL (instr), @enumToInt(Opcode.LW ) => iLW (instr), @enumToInt(Opcode.LBU ) => iLBU (instr), @enumToInt(Opcode.LHU ) => iLHU (instr), @enumToInt(Opcode.LWR ) => iLWR (instr), @enumToInt(Opcode.LWU ) => iLWU (instr), @enumToInt(Opcode.SB ) => iSB (instr), @enumToInt(Opcode.SH ) => iSH (instr), @enumToInt(Opcode.SWL ) => iSWL (instr), @enumToInt(Opcode.SW ) => iSW (instr), @enumToInt(Opcode.SWR ) => iSWR (instr), @enumToInt(Opcode.CACHE ) => { //warn("[CPU] Unhandled CACHE instruction.", .{}); }, @enumToInt(Opcode.LWC1 ) => iLWC1 (instr), @enumToInt(Opcode.LDC1 ) => iLDC1 (instr), @enumToInt(Opcode.LD ) => iLD (instr), @enumToInt(Opcode.SWC1 ) => iSWC1 (instr), @enumToInt(Opcode.SDC1 ) => iSDC1 (instr), @enumToInt(Opcode.SD ) => iSD (instr), else => { warn("[CPU] Unhandled opcode {X}h ({X}h).", .{opcode, instr}); unreachable; } } // if (regs.pc >= 0xFFFFFFFF_800012E0 and regs.pc < 0xFFFFFFFF_80800000) unreachable; } // Instruction helpers fn doBranch(target: u64, isCondition: bool, isLink: comptime bool, isLikely: comptime bool) void { if (isLink) regs.set64(@enumToInt(CPUReg.RA), regs.npc); if (isCondition) { regs.npc = target; isBranchDelay = true; } else { if (isLikely) { regs.pc = regs.npc; regs.npc +%= 4; } } } // Instruction handlers /// ADD - ADD fn iADD(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); var result: i32 = undefined; if (@addWithOverflow(i32, @bitCast(i32, @truncate(u32, regs.get(rs))), @bitCast(i32, @truncate(u32, regs.get(rt))), &result)) { warn("[CPU] ADD overflow.", .{}); unreachable; } regs.set32(rd, @bitCast(u32, result), true); if (isDisasm) info("[CPU] ADD ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// ADDI - ADD Immediate fn iADDI(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); var result: i32 = undefined; if (@addWithOverflow(i32, @bitCast(i32, @truncate(u32, regs.get(rs))), @bitCast(i32, @truncate(u32, imm)), &result)) { warn("[CPU] ADDI overflow. rs: {X}h, imm: {X}h", .{@truncate(u32, regs.get(rs)), @truncate(u32, imm)}); unreachable; } regs.set32(rt, @bitCast(u32, result), true); if (isDisasm) info("[CPU] ADDI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// ADDIU - ADD Immediate Unsigned fn iADDIU(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rt, @truncate(u32, regs.get(rs) +% @truncate(u32, imm)), true); if (isDisasm) info("[CPU] ADDIU ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// ADDU - ADD Unsigned fn iADDU(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rs) +% @truncate(u32, regs.get(rt))), true); if (isDisasm) info("[CPU] ADDU ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// AND - AND fn iAND(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rs) & regs.get(rt)); if (isDisasm) info("[CPU] AND ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// ANDI - AND Immediate fn iANDI(instr: u32) void { const imm = @intCast(u64, getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, regs.get(rs) & imm); if (isDisasm) info("[CPU] ANDI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// Branch On Coprocessor z fn iBC(instr: u32, isTrue: comptime bool, isLikely: comptime bool, comptime copN: comptime_int) void { const offset = exts16(getImm16(instr)) << 2; const target = regs.pc +% offset; var coc: bool = undefined; if (copN == 1) { coc = cop1.coc1; } else { @panic("bc: unhandled copN"); } if (isTrue) { if (isLikely) { doBranch(target, coc, false, true); if (isDisasm) info("[CPU] BC{}TL, {X}h", .{copN, target}); } else { doBranch(target, coc, false, false); if (isDisasm) info("[CPU] BC{}T, {X}h", .{copN, target}); } } else { if (isLikely) { doBranch(target, !coc, false, true); if (isDisasm) info("[CPU] BC{}FL, {X}h", .{copN, target}); } else { doBranch(target, !coc, false, false); if (isDisasm) info("[CPU] BC{}F, {X}h", .{copN, target}); } } } /// BEQ - Branch on EQual fn iBEQ(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const rt = getRt(instr); const target = regs.pc +% offset; doBranch(target, regs.get(rs) == regs.get(rt), false, false); if (isDisasm) info("[CPU] BEQ ${}, ${}, {X}h; ${} = {X}h, ${} = {X}h", .{rs, rt, target, rs, regs.get(rs), rt, regs.get(rt)}); } /// BEQL - Branch on EQual Likely fn iBEQL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const rt = getRt(instr); const target = regs.pc +% offset; doBranch(target, regs.get(rs) == regs.get(rt), false, true); if (isDisasm) info("[CPU] BEQL ${}, ${}, {X}h; ${} = {X}h, ${} = {X}h", .{rs, rt, target, rs, regs.get(rs), rt, regs.get(rt)}); } /// BGEZ - Branch on Greater than or Equal Zero fn iBGEZ(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) >= 0, false, false); if (isDisasm) info("[CPU] BGEZ ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BGEZAL - Branch on Greater than or Equal Zero And Link fn iBGEZAL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) >= 0, true, false); if (isDisasm) info("[CPU] BGEZAL ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BGEZL - Branch on Greater than or Equal Zero Likely fn iBGEZL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) >= 0, false, true); if (isDisasm) info("[CPU] BGEZL ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BGTZ - Branch on Greater Than Zero fn iBGTZ(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) > 0, false, false); if (isDisasm) info("[CPU] BGTZ ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BGTZL - Branch on Greater Than Zero Likely fn iBGTZL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) > 0, false, true); if (isDisasm) info("[CPU] BGTZL ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BLEZ - Branch on Less than or Equal Zero fn iBLEZ(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) <= 0, false, false); if (isDisasm) info("[CPU] BLEZ ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BLEZL - Branch on Less than or Equal Zero Likely fn iBLEZL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) <= 0, false, true); if (isDisasm) info("[CPU] BLEZL ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BLTZ - Branch on Less Than Zero fn iBLTZ(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) < 0, false, false); if (isDisasm) info("[CPU] BLTZ ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BLTZL - Branch on Less Than Zero Likely fn iBLTZL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const target = regs.pc +% offset; doBranch(target, @bitCast(i64, regs.get(rs)) < 0, false, true); if (isDisasm) info("[CPU] BLTZL ${}, {X}h; ${} = {X}h", .{rs, target, rs, regs.get(rs)}); } /// BNE - Branch on Not Equal fn iBNE(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const rt = getRt(instr); const target = regs.pc +% offset; doBranch(target, regs.get(rs) != regs.get(rt), false, false); if (isDisasm) info("[CPU] BNE ${}, ${}, {X}h; ${} = {X}h, ${} = {X}h", .{rs, rt, target, rs, regs.get(rs), rt, regs.get(rt)}); if (rs == 30 and rt == 0) { if (regs.get(rs) == 0) { if (isDisasm) info("[CPU] All tests passed!", .{}); } else { if (isDisasm) info("[CPU] Failed test {}!", .{regs.get(rs)}); } } } /// BNEL - Branch on Not Equal Likely fn iBNEL(instr: u32) void { const offset = exts16(getImm16(instr)) << 2; const rs = getRs(instr); const rt = getRt(instr); const target = regs.pc +% offset; doBranch(target, regs.get(rs) != regs.get(rt), false, true); if (isDisasm) info("[CPU] BNEL ${}, ${}, {X}h; ${} = {X}h, ${} = {X}h", .{rs, rt, target, rs, regs.get(rs), rt, regs.get(rt)}); } /// CFC - Move From Control fn iCFC(instr: u32, copN: comptime i32) void { const rd = getRd(instr); const rt = getRt(instr); var data: u32 = undefined; if (copN == 1) { data = cop1.getCtrl32(rd); if (isDisasm) info("[CPU] CFC1 ${}, ${}; ${} = {X}h", .{rt, rd, rt, data}); } regs.set32(rt, data, true); } /// CTC - Move To Control fn iCTC(instr: u32, copN: comptime i32) void { const rd = getRd(instr); const rt = getRt(instr); const data = @truncate(u32, regs.get(rt)); if (copN == 1) { cop1.setCtrl32(rd, data); if (isDisasm) info("[CPU] CTC1 ${}, ${}; ${} = {X}h", .{rt, rd, rd, data}); } } /// DADD - Doubleword ADD fn iDADD(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); var result: i64 = undefined; if (@addWithOverflow(i64, @bitCast(i64, regs.get(rs)), @bitCast(i64, regs.get(rt)), &result)) { @panic("dadd: overflow"); } regs.set64(rd, @bitCast(u64, result)); if (isDisasm) info("[CPU] DADD ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// DADDI - Doubleword ADD Immediate fn iDADDI(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); var result: i64 = undefined; if (@addWithOverflow(i64, @bitCast(i64, regs.get(rs)), @bitCast(i64, imm), &result)) { @panic("daddi: overflow"); } regs.set64(rt, @bitCast(u64, result)); if (isDisasm) info("[CPU] DADDI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// DADDIU - Doubleword ADD Immediate Unsigned fn iDADDIU(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, regs.get(rs) +% imm); if (isDisasm) info("[CPU] DADDIU ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// DADDU - Doubleword ADD Unsigned fn iDADDU(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rs) +% regs.get(rt)); if (isDisasm) info("[CPU] DADDU ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// DDIV - Doubleword DIVide fn iDDIV(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const n = @bitCast(i64, regs.get(rs)); const d = @bitCast(i64, regs.get(rt)); if (d == 0) { warn("[CPU] DIV by zero.", .{}); if (n < 0) { regs.lo = 1; } else { regs.lo = 0xFFFFFFFF_FFFFFFFF; } regs.hi = @bitCast(u64, n); } else if (n == -0x80000000_00000000 and d == -1) { regs.lo = 0x8_00000000; regs.hi = 0; } else { regs.lo = @bitCast(u64, @divFloor(n, d)); if (d < 0) { regs.hi = @bitCast(u64, @rem(n, -d)); } else { regs.hi = @bitCast(u64, n) % @bitCast(u64, d); } } if (isDisasm) info("[CPU] DDIV ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// DDIVU - Doubleword DIVide Unsigned fn iDDIVU(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const n = regs.get(rs); const d = regs.get(rt); if (d == 0) { warn("[CPU] DDIVU by zero.", .{}); regs.lo = 0xFFFFFFFF_FFFFFFFF; regs.hi = n; } else { regs.lo = n / d; regs.hi = n % d; } if (isDisasm) info("[CPU] DDIVU ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// DIV - DIVide fn iDIV(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const n = @bitCast(i32, @truncate(u32, regs.get(rs))); const d = @bitCast(i32, @truncate(u32, regs.get(rt))); if (d == 0) { warn("[CPU] DIV by zero.", .{}); if (n < 0) { regs.lo = 1; } else { regs.lo = 0xFFFFFFFF_FFFFFFFF; } regs.hi = exts32(@bitCast(u32, n)); } else if (n == -0x80000000 and d == -1) { regs.lo = 0xFFFFFFFF_80000000; regs.hi = 0; } else { regs.lo = exts32(@bitCast(u32, @divFloor(n, d))); if (d < 0) { regs.hi = exts32(@bitCast(u32, @rem(n, -d))); } else { regs.hi = exts32(@bitCast(u32, n) % @bitCast(u32, d)); } } if (isDisasm) info("[CPU] DIV ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// DIVU - DIVide Unsigned fn iDIVU(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const n = @truncate(u32, regs.get(rs)); const d = @truncate(u32, regs.get(rt)); if (d == 0) { warn("[CPU] DIVU by zero.", .{}); regs.lo = 0xFFFFFFFF_FFFFFFFF; regs.hi = exts32(n); } else { regs.lo = exts32(n / d); regs.hi = exts32(n % d); } if (isDisasm) info("[CPU] DIVU ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// DMULTU - Doubleword MULTply Unsigned fn iDMULTU(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const result = @intCast(u128, regs.get(rs)) * @intCast(u128, regs.get(rt)); regs.lo = @truncate(u64, result >> 0); regs.hi = @truncate(u64, result >> 64); if (isDisasm) info("[CPU] DMULTU ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// DSLL - Doubleword Shift Left Logical fn iDSLL(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rt) << @truncate(u6, sa)); if (isDisasm) info("[CPU] DSLL ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } /// DSLL32 - Doubleword Shift Left Logical + 32 fn iDSLL32(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rt) << @truncate(u6, sa + 32)); if (isDisasm) info("[CPU] DSLL32 ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } /// DSRA32 - Doubleword Shift Right Arithmetic + 32 fn iDSRA32(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set64(rd, @bitCast(u64, @bitCast(i64, regs.get(rt)) >> @truncate(u6, sa + 32))); if (isDisasm) info("[CPU] DSRA32 ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } /// ERET - Exception RETurn fn iERET() void { if (cop0.status.erl) { cop0.status.erl = false; regs.setPC32(cop0.errorEPC); } else { cop0.status.exl = false; regs.setPC32(cop0.epc); } // TODO: set LL to false info("ERET, PC: {X}h", .{regs.pc}); if (isDisasm) info("[CPU] ERET", .{}); } /// J - Jump fn iJ(instr: u32) void { const target = (regs.pc & 0xFFFFFFFF_F0000000) | getTarget(instr); doBranch(target, true, false, false); if (isDisasm) info("[CPU] J {X}h", .{target}); } /// JAL - Jump And Link fn iJAL(instr: u32) void { const target = (regs.pc & 0xFFFFFFFF_F0000000) | getTarget(instr); doBranch(target, true, true, false); if (isDisasm) info("[CPU] JAL {X}h", .{target}); } /// JALR - Jump And Link Register fn iJALR(instr: u32) void { const rs = getRs(instr); const target = regs.get(rs); doBranch(target, true, true, false); if (isDisasm) info("[CPU] JALR ${}; PC = {X}h", .{rs, target}); } /// JR - Jump Register fn iJR(instr: u32) void { const rs = getRs(instr); const target = regs.get(rs); doBranch(target, true, false, false); if (isDisasm) info("[CPU] JR ${}; PC = {X}h", .{rs, target}); } /// LB - Load Byte fn iLB(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; regs.set64(rt, exts8(read8(addr))); if (isDisasm) info("[CPU] LB ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LBU - Load Byte Unsigned fn iLBU(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; regs.set64(rt, @intCast(u64, read8(addr))); if (isDisasm) info("[CPU] LBU ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LD - Load Doubleword fn iLD(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 7) != 0) @panic("unaligned load"); regs.set64(rt, read64(addr)); if (isDisasm) info("[CPU] LD ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LDC1 - Load Doubleword Coprocessor 1 fn iLDC1(instr: u32) void { if (!checkCOPUsable(1)) return; const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 7) != 0) @panic("unaligned load"); cop1.setFGR64(rt, read64(addr)); if (isDisasm) info("[CPU] LDC1 ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, cop1.getFGR64(rt)}); } /// LDL - Load Doubleword Left fn iLDL(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u6, 8 * (addr & 7)); const mask = @intCast(u64, 0xFFFFFFFF_FFFFFFFF) << shift; regs.set64(rt, (regs.get(rt) & ~mask) | (read64(addr & 0xFFFFFFF8) << shift)); if (isDisasm) info("[CPU] LDL ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LDR - Load Doubleword Right fn iLDR(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u6, 8 * ((addr ^ 7) & 7)); const mask = @intCast(u64, 0xFFFFFFFF_FFFFFFFF) >> shift; regs.set64(rt, (regs.get(rt) & ~mask) | (read64(addr & 0xFFFFFFF8) >> shift)); if (isDisasm) info("[CPU] LDR ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LH - Load Halfword fn iLH(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 1) != 0) @panic("unaligned load"); regs.set64(rt, exts16(read16(addr))); if (isDisasm) info("[CPU] LH ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LHU - Load Halfword Unsigned fn iLHU(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 1) != 0) @panic("unaligned load"); regs.set64(rt, @intCast(u64, read16(addr))); if (isDisasm) info("[CPU] LHU ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LUI - Load Upper Immediate fn iLUI(instr: u32) void { const imm = getImm16(instr); const rt = getRt(instr); regs.set64(rt, exts16(imm) << 16); if (isDisasm) info("[CPU] LUI ${}, {X}h; ${} = {X}h", .{rt, imm, rt, regs.get(rt)}); } /// LW - Load Word fn iLW(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 3) != 0) @panic("unaligned load"); regs.set32(rt, read32(addr), true); if (isDisasm) info("[CPU] LW ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LWC1 - Load Word Coprocessor 1 fn iLWC1(instr: u32) void { if (!checkCOPUsable(1)) return; const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; if ((addr & 3) != 0) @panic("unaligned load"); cop1.setFGR32(rt, read32(addr)); if (isDisasm) info("[CPU] LWC1 ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, cop1.getFGR32(rt)}); } /// LWL - Load Word Left fn iLWL(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u5, 8 * (addr & 3)); const mask = @intCast(u32, 0xFFFFFFFF) << shift; regs.set32(rt, (@truncate(u32, regs.get(rt)) & ~mask) | (read32(addr & 0xFFFFFFFC) << shift), true); if (isDisasm) info("[CPU] LWL ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LWR - Load Word Right fn iLWR(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u5, 8 * ((addr ^ 3) & 3)); const mask = @intCast(u32, 0xFFFFFFFF) >> shift; regs.set32(rt, (@truncate(u32, regs.get(rt)) & ~mask) | (read32(addr & 0xFFFFFFFC) >> shift), true); if (isDisasm) info("[CPU] LWR ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// LWU - Load Word Unsigned fn iLWU(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) + imm; if ((addr & 3) != 0) @panic("unaligned load"); regs.set64(rt, @intCast(u64, read32(addr))); if (isDisasm) info("[CPU] LWU ${}, ${}({}); ${} = ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), rt, addr, regs.get(rt)}); } /// MFC - Move From Coprocessor fn iMFC(instr: u32, copN: comptime i32) void { const rd = getRd(instr); const rt = getRt(instr); const data = @truncate(u32, regs.get(rt)); if (copN == 0) { regs.set32(rt, cop0.get32(rd), true); } else if (copN == 1) { regs.set32(rt, cop1.getFGR32(rd), true); } if (isDisasm) info("[CPU] MFC{} ${}, ${}; ${} = {X}h", .{copN, rt, rd, rd, data}); } /// MFHI - Move From HI fn iMFHI(instr: u32) void { const rd = getRd(instr); regs.set64(rd, regs.hi); if (isDisasm) info("[CPU] MFHI ${}; ${} = {X}h", .{rd, rd, regs.get(rd)}); } /// MFLO - Move From LO fn iMFLO(instr: u32) void { const rd = getRd(instr); regs.set64(rd, regs.lo); if (isDisasm) info("[CPU] MFLO ${}; ${} = {X}h", .{rd, rd, regs.get(rd)}); } /// MTC - Move To Coprocessor fn iMTC(instr: u32, copN: comptime i32) void { const rd = getRd(instr); const rt = getRt(instr); const data = @truncate(u32, regs.get(rt)); if (copN == 0) { cop0.set32(rd, data); if (isDisasm) info("[CPU] MTC0 ${}, ${}; ${} = {X}h", .{rt, rd, rd, data}); } else if (copN == 1) { if (!checkCOPUsable(1)) return; cop1.setFGR32(rd, data); if (isDisasm) info("[CPU] MTC1 ${}, ${}; ${} = {X}h", .{rt, rd, rd, data}); } } /// MTHI - Move To HI fn iMTHI(instr: u32) void { const rd = getRd(instr); regs.hi = regs.get(rd); if (isDisasm) info("[CPU] MTHI ${}; HI = {X}h", .{rd, regs.hi}); } /// MTLO - Move To LO fn iMTLO(instr: u32) void { const rd = getRd(instr); regs.lo = regs.get(rd); if (isDisasm) info("[CPU] MTLO ${}; LO = {X}h", .{rd, regs.lo}); } /// MULT - MULTply fn iMULT(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const result = @intCast(i64, @bitCast(i32, @truncate(u32, regs.get(rs)))) * @intCast(i64, @bitCast(i32, @truncate(u32, regs.get(rt)))); regs.lo = exts32(@truncate(u32, @bitCast(u64, result) >> 0)); regs.hi = exts32(@truncate(u32, @bitCast(u64, result) >> 32)); if (isDisasm) info("[CPU] MULT ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// MULTU - MULTply Unsigned fn iMULTU(instr: u32) void { const rs = getRs(instr); const rt = getRt(instr); const result = @intCast(u64, @truncate(u32, regs.get(rs))) * @intCast(u64, @truncate(u32, regs.get(rt))); regs.lo = exts32(@truncate(u32, result >> 0)); regs.hi = exts32(@truncate(u32, result >> 32)); if (isDisasm) info("[CPU] MULTU ${}, ${}; HI = {X}h, LO = {X}h", .{rs, rt, regs.hi, regs.lo}); } /// NOR - NOR fn iNOR(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, ~(regs.get(rs) | regs.get(rt))); if (isDisasm) info("[CPU] NOR ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// OR - OR fn iOR(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rs) | regs.get(rt)); if (isDisasm) info("[CPU] OR ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// ORI - OR Immediate fn iORI(instr: u32) void { const imm = @intCast(u64, getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, regs.get(rs) | imm); if (isDisasm) info("[CPU] ORI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// SB - Store Byte fn iSB(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store8(addr, @truncate(u8, regs.get(rt))); if (isDisasm) info("[CPU] SB ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, @truncate(u8, regs.get(rt))}); } /// SD - Store Doubleword fn iSD(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store64(addr, regs.get(rt)); if (isDisasm) info("[CPU] SD ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, regs.get(rt)}); } /// SDC1 - Store Doubleword Coprocessor 1 fn iSDC1(instr: u32) void { if (!checkCOPUsable(1)) return; const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store64(addr, cop1.getFGR64(rt)); if (isDisasm) info("[CPU] SDC1 ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, cop1.getFGR64(rt)}); } /// SH - Store Halfword fn iSH(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store16(addr, @truncate(u16, regs.get(rt))); if (isDisasm) info("[CPU] SH ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, @truncate(u16, regs.get(rt))}); } /// SLL - Shift Left Logical fn iSLL(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rt)) << @truncate(u5, sa), true); if (rd == @enumToInt(CPUReg.R0)) { if (isDisasm) info("[CPU] NOP", .{}); } else { if (isDisasm) info("[CPU] SLL ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } } /// SLLV - Shift Right Logical Variable fn iSLLV(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rt)) << @truncate(u5, regs.get(rs)), true); if (isDisasm) info("[CPU] SLLV ${}, ${}, ${}; ${} = {X}h", .{rd, rt, rs, rd, regs.get(rd)}); } /// SLT - Set on Less Than fn iSLT(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, @intCast(u64, @bitCast(u1, @bitCast(i64, regs.get(rs)) < @bitCast(i64, regs.get(rt))))); if (isDisasm) info("[CPU] SLT ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// SLTI - Set on Less Than Immediate fn iSLTI(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, @intCast(u64, @bitCast(u1, @bitCast(i64, regs.get(rs)) < @bitCast(i64, imm)))); if (isDisasm) info("[CPU] SLTI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// SLTIU - Set on Less Than Immediate fn iSLTIU(instr: u32) void { const imm = exts16(getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, @intCast(u64, @bitCast(u1, regs.get(rs) < imm))); if (isDisasm) info("[CPU] SLTIU ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// SLTU - Set on Less Than Unsigned fn iSLTU(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, @intCast(u64, @bitCast(u1, regs.get(rs) < regs.get(rt)))); if (isDisasm) info("[CPU] SLTU ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// SRA - Shift Right Arithmetic fn iSRA(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, @bitCast(u64, @bitCast(i64, regs.get(rt)) >> @truncate(u6, sa))), true); if (isDisasm) info("[CPU] SRA ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } /// SRAV - Shift Right Arithmetic Variable fn iSRAV(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, @bitCast(u64, @bitCast(i64, regs.get(rt)) >> @truncate(u6, regs.get(rs)))), true); if (isDisasm) info("[CPU] SRAV ${}, ${}, ${}; ${} = {X}h", .{rd, rt, rs, rd, regs.get(rd)}); } /// SRL - Shift Right Logical fn iSRL(instr: u32) void { const sa = getSa(instr); const rd = getRd(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rt)) >> @truncate(u5, sa), true); if (isDisasm) info("[CPU] SRL ${}, ${}, {}; ${} = {X}h", .{rd, rt, sa, rd, regs.get(rd)}); } /// SRLV - Shift Right Logical Variable fn iSRLV(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rt)) >> @truncate(u5, regs.get(rs)), true); if (isDisasm) info("[CPU] SRLV ${}, ${}, ${}; ${} = {X}h", .{rd, rt, rs, rd, regs.get(rd)}); } /// SUB - SUB fn iSUB(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); var result: i32 = undefined; if (@subWithOverflow(i32, @bitCast(i32, @truncate(u32, regs.get(rs))), @bitCast(i32, @truncate(u32, regs.get(rt))), &result)) { warn("[CPU] SUB overflow.", .{}); unreachable; } regs.set32(rd, @bitCast(u32, result), true); if (isDisasm) info("[CPU] SUB ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// SUBU - SUB Unsigned fn iSUBU(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set32(rd, @truncate(u32, regs.get(rs) -% @truncate(u32, regs.get(rt))), true); if (isDisasm) info("[CPU] SUBU ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// SW - Store Word fn iSW(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store32(addr, @truncate(u32, regs.get(rt))); if (isDisasm) info("[CPU] SW ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, @truncate(u32, regs.get(rt))}); } /// SWC1 - Store Word Coprocessor 1 fn iSWC1(instr: u32) void { if (!checkCOPUsable(1)) return; const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; store32(addr, cop1.getFGR32(rt)); if (isDisasm) info("[CPU] SWC1 ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, cop1.getFGR64(rt)}); } /// SWL - Store Word Left fn iSWL(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u5, 8 * (addr & 3)); const mask = @intCast(u32, 0xFFFFFFFF) >> shift; const data = read32(addr & 0xFFFFFFFC); store32(addr & 0xFFFFFFFC, (data & ~mask) | (@truncate(u32, regs.get(rt)) >> shift)); if (isDisasm) info("[CPU] SWL ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, @truncate(u32, regs.get(rt))}); } /// SWR - Store Word Right fn iSWR(instr: u32) void { const imm = exts16(getImm16(instr)); const base = getRs(instr); const rt = getRt(instr); const addr = regs.get(base) +% imm; const shift = @truncate(u5, 8 * ((addr ^ 3) & 3)); const mask = @intCast(u32, 0xFFFFFFFF) << shift; const data = read32(addr & 0xFFFFFFFC); store32(addr & 0xFFFFFFFC, (data & ~mask) | (@truncate(u32, regs.get(rt)) << shift)); if (isDisasm) info("[CPU] SWR ${}, ${}({}); ({X}h) = {X}h", .{rt, base, @bitCast(i64, imm), addr, @truncate(u32, regs.get(rt))}); } /// TLBP - TLB Probe fn iTLBP() void { cop0.index.p = true; var idx: u7 = 0; while (idx < 32) : (idx += 1) { const e = cop0.tlbEntries[idx]; if ((e.entryHi.vpn2l == cop0.entryHi.vpn2l and e.entryHi.vpn2h == cop0.entryHi.vpn2h) and (e.entryHi.g or e.entryHi.asid == cop0.entryHi.asid)) { cop0.index.index = @truncate(u5, idx); } } info("[CPU] TLBP", .{}); } /// TLBR - TLB Read fn iTLBR() void { const idx = cop0.index.index; const g = @intCast(u32, @bitCast(u1, cop0.tlbEntries[idx].entryHi.g)); const entryLo0 = @bitCast(u32, cop0.tlbEntries[idx].entryLo0); const entryLo1 = @bitCast(u32, cop0.tlbEntries[idx].entryLo1); const entryHi = @bitCast(u32, cop0.tlbEntries[idx].entryHi); const pageMask = @bitCast(u32, cop0.tlbEntries[idx].pageMask); cop0.set32(@enumToInt(cop0.COP0Reg.EntryLo0), entryLo0 | g); cop0.set32(@enumToInt(cop0.COP0Reg.EntryLo1), entryLo1 | g); cop0.set32(@enumToInt(cop0.COP0Reg.EntryHi ), entryHi); cop0.set32(@enumToInt(cop0.COP0Reg.PageMask), pageMask); info("[CPU] TLBR", .{}); } /// TLBWI - TLB Write Indexed fn iTLBWI() void { const idx = cop0.index.index; cop0.tlbEntries[idx].entryLo0 = @bitCast(cop0.EntryLo, @bitCast(u32, cop0.entryLo0) & 0xFFFF_FFFE); cop0.tlbEntries[idx].entryLo1 = @bitCast(cop0.EntryLo, @bitCast(u32, cop0.entryLo1) & 0xFFFF_FFFE); cop0.tlbEntries[idx].entryHi = @bitCast(cop0.EntryHi, @bitCast(u32, cop0.entryHi) & ~@bitCast(u32, cop0.pageMask)); cop0.tlbEntries[idx].pageMask = cop0.pageMask; cop0.tlbEntries[idx].entryHi.g = cop0.entryLo0.g and cop0.entryLo1.g; info("[CPU] TLBWI", .{}); } /// XOR - XOR fn iXOR(instr: u32) void { const rd = getRd(instr); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rd, regs.get(rs) ^ regs.get(rt)); if (isDisasm) info("[CPU] XOR ${}, ${}, ${}; ${} = {X}h", .{rd, rs, rt, rd, regs.get(rd)}); } /// XORI - XOR Immediate fn iXORI(instr: u32) void { const imm = @intCast(u64, getImm16(instr)); const rs = getRs(instr); const rt = getRt(instr); regs.set64(rt, regs.get(rs) ^ imm); if (isDisasm) info("[CPU] XORI ${}, ${}, {X}h; ${} = {X}h", .{rt, rs, imm, rt, regs.get(rt)}); } /// Steps the CPU module, returns elapsed cycles pub fn step() i64 { regs.cpc = regs.pc; if(cop0.checkForInterrupts()) { cop0.tickCount(1); return 2; } const instr = fetchInstr(); decodeInstr(instr); if (isDisasm) info("{X}h:{X}h", .{regs.cpc, instr}); cop0.tickCount(1); return 2; }
src/core/cpu.zig
usingnamespace @import("psptypes.zig"); pub const SceMpegLLI = extern struct { pSrc: ScePVoid, pDst: ScePVoid, Next: ScePVoid, iSize: SceInt32, }; pub const SceMpegYCrCbBuffer = extern struct { iFrameBufferHeight16: SceInt32, iFrameBufferWidth16: SceInt32, iUnknown: SceInt32, iUnknown2: SceInt32, pYBuffer: ScePVoid, pYBuffer2: ScePVoid, pCrBuffer: ScePVoid, pCbBuffer: ScePVoid, pCrBuffer2: ScePVoid, pCbBuffer2: ScePVoid, iFrameHeight: SceInt32, iFrameWidth: SceInt32, iFrameBufferWidth: SceInt32, iUnknown3: [11]SceInt32, }; pub const SceMpeg = ScePVoid; pub const SceMpegStream = SceVoid; pub const sceMpegRingbufferCB = ?fn (ScePVoid, SceInt32, ScePVoid) callconv(.C) SceInt32; pub const SceMpegRingbuffer = extern struct { iPackets: SceInt32, iUnk0: SceUInt32, iUnk1: SceUInt32, iUnk2: SceUInt32, iUnk3: SceUInt32, pData: ScePVoid, Callback: sceMpegRingbufferCB, pCBparam: ScePVoid, iUnk4: SceUInt32, iUnk5: SceUInt32, pSceMpeg: SceMpeg, }; pub const SceMpegAu = extern struct { iPtsMSB: SceUInt32, iPts: SceUInt32, iDtsMSB: SceUInt32, iDts: SceUInt32, iEsBuffer: SceUInt32, iAuSize: SceUInt32, }; pub const SceMpegAvcMode = extern struct { iUnk0: SceInt32, iPixelFormat: SceInt32, }; //MpegBase pub extern fn sceMpegBaseYCrCbCopyVme(YUVBuffer: ScePVoid, Buffer: [*c]SceInt32, Type: SceInt32) SceInt32; pub extern fn sceMpegBaseCscInit(width: SceInt32) SceInt32; pub extern fn sceMpegBaseCscVme(pRGBbuffer: ScePVoid, pRGBbuffer2: ScePVoid, width: SceInt32, pYCrCbBuffer: [*c]SceMpegYCrCbBuffer) SceInt32; pub extern fn sceMpegbase_BEA18F91(pLLI: [*c]SceMpegLLI) SceInt32; // sceMpegInit // // @return 0 if success. pub extern fn sceMpegInit() SceInt32; //sceMpegFinish pub extern fn sceMpegFinish() SceVoid; // sceMpegRingbufferQueryMemSize // // @param iPackets - number of packets in the ringbuffer // // @return < 0 if error else ringbuffer data size. pub extern fn sceMpegRingbufferQueryMemSize(iPackets: SceInt32) SceInt32; // sceMpegRingbufferConstruct // // @param Ringbuffer - pointer to a sceMpegRingbuffer struct // @param iPackets - number of packets in the ringbuffer // @param pData - pointer to allocated memory // @param iSize - size of allocated memory, shoud be sceMpegRingbufferQueryMemSize(iPackets) // @param Callback - ringbuffer callback // @param pCBparam - param passed to callback // // @return 0 if success. pub extern fn sceMpegRingbufferConstruct(Ringbuffer: [*c]SceMpegRingbuffer, iPackets: SceInt32, pData: ScePVoid, iSize: SceInt32, Callback: sceMpegRingbufferCB, pCBparam: ScePVoid) SceInt32; // sceMpegRingbufferDestruct // // @param Ringbuffer - pointer to a sceMpegRingbuffer struct pub extern fn sceMpegRingbufferDestruct(Ringbuffer: [*c]SceMpegRingbuffer) SceVoid; // sceMpegQueryMemSize // // @param Ringbuffer - pointer to a sceMpegRingbuffer struct // // @return < 0 if error else number of free packets in the ringbuffer. pub extern fn sceMpegRingbufferAvailableSize(Ringbuffer: [*c]SceMpegRingbuffer) SceInt32; // sceMpegRingbufferPut // // @param Ringbuffer - pointer to a sceMpegRingbuffer struct // @param iNumPackets - num packets to put into the ringbuffer // @param iAvailable - free packets in the ringbuffer, should be sceMpegRingbufferAvailableSize() // // @return < 0 if error else number of packets. pub extern fn sceMpegRingbufferPut(Ringbuffer: [*c]SceMpegRingbuffer, iNumPackets: SceInt32, iAvailable: SceInt32) SceInt32; // sceMpegQueryMemSize // // @param iUnk - Unknown, set to 0 // // @return < 0 if error else decoder data size. pub extern fn sceMpegQueryMemSize(iUnk: c_int) SceInt32; // sceMpegCreate // // @param Mpeg - will be filled // @param pData - pointer to allocated memory of size = sceMpegQueryMemSize() // @param iSize - size of data, should be = sceMpegQueryMemSize() // @param Ringbuffer - a ringbuffer // @param iFrameWidth - display buffer width, set to 512 if writing to framebuffer // @param iUnk1 - unknown, set to 0 // @param iUnk2 - unknown, set to 0 // // @return 0 if success. pub extern fn sceMpegCreate(Mpeg: [*c]SceMpeg, pData: ScePVoid, iSize: SceInt32, Ringbuffer: [*c]SceMpegRingbuffer, iFrameWidth: SceInt32, iUnk1: SceInt32, iUnk2: SceInt32) SceInt32; // sceMpegDelete // // @param Mpeg - SceMpeg handle pub extern fn sceMpegDelete(Mpeg: [*c]SceMpeg) SceVoid; // sceMpegQueryStreamOffset // // @param Mpeg - SceMpeg handle // @param pBuffer - pointer to file header // @param iOffset - will contain stream offset in bytes, usually 2048 // // @return 0 if success. pub extern fn sceMpegQueryStreamOffset(Mpeg: [*c]SceMpeg, pBuffer: ScePVoid, iOffset: [*c]SceInt32) SceInt32; // sceMpegQueryStreamSize // // @param pBuffer - pointer to file header // @param iSize - will contain stream size in bytes // // @return 0 if success. pub extern fn sceMpegQueryStreamSize(pBuffer: ScePVoid, iSize: [*c]SceInt32) SceInt32; // sceMpegRegistStream // // @param Mpeg - SceMpeg handle // @param iStreamID - stream id, 0 for video, 1 for audio // @param iUnk - unknown, set to 0 // // @return 0 if error. pub extern fn sceMpegRegistStream(Mpeg: [*c]SceMpeg, iStreamID: SceInt32, iUnk: SceInt32) ?*SceMpegStream; // sceMpegUnRegistStream // // @param Mpeg - SceMpeg handle // @param pStream - pointer to stream pub extern fn sceMpegUnRegistStream(Mpeg: SceMpeg, pStream: ?*SceMpegStream) SceVoid; // sceMpegFlushAllStreams // // @return 0 if success. pub extern fn sceMpegFlushAllStream(Mpeg: [*c]SceMpeg) SceInt32; // sceMpegMallocAvcEsBuf // // @return 0 if error else pointer to buffer. pub extern fn sceMpegMallocAvcEsBuf(Mpeg: [*c]SceMpeg) ScePVoid; // sceMpegFreeAvcEsBuf pub extern fn sceMpegFreeAvcEsBuf(Mpeg: [*c]SceMpeg, pBuf: ScePVoid) SceVoid; // sceMpegQueryAtracEsSize // // @param Mpeg - SceMpeg handle // @param iEsSize - will contain size of Es // @param iOutSize - will contain size of decoded data // // @return 0 if success. pub extern fn sceMpegQueryAtracEsSize(Mpeg: [*c]SceMpeg, iEsSize: [*c]SceInt32, iOutSize: [*c]SceInt32) SceInt32; // sceMpegInitAu // // @param Mpeg - SceMpeg handle // @param pEsBuffer - prevously allocated Es buffer // @param pAu - will contain pointer to Au // // @return 0 if success. pub extern fn sceMpegInitAu(Mpeg: [*c]SceMpeg, pEsBuffer: ScePVoid, pAu: [*c]SceMpegAu) SceInt32; // sceMpegGetAvcAu // // @param Mpeg - SceMpeg handle // @param pStream - associated stream // @param pAu - will contain pointer to Au // @param iUnk - unknown // // @return 0 if success. pub extern fn sceMpegGetAvcAu(Mpeg: [*c]SceMpeg, pStream: ?*SceMpegStream, pAu: [*c]SceMpegAu, iUnk: [*c]SceInt32) SceInt32; // sceMpegAvcDecodeMode // // @param Mpeg - SceMpeg handle // @param pMode - pointer to SceMpegAvcMode struct defining the decode mode (pixelformat) // @return 0 if success. pub extern fn sceMpegAvcDecodeMode(Mpeg: [*c]SceMpeg, pMode: [*c]SceMpegAvcMode) SceInt32; // sceMpegAvcDecode // // @param Mpeg - SceMpeg handle // @param pAu - video Au // @param iFrameWidth - output buffer width, set to 512 if writing to framebuffer // @param pBuffer - buffer that will contain the decoded frame // @param iInit - will be set to 0 on first call, then 1 // // @return 0 if success. pub extern fn sceMpegAvcDecode(Mpeg: [*c]SceMpeg, pAu: [*c]SceMpegAu, iFrameWidth: SceInt32, pBuffer: ScePVoid, iInit: [*c]SceInt32) SceInt32; // sceMpegAvcDecodeStop // // @param Mpeg - SceMpeg handle // @param iFrameWidth - output buffer width, set to 512 if writing to framebuffer // @param pBuffer - buffer that will contain the decoded frame // @param iStatus - frame number // // @return 0 if success. pub extern fn sceMpegAvcDecodeStop(Mpeg: [*c]SceMpeg, iFrameWidth: SceInt32, pBuffer: ScePVoid, iStatus: [*c]SceInt32) SceInt32; // sceMpegGetAtracAu // // @param Mpeg - SceMpeg handle // @param pStream - associated stream // @param pAu - will contain pointer to Au // @param pUnk - unknown // // @return 0 if success. pub extern fn sceMpegGetAtracAu(Mpeg: [*c]SceMpeg, pStream: ?*SceMpegStream, pAu: [*c]SceMpegAu, pUnk: ScePVoid) SceInt32; // sceMpegAtracDecode // // @param Mpeg - SceMpeg handle // @param pAu - video Au // @param pBuffer - buffer that will contain the decoded frame // @param iInit - set this to 1 on first call // // @return 0 if success. pub extern fn sceMpegAtracDecode(Mpeg: [*c]SceMpeg, pAu: [*c]SceMpegAu, pBuffer: ScePVoid, iInit: SceInt32) SceInt32;
src/psp/sdk/pspmpeg.zig
const std = @import("std"); const off_t = std.c.off_t; const size_t = std.c.size_t; const list = @import("list.zig"); const shmarea = @import("shmarea.zig"); const local = @import("local.zig"); pub const snd_pcm_stream_t = enum(c_int) { PLAYBACK = 0, CAPTURE, }; pub const snd_pcm_access_t = enum(c_int) { MMAP_INTERLEAVED = 0, MMAP_NONINTERLEAVED, MMAP_COMPLEX, RW_INTERLEAVED, RW_NONINTERLEAVED, }; pub const snd_pcm_format_t = enum(c_int) { UNKNOWN = -1, S8 = 0, U8, S16_LE, S16_BE, U16_LE, U16_BE, S24_LE, S24_BE, U24_LE, U24_BE, S32_LE, S32_BE, U32_LE, U32_BE, FLOAT_LE, FLOAT_BE, FLOAT64_LE, FLOAT64_BE, IEC958_SUBFRAME_LE, IEC958_SUBFRAME_BE, MU_LAW, A_LAW, IMA_ADPCM, MPEG, GSM, SPECIAL = 31, S24_3LE = 32, S24_3BE, U24_3LE, U24_3BE, S20_3LE, S20_3BE, U20_3LE, U20_3BE, S18_3LE, S18_3BE, U18_3LE, U18_3BE, }; pub const snd_pcm_subformat_t = enum(c_int) { STD = 0, }; pub const snd_pcm_tstamp_t = enum(c_int) { SND_PCM_TSTAMP_NONE = 0, SND_PCM_TSTAMP_ENABLE, }; pub const snd_pcm_uframes_t = c_ulong; pub const snd_pcm_sframes_t = c_long; pub const SND_PCM_NONBLOCK: c_int = 0x00000001; pub const SND_PCM_ASYNC: c_int = 0x00000002; pub const SND_PCM_NO_AUTO_RESAMPLE: c_int = 0x00010000; pub const SND_PCM_NO_AUTO_CHANNELS: c_int = 0x00020000; pub const SND_PCM_NO_AUTO_FORMAT: c_int = 0x00040000; pub const SND_PCM_NO_SOFTVOL: c_int = 0x00080000; pub const snd_pcm_rbptr_t = extern struct { master: ?*snd_pcm_t, ptr: ?*volatile snd_pcm_uframes_t, fd: c_int, offset: off_t, link_dst_count: c_int, link_dst: ?*?*snd_pcm_t, private_data: ?*anyopaque, changed: ?*anyopaque, }; pub const snd_pcm_channel_info_t = extern struct { channel: c_uint, addr: ?*anyopaque, first: c_uint, step: c_uint, type: enum(c_int) { AREA_SHM, AREA_MMAP, AREA_LOCAL }, u: extern union { shm: struct { area: ?*shmarea.snd_shm_area_t, sdmid: c_int, }, mmap: struct { fd: c_int, offset: off_t, }, }, reserved: [64]u8, }; pub const snd_pcm_ops_t = extern struct { close: ?*anyopaque, nonblock: ?*anyopaque, @"async": ?*anyopaque, info: ?*anyopaque, hw_refine: ?*anyopaque, hw_params: ?*anyopaque, hw_free: ?*anyopaque, sw_params: ?*anyopaque, channel_info: ?*anyopaque, dump: ?*anyopaque, mmap: ?*anyopaque, munmap: ?*anyopaque, }; pub const snd_pcm_fast_ops_t = extern struct { status: ?*anyopaque, prepare: ?*anyopaque, reset: ?*anyopaque, start: ?*anyopaque, drop: ?*anyopaque, drain: ?*anyopaque, pause: ?*anyopaque, state: ?*anyopaque, hwsync: ?*anyopaque, delay: ?*anyopaque, @"resume": ?*anyopaque, link: ?*anyopaque, link_slaves: ?*anyopaque, unlink: ?*anyopaque, rewindable: ?*anyopaque, rewind: ?*anyopaque, forwardable: ?*anyopaque, forward: ?*anyopaque, writei: ?*anyopaque, writen: ?*anyopaque, readi: ?*anyopaque, readn: ?*anyopaque, avail_update: ?*anyopaque, mmap_commit: ?*anyopaque, htimestamp: ?*anyopaque, poll_descriptors_count: ?*anyopaque, poll_descriptors: ?*anyopaque, poll_reevents: ?*anyopaque, }; pub const snd_pcm_t = extern struct { open_func: ?*anyopaque, name: [*c]u8, type: snd_pcm_type, stream: snd_pcm_stream_t, mode: c_int, minperiodtime: c_long, poll_fd_count: c_int, poll_fd: c_int, poll_events: c_ushort, setup_flags: c_int, access: snd_pcm_access_t, format: snd_pcm_format_t, subformat: snd_pcm_subformat_t, channels: c_uint, rate: c_uint, period_size: snd_pcm_uframes_t, period_time: c_uint, periods: local.snd_interval_t, tstamp_mode: snd_pcm_tstamp_t, period_step: c_uint, avail_min: snd_pcm_uframes_t, period_event: c_int, start_threshold: snd_pcm_uframes_t, stop_threshold: snd_pcm_uframes_t, silence_threshold: snd_pcm_uframes_t, silence_size: snd_pcm_uframes_t, boundary: snd_pcm_uframes_t, info: c_uint, msbits: c_uint, rate_num: c_uint, rate_den: c_uint, hw_flags: c_uint, fifo_size: snd_pcm_uframes_t, buffer_size: snd_pcm_uframes_t, buffer_time: local.snd_interval_t, sample_bits: c_uint, frame_bits: c_uint, appl: snd_pcm_rbptr_t, hw: snd_pcm_rbptr_t, min_align: snd_pcm_uframes_t, flags: c_uint, mmap_channels: [*]snd_pcm_channel_info_t, running_areas: [*]snd_pcm_channel_area_t, stopped_areas: [*]snd_pcm_channel_area_t, ops: ?*const snd_pcm_ops_t, fast_ops: ?*const snd_pcm_fast_ops_t, op_arg: ?*snd_pcm_t, fast_op_arg: ?*snd_pcm_t, private_data: ?*anyopaque, async_handlers: list.list_head, }; pub const snd_pcm_type = enum(c_int) { HW = 0, HOOKS, MULTI, FILE, NULL, SHM, INET, COPY, LINEAR, ALAW, MULAW, ADPCM, RATE, ROUTE, PLUG, SHARE, METER, MIX, DROUTE, LBSERVER, LINEAR_FLOAT, LADSPA, DMIX, JACK, DSNOOP, DSHARE, IEC958, SOFTVOL, IOPLUG, EXTPLUG, MMAP_EMUL, }; pub const snd_pcm_channel_area_t = extern struct { addr: ?*anyopaque, first: c_uint, step: c_uint, }; pub extern "asound" fn snd_pcm_open( *?*snd_pcm_t, [*c]const u8, snd_pcm_stream_t, c_int, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_close(?*snd_pcm_t) callconv(.C) c_int; pub extern "asound" fn snd_pcm_prepare(?*snd_pcm_t) callconv(.C) c_int; pub extern "asound" fn snd_pcm_drop(?*snd_pcm_t) callconv(.C) c_int; pub extern "asound" fn snd_pcm_drain(?*snd_pcm_t) callconv(.C) c_int; pub extern "asound" fn snd_pcm_start(?*snd_pcm_t) callconv(.C) c_int; pub extern "asound" fn snd_pcm_wait( ?*snd_pcm_t, c_int, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_writei( ?*snd_pcm_t, *anyopaque, snd_pcm_uframes_t, ) callconv(.C) snd_pcm_sframes_t; pub extern "asound" fn snd_pcm_hw_params_sizeof() callconv(.C) size_t; pub extern "asound" fn snd_pcm_hw_params_malloc( *?*local.snd_pcm_hw_params_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_free( ?*local.snd_pcm_hw_params_t, ) callconv(.C) void; pub extern "asound" fn snd_pcm_hw_params_copy( ?*local.snd_pcm_hw_params_t, ?*const local.snd_pcm_hw_params_t, ) callconv(.C) void; pub extern "asound" fn snd_pcm_hw_params_any( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_rate_resample( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, c_uint, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_access( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, snd_pcm_access_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_format( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, snd_pcm_format_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_channels( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, c_uint, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_rate_near( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, ?*c_uint, ?*c_int, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_get_buffer_size( ?*local.snd_pcm_hw_params_t, ?*snd_pcm_uframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_buffer_size( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, snd_pcm_uframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_hw_params_set_buffer_size_near( ?*snd_pcm_t, ?*local.snd_pcm_hw_params_t, ?*snd_pcm_uframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_sw_params_sizeof() callconv(.C) size_t; pub extern "asound" fn snd_pcm_sw_params_malloc( *?*local.snd_pcm_sw_params_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_sw_params_free( ?*local.snd_pcm_sw_params_t, ) callconv(.C) void; pub extern "asound" fn snd_pcm_sw_params_copy( ?*local.snd_pcm_sw_params_t, ?*const local.snd_pcm_sw_params_t, ) callconv(.C) void; pub extern "asound" fn snd_pcm_sw_params_set_start_threshold( ?*snd_pcm_t, ?*local.snd_pcm_sw_params_t, snd_pcm_uframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_avail( ?*snd_pcm_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_avail_update( ?*snd_pcm_t, ) callconv(.C) snd_pcm_sframes_t; pub extern "asound" fn snd_pcm_rewindable( ?*snd_pcm_t, ) callconv(.C) snd_pcm_sframes_t; pub extern "asound" fn snd_pcm_rewind( ?*snd_pcm_t, snd_pcm_sframes_t, ) callconv(.C) snd_pcm_sframes_t; pub extern "asound" fn snd_pcm_delay( ?*snd_pcm_t, ?*snd_pcm_sframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_mmap_begin( ?*snd_pcm_t, ?**const snd_pcm_channel_area_t, *snd_pcm_uframes_t, *snd_pcm_uframes_t, ) callconv(.C) c_int; pub extern "asound" fn snd_pcm_mmap_commit( ?*snd_pcm_t, snd_pcm_uframes_t, snd_pcm_uframes_t, ) callconv(.C) snd_pcm_sframes_t;
modules/platform/vendored/zig-alsa/src/pcm.zig
const std = @import("std"); const math = @import("math.zig"); const files = @import("files.zig"); const config = @import("config.zig"); const term = @import("term.zig"); const mem = std.mem; const print = std.debug.print; const assert = std.debug.assert; const expect = std.testing.expect; const Allocator = std.mem.Allocator; const Color = term.Color; const Scope = term.Scope; const Position = term.Position; const Builtin = config.Builtin; const KeyCode = config.KeyCode; const NEW_LINE = 0x0a; const MENU_BAR_HEIGHT = 1; const STATUS_BAR_HEIGHT = 1; // Errors const OOM = "Out of memory error"; const keyCodeOffset = 21; pub const Mode = enum { edit, conf }; var old_modus: Mode = undefined; var modus: Mode = .edit; test "indexOfRowStart" { var t = [_]u8{0} ** 5; try expect(Text.forTest("", &t).indexOfRowStart(0) == 0); try expect(Text.forTest("", &t).indexOfRowStart(1) == 0); try expect(Text.forTest("a", &t).indexOfRowStart(0) == 0); try expect(Text.forTest("\n", &t).indexOfRowStart(0) == 0); try expect(Text.forTest("\n", &t).indexOfRowStart(1) == 1); try expect(Text.forTest("\n\n", &t).indexOfRowStart(1) == 1); try expect(Text.forTest("a\n", &t).indexOfRowStart(1) == 2); try expect(Text.forTest("a\na", &t).indexOfRowStart(1) == 2); try expect(Text.forTest("a\n\na", &t).indexOfRowStart(2) == 3); } test "indexOf" { var t = [_]u8{0} ** 5; try expect(Text.forTest("", &t).indexOf(Position{.x=0, .y=0}) == 0); try expect(Text.forTest("a", &t).indexOf(Position{.x=1, .y=0}) == 1); try expect(Text.forTest("a", &t).indexOf(Position{.x=2, .y=0}) == 1); try expect(Text.forTest("a", &t).indexOf(Position{.x=0, .y=0}) == 0); try expect(Text.forTest("ab", &t).indexOf(Position{.x=1, .y=0}) == 1); try expect(Text.forTest("a\n", &t).indexOf(Position{.x=1, .y=0}) == 1); try expect(Text.forTest("a\nb", &t).indexOf(Position{.x=0, .y=1}) == 2); try expect(Text.forTest("a\n\nb", &t).indexOf(Position{.x=1, .y=2}) == 4); try expect(Text.forTest("a\nb\n", &t).indexOf(Position{.x=0, .y=2}) == 4); try expect(Text.forTest("a\n\nb", &t).indexOf(Position{.x=0, .y=2}) == 3); try expect(Text.forTest("a\nb\nc", &t).indexOf(Position{.x=0, .y=2}) == 4); } test "rowLength" { var t = [_]u8{0} ** 5; try expect(Text.forTest("", &t).rowLength(0) == 0); try expect(Text.forTest("a", &t).rowLength(0) == 1); try expect(Text.forTest("ab", &t).rowLength(0) == 2); try expect(Text.forTest("\n", &t).rowLength(0) == 1); try expect(Text.forTest("\n", &t).rowLength(1) == 0); try expect(Text.forTest("\na", &t).rowLength(0) == 1); try expect(Text.forTest("\na", &t).rowLength(1) == 1); try expect(Text.forTest("\na\n", &t).rowLength(1) == 2); try expect(Text.forTest("\n\n", &t).rowLength(1) == 1); try expect(Text.forTest("\n\n", &t).rowLength(2) == 0); try expect(Text.forTest("\n\na", &t).rowLength(2) == 1); } test "new" { var t = [_]u8{0} ** 5; try expect(Text.forTest("", &t).length == 0); try expect(Text.forTest("a", &t).length == 1); } const Text = struct { content: []u8, length: usize, cursor: Position, filename: []const u8, modified: bool, last_x: usize, page_y: usize, fn rows(self: *const Text) usize { var n: usize = 0; var i: usize = 0; while (i < self.length) : (i+=1) { if(self.content[i] == NEW_LINE) { n+=1; } } return n; } /// return the index of first charactern in given line fn indexOfRowStart(self: *const Text, line: usize) usize { if (line == 0) return 0; var n: usize = 0; var i: usize = 0; while (i < self.length) : (i+=1) { if(self.content[i] == NEW_LINE) { n+=1; if (n == line) return i + 1; } } if (n == 0) return 0; if (self.content[i] == NEW_LINE) return i + 1; if (n < line) return self.length; @panic("no more lines!"); } fn indexOfRowEnd(self: *const Text, line: usize) usize { return self.indexOfRowStart(line) + self.rowLength(line); } fn nextNewLine(self: *const Text, index: usize) usize { if (self.length == 0) return 0; var i = index; while (i < self.length) : (i+=1) { if(self.content[i] == NEW_LINE) { return i + 1; } } return self.length; } fn rowLength(self: *const Text, row: usize) usize { if (self.length == 0) return 0; const row_start = self.indexOfRowStart(row); const row_end = self.nextNewLine(row_start); if (row_end > row_start) return row_end - row_start; return 0; } fn indexOf(self: *Text, pos: Position) usize { if (self.length == 0) return 0; var i = self.indexOfRowStart(pos.y); const row_length = self.nextNewLine(i) - i; if (pos.x > row_length) { return i + row_length; } return i + pos.x; } fn cursorIndex(self: *Text) usize { return self.indexOf(self.cursor); } fn new(txt: []u8, len: usize) Text { assert(len <= txt.len); return Text { .content = txt, .length = len, .cursor = Position{ .x = 0, .y = 0 }, .filename = "", .modified = false, .last_x = 0, .page_y = 0, }; } fn copy(orig: Text, txt: []u8) Text { return Text { .content = txt, .cursor = Position{ .x = orig.cursor.x, .y = orig.cursor.y }, .length = orig.length, .filename = orig.filename, .modified = orig.modified, .last_x = orig.last_x, .page_y = orig.page_y, }; } fn forTest(comptime txt: []const u8, t: []u8) Text { return Text { .content = config.literalToArray(txt, t), .length = txt.len, .cursor = Position{ .x = 0, .y = 0 }, .filename = "", .modified = false, .last_x = 0, .page_y = 0, }; } }; const ScreenBuffer = struct { content: []u8, index: usize, fn new() ScreenBuffer { return ScreenBuffer { .content = "", .index = 0, }; } }; pub const ControlKey = enum(u8) { backspace = 0x7f, pub fn isControlKey(char: u8) bool { inline for (std.meta.fields(ControlKey)) |field| { if (char == field.value) return true; } return false; } }; pub fn loadFile(txt: Text, filepath: []const u8, allocator: Allocator) Text { var t = txt; t.filename = filepath; const file = std.fs.cwd().openFile(t.filename, .{ .mode = .read_only }) catch @panic("File open failed!"); defer file.close(); t.length = file.getEndPos() catch @panic("file seek error!"); // extent to multiple of chunk and add one chunk const length = math.multipleOf(config.chunk, t.length) + config.chunk; t.content = allocator.alloc(u8, length) catch @panic(OOM); const bytes_read = file.readAll(t.content) catch @panic("File too large!"); assert(bytes_read == t.length); message = ""; return t; } pub fn saveFile(t: *Text, screen_content: []u8) !void { const file = try std.fs.cwd().openFile(t.filename, .{ .mode = .write_only }); defer file.close(); _ = try file.write(t.content[0..t.length]); _ = try file.setEndPos(t.length); const stat = try file.stat(); assert(stat.size == t.length); t.modified = false; var size = bufStatusBar(t, screen_content, 0); size = bufCursor(t, screen_content, size); term.write(screen_content[0..size]); } pub fn loop(filepath: ?[]u8, allocator: Allocator) !void { var text = Text.new("", 0); var conf = Text.new("", 0); var screen = ScreenBuffer.new(); _ = term.updateWindowSize(); if(filepath != null) text = loadFile(text, filepath.?, allocator); defer allocator.free(text.content); // multiple times the space for long utf codes and ESC-Seq. screen.content = allocator.alloc(u8, config.width * config.height * 4) catch @panic(OOM); defer allocator.free(screen.content); term.rawMode(5); term.write(term.CLEAR_SCREEN); const home_config_file = files.homeFilePath(allocator); if(files.exists(home_config_file)) { conf = loadFile(conf, home_config_file, allocator); } else { if (!files.exists(files.home_path)) { message = "DIR"; std.fs.makeDirAbsolute(files.home_path) catch @panic("Failed: makeDirAbsolute"); } const cf = std.fs.createFileAbsolute(home_config_file, .{}) catch @panic("Failed: createFileAbsolute"); cf.close(); conf.filename = home_config_file; conf.content = allocator.alloc(u8, config.templ.len) catch @panic(OOM); conf.content = config.literalToArray(config.templ, conf.content); conf.length = config.templ.len; saveFile(&conf, screen.content) catch @panic("failed: save file"); } defer allocator.free(conf.content); config.parse(conf.content); var key: KeyCode = undefined; var current_text = getCurrentText(&text, &conf); bufScreen(current_text, screen.content, key); while(key.data[0] != quitKey()) { key = term.readKey(); if(key.len > 0) { processKey(&text, &conf, screen.content, key, allocator); } if (term.updateWindowSize()) bufScreen(current_text, screen.content, key); } term.write(term.RESET_MODE); term.cookedMode(); term.write(term.CLEAR_SCREEN); term.write(term.CURSOR_HOME); files.free(allocator); } /// builtin fn inline fn quitKey() u8 { return config.charOf(Builtin.quit, config.ctrlKey('q')); } inline fn toggleModus(mode: Mode) void { if (modus != mode) { old_modus = modus; modus = mode; } else { modus = old_modus; old_modus = mode; } } inline fn getCurrentText(text: *Text, cnf: *Text) *Text { return if (modus == .edit) text else cnf; } var enter_filename = false; const MAX_FILENAME_LENGTH: u8 = 32; var input_filename = [_]u8{0} ** MAX_FILENAME_LENGTH; var input_filename_index: u8 = 0; inline fn writeFilenameChar(char: u8, txt: *Text, screen_content: []u8, screen_index: usize) usize { if (input_filename_index < MAX_FILENAME_LENGTH) { input_filename[input_filename_index] = char; input_filename_index += 1; txt.filename = input_filename[0..input_filename_index]; message = if(files.exists(txt.filename)) "exists!" else ""; return bufStatusBar(txt, screen_content, screen_index); } return screen_index; } inline fn backspaceFilename(txt: *Text, screen_content: []u8, screen_index: usize) usize { if (input_filename_index > 0) { input_filename_index -= 1; txt.filename = input_filename[0..input_filename_index]; return bufStatusBar(txt, screen_content, screen_index); } return screen_index; } inline fn filenameEntered(txt: *Text, screen_content: []u8, screen_index: usize, allocator: Allocator) usize { if(files.exists(txt.filename)) message = "exists: overwriting!"; enter_filename = false; const file = std.fs.cwd().createFile(txt.filename, .{}) catch @panic("Failed: createFile"); file.close(); saveFile(txt, screen_content) catch |err| { message = std.fmt.allocPrint(allocator, "Can't save: {s}", .{ err }) catch @panic(OOM); }; return bufStatusBar(txt, screen_content, screen_index); } /// builtin fn fn toggleConfig(text: *Text, cnf: *Text, screen_content: []u8, key: KeyCode) *Text { var result = text; if (!enter_filename) { toggleModus(.conf); result = getCurrentText(text, cnf); bufScreen(result, screen_content, key); } return result; } /// builtin fn fn save(txt: *Text, screen_content: []u8, allocator: Allocator) void { if (txt.filename.len == 0) { enter_filename = true; } else { saveFile(txt, screen_content) catch |err| { message = std.fmt.allocPrint(allocator, "Can't save: {s}", .{ err }) catch @panic(OOM); }; } } inline fn isKeyBuiltin(key: KeyCode, builtin: Builtin) bool { const tc = config.keyOf(builtin); if (key.len == 0 or key.len != tc.len) return false; var i: usize = 0; while(i < key.len) : (i += 1) { if (key.data[i] != tc.data[i]) return false; } return true; } pub fn processKey(text: *Text, cnf: *Text, screen_content: []u8, key: KeyCode, allocator: Allocator) void { var t = getCurrentText(text, cnf); var i: usize = 0; if (isKeyBuiltin(key, Builtin.toggle_config)) { t = toggleConfig(text, cnf, screen_content, key); } else if (key.len == 1) { const c = key.data[0]; if (c == config.charOf(Builtin.new_line, config.ENTER)) { if (enter_filename) { i = filenameEntered(t, screen_content, i, allocator); } else { newLine(t, screen_content, key, allocator); } } else if (std.ascii.isAlNum(c) or std.ascii.isGraph(c) or c == ' ') { if (enter_filename) { i = writeFilenameChar(c, t, screen_content, i); } else { writeChar(c, t, screen_content, key, allocator); } } if (c == config.charOf(Builtin.save, config.ctrlKey('s'))) { save(t, screen_content, allocator); if (modus == .conf) config.parse(cnf.content); } if (c == @enumToInt(ControlKey.backspace)) { if (enter_filename) { i = backspaceFilename(t, screen_content, i); } else { backspace(t, screen_content, key); } } } else if (key.len == 3) { if (key.data[0] == 0x1b and key.data[1] == 0x5b and key.data[2] == 0x41) cursorUp(t, screen_content, key); if (key.data[0] == 0x1b and key.data[1] == 0x5b and key.data[2] == 0x42) cursorDown(t, screen_content, key); if (key.data[0] == 0x1b and key.data[1] == 0x5b and key.data[2] == 0x43) cursorRight(t, screen_content, key); if (key.data[0] == 0x1b and key.data[1] == 0x5b and key.data[2] == 0x44) cursorLeft(t, screen_content, key); } if (key.len > 0) { writeKeyCodes(t, screen_content, i, key); } } var themeForeground = Color.cyan; var themeBackground = Color.blue; var themeHighlight = Color.white; var themeWarn = Color.yellow; var themeError = Color.red; fn bufMenuBarMode(screen_content: []u8, screen_index: usize) usize { return term.bufAttributes(Scope.foreground, themeForeground, Scope.background, themeBackground, screen_content, screen_index); } fn bufMenuBarHighlightMode(screen_content: []u8, screen_index: usize) usize { return term.bufAttributes(Scope.foreground, themeHighlight, Scope.background, themeBackground, screen_content, screen_index); } fn bufStatusBarHighlightMode(screen_content: []u8, screen_index: usize) usize { return term.bufAttributes(Scope.foreground, themeHighlight, Scope.background, themeBackground, screen_content, screen_index); } fn bufStatusBarMode(screen_content: []u8, screen_index: usize) usize { return term.bufAttributes(Scope.foreground, themeForeground, Scope.background, themeBackground, screen_content, screen_index); } fn repeatChar(char: u8, count: u16) void { var i: u8 = 0; while(i<count) : (i += 1) { term.writeByte(char); } } fn bufShortCut(key: []const u8, label: []const u8, screen_content: []u8, screen_index: usize) usize { var i = bufMenuBarHighlightMode(screen_content, screen_index); i = term.bufWrite(key, screen_content, i); i = bufMenuBarMode(screen_content, i); return term.bufWrite(label, screen_content, i); } inline fn bufMenuBar(screen_content: []u8, screen_index: usize) usize { var i = term.bufWrite(term.CURSOR_HOME, screen_content, screen_index); if (modus == .edit) { i = bufShortCut("F1", " Config ", screen_content, i); } if (modus == .conf) { i = bufShortCut("F1", " go back", screen_content, i); } i = bufMenuBarMode(screen_content, i); i = term.bufWriteRepeat(' ', config.width - 10 - 25, screen_content, i); i = bufShortCut("S", "ave: Ctrl-s ", screen_content, i); i = bufShortCut("Q", "uit: Ctrl-q", screen_content, i); return i; } fn fileColor(changed: bool) Color { return if(changed) Color.yellow else Color.white; } inline fn positionOnScreen(pos: Position, page_y: usize) Position { return Position{ .x = pos.x, .y = MENU_BAR_HEIGHT + pos.y - page_y, }; } fn bufTextCursor(txt: *Text, screen_content: []u8, screen_index: usize) usize { var screen_pos = positionOnScreen(txt.cursor, txt.page_y); if (screen_pos.x >= config.width) { screen_pos.x = config.width - 1; } return term.bufCursor(screen_pos, screen_content, screen_index); } fn bufCursor(txt: *Text, screen_content: []u8, screen_index: usize) usize { return bufTextCursor(txt, screen_content, screen_index); } fn setTextCursor(pos: Position, page_y: usize, allocator: Allocator) void { term.setCursor(positionOnScreen(pos, page_y), allocator); } inline fn modifiedChar(text: *Text) []const u8 { return if (text.filename.len > 0 and text.modified and !enter_filename) "*" else ""; } inline fn filenameCursorPosition(text_cursor: Position) Position { return Position{ .x = math.digits(usize, text_cursor.y) + math.digits(usize, text_cursor.x) + input_filename_index + 4, .y = config.height - 1 }; } pub var message: []const u8 = "READY."; inline fn bufStatusBar(txt: *Text, screen_content: []u8, screen_index: usize) usize { var i = bufStatusBarMode(screen_content, screen_index); i = term.bufCursor(Position{ .x = 0, .y = config.height - 1}, screen_content, i); screen_content[i] = 'L'; i += 1; i = term.bufAttribute(Scope.foreground, themeHighlight, screen_content, i); const row = std.fmt.bufPrint(screen_content[i..], "{d}", .{txt.cursor.y + 1}) catch @panic(OOM); i += row.len; i = term.bufAttribute(Scope.foreground, themeForeground, screen_content, i); screen_content[i] = ':'; i += 1; screen_content[i] = 'C'; i += 1; i = term.bufAttribute(Scope.foreground, themeHighlight, screen_content, i); const col = std.fmt.bufPrint(screen_content[i..], "{d} ", .{txt.cursor.x + 1}) catch @panic(OOM); i += col.len; const filename = std.fmt.bufPrint(screen_content[i..], "{s}{s} ", .{txt.filename, modifiedChar(txt)}) catch @panic(OOM); i += filename.len; i = term.bufAttribute(Scope.foreground, themeWarn, screen_content, i); const msg = std.fmt.bufPrint(screen_content[i..], "{s}", .{message}) catch @panic(OOM); i += msg.len; const offset = config.width - keyCodeOffset; i = term.bufWriteRepeat(' ', offset - 3 - row.len - col.len - filename.len - msg.len, screen_content, i); i = term.bufAttribute(Scope.foreground, themeForeground, screen_content, i); i = term.bufWrite("key code: ", screen_content, i); return term.bufCursor(Position{ .x = offset, .y = config.height - 1}, screen_content, i); } test "endOfPageIndex" { var t = [_]u8{0} ** 5; var txt = Text.forTest("", &t); try expect(endOfPageIndex(&txt) == 0); txt.content = config.literalToArray("a", &t); txt.length = 1; try expect(endOfPageIndex(&txt) == 1); } inline fn textHeight() usize { return config.height - MENU_BAR_HEIGHT - STATUS_BAR_HEIGHT; } inline fn endOfPageIndex(txt: *Text) usize { return txt.indexOfRowEnd(txt.page_y + textHeight() - 1); } inline fn bufText(txt: *Text, screen_content: []u8, screen_index: usize) usize { assert(screen_content.len > screen_index); var i = term.bufWrite(term.CURSOR_SHOW, screen_content, screen_index); i = term.bufWrite(term.RESET_MODE, screen_content, i); const sop = txt.indexOfRowStart(txt.page_y); const eop = endOfPageIndex(txt); const page = txt.content[sop..eop]; return term.bufFillScreen(page, screen_content, i, config.width, textHeight()); } inline fn bufConf(conf: []const u8, screen_content: []u8, screen_index: usize) usize { assert(screen_content.len > screen_index); // var i = term.bufWrite(term.CURSOR_HIDE, screen_content, screen_index); var i = term.bufAttributeMode(term.Mode.reset, term.Scope.foreground, themeForeground, screen_content, screen_index); return term.bufFillScreen(conf, screen_content, i, config.width, textHeight()); } fn bufScreen(txt: *Text, screen_content: ?[]u8, key: KeyCode) void { if (screen_content != null) { var i = bufMenuBar(screen_content.?, 0); i = bufText(txt, screen_content.?, i); i = bufStatusBar(txt, screen_content.?, i); writeKeyCodes(txt, screen_content.?, i, key); } } fn writeKeyCodes(txt: *Text, screen_content: []u8, screen_index: usize, key: KeyCode) void { assert(screen_content.len > screen_index); var i = bufKeyCodes(key, Position{ .x = config.width - keyCodeOffset + 10, .y = config.height - 1}, screen_content, screen_index); if (enter_filename) { i = term.bufCursor(filenameCursorPosition(txt.cursor), screen_content, i); } else { i = bufTextCursor(txt, screen_content, i); } term.write(screen_content[0..i]); } fn shiftLeft(t: *Text, pos: Position) void { var i = t.indexOf(pos); while(i < t.length) : (i += 1) { t.content[i-1] = t.content[i]; } } fn shiftRight(t: *Text, pos: Position) void { var i = t.length; var ci = t.indexOf(pos); while(i > ci) : (i -= 1) { t.content[i] = t.content[i-1]; } } fn extendBuffer(t: *Text, allocator: Allocator) void { const length = math.multipleOf(config.chunk, t.content.len) + config.chunk; var new_content = allocator.alloc(u8, length) catch @panic(OOM); const i = t.cursorIndex(); if (i < t.content.len) { mem.copy(u8, new_content[0..i - 1], t.content[0..i - 1]); } allocator.free(t.content); t.content = new_content; } fn extendBufferIfNeeded(t: *Text, allocator: Allocator) void { if(t.content.len == 0 or t.cursorIndex() >= t.content.len) { extendBuffer(t, allocator); } } fn cursorLeft(txt: *Text, screen_content: ?[]u8, key: KeyCode) void { var t = txt; var update = false; if (t.cursor.x > 0) { t.cursor.x -= 1; t.last_x = t.cursor.x; update = true; } else { if (t.cursor.y > 0) { t.cursor.x = t.rowLength(t.cursor.y - 1) - 1; t.cursor.y -= 1; if (t.page_y > 0 and positionOnScreen(t.cursor, t.page_y).y == 0) { scrollDown(t); } update = true; } } if (update) { t.last_x = t.cursor.x; bufScreen(t, screen_content, key); } } test "cursorRight" { var t = [_]u8{0} ** 5; var txt = Text.forTest("", &t); const key = KeyCode{ .data = [_]u8{ 0x61, 0x00, 0x00, 0x00}, .len = 1}; try expect(txt.cursor.x == 0); try expect(txt.cursor.y == 0); cursorRight(&txt, null, key); try expect(txt.cursor.x == 0); try expect(txt.cursor.y == 0); txt.content = config.literalToArray("a", &t); txt.length = 1; cursorRight(&txt, null, key); try expect(txt.cursor.x == 1); try expect(txt.cursor.y == 0); txt.content = config.literalToArray("a\n", &t); txt.length = 2; txt.cursor.x = 1; txt.cursor.y = 0; try expect(txt.rowLength(0) == 2); cursorRight(&txt, null, key); try expect(txt.cursor.x == 0); try expect(txt.cursor.y == 1); } fn cursorRight(t: *Text, screen_content: ?[]u8, key: KeyCode) void { if (t.length == 0) return; if (t.cursor.x < t.rowLength(t.cursor.y)) { if (t.content[t.cursorIndex()] == NEW_LINE) { t.cursor.x = 0; t.cursor.y += 1; } else { t.cursor.x += 1; } const pos = positionOnScreen(t.cursor, t.page_y); t.last_x = pos.x; if (pos.y == config.height - MENU_BAR_HEIGHT) { scrollUp(t); } bufScreen(t, screen_content, key); } } fn newLine(t: *Text, screen_content: ?[]u8, key: KeyCode, allocator: Allocator) void { extendBufferIfNeeded(t, allocator); var i = t.cursorIndex(); if (i < t.length) shiftRight(t, t.cursor); t.content[i] = NEW_LINE; t.length += 1; cursorRight(t, screen_content, key); t.modified = true; bufScreen(t, screen_content, key); } test "writeChar" { const allocator = std.testing.allocator; var t = [_]u8{0} ** 5; var txt = Text.forTest("", &t); const key = KeyCode{ .data = [_]u8{ 0x61, 0x00, 0x00, 0x00}, .len = 1}; try expect(txt.cursor.x == 0); try expect(txt.cursor.y == 0); writeChar('a', &txt, null, key, allocator); try expect(txt.length == 1); try expect(txt.content[0] == 'a'); try expect(txt.cursor.x == 1); try expect(txt.cursor.y == 0); writeChar('b', &txt, null, key, allocator); try expect(txt.length == 2); try expect(txt.content[1] == 'b'); allocator.free(txt.content); } fn writeChar(char: u8, t: *Text, screen_content: ?[]u8, key: KeyCode, allocator: Allocator) void { extendBufferIfNeeded(t, allocator); const i = t.cursorIndex(); if (i < t.length) shiftRight(t, t.cursor); t.content[i] = char; t.modified = true; t.length += 1; cursorRight(t, screen_content, key); } fn backspace(t: *Text, screen_content: ?[]u8, key: KeyCode) void { if (t.cursorIndex() > 0) { if (t.cursor.x == 0) { const pos = t.cursor; cursorLeft(t, null, key); shiftLeft(t, pos); } else { shiftLeft(t, t.cursor); cursorLeft(t, null, key); } t.modified = true; t.length -= 1; bufScreen(t, screen_content, key); } } test "scrollDown" { var t = [_]u8{0} ** 5; var txt = Text.forTest("a\nb\nc", &t); txt.page_y = 1; scrollDown(&txt); try expect(txt.page_y == 0); } fn scrollDown(t: *Text) void { if (t.page_y > 0) { t.page_y -= 1; } } test "scrollUp" { var t = [_]u8{0} ** 5; var txt = Text.forTest("a\nb\nc", &t); scrollUp(&txt); try expect(txt.page_y == 1); } fn scrollUp(t: *Text) void { if (t.page_y < t.rows()) { t.page_y += 1; } } test "cursorUp" { var t = [_]u8{0} ** 4; var txt = Text.forTest("a\na\n", &t); txt.cursor = Position{.x=0, .y=2}; try expect(txt.cursorIndex() == 4); const key = KeyCode{ .data = [_]u8{ 0x1b, 0x5b, 0x41, 0x00}, .len = 3}; cursorUp(&txt, null, key); try expect(txt.cursorIndex() == 2); try expect(txt.cursor.x == 0); try expect(txt.cursor.y == 1); } fn cursorUp(t: *Text, screen_content: ?[]u8, key: KeyCode) void { _ = t.cursorIndex(); if (t.cursor.y > 0) { if (positionOnScreen(t.cursor, t.page_y).y == MENU_BAR_HEIGHT and t.page_y > 0) { scrollDown(t); } t.cursor.y -= 1; if(t.rowLength(t.cursor.y) - 1 < t.last_x) { t.cursor.x = t.rowLength(t.cursor.y) - 1; } else { t.cursor.x = t.last_x; } bufScreen(t, screen_content, key); } } fn cursorDown(t: *Text, screen_content: ?[]u8, key: KeyCode) void { if (t.cursor.y < t.rows()) { t.cursor.y += 1; const row_len = t.rowLength(t.cursor.y); if (row_len == 0) { t.cursor.x = 0; } else if (t.indexOf(Position{.x=t.last_x, .y=t.cursor.y}) == t.length) { t.cursor.x = row_len; } else if(row_len - 1 < t.last_x) { t.cursor.x = row_len - 1; } else { t.cursor.x = t.last_x; } if (positionOnScreen(t.cursor, t.page_y).y == config.height - MENU_BAR_HEIGHT and t.page_y < t.rows()) { scrollUp(t); } bufScreen(t, screen_content, key); } } const NOBR = "Failed: bufPrint"; fn bufKeyCodes(key: KeyCode, pos: Position, screen_content: []u8, screen_index: usize) usize { var i = bufStatusBarHighlightMode(screen_content, screen_index); i = term.bufCursor(pos, screen_content, i); i = term.bufWrite(" ", screen_content, i); i = term.bufAttribute(Scope.foreground, themeHighlight, screen_content, i); i = term.bufCursor(pos, screen_content, i); if(key.len == 0) { return i; } if(key.len == 1) { const written = std.fmt.bufPrint(screen_content[i..], "{x}", .{key.data[0]}) catch @panic(NOBR); i += written.len; } if(key.len == 2) { const written = std.fmt.bufPrint(screen_content[i..], "{x} {x}", .{key.data[0], key.data[1]}) catch @panic(NOBR); i += written.len; } if(key.len == 3) { const written = std.fmt.bufPrint(screen_content[i..], "{x} {x} {x}", .{key.data[0], key.data[1], key.data[2]}) catch @panic(NOBR); i += written.len; } if(key.len == 4) { const written = std.fmt.bufPrint(screen_content[i..], "{x} {x} {x} {x}", .{key.data[0], key.data[1], key.data[2], key.data[3]}) catch @panic(NOBR); i += written.len; } return term.bufWrite(term.RESET_MODE, screen_content, i); }
libs/edit.zig
const std = @import("std.zig"); const builtin = std.builtin; const io = std.io; const fs = std.fs; const mem = std.mem; const debug = std.debug; const panic = std.debug.panic; const assert = debug.assert; const warn = std.debug.warn; const ArrayList = std.ArrayList; const StringHashMap = std.StringHashMap; const Allocator = mem.Allocator; const process = std.process; const BufSet = std.BufSet; const BufMap = std.BufMap; const fmt_lib = std.fmt; const File = std.fs.File; const CrossTarget = std.zig.CrossTarget; pub const FmtStep = @import("build/fmt.zig").FmtStep; pub const TranslateCStep = @import("build/translate_c.zig").TranslateCStep; pub const WriteFileStep = @import("build/write_file.zig").WriteFileStep; pub const RunStep = @import("build/run.zig").RunStep; pub const CheckFileStep = @import("build/check_file.zig").CheckFileStep; pub const InstallRawStep = @import("build/emit_raw.zig").InstallRawStep; pub const Builder = struct { install_tls: TopLevelStep, uninstall_tls: TopLevelStep, allocator: *Allocator, user_input_options: UserInputOptionsMap, available_options_map: AvailableOptionsMap, available_options_list: ArrayList(AvailableOption), verbose: bool, verbose_tokenize: bool, verbose_ast: bool, verbose_link: bool, verbose_cc: bool, verbose_ir: bool, verbose_llvm_ir: bool, verbose_cimport: bool, verbose_llvm_cpu_features: bool, color: enum { auto, on, off } = .auto, invalid_user_input: bool, zig_exe: []const u8, default_step: *Step, env_map: *BufMap, top_level_steps: ArrayList(*TopLevelStep), install_prefix: ?[]const u8, dest_dir: ?[]const u8, lib_dir: []const u8, exe_dir: []const u8, h_dir: []const u8, install_path: []const u8, search_prefixes: ArrayList([]const u8), installed_files: ArrayList(InstalledFile), build_root: []const u8, cache_root: []const u8, global_cache_root: []const u8, release_mode: ?builtin.Mode, is_release: bool, override_lib_dir: ?[]const u8, vcpkg_root: VcpkgRoot, pkg_config_pkg_list: ?(PkgConfigError![]const PkgConfigPkg) = null, args: ?[][]const u8 = null, const PkgConfigError = error{ PkgConfigCrashed, PkgConfigFailed, PkgConfigNotInstalled, PkgConfigInvalidOutput, }; pub const PkgConfigPkg = struct { name: []const u8, desc: []const u8, }; pub const CStd = enum { C89, C99, C11, }; const UserInputOptionsMap = StringHashMap(UserInputOption); const AvailableOptionsMap = StringHashMap(AvailableOption); const AvailableOption = struct { name: []const u8, type_id: TypeId, description: []const u8, }; const UserInputOption = struct { name: []const u8, value: UserValue, used: bool, }; const UserValue = union(enum) { Flag: void, Scalar: []const u8, List: ArrayList([]const u8), }; const TypeId = enum { Bool, Int, Float, Enum, String, List, }; const TopLevelStep = struct { step: Step, description: []const u8, }; pub fn create( allocator: *Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8, global_cache_root: []const u8, ) !*Builder { const env_map = try allocator.create(BufMap); env_map.* = try process.getEnvMap(allocator); const self = try allocator.create(Builder); self.* = Builder{ .zig_exe = zig_exe, .build_root = build_root, .cache_root = try fs.path.relative(allocator, build_root, cache_root), .global_cache_root = global_cache_root, .verbose = false, .verbose_tokenize = false, .verbose_ast = false, .verbose_link = false, .verbose_cc = false, .verbose_ir = false, .verbose_llvm_ir = false, .verbose_cimport = false, .verbose_llvm_cpu_features = false, .invalid_user_input = false, .allocator = allocator, .user_input_options = UserInputOptionsMap.init(allocator), .available_options_map = AvailableOptionsMap.init(allocator), .available_options_list = ArrayList(AvailableOption).init(allocator), .top_level_steps = ArrayList(*TopLevelStep).init(allocator), .default_step = undefined, .env_map = env_map, .search_prefixes = ArrayList([]const u8).init(allocator), .install_prefix = null, .lib_dir = undefined, .exe_dir = undefined, .h_dir = undefined, .dest_dir = env_map.get("DESTDIR"), .installed_files = ArrayList(InstalledFile).init(allocator), .install_tls = TopLevelStep{ .step = Step.initNoOp(.TopLevel, "install", allocator), .description = "Copy build artifacts to prefix path", }, .uninstall_tls = TopLevelStep{ .step = Step.init(.TopLevel, "uninstall", allocator, makeUninstall), .description = "Remove build artifacts from prefix path", }, .release_mode = null, .is_release = false, .override_lib_dir = null, .install_path = undefined, .vcpkg_root = VcpkgRoot{ .Unattempted = {} }, .args = null, }; try self.top_level_steps.append(&self.install_tls); try self.top_level_steps.append(&self.uninstall_tls); self.default_step = &self.install_tls.step; return self; } pub fn destroy(self: *Builder) void { self.env_map.deinit(); self.top_level_steps.deinit(); self.allocator.destroy(self); } /// This function is intended to be called by std/special/build_runner.zig, not a build.zig file. pub fn setInstallPrefix(self: *Builder, optional_prefix: ?[]const u8) void { self.install_prefix = optional_prefix; } /// This function is intended to be called by std/special/build_runner.zig, not a build.zig file. pub fn resolveInstallPrefix(self: *Builder) void { if (self.dest_dir) |dest_dir| { const install_prefix = self.install_prefix orelse "/usr"; self.install_path = fs.path.join(self.allocator, &[_][]const u8{ dest_dir, install_prefix }) catch unreachable; } else { const install_prefix = self.install_prefix orelse blk: { const p = self.cache_root; self.install_prefix = p; break :blk p; }; self.install_path = install_prefix; } self.lib_dir = fs.path.join(self.allocator, &[_][]const u8{ self.install_path, "lib" }) catch unreachable; self.exe_dir = fs.path.join(self.allocator, &[_][]const u8{ self.install_path, "bin" }) catch unreachable; self.h_dir = fs.path.join(self.allocator, &[_][]const u8{ self.install_path, "include" }) catch unreachable; } pub fn addExecutable(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { return LibExeObjStep.createExecutable( self, name, if (root_src) |p| FileSource{ .path = p } else null, false, ); } pub fn addExecutableFromWriteFileStep( self: *Builder, name: []const u8, wfs: *WriteFileStep, basename: []const u8, ) *LibExeObjStep { return LibExeObjStep.createExecutable(self, name, @as(FileSource, .{ .write_file = .{ .step = wfs, .basename = basename, }, }), false); } pub fn addExecutableSource( self: *Builder, name: []const u8, root_src: ?FileSource, ) *LibExeObjStep { return LibExeObjStep.createExecutable(self, name, root_src, false); } pub fn addObject(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { const root_src_param = if (root_src) |p| @as(FileSource, .{ .path = p }) else null; return LibExeObjStep.createObject(self, name, root_src_param); } pub fn addObjectFromWriteFileStep( self: *Builder, name: []const u8, wfs: *WriteFileStep, basename: []const u8, ) *LibExeObjStep { return LibExeObjStep.createObject(self, name, @as(FileSource, .{ .write_file = .{ .step = wfs, .basename = basename, }, })); } pub fn addSharedLibrary( self: *Builder, name: []const u8, root_src: ?[]const u8, kind: LibExeObjStep.SharedLibKind, ) *LibExeObjStep { const root_src_param = if (root_src) |p| @as(FileSource, .{ .path = p }) else null; return LibExeObjStep.createSharedLibrary(self, name, root_src_param, kind); } pub fn addStaticLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { const root_src_param = if (root_src) |p| @as(FileSource, .{ .path = p }) else null; return LibExeObjStep.createStaticLibrary(self, name, root_src_param); } pub fn addTest(self: *Builder, root_src: []const u8) *LibExeObjStep { return LibExeObjStep.createTest(self, "test", .{ .path = root_src }); } pub fn addAssemble(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep { const obj_step = LibExeObjStep.createObject(self, name, null); obj_step.addAssemblyFile(src); return obj_step; } /// Initializes a RunStep with argv, which must at least have the path to the /// executable. More command line arguments can be added with `addArg`, /// `addArgs`, and `addArtifactArg`. /// Be careful using this function, as it introduces a system dependency. /// To run an executable built with zig build, see `LibExeObjStep.run`. pub fn addSystemCommand(self: *Builder, argv: []const []const u8) *RunStep { assert(argv.len >= 1); const run_step = RunStep.create(self, self.fmt("run {}", .{argv[0]})); run_step.addArgs(argv); return run_step; } pub fn dupe(self: *Builder, bytes: []const u8) []u8 { return self.allocator.dupe(u8, bytes) catch unreachable; } pub fn dupePath(self: *Builder, bytes: []const u8) []u8 { const the_copy = self.dupe(bytes); for (the_copy) |*byte| { switch (byte.*) { '/', '\\' => byte.* = fs.path.sep, else => {}, } } return the_copy; } pub fn dupePkg(self: *Builder, package: Pkg) Pkg { var the_copy = Pkg{ .name = self.dupe(package.name), .path = self.dupePath(package.path), }; if (package.dependencies) |dependencies| { const new_dependencies = self.allocator.alloc(Pkg, dependencies.len) catch unreachable; the_copy.dependencies = new_dependencies; for (dependencies) |dep_package, i| { new_dependencies[i] = self.dupePkg(dep_package); } } return the_copy; } pub fn addWriteFile(self: *Builder, file_path: []const u8, data: []const u8) *WriteFileStep { const write_file_step = self.addWriteFiles(); write_file_step.add(file_path, data); return write_file_step; } pub fn addWriteFiles(self: *Builder) *WriteFileStep { const write_file_step = self.allocator.create(WriteFileStep) catch unreachable; write_file_step.* = WriteFileStep.init(self); return write_file_step; } pub fn addLog(self: *Builder, comptime format: []const u8, args: anytype) *LogStep { const data = self.fmt(format, args); const log_step = self.allocator.create(LogStep) catch unreachable; log_step.* = LogStep.init(self, data); return log_step; } pub fn addRemoveDirTree(self: *Builder, dir_path: []const u8) *RemoveDirStep { const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable; remove_dir_step.* = RemoveDirStep.init(self, dir_path); return remove_dir_step; } pub fn addFmt(self: *Builder, paths: []const []const u8) *FmtStep { return FmtStep.create(self, paths); } pub fn addTranslateC(self: *Builder, source: FileSource) *TranslateCStep { return TranslateCStep.create(self, source); } pub fn version(self: *const Builder, major: u32, minor: u32, patch: u32) LibExeObjStep.SharedLibKind { return .{ .versioned = .{ .major = major, .minor = minor, .patch = patch, }, }; } pub fn make(self: *Builder, step_names: []const []const u8) !void { try self.makePath(self.cache_root); var wanted_steps = ArrayList(*Step).init(self.allocator); defer wanted_steps.deinit(); if (step_names.len == 0) { try wanted_steps.append(self.default_step); } else { for (step_names) |step_name| { const s = try self.getTopLevelStepByName(step_name); try wanted_steps.append(s); } } for (wanted_steps.items) |s| { try self.makeOneStep(s); } } pub fn getInstallStep(self: *Builder) *Step { return &self.install_tls.step; } pub fn getUninstallStep(self: *Builder) *Step { return &self.uninstall_tls.step; } fn makeUninstall(uninstall_step: *Step) anyerror!void { const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step); const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls); for (self.installed_files.items) |installed_file| { const full_path = self.getInstallPath(installed_file.dir, installed_file.path); if (self.verbose) { warn("rm {}\n", .{full_path}); } fs.cwd().deleteTree(full_path) catch {}; } // TODO remove empty directories } fn makeOneStep(self: *Builder, s: *Step) anyerror!void { if (s.loop_flag) { warn("Dependency loop detected:\n {}\n", .{s.name}); return error.DependencyLoopDetected; } s.loop_flag = true; for (s.dependencies.items) |dep| { self.makeOneStep(dep) catch |err| { if (err == error.DependencyLoopDetected) { warn(" {}\n", .{s.name}); } return err; }; } s.loop_flag = false; try s.make(); } fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step { for (self.top_level_steps.items) |top_level_step| { if (mem.eql(u8, top_level_step.step.name, name)) { return &top_level_step.step; } } warn("Cannot run step '{}' because it does not exist\n", .{name}); return error.InvalidStepName; } pub fn option(self: *Builder, comptime T: type, name: []const u8, description: []const u8) ?T { const type_id = comptime typeToEnum(T); const available_option = AvailableOption{ .name = name, .type_id = type_id, .description = description, }; if ((self.available_options_map.fetchPut(name, available_option) catch unreachable) != null) { panic("Option '{}' declared twice", .{name}); } self.available_options_list.append(available_option) catch unreachable; const entry = self.user_input_options.getEntry(name) orelse return null; entry.value.used = true; switch (type_id) { .Bool => switch (entry.value.value) { .Flag => return true, .Scalar => |s| { if (mem.eql(u8, s, "true")) { return true; } else if (mem.eql(u8, s, "false")) { return false; } else { warn("Expected -D{} to be a boolean, but received '{}'\n", .{ name, s }); self.markInvalidUserInput(); return null; } }, .List => { warn("Expected -D{} to be a boolean, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Int => switch (entry.value.value) { .Flag => { warn("Expected -D{} to be an integer, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { const n = std.fmt.parseInt(T, s, 10) catch |err| switch (err) { error.Overflow => { warn("-D{} value {} cannot fit into type {}.\n", .{ name, s, @typeName(T) }); self.markInvalidUserInput(); return null; }, else => { warn("Expected -D{} to be an integer of type {}.\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; }, }; return n; }, .List => { warn("Expected -D{} to be an integer, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Float => switch (entry.value.value) { .Flag => { warn("Expected -D{} to be a float, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { const n = std.fmt.parseFloat(T, s) catch |err| { warn("Expected -D{} to be a float of type {}.\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; }; return n; }, .List => { warn("Expected -D{} to be a float, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Enum => switch (entry.value.value) { .Flag => { warn("Expected -D{} to be a string, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { if (std.meta.stringToEnum(T, s)) |enum_lit| { return enum_lit; } else { warn("Expected -D{} to be of type {}.\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; } }, .List => { warn("Expected -D{} to be a string, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, }, .String => switch (entry.value.value) { .Flag => { warn("Expected -D{} to be a string, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, .List => { warn("Expected -D{} to be a string, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| return s, }, .List => switch (entry.value.value) { .Flag => { warn("Expected -D{} to be a list, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { return self.allocator.dupe([]const u8, &[_][]const u8{s}) catch unreachable; }, .List => |lst| return lst.items, }, } } pub fn step(self: *Builder, name: []const u8, description: []const u8) *Step { const step_info = self.allocator.create(TopLevelStep) catch unreachable; step_info.* = TopLevelStep{ .step = Step.initNoOp(.TopLevel, name, self.allocator), .description = description, }; self.top_level_steps.append(step_info) catch unreachable; return &step_info.step; } /// This provides the -Drelease option to the build user and does not give them the choice. pub fn setPreferredReleaseMode(self: *Builder, mode: builtin.Mode) void { if (self.release_mode != null) { @panic("setPreferredReleaseMode must be called before standardReleaseOptions and may not be called twice"); } const description = self.fmt("Create a release build ({})", .{@tagName(mode)}); self.is_release = self.option(bool, "release", description) orelse false; self.release_mode = if (self.is_release) mode else builtin.Mode.Debug; } /// If you call this without first calling `setPreferredReleaseMode` then it gives the build user /// the choice of what kind of release. pub fn standardReleaseOptions(self: *Builder) builtin.Mode { if (self.release_mode) |mode| return mode; const release_safe = self.option(bool, "release-safe", "Optimizations on and safety on") orelse false; const release_fast = self.option(bool, "release-fast", "Optimizations on and safety off") orelse false; const release_small = self.option(bool, "release-small", "Size optimizations on and safety off") orelse false; const mode = if (release_safe and !release_fast and !release_small) builtin.Mode.ReleaseSafe else if (release_fast and !release_safe and !release_small) builtin.Mode.ReleaseFast else if (release_small and !release_fast and !release_safe) builtin.Mode.ReleaseSmall else if (!release_fast and !release_safe and !release_small) builtin.Mode.Debug else x: { warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)", .{}); self.markInvalidUserInput(); break :x builtin.Mode.Debug; }; self.is_release = mode != .Debug; self.release_mode = mode; return mode; } pub const StandardTargetOptionsArgs = struct { whitelist: ?[]const CrossTarget = null, default_target: CrossTarget = CrossTarget{}, }; /// Exposes standard `zig build` options for choosing a target. pub fn standardTargetOptions(self: *Builder, args: StandardTargetOptionsArgs) CrossTarget { const triple = self.option( []const u8, "target", "The CPU architecture, OS, and ABI to build for", ) orelse return args.default_target; // TODO add cpu and features as part of the target triple var diags: CrossTarget.ParseOptions.Diagnostics = .{}; const selected_target = CrossTarget.parse(.{ .arch_os_abi = triple, .diagnostics = &diags, }) catch |err| switch (err) { error.UnknownCpuModel => { std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{ diags.cpu_name.?, @tagName(diags.arch.?), }); for (diags.arch.?.allCpuModels()) |cpu| { std.debug.warn(" {}\n", .{cpu.name}); } process.exit(1); }, error.UnknownCpuFeature => { std.debug.warn( \\Unknown CPU feature: '{}' \\Available CPU features for architecture '{}': \\ , .{ diags.unknown_feature_name, @tagName(diags.arch.?), }); for (diags.arch.?.allFeaturesList()) |feature| { std.debug.warn(" {}: {}\n", .{ feature.name, feature.description }); } process.exit(1); }, error.UnknownOperatingSystem => { std.debug.warn( \\Unknown OS: '{}' \\Available operating systems: \\ , .{diags.os_name}); inline for (std.meta.fields(std.Target.Os.Tag)) |field| { std.debug.warn(" {}\n", .{field.name}); } process.exit(1); }, else => |e| { std.debug.warn("Unable to parse target '{}': {}\n", .{ triple, @errorName(e) }); process.exit(1); }, }; const selected_canonicalized_triple = selected_target.zigTriple(self.allocator) catch unreachable; if (args.whitelist) |list| whitelist_check: { // Make sure it's a match of one of the list. for (list) |t| { const t_triple = t.zigTriple(self.allocator) catch unreachable; if (mem.eql(u8, t_triple, selected_canonicalized_triple)) { break :whitelist_check; } } std.debug.warn("Chosen target '{}' does not match one of the supported targets:\n", .{ selected_canonicalized_triple, }); for (list) |t| { const t_triple = t.zigTriple(self.allocator) catch unreachable; std.debug.warn(" {}\n", .{t_triple}); } // TODO instead of process exit, return error and have a zig build flag implemented by // the build runner that turns process exits into error return traces process.exit(1); } return selected_target; } pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) !bool { const gop = try self.user_input_options.getOrPut(name); if (!gop.found_existing) { gop.entry.value = UserInputOption{ .name = name, .value = UserValue{ .Scalar = value }, .used = false, }; return false; } // option already exists switch (gop.entry.value.value) { UserValue.Scalar => |s| { // turn it into a list var list = ArrayList([]const u8).init(self.allocator); list.append(s) catch unreachable; list.append(value) catch unreachable; _ = self.user_input_options.put(name, UserInputOption{ .name = name, .value = UserValue{ .List = list }, .used = false, }) catch unreachable; }, UserValue.List => |*list| { // append to the list list.append(value) catch unreachable; _ = self.user_input_options.put(name, UserInputOption{ .name = name, .value = UserValue{ .List = list.* }, .used = false, }) catch unreachable; }, UserValue.Flag => { warn("Option '-D{}={}' conflicts with flag '-D{}'.\n", .{ name, value, name }); return true; }, } return false; } pub fn addUserInputFlag(self: *Builder, name: []const u8) !bool { const gop = try self.user_input_options.getOrPut(name); if (!gop.found_existing) { gop.entry.value = UserInputOption{ .name = name, .value = UserValue{ .Flag = {} }, .used = false, }; return false; } // option already exists switch (gop.entry.value.value) { UserValue.Scalar => |s| { warn("Flag '-D{}' conflicts with option '-D{}={}'.\n", .{ name, name, s }); return true; }, UserValue.List => { warn("Flag '-D{}' conflicts with multiple options of the same name.\n", .{name}); return true; }, UserValue.Flag => {}, } return false; } fn typeToEnum(comptime T: type) TypeId { return switch (@typeInfo(T)) { .Int => .Int, .Float => .Float, .Bool => .Bool, .Enum => .Enum, else => switch (T) { []const u8 => .String, []const []const u8 => .List, else => @compileError("Unsupported type: " ++ @typeName(T)), }, }; } fn markInvalidUserInput(self: *Builder) void { self.invalid_user_input = true; } pub fn typeIdName(id: TypeId) []const u8 { return switch (id) { .Bool => "bool", .Int => "int", .Float => "float", .Enum => "enum", .String => "string", .List => "list", }; } pub fn validateUserInputDidItFail(self: *Builder) bool { // make sure all args are used var it = self.user_input_options.iterator(); while (true) { const entry = it.next() orelse break; if (!entry.value.used) { warn("Invalid option: -D{}\n\n", .{entry.key}); self.markInvalidUserInput(); } } return self.invalid_user_input; } pub fn spawnChild(self: *Builder, argv: []const []const u8) !void { return self.spawnChildEnvMap(null, self.env_map, argv); } fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void { if (cwd) |yes_cwd| warn("cd {} && ", .{yes_cwd}); for (argv) |arg| { warn("{} ", .{arg}); } warn("\n", .{}); } fn spawnChildEnvMap(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) !void { if (self.verbose) { printCmd(cwd, argv); } const child = std.ChildProcess.init(argv, self.allocator) catch unreachable; defer child.deinit(); child.cwd = cwd; child.env_map = env_map; const term = child.spawnAndWait() catch |err| { warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) }); return err; }; switch (term) { .Exited => |code| { if (code != 0) { warn("The following command exited with error code {}:\n", .{code}); printCmd(cwd, argv); return error.UncleanExit; } }, else => { warn("The following command terminated unexpectedly:\n", .{}); printCmd(cwd, argv); return error.UncleanExit; }, } } pub fn makePath(self: *Builder, path: []const u8) !void { fs.cwd().makePath(self.pathFromRoot(path)) catch |err| { warn("Unable to create path {}: {}\n", .{ path, @errorName(err) }); return err; }; } pub fn installArtifact(self: *Builder, artifact: *LibExeObjStep) void { self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step); } pub fn addInstallArtifact(self: *Builder, artifact: *LibExeObjStep) *InstallArtifactStep { return InstallArtifactStep.create(self, artifact); } ///`dest_rel_path` is relative to prefix path pub fn installFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void { self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Prefix, dest_rel_path).step); } pub fn installDirectory(self: *Builder, options: InstallDirectoryOptions) void { self.getInstallStep().dependOn(&self.addInstallDirectory(options).step); } ///`dest_rel_path` is relative to bin path pub fn installBinFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void { self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Bin, dest_rel_path).step); } ///`dest_rel_path` is relative to lib path pub fn installLibFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void { self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Lib, dest_rel_path).step); } pub fn installRaw(self: *Builder, artifact: *LibExeObjStep, dest_filename: []const u8) void { self.getInstallStep().dependOn(&self.addInstallRaw(artifact, dest_filename).step); } ///`dest_rel_path` is relative to install prefix path pub fn addInstallFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep { return self.addInstallFileWithDir(src_path, .Prefix, dest_rel_path); } ///`dest_rel_path` is relative to bin path pub fn addInstallBinFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep { return self.addInstallFileWithDir(src_path, .Bin, dest_rel_path); } ///`dest_rel_path` is relative to lib path pub fn addInstallLibFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep { return self.addInstallFileWithDir(src_path, .Lib, dest_rel_path); } pub fn addInstallRaw(self: *Builder, artifact: *LibExeObjStep, dest_filename: []const u8) *InstallRawStep { return InstallRawStep.create(self, artifact, dest_filename); } pub fn addInstallFileWithDir( self: *Builder, src_path: []const u8, install_dir: InstallDir, dest_rel_path: []const u8, ) *InstallFileStep { if (dest_rel_path.len == 0) { panic("dest_rel_path must be non-empty", .{}); } const install_step = self.allocator.create(InstallFileStep) catch unreachable; install_step.* = InstallFileStep.init(self, src_path, install_dir, dest_rel_path); return install_step; } pub fn addInstallDirectory(self: *Builder, options: InstallDirectoryOptions) *InstallDirStep { const install_step = self.allocator.create(InstallDirStep) catch unreachable; install_step.* = InstallDirStep.init(self, options); return install_step; } pub fn pushInstalledFile(self: *Builder, dir: InstallDir, dest_rel_path: []const u8) void { self.installed_files.append(InstalledFile{ .dir = dir, .path = dest_rel_path, }) catch unreachable; } pub fn updateFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void { if (self.verbose) { warn("cp {} {} ", .{ source_path, dest_path }); } const cwd = fs.cwd(); const prev_status = try fs.Dir.updateFile(cwd, source_path, cwd, dest_path, .{}); if (self.verbose) switch (prev_status) { .stale => warn("# installed\n", .{}), .fresh => warn("# up-to-date\n", .{}), }; } pub fn pathFromRoot(self: *Builder, rel_path: []const u8) []u8 { return fs.path.resolve(self.allocator, &[_][]const u8{ self.build_root, rel_path }) catch unreachable; } pub fn fmt(self: *Builder, comptime format: []const u8, args: anytype) []u8 { return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable; } pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { // TODO report error for ambiguous situations const exe_extension = @as(CrossTarget, .{}).exeFileExt(); for (self.search_prefixes.items) |search_prefix| { for (names) |name| { if (fs.path.isAbsolute(name)) { return name; } const full_path = try fs.path.join(self.allocator, &[_][]const u8{ search_prefix, "bin", self.fmt("{}{}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } if (self.env_map.get("PATH")) |PATH| { for (names) |name| { if (fs.path.isAbsolute(name)) { return name; } var it = mem.tokenize(PATH, &[_]u8{fs.path.delimiter}); while (it.next()) |path| { const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, self.fmt("{}{}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } } for (names) |name| { if (fs.path.isAbsolute(name)) { return name; } for (paths) |path| { const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, self.fmt("{}{}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } return error.FileNotFound; } pub fn execAllowFail( self: *Builder, argv: []const []const u8, out_code: *u8, stderr_behavior: std.ChildProcess.StdIo, ) ![]u8 { assert(argv.len != 0); const max_output_size = 400 * 1024; const child = try std.ChildProcess.init(argv, self.allocator); defer child.deinit(); child.stdin_behavior = .Ignore; child.stdout_behavior = .Pipe; child.stderr_behavior = stderr_behavior; try child.spawn(); const stdout = try child.stdout.?.inStream().readAllAlloc(self.allocator, max_output_size); errdefer self.allocator.free(stdout); const term = try child.wait(); switch (term) { .Exited => |code| { if (code != 0) { out_code.* = @truncate(u8, code); return error.ExitCodeFailure; } return stdout; }, .Signal, .Stopped, .Unknown => |code| { out_code.* = @truncate(u8, code); return error.ProcessTerminated; }, } } pub fn execFromStep(self: *Builder, argv: []const []const u8, src_step: ?*Step) ![]u8 { assert(argv.len != 0); if (self.verbose) { printCmd(null, argv); } var code: u8 = undefined; return self.execAllowFail(argv, &code, .Inherit) catch |err| switch (err) { error.FileNotFound => { if (src_step) |s| warn("{}...", .{s.name}); warn("Unable to spawn the following command: file not found\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ExitCodeFailure => { if (src_step) |s| warn("{}...", .{s.name}); warn("The following command exited with error code {}:\n", .{code}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ProcessTerminated => { if (src_step) |s| warn("{}...", .{s.name}); warn("The following command terminated unexpectedly:\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, else => |e| return e, }; } pub fn exec(self: *Builder, argv: []const []const u8) ![]u8 { return self.execFromStep(argv, null); } pub fn addSearchPrefix(self: *Builder, search_prefix: []const u8) void { self.search_prefixes.append(search_prefix) catch unreachable; } pub fn getInstallPath(self: *Builder, dir: InstallDir, dest_rel_path: []const u8) []const u8 { const base_dir = switch (dir) { .Prefix => self.install_path, .Bin => self.exe_dir, .Lib => self.lib_dir, .Header => self.h_dir, .Custom => |path| fs.path.join(self.allocator, &[_][]const u8{ self.install_path, path }) catch unreachable, }; return fs.path.resolve( self.allocator, &[_][]const u8{ base_dir, dest_rel_path }, ) catch unreachable; } fn execPkgConfigList(self: *Builder, out_code: *u8) ![]const PkgConfigPkg { const stdout = try self.execAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore); var list = ArrayList(PkgConfigPkg).init(self.allocator); var line_it = mem.tokenize(stdout, "\r\n"); while (line_it.next()) |line| { if (mem.trim(u8, line, " \t").len == 0) continue; var tok_it = mem.tokenize(line, " \t"); try list.append(PkgConfigPkg{ .name = tok_it.next() orelse return error.PkgConfigInvalidOutput, .desc = tok_it.rest(), }); } return list.items; } fn getPkgConfigList(self: *Builder) ![]const PkgConfigPkg { if (self.pkg_config_pkg_list) |res| { return res; } var code: u8 = undefined; if (self.execPkgConfigList(&code)) |list| { self.pkg_config_pkg_list = list; return list; } else |err| { const result = switch (err) { error.ProcessTerminated => error.PkgConfigCrashed, error.ExitCodeFailure => error.PkgConfigFailed, error.FileNotFound => error.PkgConfigNotInstalled, error.InvalidName => error.PkgConfigNotInstalled, error.PkgConfigInvalidOutput => error.PkgConfigInvalidOutput, else => return err, }; self.pkg_config_pkg_list = result; return result; } } }; test "builder.findProgram compiles" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const builder = try Builder.create( &arena.allocator, "zig", "zig-cache", "zig-cache", "zig-cache", ); defer builder.destroy(); _ = builder.findProgram(&[_][]const u8{}, &[_][]const u8{}) catch null; } /// Deprecated. Use `std.builtin.Version`. pub const Version = builtin.Version; /// Deprecated. Use `std.zig.CrossTarget`. pub const Target = std.zig.CrossTarget; pub const Pkg = struct { name: []const u8, path: []const u8, dependencies: ?[]const Pkg = null, }; const CSourceFile = struct { source: FileSource, args: []const []const u8, }; const CSourceFiles = struct { files: []const []const u8, flags: []const []const u8, }; fn isLibCLibrary(name: []const u8) bool { const libc_libraries = [_][]const u8{ "c", "m", "dl", "rt", "pthread" }; for (libc_libraries) |libc_lib_name| { if (mem.eql(u8, name, libc_lib_name)) return true; } return false; } pub const FileSource = union(enum) { /// Relative to build root path: []const u8, write_file: struct { step: *WriteFileStep, basename: []const u8, }, translate_c: *TranslateCStep, pub fn addStepDependencies(self: FileSource, step: *Step) void { switch (self) { .path => {}, .write_file => |wf| step.dependOn(&wf.step.step), .translate_c => |tc| step.dependOn(&tc.step), } } /// Should only be called during make() pub fn getPath(self: FileSource, builder: *Builder) []const u8 { return switch (self) { .path => |p| builder.pathFromRoot(p), .write_file => |wf| wf.step.getOutputPath(wf.basename), .translate_c => |tc| tc.getOutputPath(), }; } }; const BuildOptionArtifactArg = struct { name: []const u8, artifact: *LibExeObjStep, }; pub const LibExeObjStep = struct { step: Step, builder: *Builder, name: []const u8, target: CrossTarget = CrossTarget{}, linker_script: ?[]const u8 = null, version_script: ?[]const u8 = null, out_filename: []const u8, is_dynamic: bool, version: ?Version, build_mode: builtin.Mode, kind: Kind, major_only_filename: []const u8, name_only_filename: []const u8, strip: bool, lib_paths: ArrayList([]const u8), framework_dirs: ArrayList([]const u8), frameworks: BufSet, verbose_link: bool, verbose_cc: bool, emit_llvm_ir: bool = false, emit_asm: bool = false, emit_bin: bool = true, emit_docs: bool = false, emit_h: bool = false, bundle_compiler_rt: ?bool = null, disable_stack_probing: bool, disable_sanitize_c: bool, rdynamic: bool, c_std: Builder.CStd, override_lib_dir: ?[]const u8, main_pkg_path: ?[]const u8, exec_cmd_args: ?[]const ?[]const u8, name_prefix: []const u8, filter: ?[]const u8, single_threaded: bool, test_evented_io: bool = false, code_model: builtin.CodeModel = .default, root_src: ?FileSource, out_h_filename: []const u8, out_lib_filename: []const u8, out_pdb_filename: []const u8, packages: ArrayList(Pkg), build_options_contents: std.ArrayList(u8), build_options_artifact_args: std.ArrayList(BuildOptionArtifactArg), object_src: []const u8, link_objects: ArrayList(LinkObject), include_dirs: ArrayList(IncludeDir), c_macros: ArrayList([]const u8), output_dir: ?[]const u8, is_linking_libc: bool = false, vcpkg_bin_path: ?[]const u8 = null, /// This may be set in order to override the default install directory override_dest_dir: ?InstallDir, installed_path: ?[]const u8, install_step: ?*InstallArtifactStep, /// Base address for an executable image. image_base: ?u64 = null, libc_file: ?[]const u8 = null, valgrind_support: ?bool = null, /// Create a .eh_frame_hdr section and a PT_GNU_EH_FRAME segment in the ELF /// file. link_eh_frame_hdr: bool = false, link_emit_relocs: bool = false, /// Place every function in its own section so that unused ones may be /// safely garbage-collected during the linking phase. link_function_sections: bool = false, /// Uses system Wine installation to run cross compiled Windows build artifacts. enable_wine: bool = false, /// Uses system QEMU installation to run cross compiled foreign architecture build artifacts. enable_qemu: bool = false, /// Uses system Wasmtime installation to run cross compiled wasm/wasi build artifacts. enable_wasmtime: bool = false, /// After following the steps in https://github.com/ziglang/zig/wiki/Updating-libc#glibc, /// this will be the directory $glibc-build-dir/install/glibcs /// Given the example of the aarch64 target, this is the directory /// that contains the path `aarch64-linux-gnu/lib/ld-linux-aarch64.so.1`. glibc_multi_install_dir: ?[]const u8 = null, /// Position Independent Code force_pic: ?bool = null, /// Position Independent Executable pie: ?bool = null, subsystem: ?builtin.SubSystem = null, /// Overrides the default stack size stack_size: ?u64 = null, const LinkObject = union(enum) { StaticPath: []const u8, OtherStep: *LibExeObjStep, SystemLib: []const u8, AssemblyFile: FileSource, CSourceFile: *CSourceFile, CSourceFiles: *CSourceFiles, }; const IncludeDir = union(enum) { RawPath: []const u8, RawPathSystem: []const u8, OtherStep: *LibExeObjStep, }; const Kind = enum { Exe, Lib, Obj, Test, }; const SharedLibKind = union(enum) { versioned: Version, unversioned: void, }; pub fn createSharedLibrary(builder: *Builder, name: []const u8, root_src: ?FileSource, kind: SharedLibKind) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, switch (kind) { .versioned => |ver| ver, .unversioned => null, }); return self; } pub fn createStaticLibrary(builder: *Builder, name: []const u8, root_src: ?FileSource) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, null); return self; } pub fn createObject(builder: *Builder, name: []const u8, root_src: ?FileSource) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, null); return self; } pub fn createExecutable(builder: *Builder, name: []const u8, root_src: ?FileSource, is_dynamic: bool) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Exe, is_dynamic, null); return self; } pub fn createTest(builder: *Builder, name: []const u8, root_src: FileSource) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Test, false, null); return self; } fn initExtraArgs( builder: *Builder, name: []const u8, root_src: ?FileSource, kind: Kind, is_dynamic: bool, ver: ?Version, ) LibExeObjStep { if (mem.indexOf(u8, name, "/") != null or mem.indexOf(u8, name, "\\") != null) { panic("invalid name: '{}'. It looks like a file path, but it is supposed to be the library or application name.", .{name}); } var self = LibExeObjStep{ .strip = false, .builder = builder, .verbose_link = false, .verbose_cc = false, .build_mode = builtin.Mode.Debug, .is_dynamic = is_dynamic, .kind = kind, .root_src = root_src, .name = name, .frameworks = BufSet.init(builder.allocator), .step = Step.init(.LibExeObj, name, builder.allocator, make), .version = ver, .out_filename = undefined, .out_h_filename = builder.fmt("{}.h", .{name}), .out_lib_filename = undefined, .out_pdb_filename = builder.fmt("{}.pdb", .{name}), .major_only_filename = undefined, .name_only_filename = undefined, .packages = ArrayList(Pkg).init(builder.allocator), .include_dirs = ArrayList(IncludeDir).init(builder.allocator), .link_objects = ArrayList(LinkObject).init(builder.allocator), .c_macros = ArrayList([]const u8).init(builder.allocator), .lib_paths = ArrayList([]const u8).init(builder.allocator), .framework_dirs = ArrayList([]const u8).init(builder.allocator), .object_src = undefined, .build_options_contents = std.ArrayList(u8).init(builder.allocator), .build_options_artifact_args = std.ArrayList(BuildOptionArtifactArg).init(builder.allocator), .c_std = Builder.CStd.C99, .override_lib_dir = null, .main_pkg_path = null, .exec_cmd_args = null, .name_prefix = "", .filter = null, .disable_stack_probing = false, .disable_sanitize_c = false, .rdynamic = false, .output_dir = null, .single_threaded = false, .override_dest_dir = null, .installed_path = null, .install_step = null, }; self.computeOutFileNames(); if (root_src) |rs| rs.addStepDependencies(&self.step); return self; } fn computeOutFileNames(self: *LibExeObjStep) void { const target_info = std.zig.system.NativeTargetInfo.detect( self.builder.allocator, self.target, ) catch unreachable; const target = target_info.target; self.out_filename = std.zig.binNameAlloc(self.builder.allocator, .{ .root_name = self.name, .target = target, .output_mode = switch (self.kind) { .Lib => .Lib, .Obj => .Obj, .Exe, .Test => .Exe, }, .link_mode = if (self.is_dynamic) .Dynamic else .Static, .version = self.version, }) catch unreachable; if (self.kind == .Lib) { if (!self.is_dynamic) { self.out_lib_filename = self.out_filename; } else if (self.version) |version| { if (target.isDarwin()) { self.major_only_filename = self.builder.fmt("lib{s}.{d}.dylib", .{ self.name, version.major, }); self.name_only_filename = self.builder.fmt("lib{s}.dylib", .{self.name}); self.out_lib_filename = self.out_filename; } else if (target.os.tag == .windows) { self.out_lib_filename = self.builder.fmt("{s}.lib", .{self.name}); } else { self.major_only_filename = self.builder.fmt("lib{s}.so.{d}", .{ self.name, version.major }); self.name_only_filename = self.builder.fmt("lib{s}.so", .{self.name}); self.out_lib_filename = self.out_filename; } } else { if (target.isDarwin()) { self.out_lib_filename = self.out_filename; } else if (target.os.tag == .windows) { self.out_lib_filename = self.builder.fmt("{s}.lib", .{self.name}); } else { self.out_lib_filename = self.out_filename; } } } } pub fn setTarget(self: *LibExeObjStep, target: CrossTarget) void { self.target = target; self.computeOutFileNames(); } pub fn setOutputDir(self: *LibExeObjStep, dir: []const u8) void { self.output_dir = self.builder.dupePath(dir); } pub fn install(self: *LibExeObjStep) void { self.builder.installArtifact(self); } pub fn installRaw(self: *LibExeObjStep, dest_filename: []const u8) void { self.builder.installRaw(self, dest_filename); } /// Creates a `RunStep` with an executable built with `addExecutable`. /// Add command line arguments with `addArg`. pub fn run(exe: *LibExeObjStep) *RunStep { assert(exe.kind == Kind.Exe); // It doesn't have to be native. We catch that if you actually try to run it. // Consider that this is declarative; the run step may not be run unless a user // option is supplied. const run_step = RunStep.create(exe.builder, exe.builder.fmt("run {}", .{exe.step.name})); run_step.addArtifactArg(exe); if (exe.vcpkg_bin_path) |path| { run_step.addPathDir(path); } return run_step; } pub fn setLinkerScriptPath(self: *LibExeObjStep, path: []const u8) void { self.linker_script = path; } pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void { assert(self.target.isDarwin()); self.frameworks.put(framework_name) catch unreachable; } /// Returns whether the library, executable, or object depends on a particular system library. pub fn dependsOnSystemLibrary(self: LibExeObjStep, name: []const u8) bool { if (isLibCLibrary(name)) { return self.is_linking_libc; } for (self.link_objects.items) |link_object| { switch (link_object) { LinkObject.SystemLib => |n| if (mem.eql(u8, n, name)) return true, else => continue, } } return false; } pub fn linkLibrary(self: *LibExeObjStep, lib: *LibExeObjStep) void { assert(lib.kind == Kind.Lib); self.linkLibraryOrObject(lib); } pub fn isDynamicLibrary(self: *LibExeObjStep) bool { return self.kind == Kind.Lib and self.is_dynamic; } pub fn producesPdbFile(self: *LibExeObjStep) bool { if (!self.target.isWindows() and !self.target.isUefi()) return false; if (self.strip) return false; return self.isDynamicLibrary() or self.kind == .Exe; } pub fn linkLibC(self: *LibExeObjStep) void { if (!self.is_linking_libc) { self.is_linking_libc = true; self.link_objects.append(LinkObject{ .SystemLib = "c" }) catch unreachable; } } /// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1. pub fn defineCMacro(self: *LibExeObjStep, name_and_value: []const u8) void { self.c_macros.append(self.builder.dupe(name_and_value)) catch unreachable; } /// This one has no integration with anything, it just puts -lname on the command line. /// Prefer to use `linkSystemLibrary` instead. pub fn linkSystemLibraryName(self: *LibExeObjStep, name: []const u8) void { self.link_objects.append(LinkObject{ .SystemLib = self.builder.dupe(name) }) catch unreachable; } /// This links against a system library, exclusively using pkg-config to find the library. /// Prefer to use `linkSystemLibrary` instead. pub fn linkSystemLibraryPkgConfigOnly(self: *LibExeObjStep, lib_name: []const u8) !void { const pkg_name = match: { // First we have to map the library name to pkg config name. Unfortunately, // there are several examples where this is not straightforward: // -lSDL2 -> pkg-config sdl2 // -lgdk-3 -> pkg-config gdk-3.0 // -latk-1.0 -> pkg-config atk const pkgs = try self.builder.getPkgConfigList(); // Exact match means instant winner. for (pkgs) |pkg| { if (mem.eql(u8, pkg.name, lib_name)) { break :match pkg.name; } } // Next we'll try ignoring case. for (pkgs) |pkg| { if (std.ascii.eqlIgnoreCase(pkg.name, lib_name)) { break :match pkg.name; } } // Now try appending ".0". for (pkgs) |pkg| { if (std.ascii.indexOfIgnoreCase(pkg.name, lib_name)) |pos| { if (pos != 0) continue; if (mem.eql(u8, pkg.name[lib_name.len..], ".0")) { break :match pkg.name; } } } // Trimming "-1.0". if (mem.endsWith(u8, lib_name, "-1.0")) { const trimmed_lib_name = lib_name[0 .. lib_name.len - "-1.0".len]; for (pkgs) |pkg| { if (std.ascii.eqlIgnoreCase(pkg.name, trimmed_lib_name)) { break :match pkg.name; } } } return error.PackageNotFound; }; var code: u8 = undefined; const stdout = if (self.builder.execAllowFail(&[_][]const u8{ "pkg-config", pkg_name, "--cflags", "--libs", }, &code, .Ignore)) |stdout| stdout else |err| switch (err) { error.ProcessTerminated => return error.PkgConfigCrashed, error.ExitCodeFailure => return error.PkgConfigFailed, error.FileNotFound => return error.PkgConfigNotInstalled, else => return err, }; var it = mem.tokenize(stdout, " \r\n\t"); while (it.next()) |tok| { if (mem.eql(u8, tok, "-I")) { const dir = it.next() orelse return error.PkgConfigInvalidOutput; self.addIncludeDir(dir); } else if (mem.startsWith(u8, tok, "-I")) { self.addIncludeDir(tok["-I".len..]); } else if (mem.eql(u8, tok, "-L")) { const dir = it.next() orelse return error.PkgConfigInvalidOutput; self.addLibPath(dir); } else if (mem.startsWith(u8, tok, "-L")) { self.addLibPath(tok["-L".len..]); } else if (mem.eql(u8, tok, "-l")) { const lib = it.next() orelse return error.PkgConfigInvalidOutput; self.linkSystemLibraryName(lib); } else if (mem.startsWith(u8, tok, "-l")) { self.linkSystemLibraryName(tok["-l".len..]); } else if (mem.eql(u8, tok, "-D")) { const macro = it.next() orelse return error.PkgConfigInvalidOutput; self.defineCMacro(macro); } else if (mem.startsWith(u8, tok, "-D")) { self.defineCMacro(tok["-D".len..]); } else if (mem.eql(u8, tok, "-pthread")) { self.linkLibC(); } else if (self.builder.verbose) { warn("Ignoring pkg-config flag '{}'\n", .{tok}); } } } pub fn linkSystemLibrary(self: *LibExeObjStep, name: []const u8) void { if (isLibCLibrary(name)) { self.linkLibC(); return; } if (self.linkSystemLibraryPkgConfigOnly(name)) |_| { // pkg-config worked, so nothing further needed to do. return; } else |err| switch (err) { error.PkgConfigInvalidOutput, error.PkgConfigCrashed, error.PkgConfigFailed, error.PkgConfigNotInstalled, error.PackageNotFound, => {}, else => unreachable, } self.linkSystemLibraryName(name); } pub fn setNamePrefix(self: *LibExeObjStep, text: []const u8) void { assert(self.kind == Kind.Test); self.name_prefix = text; } pub fn setFilter(self: *LibExeObjStep, text: ?[]const u8) void { assert(self.kind == Kind.Test); self.filter = text; } /// Handy when you have many C/C++ source files and want them all to have the same flags. pub fn addCSourceFiles(self: *LibExeObjStep, files: []const []const u8, flags: []const []const u8) void { const c_source_files = self.builder.allocator.create(CSourceFiles) catch unreachable; const flags_copy = self.builder.allocator.alloc([]u8, flags.len) catch unreachable; for (flags) |flag, i| { flags_copy[i] = self.builder.dupe(flag); } c_source_files.* = .{ .files = files, .flags = flags_copy, }; self.link_objects.append(LinkObject{ .CSourceFiles = c_source_files }) catch unreachable; } pub fn addCSourceFile(self: *LibExeObjStep, file: []const u8, flags: []const []const u8) void { self.addCSourceFileSource(.{ .args = flags, .source = .{ .path = file }, }); } pub fn addCSourceFileSource(self: *LibExeObjStep, source: CSourceFile) void { const c_source_file = self.builder.allocator.create(CSourceFile) catch unreachable; const args_copy = self.builder.allocator.alloc([]u8, source.args.len) catch unreachable; for (source.args) |arg, i| { args_copy[i] = self.builder.dupe(arg); } c_source_file.* = source; c_source_file.args = args_copy; self.link_objects.append(LinkObject{ .CSourceFile = c_source_file }) catch unreachable; } pub fn setVerboseLink(self: *LibExeObjStep, value: bool) void { self.verbose_link = value; } pub fn setVerboseCC(self: *LibExeObjStep, value: bool) void { self.verbose_cc = value; } pub fn setBuildMode(self: *LibExeObjStep, mode: builtin.Mode) void { self.build_mode = mode; } pub fn overrideZigLibDir(self: *LibExeObjStep, dir_path: []const u8) void { self.override_lib_dir = self.builder.dupe(dir_path); } pub fn setMainPkgPath(self: *LibExeObjStep, dir_path: []const u8) void { self.main_pkg_path = dir_path; } pub fn setLibCFile(self: *LibExeObjStep, libc_file: ?[]const u8) void { self.libc_file = libc_file; } /// Unless setOutputDir was called, this function must be called only in /// the make step, from a step that has declared a dependency on this one. /// To run an executable built with zig build, use `run`, or create an install step and invoke it. pub fn getOutputPath(self: *LibExeObjStep) []const u8 { return fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir.?, self.out_filename }, ) catch unreachable; } /// Unless setOutputDir was called, this function must be called only in /// the make step, from a step that has declared a dependency on this one. pub fn getOutputLibPath(self: *LibExeObjStep) []const u8 { assert(self.kind == Kind.Lib); return fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir.?, self.out_lib_filename }, ) catch unreachable; } /// Unless setOutputDir was called, this function must be called only in /// the make step, from a step that has declared a dependency on this one. pub fn getOutputHPath(self: *LibExeObjStep) []const u8 { assert(self.kind != Kind.Exe); assert(self.emit_h); return fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir.?, self.out_h_filename }, ) catch unreachable; } /// Unless setOutputDir was called, this function must be called only in /// the make step, from a step that has declared a dependency on this one. pub fn getOutputPdbPath(self: *LibExeObjStep) []const u8 { assert(self.target.isWindows() or self.target.isUefi()); return fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir.?, self.out_pdb_filename }, ) catch unreachable; } pub fn addAssemblyFile(self: *LibExeObjStep, path: []const u8) void { self.link_objects.append(LinkObject{ .AssemblyFile = .{ .path = self.builder.dupe(path) }, }) catch unreachable; } pub fn addAssemblyFileFromWriteFileStep(self: *LibExeObjStep, wfs: *WriteFileStep, basename: []const u8) void { self.addAssemblyFileSource(.{ .write_file = .{ .step = wfs, .basename = self.builder.dupe(basename), }, }); } pub fn addAssemblyFileSource(self: *LibExeObjStep, source: FileSource) void { self.link_objects.append(LinkObject{ .AssemblyFile = source }) catch unreachable; source.addStepDependencies(&self.step); } pub fn addObjectFile(self: *LibExeObjStep, path: []const u8) void { self.link_objects.append(LinkObject{ .StaticPath = self.builder.dupe(path) }) catch unreachable; } pub fn addObject(self: *LibExeObjStep, obj: *LibExeObjStep) void { assert(obj.kind == Kind.Obj); self.linkLibraryOrObject(obj); } pub fn addBuildOption(self: *LibExeObjStep, comptime T: type, name: []const u8, value: T) void { const out = self.build_options_contents.outStream(); switch (T) { []const []const u8 => { out.print("pub const {z}: []const []const u8 = &[_][]const u8{{\n", .{name}) catch unreachable; for (value) |slice| { out.print(" \"{Z}\",\n", .{slice}) catch unreachable; } out.writeAll("};\n") catch unreachable; return; }, [:0]const u8 => { out.print("pub const {z}: [:0]const u8 = \"{Z}\";\n", .{ name, value }) catch unreachable; return; }, []const u8 => { out.print("pub const {z}: []const u8 = \"{Z}\";\n", .{ name, value }) catch unreachable; return; }, ?[]const u8 => { out.print("pub const {z}: ?[]const u8 = ", .{name}) catch unreachable; if (value) |payload| { out.print("\"{Z}\";\n", .{payload}) catch unreachable; } else { out.writeAll("null;\n") catch unreachable; } return; }, std.builtin.Version => { out.print( \\pub const {z}: @import("builtin").Version = .{{ \\ .major = {d}, \\ .minor = {d}, \\ .patch = {d}, \\}}; \\ , .{ name, value.major, value.minor, value.patch, }) catch unreachable; }, std.SemanticVersion => { out.print( \\pub const {z}: @import("std").SemanticVersion = .{{ \\ .major = {d}, \\ .minor = {d}, \\ .patch = {d}, \\ , .{ name, value.major, value.minor, value.patch, }) catch unreachable; if (value.pre) |some| { out.print(" .pre = \"{Z}\",\n", .{some}) catch unreachable; } if (value.build) |some| { out.print(" .build = \"{Z}\",\n", .{some}) catch unreachable; } out.writeAll("};\n") catch unreachable; return; }, else => {}, } switch (@typeInfo(T)) { .Enum => |enum_info| { out.print("pub const {z} = enum {{\n", .{@typeName(T)}) catch unreachable; inline for (enum_info.fields) |field| { out.print(" {z},\n", .{field.name}) catch unreachable; } out.writeAll("};\n") catch unreachable; }, else => {}, } out.print("pub const {z}: {} = {};\n", .{ name, @typeName(T), value }) catch unreachable; } /// The value is the path in the cache dir. /// Adds a dependency automatically. pub fn addBuildOptionArtifact(self: *LibExeObjStep, name: []const u8, artifact: *LibExeObjStep) void { self.build_options_artifact_args.append(.{ .name = name, .artifact = artifact }) catch unreachable; self.step.dependOn(&artifact.step); } pub fn addSystemIncludeDir(self: *LibExeObjStep, path: []const u8) void { self.include_dirs.append(IncludeDir{ .RawPathSystem = self.builder.dupe(path) }) catch unreachable; } pub fn addIncludeDir(self: *LibExeObjStep, path: []const u8) void { self.include_dirs.append(IncludeDir{ .RawPath = self.builder.dupe(path) }) catch unreachable; } pub fn addLibPath(self: *LibExeObjStep, path: []const u8) void { self.lib_paths.append(self.builder.dupe(path)) catch unreachable; } pub fn addFrameworkDir(self: *LibExeObjStep, dir_path: []const u8) void { self.framework_dirs.append(self.builder.dupe(dir_path)) catch unreachable; } pub fn addPackage(self: *LibExeObjStep, package: Pkg) void { self.packages.append(self.builder.dupePkg(package)) catch unreachable; } pub fn addPackagePath(self: *LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void { self.packages.append(Pkg{ .name = self.builder.dupe(name), .path = self.builder.dupe(pkg_index_path), }) catch unreachable; } /// If Vcpkg was found on the system, it will be added to include and lib /// paths for the specified target. pub fn addVcpkgPaths(self: *LibExeObjStep, linkage: VcpkgLinkage) !void { // Ideally in the Unattempted case we would call the function recursively // after findVcpkgRoot and have only one switch statement, but the compiler // cannot resolve the error set. switch (self.builder.vcpkg_root) { .Unattempted => { self.builder.vcpkg_root = if (try findVcpkgRoot(self.builder.allocator)) |root| VcpkgRoot{ .Found = root } else .NotFound; }, .NotFound => return error.VcpkgNotFound, .Found => {}, } switch (self.builder.vcpkg_root) { .Unattempted => unreachable, .NotFound => return error.VcpkgNotFound, .Found => |root| { const allocator = self.builder.allocator; const triplet = try self.target.vcpkgTriplet(allocator, linkage); defer self.builder.allocator.free(triplet); const include_path = try fs.path.join(allocator, &[_][]const u8{ root, "installed", triplet, "include" }); errdefer allocator.free(include_path); try self.include_dirs.append(IncludeDir{ .RawPath = include_path }); const lib_path = try fs.path.join(allocator, &[_][]const u8{ root, "installed", triplet, "lib" }); try self.lib_paths.append(lib_path); self.vcpkg_bin_path = try fs.path.join(allocator, &[_][]const u8{ root, "installed", triplet, "bin" }); }, } } pub fn setExecCmd(self: *LibExeObjStep, args: []const ?[]const u8) void { assert(self.kind == Kind.Test); self.exec_cmd_args = args; } fn linkLibraryOrObject(self: *LibExeObjStep, other: *LibExeObjStep) void { self.step.dependOn(&other.step); self.link_objects.append(LinkObject{ .OtherStep = other }) catch unreachable; self.include_dirs.append(IncludeDir{ .OtherStep = other }) catch unreachable; // Inherit dependency on system libraries for (other.link_objects.items) |link_object| { switch (link_object) { .SystemLib => |name| self.linkSystemLibrary(name), else => continue, } } // Inherit dependencies on darwin frameworks if (self.target.isDarwin() and !other.isDynamicLibrary()) { var it = other.frameworks.iterator(); while (it.next()) |entry| { self.frameworks.put(entry.key) catch unreachable; } } } fn makePackageCmd(self: *LibExeObjStep, pkg: Pkg, zig_args: *ArrayList([]const u8)) error{OutOfMemory}!void { const builder = self.builder; try zig_args.append("--pkg-begin"); try zig_args.append(pkg.name); try zig_args.append(builder.pathFromRoot(pkg.path)); if (pkg.dependencies) |dependencies| { for (dependencies) |sub_pkg| { try self.makePackageCmd(sub_pkg, zig_args); } } try zig_args.append("--pkg-end"); } fn make(step: *Step) !void { const self = @fieldParentPtr(LibExeObjStep, "step", step); const builder = self.builder; if (self.root_src == null and self.link_objects.items.len == 0) { warn("{}: linker needs 1 or more objects to link\n", .{self.step.name}); return error.NeedAnObject; } var zig_args = ArrayList([]const u8).init(builder.allocator); defer zig_args.deinit(); zig_args.append(builder.zig_exe) catch unreachable; const cmd = switch (self.kind) { .Lib => "build-lib", .Exe => "build-exe", .Obj => "build-obj", .Test => "test", }; zig_args.append(cmd) catch unreachable; if (builder.color != .auto) { try zig_args.append("--color"); try zig_args.append(@tagName(builder.color)); } if (self.stack_size) |stack_size| { try zig_args.append("--stack"); try zig_args.append(try std.fmt.allocPrint(builder.allocator, "{}", .{stack_size})); } if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder)); var prev_has_extra_flags = false; for (self.link_objects.items) |link_object| { switch (link_object) { .StaticPath => |static_path| { try zig_args.append(builder.pathFromRoot(static_path)); }, .OtherStep => |other| switch (other.kind) { .Exe => unreachable, .Test => unreachable, .Obj => { try zig_args.append(other.getOutputPath()); }, .Lib => { const full_path_lib = other.getOutputLibPath(); try zig_args.append(full_path_lib); if (other.is_dynamic and !self.target.isWindows()) { if (fs.path.dirname(full_path_lib)) |dirname| { try zig_args.append("-rpath"); try zig_args.append(dirname); } } }, }, .SystemLib => |name| { try zig_args.append(builder.fmt("-l{s}", .{name})); }, .AssemblyFile => |asm_file| { if (prev_has_extra_flags) { try zig_args.append("-extra-cflags"); try zig_args.append("--"); prev_has_extra_flags = false; } try zig_args.append(asm_file.getPath(builder)); }, .CSourceFile => |c_source_file| { if (c_source_file.args.len == 0) { if (prev_has_extra_flags) { try zig_args.append("-cflags"); try zig_args.append("--"); prev_has_extra_flags = false; } } else { try zig_args.append("-cflags"); for (c_source_file.args) |arg| { try zig_args.append(arg); } try zig_args.append("--"); } try zig_args.append(c_source_file.source.getPath(builder)); }, .CSourceFiles => |c_source_files| { if (c_source_files.flags.len == 0) { if (prev_has_extra_flags) { try zig_args.append("-cflags"); try zig_args.append("--"); prev_has_extra_flags = false; } } else { try zig_args.append("-cflags"); for (c_source_files.flags) |flag| { try zig_args.append(flag); } try zig_args.append("--"); } for (c_source_files.files) |file| { try zig_args.append(builder.pathFromRoot(file)); } }, } } if (self.build_options_contents.items.len > 0 or self.build_options_artifact_args.items.len > 0) { // Render build artifact options at the last minute, now that the path is known. for (self.build_options_artifact_args.items) |item| { const out = self.build_options_contents.writer(); out.print("pub const {}: []const u8 = \"{Z}\";\n", .{ item.name, item.artifact.getOutputPath() }) catch unreachable; } const build_options_file = try fs.path.join( builder.allocator, &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) }, ); const path_from_root = builder.pathFromRoot(build_options_file); try fs.cwd().writeFile(path_from_root, self.build_options_contents.items); try zig_args.append("--pkg-begin"); try zig_args.append("build_options"); try zig_args.append(path_from_root); try zig_args.append("--pkg-end"); } if (self.image_base) |image_base| { try zig_args.append("--image-base"); try zig_args.append(builder.fmt("0x{x}", .{image_base})); } if (self.filter) |filter| { try zig_args.append("--test-filter"); try zig_args.append(filter); } if (self.test_evented_io) { try zig_args.append("--test-evented-io"); } if (self.name_prefix.len != 0) { try zig_args.append("--test-name-prefix"); try zig_args.append(self.name_prefix); } if (builder.verbose_tokenize) zig_args.append("--verbose-tokenize") catch unreachable; if (builder.verbose_ast) zig_args.append("--verbose-ast") catch unreachable; if (builder.verbose_cimport) zig_args.append("--verbose-cimport") catch unreachable; if (builder.verbose_ir) zig_args.append("--verbose-ir") catch unreachable; if (builder.verbose_llvm_ir) zig_args.append("--verbose-llvm-ir") catch unreachable; if (builder.verbose_link or self.verbose_link) zig_args.append("--verbose-link") catch unreachable; if (builder.verbose_cc or self.verbose_cc) zig_args.append("--verbose-cc") catch unreachable; if (builder.verbose_llvm_cpu_features) zig_args.append("--verbose-llvm-cpu-features") catch unreachable; if (self.emit_llvm_ir) try zig_args.append("-femit-llvm-ir"); if (self.emit_asm) try zig_args.append("-femit-asm"); if (!self.emit_bin) try zig_args.append("-fno-emit-bin"); if (self.emit_docs) try zig_args.append("-femit-docs"); if (self.emit_h) try zig_args.append("-femit-h"); if (self.strip) { try zig_args.append("--strip"); } if (self.link_eh_frame_hdr) { try zig_args.append("--eh-frame-hdr"); } if (self.link_emit_relocs) { try zig_args.append("--emit-relocs"); } if (self.link_function_sections) { try zig_args.append("-ffunction-sections"); } if (self.single_threaded) { try zig_args.append("--single-threaded"); } if (self.libc_file) |libc_file| { try zig_args.append("--libc"); try zig_args.append(builder.pathFromRoot(libc_file)); } switch (self.build_mode) { .Debug => {}, // Skip since it's the default. else => zig_args.append(builder.fmt("-O{s}", .{@tagName(self.build_mode)})) catch unreachable, } try zig_args.append("--cache-dir"); try zig_args.append(builder.pathFromRoot(builder.cache_root)); try zig_args.append("--global-cache-dir"); try zig_args.append(builder.pathFromRoot(builder.global_cache_root)); zig_args.append("--name") catch unreachable; zig_args.append(self.name) catch unreachable; if (self.kind == Kind.Lib and self.is_dynamic) { if (self.version) |version| { zig_args.append("--version") catch unreachable; zig_args.append(builder.fmt("{}", .{version})) catch unreachable; } } if (self.is_dynamic) { try zig_args.append("-dynamic"); } if (self.bundle_compiler_rt) |x| { if (x) { try zig_args.append("-fcompiler-rt"); } else { try zig_args.append("-fno-compiler-rt"); } } if (self.disable_stack_probing) { try zig_args.append("-fno-stack-check"); } if (self.disable_sanitize_c) { try zig_args.append("-fno-sanitize-c"); } if (self.rdynamic) { try zig_args.append("-rdynamic"); } if (self.code_model != .default) { try zig_args.append("-mcmodel"); try zig_args.append(@tagName(self.code_model)); } if (!self.target.isNative()) { try zig_args.append("-target"); try zig_args.append(try self.target.zigTriple(builder.allocator)); // TODO this logic can disappear if cpu model + features becomes part of the target triple const cross = self.target.toTarget(); const all_features = cross.cpu.arch.allFeaturesList(); var populated_cpu_features = cross.cpu.model.features; populated_cpu_features.populateDependencies(all_features); if (populated_cpu_features.eql(cross.cpu.features)) { // The CPU name alone is sufficient. // If it is the baseline CPU, no command line args are required. if (cross.cpu.model != std.Target.Cpu.baseline(cross.cpu.arch).model) { try zig_args.append("-mcpu"); try zig_args.append(cross.cpu.model.name); } } else { var mcpu_buffer = std.ArrayList(u8).init(builder.allocator); try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name}); for (all_features) |feature, i_usize| { const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize); const in_cpu_set = populated_cpu_features.isEnabled(i); const in_actual_set = cross.cpu.features.isEnabled(i); if (in_cpu_set and !in_actual_set) { try mcpu_buffer.outStream().print("-{}", .{feature.name}); } else if (!in_cpu_set and in_actual_set) { try mcpu_buffer.outStream().print("+{}", .{feature.name}); } } try zig_args.append(mcpu_buffer.toOwnedSlice()); } if (self.target.dynamic_linker.get()) |dynamic_linker| { try zig_args.append("--dynamic-linker"); try zig_args.append(dynamic_linker); } } if (self.linker_script) |linker_script| { try zig_args.append("--script"); try zig_args.append(builder.pathFromRoot(linker_script)); } if (self.version_script) |version_script| { try zig_args.append("--version-script"); try zig_args.append(builder.pathFromRoot(version_script)); } if (self.exec_cmd_args) |exec_cmd_args| { for (exec_cmd_args) |cmd_arg| { if (cmd_arg) |arg| { try zig_args.append("--test-cmd"); try zig_args.append(arg); } else { try zig_args.append("--test-cmd-bin"); } } } else switch (self.target.getExternalExecutor()) { .native, .unavailable => {}, .qemu => |bin_name| if (self.enable_qemu) qemu: { const need_cross_glibc = self.target.isGnuLibC() and self.is_linking_libc; const glibc_dir_arg = if (need_cross_glibc) self.glibc_multi_install_dir orelse break :qemu else null; try zig_args.append("--test-cmd"); try zig_args.append(bin_name); if (glibc_dir_arg) |dir| { const full_dir = try fs.path.join(builder.allocator, &[_][]const u8{ dir, try self.target.linuxTriple(builder.allocator), }); try zig_args.append("--test-cmd"); try zig_args.append("-L"); try zig_args.append("--test-cmd"); try zig_args.append(full_dir); } try zig_args.append("--test-cmd-bin"); }, .wine => |bin_name| if (self.enable_wine) { try zig_args.append("--test-cmd"); try zig_args.append(bin_name); try zig_args.append("--test-cmd-bin"); }, .wasmtime => |bin_name| if (self.enable_wasmtime) { try zig_args.append("--test-cmd"); try zig_args.append(bin_name); try zig_args.append("--test-cmd"); try zig_args.append("--dir=."); try zig_args.append("--test-cmd-bin"); }, } for (self.packages.items) |pkg| { try self.makePackageCmd(pkg, &zig_args); } for (self.include_dirs.items) |include_dir| { switch (include_dir) { .RawPath => |include_path| { try zig_args.append("-I"); try zig_args.append(self.builder.pathFromRoot(include_path)); }, .RawPathSystem => |include_path| { try zig_args.append("-isystem"); try zig_args.append(self.builder.pathFromRoot(include_path)); }, .OtherStep => |other| if (other.emit_h) { const h_path = other.getOutputHPath(); try zig_args.append("-isystem"); try zig_args.append(fs.path.dirname(h_path).?); }, } } for (self.lib_paths.items) |lib_path| { try zig_args.append("-L"); try zig_args.append(lib_path); } for (self.c_macros.items) |c_macro| { try zig_args.append("-D"); try zig_args.append(c_macro); } if (self.target.isDarwin()) { for (self.framework_dirs.items) |dir| { try zig_args.append("-F"); try zig_args.append(dir); } var it = self.frameworks.iterator(); while (it.next()) |entry| { zig_args.append("-framework") catch unreachable; zig_args.append(entry.key) catch unreachable; } } for (builder.search_prefixes.items) |search_prefix| { try zig_args.append("-L"); try zig_args.append(try fs.path.join(builder.allocator, &[_][]const u8{ search_prefix, "lib", })); try zig_args.append("-isystem"); try zig_args.append(try fs.path.join(builder.allocator, &[_][]const u8{ search_prefix, "include", })); } if (self.valgrind_support) |valgrind_support| { if (valgrind_support) { try zig_args.append("-fvalgrind"); } else { try zig_args.append("-fno-valgrind"); } } if (self.override_lib_dir) |dir| { try zig_args.append("--override-lib-dir"); try zig_args.append(builder.pathFromRoot(dir)); } else if (self.builder.override_lib_dir) |dir| { try zig_args.append("--override-lib-dir"); try zig_args.append(builder.pathFromRoot(dir)); } if (self.main_pkg_path) |dir| { try zig_args.append("--main-pkg-path"); try zig_args.append(builder.pathFromRoot(dir)); } if (self.force_pic) |pic| { if (pic) { try zig_args.append("-fPIC"); } else { try zig_args.append("-fno-PIC"); } } if (self.pie) |pie| { if (pie) { try zig_args.append("-fPIE"); } else { try zig_args.append("-fno-PIE"); } } if (self.subsystem) |subsystem| { try zig_args.append("--subsystem"); try zig_args.append(switch (subsystem) { .Console => "console", .Windows => "windows", .Posix => "posix", .Native => "native", .EfiApplication => "efi_application", .EfiBootServiceDriver => "efi_boot_service_driver", .EfiRom => "efi_rom", .EfiRuntimeDriver => "efi_runtime_driver", }); } if (self.kind == Kind.Test) { try builder.spawnChild(zig_args.items); } else { try zig_args.append("--enable-cache"); const output_dir_nl = try builder.execFromStep(zig_args.items, &self.step); const build_output_dir = mem.trimRight(u8, output_dir_nl, "\r\n"); if (self.output_dir) |output_dir| { var src_dir = try std.fs.cwd().openDir(build_output_dir, .{ .iterate = true }); defer src_dir.close(); // Create the output directory if it doesn't exist. try std.fs.cwd().makePath(output_dir); var dest_dir = try std.fs.cwd().openDir(output_dir, .{}); defer dest_dir.close(); var it = src_dir.iterate(); while (try it.next()) |entry| { // The compiler can put these files into the same directory, but we don't // want to copy them over. if (mem.eql(u8, entry.name, "stage1.id") or mem.eql(u8, entry.name, "llvm-ar.id") or mem.eql(u8, entry.name, "libs.txt") or mem.eql(u8, entry.name, "builtin.zig") or mem.eql(u8, entry.name, "lld.id")) continue; _ = try src_dir.updateFile(entry.name, dest_dir, entry.name, .{}); } } else { self.output_dir = build_output_dir; } } if (self.kind == Kind.Lib and self.is_dynamic and self.version != null and self.target.wantSharedLibSymLinks()) { try doAtomicSymLinks(builder.allocator, self.getOutputPath(), self.major_only_filename, self.name_only_filename); } } }; pub const InstallArtifactStep = struct { step: Step, builder: *Builder, artifact: *LibExeObjStep, dest_dir: InstallDir, pdb_dir: ?InstallDir, h_dir: ?InstallDir, const Self = @This(); pub fn create(builder: *Builder, artifact: *LibExeObjStep) *Self { if (artifact.install_step) |s| return s; const self = builder.allocator.create(Self) catch unreachable; self.* = Self{ .builder = builder, .step = Step.init(.InstallArtifact, builder.fmt("install {}", .{artifact.step.name}), builder.allocator, make), .artifact = artifact, .dest_dir = artifact.override_dest_dir orelse switch (artifact.kind) { .Obj => unreachable, .Test => unreachable, .Exe => InstallDir{ .Bin = {} }, .Lib => InstallDir{ .Lib = {} }, }, .pdb_dir = if (artifact.producesPdbFile()) blk: { if (artifact.kind == .Exe) { break :blk InstallDir{ .Bin = {} }; } else { break :blk InstallDir{ .Lib = {} }; } } else null, .h_dir = if (artifact.kind == .Lib and artifact.emit_h) .Header else null, }; self.step.dependOn(&artifact.step); artifact.install_step = self; builder.pushInstalledFile(self.dest_dir, artifact.out_filename); if (self.artifact.isDynamicLibrary()) { if (self.artifact.version != null) { builder.pushInstalledFile(.Lib, artifact.major_only_filename); builder.pushInstalledFile(.Lib, artifact.name_only_filename); } if (self.artifact.target.isWindows()) { builder.pushInstalledFile(.Lib, artifact.out_lib_filename); } } if (self.pdb_dir) |pdb_dir| { builder.pushInstalledFile(pdb_dir, artifact.out_pdb_filename); } if (self.h_dir) |h_dir| { builder.pushInstalledFile(h_dir, artifact.out_h_filename); } return self; } fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); const builder = self.builder; const full_dest_path = builder.getInstallPath(self.dest_dir, self.artifact.out_filename); try builder.updateFile(self.artifact.getOutputPath(), full_dest_path); if (self.artifact.isDynamicLibrary() and self.artifact.version != null and self.artifact.target.wantSharedLibSymLinks()) { try doAtomicSymLinks(builder.allocator, full_dest_path, self.artifact.major_only_filename, self.artifact.name_only_filename); } if (self.pdb_dir) |pdb_dir| { const full_pdb_path = builder.getInstallPath(pdb_dir, self.artifact.out_pdb_filename); try builder.updateFile(self.artifact.getOutputPdbPath(), full_pdb_path); } if (self.h_dir) |h_dir| { const full_pdb_path = builder.getInstallPath(h_dir, self.artifact.out_h_filename); try builder.updateFile(self.artifact.getOutputHPath(), full_pdb_path); } self.artifact.installed_path = full_dest_path; } }; pub const InstallFileStep = struct { step: Step, builder: *Builder, src_path: []const u8, dir: InstallDir, dest_rel_path: []const u8, pub fn init( builder: *Builder, src_path: []const u8, dir: InstallDir, dest_rel_path: []const u8, ) InstallFileStep { builder.pushInstalledFile(dir, dest_rel_path); return InstallFileStep{ .builder = builder, .step = Step.init(.InstallFile, builder.fmt("install {}", .{src_path}), builder.allocator, make), .src_path = src_path, .dir = dir, .dest_rel_path = dest_rel_path, }; } fn make(step: *Step) !void { const self = @fieldParentPtr(InstallFileStep, "step", step); const full_dest_path = self.builder.getInstallPath(self.dir, self.dest_rel_path); const full_src_path = self.builder.pathFromRoot(self.src_path); try self.builder.updateFile(full_src_path, full_dest_path); } }; pub const InstallDirectoryOptions = struct { source_dir: []const u8, install_dir: InstallDir, install_subdir: []const u8, exclude_extensions: ?[]const []const u8 = null, }; pub const InstallDirStep = struct { step: Step, builder: *Builder, options: InstallDirectoryOptions, pub fn init( builder: *Builder, options: InstallDirectoryOptions, ) InstallDirStep { builder.pushInstalledFile(options.install_dir, options.install_subdir); return InstallDirStep{ .builder = builder, .step = Step.init(.InstallDir, builder.fmt("install {}/", .{options.source_dir}), builder.allocator, make), .options = options, }; } fn make(step: *Step) !void { const self = @fieldParentPtr(InstallDirStep, "step", step); const dest_prefix = self.builder.getInstallPath(self.options.install_dir, self.options.install_subdir); const full_src_dir = self.builder.pathFromRoot(self.options.source_dir); var it = try fs.walkPath(self.builder.allocator, full_src_dir); next_entry: while (try it.next()) |entry| { if (self.options.exclude_extensions) |ext_list| for (ext_list) |ext| { if (mem.endsWith(u8, entry.path, ext)) { continue :next_entry; } }; const rel_path = entry.path[full_src_dir.len + 1 ..]; const dest_path = try fs.path.join(self.builder.allocator, &[_][]const u8{ dest_prefix, rel_path }); switch (entry.kind) { .Directory => try fs.cwd().makePath(dest_path), .File => try self.builder.updateFile(entry.path, dest_path), else => continue, } } } }; pub const LogStep = struct { step: Step, builder: *Builder, data: []const u8, pub fn init(builder: *Builder, data: []const u8) LogStep { return LogStep{ .builder = builder, .step = Step.init(.Log, builder.fmt("log {}", .{data}), builder.allocator, make), .data = data, }; } fn make(step: *Step) anyerror!void { const self = @fieldParentPtr(LogStep, "step", step); warn("{}", .{self.data}); } }; pub const RemoveDirStep = struct { step: Step, builder: *Builder, dir_path: []const u8, pub fn init(builder: *Builder, dir_path: []const u8) RemoveDirStep { return RemoveDirStep{ .builder = builder, .step = Step.init(.RemoveDir, builder.fmt("RemoveDir {}", .{dir_path}), builder.allocator, make), .dir_path = dir_path, }; } fn make(step: *Step) !void { const self = @fieldParentPtr(RemoveDirStep, "step", step); const full_path = self.builder.pathFromRoot(self.dir_path); fs.cwd().deleteTree(full_path) catch |err| { warn("Unable to remove {}: {}\n", .{ full_path, @errorName(err) }); return err; }; } }; const ThisModule = @This(); pub const Step = struct { id: Id, name: []const u8, makeFn: fn (self: *Step) anyerror!void, dependencies: ArrayList(*Step), loop_flag: bool, done_flag: bool, pub const Id = enum { TopLevel, LibExeObj, InstallArtifact, InstallFile, InstallDir, Log, RemoveDir, Fmt, TranslateC, WriteFile, Run, CheckFile, InstallRaw, Custom, }; pub fn init(id: Id, name: []const u8, allocator: *Allocator, makeFn: fn (*Step) anyerror!void) Step { return Step{ .id = id, .name = name, .makeFn = makeFn, .dependencies = ArrayList(*Step).init(allocator), .loop_flag = false, .done_flag = false, }; } pub fn initNoOp(id: Id, name: []const u8, allocator: *Allocator) Step { return init(id, name, allocator, makeNoOp); } pub fn make(self: *Step) !void { if (self.done_flag) return; try self.makeFn(self); self.done_flag = true; } pub fn dependOn(self: *Step, other: *Step) void { self.dependencies.append(other) catch unreachable; } fn makeNoOp(self: *Step) anyerror!void {} pub fn cast(step: *Step, comptime T: type) ?*T { if (step.id == comptime typeToId(T)) { return @fieldParentPtr(T, "step", step); } return null; } fn typeToId(comptime T: type) Id { inline for (@typeInfo(Id).Enum.fields) |f| { if (std.mem.eql(u8, f.name, "TopLevel") or std.mem.eql(u8, f.name, "Custom")) continue; if (T == @field(ThisModule, f.name ++ "Step")) { return @field(Id, f.name); } } unreachable; } }; fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void { const out_dir = fs.path.dirname(output_path) orelse "."; const out_basename = fs.path.basename(output_path); // sym link for libfoo.so.1 to libfoo.so.1.2.3 const major_only_path = fs.path.join( allocator, &[_][]const u8{ out_dir, filename_major_only }, ) catch unreachable; fs.atomicSymLink(allocator, out_basename, major_only_path) catch |err| { warn("Unable to symlink {} -> {}\n", .{ major_only_path, out_basename }); return err; }; // sym link for libfoo.so to libfoo.so.1 const name_only_path = fs.path.join( allocator, &[_][]const u8{ out_dir, filename_name_only }, ) catch unreachable; fs.atomicSymLink(allocator, filename_major_only, name_only_path) catch |err| { warn("Unable to symlink {} -> {}\n", .{ name_only_path, filename_major_only }); return err; }; } /// Returned slice must be freed by the caller. fn findVcpkgRoot(allocator: *Allocator) !?[]const u8 { const appdata_path = try fs.getAppDataDir(allocator, "vcpkg"); defer allocator.free(appdata_path); const path_file = try fs.path.join(allocator, &[_][]const u8{ appdata_path, "vcpkg.path.txt" }); defer allocator.free(path_file); const file = fs.cwd().openFile(path_file, .{}) catch return null; defer file.close(); const size = @intCast(usize, try file.getEndPos()); const vcpkg_path = try allocator.alloc(u8, size); const size_read = try file.read(vcpkg_path); std.debug.assert(size == size_read); return vcpkg_path; } const VcpkgRoot = union(VcpkgRootStatus) { Unattempted: void, NotFound: void, Found: []const u8, }; const VcpkgRootStatus = enum { Unattempted, NotFound, Found, }; pub const VcpkgLinkage = std.builtin.LinkMode; pub const InstallDir = union(enum) { Prefix: void, Lib: void, Bin: void, Header: void, /// A path relative to the prefix Custom: []const u8, }; pub const InstalledFile = struct { dir: InstallDir, path: []const u8, }; test "Builder.dupePkg()" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var builder = try Builder.create( &arena.allocator, "test", "test", "test", "test", ); defer builder.destroy(); var pkg_dep = Pkg{ .name = "pkg_dep", .path = "/not/a/pkg_dep.zig", }; var pkg_top = Pkg{ .name = "pkg_top", .path = "/not/a/pkg_top.zig", .dependencies = &[_]Pkg{pkg_dep}, }; const dupe = builder.dupePkg(pkg_top); const original_deps = pkg_top.dependencies.?; const dupe_deps = dupe.dependencies.?; // probably the same top level package details std.testing.expectEqualStrings(pkg_top.name, dupe.name); // probably the same dependencies std.testing.expectEqual(original_deps.len, dupe_deps.len); std.testing.expectEqual(original_deps[0].name, pkg_dep.name); // could segfault otherwise if pointers in duplicated package's fields are // the same as those in stack allocated package's fields std.testing.expect(dupe_deps.ptr != original_deps.ptr); std.testing.expect(dupe.name.ptr != pkg_top.name.ptr); std.testing.expect(dupe.path.ptr != pkg_top.path.ptr); std.testing.expect(dupe_deps[0].name.ptr != pkg_dep.name.ptr); std.testing.expect(dupe_deps[0].path.ptr != pkg_dep.path.ptr); } test "LibExeObjStep.addBuildOption" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var builder = try Builder.create( &arena.allocator, "test", "test", "test", "test", ); defer builder.destroy(); var exe = builder.addExecutable("not_an_executable", "/not/an/executable.zig"); exe.addBuildOption(usize, "option1", 1); exe.addBuildOption(?usize, "option2", null); exe.addBuildOption([]const u8, "string", "zigisthebest"); exe.addBuildOption(?[]const u8, "optional_string", null); exe.addBuildOption(std.SemanticVersion, "semantic_version", try std.SemanticVersion.parse("0.1.2-foo+bar")); std.testing.expectEqualStrings( \\pub const option1: usize = 1; \\pub const option2: ?usize = null; \\pub const string: []const u8 = "zigisthebest"; \\pub const optional_string: ?[]const u8 = null; \\pub const semantic_version: @import("std").SemanticVersion = .{ \\ .major = 0, \\ .minor = 1, \\ .patch = 2, \\ .pre = "foo", \\ .build = "bar", \\}; \\ , exe.build_options_contents.items); } test "LibExeObjStep.addPackage" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var builder = try Builder.create( &arena.allocator, "test", "test", "test", "test", ); defer builder.destroy(); const pkg_dep = Pkg{ .name = "pkg_dep", .path = "/not/a/pkg_dep.zig", }; const pkg_top = Pkg{ .name = "pkg_dep", .path = "/not/a/pkg_top.zig", .dependencies = &[_]Pkg{pkg_dep}, }; var exe = builder.addExecutable("not_an_executable", "/not/an/executable.zig"); exe.addPackage(pkg_top); std.testing.expectEqual(@as(usize, 1), exe.packages.items.len); const dupe = exe.packages.items[0]; std.testing.expectEqualStrings(pkg_top.name, dupe.name); } test "" { // The only purpose of this test is to get all these untested functions // to be referenced to avoid regression so it is okay to skip some targets. if (comptime std.Target.current.cpu.arch.ptrBitWidth() == 64) { std.testing.refAllDecls(@This()); std.testing.refAllDecls(Builder); inline for (std.meta.declarations(@This())) |decl| if (comptime mem.endsWith(u8, decl.name, "Step")) std.testing.refAllDecls(decl.data.Type); } }
lib/std/build.zig
const std = @import("std"); const os = std.os; const io = std.io; const mem = std.mem; const Allocator = mem.Allocator; const Buffer = std.Buffer; const llvm = @import("llvm.zig"); const c = @import("c.zig"); const builtin = @import("builtin"); const Target = @import("target.zig").Target; const warn = std.debug.warn; const Token = std.zig.Token; const ArrayList = std.ArrayList; const errmsg = @import("errmsg.zig"); const ast = std.zig.ast; const event = std.event; const assert = std.debug.assert; const AtomicRmwOp = builtin.AtomicRmwOp; const AtomicOrder = builtin.AtomicOrder; const Scope = @import("scope.zig").Scope; const Decl = @import("decl.zig").Decl; const ir = @import("ir.zig"); const Visib = @import("visib.zig").Visib; const Value = @import("value.zig").Value; const Type = Value.Type; const Span = errmsg.Span; const Msg = errmsg.Msg; const codegen = @import("codegen.zig"); const Package = @import("package.zig").Package; const link = @import("link.zig").link; const LibCInstallation = @import("libc_installation.zig").LibCInstallation; const CInt = @import("c_int.zig").CInt; const fs = event.fs; const max_src_size = 2 * 1024 * 1024 * 1024; // 2 GiB /// Data that is local to the event loop. pub const ZigCompiler = struct { loop: *event.Loop, llvm_handle_pool: std.atomic.Stack(llvm.ContextRef), lld_lock: event.Lock, /// TODO pool these so that it doesn't have to lock prng: event.Locked(std.rand.DefaultPrng), native_libc: event.Future(LibCInstallation), var lazy_init_targets = std.lazyInit(void); fn init(loop: *event.Loop) !ZigCompiler { lazy_init_targets.get() orelse { Target.initializeAll(); lazy_init_targets.resolve(); }; var seed_bytes: [@sizeOf(u64)]u8 = undefined; try std.os.getRandomBytes(seed_bytes[0..]); const seed = mem.readIntNative(u64, &seed_bytes); return ZigCompiler{ .loop = loop, .lld_lock = event.Lock.init(loop), .llvm_handle_pool = std.atomic.Stack(llvm.ContextRef).init(), .prng = event.Locked(std.rand.DefaultPrng).init(loop, std.rand.DefaultPrng.init(seed)), .native_libc = event.Future(LibCInstallation).init(loop), }; } /// Must be called only after EventLoop.run completes. fn deinit(self: *ZigCompiler) void { self.lld_lock.deinit(); while (self.llvm_handle_pool.pop()) |node| { c.LLVMContextDispose(node.data); self.loop.allocator.destroy(node); } } /// Gets an exclusive handle on any LlvmContext. /// Caller must release the handle when done. pub fn getAnyLlvmContext(self: *ZigCompiler) !LlvmHandle { if (self.llvm_handle_pool.pop()) |node| return LlvmHandle{ .node = node }; const context_ref = c.LLVMContextCreate() orelse return error.OutOfMemory; errdefer c.LLVMContextDispose(context_ref); const node = try self.loop.allocator.create(std.atomic.Stack(llvm.ContextRef).Node{ .next = undefined, .data = context_ref, }); errdefer self.loop.allocator.destroy(node); return LlvmHandle{ .node = node }; } pub async fn getNativeLibC(self: *ZigCompiler) !*LibCInstallation { if (await (async self.native_libc.start() catch unreachable)) |ptr| return ptr; try await (async self.native_libc.data.findNative(self.loop) catch unreachable); self.native_libc.resolve(); return &self.native_libc.data; } /// Must be called only once, ever. Sets global state. pub fn setLlvmArgv(allocator: *Allocator, llvm_argv: []const []const u8) !void { if (llvm_argv.len != 0) { var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(allocator, [][]const []const u8{ [][]const u8{"zig (LLVM option parsing)"}, llvm_argv, }); defer c_compatible_args.deinit(); c.ZigLLVMParseCommandLineOptions(llvm_argv.len + 1, c_compatible_args.ptr); } } }; pub const LlvmHandle = struct { node: *std.atomic.Stack(llvm.ContextRef).Node, pub fn release(self: LlvmHandle, zig_compiler: *ZigCompiler) void { zig_compiler.llvm_handle_pool.push(self.node); } }; pub const Compilation = struct { zig_compiler: *ZigCompiler, loop: *event.Loop, name: Buffer, llvm_triple: Buffer, root_src_path: ?[]const u8, target: Target, llvm_target: llvm.TargetRef, build_mode: builtin.Mode, zig_lib_dir: []const u8, zig_std_dir: []const u8, /// lazily created when we need it tmp_dir: event.Future(BuildError![]u8), version_major: u32, version_minor: u32, version_patch: u32, linker_script: ?[]const u8, out_h_path: ?[]const u8, is_test: bool, each_lib_rpath: bool, strip: bool, is_static: bool, linker_rdynamic: bool, clang_argv: []const []const u8, lib_dirs: []const []const u8, rpath_list: []const []const u8, assembly_files: []const []const u8, /// paths that are explicitly provided by the user to link against link_objects: []const []const u8, /// functions that have their own objects that we need to link /// it uses an optional pointer so that tombstone removals are possible fn_link_set: event.Locked(FnLinkSet), pub const FnLinkSet = std.LinkedList(?*Value.Fn); windows_subsystem_windows: bool, windows_subsystem_console: bool, link_libs_list: ArrayList(*LinkLib), libc_link_lib: ?*LinkLib, err_color: errmsg.Color, verbose_tokenize: bool, verbose_ast_tree: bool, verbose_ast_fmt: bool, verbose_cimport: bool, verbose_ir: bool, verbose_llvm_ir: bool, verbose_link: bool, darwin_frameworks: []const []const u8, darwin_version_min: DarwinVersionMin, test_filters: []const []const u8, test_name_prefix: ?[]const u8, emit_file_type: Emit, kind: Kind, link_out_file: ?[]const u8, events: *event.Channel(Event), exported_symbol_names: event.Locked(Decl.Table), /// Before code generation starts, must wait on this group to make sure /// the build is complete. prelink_group: event.Group(BuildError!void), compile_errors: event.Locked(CompileErrList), meta_type: *Type.MetaType, void_type: *Type.Void, bool_type: *Type.Bool, noreturn_type: *Type.NoReturn, comptime_int_type: *Type.ComptimeInt, u8_type: *Type.Int, void_value: *Value.Void, true_value: *Value.Bool, false_value: *Value.Bool, noreturn_value: *Value.NoReturn, target_machine: llvm.TargetMachineRef, target_data_ref: llvm.TargetDataRef, target_layout_str: [*]u8, target_ptr_bits: u32, /// for allocating things which have the same lifetime as this Compilation arena_allocator: std.heap.ArenaAllocator, root_package: *Package, std_package: *Package, override_libc: ?*LibCInstallation, /// need to wait on this group before deinitializing deinit_group: event.Group(void), destroy_handle: promise, main_loop_handle: promise, main_loop_future: event.Future(void), have_err_ret_tracing: bool, /// not locked because it is read-only primitive_type_table: TypeTable, int_type_table: event.Locked(IntTypeTable), array_type_table: event.Locked(ArrayTypeTable), ptr_type_table: event.Locked(PtrTypeTable), fn_type_table: event.Locked(FnTypeTable), c_int_types: [CInt.list.len]*Type.Int, fs_watch: *fs.Watch(*Scope.Root), const IntTypeTable = std.HashMap(*const Type.Int.Key, *Type.Int, Type.Int.Key.hash, Type.Int.Key.eql); const ArrayTypeTable = std.HashMap(*const Type.Array.Key, *Type.Array, Type.Array.Key.hash, Type.Array.Key.eql); const PtrTypeTable = std.HashMap(*const Type.Pointer.Key, *Type.Pointer, Type.Pointer.Key.hash, Type.Pointer.Key.eql); const FnTypeTable = std.HashMap(*const Type.Fn.Key, *Type.Fn, Type.Fn.Key.hash, Type.Fn.Key.eql); const TypeTable = std.HashMap([]const u8, *Type, mem.hash_slice_u8, mem.eql_slice_u8); const CompileErrList = std.ArrayList(*Msg); // TODO handle some of these earlier and report them in a way other than error codes pub const BuildError = error{ OutOfMemory, EndOfStream, IsDir, Unexpected, SystemResources, SharingViolation, PathAlreadyExists, FileNotFound, AccessDenied, PipeBusy, FileTooBig, SymLinkLoop, ProcessFdQuotaExceeded, NameTooLong, SystemFdQuotaExceeded, NoDevice, NoSpaceLeft, NotDir, FileSystem, OperationAborted, IoPending, BrokenPipe, WouldBlock, FileClosed, DestinationAddressRequired, DiskQuota, InputOutput, NoStdHandles, Overflow, NotSupported, BufferTooSmall, Unimplemented, // TODO remove this one SemanticAnalysisFailed, // TODO remove this one ReadOnlyFileSystem, LinkQuotaExceeded, EnvironmentVariableNotFound, AppDataDirUnavailable, LinkFailed, LibCRequiredButNotProvidedOrFound, LibCMissingDynamicLinker, InvalidDarwinVersionString, UnsupportedLinkArchitecture, UserResourceLimitReached, InvalidUtf8, BadPathName, }; pub const Event = union(enum) { Ok, Error: BuildError, Fail: []*Msg, }; pub const DarwinVersionMin = union(enum) { None, MacOS: []const u8, Ios: []const u8, }; pub const Kind = enum { Exe, Lib, Obj, }; pub const LinkLib = struct { name: []const u8, path: ?[]const u8, /// the list of symbols we depend on from this lib symbols: ArrayList([]u8), provided_explicitly: bool, }; pub const Emit = enum { Binary, Assembly, LlvmIr, }; pub fn create( zig_compiler: *ZigCompiler, name: []const u8, root_src_path: ?[]const u8, target: Target, kind: Kind, build_mode: builtin.Mode, is_static: bool, zig_lib_dir: []const u8, ) !*Compilation { var optional_comp: ?*Compilation = null; const handle = try async<zig_compiler.loop.allocator> createAsync( &optional_comp, zig_compiler, name, root_src_path, target, kind, build_mode, is_static, zig_lib_dir, ); return optional_comp orelse if (getAwaitResult( zig_compiler.loop.allocator, handle, )) |_| unreachable else |err| err; } async fn createAsync( out_comp: *?*Compilation, zig_compiler: *ZigCompiler, name: []const u8, root_src_path: ?[]const u8, target: Target, kind: Kind, build_mode: builtin.Mode, is_static: bool, zig_lib_dir: []const u8, ) !void { // workaround for https://github.com/ziglang/zig/issues/1194 suspend { resume @handle(); } const loop = zig_compiler.loop; var comp = Compilation{ .loop = loop, .arena_allocator = std.heap.ArenaAllocator.init(loop.allocator), .zig_compiler = zig_compiler, .events = undefined, .root_src_path = root_src_path, .target = target, .llvm_target = undefined, .kind = kind, .build_mode = build_mode, .zig_lib_dir = zig_lib_dir, .zig_std_dir = undefined, .tmp_dir = event.Future(BuildError![]u8).init(loop), .destroy_handle = @handle(), .main_loop_handle = undefined, .main_loop_future = event.Future(void).init(loop), .name = undefined, .llvm_triple = undefined, .version_major = 0, .version_minor = 0, .version_patch = 0, .verbose_tokenize = false, .verbose_ast_tree = false, .verbose_ast_fmt = false, .verbose_cimport = false, .verbose_ir = false, .verbose_llvm_ir = false, .verbose_link = false, .linker_script = null, .out_h_path = null, .is_test = false, .each_lib_rpath = false, .strip = false, .is_static = is_static, .linker_rdynamic = false, .clang_argv = [][]const u8{}, .lib_dirs = [][]const u8{}, .rpath_list = [][]const u8{}, .assembly_files = [][]const u8{}, .link_objects = [][]const u8{}, .fn_link_set = event.Locked(FnLinkSet).init(loop, FnLinkSet.init()), .windows_subsystem_windows = false, .windows_subsystem_console = false, .link_libs_list = undefined, .libc_link_lib = null, .err_color = errmsg.Color.Auto, .darwin_frameworks = [][]const u8{}, .darwin_version_min = DarwinVersionMin.None, .test_filters = [][]const u8{}, .test_name_prefix = null, .emit_file_type = Emit.Binary, .link_out_file = null, .exported_symbol_names = event.Locked(Decl.Table).init(loop, Decl.Table.init(loop.allocator)), .prelink_group = event.Group(BuildError!void).init(loop), .deinit_group = event.Group(void).init(loop), .compile_errors = event.Locked(CompileErrList).init(loop, CompileErrList.init(loop.allocator)), .int_type_table = event.Locked(IntTypeTable).init(loop, IntTypeTable.init(loop.allocator)), .array_type_table = event.Locked(ArrayTypeTable).init(loop, ArrayTypeTable.init(loop.allocator)), .ptr_type_table = event.Locked(PtrTypeTable).init(loop, PtrTypeTable.init(loop.allocator)), .fn_type_table = event.Locked(FnTypeTable).init(loop, FnTypeTable.init(loop.allocator)), .c_int_types = undefined, .meta_type = undefined, .void_type = undefined, .void_value = undefined, .bool_type = undefined, .true_value = undefined, .false_value = undefined, .noreturn_type = undefined, .noreturn_value = undefined, .comptime_int_type = undefined, .u8_type = undefined, .target_machine = undefined, .target_data_ref = undefined, .target_layout_str = undefined, .target_ptr_bits = target.getArchPtrBitWidth(), .root_package = undefined, .std_package = undefined, .override_libc = null, .have_err_ret_tracing = false, .primitive_type_table = undefined, .fs_watch = undefined, }; comp.link_libs_list = ArrayList(*LinkLib).init(comp.arena()); comp.primitive_type_table = TypeTable.init(comp.arena()); defer { comp.int_type_table.private_data.deinit(); comp.array_type_table.private_data.deinit(); comp.ptr_type_table.private_data.deinit(); comp.fn_type_table.private_data.deinit(); comp.arena_allocator.deinit(); } comp.name = try Buffer.init(comp.arena(), name); comp.llvm_triple = try target.getTriple(comp.arena()); comp.llvm_target = try Target.llvmTargetFromTriple(comp.llvm_triple); comp.zig_std_dir = try std.os.path.join(comp.arena(), zig_lib_dir, "std"); const opt_level = switch (build_mode) { builtin.Mode.Debug => llvm.CodeGenLevelNone, else => llvm.CodeGenLevelAggressive, }; const reloc_mode = if (is_static) llvm.RelocStatic else llvm.RelocPIC; // LLVM creates invalid binaries on Windows sometimes. // See https://github.com/ziglang/zig/issues/508 // As a workaround we do not use target native features on Windows. var target_specific_cpu_args: ?[*]u8 = null; var target_specific_cpu_features: ?[*]u8 = null; defer llvm.DisposeMessage(target_specific_cpu_args); defer llvm.DisposeMessage(target_specific_cpu_features); if (target == Target.Native and !target.isWindows()) { target_specific_cpu_args = llvm.GetHostCPUName() orelse return error.OutOfMemory; target_specific_cpu_features = llvm.GetNativeFeatures() orelse return error.OutOfMemory; } comp.target_machine = llvm.CreateTargetMachine( comp.llvm_target, comp.llvm_triple.ptr(), target_specific_cpu_args orelse c"", target_specific_cpu_features orelse c"", opt_level, reloc_mode, llvm.CodeModelDefault, ) orelse return error.OutOfMemory; defer llvm.DisposeTargetMachine(comp.target_machine); comp.target_data_ref = llvm.CreateTargetDataLayout(comp.target_machine) orelse return error.OutOfMemory; defer llvm.DisposeTargetData(comp.target_data_ref); comp.target_layout_str = llvm.CopyStringRepOfTargetData(comp.target_data_ref) orelse return error.OutOfMemory; defer llvm.DisposeMessage(comp.target_layout_str); comp.events = try event.Channel(Event).create(comp.loop, 0); defer comp.events.destroy(); if (root_src_path) |root_src| { const dirname = std.os.path.dirname(root_src) orelse "."; const basename = std.os.path.basename(root_src); comp.root_package = try Package.create(comp.arena(), dirname, basename); comp.std_package = try Package.create(comp.arena(), comp.zig_std_dir, "index.zig"); try comp.root_package.add("std", comp.std_package); } else { comp.root_package = try Package.create(comp.arena(), ".", ""); } comp.fs_watch = try fs.Watch(*Scope.Root).create(loop, 16); defer comp.fs_watch.destroy(); try comp.initTypes(); defer comp.primitive_type_table.deinit(); comp.main_loop_handle = async comp.mainLoop() catch unreachable; // Set this to indicate that initialization completed successfully. // from here on out we must not return an error. // This must occur before the first suspend/await. out_comp.* = &comp; // This suspend is resumed by destroy() suspend; // From here on is cleanup. await (async comp.deinit_group.wait() catch unreachable); if (comp.tmp_dir.getOrNull()) |tmp_dir_result| if (tmp_dir_result.*) |tmp_dir| { // TODO evented I/O? os.deleteTree(comp.arena(), tmp_dir) catch {}; } else |_| {}; } /// it does ref the result because it could be an arbitrary integer size pub async fn getPrimitiveType(comp: *Compilation, name: []const u8) !?*Type { if (name.len >= 2) { switch (name[0]) { 'i', 'u' => blk: { for (name[1..]) |byte| switch (byte) { '0'...'9' => {}, else => break :blk, }; const is_signed = name[0] == 'i'; const bit_count = std.fmt.parseUnsigned(u32, name[1..], 10) catch |err| switch (err) { error.Overflow => return error.Overflow, error.InvalidCharacter => unreachable, // we just checked the characters above }; const int_type = try await (async Type.Int.get(comp, Type.Int.Key{ .bit_count = bit_count, .is_signed = is_signed, }) catch unreachable); errdefer int_type.base.base.deref(); return &int_type.base; }, else => {}, } } if (comp.primitive_type_table.get(name)) |entry| { entry.value.base.ref(); return entry.value; } return null; } fn initTypes(comp: *Compilation) !void { comp.meta_type = try comp.arena().create(Type.MetaType{ .base = Type{ .name = "type", .base = Value{ .id = Value.Id.Type, .typ = undefined, .ref_count = std.atomic.Int(usize).init(3), // 3 because it references itself twice }, .id = builtin.TypeId.Type, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, .value = undefined, }); comp.meta_type.value = &comp.meta_type.base; comp.meta_type.base.base.typ = &comp.meta_type.base; assert((try comp.primitive_type_table.put(comp.meta_type.base.name, &comp.meta_type.base)) == null); comp.void_type = try comp.arena().create(Type.Void{ .base = Type{ .name = "void", .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.Void, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, }); assert((try comp.primitive_type_table.put(comp.void_type.base.name, &comp.void_type.base)) == null); comp.noreturn_type = try comp.arena().create(Type.NoReturn{ .base = Type{ .name = "noreturn", .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.NoReturn, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, }); assert((try comp.primitive_type_table.put(comp.noreturn_type.base.name, &comp.noreturn_type.base)) == null); comp.comptime_int_type = try comp.arena().create(Type.ComptimeInt{ .base = Type{ .name = "comptime_int", .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.ComptimeInt, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, }); assert((try comp.primitive_type_table.put(comp.comptime_int_type.base.name, &comp.comptime_int_type.base)) == null); comp.bool_type = try comp.arena().create(Type.Bool{ .base = Type{ .name = "bool", .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.Bool, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, }); assert((try comp.primitive_type_table.put(comp.bool_type.base.name, &comp.bool_type.base)) == null); comp.void_value = try comp.arena().create(Value.Void{ .base = Value{ .id = Value.Id.Void, .typ = &Type.Void.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, }); comp.true_value = try comp.arena().create(Value.Bool{ .base = Value{ .id = Value.Id.Bool, .typ = &Type.Bool.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .x = true, }); comp.false_value = try comp.arena().create(Value.Bool{ .base = Value{ .id = Value.Id.Bool, .typ = &Type.Bool.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .x = false, }); comp.noreturn_value = try comp.arena().create(Value.NoReturn{ .base = Value{ .id = Value.Id.NoReturn, .typ = &Type.NoReturn.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, }); for (CInt.list) |cint, i| { const c_int_type = try comp.arena().create(Type.Int{ .base = Type{ .name = cint.zig_name, .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.Int, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, .key = Type.Int.Key{ .is_signed = cint.is_signed, .bit_count = comp.target.cIntTypeSizeInBits(cint.id), }, .garbage_node = undefined, }); comp.c_int_types[i] = c_int_type; assert((try comp.primitive_type_table.put(cint.zig_name, &c_int_type.base)) == null); } comp.u8_type = try comp.arena().create(Type.Int{ .base = Type{ .name = "u8", .base = Value{ .id = Value.Id.Type, .typ = &Type.MetaType.get(comp).base, .ref_count = std.atomic.Int(usize).init(1), }, .id = builtin.TypeId.Int, .abi_alignment = Type.AbiAlignment.init(comp.loop), }, .key = Type.Int.Key{ .is_signed = false, .bit_count = 8, }, .garbage_node = undefined, }); assert((try comp.primitive_type_table.put(comp.u8_type.base.name, &comp.u8_type.base)) == null); } pub fn destroy(self: *Compilation) void { cancel self.main_loop_handle; resume self.destroy_handle; } fn start(self: *Compilation) void { self.main_loop_future.resolve(); } async fn mainLoop(self: *Compilation) void { // wait until start() is called _ = await (async self.main_loop_future.get() catch unreachable); var build_result = await (async self.initialCompile() catch unreachable); while (true) { const link_result = if (build_result) blk: { break :blk await (async self.maybeLink() catch unreachable); } else |err| err; // this makes a handy error return trace and stack trace in debug mode if (std.debug.runtime_safety) { link_result catch unreachable; } const compile_errors = blk: { const held = await (async self.compile_errors.acquire() catch unreachable); defer held.release(); break :blk held.value.toOwnedSlice(); }; if (link_result) |_| { if (compile_errors.len == 0) { await (async self.events.put(Event.Ok) catch unreachable); } else { await (async self.events.put(Event{ .Fail = compile_errors }) catch unreachable); } } else |err| { // if there's an error then the compile errors have dangling references self.gpa().free(compile_errors); await (async self.events.put(Event{ .Error = err }) catch unreachable); } // First, get an item from the watch channel, waiting on the channel. var group = event.Group(BuildError!void).init(self.loop); { const ev = (await (async self.fs_watch.channel.get() catch unreachable)) catch |err| { build_result = err; continue; }; const root_scope = ev.data; group.call(rebuildFile, self, root_scope) catch |err| { build_result = err; continue; }; } // Next, get all the items from the channel that are buffered up. while (await (async self.fs_watch.channel.getOrNull() catch unreachable)) |ev_or_err| { if (ev_or_err) |ev| { const root_scope = ev.data; group.call(rebuildFile, self, root_scope) catch |err| { build_result = err; continue; }; } else |err| { build_result = err; continue; } } build_result = await (async group.wait() catch unreachable); } } async fn rebuildFile(self: *Compilation, root_scope: *Scope.Root) !void { const tree_scope = blk: { const source_code = (await (async fs.readFile( self.loop, root_scope.realpath, max_src_size, ) catch unreachable)) catch |err| { try self.addCompileErrorCli(root_scope.realpath, "unable to open: {}", @errorName(err)); return; }; errdefer self.gpa().free(source_code); const tree = try self.gpa().createOne(ast.Tree); tree.* = try std.zig.parse(self.gpa(), source_code); errdefer { tree.deinit(); self.gpa().destroy(tree); } break :blk try Scope.AstTree.create(self, tree, root_scope); }; defer tree_scope.base.deref(self); var error_it = tree_scope.tree.errors.iterator(0); while (error_it.next()) |parse_error| { const msg = try Msg.createFromParseErrorAndScope(self, tree_scope, parse_error); errdefer msg.destroy(); try await (async self.addCompileErrorAsync(msg) catch unreachable); } if (tree_scope.tree.errors.len != 0) { return; } const locked_table = await (async root_scope.decls.table.acquireWrite() catch unreachable); defer locked_table.release(); var decl_group = event.Group(BuildError!void).init(self.loop); defer decl_group.deinit(); try await try async self.rebuildChangedDecls( &decl_group, locked_table.value, root_scope.decls, &tree_scope.tree.root_node.decls, tree_scope, ); try await (async decl_group.wait() catch unreachable); } async fn rebuildChangedDecls( self: *Compilation, group: *event.Group(BuildError!void), locked_table: *Decl.Table, decl_scope: *Scope.Decls, ast_decls: *ast.Node.Root.DeclList, tree_scope: *Scope.AstTree, ) !void { var existing_decls = try locked_table.clone(); defer existing_decls.deinit(); var ast_it = ast_decls.iterator(0); while (ast_it.next()) |decl_ptr| { const decl = decl_ptr.*; switch (decl.id) { ast.Node.Id.Comptime => { const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", decl); // TODO connect existing comptime decls to updated source files try self.prelink_group.call(addCompTimeBlock, self, tree_scope, &decl_scope.base, comptime_node); }, ast.Node.Id.VarDecl => @panic("TODO"), ast.Node.Id.FnProto => { const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); const name = if (fn_proto.name_token) |name_token| tree_scope.tree.tokenSlice(name_token) else { try self.addCompileError(tree_scope, Span{ .first = fn_proto.fn_token, .last = fn_proto.fn_token + 1, }, "missing function name"); continue; }; if (existing_decls.remove(name)) |entry| { // compare new code to existing if (entry.value.cast(Decl.Fn)) |existing_fn_decl| { // Just compare the old bytes to the new bytes of the top level decl. // Even if the AST is technically the same, we want error messages to display // from the most recent source. const old_decl_src = existing_fn_decl.base.tree_scope.tree.getNodeSource( &existing_fn_decl.fn_proto.base, ); const new_decl_src = tree_scope.tree.getNodeSource(&fn_proto.base); if (mem.eql(u8, old_decl_src, new_decl_src)) { // it's the same, we can skip this decl continue; } else { @panic("TODO decl changed implementation"); // Add the new thing before dereferencing the old thing. This way we don't end // up pointlessly re-creating things we end up using in the new thing. } } else { @panic("TODO decl changed kind"); } } else { // add new decl const fn_decl = try self.gpa().create(Decl.Fn{ .base = Decl{ .id = Decl.Id.Fn, .name = name, .visib = parseVisibToken(tree_scope.tree, fn_proto.visib_token), .resolution = event.Future(BuildError!void).init(self.loop), .parent_scope = &decl_scope.base, .tree_scope = tree_scope, }, .value = Decl.Fn.Val{ .Unresolved = {} }, .fn_proto = fn_proto, }); tree_scope.base.ref(); errdefer self.gpa().destroy(fn_decl); try group.call(addTopLevelDecl, self, &fn_decl.base, locked_table); } }, ast.Node.Id.TestDecl => @panic("TODO"), else => unreachable, } } var existing_decl_it = existing_decls.iterator(); while (existing_decl_it.next()) |entry| { // this decl was deleted const existing_decl = entry.value; @panic("TODO handle decl deletion"); } } async fn initialCompile(self: *Compilation) !void { if (self.root_src_path) |root_src_path| { const root_scope = blk: { // TODO async/await os.path.real const root_src_real_path = os.path.realAlloc(self.gpa(), root_src_path) catch |err| { try self.addCompileErrorCli(root_src_path, "unable to open: {}", @errorName(err)); return; }; errdefer self.gpa().free(root_src_real_path); break :blk try Scope.Root.create(self, root_src_real_path); }; defer root_scope.base.deref(self); assert((try await try async self.fs_watch.addFile(root_scope.realpath, root_scope)) == null); try await try async self.rebuildFile(root_scope); } } async fn maybeLink(self: *Compilation) !void { (await (async self.prelink_group.wait() catch unreachable)) catch |err| switch (err) { error.SemanticAnalysisFailed => {}, else => return err, }; const any_prelink_errors = blk: { const compile_errors = await (async self.compile_errors.acquire() catch unreachable); defer compile_errors.release(); break :blk compile_errors.value.len != 0; }; if (!any_prelink_errors) { try await (async link(self) catch unreachable); } } /// caller takes ownership of resulting Code async fn genAndAnalyzeCode( comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, node: *ast.Node, expected_type: ?*Type, ) !*ir.Code { const unanalyzed_code = try await (async ir.gen( comp, node, tree_scope, scope, ) catch unreachable); defer unanalyzed_code.destroy(comp.gpa()); if (comp.verbose_ir) { std.debug.warn("unanalyzed:\n"); unanalyzed_code.dump(); } const analyzed_code = try await (async ir.analyze( comp, unanalyzed_code, expected_type, ) catch unreachable); errdefer analyzed_code.destroy(comp.gpa()); if (comp.verbose_ir) { std.debug.warn("analyzed:\n"); analyzed_code.dump(); } return analyzed_code; } async fn addCompTimeBlock( comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, comptime_node: *ast.Node.Comptime, ) !void { const void_type = Type.Void.get(comp); defer void_type.base.base.deref(comp); const analyzed_code = (await (async genAndAnalyzeCode( comp, tree_scope, scope, comptime_node.expr, &void_type.base, ) catch unreachable)) catch |err| switch (err) { // This poison value should not cause the errdefers to run. It simply means // that comp.compile_errors is populated. error.SemanticAnalysisFailed => return {}, else => return err, }; analyzed_code.destroy(comp.gpa()); } async fn addTopLevelDecl( self: *Compilation, decl: *Decl, locked_table: *Decl.Table, ) !void { const is_export = decl.isExported(decl.tree_scope.tree); if (is_export) { try self.prelink_group.call(verifyUniqueSymbol, self, decl); try self.prelink_group.call(resolveDecl, self, decl); } const gop = try locked_table.getOrPut(decl.name); if (gop.found_existing) { try self.addCompileError(decl.tree_scope, decl.getSpan(), "redefinition of '{}'", decl.name); // TODO note: other definition here } else { gop.kv.value = decl; } } fn addCompileError(self: *Compilation, tree_scope: *Scope.AstTree, span: Span, comptime fmt: []const u8, args: ...) !void { const text = try std.fmt.allocPrint(self.gpa(), fmt, args); errdefer self.gpa().free(text); const msg = try Msg.createFromScope(self, tree_scope, span, text); errdefer msg.destroy(); try self.prelink_group.call(addCompileErrorAsync, self, msg); } fn addCompileErrorCli(self: *Compilation, realpath: []const u8, comptime fmt: []const u8, args: ...) !void { const text = try std.fmt.allocPrint(self.gpa(), fmt, args); errdefer self.gpa().free(text); const msg = try Msg.createFromCli(self, realpath, text); errdefer msg.destroy(); try self.prelink_group.call(addCompileErrorAsync, self, msg); } async fn addCompileErrorAsync( self: *Compilation, msg: *Msg, ) !void { errdefer msg.destroy(); const compile_errors = await (async self.compile_errors.acquire() catch unreachable); defer compile_errors.release(); try compile_errors.value.append(msg); } async fn verifyUniqueSymbol(self: *Compilation, decl: *Decl) !void { const exported_symbol_names = await (async self.exported_symbol_names.acquire() catch unreachable); defer exported_symbol_names.release(); if (try exported_symbol_names.value.put(decl.name, decl)) |other_decl| { try self.addCompileError( decl.tree_scope, decl.getSpan(), "exported symbol collision: '{}'", decl.name, ); // TODO add error note showing location of other symbol } } pub fn haveLibC(self: *Compilation) bool { return self.libc_link_lib != null; } pub fn addLinkLib(self: *Compilation, name: []const u8, provided_explicitly: bool) !*LinkLib { const is_libc = mem.eql(u8, name, "c"); if (is_libc) { if (self.libc_link_lib) |libc_link_lib| { return libc_link_lib; } } for (self.link_libs_list.toSliceConst()) |existing_lib| { if (mem.eql(u8, name, existing_lib.name)) { return existing_lib; } } const link_lib = try self.gpa().create(LinkLib{ .name = name, .path = null, .provided_explicitly = provided_explicitly, .symbols = ArrayList([]u8).init(self.gpa()), }); try self.link_libs_list.append(link_lib); if (is_libc) { self.libc_link_lib = link_lib; // get a head start on looking for the native libc if (self.target == Target.Native and self.override_libc == null) { try self.deinit_group.call(startFindingNativeLibC, self); } } return link_lib; } /// cancels itself so no need to await or cancel the promise. async fn startFindingNativeLibC(self: *Compilation) void { await (async self.loop.yield() catch unreachable); // we don't care if it fails, we're just trying to kick off the future resolution _ = (await (async self.zig_compiler.getNativeLibC() catch unreachable)) catch return; } /// General Purpose Allocator. Must free when done. fn gpa(self: Compilation) *mem.Allocator { return self.loop.allocator; } /// Arena Allocator. Automatically freed when the Compilation is destroyed. fn arena(self: *Compilation) *mem.Allocator { return &self.arena_allocator.allocator; } /// If the temporary directory for this compilation has not been created, it creates it. /// Then it creates a random file name in that dir and returns it. pub async fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer { const tmp_dir = try await (async self.getTmpDir() catch unreachable); const file_prefix = await (async self.getRandomFileName() catch unreachable); const file_name = try std.fmt.allocPrint(self.gpa(), "{}{}", file_prefix[0..], suffix); defer self.gpa().free(file_name); const full_path = try os.path.join(self.gpa(), tmp_dir, file_name[0..]); errdefer self.gpa().free(full_path); return Buffer.fromOwnedSlice(self.gpa(), full_path); } /// If the temporary directory for this Compilation has not been created, creates it. /// Then returns it. The directory is unique to this Compilation and cleaned up when /// the Compilation deinitializes. async fn getTmpDir(self: *Compilation) ![]const u8 { if (await (async self.tmp_dir.start() catch unreachable)) |ptr| return ptr.*; self.tmp_dir.data = await (async self.getTmpDirImpl() catch unreachable); self.tmp_dir.resolve(); return self.tmp_dir.data; } async fn getTmpDirImpl(self: *Compilation) ![]u8 { const comp_dir_name = await (async self.getRandomFileName() catch unreachable); const zig_dir_path = try getZigDir(self.gpa()); defer self.gpa().free(zig_dir_path); const tmp_dir = try os.path.join(self.arena(), zig_dir_path, comp_dir_name[0..]); try os.makePath(self.gpa(), tmp_dir); return tmp_dir; } async fn getRandomFileName(self: *Compilation) [12]u8 { // here we replace the standard +/ with -_ so that it can be used in a file name const b64_fs_encoder = std.base64.Base64Encoder.init( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", std.base64.standard_pad_char, ); var rand_bytes: [9]u8 = undefined; { const held = await (async self.zig_compiler.prng.acquire() catch unreachable); defer held.release(); held.value.random.bytes(rand_bytes[0..]); } var result: [12]u8 = undefined; b64_fs_encoder.encode(result[0..], rand_bytes); return result; } fn registerGarbage(comp: *Compilation, comptime T: type, node: *std.atomic.Stack(*T).Node) void { // TODO put the garbage somewhere } /// Returns a value which has been ref()'d once async fn analyzeConstValue( comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, node: *ast.Node, expected_type: *Type, ) !*Value { const analyzed_code = try await (async comp.genAndAnalyzeCode(tree_scope, scope, node, expected_type) catch unreachable); defer analyzed_code.destroy(comp.gpa()); return analyzed_code.getCompTimeResult(comp); } async fn analyzeTypeExpr(comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, node: *ast.Node) !*Type { const meta_type = &Type.MetaType.get(comp).base; defer meta_type.base.deref(comp); const result_val = try await (async comp.analyzeConstValue(tree_scope, scope, node, meta_type) catch unreachable); errdefer result_val.base.deref(comp); return result_val.cast(Type).?; } /// This declaration has been blessed as going into the final code generation. pub async fn resolveDecl(comp: *Compilation, decl: *Decl) !void { if (await (async decl.resolution.start() catch unreachable)) |ptr| return ptr.*; decl.resolution.data = try await (async generateDecl(comp, decl) catch unreachable); decl.resolution.resolve(); return decl.resolution.data; } }; fn parseVisibToken(tree: *ast.Tree, optional_token_index: ?ast.TokenIndex) Visib { if (optional_token_index) |token_index| { const token = tree.tokens.at(token_index); assert(token.id == Token.Id.Keyword_pub); return Visib.Pub; } else { return Visib.Private; } } /// The function that actually does the generation. async fn generateDecl(comp: *Compilation, decl: *Decl) !void { switch (decl.id) { Decl.Id.Var => @panic("TODO"), Decl.Id.Fn => { const fn_decl = @fieldParentPtr(Decl.Fn, "base", decl); return await (async generateDeclFn(comp, fn_decl) catch unreachable); }, Decl.Id.CompTime => @panic("TODO"), } } async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void { const tree_scope = fn_decl.base.tree_scope; const body_node = fn_decl.fn_proto.body_node orelse return await (async generateDeclFnProto(comp, fn_decl) catch unreachable); const fndef_scope = try Scope.FnDef.create(comp, fn_decl.base.parent_scope); defer fndef_scope.base.deref(comp); const fn_type = try await (async analyzeFnType(comp, tree_scope, fn_decl.base.parent_scope, fn_decl.fn_proto) catch unreachable); defer fn_type.base.base.deref(comp); var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name); var symbol_name_consumed = false; errdefer if (!symbol_name_consumed) symbol_name.deinit(); // The Decl.Fn owns the initial 1 reference count const fn_val = try Value.Fn.create(comp, fn_type, fndef_scope, symbol_name); fn_decl.value = Decl.Fn.Val{ .Fn = fn_val }; symbol_name_consumed = true; // Define local parameter variables for (fn_type.key.data.Normal.params) |param, i| { //AstNode *param_decl_node = get_param_decl_node(fn_table_entry, i); const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", fn_decl.fn_proto.params.at(i).*); const name_token = param_decl.name_token orelse { try comp.addCompileError(tree_scope, Span{ .first = param_decl.firstToken(), .last = param_decl.type_node.firstToken(), }, "missing parameter name"); return error.SemanticAnalysisFailed; }; const param_name = tree_scope.tree.tokenSlice(name_token); // if (is_noalias && get_codegen_ptr_type(param_type) == nullptr) { // add_node_error(g, param_decl_node, buf_sprintf("noalias on non-pointer parameter")); // } // TODO check for shadowing const var_scope = try Scope.Var.createParam( comp, fn_val.child_scope, param_name, &param_decl.base, i, param.typ, ); fn_val.child_scope = &var_scope.base; try fn_type.non_key.Normal.variable_list.append(var_scope); } const analyzed_code = try await (async comp.genAndAnalyzeCode( tree_scope, fn_val.child_scope, body_node, fn_type.key.data.Normal.return_type, ) catch unreachable); errdefer analyzed_code.destroy(comp.gpa()); assert(fn_val.block_scope != null); // Kick off rendering to LLVM module, but it doesn't block the fn decl // analysis from being complete. try comp.prelink_group.call(codegen.renderToLlvm, comp, fn_val, analyzed_code); try comp.prelink_group.call(addFnToLinkSet, comp, fn_val); } async fn addFnToLinkSet(comp: *Compilation, fn_val: *Value.Fn) void { fn_val.base.ref(); defer fn_val.base.deref(comp); fn_val.link_set_node.data = fn_val; const held = await (async comp.fn_link_set.acquire() catch unreachable); defer held.release(); held.value.append(fn_val.link_set_node); } fn getZigDir(allocator: *mem.Allocator) ![]u8 { return os.getAppDataDir(allocator, "zig"); } async fn analyzeFnType( comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, fn_proto: *ast.Node.FnProto, ) !*Type.Fn { const return_type_node = switch (fn_proto.return_type) { ast.Node.FnProto.ReturnType.Explicit => |n| n, ast.Node.FnProto.ReturnType.InferErrorSet => |n| n, }; const return_type = try await (async comp.analyzeTypeExpr(tree_scope, scope, return_type_node) catch unreachable); return_type.base.deref(comp); var params = ArrayList(Type.Fn.Param).init(comp.gpa()); var params_consumed = false; defer if (!params_consumed) { for (params.toSliceConst()) |param| { param.typ.base.deref(comp); } params.deinit(); }; { var it = fn_proto.params.iterator(0); while (it.next()) |param_node_ptr| { const param_node = param_node_ptr.*.cast(ast.Node.ParamDecl).?; const param_type = try await (async comp.analyzeTypeExpr(tree_scope, scope, param_node.type_node) catch unreachable); errdefer param_type.base.deref(comp); try params.append(Type.Fn.Param{ .typ = param_type, .is_noalias = param_node.noalias_token != null, }); } } const key = Type.Fn.Key{ .alignment = null, .data = Type.Fn.Key.Data{ .Normal = Type.Fn.Key.Normal{ .return_type = return_type, .params = params.toOwnedSlice(), .is_var_args = false, // TODO .cc = Type.Fn.CallingConvention.Auto, // TODO }, }, }; params_consumed = true; var key_consumed = false; defer if (!key_consumed) { for (key.data.Normal.params) |param| { param.typ.base.deref(comp); } comp.gpa().free(key.data.Normal.params); }; const fn_type = try await (async Type.Fn.get(comp, key) catch unreachable); key_consumed = true; errdefer fn_type.base.base.deref(comp); return fn_type; } async fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void { const fn_type = try await (async analyzeFnType( comp, fn_decl.base.tree_scope, fn_decl.base.parent_scope, fn_decl.fn_proto, ) catch unreachable); defer fn_type.base.base.deref(comp); var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name); var symbol_name_consumed = false; defer if (!symbol_name_consumed) symbol_name.deinit(); // The Decl.Fn owns the initial 1 reference count const fn_proto_val = try Value.FnProto.create(comp, fn_type, symbol_name); fn_decl.value = Decl.Fn.Val{ .FnProto = fn_proto_val }; symbol_name_consumed = true; } // TODO these are hacks which should probably be solved by the language fn getAwaitResult(allocator: *Allocator, handle: var) @typeInfo(@typeOf(handle)).Promise.child.? { var result: ?@typeInfo(@typeOf(handle)).Promise.child.? = null; cancel (async<allocator> getAwaitResultAsync(handle, &result) catch unreachable); return result.?; } async fn getAwaitResultAsync(handle: var, out: *?@typeInfo(@typeOf(handle)).Promise.child.?) void { out.* = await handle; }
src-self-hosted/compilation.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the least integer value greater than of equal to x. /// /// Special Cases: /// - ceil(+-0) = +-0 /// - ceil(+-inf) = +-inf /// - ceil(nan) = nan pub fn ceil(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => ceil32(x), f64 => ceil64(x), f128 => ceil128(x), else => @compileError("ceil not implemented for " ++ @typeName(T)), }; } fn ceil32(x: f32) f32 { var u = @bitCast(u32, x); var e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 23) { return x; } else if (e >= 0) { m = @as(u32, 0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } math.forceEval(x + 0x1.0p120); if (u >> 31 == 0) { u += m; } u &= ~m; return @bitCast(f32, u); } else { math.forceEval(x + 0x1.0p120); if (u >> 31 != 0) { return -0.0; } else { return 1.0; } } } fn ceil64(x: f64) f64 { const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52 or x == 0) { return x; } if (u >> 63 != 0) { y = x - math.f64_toint + math.f64_toint - x; } else { y = x + math.f64_toint - math.f64_toint - x; } if (e <= 0x3FF - 1) { math.forceEval(y); if (u >> 63 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } fn ceil128(x: f128) f128 { const u = @bitCast(u128, x); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112 or x == 0) return x; if (u >> 127 != 0) { y = x - math.f128_toint + math.f128_toint - x; } else { y = x + math.f128_toint - math.f128_toint - x; } if (e <= 0x3FFF - 1) { math.forceEval(y); if (u >> 127 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } test "math.ceil" { expect(ceil(@as(f32, 0.0)) == ceil32(0.0)); expect(ceil(@as(f64, 0.0)) == ceil64(0.0)); expect(ceil(@as(f128, 0.0)) == ceil128(0.0)); } test "math.ceil32" { expect(ceil32(1.3) == 2.0); expect(ceil32(-1.3) == -1.0); expect(ceil32(0.2) == 1.0); } test "math.ceil64" { expect(ceil64(1.3) == 2.0); expect(ceil64(-1.3) == -1.0); expect(ceil64(0.2) == 1.0); } test "math.ceil128" { expect(ceil128(1.3) == 2.0); expect(ceil128(-1.3) == -1.0); expect(ceil128(0.2) == 1.0); } test "math.ceil32.special" { expect(ceil32(0.0) == 0.0); expect(ceil32(-0.0) == -0.0); expect(math.isPositiveInf(ceil32(math.inf(f32)))); expect(math.isNegativeInf(ceil32(-math.inf(f32)))); expect(math.isNan(ceil32(math.nan(f32)))); } test "math.ceil64.special" { expect(ceil64(0.0) == 0.0); expect(ceil64(-0.0) == -0.0); expect(math.isPositiveInf(ceil64(math.inf(f64)))); expect(math.isNegativeInf(ceil64(-math.inf(f64)))); expect(math.isNan(ceil64(math.nan(f64)))); } test "math.ceil128.special" { expect(ceil128(0.0) == 0.0); expect(ceil128(-0.0) == -0.0); expect(math.isPositiveInf(ceil128(math.inf(f128)))); expect(math.isNegativeInf(ceil128(-math.inf(f128)))); expect(math.isNan(ceil128(math.nan(f128)))); }
lib/std/math/ceil.zig
const std = @import("std"); const mem = std.mem; const NonCanonicalError = std.crypto.errors.NonCanonicalError; /// 2^252 + 27742317777372353535851937790883648493 pub const field_size = [32]u8{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, // 2^252+27742317777372353535851937790883648493 }; /// A compressed scalar pub const CompressedScalar = [32]u8; /// Zero pub const zero = [_]u8{0} ** 32; /// Reject a scalar whose encoding is not canonical. pub fn rejectNonCanonical(s: [32]u8) NonCanonicalError!void { var c: u8 = 0; var n: u8 = 1; var i: usize = 31; while (true) : (i -= 1) { const xs = @as(u16, s[i]); const xfield_size = @as(u16, field_size[i]); c |= @intCast(u8, ((xs -% xfield_size) >> 8) & n); n &= @intCast(u8, ((xs ^ xfield_size) -% 1) >> 8); if (i == 0) break; } if (c == 0) { return error.NonCanonical; } } /// Reduce a scalar to the field size. pub fn reduce(s: [32]u8) [32]u8 { return Scalar.fromBytes(s).toBytes(); } /// Reduce a 64-bytes scalar to the field size. pub fn reduce64(s: [64]u8) [32]u8 { return ScalarDouble.fromBytes64(s).toBytes(); } /// Perform the X25519 "clamping" operation. /// The scalar is then guaranteed to be a multiple of the cofactor. pub fn clamp(s: *[32]u8) callconv(.Inline) void { s[0] &= 248; s[31] = (s[31] & 127) | 64; } /// Return a*b (mod L) pub fn mul(a: [32]u8, b: [32]u8) [32]u8 { return Scalar.fromBytes(a).mul(Scalar.fromBytes(b)).toBytes(); } /// Return a*b+c (mod L) pub fn mulAdd(a: [32]u8, b: [32]u8, c: [32]u8) [32]u8 { return Scalar.fromBytes(a).mul(Scalar.fromBytes(b)).add(Scalar.fromBytes(c)).toBytes(); } /// Return a*8 (mod L) pub fn mul8(s: [32]u8) [32]u8 { var x = Scalar.fromBytes(s); x = x.add(x); x = x.add(x); x = x.add(x); return x.toBytes(); } /// Return a+b (mod L) pub fn add(a: [32]u8, b: [32]u8) [32]u8 { return Scalar.fromBytes(a).add(Scalar.fromBytes(b)).toBytes(); } /// Return -s (mod L) pub fn neg(s: [32]u8) [32]u8 { const fs: [64]u8 = field_size ++ [_]u8{0} ** 32; var sx: [64]u8 = undefined; mem.copy(u8, sx[0..32], s[0..]); mem.set(u8, sx[32..], 0); var carry: u32 = 0; var i: usize = 0; while (i < 64) : (i += 1) { carry = @as(u32, fs[i]) -% sx[i] -% @as(u32, carry); sx[i] = @truncate(u8, carry); carry = (carry >> 8) & 1; } return reduce64(sx); } /// Return (a-b) (mod L) pub fn sub(a: [32]u8, b: [32]u8) [32]u8 { return add(a, neg(b)); } /// A scalar in unpacked representation pub const Scalar = struct { const Limbs = [5]u64; limbs: Limbs = undefined, /// Unpack a 32-byte representation of a scalar pub fn fromBytes(bytes: [32]u8) Scalar { return ScalarDouble.fromBytes32(bytes).reduce(5); } /// Pack a scalar into bytes pub fn toBytes(expanded: *const Scalar) [32]u8 { var bytes: [32]u8 = undefined; var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u64, bytes[i * 7 ..][0..8], expanded.limbs[i]); } mem.writeIntLittle(u32, bytes[i * 7 ..][0..4], @intCast(u32, expanded.limbs[i])); return bytes; } /// Return x+y (mod l) pub fn add(x: Scalar, y: Scalar) Scalar { const carry0 = (x.limbs[0] + y.limbs[0]) >> 56; const t0 = (x.limbs[0] + y.limbs[0]) & 0xffffffffffffff; const t00 = t0; const c0 = carry0; const carry1 = (x.limbs[1] + y.limbs[1] + c0) >> 56; const t1 = (x.limbs[1] + y.limbs[1] + c0) & 0xffffffffffffff; const t10 = t1; const c1 = carry1; const carry2 = (x.limbs[2] + y.limbs[2] + c1) >> 56; const t2 = (x.limbs[2] + y.limbs[2] + c1) & 0xffffffffffffff; const t20 = t2; const c2 = carry2; const carry = (x.limbs[3] + y.limbs[3] + c2) >> 56; const t3 = (x.limbs[3] + y.limbs[3] + c2) & 0xffffffffffffff; const t30 = t3; const c3 = carry; const t4 = x.limbs[4] + y.limbs[4] + c3; const y01: u64 = 5175514460705773; const y11: u64 = 70332060721272408; const y21: u64 = 5342; const y31: u64 = 0; const y41: u64 = 268435456; const b5 = (t00 -% y01) >> 63; const t5 = ((b5 << 56) + t00) -% y01; const b0 = b5; const t01 = t5; const b6 = (t10 -% (y11 + b0)) >> 63; const t6 = ((b6 << 56) + t10) -% (y11 + b0); const b1 = b6; const t11 = t6; const b7 = (t20 -% (y21 + b1)) >> 63; const t7 = ((b7 << 56) + t20) -% (y21 + b1); const b2 = b7; const t21 = t7; const b8 = (t30 -% (y31 + b2)) >> 63; const t8 = ((b8 << 56) + t30) -% (y31 + b2); const b3 = b8; const t31 = t8; const b = (t4 -% (y41 + b3)) >> 63; const t = ((b << 56) + t4) -% (y41 + b3); const b4 = b; const t41 = t; const mask = (b4 -% 1); const z00 = t00 ^ (mask & (t00 ^ t01)); const z10 = t10 ^ (mask & (t10 ^ t11)); const z20 = t20 ^ (mask & (t20 ^ t21)); const z30 = t30 ^ (mask & (t30 ^ t31)); const z40 = t4 ^ (mask & (t4 ^ t41)); return Scalar{ .limbs = .{ z00, z10, z20, z30, z40 } }; } /// Return x*r (mod l) pub fn mul(x: Scalar, y: Scalar) Scalar { const xy000 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[0]); const xy010 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[1]); const xy020 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[2]); const xy030 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[3]); const xy040 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[4]); const xy100 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[0]); const xy110 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[1]); const xy120 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[2]); const xy130 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[3]); const xy140 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[4]); const xy200 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[0]); const xy210 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[1]); const xy220 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[2]); const xy230 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[3]); const xy240 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[4]); const xy300 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[0]); const xy310 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[1]); const xy320 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[2]); const xy330 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[3]); const xy340 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[4]); const xy400 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[0]); const xy410 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[1]); const xy420 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[2]); const xy430 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[3]); const xy440 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[4]); const z00 = xy000; const z10 = xy010 + xy100; const z20 = xy020 + xy110 + xy200; const z30 = xy030 + xy120 + xy210 + xy300; const z40 = xy040 + xy130 + xy220 + xy310 + xy400; const z50 = xy140 + xy230 + xy320 + xy410; const z60 = xy240 + xy330 + xy420; const z70 = xy340 + xy430; const z80 = xy440; const carry0 = z00 >> 56; const t10 = @truncate(u64, z00) & 0xffffffffffffff; const c00 = carry0; const t00 = t10; const carry1 = (z10 + c00) >> 56; const t11 = @truncate(u64, (z10 + c00)) & 0xffffffffffffff; const c10 = carry1; const t12 = t11; const carry2 = (z20 + c10) >> 56; const t13 = @truncate(u64, (z20 + c10)) & 0xffffffffffffff; const c20 = carry2; const t20 = t13; const carry3 = (z30 + c20) >> 56; const t14 = @truncate(u64, (z30 + c20)) & 0xffffffffffffff; const c30 = carry3; const t30 = t14; const carry4 = (z40 + c30) >> 56; const t15 = @truncate(u64, (z40 + c30)) & 0xffffffffffffff; const c40 = carry4; const t40 = t15; const carry5 = (z50 + c40) >> 56; const t16 = @truncate(u64, (z50 + c40)) & 0xffffffffffffff; const c50 = carry5; const t50 = t16; const carry6 = (z60 + c50) >> 56; const t17 = @truncate(u64, (z60 + c50)) & 0xffffffffffffff; const c60 = carry6; const t60 = t17; const carry7 = (z70 + c60) >> 56; const t18 = @truncate(u64, (z70 + c60)) & 0xffffffffffffff; const c70 = carry7; const t70 = t18; const carry8 = (z80 + c70) >> 56; const t19 = @truncate(u64, (z80 + c70)) & 0xffffffffffffff; const c80 = carry8; const t80 = t19; const t90 = (@truncate(u64, c80)); const r0 = t00; const r1 = t12; const r2 = t20; const r3 = t30; const r4 = t40; const r5 = t50; const r6 = t60; const r7 = t70; const r8 = t80; const r9 = t90; const m0: u64 = 5175514460705773; const m1: u64 = 70332060721272408; const m2: u64 = 5342; const m3: u64 = 0; const m4: u64 = 268435456; const mu0: u64 = 44162584779952923; const mu1: u64 = 9390964836247533; const mu2: u64 = 72057594036560134; const mu3: u64 = 72057594037927935; const mu4: u64 = 68719476735; const y_ = (r5 & 0xffffff) << 32; const x_ = r4 >> 24; const z01 = (x_ | y_); const y_0 = (r6 & 0xffffff) << 32; const x_0 = r5 >> 24; const z11 = (x_0 | y_0); const y_1 = (r7 & 0xffffff) << 32; const x_1 = r6 >> 24; const z21 = (x_1 | y_1); const y_2 = (r8 & 0xffffff) << 32; const x_2 = r7 >> 24; const z31 = (x_2 | y_2); const y_3 = (r9 & 0xffffff) << 32; const x_3 = r8 >> 24; const z41 = (x_3 | y_3); const q0 = z01; const q1 = z11; const q2 = z21; const q3 = z31; const q4 = z41; const xy001 = @as(u128, q0) * @as(u128, mu0); const xy011 = @as(u128, q0) * @as(u128, mu1); const xy021 = @as(u128, q0) * @as(u128, mu2); const xy031 = @as(u128, q0) * @as(u128, mu3); const xy041 = @as(u128, q0) * @as(u128, mu4); const xy101 = @as(u128, q1) * @as(u128, mu0); const xy111 = @as(u128, q1) * @as(u128, mu1); const xy121 = @as(u128, q1) * @as(u128, mu2); const xy131 = @as(u128, q1) * @as(u128, mu3); const xy14 = @as(u128, q1) * @as(u128, mu4); const xy201 = @as(u128, q2) * @as(u128, mu0); const xy211 = @as(u128, q2) * @as(u128, mu1); const xy221 = @as(u128, q2) * @as(u128, mu2); const xy23 = @as(u128, q2) * @as(u128, mu3); const xy24 = @as(u128, q2) * @as(u128, mu4); const xy301 = @as(u128, q3) * @as(u128, mu0); const xy311 = @as(u128, q3) * @as(u128, mu1); const xy32 = @as(u128, q3) * @as(u128, mu2); const xy33 = @as(u128, q3) * @as(u128, mu3); const xy34 = @as(u128, q3) * @as(u128, mu4); const xy401 = @as(u128, q4) * @as(u128, mu0); const xy41 = @as(u128, q4) * @as(u128, mu1); const xy42 = @as(u128, q4) * @as(u128, mu2); const xy43 = @as(u128, q4) * @as(u128, mu3); const xy44 = @as(u128, q4) * @as(u128, mu4); const z02 = xy001; const z12 = xy011 + xy101; const z22 = xy021 + xy111 + xy201; const z32 = xy031 + xy121 + xy211 + xy301; const z42 = xy041 + xy131 + xy221 + xy311 + xy401; const z5 = xy14 + xy23 + xy32 + xy41; const z6 = xy24 + xy33 + xy42; const z7 = xy34 + xy43; const z8 = xy44; const carry9 = z02 >> 56; const c01 = carry9; const carry10 = (z12 + c01) >> 56; const t21 = @truncate(u64, z12 + c01) & 0xffffffffffffff; const c11 = carry10; const carry11 = (z22 + c11) >> 56; const t22 = @truncate(u64, z22 + c11) & 0xffffffffffffff; const c21 = carry11; const carry12 = (z32 + c21) >> 56; const t23 = @truncate(u64, z32 + c21) & 0xffffffffffffff; const c31 = carry12; const carry13 = (z42 + c31) >> 56; const t24 = @truncate(u64, z42 + c31) & 0xffffffffffffff; const c41 = carry13; const t41 = t24; const carry14 = (z5 + c41) >> 56; const t25 = @truncate(u64, z5 + c41) & 0xffffffffffffff; const c5 = carry14; const t5 = t25; const carry15 = (z6 + c5) >> 56; const t26 = @truncate(u64, z6 + c5) & 0xffffffffffffff; const c6 = carry15; const t6 = t26; const carry16 = (z7 + c6) >> 56; const t27 = @truncate(u64, z7 + c6) & 0xffffffffffffff; const c7 = carry16; const t7 = t27; const carry17 = (z8 + c7) >> 56; const t28 = @truncate(u64, z8 + c7) & 0xffffffffffffff; const c8 = carry17; const t8 = t28; const t9 = @truncate(u64, c8); const qmu4_ = t41; const qmu5_ = t5; const qmu6_ = t6; const qmu7_ = t7; const qmu8_ = t8; const qmu9_ = t9; const y_4 = (qmu5_ & 0xffffffffff) << 16; const x_4 = qmu4_ >> 40; const z03 = (x_4 | y_4); const y_5 = (qmu6_ & 0xffffffffff) << 16; const x_5 = qmu5_ >> 40; const z13 = (x_5 | y_5); const y_6 = (qmu7_ & 0xffffffffff) << 16; const x_6 = qmu6_ >> 40; const z23 = (x_6 | y_6); const y_7 = (qmu8_ & 0xffffffffff) << 16; const x_7 = qmu7_ >> 40; const z33 = (x_7 | y_7); const y_8 = (qmu9_ & 0xffffffffff) << 16; const x_8 = qmu8_ >> 40; const z43 = (x_8 | y_8); const qdiv0 = z03; const qdiv1 = z13; const qdiv2 = z23; const qdiv3 = z33; const qdiv4 = z43; const r01 = r0; const r11 = r1; const r21 = r2; const r31 = r3; const r41 = (r4 & 0xffffffffff); const xy00 = @as(u128, qdiv0) * @as(u128, m0); const xy01 = @as(u128, qdiv0) * @as(u128, m1); const xy02 = @as(u128, qdiv0) * @as(u128, m2); const xy03 = @as(u128, qdiv0) * @as(u128, m3); const xy04 = @as(u128, qdiv0) * @as(u128, m4); const xy10 = @as(u128, qdiv1) * @as(u128, m0); const xy11 = @as(u128, qdiv1) * @as(u128, m1); const xy12 = @as(u128, qdiv1) * @as(u128, m2); const xy13 = @as(u128, qdiv1) * @as(u128, m3); const xy20 = @as(u128, qdiv2) * @as(u128, m0); const xy21 = @as(u128, qdiv2) * @as(u128, m1); const xy22 = @as(u128, qdiv2) * @as(u128, m2); const xy30 = @as(u128, qdiv3) * @as(u128, m0); const xy31 = @as(u128, qdiv3) * @as(u128, m1); const xy40 = @as(u128, qdiv4) * @as(u128, m0); const carry18 = xy00 >> 56; const t29 = @truncate(u64, xy00) & 0xffffffffffffff; const c0 = carry18; const t01 = t29; const carry19 = (xy01 + xy10 + c0) >> 56; const t31 = @truncate(u64, xy01 + xy10 + c0) & 0xffffffffffffff; const c12 = carry19; const t110 = t31; const carry20 = (xy02 + xy11 + xy20 + c12) >> 56; const t32 = @truncate(u64, xy02 + xy11 + xy20 + c12) & 0xffffffffffffff; const c22 = carry20; const t210 = t32; const carry = (xy03 + xy12 + xy21 + xy30 + c22) >> 56; const t33 = @truncate(u64, xy03 + xy12 + xy21 + xy30 + c22) & 0xffffffffffffff; const c32 = carry; const t34 = t33; const t42 = @truncate(u64, xy04 + xy13 + xy22 + xy31 + xy40 + c32) & 0xffffffffff; const qmul0 = t01; const qmul1 = t110; const qmul2 = t210; const qmul3 = t34; const qmul4 = t42; const b5 = (r01 -% qmul0) >> 63; const t35 = ((b5 << 56) + r01) -% qmul0; const c1 = b5; const t02 = t35; const b6 = (r11 -% (qmul1 + c1)) >> 63; const t36 = ((b6 << 56) + r11) -% (qmul1 + c1); const c2 = b6; const t111 = t36; const b7 = (r21 -% (qmul2 + c2)) >> 63; const t37 = ((b7 << 56) + r21) -% (qmul2 + c2); const c3 = b7; const t211 = t37; const b8 = (r31 -% (qmul3 + c3)) >> 63; const t38 = ((b8 << 56) + r31) -% (qmul3 + c3); const c4 = b8; const t39 = t38; const b9 = (r41 -% (qmul4 + c4)) >> 63; const t43 = ((b9 << 40) + r41) -% (qmul4 + c4); const t44 = t43; const s0 = t02; const s1 = t111; const s2 = t211; const s3 = t39; const s4 = t44; const y01: u64 = 5175514460705773; const y11: u64 = 70332060721272408; const y21: u64 = 5342; const y31: u64 = 0; const y41: u64 = 268435456; const b10 = (s0 -% y01) >> 63; const t45 = ((b10 << 56) + s0) -% y01; const b0 = b10; const t0 = t45; const b11 = (s1 -% (y11 + b0)) >> 63; const t46 = ((b11 << 56) + s1) -% (y11 + b0); const b1 = b11; const t1 = t46; const b12 = (s2 -% (y21 + b1)) >> 63; const t47 = ((b12 << 56) + s2) -% (y21 + b1); const b2 = b12; const t2 = t47; const b13 = (s3 -% (y31 + b2)) >> 63; const t48 = ((b13 << 56) + s3) -% (y31 + b2); const b3 = b13; const t3 = t48; const b = (s4 -% (y41 + b3)) >> 63; const t = ((b << 56) + s4) -% (y41 + b3); const b4 = b; const t4 = t; const mask = (b4 -% @intCast(u64, ((1)))); const z04 = s0 ^ (mask & (s0 ^ t0)); const z14 = s1 ^ (mask & (s1 ^ t1)); const z24 = s2 ^ (mask & (s2 ^ t2)); const z34 = s3 ^ (mask & (s3 ^ t3)); const z44 = s4 ^ (mask & (s4 ^ t4)); return Scalar{ .limbs = .{ z04, z14, z24, z34, z44 } }; } }; const ScalarDouble = struct { const Limbs = [10]u64; limbs: Limbs = undefined, fn fromBytes64(bytes: [64]u8) ScalarDouble { var limbs: Limbs = undefined; var i: usize = 0; while (i < 9) : (i += 1) { limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; } limbs[i] = @as(u64, bytes[i * 7]); return ScalarDouble{ .limbs = limbs }; } fn fromBytes32(bytes: [32]u8) ScalarDouble { var limbs: Limbs = undefined; var i: usize = 0; while (i < 4) : (i += 1) { limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; } limbs[i] = @as(u64, mem.readIntLittle(u32, bytes[i * 7 ..][0..4])); mem.set(u64, limbs[5..], 0); return ScalarDouble{ .limbs = limbs }; } fn toBytes(expanded_double: *ScalarDouble) [32]u8 { return expanded_double.reduce(10).toBytes(); } /// Barrett reduction fn reduce(expanded: *ScalarDouble, comptime limbs_count: usize) Scalar { const t = expanded.limbs; const t0 = if (limbs_count <= 0) 0 else t[0]; const t1 = if (limbs_count <= 1) 0 else t[1]; const t2 = if (limbs_count <= 2) 0 else t[2]; const t3 = if (limbs_count <= 3) 0 else t[3]; const t4 = if (limbs_count <= 4) 0 else t[4]; const t5 = if (limbs_count <= 5) 0 else t[5]; const t6 = if (limbs_count <= 6) 0 else t[6]; const t7 = if (limbs_count <= 7) 0 else t[7]; const t8 = if (limbs_count <= 8) 0 else t[8]; const t9 = if (limbs_count <= 9) 0 else t[9]; const m0: u64 = 5175514460705773; const m1: u64 = 70332060721272408; const m2: u64 = 5342; const m3: u64 = 0; const m4: u64 = 268435456; const mu0: u64 = 44162584779952923; const mu1: u64 = 9390964836247533; const mu2: u64 = 72057594036560134; const mu3: u64 = 0xffffffffffffff; const mu4: u64 = 68719476735; const y_ = (t5 & 0xffffff) << 32; const x_ = t4 >> 24; const z00 = x_ | y_; const y_0 = (t6 & 0xffffff) << 32; const x_0 = t5 >> 24; const z10 = x_0 | y_0; const y_1 = (t7 & 0xffffff) << 32; const x_1 = t6 >> 24; const z20 = x_1 | y_1; const y_2 = (t8 & 0xffffff) << 32; const x_2 = t7 >> 24; const z30 = x_2 | y_2; const y_3 = (t9 & 0xffffff) << 32; const x_3 = t8 >> 24; const z40 = x_3 | y_3; const q0 = z00; const q1 = z10; const q2 = z20; const q3 = z30; const q4 = z40; const xy000 = @as(u128, q0) * @as(u128, mu0); const xy010 = @as(u128, q0) * @as(u128, mu1); const xy020 = @as(u128, q0) * @as(u128, mu2); const xy030 = @as(u128, q0) * @as(u128, mu3); const xy040 = @as(u128, q0) * @as(u128, mu4); const xy100 = @as(u128, q1) * @as(u128, mu0); const xy110 = @as(u128, q1) * @as(u128, mu1); const xy120 = @as(u128, q1) * @as(u128, mu2); const xy130 = @as(u128, q1) * @as(u128, mu3); const xy14 = @as(u128, q1) * @as(u128, mu4); const xy200 = @as(u128, q2) * @as(u128, mu0); const xy210 = @as(u128, q2) * @as(u128, mu1); const xy220 = @as(u128, q2) * @as(u128, mu2); const xy23 = @as(u128, q2) * @as(u128, mu3); const xy24 = @as(u128, q2) * @as(u128, mu4); const xy300 = @as(u128, q3) * @as(u128, mu0); const xy310 = @as(u128, q3) * @as(u128, mu1); const xy32 = @as(u128, q3) * @as(u128, mu2); const xy33 = @as(u128, q3) * @as(u128, mu3); const xy34 = @as(u128, q3) * @as(u128, mu4); const xy400 = @as(u128, q4) * @as(u128, mu0); const xy41 = @as(u128, q4) * @as(u128, mu1); const xy42 = @as(u128, q4) * @as(u128, mu2); const xy43 = @as(u128, q4) * @as(u128, mu3); const xy44 = @as(u128, q4) * @as(u128, mu4); const z01 = xy000; const z11 = xy010 + xy100; const z21 = xy020 + xy110 + xy200; const z31 = xy030 + xy120 + xy210 + xy300; const z41 = xy040 + xy130 + xy220 + xy310 + xy400; const z5 = xy14 + xy23 + xy32 + xy41; const z6 = xy24 + xy33 + xy42; const z7 = xy34 + xy43; const z8 = xy44; const carry0 = z01 >> 56; const c00 = carry0; const carry1 = (z11 + c00) >> 56; const t100 = @as(u64, @truncate(u64, z11 + c00)) & 0xffffffffffffff; const c10 = carry1; const carry2 = (z21 + c10) >> 56; const t101 = @as(u64, @truncate(u64, z21 + c10)) & 0xffffffffffffff; const c20 = carry2; const carry3 = (z31 + c20) >> 56; const t102 = @as(u64, @truncate(u64, z31 + c20)) & 0xffffffffffffff; const c30 = carry3; const carry4 = (z41 + c30) >> 56; const t103 = @as(u64, @truncate(u64, z41 + c30)) & 0xffffffffffffff; const c40 = carry4; const t410 = t103; const carry5 = (z5 + c40) >> 56; const t104 = @as(u64, @truncate(u64, z5 + c40)) & 0xffffffffffffff; const c5 = carry5; const t51 = t104; const carry6 = (z6 + c5) >> 56; const t105 = @as(u64, @truncate(u64, z6 + c5)) & 0xffffffffffffff; const c6 = carry6; const t61 = t105; const carry7 = (z7 + c6) >> 56; const t106 = @as(u64, @truncate(u64, z7 + c6)) & 0xffffffffffffff; const c7 = carry7; const t71 = t106; const carry8 = (z8 + c7) >> 56; const t107 = @as(u64, @truncate(u64, z8 + c7)) & 0xffffffffffffff; const c8 = carry8; const t81 = t107; const t91 = @as(u64, @truncate(u64, c8)); const qmu4_ = t410; const qmu5_ = t51; const qmu6_ = t61; const qmu7_ = t71; const qmu8_ = t81; const qmu9_ = t91; const y_4 = (qmu5_ & 0xffffffffff) << 16; const x_4 = qmu4_ >> 40; const z02 = x_4 | y_4; const y_5 = (qmu6_ & 0xffffffffff) << 16; const x_5 = qmu5_ >> 40; const z12 = x_5 | y_5; const y_6 = (qmu7_ & 0xffffffffff) << 16; const x_6 = qmu6_ >> 40; const z22 = x_6 | y_6; const y_7 = (qmu8_ & 0xffffffffff) << 16; const x_7 = qmu7_ >> 40; const z32 = x_7 | y_7; const y_8 = (qmu9_ & 0xffffffffff) << 16; const x_8 = qmu8_ >> 40; const z42 = x_8 | y_8; const qdiv0 = z02; const qdiv1 = z12; const qdiv2 = z22; const qdiv3 = z32; const qdiv4 = z42; const r0 = t0; const r1 = t1; const r2 = t2; const r3 = t3; const r4 = t4 & 0xffffffffff; const xy00 = @as(u128, qdiv0) * @as(u128, m0); const xy01 = @as(u128, qdiv0) * @as(u128, m1); const xy02 = @as(u128, qdiv0) * @as(u128, m2); const xy03 = @as(u128, qdiv0) * @as(u128, m3); const xy04 = @as(u128, qdiv0) * @as(u128, m4); const xy10 = @as(u128, qdiv1) * @as(u128, m0); const xy11 = @as(u128, qdiv1) * @as(u128, m1); const xy12 = @as(u128, qdiv1) * @as(u128, m2); const xy13 = @as(u128, qdiv1) * @as(u128, m3); const xy20 = @as(u128, qdiv2) * @as(u128, m0); const xy21 = @as(u128, qdiv2) * @as(u128, m1); const xy22 = @as(u128, qdiv2) * @as(u128, m2); const xy30 = @as(u128, qdiv3) * @as(u128, m0); const xy31 = @as(u128, qdiv3) * @as(u128, m1); const xy40 = @as(u128, qdiv4) * @as(u128, m0); const carry9 = xy00 >> 56; const t108 = @truncate(u64, xy00) & 0xffffffffffffff; const c0 = carry9; const t010 = t108; const carry10 = (xy01 + xy10 + c0) >> 56; const t109 = @truncate(u64, xy01 + xy10 + c0) & 0xffffffffffffff; const c11 = carry10; const t110 = t109; const carry11 = (xy02 + xy11 + xy20 + c11) >> 56; const t1010 = @truncate(u64, xy02 + xy11 + xy20 + c11) & 0xffffffffffffff; const c21 = carry11; const t210 = t1010; const carry = (xy03 + xy12 + xy21 + xy30 + c21) >> 56; const t1011 = @truncate(u64, xy03 + xy12 + xy21 + xy30 + c21) & 0xffffffffffffff; const c31 = carry; const t310 = t1011; const t411 = @truncate(u64, xy04 + xy13 + xy22 + xy31 + xy40 + c31) & 0xffffffffff; const qmul0 = t010; const qmul1 = t110; const qmul2 = t210; const qmul3 = t310; const qmul4 = t411; const b5 = (r0 -% qmul0) >> 63; const t1012 = ((b5 << 56) + r0) -% qmul0; const c1 = b5; const t011 = t1012; const b6 = (r1 -% (qmul1 + c1)) >> 63; const t1013 = ((b6 << 56) + r1) -% (qmul1 + c1); const c2 = b6; const t111 = t1013; const b7 = (r2 -% (qmul2 + c2)) >> 63; const t1014 = ((b7 << 56) + r2) -% (qmul2 + c2); const c3 = b7; const t211 = t1014; const b8 = (r3 -% (qmul3 + c3)) >> 63; const t1015 = ((b8 << 56) + r3) -% (qmul3 + c3); const c4 = b8; const t311 = t1015; const b9 = (r4 -% (qmul4 + c4)) >> 63; const t1016 = ((b9 << 40) + r4) -% (qmul4 + c4); const t412 = t1016; const s0 = t011; const s1 = t111; const s2 = t211; const s3 = t311; const s4 = t412; const y0: u64 = 5175514460705773; const y1: u64 = 70332060721272408; const y2: u64 = 5342; const y3: u64 = 0; const y4: u64 = 268435456; const b10 = (s0 -% y0) >> 63; const t1017 = ((b10 << 56) + s0) -% y0; const b0 = b10; const t01 = t1017; const b11 = (s1 -% (y1 + b0)) >> 63; const t1018 = ((b11 << 56) + s1) -% (y1 + b0); const b1 = b11; const t11 = t1018; const b12 = (s2 -% (y2 + b1)) >> 63; const t1019 = ((b12 << 56) + s2) -% (y2 + b1); const b2 = b12; const t21 = t1019; const b13 = (s3 -% (y3 + b2)) >> 63; const t1020 = ((b13 << 56) + s3) -% (y3 + b2); const b3 = b13; const t31 = t1020; const b = (s4 -% (y4 + b3)) >> 63; const t10 = ((b << 56) + s4) -% (y4 + b3); const b4 = b; const t41 = t10; const mask = b4 -% @as(u64, @as(u64, 1)); const z03 = s0 ^ (mask & (s0 ^ t01)); const z13 = s1 ^ (mask & (s1 ^ t11)); const z23 = s2 ^ (mask & (s2 ^ t21)); const z33 = s3 ^ (mask & (s3 ^ t31)); const z43 = s4 ^ (mask & (s4 ^ t41)); return Scalar{ .limbs = .{ z03, z13, z23, z33, z43 } }; } }; test "scalar25519" { const bytes: [32]u8 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 255 }; var x = Scalar.fromBytes(bytes); var y = x.toBytes(); try rejectNonCanonical(y); var buf: [128]u8 = undefined; try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&y)}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F"); const reduced = reduce(field_size); try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&reduced)}), "0000000000000000000000000000000000000000000000000000000000000000"); } test "non-canonical scalar25519" { const too_targe: [32]u8 = .{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 }; try std.testing.expectError(error.NonCanonical, rejectNonCanonical(too_targe)); } test "mulAdd overflow check" { const a: [32]u8 = [_]u8{0xff} ** 32; const b: [32]u8 = [_]u8{0xff} ** 32; const c: [32]u8 = [_]u8{0xff} ** 32; const x = mulAdd(a, b, c); var buf: [128]u8 = undefined; try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&x)}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903"); }
lib/std/crypto/25519/scalar.zig
const std = @import("std"); const heap = std.heap; const io = std.io; const testing = std.testing; const ArrayList = std.ArrayList; const filter = @import("filter.zig"); const ui = @import("ui.zig"); const version = "0.5-dev"; const version_str = std.fmt.comptimePrint("zf {s} <NAME>", .{version}); const help = \\Usage: zf [options] \\ \\-f, --filter Skip interactive use and filter using the given query \\-k, --keep-order Don't sort by rank and preserve order of lines read on stdin \\-l, --lines Set the maximum number of result lines to show (default 10) \\-p, --plain Disable filename match prioritization \\-v, --version Show version information and exit \\-h, --help Display this help and exit ; const Config = struct { help: bool = false, version: bool = false, skip_ui: bool = false, keep_order: bool = false, lines: usize = 10, plain: bool = false, query: []u8 = undefined, // HACK: error unions cannot return a value, so return error messages in // the config struct instead err: bool = false, err_str: []u8 = undefined, }; // TODO: handle args immediately after a short arg, i.e. -qhello or -l5 fn parseArgs(allocator: std.mem.Allocator, args: []const []const u8) !Config { var config: Config = .{}; const eql = std.mem.eql; var skip = false; for (args[1..]) |arg, i| { if (skip) { skip = false; continue; } const index = i + 1; if (eql(u8, arg, "-h") or eql(u8, arg, "--help")) { config.help = true; return config; } else if (eql(u8, arg, "-v") or eql(u8, arg, "--version")) { config.version = true; return config; } else if (eql(u8, arg, "-k") or eql(u8, arg, "--keep-order")) { config.keep_order = true; } else if (eql(u8, arg, "-p") or eql(u8, arg, "--plain")) { config.plain = true; } else if (eql(u8, arg, "-l") or eql(u8, arg, "--lines")) { if (index + 1 > args.len - 1) { config.err = true; config.err_str = try std.fmt.allocPrint( allocator, "zf: option '{s}' requires an argument\n{s}", .{ arg, help }, ); return config; } config.lines = try std.fmt.parseUnsigned(usize, args[index + 1], 10); if (config.lines == 0) return error.InvalidCharacter; skip = true; } else if (eql(u8, arg, "-f") or eql(u8, arg, "--filter")) { config.skip_ui = true; // read query if (index + 1 > args.len - 1) { config.err = true; config.err_str = try std.fmt.allocPrint( allocator, "zf: option '{s}' requires an argument\n{s}", .{ arg, help }, ); return config; } config.query = try allocator.alloc(u8, args[index + 1].len); std.mem.copy(u8, config.query, args[index + 1]); skip = true; } else { config.err = true; config.err_str = try std.fmt.allocPrint( allocator, "zf: unrecognized option '{s}'\n{s}", .{ arg, help }, ); return config; } } return config; } test "parse args" { { const args = [_][]const u8{"zf"}; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{}; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "--help" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .help = true }; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "--version" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .version = true }; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "-v", "-h" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .help = false, .version = true }; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "-f", "query" }; const config = try parseArgs(testing.allocator, &args); defer testing.allocator.free(config.query); try testing.expect(config.skip_ui); try testing.expectEqualStrings("query", config.query); } { const args = [_][]const u8{ "zf", "-l", "12" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .lines = 12 }; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "-k", "-p" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .keep_order = true, .plain = true }; try testing.expectEqual(expected, config); } { const args = [_][]const u8{ "zf", "--keep-order", "--plain" }; const config = try parseArgs(testing.allocator, &args); const expected: Config = .{ .keep_order = true, .plain = true }; try testing.expectEqual(expected, config); } // failure cases { const args = [_][]const u8{ "zf", "--filter" }; const config = try parseArgs(testing.allocator, &args); defer testing.allocator.free(config.err_str); try testing.expect(config.err); } { const args = [_][]const u8{ "zf", "asdf" }; const config = try parseArgs(testing.allocator, &args); defer testing.allocator.free(config.err_str); try testing.expect(config.err); } { const args = [_][]const u8{ "zf", "bad arg here", "--help" }; const config = try parseArgs(testing.allocator, &args); defer testing.allocator.free(config.err_str); try testing.expect(config.err); } { const args = [_][]const u8{ "zf", "--lines", "-10" }; try testing.expectError(error.InvalidCharacter, parseArgs(testing.allocator, &args)); } } pub fn main() anyerror!void { // create an arena allocator to reduce time spent allocating // and freeing memory during runtime. var arena = heap.ArenaAllocator.init(heap.page_allocator); defer arena.deinit(); const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); const config = parseArgs(allocator, args) catch |e| switch (e) { error.InvalidCharacter, error.Overflow => { try stderr.print("Number of lines must be an integer greater than 0\n", .{}); std.process.exit(2); }, else => return e, }; if (config.err) { try stderr.print("{s}\n", .{config.err_str}); std.process.exit(2); } else if (config.help) { try stdout.print("{s}\n", .{help}); std.process.exit(0); } else if (config.version) { try stdout.print("{s}\n", .{version_str}); std.process.exit(0); } // read all lines or exit on out of memory var stdin = io.getStdIn().reader(); const buf = try readAll(allocator, &stdin); const delimiter = '\n'; var candidates = try filter.collectCandidates(allocator, buf, delimiter, config.plain); if (candidates.len == 0) std.process.exit(1); if (config.skip_ui) { const filtered = try filter.rankCandidates(allocator, candidates, config.query, config.keep_order); if (filtered.len == 0) std.process.exit(1); for (filtered) |candidate| { try stdout.print("{s}\n", .{candidate.str}); } } else { var terminal = try ui.Terminal.init(@minimum(candidates.len, config.lines)); var selected = try ui.run(allocator, &terminal, candidates, config.keep_order); try ui.cleanUp(&terminal); terminal.deinit(); if (selected) |str| { try stdout.print("{s}\n", .{str}); } else std.process.exit(1); } } /// read from a file into an ArrayList. similar to readAllAlloc from the /// standard library, but will read until out of memory rather than limiting to /// a maximum size. pub fn readAll(allocator: std.mem.Allocator, reader: *std.fs.File.Reader) ![]u8 { var buf = ArrayList(u8).init(allocator); // ensure the array starts at a decent size try buf.ensureTotalCapacity(4096); var index: usize = 0; while (true) { buf.expandToCapacity(); const slice = buf.items[index..]; const read = try reader.readAll(slice); index += read; if (read != slice.len) { buf.shrinkAndFree(index); return buf.toOwnedSlice(); } try buf.ensureTotalCapacity(index + 1); } } test { _ = @import("filter.zig"); }
src/main.zig
const std = @import("std"); const TestContext = @import("../../src-self-hosted/test.zig").TestContext; // self-hosted does not yet support PE executable files / COFF object files // or mach-o files. So we do the ZIR transform test cases cross compiling for // x86_64-linux. const linux_x64 = std.zig.CrossTarget{ .cpu_arch = .x86_64, .os_tag = .linux, }; pub fn addCases(ctx: *TestContext) !void { ctx.transformZIR("referencing decls which appear later in the file", linux_x64, \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\ \\@9 = str("entry") \\@11 = export(@9, "entry") \\ \\@entry = fn(@fnty, { \\ %11 = returnvoid() \\}) , \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\@9 = declref("9__anon_0") \\@9__anon_0 = str("entry") \\@unnamed$4 = str("entry") \\@unnamed$5 = export(@unnamed$4, "entry") \\@unnamed$6 = fntype([], @void, cc=C) \\@entry = fn(@unnamed$6, { \\ %0 = returnvoid() \\}) \\ ); ctx.transformZIR("elemptr, add, cmp, condbr, return, breakpoint", linux_x64, \\@void = primitive(void) \\@usize = primitive(usize) \\@fnty = fntype([], @void, cc=C) \\@0 = int(0) \\@1 = int(1) \\@2 = int(2) \\@3 = int(3) \\ \\@entry = fn(@fnty, { \\ %a = str("\x32\x08\x01\x0a") \\ %eptr0 = elemptr(%a, @0) \\ %eptr1 = elemptr(%a, @1) \\ %eptr2 = elemptr(%a, @2) \\ %eptr3 = elemptr(%a, @3) \\ %v0 = deref(%eptr0) \\ %v1 = deref(%eptr1) \\ %v2 = deref(%eptr2) \\ %v3 = deref(%eptr3) \\ %x0 = add(%v0, %v1) \\ %x1 = add(%v2, %v3) \\ %result = add(%x0, %x1) \\ \\ %expected = int(69) \\ %ok = cmp_eq(%result, %expected) \\ %10 = condbr(%ok, { \\ %11 = returnvoid() \\ }, { \\ %12 = breakpoint() \\ }) \\}) \\ \\@9 = str("entry") \\@11 = export(@9, "entry") , \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\@0 = int(0) \\@1 = int(1) \\@2 = int(2) \\@3 = int(3) \\@unnamed$6 = fntype([], @void, cc=C) \\@entry = fn(@unnamed$6, { \\ %0 = returnvoid() \\}) \\@entry__anon_1 = str("2\x08\x01\n") \\@9 = declref("9__anon_0") \\@9__anon_0 = str("entry") \\@unnamed$11 = str("entry") \\@unnamed$12 = export(@unnamed$11, "entry") \\ ); { var case = ctx.objZIR("reference cycle with compile error in the cycle", linux_x64); case.addTransform( \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\ \\@9 = str("entry") \\@11 = export(@9, "entry") \\ \\@entry = fn(@fnty, { \\ %0 = call(@a, []) \\ %1 = returnvoid() \\}) \\ \\@a = fn(@fnty, { \\ %0 = call(@b, []) \\ %1 = returnvoid() \\}) \\ \\@b = fn(@fnty, { \\ %0 = call(@a, []) \\ %1 = returnvoid() \\}) , \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\@9 = declref("9__anon_0") \\@9__anon_0 = str("entry") \\@unnamed$4 = str("entry") \\@unnamed$5 = export(@unnamed$4, "entry") \\@unnamed$6 = fntype([], @void, cc=C) \\@entry = fn(@unnamed$6, { \\ %0 = call(@a, [], modifier=auto) \\ %1 = returnvoid() \\}) \\@unnamed$8 = fntype([], @void, cc=C) \\@a = fn(@unnamed$8, { \\ %0 = call(@b, [], modifier=auto) \\ %1 = returnvoid() \\}) \\@unnamed$10 = fntype([], @void, cc=C) \\@b = fn(@unnamed$10, { \\ %0 = call(@a, [], modifier=auto) \\ %1 = returnvoid() \\}) \\ ); // Now we introduce a compile error case.addError( \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\ \\@9 = str("entry") \\@11 = export(@9, "entry") \\ \\@entry = fn(@fnty, { \\ %0 = call(@a, []) \\ %1 = returnvoid() \\}) \\ \\@a = fn(@fnty, { \\ %0 = call(@b, []) \\ %1 = returnvoid() \\}) \\ \\@b = fn(@fnty, { \\ %9 = compileerror("message") \\ %0 = call(@a, []) \\ %1 = returnvoid() \\}) , &[_][]const u8{ ":18:21: error: message", }, ); // Now we remove the call to `a`. `a` and `b` form a cycle, but no entry points are // referencing either of them. This tests that the cycle is detected, and the error // goes away. case.addTransform( \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\ \\@9 = str("entry") \\@11 = export(@9, "entry") \\ \\@entry = fn(@fnty, { \\ %0 = returnvoid() \\}) \\ \\@a = fn(@fnty, { \\ %0 = call(@b, []) \\ %1 = returnvoid() \\}) \\ \\@b = fn(@fnty, { \\ %9 = compileerror("message") \\ %0 = call(@a, []) \\ %1 = returnvoid() \\}) , \\@void = primitive(void) \\@fnty = fntype([], @void, cc=C) \\@9 = declref("9__anon_2") \\@9__anon_2 = str("entry") \\@unnamed$4 = str("entry") \\@unnamed$5 = export(@unnamed$4, "entry") \\@unnamed$6 = fntype([], @void, cc=C) \\@entry = fn(@unnamed$6, { \\ %0 = returnvoid() \\}) \\ ); } if (std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64) { // TODO implement self-hosted PE (.exe file) linking // TODO implement more ZIR so we don't depend on x86_64-linux return; } ctx.compareOutputZIR("hello world ZIR", \\@noreturn = primitive(noreturn) \\@void = primitive(void) \\@usize = primitive(usize) \\@0 = int(0) \\@1 = int(1) \\@2 = int(2) \\@3 = int(3) \\ \\@msg = str("Hello, world!\n") \\ \\@start_fnty = fntype([], @noreturn, cc=Naked) \\@start = fn(@start_fnty, { \\ %SYS_exit_group = int(231) \\ %exit_code = as(@usize, @0) \\ \\ %syscall = str("syscall") \\ %sysoutreg = str("={rax}") \\ %rax = str("{rax}") \\ %rdi = str("{rdi}") \\ %rcx = str("rcx") \\ %rdx = str("{rdx}") \\ %rsi = str("{rsi}") \\ %r11 = str("r11") \\ %memory = str("memory") \\ \\ %SYS_write = as(@usize, @1) \\ %STDOUT_FILENO = as(@usize, @1) \\ \\ %msg_addr = ptrtoint(@msg) \\ \\ %len_name = str("len") \\ %msg_len_ptr = fieldptr(@msg, %len_name) \\ %msg_len = deref(%msg_len_ptr) \\ %rc_write = asm(%syscall, @usize, \\ volatile=1, \\ output=%sysoutreg, \\ inputs=[%rax, %rdi, %rsi, %rdx], \\ clobbers=[%rcx, %r11, %memory], \\ args=[%SYS_write, %STDOUT_FILENO, %msg_addr, %msg_len]) \\ \\ %rc_exit = asm(%syscall, @usize, \\ volatile=1, \\ output=%sysoutreg, \\ inputs=[%rax, %rdi], \\ clobbers=[%rcx, %r11, %memory], \\ args=[%SYS_exit_group, %exit_code]) \\ \\ %99 = unreachable() \\}); \\ \\@9 = str("_start") \\@11 = export(@9, "start") , \\Hello, world! \\ ); ctx.compareOutputZIR("function call with no args no return value", \\@noreturn = primitive(noreturn) \\@void = primitive(void) \\@usize = primitive(usize) \\@0 = int(0) \\@1 = int(1) \\@2 = int(2) \\@3 = int(3) \\ \\@exit0_fnty = fntype([], @noreturn) \\@exit0 = fn(@exit0_fnty, { \\ %SYS_exit_group = int(231) \\ %exit_code = as(@usize, @0) \\ \\ %syscall = str("syscall") \\ %sysoutreg = str("={rax}") \\ %rax = str("{rax}") \\ %rdi = str("{rdi}") \\ %rcx = str("rcx") \\ %r11 = str("r11") \\ %memory = str("memory") \\ \\ %rc = asm(%syscall, @usize, \\ volatile=1, \\ output=%sysoutreg, \\ inputs=[%rax, %rdi], \\ clobbers=[%rcx, %r11, %memory], \\ args=[%SYS_exit_group, %exit_code]) \\ \\ %99 = unreachable() \\}); \\ \\@start_fnty = fntype([], @noreturn, cc=Naked) \\@start = fn(@start_fnty, { \\ %0 = call(@exit0, []) \\}) \\@9 = str("_start") \\@11 = export(@9, "start") , ""); }
test/stage2/zir.zig
const std = @import("std.zig"); const assert = std.debug.assert; const testing = std.testing; const Allocator = std.mem.Allocator; // Imagine that `fn at(self: *Self, index: usize) &T` is a customer asking for a box // from a warehouse, based on a flat array, boxes ordered from 0 to N - 1. // But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes. // So when the customer requests a box index, we have to translate it to shelf index // and box index within that shelf. Illustration: // // customer indexes: // shelf 0: 0 // shelf 1: 1 2 // shelf 2: 3 4 5 6 // shelf 3: 7 8 9 10 11 12 13 14 // shelf 4: 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // shelf 5: 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // ... // // warehouse indexes: // shelf 0: 0 // shelf 1: 0 1 // shelf 2: 0 1 2 3 // shelf 3: 0 1 2 3 4 5 6 7 // shelf 4: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // shelf 5: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // ... // // With this arrangement, here are the equations to get the shelf index and // box index based on customer box index: // // shelf_index = floor(log2(customer_index + 1)) // shelf_count = ceil(log2(box_count + 1)) // box_index = customer_index + 1 - 2 ** shelf // shelf_size = 2 ** shelf_index // // Now we complicate it a little bit further by adding a preallocated shelf, which must be // a power of 2: // prealloc=4 // // customer indexes: // prealloc: 0 1 2 3 // shelf 0: 4 5 6 7 8 9 10 11 // shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // shelf 2: 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // ... // // warehouse indexes: // prealloc: 0 1 2 3 // shelf 0: 0 1 2 3 4 5 6 7 // shelf 1: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // shelf 2: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // ... // // Now the equations are: // // shelf_index = floor(log2(customer_index + prealloc)) - log2(prealloc) - 1 // shelf_count = ceil(log2(box_count + prealloc)) - log2(prealloc) - 1 // box_index = customer_index + prealloc - 2 ** (log2(prealloc) + 1 + shelf) // shelf_size = prealloc * 2 ** (shelf_index + 1) /// This is a stack data structure where pointers to indexes have the same lifetime as the data structure /// itself, unlike ArrayList where push() invalidates all existing element pointers. /// The tradeoff is that elements are not guaranteed to be contiguous. For that, use ArrayList. /// Note however that most elements are contiguous, making this data structure cache-friendly. /// /// Because it never has to copy elements from an old location to a new location, it does not require /// its elements to be copyable, and it avoids wasting memory when backed by an ArenaAllocator. /// Note that the push() and pop() convenience methods perform a copy, but you can instead use /// addOne(), at(), setCapacity(), and shrinkCapacity() to avoid copying items. /// /// This data structure has O(1) push and O(1) pop. /// /// It supports preallocated elements, making it especially well suited when the expected maximum /// size is small. `prealloc_item_count` must be 0, or a power of 2. pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type { return struct { const Self = @This(); const ShelfIndex = std.math.Log2Int(usize); const prealloc_exp: ShelfIndex = blk: { // we don't use the prealloc_exp constant when prealloc_item_count is 0 // but lazy-init may still be triggered by other code so supply a value if (prealloc_item_count == 0) { break :blk 0; } else { assert(std.math.isPowerOfTwo(prealloc_item_count)); const value = std.math.log2_int(usize, prealloc_item_count); break :blk value; } }; prealloc_segment: [prealloc_item_count]T, dynamic_segments: [][*]T, allocator: *Allocator, len: usize, pub const prealloc_count = prealloc_item_count; fn AtType(comptime SelfType: type) type { if (@typeInfo(SelfType).Pointer.is_const) { return *const T; } else { return *T; } } /// Deinitialize with `deinit` pub fn init(allocator: *Allocator) Self { return Self{ .allocator = allocator, .len = 0, .prealloc_segment = undefined, .dynamic_segments = &[_][*]T{}, }; } pub fn deinit(self: *Self) void { self.freeShelves(@intCast(ShelfIndex, self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); self.* = undefined; } pub fn at(self: var, i: usize) AtType(@TypeOf(self)) { assert(i < self.len); return self.uncheckedAt(i); } pub fn count(self: Self) usize { return self.len; } pub fn push(self: *Self, item: T) !void { const new_item_ptr = try self.addOne(); new_item_ptr.* = item; } pub fn pushMany(self: *Self, items: []const T) !void { for (items) |item| { try self.push(item); } } pub fn pop(self: *Self) ?T { if (self.len == 0) return null; const index = self.len - 1; const result = uncheckedAt(self, index).*; self.len = index; return result; } pub fn addOne(self: *Self) !*T { const new_length = self.len + 1; try self.growCapacity(new_length); const result = uncheckedAt(self, self.len); self.len = new_length; return result; } /// Grows or shrinks capacity to match usage. pub fn setCapacity(self: *Self, new_capacity: usize) !void { if (prealloc_item_count != 0) { if (new_capacity <= @as(usize, 1) << (prealloc_exp + @intCast(ShelfIndex, self.dynamic_segments.len))) { return self.shrinkCapacity(new_capacity); } } return self.growCapacity(new_capacity); } /// Only grows capacity, or retains current capacity pub fn growCapacity(self: *Self, new_capacity: usize) !void { const new_cap_shelf_count = shelfCount(new_capacity); const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); if (new_cap_shelf_count > old_shelf_count) { self.dynamic_segments = try self.allocator.realloc(self.dynamic_segments, new_cap_shelf_count); var i = old_shelf_count; errdefer { self.freeShelves(i, old_shelf_count); self.dynamic_segments = self.allocator.shrink(self.dynamic_segments, old_shelf_count); } while (i < new_cap_shelf_count) : (i += 1) { self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr; } } } /// Only shrinks capacity or retains current capacity pub fn shrinkCapacity(self: *Self, new_capacity: usize) void { if (new_capacity <= prealloc_item_count) { const len = @intCast(ShelfIndex, self.dynamic_segments.len); self.freeShelves(len, 0); self.allocator.free(self.dynamic_segments); self.dynamic_segments = &[_][*]T{}; return; } const new_cap_shelf_count = shelfCount(new_capacity); const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); assert(new_cap_shelf_count <= old_shelf_count); if (new_cap_shelf_count == old_shelf_count) { return; } self.freeShelves(old_shelf_count, new_cap_shelf_count); self.dynamic_segments = self.allocator.shrink(self.dynamic_segments, new_cap_shelf_count); } pub fn shrink(self: *Self, new_len: usize) void { assert(new_len <= self.len); // TODO take advantage of the new realloc semantics self.len = new_len; } pub fn uncheckedAt(self: var, index: usize) AtType(@TypeOf(self)) { if (index < prealloc_item_count) { return &self.prealloc_segment[index]; } const shelf_index = shelfIndex(index); const box_index = boxIndex(index, shelf_index); return &self.dynamic_segments[shelf_index][box_index]; } fn shelfCount(box_count: usize) ShelfIndex { if (prealloc_item_count == 0) { return std.math.log2_int_ceil(usize, box_count + 1); } return std.math.log2_int_ceil(usize, box_count + prealloc_item_count) - prealloc_exp - 1; } fn shelfSize(shelf_index: ShelfIndex) usize { if (prealloc_item_count == 0) { return @as(usize, 1) << shelf_index; } return @as(usize, 1) << (shelf_index + (prealloc_exp + 1)); } fn shelfIndex(list_index: usize) ShelfIndex { if (prealloc_item_count == 0) { return std.math.log2_int(usize, list_index + 1); } return std.math.log2_int(usize, list_index + prealloc_item_count) - prealloc_exp - 1; } fn boxIndex(list_index: usize, shelf_index: ShelfIndex) usize { if (prealloc_item_count == 0) { return (list_index + 1) - (@as(usize, 1) << shelf_index); } return list_index + prealloc_item_count - (@as(usize, 1) << ((prealloc_exp + 1) + shelf_index)); } fn freeShelves(self: *Self, from_count: ShelfIndex, to_count: ShelfIndex) void { var i = from_count; while (i != to_count) { i -= 1; self.allocator.free(self.dynamic_segments[i][0..shelfSize(i)]); } } pub const Iterator = struct { list: *Self, index: usize, box_index: usize, shelf_index: ShelfIndex, shelf_size: usize, pub fn next(it: *Iterator) ?*T { if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) { const ptr = &it.list.prealloc_segment[it.index]; it.index += 1; if (it.index == prealloc_item_count) { it.box_index = 0; it.shelf_index = 0; it.shelf_size = prealloc_item_count * 2; } return ptr; } const ptr = &it.list.dynamic_segments[it.shelf_index][it.box_index]; it.index += 1; it.box_index += 1; if (it.box_index == it.shelf_size) { it.shelf_index += 1; it.box_index = 0; it.shelf_size *= 2; } return ptr; } pub fn prev(it: *Iterator) ?*T { if (it.index == 0) return null; it.index -= 1; if (it.index < prealloc_item_count) return &it.list.prealloc_segment[it.index]; if (it.box_index == 0) { it.shelf_index -= 1; it.shelf_size /= 2; it.box_index = it.shelf_size - 1; } else { it.box_index -= 1; } return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } pub fn peek(it: *Iterator) ?*T { if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) return &it.list.prealloc_segment[it.index]; return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } pub fn set(it: *Iterator, index: usize) void { it.index = index; if (index < prealloc_item_count) return; it.shelf_index = shelfIndex(index); it.box_index = boxIndex(index, it.shelf_index); it.shelf_size = shelfSize(it.shelf_index); } }; pub fn iterator(self: *Self, start_index: usize) Iterator { var it = Iterator{ .list = self, .index = undefined, .shelf_index = undefined, .box_index = undefined, .shelf_size = undefined, }; it.set(start_index); return it; } }; } test "std.SegmentedList" { var a = std.heap.page_allocator; try testSegmentedList(0, a); try testSegmentedList(1, a); try testSegmentedList(2, a); try testSegmentedList(4, a); try testSegmentedList(8, a); try testSegmentedList(16, a); } fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { var list = SegmentedList(i32, prealloc).init(allocator); defer list.deinit(); { var i: usize = 0; while (i < 100) : (i += 1) { try list.push(@intCast(i32, i + 1)); testing.expect(list.len == i + 1); } } { var i: usize = 0; while (i < 100) : (i += 1) { testing.expect(list.at(i).* == @intCast(i32, i + 1)); } } { var it = list.iterator(0); var x: i32 = 0; while (it.next()) |item| { x += 1; testing.expect(item.* == x); } testing.expect(x == 100); while (it.prev()) |item| : (x -= 1) { testing.expect(item.* == x); } testing.expect(x == 0); } testing.expect(list.pop().? == 100); testing.expect(list.len == 99); try list.pushMany(&[_]i32{ 1, 2, 3 }); testing.expect(list.len == 102); testing.expect(list.pop().? == 3); testing.expect(list.pop().? == 2); testing.expect(list.pop().? == 1); testing.expect(list.len == 99); try list.pushMany(&[_]i32{}); testing.expect(list.len == 99); var i: i32 = 99; while (list.pop()) |item| : (i -= 1) { testing.expect(item == i); list.shrinkCapacity(list.len); } try list.setCapacity(0); }
lib/std/segmented_list.zig
const std = @import("std"); pub const Futex = if (std.builtin.os.tag == .windows) WindowsFutex else if (std.builtin.os.tag == .linux) LinuxFutex else if (std.Target.current.isDarwin()) DarwinFutex else if (std.builtin.link_libc) PosixFutex else @compileError("Platform not supported"); const LinuxFutex = struct { pub fn wait(ptr: *const u32, expected: u32, timeout: ?u64) error{TimedOut}!void { var ts: std.os.timespec = undefined; var ts_ptr: ?*std.os.timespec = null; if (timeout) |timeout_ns| { ts_ptr = &ts; ts.tv_sec = std.math.cast(@TypeOf(ts.tv_sec), timeout_ns / std.time.ns_per_s) catch std.math.maxInt(@TypeOf(ts.tv_sec)); ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), timeout_ns % std.time.ns_per_s); } switch (std.os.linux.getErrno(std.os.linux.futex_wait( @ptrCast(*const i32, ptr), std.os.linux.FUTEX_PRIVATE_FLAG | std.os.linux.FUTEX_WAIT, @bitCast(i32, expected), ts_ptr, ))) { 0 => {}, std.os.EINTR => {}, std.os.EAGAIN => {}, std.os.ETIMEDOUT => return error.TimedOut, else => unreachable, } } pub fn wake(ptr: *const u32, waiters: u32) void { switch (std.os.linux.getErrno(std.os.linux.futex_wake( @ptrCast(*const i32, ptr), std.os.linux.FUTEX_PRIVATE_FLAG | std.os.linux.FUTEX_WAKE, std.math.cast(i32, waiters) catch std.math.maxInt(i32), ))) { 0 => {}, std.os.EINVAL => {}, std.os.EACCES => {}, std.os.EFAULT => {}, else => unreachable, } } pub fn yield(iteration: usize) bool { if (iteration > 100) return false; std.Thread.spinLoopHint(); return true; } }; const DarwinFutex = struct { pub inline fn wait(ptr: *const u32, expected: u32, timeout: ?u64) error{TimedOut}!void { return PosixFutex.wait(ptr, expected, timeout); } pub inline fn wake(ptr: *const u32, waiters: u32) void { return PosixFutex.wake(ptr, waiters); } pub fn yield(iteration: usize) bool { if (std.builtin.os.tag != .macos) return false; const max_spin = if (std.builtin.arch == .x86_64) 1000 else 100; if (iteration > max_spin) return false; std.Thread.spinLoopHint(); return true; } }; const PosixFutex = GenericFutex(struct { state: State = .empty, cond: std.c.pthread_cond_t = std.c.PTHREAD_COND_INITIALIZER, mutex: std.c.pthread_mutex_t = std.c.PTHREAD_MUTEX_INITIALIZER, const State = enum { empty, waiting, notified, }; pub fn init(self: *@This()) void { self.* = .{}; } pub fn deinit(self: *@This()) void { const rc = std.c.pthread_cond_destroy(&self.cond); std.debug.assert(rc == 0 or rc == std.os.EINVAL); const rm = std.c.pthread_mutex_destroy(&self.mutex); std.debug.assert(rm == 0 or rm == std.os.EINVAL); self.* = undefined; } pub fn set(self: *@This()) void { std.debug.assert(std.c.pthread_mutex_lock(&self.mutex) == 0); defer std.debug.assert(std.c.pthread_mutex_unlock(&self.mutex) == 0); const state = self.state; self.state = .notified; switch (state) { .empty => {}, .waiting => std.debug.assert(std.c.pthread_cond_signal(&self.cond) == 0), .notified => unreachable, } } pub fn wait(self: *@This(), timeout: ?u64) error{TimedOut}!void { var deadline: ?u64 = null; if (timeout) |timeout_ns| deadline = timestamp(std.os.CLOCK_MONOTONIC, timeout_ns); std.debug.assert(std.c.pthread_mutex_lock(&self.mutex) == 0); defer std.debug.assert(std.c.pthread_mutex_unlock(&self.mutex) == 0); switch (self.state) { .empty => self.state = .waiting, .waiting => unreachable, .notified => return, } while (true) { switch (self.state) { .empty => unreachable, .waiting => {}, .notified => return, } const deadline_ns = deadline orelse { std.debug.assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == 0); continue; }; var ns = timestamp(std.os.CLOCK_MONOTONIC, 0); if (ns > deadline_ns) { self.state = .empty; return error.TimedOut; } else { ns = timestamp(std.os.CLOCK_REALTIME, deadline_ns - ns); } var ts: std.os.timespec = undefined; ts.tv_sec = std.math.cast(@TypeOf(ts.tv_sec), ns / std.time.ns_per_s) catch std.math.maxInt(@TypeOf(ts.tv_sec)); ts.tv_nsec = std.math.cast(@TypeOf(ts.tv_nsec), ns % std.time.ns_per_s) catch std.time.ns_per_s; switch (std.c.pthread_cond_timedwait(&self.cond, &self.mutex, &ts)) { 0 => {}, std.os.ETIMEDOUT => {}, else => unreachable, } } } pub fn yield(iteration: usize) bool { if (iteration > 40) return false; std.os.sched_yield() catch {}; return true; } fn timestamp(comptime clock: u32, offset: u64) u64 { var now: u64 = undefined; if (std.Target.current.isDarwin()) { switch (clock) { std.os.CLOCK_REALTIME => { var tv: std.os.timeval = undefined; std.os.gettimeofday(&tv, null); now = @intCast(u64, tv.tv_sec) * std.time.ns_per_s; now += @intCast(u64, tv.tv_usec) * std.time.ns_per_us; }, std.os.CLOCK_MONOTONIC => { var freq: std.os.darwin.mach_timebase_info_data = undefined; std.os.darwin.mach_timebase_info(&freq); now = std.os.darwin.mach_absolute_time(); if (freq.numer > 1) now *= freq.numer; if (freq.denom > 1) now /= freq.denom; }, else => unreachable, } } else { var ts: std.os.timespec = undefined; std.os.clock_gettime(clock, &ts) catch { ts.tv_sec = std.math.maxInt(@TypeOf(ts.tv_sec)); ts.tv_nsec = std.time.ns_per_s - 1; }; now = @intCast(u64, ts.tv_sec) * std.time.ns_per_s; now += @intCast(u64, ts.tv_nsec); } var ns = now; if (@addWithOverflow(u64, now, offset, &ns)) ns = std.math.maxInt(u64); return ns; } }); const WindowsFutex = struct { pub fn wait(ptr: *const u32, expected: u32, timeout: ?u64) error{TimedOut}!void { if (WaitOnAddress.isSupported()) return WaitOnAddress.wait(ptr, expected, timeout); return Generic.wait(ptr, expected, timeout); } pub fn wake(ptr: *const u32, waiters: u32) void { if (WaitOnAddress.isSupported()) return WaitOnAddress.wake(ptr, waiters); return Generic.wake(ptr, waiters); } pub fn yield(iteration: usize) bool { return Generic.Event.yield(iteration); } const WaitOnAddress = struct { var state: State = .uninit; var wait_ptr: WaitOnAddressFn = undefined; var wake_one_ptr: WakeByAddressFn = undefined; var wake_all_ptr: WakeByAddressFn = undefined; const State = enum(u8) { uninit, supported, unsupported, }; const WakeByAddressFn = fn ( address: ?*const volatile anyopaque, ) callconv(std.os.windows.WINAPI) void; const WaitOnAddressFn = fn ( address: ?*const volatile anyopaque, compare_address: ?*const anyopaque, address_size: std.os.windows.SIZE_T, timeout_ms: std.os.windows.DWORD, ) callconv(std.os.windows.WINAPI) std.os.windows.BOOL; fn isSupported() bool { return switch (@atomicLoad(State, &state, .Acquire)) { .uninit => checkSupported(), .supported => true, .unsupported => false, }; } fn checkSupported() bool { @setCold(true); const is_supported = tryLoad(); const new_state = if (is_supported) State.supported else .unsupported; @atomicStore(State, &state, new_state, .Release); return is_supported; } fn tryLoad() bool { // MSDN says that the functions are in kernel32.dll, but apparently they aren't... const synch_dll = std.os.windows.kernel32.GetModuleHandleW(blk: { const dll = "api-ms-win-core-synch-l1-2-0.dll"; comptime var wdll = [_]std.os.windows.WCHAR{0} ** (dll.len + 1); inline for (dll) |char, index| wdll[index] = @as(std.os.windows.WCHAR, char); break :blk @ptrCast([*:0]const std.os.windows.WCHAR, &wdll); }) orelse return false; const _wait_ptr = std.os.windows.kernel32.GetProcAddress( synch_dll, "WaitOnAddress\x00", ) orelse return false; const _wake_one_ptr = std.os.windows.kernel32.GetProcAddress( synch_dll, "WakeByAddressSingle\x00", ) orelse return false; const _wake_all_ptr = std.os.windows.kernel32.GetProcAddress( synch_dll, "WakeByAddressAll\x00", ) orelse return false; // Unordered stores since this could be racing with other threads @atomicStore(WaitOnAddressFn, &wait_ptr, @ptrCast(WaitOnAddressFn, _wait_ptr), .Unordered); @atomicStore(WakeByAddressFn, &wake_one_ptr, @ptrCast(WakeByAddressFn, _wake_one_ptr), .Unordered); @atomicStore(WakeByAddressFn, &wake_all_ptr, @ptrCast(WakeByAddressFn, _wake_all_ptr), .Unordered); return true; } fn wait(ptr: *const u32, expected: u32, timeout: ?u64) error{TimedOut}!void { var timeout_ms: std.os.windows.DWORD = std.os.windows.INFINITE; if (timeout) |timeout_ns| { timeout_ms = std.math.cast(std.os.windows.DWORD, timeout_ns / std.time.ns_per_ms) catch timeout_ms; } const status = (wait_ptr)( @ptrCast(*const volatile anyopaque, ptr), @ptrCast(*const anyopaque, &expected), @sizeOf(u32), timeout_ms, ); if (status == std.os.windows.FALSE) { switch (std.os.windows.kernel32.GetLastError()) { .TIMEOUT => {}, else => |err| { const e = std.os.windows.unexpectedError(err); unreachable; }, } } } fn wake(ptr: *const u32, waiters: u32) void { const address = @ptrCast(*const volatile anyopaque, ptr); return switch (waiters) { 0 => {}, 1 => (wake_one_ptr)(address), else => (wake_all_ptr)(address), }; } }; const Generic = GenericFutex(struct { state: State = .empty, lock: std.os.windows.SRWLOCK = std.os.windows.SRWLOCK_INIT, cond: std.os.windows.CONDITION_VARIABLE = std.os.windows.CONDITION_VARIABLE_INIT, const State = enum { empty, waiting, notified, }; pub fn init(self: *@This()) void { self.* = .{}; } pub fn deinit(self: *@This()) void { self.* = undefined; } pub fn set(self: *@This()) void { std.os.windows.kernel32.AcquireSRWLockExclusive(&self.lock); defer std.os.windows.kernel32.ReleaseSRWLockExclusive(&self.lock); const state = self.state; self.state = .notified; switch (state) { .empty => {}, .waiting => std.os.windows.kernel32.WakeConditionVariable(&self.cond), .notified => unreachable, } } threadlocal var frequency: u64 = 0; pub fn wait(self: *@This(), timeout: ?u64) error{TimedOut}!void { var start: u64 = undefined; if (timeout != null) { if (frequency == 0) frequency = std.os.windows.QueryPerformanceFrequency(); start = std.os.windows.QueryPerformanceCounter(); } std.os.windows.kernel32.AcquireSRWLockExclusive(&self.lock); defer std.os.windows.kernel32.ReleaseSRWLockExclusive(&self.lock); switch (self.state) { .empty => self.state = .waiting, .waiting => unreachable, .notified => return, } while (true) { switch (self.state) { .empty => unreachable, .waiting => {}, .notified => return, } var timeout_ms: std.os.windows.DWORD = std.os.windows.INFINITE; if (timeout) |timeout_ns| { const now = std.os.windows.QueryPerformanceCounter(); const elapsed = if (now < start) 0 else blk: { const a = now - start; const b = std.time.ns_per_s; const c = frequency; const q = a / c; const r = a % c; break :blk (q * b) + (r * b) / c; }; if (elapsed > timeout_ns) { self.state = .empty; return error.TimedOut; } const delay_ms = (timeout_ns - elapsed) / std.time.ns_per_ms; timeout_ms = std.math.cast(std.os.windows.DWORD, delay_ms) catch timeout_ms; } const status = std.os.windows.kernel32.SleepConditionVariableSRW( &self.cond, &self.lock, timeout_ms, 0, ); if (status == std.os.windows.FALSE) { switch (std.os.windows.kernel32.GetLastError()) { .TIMEOUT => {}, else => |err| { const e = std.os.windows.unexpectedError(err); unreachable; }, } } } } pub fn yield(iteration: usize) bool { if (iteration > 4000) return false; std.Thread.spinLoopHint(); return true; } }); }; fn GenericFutex(comptime EventImpl: type) type { return struct { pub const Event = EventImpl; const Waiter = struct { prev: ?*Waiter, next: ?*Waiter, address: usize, event: Event, waiting: bool, }; const Bucket = struct { lock: @import("./Lock.zig").Lock = .{}, head: ?*Waiter = null, tail: ?*Waiter = null, waiters: usize = 0, const num_buckets = 256; var buckets = [_]Bucket{.{}} ** num_buckets; fn from(address: usize) *Bucket { const index = (address >> @sizeOf(u32)) % num_buckets; return &buckets[index]; } fn push(self: *Bucket, waiter: *Waiter, address: usize) void { waiter.waiting = true; waiter.address = address; waiter.prev = self.tail; waiter.next = null; if (self.head == null) self.head = waiter; if (self.tail) |tail| tail.next = waiter; self.tail = waiter; } fn pop(self: *Bucket, address: usize, max: usize) ?*Waiter { var removed: usize = 0; var waiters: ?*Waiter = null; var iter = self.head; dequeue: while (removed < max) { const waiter = blk: { while (true) { const waiter = iter orelse break :dequeue; iter = waiter.next; if (waiter.address != address) continue; break :blk waiter; } }; self.remove(waiter); removed += 1; waiter.next = waiters; waiters = waiter; } if (removed > 0) _ = @atomicRmw(usize, &self.waiters, .Sub, removed, .SeqCst); return waiters; } fn remove(self: *Bucket, waiter: *Waiter) void { std.debug.assert(waiter.waiting); waiter.waiting = false; if (waiter.prev) |prev| prev.next = waiter.next; if (waiter.next) |next| next.prev = waiter.prev; if (self.head == waiter) { self.head = waiter.next; if (self.head == null) self.tail = null; } else if (self.tail == waiter) { self.tail = waiter.prev; } } }; pub fn wait(ptr: *const u32, expected: u32, timeout: ?u64) error{TimedOut}!void { const address = @ptrToInt(ptr); const bucket = Bucket.from(address); bucket.lock.acquire(); _ = @atomicRmw(usize, &bucket.waiters, .Add, 1, .SeqCst); if (@atomicLoad(u32, ptr, .SeqCst) != expected) { _ = @atomicRmw(usize, &bucket.waiters, .Sub, 1, .SeqCst); bucket.lock.release(); return; } var waiter: Waiter = undefined; waiter.event.init(); defer waiter.event.deinit(); bucket.push(&waiter, address); bucket.lock.release(); var timed_out = false; waiter.event.wait(timeout) catch { timed_out = true; }; if (timed_out) { bucket.lock.acquire(); if (waiter.waiting) { _ = @atomicRmw(usize, &bucket.waiters, .Sub, 1, .SeqCst); bucket.remove(&waiter); bucket.lock.release(); } else { timed_out = false; bucket.lock.release(); waiter.event.wait(null) catch unreachable; } } if (timed_out) return error.TimedOut; } pub fn wake(ptr: *const u32, waiters: u32) void { const address = @ptrToInt(ptr); const bucket = Bucket.from(address); if (@atomicLoad(usize, &bucket.waiters, .SeqCst) == 0) return; var pending = blk: { bucket.lock.acquire(); defer bucket.lock.release(); break :blk bucket.pop(address, waiters); }; while (pending) |waiter| { pending = waiter.next; waiter.event.set(); } } pub fn yield(iteration: usize) bool { return Event.yield(iteration); } }; }
src/runtime/Futex.zig
const std = @import("std"); const basic_type = @import("basic_type.zig"); const assert = std.debug.assert; const testing = std.testing; const log = std.log.scoped(.grid); const IndexLinkList = @import("IndexLinkList.zig"); const node_null = basic_type.node_null; const Index = basic_type.Index; const Grid = @This(); const Vec2 = basic_type.Vec2; const Node = struct { /// Stores the next element in the cell. next: Index, /// Stores the ID of the element. This can be used to associate external /// data to the element. entity: Index, /// Stores the center position of the uniformly-sized element. m_pos: Vec2, /// Remove a node from the list. pub fn removeNext(node: Index, next: []Index) ?Index { const next_node = next[node]; if (next_node == node_null) return null; next[node] = next[next_node]; return next_node; } pub fn getNext(node: Index, next: []Index) ?Index { const next_node = next[node]; return if (next_node != node_null) next_node else null; } }; const NodeList = std.MultiArrayList(Node); /// Stores the number of columns, rows, and cells in the grid. num_cols: u32, num_rows: u32, num_cells: u32, // Stores the inverse size of a cell. inv_cells_size: f32, // Stores the half-size of all elements stored in the grid. h_size: Vec2, // Stores the lower-left corner of the grid. pos: Vec2, // Stores the size of the grid. width: u32, height: u32, nodes: NodeList.Slice, node_list: NodeList, lists: std.ArrayList(IndexLinkList), free_list: IndexLinkList, allocator: *std.mem.Allocator, pub const InitInfo = struct {}; pub fn init( allocator: *std.mem.Allocator, position: Vec2, h_size: Vec2, cell_size: f32, num_cols: u32, num_rows: u32, ) Grid { var node_list = NodeList{}; return .{ .inv_cells_size = 1.0 / cell_size, .num_cols = num_cols, .num_rows = num_rows, .num_cells = num_cols * num_rows, .pos = position, .width = num_rows * @floatToInt(u32, @floor(cell_size)), .height = num_cols * @floatToInt(u32, @floor(cell_size)), .h_size = h_size, .lists = std.ArrayList(IndexLinkList).init(allocator), .nodes = node_list.slice(), .node_list = node_list, .free_list = IndexLinkList{}, .allocator = allocator, }; } pub fn deinit(self: *Grid) void { self.node_list.deinit(self.allocator); self.lists.deinit(); } pub fn insert(self: *Grid, entity: Index, pos: Vec2) void { self.ensureInitLists(); const cell = self.posToCell(pos); self.insertToCell(cell, Node{ .next = node_null, .entity = entity, .m_pos = pos, }); } fn ensureInitLists(self: *Grid) void { if (self.lists.items.len != 0) return; self.lists.appendNTimes(.{}, self.num_rows * self.num_cols) catch unreachable; } pub fn remove(self: *Grid, entity: Index, m_pos: Vec2) void { const cell = self.posToCell(m_pos); self.removeFromCell(cell, entity); } pub fn move(self: *Grid, entity: Index, from_pos: Vec2, to_pos: Vec2) void { var from_cell = self.posToCell(from_pos); var to_cell = self.posToCell(to_pos); if (from_cell == to_cell) return; self.removeFromCell(from_cell, entity); self.insertToCell(to_cell, Node{ .next = node_null, .entity = entity, .m_pos = to_pos, }); } fn insertToCell(self: *Grid, cell: Index, elt: Node) void { var next = self.nodes.items(.next); const free_node = self.free_list.popFirst(next); if (free_node) |index| { self.node_list.set(index, elt); return self.lists.items[cell].prepend(index, next); } const index = @intCast(Index, self.nodes.len); self.node_list.append(self.allocator, elt) catch unreachable; self.nodes = self.node_list.slice(); self.lists.items[cell].prepend(index, self.nodes.items(.next)); } fn removeFromCell(self: *Grid, cell: Index, entity: Index) void { var lists = self.lists.items; var next = self.nodes.items(.next); var entities = self.nodes.items(.entity); var node = lists[cell].getFirst().?; var prev_idx: ?Index = null; while (entities[node] != entity) { prev_idx = node; node = Node.getNext(node, next).?; } if (prev_idx) |prev| { next[prev] = next[node]; } else { lists[cell].first = next[node]; } } pub fn query(grid: *Grid, m_pos: Vec2, h_size: Vec2, entity: anytype, callback: anytype) void { const CallBackType = std.meta.Child(@TypeOf(callback)); if (!@hasDecl(CallBackType, "onOverlap")) { @compileError("Expect " ++ @typeName(@TypeOf(callback)) ++ " has onCallback function"); } const f_size = h_size.add(grid.h_size); const begin_x = grid.posToGridXClamp(m_pos.x - f_size.x); const end_x = grid.posToGridXClamp(m_pos.x + f_size.x); const end_y = grid.posToGridYClamp(m_pos.y + f_size.y); var current_y = grid.posToGridYClamp(m_pos.y - f_size.y); const lists = grid.lists.items; const next = grid.nodes.items(.next); const entities = grid.nodes.items(.entity); const positions = grid.nodes.items(.m_pos); while (current_y <= end_y) : (current_y += 1) { var current_x = begin_x; while (current_x <= end_x) : (current_x += 1) { const cell = grid.cellIndex(current_x, current_y); var current_idx = lists[cell].getFirst(); while (current_idx) |value| : (current_idx = Node.getNext(value, next)) { if (@TypeOf(entity) == u32) { if (entities[value] == entity) continue; } if (std.math.fabs(m_pos.x - positions[value].x) <= f_size.x and std.math.fabs(m_pos.y - positions[value].y) <= f_size.y) { callback.onOverlap(entity, entities[value]); } } } } } fn posToCell(self: Grid, pos: Vec2) u32 { const x = self.posToGridX(pos.x); const y = self.posToGridY(pos.y); return self.cellIndex(x, y); } fn posToGridX(self: Grid, x: f32) u32 { const local_x = @floor(x) - self.pos.x; return self.localPosToIdx(local_x, self.num_rows); } fn posToGridY(self: Grid, y: f32) u32 { const local_y = @floor(y) - self.pos.y; return self.localPosToIdx(local_y, self.num_cols); } fn localPosToIdx(self: Grid, value: f32, cells: u32) u32 { assert(value >= 0); const idx = @floatToInt(u32, value * self.inv_cells_size); assert(idx < cells); return idx; } fn posToGridXClamp(self: Grid, x: f32) u32 { const local_x = x - self.pos.x; return self.localPosToIdxClamp(local_x, self.num_rows); } fn posToGridYClamp(self: Grid, y: f32) u32 { const local_y = y - self.pos.y; return self.localPosToIdxClamp(local_y, self.num_cols); } fn localPosToIdxClamp(self: Grid, value: f32, cells: u32) u32 { if (value < 0) return 0; return std.math.min( @floatToInt(u32, value * self.inv_cells_size), cells - 1, ); } fn cellIndex(self: Grid, grid_x: u32, grid_y: u32) u32 { return grid_y * self.num_rows + grid_x; } test "Performance" { std.debug.print("\n", .{}); const x = 100; const y = 100; const size = 4; const h_size = @intToFloat(f32, size) / 4; const total = x * y * 4; var random = std.rand.Xoshiro256.init(0).random(); const Entity = std.MultiArrayList(struct { entity: u32, pos: Vec2, half_size: f32, }); const allocator = std.testing.allocator; var grid = Grid.init( testing.allocator, Vec2.new(0, 0), Vec2.new(h_size, h_size), size, x, y, ); defer grid.deinit(); var manager = Entity{}; defer manager.deinit(allocator); try manager.setCapacity(allocator, total); { var entity: u32 = 0; while (entity < total) : (entity += 1) { const x_pos = random.float(f32) * @intToFloat(f32, x * size); const y_pos = random.float(f32) * @intToFloat(f32, y * size); const pos = Vec2.new(x_pos, y_pos); try manager.append(allocator, .{ .entity = entity, .pos = pos, .half_size = 1.0, }); } } var slice = manager.slice(); var entities = slice.items(.entity); var position = slice.items(.pos); { var timer = try std.time.Timer.start(); var index: u32 = 0; while (index < slice.len) : (index += 1) { grid.insert(entities[index], position[index]); } const time_0 = timer.read(); std.debug.print("add {} entity take {}ms\n", .{ total, time_0 / std.time.ns_per_ms }); } const total_loop = 20; var current_loop: u32 = 0; var move_time: u64 = 0; var query_time: u64 = 0; while (current_loop < total_loop) : (current_loop += 1) { { var timer = try std.time.Timer.start(); var entity: u32 = 0; while (entity < total) : (entity += 1) { const x_pos = random.float(f32) * @intToFloat(f32, x * size); const y_pos = random.float(f32) * @intToFloat(f32, y * size); const pos = Vec2.new(x_pos, y_pos); grid.move(entities[entity], position[entity], pos); position[entity] = pos; } const time_0 = timer.read(); move_time += time_0 / std.time.ns_per_ms; } { const QueryCallback = struct { total: u32 = 0, pub fn onOverlap(self: *@This(), payload: u32, entity: u32) void { if (payload >= entity) return; self.total += 1; } }; var callback = QueryCallback{}; var entity: u32 = 0; const esize = Vec2.new(size / 4, size / 4); var timer = try std.time.Timer.start(); while (entity < slice.len) : (entity += 1) { grid.query(position[entity], esize, entities[entity], &callback); } const time_0 = timer.read(); query_time += time_0 / std.time.ns_per_ms; } } std.debug.print("move take {}ms\n", .{move_time / total_loop}); std.debug.print("query take {}ms\n", .{query_time / total_loop}); }
src/physic/Grid.zig
const builtin = @import("builtin"); const std = @import("std"); const assert = std.debug.assert; const root = @import("root"); pub const pl = if (builtin.os.tag == .windows) WindowsPlatform else UnixPlatform; // win32.h const WindowsPlatform = struct { const ws2 = std.os.windows.ws2_32; pub const SocketHandle = ws2.SOCKET; pub const SOCKET_NULL = ws2.INVALID_SOCKET; pub const Buffer = extern struct { dataLength: usize, data: [*]u8, }; const FD_SETSIZE = 64; /// This structure is binary compatible with fd_set pub const SocketSet = extern struct { fd_count: c_uint = 0, fd_array: [FD_SETSIZE]SocketHandle align(8) = undefined, /// AKA FD_ZERO pub fn empty(self: *SocketSet) void { self.fd_count = 0; } /// AKA FD_SET /// Mimics the winsock2 version, which checks for duplicates. pub fn add(self: *SocketSet, socket: SocketHandle) void { for (self.fd_array[0..self.fd_count]) |handle| { if (handle == socket) break; } else if (self.fd_count < FD_SETSIZE) { self.fd_array[self.fd_count] = socket; self.fd_count += 1; } } /// AKA FD_CLR pub fn remove(self: *SocketSet, socket: SocketHandle) void { var i: c_uint = 0; while (i < self.fd_count) : (i += 1) { if (self.fd_array[i] == socket) { self.fd_count -= 1; while (i < self.fd_count) { self.fd_array[i] = self.fd_array[i + 1]; } break; } } } /// AKA FD_ISSET pub fn check(self: *SocketSet, socket: SocketHandle) c_int { return __WSAFDIsSet(socket, self); } extern "ws2_32" fn __WSAFDIsSet(socket: SocketHandle, set: *SocketSet) c_int; }; }; // unix.h const UnixPlatform = struct { pub const SocketHandle = c_int; pub const SOCKET_NULL: SocketHandle = -1; pub const Buffer = extern struct { data: [*]u8, dataLength: usize, }; const SocketSet = extern struct { const max_fd = 1024; const Mask = c_long; const MaskShift = std.math.Log2Int(Mask); const mask_bits = 8 * @sizeOf(Mask); const num_masks = @divExact(max_fd, mask_bits); fds_bits: [num_masks]Mask = [_]Mask{0} ** num_masks, /// FD_ZERO pub fn empty(self: *SocketSet) void { self.* = .{}; } /// FD_SET pub fn add(self: *SocketSet, socket: SocketHandle) void { assert(socket >= 0); assert(socket < max_fd); self.fds_bits[index(socket)] |= mask(socket); } /// FD_CLR pub fn remove(self: *SocketSet, socket: SocketHandle) void { assert(socket >= 0); assert(socket < max_fd); self.fds_bits[index(socket)] &= ~mask(socket); } /// FD_ISSET pub fn check(self: *SocketSet, socket: SocketHandle) bool { return (self.fds_bits[index(socket)] & mask(socket)) != 0; } fn index(fd: SocketHandle) usize { return @intCast(usize, @divFloor(fd, mask_bits)); } fn mask(fd: SocketHandle) Mask { return @shlExact(@as(Mask, 1), @intCast(MaskShift, @mod(fd, mask_bits))); } }; }; pub inline fn HOST_TO_NET(a: anytype) @TypeOf(a) { if (builtin.endian == .little) { return @byteSwap(@TypeOf(a), a); } else { return a; } } pub inline fn NET_TO_HOST(a: anytype) @TypeOf(a) { if (builtin.endian == .little) { return @byteSwap(@TypeOf(a), a); } else { return a; } } pub const time = struct { pub const OVERFLOW = 86400000; pub inline fn less(a: u32, b: u32) bool { return (a -% b) >= OVERFLOW; } pub inline fn greater(a: u32, b: u32) bool { return (b -% a) >= OVERFLOW; } pub inline fn less_equal(a: u32, b: u32) bool { return !greater(a, b); } pub inline fn greater_equal(a: u32, b: u32) bool { return !less(a, b); } }; // enet/protocol.h pub const Protocol = packed union { pub const MINIMUM_MTU = 576; pub const MAXIMUM_MTU = 4096; pub const MAXIMUM_PACKET_COMMANDS = 32; pub const MINIMUM_WINDOW_SIZE = 4096; pub const MAXIMUM_WINDOW_SIZE = 65536; pub const MINIMUM_CHANNEL_COUNT = 1; pub const MAXIMUM_CHANNEL_COUNT = 255; pub const MAXIMUM_PEER_ID = 0xFFF; pub const MAXIMUM_FRAGMENT_COUNT = 1024 * 1024; header: CommandHeader, acknowledge: Acknowledge, connect: Connect, verifyConnect: VerifyConnect, disconnect: Disconnect, ping: Ping, sendReliable: SendReliable, sendUnreliable: SendUnreliable, sendUnsequenced: SendUnsequenced, sendFragment: SendFragment, bandwidthLimit: BandwidthLimit, throttleConfigure: ThrottleConfigure, pub const Command = enum(u8) { none = 0, acknowledge = 1, connect = 2, verify_connect = 3, disconnect = 4, ping = 5, send_reliable = 6, send_unreliable = 7, send_fragment = 8, send_unsequenced = 9, bandwidth_limit = 10, throttle_configure = 11, send_unreliable_fragment = 12, pub const count = 13; pub const mask = 0xF; }; pub const Flags = packed struct { __pad0: u6 = 0, command_unsequenced: bool = false, command_acknowledge: bool = false, __pad1: u4 = 0, header_session: u2 = 0, header_compressed: bool = false, header_sent_time: bool = false, __pad2: u16 = 0, pub const header_mask = Flags{ .header_compressed = true, .header_sent_time = true }; }; pub const Header = packed struct { peerID: u16, sentTime: u16, }; pub const CommandHeader = packed struct { command: Command, channelID: u8, reliableSequenceNumber: u16, }; pub const Acknowledge = packed struct { header: CommandHeader, receivedReliableSequenceNumber: u16, receivedSentTime: u16, }; pub const Connect = packed struct { header: CommandHeader, outgoingPeerID: u16, incomingSessionID: u8, outgoingSessionID: u8, mtu: u32, windowSize: u32, channelCount: u32, incomingBandwidth: u32, outgoingBandwidth: u32, packetThrottleInterval: u32, packetThrottleAcceleration: u32, packetThrottleDeceleration: u32, connectID: u32, data: u32, }; pub const VerifyConnect = packed struct { header: CommandHeader, outgoingPeerID: u16, incomingSessionID: u8, outgoingSessionID: u8, mtu: u32, windowSize: u32, channelCount: u32, incomingBandwidth: u32, outgoingBandwidth: u32, packetThrottleInterval: u32, packetThrottleAcceleration: u32, packetThrottleDeceleration: u32, connectID: u32, }; pub const BandwidthLimit = packed struct { header: CommandHeader, incomingBandwidth: u32, outgoingBandwidth: u32, }; pub const ThrottleConfigure = packed struct { header: CommandHeader, packetThrottleInterval: u32, packetThrottleAcceleration: u32, packetThrottleDeceleration: u32, }; pub const Disconnect = packed struct { header: CommandHeader, data: u32, }; pub const Ping = packed struct { header: CommandHeader, }; pub const SendReliable = packed struct { header: CommandHeader, dataLength: u16, }; pub const SendUnreliable = packed struct { header: CommandHeader, unreliableSequenceNumber: u16, dataLength: u16, }; pub const SendUnsequenced = packed struct { header: CommandHeader, unsequencedGroup: u16, dataLength: u16, }; pub const SendFragment = packed struct { header: CommandHeader, startSequenceNumber: u16, dataLength: u16, fragmentCount: u32, fragmentNumber: u32, totalLength: u32, fragmentOffset: u32, }; }; // enet/list.h pub const ListNode = extern struct { next: *ListNode, previous: *ListNode, /// Insert a new node before this node /// Returns the new node. pub fn insert_previous(self: *ListNode, new_node: *ListNode) *ListNode { new_node.previous = self.previous; new_node.next = self; new_node.previous.next = new_node; self.previous = new_node; return new_node; } /// Remove this node from the list. /// Returns this node pub fn remove(self: *ListNode) *ListNode { self.previous.next = self.next; self.next.previous = self.previous; return self; } /// Insert a range of nodes into this list, before this node. /// Returns the first node in the moved list pub fn move_previous(self: *ListNode, first: *ListNode, last: *ListNode) *ListNode { first.previous.next = last.next; last.next.previous = first.previous; first.previous = self.previous; last.next = self; first.previous.next = first; self.previous = last; return first; } }; pub fn List(comptime T: type) type { return extern struct { sentinel: ListNode, /// Empties the list pub inline fn clear(self: *@This()) void { self.sentinel.next = &self.sentinel; self.sentinel.previous = &self.sentinel; } /// Checks if the list is empty pub inline fn empty(self: *@This()) bool { return self.sentinel.next == &self.sentinel; } /// Computes the size of the list pub fn size(self: *@This()) usize { var count: usize = 0; var curr = self.begin(); const sentinel = self.end(); while (curr != sentinel) { curr = curr.next; count += 1; } return count; } /// Returns the first item in the list. pub inline fn front(self: *@This()) *T { assert(!self.empty()); return @intToPtr(*T, @ptrToInt(self.sentinel.next)); } /// Returns the last item in the list. pub inline fn back(self: *@This()) *T { assert(!self.empty()); return @intToPtr(*T, @ptrToInt(self.sentinel.previous)); } /// Returns a pointer to the first node in the list pub inline fn begin(self: *@This()) *ListNode { return self.sentinel.next; } /// Returns a pointer to one past the last node in the list /// or one before the first node in the list pub inline fn end(self: *@This()) *ListNode { return &self.sentinel; } /// Returns an iterator pub fn iterator(self: *@This()) Iterator { return .{ .next = self.begin(), .end = self.end() }; } const Iterator = struct { next: *ListNode, end: *ListNode, pub fn next(self: *Iterator) ?*T { if (self.next == self.end) return null; const curr = self.next; self.next = curr.next; return @intToPtr(*T, @ptrToInt(curr)); } }; }; } // enet/callbacks.h pub const Callbacks = extern struct { malloc: ?fn (size: usize) callconv(.C) *anyopaque = null, free: ?fn (memory: *anyopaque) callconv(.C) void = null, no_memory: ?fn () callconv(.C) void = null, }; // enet/enet.h pub const VERSION_MAJOR = 1; pub const VERSION_MINOR = 3; pub const VERSION_PATCH = 16; pub fn VERSION_CREATE(major: u8, minor: u8, patch: u8) Version { return @shlExact(@as(Version, major), 16) | @shlExact(@as(Version, minor), 8) | @shlExact(@as(Version, patch), 0); } pub fn VERSION_GET_MAJOR(version: Version) u8 { return @truncate(u8, version >> 16); } pub fn VERSION_GET_MINOR(version: Version) u8 { return @truncate(u8, version >> 8); } pub fn VERSION_GET_PATCH(version: Version) u8 { return @truncate(u8, version >> 0); } pub const VERSION = VERSION_CREATE(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); pub const Version = u32; pub const SocketType = enum(c_int) { Stream = 1, Datagram = 2, }; pub const SocketWait = packed struct { send: bool = false, receive: bool = false, interrupt: bool = false, __pad: u29 = 0, }; comptime { assert(@sizeOf(SocketWait) == 4); } pub const SocketOption = enum(c_int) { nonblock = 1, broadcast = 2, rcvbuf = 3, sndbuf = 4, reuseaddr = 5, rcvtimeo = 6, sndtimeo = 7, opt_error = 8, // changed from "error" because that's a keyword nodelay = 9, }; pub const SocketShutdown = enum(c_int) { read = 0, write = 1, read_write = 2, }; pub const Socket = extern struct { handle: pl.SocketHandle, pub fn create(kind: SocketType) !Socket { const handle = raw.enet_socket_create(kind); if (handle == pl.SOCKET_NULL) return error.ENetError; return Socket{ .handle = handle }; } pub fn bind(self: Socket, address: Address) !void { const rc = raw.enet_socket_bind(self.handle, &address); if (rc < 0) return error.ENetError; } pub fn get_address(self: Socket) !Address { var address: Address = undefined; const rc = raw.enet_socket_get_address(self.handle, &address); if (rc < 0) return error.ENetError; return address; } pub fn listen(self: Socket, backlog: c_int) !void { const rc = raw.enet_socket_listen(self.handle, backlog); if (rc < 0) return error.ENetError; } pub fn accept(self: Socket, out_address: ?*Address) !Socket { const socket = raw.enet_socket_accept(self.handle, out_address); if (socket == pl.SOCKET_NULL) return error.ENetError; return Socket{ .handle = socket }; } pub fn connect(self: Socket, address: Address) !void { const rc = raw.enet_socket_connect(self.handle, &address); if (rc < 0) return error.ENetError; } pub fn send(self: Socket, buffers: []const pl.Buffer) !usize { const rc = raw.enet_socket_send(self.handle, null, buffers.ptr, buffers.len); if (rc < 0) return error.ENetError; return @intCast(usize, rc); } pub fn sendTo(self: Socket, address: Address, buffers: []const pl.Buffer) !usize { const rc = raw.enet_socket_send(self.handle, &address, buffers.ptr, buffers.len); if (rc < 0) return error.ENetError; return @intCast(usize, rc); } pub fn receive(self: Socket, out_address: ?*Address, buffers: []pl.Buffer) !usize { const rc = raw.enet_socket_receive(self.handle, out_address, buffers.ptr, buffers.len); if (rc < 0) return error.ENetError; return @intCast(usize, rc); } pub fn wait(self: Socket, condition: SocketWait, timeout: u32) !SocketWait { var mut_cond = @bitCast(u32, condition); const rc = raw.enet_socket_wait(self.handle, &mut_cond, timeout); if (rc < 0) return error.ENetError; return @bitCast(SocketWait, mut_cond); } pub fn set_option(self: Socket, option: SocketOption, value: c_int) !void { const rc = raw.enet_socket_set_option(self.handle, option, value); if (rc < 0) return error.ENetError; } pub fn get_option(self: Socket, option: SocketOption) !c_int { var value: c_int = undefined; const rc = raw.enet_socket_get_option(self.handle, option, &value); if (rc < 0) return error.ENetError; return value; } pub fn shutdown(self: Socket, how: SocketShutdown) !void { const rc = raw.enet_socket_shutdown(self.handle, how); if (rc < 0) return error.ENetError; } pub fn destroy(self: Socket) void { raw.enet_socket_destroy(self.handle); } }; pub const HOST_ANY = 0; pub const HOST_BROADCAST = 0xFFFFFFFF; pub const PORT_ANY = 0; /// Portable internet address structure. /// /// The host must be specified in network byte-order, and the port must be in host /// byte-order. The constant HOST_ANY may be used to specify the default /// server host. The constant HOST_BROADCAST may be used to specify the /// broadcast address (255.255.255.255). This makes sense for enet_host_connect, /// but not for enet_host_create. Once a server responds to a broadcast, the /// address is updated from HOST_BROADCAST to the server's actual IP address. pub const Address = extern struct { host: u32, port: u16, /// Attempts to parse the printable form of the IP address in the parameter hostName /// and sets the host field in the address parameter if successful. /// @param address destination to store the parsed IP address /// @param hostName IP address to parse pub fn set_host_ip(self: *Address, hostName: [*:0]const u8) !void { const rc = raw.enet_address_set_host_ip(self, hostName); if (rc < 0) return error.ENetError; } /// Attempts to resolve the host named by the parameter hostName and sets /// the host field in the address parameter if successful. /// @param address destination to store resolved address /// @param hostName host name to lookup pub fn set_host(self: *Address, hostName: [*:0]const u8) !void { const rc = raw.enet_address_set_host(self, hostName); if (rc < 0) return error.ENetError; } /// Gives the printable form of the IP address specified in the address parameter. /// @param address address printed /// @param buffer destination for name /// @returns the null-terminated name of the host on success pub fn get_host_ip(self: Address, buffer: []u8) ![*:0]u8 { const rc = raw.enet_address_get_host_ip(&self, buffer.ptr, buffer.len); if (rc < 0) return error.ENetError; return @ptrCast([*:0]u8, buffer.ptr); } /// Attempts to do a reverse lookup of the host field in the address parameter. /// @param address address used for reverse lookup /// @param buffer destination for name, must not be NULL /// @returns the null-terminated name of the host on success pub fn get_host(self: Address, buffer: []u8) ![*:0]u8 { const rc = raw.enet_address_get_host(&self, buffer.ptr, buffer.len); if (rc < 0) return error.ENetError; return @ptrCast([*:0]u8, buffer.ptr); } }; /// Packet flag bit constants. /// /// The host must be specified in network byte-order, and the port must be in /// host byte-order. The constant HOST_ANY may be used to specify the /// default server host. pub const PacketFlags = packed struct { /// packet must be received by the target peer and resend attempts should be /// made until the packet is delivered reliable: bool = false, /// packet will not be sequenced with other packets /// not supported for reliable packets unsequenced: bool = false, /// packet will not allocate data, and user must supply it instead no_allocate: bool = false, /// packet will be fragmented using unreliable (instead of reliable) sends /// if it exceeds the MTU unreliable_fragment: bool = false, __pad0: u4 = 0, /// whether the packet has been sent from all queues it has been entered into sent: bool = false, // split padding to avoid packed struct bugs __pad1: u7 = 0, __pad2: u16 = 0, }; comptime { assert(@sizeOf(PacketFlags) == 4); } pub const PacketFreeCallback = fn (*Packet) callconv(.C) void; /// ENet packet structure. /// /// An ENet data packet that may be sent to or received from a peer. The shown /// fields should only be read and never modified. The data field contains the /// allocated data for the packet. The dataLength fields specifies the length /// of the allocated data. The flags field is either 0 (specifying no flags), /// or a bitwise-or of any combination of the following flags: /// /// reliable - packet must be received by the target peer /// and resend attempts should be made until the packet is delivered /// /// unsequenced - packet will not be sequenced with other packets /// (not supported for reliable packets) /// /// no_allocate - packet will not allocate data, and user must supply it instead /// /// unreliable_fragment - packet will be fragmented using unreliable /// (instead of reliable) sends if it exceeds the MTU /// /// sent - whether the packet has been sent from all queues it has been entered into /// @sa PacketFlag pub const Packet = extern struct { /// internal use only referenceCount: usize, /// packet flags flags: PacketFlags, /// allocated data for packet data: ?[*]u8, /// length of data dataLength: usize, /// function to be called when the packet is no longer in use freeCallback: ?PacketFreeCallback, /// application private data, may be freely modified userData: ?*anyopaque, /// Creates a packet that may be sent to a peer. /// @param data initial contents of the packet's data pub fn create(data: []u8, flags: PacketFlags) !*Packet { const packet = raw.enet_packet_create(data.ptr, data.len, @bitCast(u32, flags)); if (packet) |p| return p; return error.ENetError; } /// Creates a packet that may be sent to a peer. /// @param len length of the packet's data pub fn create_uninitialized(len: usize, flags: PacketFlags) !*Packet { const packet = raw.enet_packet_create(null, len, @bitCast(u32, flags)); if (packet) |p| return p; return error.ENetError; } /// Destroys the packet and deallocates its data. pub fn destroy(self: *Packet) void { raw.enet_packet_destroy(self); } /// Attempts to resize the data in the packet to length specified in the /// dataLength parameter /// @param dataLength new size for the packet data pub fn resize(self: *Packet, len: usize) !void { const rc = raw.enet_packet_resize(self, len); if (rc < 0) return error.ENetError; } }; pub const Acknowledgement = extern struct { acknowledgementList: ListNode, sentTime: u32, command: Protocol, }; pub const OutgoingCommand = extern struct { outgoingCommandList: ListNode, reliableSequenceNumber: u16, unreliableSequenceNumber: u16, sentTime: u32, roundTripTimeout: u32, roundTripTimeoutLimit: u32, fragmentOffset: u32, fragmentLength: u16, sendAttempts: u16, command: Protocol, packet: ?*Packet, }; pub const IncomingCommand = extern struct { incomingCommandList: ListNode, reliableSequenceNumber: u16, unreliableSequenceNumber: u16, command: Protocol, fragmentCount: u32, fragmentsRemaining: u32, fragments: ?[*]u32, packet: ?*Packet, }; pub const PeerState = enum(c_int) { disconnected = 0, connecting = 1, acknowledging_connect = 2, connection_pending = 3, connection_succeeded = 4, connected = 5, disconnect_later = 6, disconnecting = 7, acknowledging_disconnect = 8, zombie = 9, }; pub const BUFFER_MAXIMUM = if (@hasDecl(root, "ENET_BUFFER_MAXIMUM")) root.ENET_BUFFER_MAXIMUM else (1 + 2 * Protocol.MAXIMUM_PACKET_COMMANDS); pub const HOST_RECEIVE_BUFFER_SIZE = 256 * 1024; pub const HOST_SEND_BUFFER_SIZE = 256 * 1024; pub const HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000; pub const HOST_DEFAULT_MTU = 1400; pub const HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024; pub const HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024; pub const PEER_DEFAULT_ROUND_TRIP_TIME = 500; pub const PEER_DEFAULT_PACKET_THROTTLE = 32; pub const PEER_PACKET_THROTTLE_SCALE = 32; pub const PEER_PACKET_THROTTLE_COUNTER = 7; pub const PEER_PACKET_THROTTLE_ACCELERATION = 2; pub const PEER_PACKET_THROTTLE_DECELERATION = 2; pub const PEER_PACKET_THROTTLE_INTERVAL = 5000; pub const PEER_PACKET_LOSS_SCALE = (1 << 16); pub const PEER_PACKET_LOSS_INTERVAL = 10000; pub const PEER_WINDOW_SIZE_SCALE = 64 * 1024; pub const PEER_TIMEOUT_LIMIT = 32; pub const PEER_TIMEOUT_MINIMUM = 5000; pub const PEER_TIMEOUT_MAXIMUM = 30000; pub const PEER_PING_INTERVAL = 500; pub const PEER_UNSEQUENCED_WINDOWS = 64; pub const PEER_UNSEQUENCED_WINDOW_SIZE = 1024; pub const PEER_FREE_UNSEQUENCED_WINDOWS = 32; pub const PEER_RELIABLE_WINDOWS = 16; pub const PEER_RELIABLE_WINDOW_SIZE = 0x1000; pub const PEER_FREE_RELIABLE_WINDOWS = 8; pub const Channel = extern struct { outgoingReliableSequenceNumber: u16, outgoingUnreliableSequenceNumber: u16, usedReliableWindows: u16, reliableWindows: [PEER_RELIABLE_WINDOWS]u16, incomingReliableSequenceNumber: u16, incomingUnreliableSequenceNumber: u16, incomingReliableCommands: List(IncomingCommand), incomingUnreliableCommands: List(IncomingCommand), }; pub const PeerFlags = packed struct { needs_dispatch: bool = false, __pad0: u15 = 0, }; comptime { assert(@sizeOf(PeerFlags) == 2); } /// An ENet peer which data packets may be sent or received from. /// /// No fields should be modified unless otherwise specified. pub const Peer = extern struct { dispatchList: ListNode, host: ?*Host, outgoingPeerID: u16, incomingPeerID: u16, connectID: u32, outgoingSessionID: u8, incomingSessionID: u8, /// Internet address of the peer address: Address, /// Application private data, may be freely modified data: ?*anyopaque, state: PeerState, channels: ?[*]Channel, /// Number of channels allocated for communication with peer channelCount: usize, /// Downstream bandwidth of the client in bytes/second incomingBandwidth: u32, /// Upstream bandwidth of the client in bytes/second outgoingBandwidth: u32, incomingBandwidthThrottleEpoch: u32, outgoingBandwidthThrottleEpoch: u32, incomingDataTotal: u32, outgoingDataTotal: u32, lastSendTime: u32, lastReceiveTime: u32, nextTimeout: u32, earliestTimeout: u32, packetLossEpoch: u32, packetsSent: u32, packetsLost: u32, /// mean packet loss of reliable packets as a ratio with respect to the constant PEER_PACKET_LOSS_SCALE packetLoss: u32, packetLossVariance: u32, packetThrottle: u32, packetThrottleLimit: u32, packetThrottleCounter: u32, packetThrottleEpoch: u32, packetThrottleAcceleration: u32, packetThrottleDeceleration: u32, packetThrottleInterval: u32, pingInterval: u32, timeoutLimit: u32, timeoutMinimum: u32, timeoutMaxiumum: u32, lastRoundTripTime: u32, lowestRoundTripTime: u32, lastRoundTripTimeVariance: u32, highestRoundTripTimeVariance: u32, /// mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgement roundTripTime: u32, roundTripTimeVariance: u32, mtu: u32, windowSize: u32, reliableDataInTransit: u32, outgoingReliableSequenceNumber: u16, acknowledgements: List(Acknowledgement), sendReliableCommands: List(OutgoingCommand), sentUnreliableCommands: List(OutgoingCommand), outgoingCommands: List(OutgoingCommand), dispatchedCommands: List(OutgoingCommand), flags: PeerFlags, reserved: u16, incomingUnsequencedGroup: u16, outgoingUnsequencedGroup: u16, unsequencedWindow: [@divExact(PEER_UNSEQUENCED_WINDOW_SIZE, 32)]u32, eventData: u32, totalWaitingData: usize, /// Queues a packet to be sent. /// @param peer destination for the packet /// @param channelID channel on which to send /// @param packet packet to send pub fn send(self: *Peer, channelID: u8, packet: *Packet) !void { const rc = raw.enet_peer_send(self, channelID, packet); if (rc < 0) return error.ENetError; } /// Attempts to dequeue any incoming queued packet. /// @param peer peer to dequeue packets from /// @param channelID holds the channel ID of the channel the packet was received on success /// @returns a pointer to the packet, or NULL if there are no available incoming queued packets pub fn receive(self: *Peer, out_channelID: *u8) ?*Packet { return raw.enet_peer_receive(self, out_channelID); } /// Sends a ping request to a peer. /// @param peer destination for the ping request /// @remarks ping requests factor into the mean round trip time as designated by the /// roundTripTime field in the Peer structure. ENet automatically pings all connected /// peers at regular intervals, however, this function may be called to ensure more /// frequent ping requests. pub fn ping(self: *Peer) void { raw.enet_peer_ping(self); } /// Sets the interval at which pings will be sent to a peer. /// /// Pings are used both to monitor the liveness of the connection and also to dynamically /// adjust the throttle during periods of low traffic so that the throttle has reasonable /// responsiveness during traffic spikes. /// @param peer the peer to adjust /// @param pingInterval the interval at which to send pings; defaults to PEER_PING_INTERVAL if 0 pub fn ping_interval(self: *Peer, interval: u32) void { raw.enet_peer_ping_interval(self, interval); } /// Sets the timeout parameters for a peer. /// /// The timeout parameter control how and when a peer will timeout from a failure to acknowledge /// reliable traffic. Timeout values use an exponential backoff mechanism, where if a reliable /// packet is not acknowledge within some multiple of the average RTT plus a variance tolerance, /// the timeout will be doubled until it reaches a set limit. If the timeout is thus at this /// limit and reliable packets have been sent but not acknowledged within a certain minimum time /// period, the peer will be disconnected. Alternatively, if reliable packets have been sent /// but not acknowledged for a certain maximum time period, the peer will be disconnected regardless /// of the current timeout limit value. /// /// @param peer the peer to adjust /// @param timeoutLimit the timeout limit; defaults to PEER_TIMEOUT_LIMIT if 0 /// @param timeoutMinimum the timeout minimum; defaults to PEER_TIMEOUT_MINIMUM if 0 /// @param timeoutMaximum the timeout maximum; defaults to PEER_TIMEOUT_MAXIMUM if 0 pub fn timeout(self: *Peer, timeoutLimit: u32, timeoutMinimum: u32, timeoutMaximum: u32) void { raw.enet_peer_timeout(self, timeoutLimit, timeoutMinimum, timeoutMaximum); } /// Forcefully disconnects a peer. /// @param peer peer to forcefully disconnect /// @remarks The foreign host represented by the peer is not notified of the disconnection and will timeout /// on its connection to the local host. pub fn reset(self: *Peer) void { raw.enet_peer_reset(self); } /// Request a disconnection from a peer. /// @param peer peer to request a disconnection /// @param data data describing the disconnection /// @remarks A .disconnect event will be generated by Host.service() /// once the disconnection is complete. pub fn disconnect(self: *Peer, data: u32) void { raw.enet_peer_disconnect(self, data); } /// Force an immediate disconnection from a peer. /// @param peer peer to disconnect /// @param data data describing the disconnection /// @remarks No .disconnect event will be generated. The foreign peer is not /// guaranteed to receive the disconnect notification, and is reset immediately upon /// return from this function. pub fn disconnect_now(self: *Peer, data: u32) void { raw.enet_peer_disconnect_now(self, data); } /// Request a disconnection from a peer, but only after all queued outgoing packets are sent. /// @param peer peer to request a disconnection /// @param data data describing the disconnection /// @remarks A .disconnect event will be generated by Host.service() /// once the disconnection is complete. pub fn disconnect_later(self: *Peer, data: u32) void { raw.enet_peer_disconnect_later(self, data); } /// Configures throttle parameter for a peer. /// /// Unreliable packets are dropped by ENet in response to the varying conditions /// of the Internet connection to the peer. The throttle represents a probability /// that an unreliable packet should not be dropped and thus sent by ENet to the peer. /// The lowest mean round trip time from the sending of a reliable packet to the /// receipt of its acknowledgement is measured over an amount of time specified by /// the interval parameter in milliseconds. If a measured round trip time happens to /// be significantly less than the mean round trip time measured over the interval, /// then the throttle probability is increased to allow more traffic by an amount /// specified in the acceleration parameter, which is a ratio to the PEER_PACKET_THROTTLE_SCALE /// constant. If a measured round trip time happens to be significantly greater than /// the mean round trip time measured over the interval, then the throttle probability /// is decreased to limit traffic by an amount specified in the deceleration parameter, which /// is a ratio to the PEER_PACKET_THROTTLE_SCALE constant. When the throttle has /// a value of PEER_PACKET_THROTTLE_SCALE, no unreliable packets are dropped by /// ENet, and so 100% of all unreliable packets will be sent. When the throttle has a /// value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable /// packets will be sent. Intermediate values for the throttle represent intermediate /// probabilities between 0% and 100% of unreliable packets being sent. The bandwidth /// limits of the local and foreign hosts are taken into account to determine a /// sensible limit for the throttle probability above which it should not raise even in /// the best of conditions. /// /// @param peer peer to configure /// @param interval interval, in milliseconds, over which to measure lowest mean RTT; the default value is PEER_PACKET_THROTTLE_INTERVAL. /// @param acceleration rate at which to increase the throttle probability as mean RTT declines /// @param deceleration rate at which to decrease the throttle probability as mean RTT increases pub fn throttle_configure(self: *Peer, interval: u32, acceleration: u32, deceleration: u32) void { raw.enet_peer_throttle_configure(self, interval, acceleration, deceleration); } }; pub const Compressor = extern struct { /// Context data for the compressor. Must be non-NULL. context: *anyopaque, /// Compresses from inBuffers[0..inBufferCount], containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. compress: fn ( context: *anyopaque, inBuffers: [*]const pl.Buffer, inBufferCount: usize, inLimit: usize, outData: [*]u8, outLimit: usize, ) callconv(.C) usize, /// Decompresses from inData, containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. decompress: fn ( context: *anyopaque, inData: [*]const u8, inLimit: usize, outData: [*]u8, outLimit: usize, ) callconv(.C) usize, /// Destroys the context when compression is disabled or the host is destroyed. May be NULL. destroy: ?fn ( context: *anyopaque, ) callconv(.C) void, }; /// Callback that computes the checksum of the data held in buffers[0..bufferCount] pub const ChecksumCallback = fn (buffers: [*]const pl.Buffer, bufferCount: usize) callconv(.C) u32; /// Callback for intercepting received raw UDP packets. Should return 1 to intercept, 0 to ignore, or -1 to propagate an error. pub const InterceptCallback = fn (host: ?*Host, event: ?*Event) callconv(.C) c_int; /// An ENet host for communicating with peers. /// /// No fields should be modified unless otherwise stated. pub const Host = extern struct { socket: Socket, /// Internet address of the host address: Address, /// downstream bandwidth of the host incomingBandwidth: u32, /// upstream bandwidth of the host outgoingBandwidth: u32, bandwidthThrottleEpoch: u32, mtu: u32, randomSeed: u32, recalculateBandwidthLimits: c_int, /// array of peers allocated for this host peers: ?[*]Peer, /// number of peers allocated for this host peerCount: usize, /// maximum number of channels allowed for connected peers channelLimit: usize, serviceTime: u32, dispatchQueue: List(Peer), continueSending: c_int, packetSize: usize, headerFlags: u16, // TODO is this a flag type? commands: [Protocol.MAXIMUM_PACKET_COMMANDS]Protocol, commandCount: usize, buffers: [BUFFER_MAXIMUM]pl.Buffer, bufferCount: usize, /// callback the user can set to enable packet checksums for this host checksum: ?ChecksumCallback, compressor: Compressor, packetData: [2][Protocol.MAXIMUM_MTU]u8, receivedAddress: Address, receivedData: ?[*]u8, receivedDataLength: usize, /// total data sent, user should reset to 0 as needed to prevent overflow totalSentData: u32, /// total UDP packets sent, user should reset to 0 as needed to prevent overflow totalSentPackets: u32, /// total data received, user should reset to 0 as needed to prevent overflow totalReceivedData: u32, /// total UDP packets received, user should reset to 0 as needed to prevent overflow totalReceivedPackets: u32, /// callback the user can set to intercept received raw UDP packets intercept: ?InterceptCallback, connectedPeers: usize, bandwidthLimitedPeers: usize, /// optional number of allowed peers from duplicate IPs, defaults to Protocol.MAXIMUM_PEER_ID duplicatePeers: usize, /// the maximum allowable packet size that may be sent or received on a peer maximumPacketSize: usize, /// the maximum aggregate amount of buffer space a peer may use waiting for packets to be delivered maximumWaitingData: usize, /// Creates a host for communicating to peers. /// @param address the address at which other peers may connect to this host. If NULL, then no peers may connect to the host. /// @param peerCount the maximum number of peers that should be allocated for the host. /// @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to PROTOCOL_MAXIMUM_CHANNEL_COUNT /// @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. /// @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. /// @returns the host on success and error.ENetError on failure /// @remarks ENet will strategically drop packets on specific sides of a connection between hosts /// to ensure the host's bandwidth is not overwhelmed. The bandwidth parameters also determine /// the window size of a connection which limits the amount of reliable packets that may be in transit /// at any given time. pub fn create(address: ?Address, peerCount: usize, channelLimit: usize, incomingBandwidth: u32, outgoingBandwidth: u32) !*Host { const addressPtr: ?*const Address = if (address) |*a| a else null; const host = raw.enet_host_create(addressPtr, peerCount, channelLimit, incomingBandwidth, outgoingBandwidth); if (host) |h| return h; return error.ENetError; } /// Destroys the host and all resources associated with it. /// @param host pointer to the host to destroy pub fn destroy(self: *Host) void { raw.enet_host_destroy(self); } /// Initiates a connection to a foreign host. /// @param host host seeking the connection /// @param address destination for the connection /// @param channelCount number of channels to allocate /// @param data user data supplied to the receiving host /// @returns a peer representing the foreign host on success, error.ENetError on failure /// @remarks The peer returned will have not completed the connection until service() /// notifies of a .connect event for the peer. pub fn connect(self: *Host, address: Address, channelCount: usize, data: u32) !*Peer { const peer = raw.enet_host_connect(self, &address, channelCount, data); if (peer) |p| return p; return error.ENetError; } /// Checks for any queued events on the host and dispatches one if available. /// @param host host to check for events /// @param event an event structure where event details will be placed if available /// If no event was dispatched, the returned event has type .none pub fn check_events(self: *Host) !Event { var event: Event = undefined; const rc = raw.enet_host_check_events(self, &event); if (rc < 0) return error.ENetError; return event; } /// Waits for events on the host specified and shuttles packets between /// the host and its peers. /// @param host host to service /// @param event an event structure where event details will be placed if one occurs /// if event == null then no events will be delivered /// @param timeout number of milliseconds that ENet should wait for events /// @retval true if an event occurred within the specified time limit /// @retval false if no event occurred /// @retval error.ENetError on failure /// @remarks service() should be called fairly regularly for adequate performance pub fn service(self: *Host, event: ?*Event, timeout: u32) !bool { const rc = raw.enet_host_service(self, event, timeout); if (rc < 0) return error.ENetError; return rc > 0; } /// Sends any queued packets on the host specified to its designated peers. /// @param host host to flush /// @remarks this function need only be used in circumstances where one wishes to send queued packets earlier than in a call to enet_host_service(). pub fn flush(self: *Host) void { raw.enet_host_flush(self); } /// Queues a packet to be sent to all peers associated with the host. /// @param host host on which to broadcast the packet /// @param channelID channel on which to broadcast /// @param packet packet to broadcast pub fn broadcast(self: *Host, channelID: u8, packet: *Packet) void { raw.enet_host_broadcast(self, channelID, packet); } /// Sets the packet compressor the host should use to compress and decompress packets. /// @param host host to enable or disable compression for /// @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled pub fn compress(self: *Host, compressor: ?*const Compressor) void { raw.enet_host_compress(self, compressor); } /// Sets the packet compressor the host should use to the default range coder. /// @param host host to enable the range coder for pub fn compress_with_range_coder(self: *Host) !void { const rc = raw.enet_host_compress_with_range_coder(self); if (rc < 0) return error.ENetError; } /// Limits the maximum allowed channels of future incoming connections. /// @param host host to limit /// @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to PROTOCOL_MAXIMUM_CHANNEL_COUNT pub fn channel_limit(self: *Host, limit: usize) void { raw.enet_host_channel_limit(self, limit); } /// Adjusts the bandwidth limits of a host. /// @param host host to adjust /// @param incomingBandwidth new incoming bandwidth /// @param outgoingBandwidth new outgoing bandwidth /// @remarks the incoming and outgoing bandwidth parameters are identical in function to those /// specified in Host.create(). pub fn bandwidth_limit(self: *Host, incomingBandwidth: u32, outgoingBandwidth: u32) void { raw.enet_host_bandwidth_limit(self, incomingBandwidth, outgoingBandwidth); } }; /// An ENet event type, as specified in @ref Event pub const EventType = enum(c_int) { /// no event occurred within the specified time limit none = 0, /// a connection request initiated by host_connect has completed. /// The peer field contains the peer which successfully connected. connect = 1, /// a peer has disconnected. This event is generated on a successful /// completion of a disconnect initiated by peer_disconnect, if /// a peer has timed out, or if a connection request intialized by /// host_connect has timed out. The peer field contains the peer /// which disconnected. The data field contains user supplied data /// describing the disconnection, or 0, if none is available. disconnect = 2, /// a packet has been received from a peer. The peer field specifies the /// peer which sent the packet. The channelID field specifies the channel /// number upon which the packet was received. The packet field contains /// the packet that was received; this packet must be destroyed with /// packet_destroy after use. receive = 3, }; /// An ENet event as returned by host_service(). /// /// @sa host_service pub const Event = extern struct { /// type of the event type: EventType, /// peer that generated a connect, disconnect or receive event peer: ?*Peer, /// channel on the peer that generated the event, if appropriate channelID: u8, /// data associated with the event, if appropriate data: u32, /// packet associated with the event, if appropriate packet: ?*Packet, }; // @defgroup global ENet global functions // @{ /// fn initialize() c_int /// Initializes ENet globally. Must be called prior to using any functions in /// ENet. pub fn initialize() !void { const rc = raw.enet_initialize(); if (rc < 0) return error.ENetError; } /// fn initialize_with_callbacks(inits: *const Callbacks) c_int /// Initializes ENet globally and supplies user-overridden callbacks. /// Must be called prior to using any functions in ENet. Do not use enet_initialize() if you use this variant. /// Make sure the ENetCallbacks structure is zeroed out so that any additional /// callbacks added in future versions will be properly ignored. /// @param inits user-overridden callbacks where any NULL callbacks will use ENet's defaults /// @returns 0 on success, < 0 on failure pub fn initialize_with_callbacks(inits: *const Callbacks) !void { const rc = raw.enet_initialize_with_callbacks(VERSION, inits); if (rc < 0) return error.ENetError; } /// fn deinitialize() void /// Shuts down ENet globally. Should be called when a program that has /// initialized ENet exits. pub const deinitialize = raw.enet_deinitialize; /// fn linked_version() Version /// Gives the linked version of the ENet library. /// @returns the version number pub const linked_version = raw.enet_linked_version; // @} // @defgroup private ENet private implementation functions /// fn time_get() u32 /// Returns the wall-time in milliseconds. Its initial value is unspecified /// unless otherwise set. pub const time_get = raw.enet_time_get; /// fn time_set(u32) void /// Sets the current wall-time in milliseconds. pub const time_set = raw.enet_time_set; /// fn crc32([]Buffer) u32 /// Computes the crc32 hash of a series of buffers pub fn crc32(buffers: []pl.Buffer) u32 { return raw.enet_crc32(buffers.ptr, buffers.len); } pub fn select(max_socket: pl.SocketHandle, in_out_read: ?*pl.SocketSet, in_out_write: ?*pl.SocketSet, timeout: u32) !void { const rc = raw.enet_socketset_select(max_socket, in_out_read, in_out_write, timeout); if (rc < 0) return error.ENetError; } pub const raw = struct { pub extern fn enet_initialize() callconv(.C) c_int; pub extern fn enet_initialize_with_callbacks(version: Version, inits: *const Callbacks) callconv(.C) c_int; pub extern fn enet_deinitialize() callconv(.C) void; pub extern fn enet_linked_version() callconv(.C) Version; pub extern fn enet_time_get() callconv(.C) u32; pub extern fn enet_time_set(time: u32) callconv(.C) void; pub extern fn enet_socket_create(SocketType) callconv(.C) pl.SocketHandle; pub extern fn enet_socket_bind(pl.SocketHandle, *const Address) callconv(.C) c_int; pub extern fn enet_socket_get_address(pl.SocketHandle, *Address) callconv(.C) c_int; pub extern fn enet_socket_listen(pl.SocketHandle, c_int) callconv(.C) c_int; pub extern fn enet_socket_accept(pl.SocketHandle, ?*Address) callconv(.C) pl.SocketHandle; pub extern fn enet_socket_connect(pl.SocketHandle, *const Address) callconv(.C) c_int; pub extern fn enet_socket_send(pl.SocketHandle, ?*const Address, [*]const pl.Buffer, usize) callconv(.C) c_int; pub extern fn enet_socket_receive(pl.SocketHandle, ?*Address, [*]pl.Buffer, usize) callconv(.C) c_int; pub extern fn enet_socket_wait(pl.SocketHandle, *u32, u32) callconv(.C) c_int; pub extern fn enet_socket_set_option(pl.SocketHandle, SocketOption, c_int) callconv(.C) c_int; pub extern fn enet_socket_get_option(pl.SocketHandle, SocketOption, *c_int) callconv(.C) c_int; pub extern fn enet_socket_shutdown(pl.SocketHandle, SocketShutdown) callconv(.C) c_int; pub extern fn enet_socket_destroy(pl.SocketHandle) callconv(.C) void; pub extern fn enet_socketset_select(pl.SocketHandle, ?*pl.SocketSet, ?*pl.SocketSet, u32) callconv(.C) c_int; pub extern fn enet_address_set_host_ip(address: *Address, hostName: [*:0]const u8) callconv(.C) c_int; pub extern fn enet_address_set_host(address: *Address, hostName: [*:0]const u8) callconv(.C) c_int; pub extern fn enet_address_get_host_ip(address: *const Address, hostName: [*]u8, nameLength: usize) callconv(.C) c_int; pub extern fn enet_address_get_host(address: *const Address, hostName: [*]u8, nameLength: usize) callconv(.C) c_int; pub extern fn enet_packet_create(?[*]const u8, usize, u32) callconv(.C) ?*Packet; pub extern fn enet_packet_destroy(*Packet) callconv(.C) void; pub extern fn enet_packet_resize(*Packet, usize) callconv(.C) c_int; pub extern fn enet_crc32([*]const pl.Buffer, usize) callconv(.C) u32; pub extern fn enet_host_create(?*const Address, usize, usize, u32, u32) callconv(.C) ?*Host; pub extern fn enet_host_destroy(*Host) callconv(.C) void; pub extern fn enet_host_connect(*Host, *const Address, usize, u32) callconv(.C) ?*Peer; pub extern fn enet_host_check_events(*Host, *Event) callconv(.C) c_int; pub extern fn enet_host_service(*Host, ?*Event, u32) callconv(.C) c_int; pub extern fn enet_host_flush(*Host) callconv(.C) void; pub extern fn enet_host_broadcast(*Host, u8, *Packet) callconv(.C) void; pub extern fn enet_host_compress(*Host, ?*const Compressor) callconv(.C) void; pub extern fn enet_host_compress_with_range_coder(*Host) callconv(.C) c_int; pub extern fn enet_host_channel_limit(*Host, usize) callconv(.C) void; pub extern fn enet_host_bandwidth_limit(*Host, u32, u32) callconv(.C) void; pub extern fn enet_peer_send(*Peer, u8, *Packet) callconv(.C) c_int; pub extern fn enet_peer_receive(*Peer, channelID: *u8) callconv(.C) ?*Packet; pub extern fn enet_peer_ping(*Peer) callconv(.C) void; pub extern fn enet_peer_ping_interval(*Peer, u32) callconv(.C) void; pub extern fn enet_peer_timeout(*Peer, u32, u32, u32) callconv(.C) void; pub extern fn enet_peer_reset(*Peer) callconv(.C) void; pub extern fn enet_peer_disconnect(*Peer, u32) callconv(.C) void; pub extern fn enet_peer_disconnect_now(*Peer, u32) callconv(.C) void; pub extern fn enet_peer_disconnect_later(*Peer, u32) callconv(.C) void; pub extern fn enet_peer_throttle_configure(*Peer, u32, u32, u32) callconv(.C) void; pub extern fn enet_range_coder_create() callconv(.C) *anyopaque; pub extern fn enet_range_coder_destroy(*anyopaque) callconv(.C) void; pub extern fn enet_range_coder_compress(*anyopaque, *const pl.Buffer, usize, usize, [*]u8, usize) callconv(.C) usize; pub extern fn enet_range_coder_decompress(*anyopaque, [*]const u8, usize, [*]u8, usize) callconv(.C) usize; /// These functions are declared in enet.h but are not exported in DLL builds. /// They probably shouldn't be used. pub const secret = struct { pub extern fn enet_host_bandwidth_throttle(*Host) callconv(.C) void; pub extern fn enet_host_random_seed() callconv(.C) u32; pub extern fn enet_peer_throttle(*Peer, u32) callconv(.C) c_int; pub extern fn enet_peer_reset_queues(*Peer) callconv(.C) void; pub extern fn enet_peer_setup_outgoing_command(*Peer, *OutgoingCommand) callconv(.C) void; pub extern fn enet_peer_queue_outgoing_command(*Peer, *const Protocol, *Packet, u32, u16) callconv(.C) *OutgoingCommand; pub extern fn enet_peer_queue_incoming_command(*Peer, *const Protocol, [*]const u8, usize, u32, u32) callconv(.C) *IncomingCommand; pub extern fn enet_peer_queue_acknowledgement(*Peer, *const Protocol, u16) callconv(.C) *Acknowledgement; pub extern fn enet_peer_dispatch_incoming_unreliable_commands(*Peer, *Channel, *IncomingCommand) callconv(.C) void; pub extern fn enet_peer_dispatch_incoming_reliable_commands(*Peer, *Channel, *IncomingCommand) callconv(.C) void; pub extern fn enet_peer_on_connect(*Peer) callconv(.C) void; pub extern fn enet_peer_on_disconnect(*Peer) callconv(.C) void; pub extern fn enet_protocol_command_size(u8) callconv(.C) usize; pub extern fn enet_malloc(usize) callconv(.C) ?*anyopaque; pub extern fn enet_free(?*anyopaque) callconv(.C) void; }; }; comptime { _ = PacketFreeCallback; _ = InterceptCallback; std.testing.refAllDecls(@This()); std.testing.refAllDecls(@This().raw); std.testing.refAllDecls(@This().Host); std.testing.refAllDecls(@This().Peer); std.testing.refAllDecls(@This().Protocol); std.testing.refAllDecls(@This().Socket); std.testing.refAllDecls(@This().ListNode); std.testing.refAllDecls(@This().WindowsPlatform); std.testing.refAllDecls(@This().UnixPlatform); } test "enet.init" { try initialize(); defer deinitialize(); }
enet.zig
pub const DMUS_MAX_DESCRIPTION = @as(u32, 128); pub const DMUS_MAX_DRIVER = @as(u32, 128); pub const DMUS_EFFECT_NONE = @as(u32, 0); pub const DMUS_EFFECT_REVERB = @as(u32, 1); pub const DMUS_EFFECT_CHORUS = @as(u32, 2); pub const DMUS_EFFECT_DELAY = @as(u32, 4); pub const DMUS_PC_INPUTCLASS = @as(u32, 0); pub const DMUS_PC_OUTPUTCLASS = @as(u32, 1); pub const DMUS_PC_DLS = @as(u32, 1); pub const DMUS_PC_EXTERNAL = @as(u32, 2); pub const DMUS_PC_SOFTWARESYNTH = @as(u32, 4); pub const DMUS_PC_MEMORYSIZEFIXED = @as(u32, 8); pub const DMUS_PC_GMINHARDWARE = @as(u32, 16); pub const DMUS_PC_GSINHARDWARE = @as(u32, 32); pub const DMUS_PC_XGINHARDWARE = @as(u32, 64); pub const DMUS_PC_DIRECTSOUND = @as(u32, 128); pub const DMUS_PC_SHAREABLE = @as(u32, 256); pub const DMUS_PC_DLS2 = @as(u32, 512); pub const DMUS_PC_AUDIOPATH = @as(u32, 1024); pub const DMUS_PC_WAVE = @as(u32, 2048); pub const DMUS_PC_SYSTEMMEMORY = @as(u32, 2147483647); pub const DMUS_PORT_WINMM_DRIVER = @as(u32, 0); pub const DMUS_PORT_USER_MODE_SYNTH = @as(u32, 1); pub const DMUS_PORT_KERNEL_MODE = @as(u32, 2); pub const DMUS_PORTPARAMS_VOICES = @as(u32, 1); pub const DMUS_PORTPARAMS_CHANNELGROUPS = @as(u32, 2); pub const DMUS_PORTPARAMS_AUDIOCHANNELS = @as(u32, 4); pub const DMUS_PORTPARAMS_SAMPLERATE = @as(u32, 8); pub const DMUS_PORTPARAMS_EFFECTS = @as(u32, 32); pub const DMUS_PORTPARAMS_SHARE = @as(u32, 64); pub const DMUS_PORTPARAMS_FEATURES = @as(u32, 128); pub const DMUS_PORT_FEATURE_AUDIOPATH = @as(u32, 1); pub const DMUS_PORT_FEATURE_STREAMING = @as(u32, 2); pub const DMUS_SYNTHSTATS_VOICES = @as(u32, 1); pub const DMUS_SYNTHSTATS_TOTAL_CPU = @as(u32, 2); pub const DMUS_SYNTHSTATS_CPU_PER_VOICE = @as(u32, 4); pub const DMUS_SYNTHSTATS_LOST_NOTES = @as(u32, 8); pub const DMUS_SYNTHSTATS_PEAK_VOLUME = @as(u32, 16); pub const DMUS_SYNTHSTATS_FREE_MEMORY = @as(u32, 32); pub const DMUS_SYNTHSTATS_SYSTEMMEMORY = @as(u32, 2147483647); pub const DMUS_CLOCKF_GLOBAL = @as(u32, 1); pub const DSBUSID_FIRST_SPKR_LOC = @as(u32, 0); pub const DSBUSID_FRONT_LEFT = @as(u32, 0); pub const DSBUSID_LEFT = @as(u32, 0); pub const DSBUSID_FRONT_RIGHT = @as(u32, 1); pub const DSBUSID_RIGHT = @as(u32, 1); pub const DSBUSID_FRONT_CENTER = @as(u32, 2); pub const DSBUSID_LOW_FREQUENCY = @as(u32, 3); pub const DSBUSID_BACK_LEFT = @as(u32, 4); pub const DSBUSID_BACK_RIGHT = @as(u32, 5); pub const DSBUSID_FRONT_LEFT_OF_CENTER = @as(u32, 6); pub const DSBUSID_FRONT_RIGHT_OF_CENTER = @as(u32, 7); pub const DSBUSID_BACK_CENTER = @as(u32, 8); pub const DSBUSID_SIDE_LEFT = @as(u32, 9); pub const DSBUSID_SIDE_RIGHT = @as(u32, 10); pub const DSBUSID_TOP_CENTER = @as(u32, 11); pub const DSBUSID_TOP_FRONT_LEFT = @as(u32, 12); pub const DSBUSID_TOP_FRONT_CENTER = @as(u32, 13); pub const DSBUSID_TOP_FRONT_RIGHT = @as(u32, 14); pub const DSBUSID_TOP_BACK_LEFT = @as(u32, 15); pub const DSBUSID_TOP_BACK_CENTER = @as(u32, 16); pub const DSBUSID_TOP_BACK_RIGHT = @as(u32, 17); pub const DSBUSID_LAST_SPKR_LOC = @as(u32, 17); pub const DSBUSID_REVERB_SEND = @as(u32, 64); pub const DSBUSID_CHORUS_SEND = @as(u32, 65); pub const DSBUSID_DYNAMIC_0 = @as(u32, 512); pub const DSBUSID_NULL = @as(u32, 4294967295); pub const DAUD_CRITICAL_VOICE_PRIORITY = @as(u32, 4026531840); pub const DAUD_HIGH_VOICE_PRIORITY = @as(u32, 3221225472); pub const DAUD_STANDARD_VOICE_PRIORITY = @as(u32, 2147483648); pub const DAUD_LOW_VOICE_PRIORITY = @as(u32, 1073741824); pub const DAUD_PERSIST_VOICE_PRIORITY = @as(u32, 268435456); pub const DAUD_CHAN1_VOICE_PRIORITY_OFFSET = @as(u32, 14); pub const DAUD_CHAN2_VOICE_PRIORITY_OFFSET = @as(u32, 13); pub const DAUD_CHAN3_VOICE_PRIORITY_OFFSET = @as(u32, 12); pub const DAUD_CHAN4_VOICE_PRIORITY_OFFSET = @as(u32, 11); pub const DAUD_CHAN5_VOICE_PRIORITY_OFFSET = @as(u32, 10); pub const DAUD_CHAN6_VOICE_PRIORITY_OFFSET = @as(u32, 9); pub const DAUD_CHAN7_VOICE_PRIORITY_OFFSET = @as(u32, 8); pub const DAUD_CHAN8_VOICE_PRIORITY_OFFSET = @as(u32, 7); pub const DAUD_CHAN9_VOICE_PRIORITY_OFFSET = @as(u32, 6); pub const DAUD_CHAN10_VOICE_PRIORITY_OFFSET = @as(u32, 15); pub const DAUD_CHAN11_VOICE_PRIORITY_OFFSET = @as(u32, 5); pub const DAUD_CHAN12_VOICE_PRIORITY_OFFSET = @as(u32, 4); pub const DAUD_CHAN13_VOICE_PRIORITY_OFFSET = @as(u32, 3); pub const DAUD_CHAN14_VOICE_PRIORITY_OFFSET = @as(u32, 2); pub const DAUD_CHAN15_VOICE_PRIORITY_OFFSET = @as(u32, 1); pub const DAUD_CHAN16_VOICE_PRIORITY_OFFSET = @as(u32, 0); pub const CLSID_DirectMusic = Guid.initString("636b9f10-0c7d-11d1-95b2-0020afdc7421"); pub const CLSID_DirectMusicCollection = Guid.initString("480ff4b0-28b2-11d1-bef7-00c04fbf8fef"); pub const CLSID_DirectMusicSynth = Guid.initString("58c2b4d0-46e7-11d1-89ac-00a0c9054129"); pub const GUID_DMUS_PROP_GM_Hardware = Guid.initString("178f2f24-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_GS_Hardware = Guid.initString("178f2f25-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_XG_Hardware = Guid.initString("178f2f26-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_XG_Capable = Guid.initString("6496aba1-61b0-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_GS_Capable = Guid.initString("6496aba2-61b0-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_DLS1 = Guid.initString("178f2f27-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_DLS2 = Guid.initString("f14599e5-4689-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_INSTRUMENT2 = Guid.initString("865fd372-9f67-11d2-872a-00600893b1bd"); pub const GUID_DMUS_PROP_SynthSink_DSOUND = Guid.initString("0aa97844-c877-11d1-870c-00600893b1bd"); pub const GUID_DMUS_PROP_SynthSink_WAVE = Guid.initString("0aa97845-c877-11d1-870c-00600893b1bd"); pub const GUID_DMUS_PROP_SampleMemorySize = Guid.initString("178f2f28-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_SamplePlaybackRate = Guid.initString("2a91f713-a4bf-11d2-bbdf-00600833dbd8"); pub const GUID_DMUS_PROP_WriteLatency = Guid.initString("268a0fa0-60f2-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_WritePeriod = Guid.initString("268a0fa1-60f2-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_MemorySize = Guid.initString("178f2f28-c364-11d1-a760-0000f875ac12"); pub const GUID_DMUS_PROP_WavesReverb = Guid.initString("04cb5622-32e5-11d2-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_Effects = Guid.initString("cda8d611-684a-11d2-871e-00600893b1bd"); pub const GUID_DMUS_PROP_LegacyCaps = Guid.initString("cfa7cdc2-00a1-11d2-aad5-0000f875ac12"); pub const GUID_DMUS_PROP_Volume = Guid.initString("fedfae25-e46e-11d1-aace-0000f875ac12"); pub const DMUS_VOLUME_MAX = @as(u32, 2000); pub const DMUS_VOLUME_MIN = @as(i32, -20000); pub const DMUS_EVENT_STRUCTURED = @as(u32, 1); pub const DMUS_DOWNLOADINFO_INSTRUMENT = @as(u32, 1); pub const DMUS_DOWNLOADINFO_WAVE = @as(u32, 2); pub const DMUS_DOWNLOADINFO_INSTRUMENT2 = @as(u32, 3); pub const DMUS_DOWNLOADINFO_WAVEARTICULATION = @as(u32, 4); pub const DMUS_DOWNLOADINFO_STREAMINGWAVE = @as(u32, 5); pub const DMUS_DOWNLOADINFO_ONESHOTWAVE = @as(u32, 6); pub const DMUS_DEFAULT_SIZE_OFFSETTABLE = @as(u32, 1); pub const DMUS_INSTRUMENT_GM_INSTRUMENT = @as(u32, 1); pub const DMUS_MIN_DATA_SIZE = @as(u32, 4); pub const CONN_SRC_NONE = @as(u32, 0); pub const CONN_SRC_LFO = @as(u32, 1); pub const CONN_SRC_KEYONVELOCITY = @as(u32, 2); pub const CONN_SRC_KEYNUMBER = @as(u32, 3); pub const CONN_SRC_EG1 = @as(u32, 4); pub const CONN_SRC_EG2 = @as(u32, 5); pub const CONN_SRC_PITCHWHEEL = @as(u32, 6); pub const CONN_SRC_CC1 = @as(u32, 129); pub const CONN_SRC_CC7 = @as(u32, 135); pub const CONN_SRC_CC10 = @as(u32, 138); pub const CONN_SRC_CC11 = @as(u32, 139); pub const CONN_DST_NONE = @as(u32, 0); pub const CONN_DST_ATTENUATION = @as(u32, 1); pub const CONN_DST_PITCH = @as(u32, 3); pub const CONN_DST_PAN = @as(u32, 4); pub const CONN_DST_LFO_FREQUENCY = @as(u32, 260); pub const CONN_DST_LFO_STARTDELAY = @as(u32, 261); pub const CONN_DST_EG1_ATTACKTIME = @as(u32, 518); pub const CONN_DST_EG1_DECAYTIME = @as(u32, 519); pub const CONN_DST_EG1_RELEASETIME = @as(u32, 521); pub const CONN_DST_EG1_SUSTAINLEVEL = @as(u32, 522); pub const CONN_DST_EG2_ATTACKTIME = @as(u32, 778); pub const CONN_DST_EG2_DECAYTIME = @as(u32, 779); pub const CONN_DST_EG2_RELEASETIME = @as(u32, 781); pub const CONN_DST_EG2_SUSTAINLEVEL = @as(u32, 782); pub const CONN_TRN_NONE = @as(u32, 0); pub const CONN_TRN_CONCAVE = @as(u32, 1); pub const F_INSTRUMENT_DRUMS = @as(u32, 2147483648); pub const F_RGN_OPTION_SELFNONEXCLUSIVE = @as(u32, 1); pub const WAVELINK_CHANNEL_LEFT = @as(i32, 1); pub const WAVELINK_CHANNEL_RIGHT = @as(i32, 2); pub const F_WAVELINK_PHASE_MASTER = @as(u32, 1); pub const POOL_CUE_NULL = @as(i32, -1); pub const F_WSMP_NO_TRUNCATION = @as(i32, 1); pub const F_WSMP_NO_COMPRESSION = @as(i32, 2); pub const WLOOP_TYPE_FORWARD = @as(u32, 0); pub const CONN_SRC_POLYPRESSURE = @as(u32, 7); pub const CONN_SRC_CHANNELPRESSURE = @as(u32, 8); pub const CONN_SRC_VIBRATO = @as(u32, 9); pub const CONN_SRC_MONOPRESSURE = @as(u32, 10); pub const CONN_SRC_CC91 = @as(u32, 219); pub const CONN_SRC_CC93 = @as(u32, 221); pub const CONN_DST_GAIN = @as(u32, 1); pub const CONN_DST_KEYNUMBER = @as(u32, 5); pub const CONN_DST_LEFT = @as(u32, 16); pub const CONN_DST_RIGHT = @as(u32, 17); pub const CONN_DST_CENTER = @as(u32, 18); pub const CONN_DST_LEFTREAR = @as(u32, 19); pub const CONN_DST_RIGHTREAR = @as(u32, 20); pub const CONN_DST_LFE_CHANNEL = @as(u32, 21); pub const CONN_DST_CHORUS = @as(u32, 128); pub const CONN_DST_REVERB = @as(u32, 129); pub const CONN_DST_VIB_FREQUENCY = @as(u32, 276); pub const CONN_DST_VIB_STARTDELAY = @as(u32, 277); pub const CONN_DST_EG1_DELAYTIME = @as(u32, 523); pub const CONN_DST_EG1_HOLDTIME = @as(u32, 524); pub const CONN_DST_EG1_SHUTDOWNTIME = @as(u32, 525); pub const CONN_DST_EG2_DELAYTIME = @as(u32, 783); pub const CONN_DST_EG2_HOLDTIME = @as(u32, 784); pub const CONN_DST_FILTER_CUTOFF = @as(u32, 1280); pub const CONN_DST_FILTER_Q = @as(u32, 1281); pub const CONN_TRN_CONVEX = @as(u32, 2); pub const CONN_TRN_SWITCH = @as(u32, 3); pub const DLS_CDL_AND = @as(u32, 1); pub const DLS_CDL_OR = @as(u32, 2); pub const DLS_CDL_XOR = @as(u32, 3); pub const DLS_CDL_ADD = @as(u32, 4); pub const DLS_CDL_SUBTRACT = @as(u32, 5); pub const DLS_CDL_MULTIPLY = @as(u32, 6); pub const DLS_CDL_DIVIDE = @as(u32, 7); pub const DLS_CDL_LOGICAL_AND = @as(u32, 8); pub const DLS_CDL_LOGICAL_OR = @as(u32, 9); pub const DLS_CDL_LT = @as(u32, 10); pub const DLS_CDL_LE = @as(u32, 11); pub const DLS_CDL_GT = @as(u32, 12); pub const DLS_CDL_GE = @as(u32, 13); pub const DLS_CDL_EQ = @as(u32, 14); pub const DLS_CDL_NOT = @as(u32, 15); pub const DLS_CDL_CONST = @as(u32, 16); pub const DLS_CDL_QUERY = @as(u32, 17); pub const DLS_CDL_QUERYSUPPORTED = @as(u32, 18); pub const WLOOP_TYPE_RELEASE = @as(u32, 2); pub const F_WAVELINK_MULTICHANNEL = @as(u32, 2); pub const DLSID_GMInHardware = Guid.initString("178f2f24-c364-11d1-a760-0000f875ac12"); pub const DLSID_GSInHardware = Guid.initString("178f2f25-c364-11d1-a760-0000f875ac12"); pub const DLSID_XGInHardware = Guid.initString("178f2f26-c364-11d1-a760-0000f875ac12"); pub const DLSID_SupportsDLS1 = Guid.initString("178f2f27-c364-11d1-a760-0000f875ac12"); pub const DLSID_SupportsDLS2 = Guid.initString("f14599e5-4689-11d2-afa6-00aa0024d8b6"); pub const DLSID_SampleMemorySize = Guid.initString("178f2f28-c364-11d1-a760-0000f875ac12"); pub const DLSID_ManufacturersID = Guid.initString("b03e1181-8095-11d2-a1ef-00600833dbd8"); pub const DLSID_ProductID = Guid.initString("b03e1182-8095-11d2-a1ef-00600833dbd8"); pub const DLSID_SamplePlaybackRate = Guid.initString("2a91f713-a4bf-11d2-bbdf-00600833dbd8"); pub const REFRESH_F_LASTBUFFER = @as(u32, 1); pub const CLSID_DirectMusicSynthSink = Guid.initString("aec17ce3-a514-11d1-afa6-00aa0024d8b6"); pub const GUID_DMUS_PROP_SetSynthSink = Guid.initString("0a3a5ba5-37b6-11d2-b9f9-0000f875ac12"); pub const GUID_DMUS_PROP_SinkUsesDSound = Guid.initString("be208857-8952-11d2-ba1c-0000f875ac12"); pub const CLSID_DirectSoundPrivate = Guid.initString("11ab3ec0-25ec-11d1-a4d8-00c04fc28aca"); pub const DSPROPSETID_DirectSoundDevice = Guid.initString("84624f82-25ec-11d1-a4d8-00c04fc28aca"); pub const DV_DVSD_NTSC_FRAMESIZE = @as(i32, 120000); pub const DV_DVSD_PAL_FRAMESIZE = @as(i32, 144000); pub const DV_SMCHN = @as(u32, 57344); pub const DV_AUDIOMODE = @as(u32, 3840); pub const DV_AUDIOSMP = @as(u32, 939524096); pub const DV_AUDIOQU = @as(u32, 117440512); pub const DV_NTSCPAL = @as(u32, 2097152); pub const DV_STYPE = @as(u32, 2031616); pub const DV_NTSC = @as(u32, 0); pub const DV_PAL = @as(u32, 1); pub const DV_SD = @as(u32, 0); pub const DV_HD = @as(u32, 1); pub const DV_SL = @as(u32, 2); pub const DV_CAP_AUD16Bits = @as(u32, 0); pub const DV_CAP_AUD12Bits = @as(u32, 1); pub const SIZE_DVINFO = @as(u32, 32); //-------------------------------------------------------------------------------- // Section: Types (74) //-------------------------------------------------------------------------------- pub const DLSID = extern struct { ulData1: u32, usData2: u16, usData3: u16, abData4: [8]u8, }; pub const DLSVERSION = extern struct { dwVersionMS: u32, dwVersionLS: u32, }; pub const CONNECTION = extern struct { usSource: u16, usControl: u16, usDestination: u16, usTransform: u16, lScale: i32, }; pub const CONNECTIONLIST = extern struct { cbSize: u32, cConnections: u32, }; pub const RGNRANGE = extern struct { usLow: u16, usHigh: u16, }; pub const MIDILOCALE = extern struct { ulBank: u32, ulInstrument: u32, }; pub const RGNHEADER = extern struct { RangeKey: RGNRANGE, RangeVelocity: RGNRANGE, fusOptions: u16, usKeyGroup: u16, }; pub const INSTHEADER = extern struct { cRegions: u32, Locale: MIDILOCALE, }; pub const DLSHEADER = extern struct { cInstruments: u32, }; pub const WAVELINK = extern struct { fusOptions: u16, usPhaseGroup: u16, ulChannel: u32, ulTableIndex: u32, }; pub const POOLCUE = extern struct { ulOffset: u32, }; pub const POOLTABLE = extern struct { cbSize: u32, cCues: u32, }; pub const _rwsmp = extern struct { cbSize: u32, usUnityNote: u16, sFineTune: i16, lAttenuation: i32, fulOptions: u32, cSampleLoops: u32, }; pub const _rloop = extern struct { cbSize: u32, ulType: u32, ulStart: u32, ulLength: u32, }; pub const DMUS_DOWNLOADINFO = extern struct { dwDLType: u32, dwDLId: u32, dwNumOffsetTableEntries: u32, cbSize: u32, }; pub const DMUS_OFFSETTABLE = extern struct { ulOffsetTable: [1]u32, }; pub const DMUS_INSTRUMENT = extern struct { ulPatch: u32, ulFirstRegionIdx: u32, ulGlobalArtIdx: u32, ulFirstExtCkIdx: u32, ulCopyrightIdx: u32, ulFlags: u32, }; pub const DMUS_REGION = extern struct { RangeKey: RGNRANGE, RangeVelocity: RGNRANGE, fusOptions: u16, usKeyGroup: u16, ulRegionArtIdx: u32, ulNextRegionIdx: u32, ulFirstExtCkIdx: u32, WaveLink: WAVELINK, WSMP: _rwsmp, WLOOP: [1]_rloop, }; pub const DMUS_LFOPARAMS = extern struct { pcFrequency: i32, tcDelay: i32, gcVolumeScale: i32, pcPitchScale: i32, gcMWToVolume: i32, pcMWToPitch: i32, }; pub const DMUS_VEGPARAMS = extern struct { tcAttack: i32, tcDecay: i32, ptSustain: i32, tcRelease: i32, tcVel2Attack: i32, tcKey2Decay: i32, }; pub const DMUS_PEGPARAMS = extern struct { tcAttack: i32, tcDecay: i32, ptSustain: i32, tcRelease: i32, tcVel2Attack: i32, tcKey2Decay: i32, pcRange: i32, }; pub const DMUS_MSCPARAMS = extern struct { ptDefaultPan: i32, }; pub const DMUS_ARTICPARAMS = extern struct { LFO: DMUS_LFOPARAMS, VolEG: DMUS_VEGPARAMS, PitchEG: DMUS_PEGPARAMS, Misc: DMUS_MSCPARAMS, }; pub const DMUS_ARTICULATION = extern struct { ulArt1Idx: u32, ulFirstExtCkIdx: u32, }; pub const DMUS_ARTICULATION2 = extern struct { ulArtIdx: u32, ulFirstExtCkIdx: u32, ulNextArtIdx: u32, }; pub const DMUS_EXTENSIONCHUNK = extern struct { cbSize: u32, ulNextExtCkIdx: u32, ExtCkID: u32, byExtCk: [4]u8, }; pub const DMUS_COPYRIGHT = extern struct { cbSize: u32, byCopyright: [4]u8, }; pub const DMUS_WAVEDATA = extern struct { cbSize: u32, byData: [4]u8, }; pub const DMUS_WAVE = extern struct { ulFirstExtCkIdx: u32, ulCopyrightIdx: u32, ulWaveDataIdx: u32, WaveformatEx: WAVEFORMATEX, }; pub const DMUS_NOTERANGE = extern struct { dwLowNote: u32, dwHighNote: u32, }; pub const DMUS_WAVEARTDL = extern struct { ulDownloadIdIdx: u32, ulBus: u32, ulBuffers: u32, ulMasterDLId: u32, usOptions: u16, }; pub const DMUS_WAVEDL = extern struct { cbWaveData: u32, }; pub const DMUS_EVENTHEADER = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbEvent: u32, dwChannelGroup: u32, rtDelta: i64, dwFlags: u32, }; pub const DMUS_BUFFERDESC = extern struct { dwSize: u32, dwFlags: u32, guidBufferFormat: Guid, cbBuffer: u32, }; pub const DMUS_PORTCAPS = extern struct { dwSize: u32, dwFlags: u32, guidPort: Guid, dwClass: u32, dwType: u32, dwMemorySize: u32, dwMaxChannelGroups: u32, dwMaxVoices: u32, dwMaxAudioChannels: u32, dwEffectFlags: u32, wszDescription: [128]u16, }; pub const _DMUS_PORTPARAMS = extern struct { dwSize: u32, dwValidParams: u32, dwVoices: u32, dwChannelGroups: u32, dwAudioChannels: u32, dwSampleRate: u32, dwEffectFlags: u32, fShare: BOOL, }; pub const DMUS_PORTPARAMS8 = extern struct { dwSize: u32, dwValidParams: u32, dwVoices: u32, dwChannelGroups: u32, dwAudioChannels: u32, dwSampleRate: u32, dwEffectFlags: u32, fShare: BOOL, dwFeatures: u32, }; pub const DMUS_SYNTHSTATS = extern struct { dwSize: u32, dwValidStats: u32, dwVoices: u32, dwTotalCPU: u32, dwCPUPerVoice: u32, dwLostNotes: u32, dwFreeMemory: u32, lPeakVolume: i32, }; pub const DMUS_SYNTHSTATS8 = extern struct { dwSize: u32, dwValidStats: u32, dwVoices: u32, dwTotalCPU: u32, dwCPUPerVoice: u32, dwLostNotes: u32, dwFreeMemory: u32, lPeakVolume: i32, dwSynthMemUse: u32, }; pub const DMUS_WAVES_REVERB_PARAMS = extern struct { fInGain: f32, fReverbMix: f32, fReverbTime: f32, fHighFreqRTRatio: f32, }; pub const DMUS_CLOCKTYPE = enum(i32) { SYSTEM = 0, WAVE = 1, }; pub const DMUS_CLOCK_SYSTEM = DMUS_CLOCKTYPE.SYSTEM; pub const DMUS_CLOCK_WAVE = DMUS_CLOCKTYPE.WAVE; pub const DMUS_CLOCKINFO7 = extern struct { dwSize: u32, ctType: DMUS_CLOCKTYPE, guidClock: Guid, wszDescription: [128]u16, }; pub const DMUS_CLOCKINFO8 = extern struct { dwSize: u32, ctType: DMUS_CLOCKTYPE, guidClock: Guid, wszDescription: [128]u16, dwFlags: u32, }; const IID_IDirectMusic_Value = Guid.initString("6536115a-7b2d-11d2-ba18-0000f875ac12"); pub const IID_IDirectMusic = &IID_IDirectMusic_Value; pub const IDirectMusic = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumPort: fn( self: *const IDirectMusic, dwIndex: u32, pPortCaps: ?*DMUS_PORTCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMusicBuffer: fn( self: *const IDirectMusic, pBufferDesc: ?*DMUS_BUFFERDESC, ppBuffer: ?*?*IDirectMusicBuffer, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePort: fn( self: *const IDirectMusic, rclsidPort: ?*const Guid, pPortParams: ?*DMUS_PORTPARAMS8, ppPort: ?*?*IDirectMusicPort, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumMasterClock: fn( self: *const IDirectMusic, dwIndex: u32, lpClockInfo: ?*DMUS_CLOCKINFO8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMasterClock: fn( self: *const IDirectMusic, pguidClock: ?*Guid, ppReferenceClock: ?*?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMasterClock: fn( self: *const IDirectMusic, rguidClock: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IDirectMusic, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultPort: fn( self: *const IDirectMusic, pguidPort: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDirectSound: fn( self: *const IDirectMusic, pDirectSound: ?*IDirectSound, hWnd: ?HWND, ) 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 IDirectMusic_EnumPort(self: *const T, dwIndex: u32, pPortCaps: ?*DMUS_PORTCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).EnumPort(@ptrCast(*const IDirectMusic, self), dwIndex, pPortCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_CreateMusicBuffer(self: *const T, pBufferDesc: ?*DMUS_BUFFERDESC, ppBuffer: ?*?*IDirectMusicBuffer, pUnkOuter: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).CreateMusicBuffer(@ptrCast(*const IDirectMusic, self), pBufferDesc, ppBuffer, pUnkOuter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_CreatePort(self: *const T, rclsidPort: ?*const Guid, pPortParams: ?*DMUS_PORTPARAMS8, ppPort: ?*?*IDirectMusicPort, pUnkOuter: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).CreatePort(@ptrCast(*const IDirectMusic, self), rclsidPort, pPortParams, ppPort, pUnkOuter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_EnumMasterClock(self: *const T, dwIndex: u32, lpClockInfo: ?*DMUS_CLOCKINFO8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).EnumMasterClock(@ptrCast(*const IDirectMusic, self), dwIndex, lpClockInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_GetMasterClock(self: *const T, pguidClock: ?*Guid, ppReferenceClock: ?*?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).GetMasterClock(@ptrCast(*const IDirectMusic, self), pguidClock, ppReferenceClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_SetMasterClock(self: *const T, rguidClock: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).SetMasterClock(@ptrCast(*const IDirectMusic, self), rguidClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_Activate(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).Activate(@ptrCast(*const IDirectMusic, self), fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_GetDefaultPort(self: *const T, pguidPort: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).GetDefaultPort(@ptrCast(*const IDirectMusic, self), pguidPort); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic_SetDirectSound(self: *const T, pDirectSound: ?*IDirectSound, hWnd: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic.VTable, self.vtable).SetDirectSound(@ptrCast(*const IDirectMusic, self), pDirectSound, hWnd); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusic8_Value = Guid.initString("2d3629f7-813d-4939-8508-f05c6b75fd97"); pub const IID_IDirectMusic8 = &IID_IDirectMusic8_Value; pub const IDirectMusic8 = extern struct { pub const VTable = extern struct { base: IDirectMusic.VTable, SetExternalMasterClock: fn( self: *const IDirectMusic8, pClock: ?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDirectMusic.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusic8_SetExternalMasterClock(self: *const T, pClock: ?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusic8.VTable, self.vtable).SetExternalMasterClock(@ptrCast(*const IDirectMusic8, self), pClock); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicBuffer_Value = Guid.initString("d2ac2878-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicBuffer = &IID_IDirectMusicBuffer_Value; pub const IDirectMusicBuffer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Flush: fn( self: *const IDirectMusicBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TotalTime: fn( self: *const IDirectMusicBuffer, prtTime: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PackStructured: fn( self: *const IDirectMusicBuffer, rt: i64, dwChannelGroup: u32, dwChannelMessage: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PackUnstructured: fn( self: *const IDirectMusicBuffer, rt: i64, dwChannelGroup: u32, cb: u32, lpb: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResetReadPtr: fn( self: *const IDirectMusicBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextEvent: fn( self: *const IDirectMusicBuffer, prt: ?*i64, pdwChannelGroup: ?*u32, pdwLength: ?*u32, ppData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRawBufferPtr: fn( self: *const IDirectMusicBuffer, ppData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStartTime: fn( self: *const IDirectMusicBuffer, prt: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUsedBytes: fn( self: *const IDirectMusicBuffer, pcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxBytes: fn( self: *const IDirectMusicBuffer, pcb: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBufferFormat: fn( self: *const IDirectMusicBuffer, pGuidFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStartTime: fn( self: *const IDirectMusicBuffer, rt: i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUsedBytes: fn( self: *const IDirectMusicBuffer, cb: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_Flush(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).Flush(@ptrCast(*const IDirectMusicBuffer, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_TotalTime(self: *const T, prtTime: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).TotalTime(@ptrCast(*const IDirectMusicBuffer, self), prtTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_PackStructured(self: *const T, rt: i64, dwChannelGroup: u32, dwChannelMessage: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).PackStructured(@ptrCast(*const IDirectMusicBuffer, self), rt, dwChannelGroup, dwChannelMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_PackUnstructured(self: *const T, rt: i64, dwChannelGroup: u32, cb: u32, lpb: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).PackUnstructured(@ptrCast(*const IDirectMusicBuffer, self), rt, dwChannelGroup, cb, lpb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_ResetReadPtr(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).ResetReadPtr(@ptrCast(*const IDirectMusicBuffer, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetNextEvent(self: *const T, prt: ?*i64, pdwChannelGroup: ?*u32, pdwLength: ?*u32, ppData: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetNextEvent(@ptrCast(*const IDirectMusicBuffer, self), prt, pdwChannelGroup, pdwLength, ppData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetRawBufferPtr(self: *const T, ppData: ?*?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetRawBufferPtr(@ptrCast(*const IDirectMusicBuffer, self), ppData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetStartTime(self: *const T, prt: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetStartTime(@ptrCast(*const IDirectMusicBuffer, self), prt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetUsedBytes(self: *const T, pcb: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetUsedBytes(@ptrCast(*const IDirectMusicBuffer, self), pcb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetMaxBytes(self: *const T, pcb: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetMaxBytes(@ptrCast(*const IDirectMusicBuffer, self), pcb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_GetBufferFormat(self: *const T, pGuidFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).GetBufferFormat(@ptrCast(*const IDirectMusicBuffer, self), pGuidFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_SetStartTime(self: *const T, rt: i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).SetStartTime(@ptrCast(*const IDirectMusicBuffer, self), rt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicBuffer_SetUsedBytes(self: *const T, cb: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicBuffer.VTable, self.vtable).SetUsedBytes(@ptrCast(*const IDirectMusicBuffer, self), cb); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicInstrument_Value = Guid.initString("d2ac287d-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicInstrument = &IID_IDirectMusicInstrument_Value; pub const IDirectMusicInstrument = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPatch: fn( self: *const IDirectMusicInstrument, pdwPatch: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPatch: fn( self: *const IDirectMusicInstrument, dwPatch: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicInstrument_GetPatch(self: *const T, pdwPatch: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicInstrument.VTable, self.vtable).GetPatch(@ptrCast(*const IDirectMusicInstrument, self), pdwPatch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicInstrument_SetPatch(self: *const T, dwPatch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicInstrument.VTable, self.vtable).SetPatch(@ptrCast(*const IDirectMusicInstrument, self), dwPatch); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicDownloadedInstrument_Value = Guid.initString("d2ac287e-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicDownloadedInstrument = &IID_IDirectMusicDownloadedInstrument_Value; pub const IDirectMusicDownloadedInstrument = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicCollection_Value = Guid.initString("d2ac287c-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicCollection = &IID_IDirectMusicCollection_Value; pub const IDirectMusicCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInstrument: fn( self: *const IDirectMusicCollection, dwPatch: u32, ppInstrument: ?*?*IDirectMusicInstrument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumInstrument: fn( self: *const IDirectMusicCollection, dwIndex: u32, pdwPatch: ?*u32, pwszName: ?PWSTR, dwNameLen: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicCollection_GetInstrument(self: *const T, dwPatch: u32, ppInstrument: ?*?*IDirectMusicInstrument) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicCollection.VTable, self.vtable).GetInstrument(@ptrCast(*const IDirectMusicCollection, self), dwPatch, ppInstrument); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicCollection_EnumInstrument(self: *const T, dwIndex: u32, pdwPatch: ?*u32, pwszName: ?PWSTR, dwNameLen: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicCollection.VTable, self.vtable).EnumInstrument(@ptrCast(*const IDirectMusicCollection, self), dwIndex, pdwPatch, pwszName, dwNameLen); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicDownload_Value = Guid.initString("d2ac287b-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicDownload = &IID_IDirectMusicDownload_Value; pub const IDirectMusicDownload = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetBuffer: fn( self: *const IDirectMusicDownload, ppvBuffer: ?*?*anyopaque, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicDownload_GetBuffer(self: *const T, ppvBuffer: ?*?*anyopaque, pdwSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicDownload.VTable, self.vtable).GetBuffer(@ptrCast(*const IDirectMusicDownload, self), ppvBuffer, pdwSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicPortDownload_Value = Guid.initString("d2ac287a-b39b-11d1-8704-00600893b1bd"); pub const IID_IDirectMusicPortDownload = &IID_IDirectMusicPortDownload_Value; pub const IDirectMusicPortDownload = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetBuffer: fn( self: *const IDirectMusicPortDownload, dwDLId: u32, ppIDMDownload: ?*?*IDirectMusicDownload, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AllocateBuffer: fn( self: *const IDirectMusicPortDownload, dwSize: u32, ppIDMDownload: ?*?*IDirectMusicDownload, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDLId: fn( self: *const IDirectMusicPortDownload, pdwStartDLId: ?*u32, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAppend: fn( self: *const IDirectMusicPortDownload, pdwAppend: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Download: fn( self: *const IDirectMusicPortDownload, pIDMDownload: ?*IDirectMusicDownload, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unload: fn( self: *const IDirectMusicPortDownload, pIDMDownload: ?*IDirectMusicDownload, ) 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 IDirectMusicPortDownload_GetBuffer(self: *const T, dwDLId: u32, ppIDMDownload: ?*?*IDirectMusicDownload) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).GetBuffer(@ptrCast(*const IDirectMusicPortDownload, self), dwDLId, ppIDMDownload); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPortDownload_AllocateBuffer(self: *const T, dwSize: u32, ppIDMDownload: ?*?*IDirectMusicDownload) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).AllocateBuffer(@ptrCast(*const IDirectMusicPortDownload, self), dwSize, ppIDMDownload); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPortDownload_GetDLId(self: *const T, pdwStartDLId: ?*u32, dwCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).GetDLId(@ptrCast(*const IDirectMusicPortDownload, self), pdwStartDLId, dwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPortDownload_GetAppend(self: *const T, pdwAppend: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).GetAppend(@ptrCast(*const IDirectMusicPortDownload, self), pdwAppend); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPortDownload_Download(self: *const T, pIDMDownload: ?*IDirectMusicDownload) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).Download(@ptrCast(*const IDirectMusicPortDownload, self), pIDMDownload); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPortDownload_Unload(self: *const T, pIDMDownload: ?*IDirectMusicDownload) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPortDownload.VTable, self.vtable).Unload(@ptrCast(*const IDirectMusicPortDownload, self), pIDMDownload); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicPort_Value = Guid.initString("08f2d8c9-37c2-11d2-b9f9-0000f875ac12"); pub const IID_IDirectMusicPort = &IID_IDirectMusicPort_Value; pub const IDirectMusicPort = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, PlayBuffer: fn( self: *const IDirectMusicPort, pBuffer: ?*IDirectMusicBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReadNotificationHandle: fn( self: *const IDirectMusicPort, hEvent: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Read: fn( self: *const IDirectMusicPort, pBuffer: ?*IDirectMusicBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DownloadInstrument: fn( self: *const IDirectMusicPort, pInstrument: ?*IDirectMusicInstrument, ppDownloadedInstrument: ?*?*IDirectMusicDownloadedInstrument, pNoteRanges: ?*DMUS_NOTERANGE, dwNumNoteRanges: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnloadInstrument: fn( self: *const IDirectMusicPort, pDownloadedInstrument: ?*IDirectMusicDownloadedInstrument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLatencyClock: fn( self: *const IDirectMusicPort, ppClock: ?*?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRunningStats: fn( self: *const IDirectMusicPort, pStats: ?*DMUS_SYNTHSTATS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Compact: fn( self: *const IDirectMusicPort, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectMusicPort, pPortCaps: ?*DMUS_PORTCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeviceIoControl: fn( self: *const IDirectMusicPort, dwIoControlCode: u32, lpInBuffer: ?*anyopaque, nInBufferSize: u32, lpOutBuffer: ?*anyopaque, nOutBufferSize: u32, lpBytesReturned: ?*u32, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNumChannelGroups: fn( self: *const IDirectMusicPort, dwChannelGroups: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumChannelGroups: fn( self: *const IDirectMusicPort, pdwChannelGroups: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IDirectMusicPort, fActive: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetChannelPriority: fn( self: *const IDirectMusicPort, dwChannelGroup: u32, dwChannel: u32, dwPriority: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChannelPriority: fn( self: *const IDirectMusicPort, dwChannelGroup: u32, dwChannel: u32, pdwPriority: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDirectSound: fn( self: *const IDirectMusicPort, pDirectSound: ?*IDirectSound, pDirectSoundBuffer: ?*IDirectSoundBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormat: fn( self: *const IDirectMusicPort, pWaveFormatEx: ?*WAVEFORMATEX, pdwWaveFormatExSize: ?*u32, pdwBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_PlayBuffer(self: *const T, pBuffer: ?*IDirectMusicBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).PlayBuffer(@ptrCast(*const IDirectMusicPort, self), pBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_SetReadNotificationHandle(self: *const T, hEvent: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).SetReadNotificationHandle(@ptrCast(*const IDirectMusicPort, self), hEvent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_Read(self: *const T, pBuffer: ?*IDirectMusicBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).Read(@ptrCast(*const IDirectMusicPort, self), pBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_DownloadInstrument(self: *const T, pInstrument: ?*IDirectMusicInstrument, ppDownloadedInstrument: ?*?*IDirectMusicDownloadedInstrument, pNoteRanges: ?*DMUS_NOTERANGE, dwNumNoteRanges: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).DownloadInstrument(@ptrCast(*const IDirectMusicPort, self), pInstrument, ppDownloadedInstrument, pNoteRanges, dwNumNoteRanges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_UnloadInstrument(self: *const T, pDownloadedInstrument: ?*IDirectMusicDownloadedInstrument) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).UnloadInstrument(@ptrCast(*const IDirectMusicPort, self), pDownloadedInstrument); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetLatencyClock(self: *const T, ppClock: ?*?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetLatencyClock(@ptrCast(*const IDirectMusicPort, self), ppClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetRunningStats(self: *const T, pStats: ?*DMUS_SYNTHSTATS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetRunningStats(@ptrCast(*const IDirectMusicPort, self), pStats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).Compact(@ptrCast(*const IDirectMusicPort, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetCaps(self: *const T, pPortCaps: ?*DMUS_PORTCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectMusicPort, self), pPortCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_DeviceIoControl(self: *const T, dwIoControlCode: u32, lpInBuffer: ?*anyopaque, nInBufferSize: u32, lpOutBuffer: ?*anyopaque, nOutBufferSize: u32, lpBytesReturned: ?*u32, lpOverlapped: ?*OVERLAPPED) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).DeviceIoControl(@ptrCast(*const IDirectMusicPort, self), dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, lpOverlapped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_SetNumChannelGroups(self: *const T, dwChannelGroups: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).SetNumChannelGroups(@ptrCast(*const IDirectMusicPort, self), dwChannelGroups); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetNumChannelGroups(self: *const T, pdwChannelGroups: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetNumChannelGroups(@ptrCast(*const IDirectMusicPort, self), pdwChannelGroups); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_Activate(self: *const T, fActive: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).Activate(@ptrCast(*const IDirectMusicPort, self), fActive); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_SetChannelPriority(self: *const T, dwChannelGroup: u32, dwChannel: u32, dwPriority: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).SetChannelPriority(@ptrCast(*const IDirectMusicPort, self), dwChannelGroup, dwChannel, dwPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetChannelPriority(self: *const T, dwChannelGroup: u32, dwChannel: u32, pdwPriority: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetChannelPriority(@ptrCast(*const IDirectMusicPort, self), dwChannelGroup, dwChannel, pdwPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_SetDirectSound(self: *const T, pDirectSound: ?*IDirectSound, pDirectSoundBuffer: ?*IDirectSoundBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).SetDirectSound(@ptrCast(*const IDirectMusicPort, self), pDirectSound, pDirectSoundBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicPort_GetFormat(self: *const T, pWaveFormatEx: ?*WAVEFORMATEX, pdwWaveFormatExSize: ?*u32, pdwBufferSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicPort.VTable, self.vtable).GetFormat(@ptrCast(*const IDirectMusicPort, self), pWaveFormatEx, pdwWaveFormatExSize, pdwBufferSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicThru_Value = Guid.initString("ced153e7-3606-11d2-b9f9-0000f875ac12"); pub const IID_IDirectMusicThru = &IID_IDirectMusicThru_Value; pub const IDirectMusicThru = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ThruChannel: fn( self: *const IDirectMusicThru, dwSourceChannelGroup: u32, dwSourceChannel: u32, dwDestinationChannelGroup: u32, dwDestinationChannel: u32, pDestinationPort: ?*IDirectMusicPort, ) 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 IDirectMusicThru_ThruChannel(self: *const T, dwSourceChannelGroup: u32, dwSourceChannel: u32, dwDestinationChannelGroup: u32, dwDestinationChannel: u32, pDestinationPort: ?*IDirectMusicPort) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicThru.VTable, self.vtable).ThruChannel(@ptrCast(*const IDirectMusicThru, self), dwSourceChannelGroup, dwSourceChannel, dwDestinationChannelGroup, dwDestinationChannel, pDestinationPort); } };} pub usingnamespace MethodMixin(@This()); }; pub const DMUS_VOICE_STATE = extern struct { bExists: BOOL, spPosition: u64, }; const IID_IDirectMusicSynth_Value = Guid.initString("09823661-5c85-11d2-afa6-00aa0024d8b6"); pub const IID_IDirectMusicSynth = &IID_IDirectMusicSynth_Value; pub const IDirectMusicSynth = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IDirectMusicSynth, pPortParams: ?*DMUS_PORTPARAMS8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IDirectMusicSynth, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNumChannelGroups: fn( self: *const IDirectMusicSynth, dwGroups: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Download: fn( self: *const IDirectMusicSynth, phDownload: ?*?HANDLE, pvData: ?*anyopaque, pbFree: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unload: fn( self: *const IDirectMusicSynth, hDownload: ?HANDLE, lpFreeHandle: isize, hUserData: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PlayBuffer: fn( self: *const IDirectMusicSynth, rt: i64, pbBuffer: ?*u8, cbBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRunningStats: fn( self: *const IDirectMusicSynth, pStats: ?*DMUS_SYNTHSTATS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPortCaps: fn( self: *const IDirectMusicSynth, pCaps: ?*DMUS_PORTCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMasterClock: fn( self: *const IDirectMusicSynth, pClock: ?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLatencyClock: fn( self: *const IDirectMusicSynth, ppClock: ?*?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IDirectMusicSynth, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSynthSink: fn( self: *const IDirectMusicSynth, pSynthSink: ?*IDirectMusicSynthSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Render: fn( self: *const IDirectMusicSynth, pBuffer: ?*i16, dwLength: u32, llPosition: i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetChannelPriority: fn( self: *const IDirectMusicSynth, dwChannelGroup: u32, dwChannel: u32, dwPriority: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChannelPriority: fn( self: *const IDirectMusicSynth, dwChannelGroup: u32, dwChannel: u32, pdwPriority: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormat: fn( self: *const IDirectMusicSynth, pWaveFormatEx: ?*WAVEFORMATEX, pdwWaveFormatExSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAppend: fn( self: *const IDirectMusicSynth, pdwAppend: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Open(self: *const T, pPortParams: ?*DMUS_PORTPARAMS8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Open(@ptrCast(*const IDirectMusicSynth, self), pPortParams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Close(@ptrCast(*const IDirectMusicSynth, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_SetNumChannelGroups(self: *const T, dwGroups: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).SetNumChannelGroups(@ptrCast(*const IDirectMusicSynth, self), dwGroups); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Download(self: *const T, phDownload: ?*?HANDLE, pvData: ?*anyopaque, pbFree: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Download(@ptrCast(*const IDirectMusicSynth, self), phDownload, pvData, pbFree); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Unload(self: *const T, hDownload: ?HANDLE, lpFreeHandle: isize, hUserData: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Unload(@ptrCast(*const IDirectMusicSynth, self), hDownload, lpFreeHandle, hUserData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_PlayBuffer(self: *const T, rt: i64, pbBuffer: ?*u8, cbBuffer: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).PlayBuffer(@ptrCast(*const IDirectMusicSynth, self), rt, pbBuffer, cbBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetRunningStats(self: *const T, pStats: ?*DMUS_SYNTHSTATS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetRunningStats(@ptrCast(*const IDirectMusicSynth, self), pStats); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetPortCaps(self: *const T, pCaps: ?*DMUS_PORTCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetPortCaps(@ptrCast(*const IDirectMusicSynth, self), pCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_SetMasterClock(self: *const T, pClock: ?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).SetMasterClock(@ptrCast(*const IDirectMusicSynth, self), pClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetLatencyClock(self: *const T, ppClock: ?*?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetLatencyClock(@ptrCast(*const IDirectMusicSynth, self), ppClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Activate(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Activate(@ptrCast(*const IDirectMusicSynth, self), fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_SetSynthSink(self: *const T, pSynthSink: ?*IDirectMusicSynthSink) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).SetSynthSink(@ptrCast(*const IDirectMusicSynth, self), pSynthSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_Render(self: *const T, pBuffer: ?*i16, dwLength: u32, llPosition: i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).Render(@ptrCast(*const IDirectMusicSynth, self), pBuffer, dwLength, llPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_SetChannelPriority(self: *const T, dwChannelGroup: u32, dwChannel: u32, dwPriority: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).SetChannelPriority(@ptrCast(*const IDirectMusicSynth, self), dwChannelGroup, dwChannel, dwPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetChannelPriority(self: *const T, dwChannelGroup: u32, dwChannel: u32, pdwPriority: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetChannelPriority(@ptrCast(*const IDirectMusicSynth, self), dwChannelGroup, dwChannel, pdwPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetFormat(self: *const T, pWaveFormatEx: ?*WAVEFORMATEX, pdwWaveFormatExSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetFormat(@ptrCast(*const IDirectMusicSynth, self), pWaveFormatEx, pdwWaveFormatExSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth_GetAppend(self: *const T, pdwAppend: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth.VTable, self.vtable).GetAppend(@ptrCast(*const IDirectMusicSynth, self), pdwAppend); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicSynth8_Value = Guid.initString("53cab625-2711-4c9f-9de7-1b7f925f6fc8"); pub const IID_IDirectMusicSynth8 = &IID_IDirectMusicSynth8_Value; pub const IDirectMusicSynth8 = extern struct { pub const VTable = extern struct { base: IDirectMusicSynth.VTable, PlayVoice: fn( self: *const IDirectMusicSynth8, rt: i64, dwVoiceId: u32, dwChannelGroup: u32, dwChannel: u32, dwDLId: u32, prPitch: i32, vrVolume: i32, stVoiceStart: u64, stLoopStart: u64, stLoopEnd: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopVoice: fn( self: *const IDirectMusicSynth8, rt: i64, dwVoiceId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVoiceState: fn( self: *const IDirectMusicSynth8, dwVoice: ?*u32, cbVoice: u32, dwVoiceState: ?*DMUS_VOICE_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Refresh: fn( self: *const IDirectMusicSynth8, dwDownloadID: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AssignChannelToBuses: fn( self: *const IDirectMusicSynth8, dwChannelGroup: u32, dwChannel: u32, pdwBuses: ?*u32, cBuses: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDirectMusicSynth.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth8_PlayVoice(self: *const T, rt: i64, dwVoiceId: u32, dwChannelGroup: u32, dwChannel: u32, dwDLId: u32, prPitch: i32, vrVolume: i32, stVoiceStart: u64, stLoopStart: u64, stLoopEnd: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth8.VTable, self.vtable).PlayVoice(@ptrCast(*const IDirectMusicSynth8, self), rt, dwVoiceId, dwChannelGroup, dwChannel, dwDLId, prPitch, vrVolume, stVoiceStart, stLoopStart, stLoopEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth8_StopVoice(self: *const T, rt: i64, dwVoiceId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth8.VTable, self.vtable).StopVoice(@ptrCast(*const IDirectMusicSynth8, self), rt, dwVoiceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth8_GetVoiceState(self: *const T, dwVoice: ?*u32, cbVoice: u32, dwVoiceState: ?*DMUS_VOICE_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth8.VTable, self.vtable).GetVoiceState(@ptrCast(*const IDirectMusicSynth8, self), dwVoice, cbVoice, dwVoiceState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth8_Refresh(self: *const T, dwDownloadID: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth8.VTable, self.vtable).Refresh(@ptrCast(*const IDirectMusicSynth8, self), dwDownloadID, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynth8_AssignChannelToBuses(self: *const T, dwChannelGroup: u32, dwChannel: u32, pdwBuses: ?*u32, cBuses: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynth8.VTable, self.vtable).AssignChannelToBuses(@ptrCast(*const IDirectMusicSynth8, self), dwChannelGroup, dwChannel, pdwBuses, cBuses); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectMusicSynthSink_Value = Guid.initString("09823663-5c85-11d2-afa6-00aa0024d8b6"); pub const IID_IDirectMusicSynthSink = &IID_IDirectMusicSynthSink_Value; pub const IDirectMusicSynthSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Init: fn( self: *const IDirectMusicSynthSink, pSynth: ?*IDirectMusicSynth, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMasterClock: fn( self: *const IDirectMusicSynthSink, pClock: ?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLatencyClock: fn( self: *const IDirectMusicSynthSink, ppClock: ?*?*IReferenceClock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Activate: fn( self: *const IDirectMusicSynthSink, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SampleToRefTime: fn( self: *const IDirectMusicSynthSink, llSampleTime: i64, prfTime: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RefTimeToSample: fn( self: *const IDirectMusicSynthSink, rfTime: i64, pllSampleTime: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDirectSound: fn( self: *const IDirectMusicSynthSink, pDirectSound: ?*IDirectSound, pDirectSoundBuffer: ?*IDirectSoundBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDesiredBufferSize: fn( self: *const IDirectMusicSynthSink, pdwBufferSizeInSamples: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_Init(self: *const T, pSynth: ?*IDirectMusicSynth) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).Init(@ptrCast(*const IDirectMusicSynthSink, self), pSynth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_SetMasterClock(self: *const T, pClock: ?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).SetMasterClock(@ptrCast(*const IDirectMusicSynthSink, self), pClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_GetLatencyClock(self: *const T, ppClock: ?*?*IReferenceClock) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).GetLatencyClock(@ptrCast(*const IDirectMusicSynthSink, self), ppClock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_Activate(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).Activate(@ptrCast(*const IDirectMusicSynthSink, self), fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_SampleToRefTime(self: *const T, llSampleTime: i64, prfTime: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).SampleToRefTime(@ptrCast(*const IDirectMusicSynthSink, self), llSampleTime, prfTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_RefTimeToSample(self: *const T, rfTime: i64, pllSampleTime: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).RefTimeToSample(@ptrCast(*const IDirectMusicSynthSink, self), rfTime, pllSampleTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_SetDirectSound(self: *const T, pDirectSound: ?*IDirectSound, pDirectSoundBuffer: ?*IDirectSoundBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).SetDirectSound(@ptrCast(*const IDirectMusicSynthSink, self), pDirectSound, pDirectSoundBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectMusicSynthSink_GetDesiredBufferSize(self: *const T, pdwBufferSizeInSamples: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectMusicSynthSink.VTable, self.vtable).GetDesiredBufferSize(@ptrCast(*const IDirectMusicSynthSink, self), pdwBufferSizeInSamples); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSPROPERTY_DIRECTSOUNDDEVICE = enum(i32) { WAVEDEVICEMAPPING_A = 1, DESCRIPTION_1 = 2, ENUMERATE_1 = 3, WAVEDEVICEMAPPING_W = 4, DESCRIPTION_A = 5, DESCRIPTION_W = 6, ENUMERATE_A = 7, ENUMERATE_W = 8, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A = DSPROPERTY_DIRECTSOUNDDEVICE.WAVEDEVICEMAPPING_A; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1 = DSPROPERTY_DIRECTSOUNDDEVICE.DESCRIPTION_1; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1 = DSPROPERTY_DIRECTSOUNDDEVICE.ENUMERATE_1; pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W = DSPROPERTY_DIRECTSOUNDDEVICE.WAVEDEVICEMAPPING_W; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A = DSPROPERTY_DIRECTSOUNDDEVICE.DESCRIPTION_A; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W = DSPROPERTY_DIRECTSOUNDDEVICE.DESCRIPTION_W; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A = DSPROPERTY_DIRECTSOUNDDEVICE.ENUMERATE_A; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W = DSPROPERTY_DIRECTSOUNDDEVICE.ENUMERATE_W; pub const DIRECTSOUNDDEVICE_TYPE = enum(i32) { EMULATED = 0, VXD = 1, WDM = 2, }; pub const DIRECTSOUNDDEVICE_TYPE_EMULATED = DIRECTSOUNDDEVICE_TYPE.EMULATED; pub const DIRECTSOUNDDEVICE_TYPE_VXD = DIRECTSOUNDDEVICE_TYPE.VXD; pub const DIRECTSOUNDDEVICE_TYPE_WDM = DIRECTSOUNDDEVICE_TYPE.WDM; pub const DIRECTSOUNDDEVICE_DATAFLOW = enum(i32) { RENDER = 0, CAPTURE = 1, }; pub const DIRECTSOUNDDEVICE_DATAFLOW_RENDER = DIRECTSOUNDDEVICE_DATAFLOW.RENDER; pub const DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE = DIRECTSOUNDDEVICE_DATAFLOW.CAPTURE; pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A_DATA = extern struct { DeviceName: ?PSTR, DataFlow: DIRECTSOUNDDEVICE_DATAFLOW, DeviceId: Guid, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W_DATA = extern struct { DeviceName: ?PWSTR, DataFlow: DIRECTSOUNDDEVICE_DATAFLOW, DeviceId: Guid, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA = extern struct { DeviceId: Guid, DescriptionA: [256]CHAR, DescriptionW: [256]u16, ModuleA: [260]CHAR, ModuleW: [260]u16, Type: DIRECTSOUNDDEVICE_TYPE, DataFlow: DIRECTSOUNDDEVICE_DATAFLOW, WaveDeviceId: u32, Devnode: u32, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA = extern struct { Type: DIRECTSOUNDDEVICE_TYPE, DataFlow: DIRECTSOUNDDEVICE_DATAFLOW, DeviceId: Guid, Description: ?PSTR, Module: ?PSTR, Interface: ?PSTR, WaveDeviceId: u32, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA = extern struct { Type: DIRECTSOUNDDEVICE_TYPE, DataFlow: DIRECTSOUNDDEVICE_DATAFLOW, DeviceId: Guid, Description: ?PWSTR, Module: ?PWSTR, Interface: ?PWSTR, WaveDeviceId: u32, }; pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1 = fn( param0: ?*DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA = fn( param0: ?*DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW = fn( param0: ?*DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1_DATA = extern struct { Callback: ?LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1, Context: ?*anyopaque, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A_DATA = extern struct { Callback: ?LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA, Context: ?*anyopaque, }; pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA = extern struct { Callback: ?LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW, Context: ?*anyopaque, }; pub const Tag_DVAudInfo = extern struct { bAudStyle: [2]u8, bAudQu: [2]u8, bNumAudPin: u8, wAvgSamplesPerPinPerFrm: [2]u16, wBlkMode: u16, wDIFMode: u16, wBlkDiv: u16, }; pub const MDEVICECAPSEX = packed struct { cbSize: u32, pCaps: ?*anyopaque, }; pub const MIDIOPENDESC = packed struct { hMidi: ?HMIDI, dwCallback: usize, dwInstance: usize, dnDevNode: usize, cIds: u32, rgIds: [1]MIDIOPENSTRMID, }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (1) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK = thismodule.LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA; }, .wide => struct { pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK = thismodule.LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW; }, .unspecified => if (@import("builtin").is_test) struct { pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK = *opaque{}; } else struct { pub const LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK = @compileError("'LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (16) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const CHAR = @import("../../foundation.zig").CHAR; const HANDLE = @import("../../foundation.zig").HANDLE; const HMIDI = @import("../../media/audio.zig").HMIDI; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const IDirectSound = @import("../../media/audio/direct_sound.zig").IDirectSound; const IDirectSoundBuffer = @import("../../media/audio/direct_sound.zig").IDirectSoundBuffer; const IReferenceClock = @import("../../media.zig").IReferenceClock; const IUnknown = @import("../../system/com.zig").IUnknown; const MIDIOPENSTRMID = @import("../../media/multimedia.zig").MIDIOPENSTRMID; const OVERLAPPED = @import("../../system/io.zig").OVERLAPPED; const PSTR = @import("../../foundation.zig").PSTR; const PWSTR = @import("../../foundation.zig").PWSTR; const WAVEFORMATEX = @import("../../media/audio.zig").WAVEFORMATEX; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1")) { _ = LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1; } if (@hasDecl(@This(), "LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA")) { _ = LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA; } if (@hasDecl(@This(), "LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW")) { _ = LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/media/audio/direct_music.zig
//! See: //! - Prefix/Huffman coding, //! - Canonical Huffman, //! - Package-merge algorithm. const std = @import("std"); const math = std.math; const expect = std.testing.expect; const expectError = std.testing.expectError; const print = std.debug.print; const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; inline fn bits_needed_to_represent_int(x: usize) usize { return if (x == 0) 0 else math.log2_int(usize, x) + 1; } test "bits needed to represent int" { try expect(bits_needed_to_represent_int(0) == 0); try expect(bits_needed_to_represent_int(1) == 1); try expect(bits_needed_to_represent_int(2) == 2); try expect(bits_needed_to_represent_int(7) == 3); try expect(bits_needed_to_represent_int(8) == 4); try expect(bits_needed_to_represent_int(10) == 4); try expect(bits_needed_to_represent_int(16) == 5); try expect(bits_needed_to_represent_int(math.maxInt(u8)) == 8); try expect(bits_needed_to_represent_int(math.maxInt(u16)) == 16); try expect(bits_needed_to_represent_int(math.maxInt(u16)+1) == 17); } const Item = struct { count: u32, token: ?u16 }; fn compare_items_asc(_: void, a: Item, b: Item) bool { return a.count < b.count; } /// Remove unused items, sort by count. fn items_prepare(allocator: *Allocator, items: []const Item) ![]const Item { var prepared = std.ArrayList(Item).init(allocator); for (items) |item| { if (item.count > 0) try prepared.append(item); } const prepared_as_slice = prepared.toOwnedSlice(); std.sort.sort(Item, prepared_as_slice, {}, compare_items_asc); return prepared_as_slice; } fn package(allocator: *Allocator, items: []const Item) ![]const Item { var packaged = std.ArrayList(Item).init(allocator); var i: usize = 0; while (i+2 <= items.len) : (i+=2) { const pairwise_sum = items[i].count + items[i+1].count; const p = Item {.count = pairwise_sum, .token = null}; try packaged.append(p); } return packaged.toOwnedSlice(); } fn merge(allocator: *Allocator, items: []const Item, packages: []const Item) ![]const Item { var merged = std.ArrayList(Item).init(allocator); // Merged it EMPTY!!! Copy items!! // Note: what is going on? for (packages) |package_| { for (items) |item| { if (item.count >= p.count) { try merged.append(package_); } else { try merged.append(item); } } } return merged.toOwnedSlice(); } fn package_merge(allocator: *Allocator, items: []const Item, max_bit_length: usize) !void { defer allocator.free(items); // Sort Items. Remove unused Items. var prepared_items = try items_prepare(allocator, items); defer allocator.free(prepared_items); // for iteration in max_bit_length: // package // merge var iterations = std.ArrayList([]const Item).init(allocator); var prev_items = prepared_items; var i: u32 = 0; while (i < max_bit_length) : (i += 1) { const packaged = try package(allocator, prev_items); const merged = try merge(allocator, prepared_items, packaged); try iterations.append(merged); prev_items = iterations.items[iterations.items.len]; } // for each slice in the arraylist of iterations: // bit_len += 1 // for each } //test "package merge" { // const allocator = std.heap.page_allocator; // const items = [_]Item{ // Item{ // .token = 'A', // .count = 10 // }, // Item{ // .token = 'C', // .count = 13 // }, // Item{ // .token = 'R', // .count = 10 // }, // Item{ // .token = 'L', // .count = 1 // }, // }; // // try package_merge(allocator, items[0..], 16); //} pub fn main() !void { const allocator = std.heap.page_allocator; const items = [_]Item{ Item{ .token = 'A', .count = 10 }, Item{ .token = 'C', .count = 13 }, Item{ .token = 'R', .count = 10 }, Item{ .token = 'L', .count = 1 }, }; try package_merge(allocator, items[0..], 16); } const PMError = error { NotEnoughBits, NoItemsToEncode }; ///// Given a slice of symbols, sorted by ascending frequency, with unused symbols removed, ///// return the canonical representation, which the caller must free. //fn package_merge(allocator: *Allocator, symbols: []const Item, max_len: usize) !void { // _ = allocator; // // if (bits_needed_to_represent_int(symbols.len) > max_len) // return PMError.NotEnoughBits; // // if (symbols.len == 0) // return PMError.NoItemsToEncode; // // { // var i: usize = 0; // while (i+2 <= symbols.len) { // var pairwise_sum = symbols[i].count + symbols[i+1].count; // try merge(allocator, // i += 2; // } // } //} // //test "package merge fails on 0 symbols" { // const allocator = std.heap.page_allocator; // const symbols = [0]Item{}; // try expectError(PMError.NoItemsToEncode, package_merge(allocator, symbols[0..], 10)); //} // //test "package merge" { // const allocator = std.heap.page_allocator; // // const symbols = [_]Item{ // Item{ // .token = 'A', // .count = 10 // } // }; // // try package_merge(allocator, symbols[0..], 10); //} // //fn package_merge(allocator: *Allocator, text: []const u8, max_len: u32) !*Node { // if (bits_needed_to_represent_int(symbols.len) < max_len) // // Build ArrayList of pointers to alloc'd leaf nodes. // var symbols = std.ArrayList(*Item).init(allocator); // defer symbols.deinit(); // // outer: for (text) |byte| { // for (symbols.items) |symbol| { // if (byte == symbol.token) { // symbol.count += 1; // continue :outer; // } // } // // // Reached only if byte not yet found. // var symbol: *Item = try allocator.create(Item); // symbol.* = Item { .leaf = .{ .byte = byte, .count = 1 } }; // try symbols.append(symbol); // } //} ///// The symbols in lexicographic order, along with the count of symbols for each bit-length. ///// Eg. A value of {1,1,2} means the first symbol in `symbols` has a ///// bit-length of 1, the next 1 has length 2, and the next two have length 3. //const CanonicalRepresentation = struct { // symbols: []const u8, // count_per_bit_length: []const u32, //};
src/package_merge.zig
const std = @import("std"); const fs = std.fs; const print = std.debug.print; const c = @cImport({ @cInclude("linux/spi/spidev.h"); @cInclude("sys/ioctl.h"); @cInclude("sys/errno.h"); }); // const Config = extern struct { // unsigned int mode; // unsigned int bits_per_word; // unsigned int speed_hz; // unsigned int delay_us; // }; const DEFAULT_MODE = 0; const DEFAULT_SPEED = 1000000; const spi_ioc_transfer = extern struct { tx_buf: u64, rx_buf: u64, len: u32, speed_hz: u32 = 1000000, delay_usecs: u16 = 10, bits_per_word: u8 = 8, cs_change: u8 = 0, tx_nbits: u8 = 0, rx_bits: u8 = 0, pad: u16 = 0, }; const SPI_DEFAULT_CHUNK_SIZE = 4096; // TODO : build this magic number based on the C macros, instead of hard coding it. const IOC_MESSAGE = 0x40206b00; pub const SPI = struct { fd: fs.File, mode: u8 = DEFAULT_MODE, speed_hz: u32 = DEFAULT_SPEED, // config: Config, chunk_size: u32 = SPI_DEFAULT_CHUNK_SIZE, pub fn configure(self: *SPI, mode: u8, speed: u32) c_int { var rv = c.ioctl(self.fd.handle, c.SPI_IOC_WR_MODE, &mode); if (rv == -1) { print("spi:configure : cannot set mode to {}\n", .{mode}); return rv; } self.mode = mode; rv = c.ioctl(self.fd.handle, c.SPI_IOC_WR_MAX_SPEED_HZ, &speed); if (rv == -1) { print("spi:configure : cannot set speed to {}\n", .{speed}); } self.speed_hz = speed; return rv; } pub fn transfer(self: *SPI, to_write: [*]u8, to_read: [*]u8, len: usize) c_int { var tfer = spi_ioc_transfer{ .tx_buf = @intCast(u64, @ptrToInt(&to_write[0])), .rx_buf = @intCast(u64, @ptrToInt(&to_read[0])), .len = len, .speed_hz = self.speed_hz, }; return c.ioctl(self.fd.handle, IOC_MESSAGE, &tfer); } pub fn write(self: *SPI, buffer: []u8) u8 { if (buffer.len < SPI_DEFAULT_CHUNK_SIZE) { var tfer = spi_ioc_transfer{ .tx_buf = @intCast(u64, @ptrToInt(&buffer[0])), .rx_buf = 0, .len = buffer.len, }; return @intCast(u8, c.ioctl(self.fd.handle, IOC_MESSAGE, &tfer)); } else { print("SPI : Trying to write a buffer larger than supported chunk size", .{}); return 0; } } pub fn read_byte(self: *SPI) ?u8 { var buffer = [_]u8{0}; var tfer = spi_ioc_transfer{ .tx_buf = 0, .rx_buf = @intCast(u64, @ptrToInt(&buffer[0])), .len = 1, .speed_hz = self.speed_hz, }; if (c.ioctl(self.fd.handle, IOC_MESSAGE, &tfer) != -1) { return buffer[0]; } return null; } pub fn read_into(self: *SPI, to_read: [*]u8, len: u8) c_int { if (length < 256) { var buffer = [_]u8{0} ** 256; var tfer = spi_ioc_transfer{ .tx_buf = 0, .rx_buf = @intCast(u64, @ptrToInt(&to_read[0])), .len = len, .speed_hz = self.speed_hz, }; return c.ioctl(self.fd.handle, IOC_MESSAGE, &tfer); } else { print("SPI : Trying to read a buffer larger than supported chunk size", .{}); return null; } } };
src/bus/spi.zig
const std = @import("../../std.zig"); const maxInt = std.math.maxInt; const pid_t = linux.pid_t; const uid_t = linux.uid_t; const clock_t = linux.clock_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; const linux = std.os.linux; const SYS = linux.SYS; const sockaddr = linux.sockaddr; const socklen_t = linux.socklen_t; const iovec = std.os.iovec; const iovec_const = std.os.iovec_const; const timespec = linux.timespec; pub fn syscall_pipe(fd: *[2]i32) usize { return asm volatile ( \\ mov %[arg], %%g3 \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ # Return the error code \\ ba 2f \\ neg %%o0 \\1: \\ st %%o0, [%%g3+0] \\ st %%o1, [%%g3+4] \\ clr %%o0 \\2: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(SYS.pipe)), [arg] "r" (fd), : "memory", "g3" ); } pub fn syscall_fork() usize { // Linux/sparc64 fork() returns two values in %o0 and %o1: // - On the parent's side, %o0 is the child's PID and %o1 is 0. // - On the child's side, %o0 is the parent's PID and %o1 is 1. // We need to clear the child's %o0 so that the return values // conform to the libc convention. return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ ba 2f \\ neg %%o0 \\ 1: \\ # Clear the child's %%o0 \\ dec %%o1 \\ and %%o1, %%o0, %%o0 \\ 2: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(SYS.fork)), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall0(number: SYS) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), [arg2] "{o1}" (arg2), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), [arg2] "{o1}" (arg2), [arg3] "{o2}" (arg3), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), [arg2] "{o1}" (arg2), [arg3] "{o2}" (arg3), [arg4] "{o3}" (arg4), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), [arg2] "{o1}" (arg2), [arg3] "{o2}" (arg3), [arg4] "{o3}" (arg4), [arg5] "{o4}" (arg5), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub fn syscall6( number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ( \\ t 0x6d \\ bcc,pt %%xcc, 1f \\ nop \\ neg %%o0 \\ 1: : [ret] "={o0}" (-> usize), : [number] "{g1}" (@enumToInt(number)), [arg1] "{o0}" (arg1), [arg2] "{o1}" (arg2), [arg3] "{o2}" (arg3), [arg4] "{o3}" (arg4), [arg5] "{o4}" (arg5), [arg6] "{o5}" (arg6), : "memory", "xcc", "o1", "o2", "o3", "o4", "o5", "o7" ); } /// This matches the libc clone function. pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags: usize, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize; pub const restore = restore_rt; // Need to use C ABI here instead of naked // to prevent an infinite loop when calling rt_sigreturn. pub fn restore_rt() callconv(.C) void { return asm volatile ("t 0x6d" : : [number] "{g1}" (@enumToInt(SYS.rt_sigreturn)), : "memory", "xcc", "o0", "o1", "o2", "o3", "o4", "o5", "o7" ); } pub const O = struct { pub const CREAT = 0x200; pub const EXCL = 0x800; pub const NOCTTY = 0x8000; pub const TRUNC = 0x400; pub const APPEND = 0x8; pub const NONBLOCK = 0x4000; pub const SYNC = 0x802000; pub const DSYNC = 0x2000; pub const RSYNC = SYNC; pub const DIRECTORY = 0x10000; pub const NOFOLLOW = 0x20000; pub const CLOEXEC = 0x400000; pub const ASYNC = 0x40; pub const DIRECT = 0x100000; pub const LARGEFILE = 0; pub const NOATIME = 0x200000; pub const PATH = 0x1000000; pub const TMPFILE = 0x2010000; pub const NDELAY = NONBLOCK | 0x4; }; pub const F = struct { pub const DUPFD = 0; pub const GETFD = 1; pub const SETFD = 2; pub const GETFL = 3; pub const SETFL = 4; pub const SETOWN = 5; pub const GETOWN = 6; pub const GETLK = 7; pub const SETLK = 8; pub const SETLKW = 9; pub const RDLCK = 1; pub const WRLCK = 2; pub const UNLCK = 3; pub const SETOWN_EX = 15; pub const GETOWN_EX = 16; pub const GETOWNER_UIDS = 17; }; pub const LOCK = struct { pub const SH = 1; pub const EX = 2; pub const NB = 4; pub const UN = 8; }; pub const MAP = struct { /// stack-like segment pub const GROWSDOWN = 0x0200; /// ETXTBSY pub const DENYWRITE = 0x0800; /// mark it as an executable pub const EXECUTABLE = 0x1000; /// pages are locked pub const LOCKED = 0x0100; /// don't check for reservations pub const NORESERVE = 0x0040; }; pub const VDSO = struct { pub const CGT_SYM = "__vdso_clock_gettime"; pub const CGT_VER = "LINUX_2.6"; }; pub const Flock = extern struct { type: i16, whence: i16, start: off_t, len: off_t, pid: pid_t, }; pub const msghdr = extern struct { name: ?*sockaddr, namelen: socklen_t, iov: [*]iovec, iovlen: u64, control: ?*anyopaque, controllen: u64, flags: i32, }; pub const msghdr_const = extern struct { name: ?*const sockaddr, namelen: socklen_t, iov: [*]iovec_const, iovlen: u64, control: ?*anyopaque, controllen: u64, flags: i32, }; pub const off_t = i64; pub const ino_t = u64; pub const mode_t = u32; pub const dev_t = usize; pub const nlink_t = u32; pub const blksize_t = isize; pub const blkcnt_t = isize; // The `stat64` definition used by the kernel. pub const Stat = extern struct { dev: u64, ino: u64, nlink: u64, mode: u32, uid: u32, gid: u32, __pad0: u32, rdev: u64, size: i64, blksize: i64, blocks: i64, atim: timespec, mtim: timespec, ctim: timespec, __unused: [3]u64, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const timeval = extern struct { tv_sec: isize, tv_usec: i32, }; pub const timezone = extern struct { tz_minuteswest: i32, tz_dsttime: i32, }; // TODO I'm not sure if the code below is correct, need someone with more // knowledge about sparc64 linux internals to look into. pub const Elf_Symndx = u32; pub const fpstate = extern struct { regs: [32]u64, fsr: u64, gsr: u64, fprs: u64, }; pub const __fpq = extern struct { fpq_addr: *u32, fpq_instr: u32, }; pub const __fq = extern struct { FQu: extern union { whole: f64, fpq: __fpq, }, }; pub const fpregset_t = extern struct { fpu_fr: extern union { fpu_regs: [32]u32, fpu_dregs: [32]f64, fpu_qregs: [16]c_longdouble, }, fpu_q: *__fq, fpu_fsr: u64, fpu_qcnt: u8, fpu_q_entrysize: u8, fpu_en: u8, }; pub const siginfo_fpu_t = extern struct { float_regs: [64]u32, fsr: u64, gsr: u64, fprs: u64, }; pub const sigcontext = extern struct { info: [128]i8, regs: extern struct { u_regs: [16]u64, tstate: u64, tpc: u64, tnpc: u64, y: u64, fprs: u64, }, fpu_save: *siginfo_fpu_t, stack: extern struct { sp: usize, flags: i32, size: u64, }, mask: u64, }; pub const greg_t = u64; pub const gregset_t = [19]greg_t; pub const fq = extern struct { addr: *u64, insn: u32, }; pub const fpu_t = extern struct { fregs: extern union { sregs: [32]u32, dregs: [32]u64, qregs: [16]c_longdouble, }, fsr: u64, fprs: u64, gsr: u64, fq: *fq, qcnt: u8, qentsz: u8, enab: u8, }; pub const mcontext_t = extern struct { gregs: gregset_t, fp: greg_t, @"i7": greg_t, fpregs: fpu_t, }; pub const ucontext_t = extern struct { link: ?*ucontext_t, flags: u64, sigmask: u64, mcontext: mcontext_t, stack: stack_t, sigmask: sigset_t, }; pub const rlimit_resource = enum(c_int) { /// Per-process CPU limit, in seconds. CPU, /// Largest file that can be created, in bytes. FSIZE, /// Maximum size of data segment, in bytes. DATA, /// Maximum size of stack segment, in bytes. STACK, /// Largest core file that can be created, in bytes. CORE, /// Largest resident set size, in bytes. /// This affects swapping; processes that are exceeding their /// resident set size will be more likely to have physical memory /// taken from them. RSS, /// Number of open files. NOFILE, /// Number of processes. NPROC, /// Locked-in-memory address space. MEMLOCK, /// Address space limit. AS, /// Maximum number of file locks. LOCKS, /// Maximum number of pending signals. SIGPENDING, /// Maximum bytes in POSIX message queues. MSGQUEUE, /// Maximum nice priority allowed to raise to. /// Nice levels 19 .. -20 correspond to 0 .. 39 /// values of this resource limit. NICE, /// Maximum realtime priority allowed for non-priviledged /// processes. RTPRIO, /// Maximum CPU time in µs that a process scheduled under a real-time /// scheduling policy may consume without making a blocking system /// call before being forcibly descheduled. RTTIME, _, };
lib/std/os/linux/sparc64.zig
const Array = @import("std").ArrayList; const Builder = @import("std").build.Builder; const builtin = @import("builtin"); const join = @import("std").mem.join; pub fn build(b: &Builder) void { //// // Default step. // const kernel = buildKernel(b); const terminal = buildServer(b, "terminal"); const keyboard = buildServer(b, "keyboard"); // TODO: unprivileged processes, not servers. const shell = buildServer(b, "shell"); //// // Test and debug on Qemu. // const qemu = b.step("qemu", "Run the OS with Qemu"); const qemu_debug = b.step("qemu-debug", "Run the OS with Qemu and wait for debugger to attach"); const common_params = [][]const u8 { "qemu-system-i386", "-display", "curses", "-kernel", kernel, "-initrd", join(b.allocator, ',', terminal, keyboard, shell) catch unreachable, }; const debug_params = [][]const u8 {"-s", "-S"}; var qemu_params = Array([]const u8).init(b.allocator); var qemu_debug_params = Array([]const u8).init(b.allocator); for (common_params) |p| { qemu_params.append(p) catch unreachable; qemu_debug_params.append(p) catch unreachable; } for (debug_params) |p| { qemu_debug_params.append(p) catch unreachable; } const run_qemu = b.addCommand(".", b.env_map, qemu_params.toSlice()); const run_qemu_debug = b.addCommand(".", b.env_map, qemu_debug_params.toSlice()); run_qemu.step.dependOn(b.default_step); run_qemu_debug.step.dependOn(b.default_step); qemu.dependOn(&run_qemu.step); qemu_debug.dependOn(&run_qemu_debug.step); } fn buildKernel(b: &Builder) []const u8 { const kernel = b.addExecutable("zen", "kernel/kmain.zig"); kernel.setBuildMode(b.standardReleaseOptions()); kernel.setOutputPath("zen"); kernel.addAssemblyFile("kernel/_start.s"); kernel.addAssemblyFile("kernel/gdt.s"); kernel.addAssemblyFile("kernel/isr.s"); kernel.addAssemblyFile("kernel/vmem.s"); kernel.setTarget(builtin.Arch.i386, builtin.Os.freestanding, builtin.Environ.gnu); kernel.setLinkerScriptPath("kernel/linker.ld"); b.default_step.dependOn(&kernel.step); return kernel.getOutputPath(); } fn buildServer(b: &Builder, comptime name: []const u8) []const u8 { const server = b.addExecutable(name, "servers/" ++ name ++ "/main.zig"); server.setOutputPath("servers/" ++ name ++ "/" ++ name); server.setTarget(builtin.Arch.i386, builtin.Os.zen, builtin.Environ.gnu); b.default_step.dependOn(&server.step); return server.getOutputPath(); }
build.zig
const std = @import("std"); const builtin = @import("builtin"); const lola = @import("../main.zig"); const whitespace = [_]u8{ 0x09, // horizontal tab 0x0A, // line feed 0x0B, // vertical tab 0x0C, // form feed 0x0D, // carriage return 0x20, // space }; const root = @import("root"); const milliTimestamp = if (builtin.os.tag == .freestanding) if (@hasDecl(root, "milliTimestamp")) root.milliTimestamp else @compileError("Please provide milliTimestamp in the root file for freestanding targets!") else std.time.milliTimestamp; /// empty compile unit for testing purposes const empty_compile_unit = lola.CompileUnit{ .arena = std.heap.ArenaAllocator.init(std.testing.failing_allocator), .comment = "empty compile unit", .globalCount = 0, .temporaryCount = 0, .code = "", .functions = &[0]lola.CompileUnit.Function{}, .debugSymbols = &[0]lola.CompileUnit.DebugSymbol{}, }; test "stdlib.install" { var pool = lola.runtime.ObjectPool([_]type{}).init(std.testing.allocator); defer pool.deinit(); var env = try lola.runtime.Environment.init(std.testing.allocator, &empty_compile_unit, pool.interface()); defer env.deinit(); // TODO: Reinsert this try env.installModule(@This(), lola.runtime.Context.null_pointer); } pub fn Sleep(env: *lola.runtime.Environment, call_context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.AsyncFunctionCall { _ = call_context; if (args.len != 1) return error.InvalidArgs; const seconds = try args[0].toNumber(); const Context = struct { allocator: std.mem.Allocator, end_time: f64, }; const ptr = try env.allocator.create(Context); ptr.* = Context{ .allocator = env.allocator, .end_time = @intToFloat(f64, milliTimestamp()) + 1000.0 * seconds, }; return lola.runtime.AsyncFunctionCall{ .context = lola.runtime.Context.make(*Context, ptr), .destructor = struct { fn dtor(exec_context: lola.runtime.Context) void { const ctx = exec_context.cast(*Context); ctx.allocator.destroy(ctx); } }.dtor, .execute = struct { fn execute(exec_context: lola.runtime.Context) anyerror!?lola.runtime.Value { const ctx = exec_context.cast(*Context); if (ctx.end_time < @intToFloat(f64, milliTimestamp())) { return .void; } else { return null; } } }.execute, }; } pub fn Yield(env: *lola.runtime.Environment, call_context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.AsyncFunctionCall { _ = call_context; if (args.len != 0) return error.InvalidArgs; const Context = struct { allocator: std.mem.Allocator, end: bool, }; const ptr = try env.allocator.create(Context); ptr.* = Context{ .allocator = env.allocator, .end = false, }; return lola.runtime.AsyncFunctionCall{ .context = lola.runtime.Context.make(*Context, ptr), .destructor = struct { fn dtor(exec_context: lola.runtime.Context) void { const ctx = exec_context.cast(*Context); ctx.allocator.destroy(ctx); } }.dtor, .execute = struct { fn execute(exec_context: lola.runtime.Context) anyerror!?lola.runtime.Value { const ctx = exec_context.cast(*Context); if (ctx.end) { return .void; } else { ctx.end = true; return null; } } }.execute, }; } pub fn Length(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return switch (args[0]) { .string => |str| lola.runtime.Value.initNumber(@intToFloat(f64, str.contents.len)), .array => |arr| lola.runtime.Value.initNumber(@intToFloat(f64, arr.contents.len)), else => error.TypeMismatch, }; } pub fn SubString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 2 or args.len > 3) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; if (args[1] != .number) return error.TypeMismatch; if (args.len == 3 and args[2] != .number) return error.TypeMismatch; const str = args[0].string; const start = try args[1].toInteger(usize); if (start >= str.contents.len) return lola.runtime.Value.initString(env.allocator, ""); const sliced = if (args.len == 3) str.contents[start..][0..std.math.min(str.contents.len - start, try args[2].toInteger(usize))] else str.contents[start..]; return try lola.runtime.Value.initString(env.allocator, sliced); } pub fn Trim(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( env.allocator, std.mem.trim(u8, str.contents, &whitespace), ); } pub fn TrimLeft(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( env.allocator, std.mem.trimLeft(u8, str.contents, &whitespace), ); } pub fn TrimRight(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( env.allocator, std.mem.trimRight(u8, str.contents, &whitespace), ); } pub fn IndexOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 2) return error.InvalidArgs; if (args[0] == .string) { if (args[1] != .string) return error.TypeMismatch; const haystack = args[0].string.contents; const needle = args[1].string.contents; return if (std.mem.indexOf(u8, haystack, needle)) |index| lola.runtime.Value.initNumber(@intToFloat(f64, index)) else .void; } else if (args[0] == .array) { const haystack = args[0].array.contents; for (haystack) |val, i| { if (val.eql(args[1])) return lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return .void; } else { return error.TypeMismatch; } } pub fn LastIndexOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 2) return error.InvalidArgs; if (args[0] == .string) { if (args[1] != .string) return error.TypeMismatch; const haystack = args[0].string.contents; const needle = args[1].string.contents; return if (std.mem.lastIndexOf(u8, haystack, needle)) |index| lola.runtime.Value.initNumber(@intToFloat(f64, index)) else .void; } else if (args[0] == .array) { const haystack = args[0].array.contents; var i: usize = haystack.len; while (i > 0) { i -= 1; if (haystack[i].eql(args[1])) return lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return .void; } else { return error.TypeMismatch; } } pub fn Byte(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const value = args[0].string.contents; if (value.len > 0) return lola.runtime.Value.initNumber(@intToFloat(f64, value[0])) else return .void; } pub fn Chr(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; const val = try args[0].toInteger(u8); return try lola.runtime.Value.initString( env.allocator, &[_]u8{val}, ); } pub fn NumToString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 1 or args.len > 2) return error.InvalidArgs; var buffer: [256]u8 = undefined; const slice = if (args.len == 2) blk: { const base = try args[1].toInteger(u8); const val = try args[0].toInteger(isize); const len = std.fmt.formatIntBuf(&buffer, val, base, .upper, std.fmt.FormatOptions{}); break :blk buffer[0..len]; } else blk: { var stream = std.io.fixedBufferStream(&buffer); const val = try args[0].toNumber(); try std.fmt.formatFloatDecimal(val, .{}, stream.writer()); break :blk stream.getWritten(); }; return try lola.runtime.Value.initString(env.allocator, slice); } pub fn StringToNum(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len < 1 or args.len > 2) return error.InvalidArgs; const str = try args[0].toString(); if (args.len == 2) { const base = try args[1].toInteger(u8); const text = if (base == 16) blk: { var tmp = str; if (std.mem.startsWith(u8, tmp, "0x")) tmp = tmp[2..]; if (std.mem.endsWith(u8, tmp, "h")) tmp = tmp[0 .. tmp.len - 1]; break :blk tmp; } else str; const val = try std.fmt.parseInt(isize, text, base); // return .void; return lola.runtime.Value.initNumber(@intToFloat(f64, val)); } else { const val = std.fmt.parseFloat(f64, str) catch return .void; return lola.runtime.Value.initNumber(val); } } pub fn Split(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 2 or args.len > 3) return error.InvalidArgs; const input = try args[0].toString(); const separator = try args[1].toString(); const removeEmpty = if (args.len == 3) try args[2].toBoolean() else false; var items = std.ArrayList(lola.runtime.Value).init(env.allocator); defer { for (items.items) |*i| { i.deinit(); } items.deinit(); } var iter = std.mem.split(u8, input, separator); while (iter.next()) |slice| { if (!removeEmpty or slice.len > 0) { var val = try lola.runtime.Value.initString(env.allocator, slice); errdefer val.deinit(); try items.append(val); } } return lola.runtime.Value.fromArray(lola.runtime.Array{ .allocator = env.allocator, .contents = items.toOwnedSlice(), }); } pub fn Join(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 1 or args.len > 2) return error.InvalidArgs; const array = try args[0].toArray(); const separator = if (args.len == 2) try args[1].toString() else ""; for (array.contents) |item| { if (item != .string) return error.TypeMismatch; } var result = std.ArrayList(u8).init(env.allocator); defer result.deinit(); for (array.contents) |item, i| { if (i > 0) { try result.appendSlice(separator); } try result.appendSlice(try item.toString()); } return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned( env.allocator, result.toOwnedSlice(), )); } pub fn Array(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 1 or args.len > 2) return error.InvalidArgs; const length = try args[0].toInteger(usize); const init_val = if (args.len > 1) args[1] else .void; var arr = try lola.runtime.Array.init(env.allocator, length); for (arr.contents) |*item| { item.* = try init_val.clone(); } return lola.runtime.Value.fromArray(arr); } pub fn Range(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len < 1 or args.len > 2) return error.InvalidArgs; if (args.len == 2) { const start = try args[0].toInteger(usize); const length = try args[1].toInteger(usize); var arr = try lola.runtime.Array.init(env.allocator, length); for (arr.contents) |*item, i| { item.* = lola.runtime.Value.initNumber(@intToFloat(f64, start + i)); } return lola.runtime.Value.fromArray(arr); } else { const length = try args[0].toInteger(usize); var arr = try lola.runtime.Array.init(env.allocator, length); for (arr.contents) |*item, i| { item.* = lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return lola.runtime.Value.fromArray(arr); } } pub fn Slice(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 3) return error.InvalidArgs; const array = try args[0].toArray(); const start = try args[1].toInteger(usize); const length = try args[2].toInteger(usize); // Out of bounds if (start >= array.contents.len) return lola.runtime.Value.fromArray(try lola.runtime.Array.init(env.allocator, 0)); const actual_length = std.math.min(length, array.contents.len - start); var arr = try lola.runtime.Array.init(env.allocator, actual_length); errdefer arr.deinit(); for (arr.contents) |*item, i| { item.* = try array.contents[start + i].clone(); } return lola.runtime.Value.fromArray(arr); } pub fn DeltaEqual(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 3) return error.InvalidArgs; const a = try args[0].toNumber(); const b = try args[1].toNumber(); const delta = try args[2].toNumber(); return lola.runtime.Value.initBoolean(@fabs(a - b) < delta); } pub fn Floor(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@floor(try args[0].toNumber())); } pub fn Ceiling(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@ceil(try args[0].toNumber())); } pub fn Round(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@round(try args[0].toNumber())); } pub fn Sin(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@sin(try args[0].toNumber())); } pub fn Cos(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@cos(try args[0].toNumber())); } pub fn Tan(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@tan(try args[0].toNumber())); } pub fn Atan(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len == 1) { return lola.runtime.Value.initNumber( std.math.atan(try args[0].toNumber()), ); } else if (args.len == 2) { return lola.runtime.Value.initNumber(std.math.atan2( f64, try args[0].toNumber(), try args[1].toNumber(), )); } else { return error.InvalidArgs; } } pub fn Sqrt(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.sqrt(try args[0].toNumber())); } pub fn Pow(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 2) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.pow( f64, try args[0].toNumber(), try args[1].toNumber(), )); } pub fn Log(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len == 1) { return lola.runtime.Value.initNumber( std.math.log10(try args[0].toNumber()), ); } else if (args.len == 2) { return lola.runtime.Value.initNumber(std.math.log( f64, try args[1].toNumber(), try args[0].toNumber(), )); } else { return error.InvalidArgs; } } pub fn Exp(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(@exp(try args[0].toNumber())); } pub fn Timestamp(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = env; _ = context; if (args.len != 0) return error.InvalidArgs; return lola.runtime.Value.initNumber(@intToFloat(f64, milliTimestamp()) / 1000.0); } pub fn TypeOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initString(env.allocator, switch (args[0]) { .void => "void", .boolean => "boolean", .string => "string", .number => "number", .object => "object", .array => "array", .enumerator => "enumerator", }); } pub fn ToString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; var str = try std.fmt.allocPrint(env.allocator, "{}", .{args[0]}); return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned(env.allocator, str)); } pub fn HasFunction(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; switch (args.len) { 1 => { var name = try args[0].toString(); return lola.runtime.Value.initBoolean(env.functions.get(name) != null); }, 2 => { var obj = try args[0].toObject(); var name = try args[1].toString(); const maybe_method = try env.objectPool.getMethod(obj, name); return lola.runtime.Value.initBoolean(maybe_method != null); }, else => return error.InvalidArgs, } } pub fn Serialize(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; const value = args[0]; var string_buffer = std.ArrayList(u8).init(env.allocator); defer string_buffer.deinit(); try value.serialize(string_buffer.writer()); return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned(env.allocator, string_buffer.toOwnedSlice())); } pub fn Deserialize(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; if (args.len != 1) return error.InvalidArgs; const serialized_string = try args[0].toString(); var stream = std.io.fixedBufferStream(serialized_string); return try lola.runtime.Value.deserialize(stream.reader(), env.allocator); } pub fn Random(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; _ = env; var lower: f64 = 0; var upper: f64 = 1; switch (args.len) { 0 => {}, 1 => upper = try args[0].toNumber(), 2 => { lower = try args[0].toNumber(); upper = try args[1].toNumber(); }, else => return error.InvalidArgs, } var result: f64 = undefined; { random_mutex.lock(); defer random_mutex.unlock(); if (random == null) { random = std.rand.DefaultPrng.init(@bitCast(u64, @intToFloat(f64, milliTimestamp()))); } result = lower + (upper - lower) * random.?.random().float(f64); } return lola.runtime.Value.initNumber(result); } pub fn RandomInt(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { _ = context; _ = env; var lower: i32 = 0; var upper: i32 = std.math.maxInt(i32); switch (args.len) { 0 => {}, 1 => upper = try args[0].toInteger(i32), 2 => { lower = try args[0].toInteger(i32); upper = try args[1].toInteger(i32); }, else => return error.InvalidArgs, } var result: i32 = undefined; { random_mutex.lock(); defer random_mutex.unlock(); if (random == null) { random = std.rand.DefaultPrng.init(@bitCast(u64, @intToFloat(f64, milliTimestamp()))); } result = random.?.random().intRangeLessThan(i32, lower, upper); } return lola.runtime.Value.initInteger(i32, result); } var random_mutex = std.Thread.Mutex{}; var random: ?std.rand.DefaultPrng = null;
src/library/libraries/stdlib.zig
const std = @import("std"); const aarch64 = @import("../../../codegen/aarch64.zig"); const assert = std.debug.assert; const log = std.log.scoped(.reloc); const macho = std.macho; const math = std.math; const mem = std.mem; const meta = std.meta; const reloc = @import("../reloc.zig"); const Allocator = mem.Allocator; const Relocation = reloc.Relocation; pub const Branch = struct { base: Relocation, /// Always .UnconditionalBranchImmediate inst: aarch64.Instruction, pub const base_type: Relocation.Type = .branch_aarch64; pub fn resolve(branch: Branch, args: Relocation.ResolveArgs) !void { const displacement = try math.cast(i28, @intCast(i64, args.target_addr) - @intCast(i64, args.source_addr)); log.debug(" | displacement 0x{x}", .{displacement}); var inst = branch.inst; inst.unconditional_branch_immediate.imm26 = @truncate(u26, @bitCast(u28, displacement) >> 2); mem.writeIntLittle(u32, branch.base.code[0..4], inst.toU32()); } }; pub const Page = struct { base: Relocation, addend: ?u32 = null, /// Always .PCRelativeAddress inst: aarch64.Instruction, pub const base_type: Relocation.Type = .page; pub fn resolve(page: Page, args: Relocation.ResolveArgs) !void { const target_addr = if (page.addend) |addend| args.target_addr + addend else args.target_addr; const source_page = @intCast(i32, args.source_addr >> 12); const target_page = @intCast(i32, target_addr >> 12); const pages = @bitCast(u21, @intCast(i21, target_page - source_page)); log.debug(" | calculated addend 0x{x}", .{page.addend}); log.debug(" | moving by {} pages", .{pages}); var inst = page.inst; inst.pc_relative_address.immhi = @truncate(u19, pages >> 2); inst.pc_relative_address.immlo = @truncate(u2, pages); mem.writeIntLittle(u32, page.base.code[0..4], inst.toU32()); } }; pub const PageOff = struct { base: Relocation, addend: ?u32 = null, op_kind: OpKind, inst: aarch64.Instruction, pub const base_type: Relocation.Type = .page_off; pub const OpKind = enum { arithmetic, load_store, }; pub fn resolve(page_off: PageOff, args: Relocation.ResolveArgs) !void { const target_addr = if (page_off.addend) |addend| args.target_addr + addend else args.target_addr; const narrowed = @truncate(u12, target_addr); log.debug(" | narrowed address within the page 0x{x}", .{narrowed}); log.debug(" | {s} opcode", .{page_off.op_kind}); var inst = page_off.inst; if (page_off.op_kind == .arithmetic) { inst.add_subtract_immediate.imm12 = narrowed; } else { const offset: u12 = blk: { if (inst.load_store_register.size == 0) { if (inst.load_store_register.v == 1) { // 128-bit SIMD is scaled by 16. break :blk try math.divExact(u12, narrowed, 16); } // Otherwise, 8-bit SIMD or ldrb. break :blk narrowed; } else { const denom: u4 = try math.powi(u4, 2, inst.load_store_register.size); break :blk try math.divExact(u12, narrowed, denom); } }; inst.load_store_register.offset = offset; } mem.writeIntLittle(u32, page_off.base.code[0..4], inst.toU32()); } }; pub const GotPage = struct { base: Relocation, /// Always .PCRelativeAddress inst: aarch64.Instruction, pub const base_type: Relocation.Type = .got_page; pub fn resolve(page: GotPage, args: Relocation.ResolveArgs) !void { const source_page = @intCast(i32, args.source_addr >> 12); const target_page = @intCast(i32, args.target_addr >> 12); const pages = @bitCast(u21, @intCast(i21, target_page - source_page)); log.debug(" | moving by {} pages", .{pages}); var inst = page.inst; inst.pc_relative_address.immhi = @truncate(u19, pages >> 2); inst.pc_relative_address.immlo = @truncate(u2, pages); mem.writeIntLittle(u32, page.base.code[0..4], inst.toU32()); } }; pub const GotPageOff = struct { base: Relocation, /// Always .LoadStoreRegister with size = 3 for GOT indirection inst: aarch64.Instruction, pub const base_type: Relocation.Type = .got_page_off; pub fn resolve(page_off: GotPageOff, args: Relocation.ResolveArgs) !void { const narrowed = @truncate(u12, args.target_addr); log.debug(" | narrowed address within the page 0x{x}", .{narrowed}); var inst = page_off.inst; const offset = try math.divExact(u12, narrowed, 8); inst.load_store_register.offset = offset; mem.writeIntLittle(u32, page_off.base.code[0..4], inst.toU32()); } }; pub const TlvpPage = struct { base: Relocation, /// Always .PCRelativeAddress inst: aarch64.Instruction, pub const base_type: Relocation.Type = .tlvp_page; pub fn resolve(page: TlvpPage, args: Relocation.ResolveArgs) !void { const source_page = @intCast(i32, args.source_addr >> 12); const target_page = @intCast(i32, args.target_addr >> 12); const pages = @bitCast(u21, @intCast(i21, target_page - source_page)); log.debug(" | moving by {} pages", .{pages}); var inst = page.inst; inst.pc_relative_address.immhi = @truncate(u19, pages >> 2); inst.pc_relative_address.immlo = @truncate(u2, pages); mem.writeIntLittle(u32, page.base.code[0..4], inst.toU32()); } }; pub const TlvpPageOff = struct { base: Relocation, /// Always .AddSubtractImmediate regardless of the source instruction. /// This means, we always rewrite the instruction to add even if the /// source instruction was an ldr. inst: aarch64.Instruction, pub const base_type: Relocation.Type = .tlvp_page_off; pub fn resolve(page_off: TlvpPageOff, args: Relocation.ResolveArgs) !void { const narrowed = @truncate(u12, args.target_addr); log.debug(" | narrowed address within the page 0x{x}", .{narrowed}); var inst = page_off.inst; inst.add_subtract_immediate.imm12 = narrowed; mem.writeIntLittle(u32, page_off.base.code[0..4], inst.toU32()); } }; pub const Parser = struct { allocator: *Allocator, it: *reloc.RelocIterator, code: []u8, parsed: std.ArrayList(*Relocation), addend: ?u32 = null, subtractor: ?Relocation.Target = null, pub fn deinit(parser: *Parser) void { parser.parsed.deinit(); } pub fn parse(parser: *Parser) !void { while (parser.it.next()) |rel| { switch (@intToEnum(macho.reloc_type_arm64, rel.r_type)) { .ARM64_RELOC_BRANCH26 => { try parser.parseBranch(rel); }, .ARM64_RELOC_SUBTRACTOR => { try parser.parseSubtractor(rel); }, .ARM64_RELOC_UNSIGNED => { try parser.parseUnsigned(rel); }, .ARM64_RELOC_ADDEND => { try parser.parseAddend(rel); }, .ARM64_RELOC_PAGE21, .ARM64_RELOC_GOT_LOAD_PAGE21, .ARM64_RELOC_TLVP_LOAD_PAGE21, => { try parser.parsePage(rel); }, .ARM64_RELOC_PAGEOFF12 => { try parser.parsePageOff(rel); }, .ARM64_RELOC_GOT_LOAD_PAGEOFF12 => { try parser.parseGotLoadPageOff(rel); }, .ARM64_RELOC_TLVP_LOAD_PAGEOFF12 => { try parser.parseTlvpLoadPageOff(rel); }, .ARM64_RELOC_POINTER_TO_GOT => { return error.ToDoRelocPointerToGot; }, } } } fn parseAddend(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_ADDEND); assert(rel.r_pcrel == 0); assert(rel.r_extern == 0); assert(parser.addend == null); parser.addend = rel.r_symbolnum; // Verify ADDEND is followed by a load. const next = @intToEnum(macho.reloc_type_arm64, parser.it.peek().r_type); switch (next) { .ARM64_RELOC_PAGE21, .ARM64_RELOC_PAGEOFF12 => {}, else => { log.err("unexpected relocation type: expected PAGE21 or PAGEOFF12, found {s}", .{next}); return error.UnexpectedRelocationType; }, } } fn parseBranch(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_BRANCH26); assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const parsed_inst = aarch64.Instruction{ .unconditional_branch_immediate = mem.bytesToValue( meta.TagPayload( aarch64.Instruction, aarch64.Instruction.unconditional_branch_immediate, ), inst, ) }; var branch = try parser.allocator.create(Branch); errdefer parser.allocator.destroy(branch); const target = Relocation.Target.from_reloc(rel); branch.* = .{ .base = .{ .@"type" = .branch_aarch64, .code = inst, .offset = offset, .target = target, }, .inst = parsed_inst, }; log.debug(" | emitting {}", .{branch}); try parser.parsed.append(&branch.base); } fn parsePage(parser: *Parser, rel: macho.relocation_info) !void { assert(rel.r_pcrel == 1); assert(rel.r_length == 2); const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); const target = Relocation.Target.from_reloc(rel); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const parsed_inst = aarch64.Instruction{ .pc_relative_address = mem.bytesToValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.pc_relative_address, ), inst) }; const ptr: *Relocation = ptr: { switch (rel_type) { .ARM64_RELOC_PAGE21 => { defer { // Reset parser's addend state parser.addend = null; } var page = try parser.allocator.create(Page); errdefer parser.allocator.destroy(page); page.* = .{ .base = .{ .@"type" = .page, .code = inst, .offset = offset, .target = target, }, .addend = parser.addend, .inst = parsed_inst, }; log.debug(" | emitting {}", .{page}); break :ptr &page.base; }, .ARM64_RELOC_GOT_LOAD_PAGE21 => { var page = try parser.allocator.create(GotPage); errdefer parser.allocator.destroy(page); page.* = .{ .base = .{ .@"type" = .got_page, .code = inst, .offset = offset, .target = target, }, .inst = parsed_inst, }; log.debug(" | emitting {}", .{page}); break :ptr &page.base; }, .ARM64_RELOC_TLVP_LOAD_PAGE21 => { var page = try parser.allocator.create(TlvpPage); errdefer parser.allocator.destroy(page); page.* = .{ .base = .{ .@"type" = .tlvp_page, .code = inst, .offset = offset, .target = target, }, .inst = parsed_inst, }; log.debug(" | emitting {}", .{page}); break :ptr &page.base; }, else => unreachable, } }; try parser.parsed.append(ptr); } fn parsePageOff(parser: *Parser, rel: macho.relocation_info) !void { defer { // Reset parser's addend state parser.addend = null; } const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_PAGEOFF12); assert(rel.r_pcrel == 0); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; var op_kind: PageOff.OpKind = undefined; var parsed_inst: aarch64.Instruction = undefined; if (isArithmeticOp(inst)) { op_kind = .arithmetic; parsed_inst = .{ .add_subtract_immediate = mem.bytesToValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.add_subtract_immediate, ), inst) }; } else { op_kind = .load_store; parsed_inst = .{ .load_store_register = mem.bytesToValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.load_store_register, ), inst) }; } const target = Relocation.Target.from_reloc(rel); var page_off = try parser.allocator.create(PageOff); errdefer parser.allocator.destroy(page_off); page_off.* = .{ .base = .{ .@"type" = .page_off, .code = inst, .offset = offset, .target = target, }, .op_kind = op_kind, .inst = parsed_inst, .addend = parser.addend, }; log.debug(" | emitting {}", .{page_off}); try parser.parsed.append(&page_off.base); } fn parseGotLoadPageOff(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_GOT_LOAD_PAGEOFF12); assert(rel.r_pcrel == 0); assert(rel.r_length == 2); const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; assert(!isArithmeticOp(inst)); const parsed_inst = mem.bytesToValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.load_store_register, ), inst); assert(parsed_inst.size == 3); const target = Relocation.Target.from_reloc(rel); var page_off = try parser.allocator.create(GotPageOff); errdefer parser.allocator.destroy(page_off); page_off.* = .{ .base = .{ .@"type" = .got_page_off, .code = inst, .offset = offset, .target = target, }, .inst = .{ .load_store_register = parsed_inst, }, }; log.debug(" | emitting {}", .{page_off}); try parser.parsed.append(&page_off.base); } fn parseTlvpLoadPageOff(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_TLVP_LOAD_PAGEOFF12); assert(rel.r_pcrel == 0); assert(rel.r_length == 2); const RegInfo = struct { rd: u5, rn: u5, size: u1, }; const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; const parsed: RegInfo = parsed: { if (isArithmeticOp(inst)) { const parsed_inst = mem.bytesAsValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.add_subtract_immediate, ), inst); break :parsed .{ .rd = parsed_inst.rd, .rn = parsed_inst.rn, .size = parsed_inst.sf, }; } else { const parsed_inst = mem.bytesAsValue(meta.TagPayload( aarch64.Instruction, aarch64.Instruction.load_store_register, ), inst); break :parsed .{ .rd = parsed_inst.rt, .rn = parsed_inst.rn, .size = @truncate(u1, parsed_inst.size), }; } }; const target = Relocation.Target.from_reloc(rel); var page_off = try parser.allocator.create(TlvpPageOff); errdefer parser.allocator.destroy(page_off); page_off.* = .{ .base = .{ .@"type" = .tlvp_page_off, .code = inst, .offset = offset, .target = target, }, .inst = .{ .add_subtract_immediate = .{ .rd = parsed.rd, .rn = parsed.rn, .imm12 = 0, // This will be filled when target addresses are known. .sh = 0, .s = 0, .op = 0, .sf = parsed.size, }, }, }; log.debug(" | emitting {}", .{page_off}); try parser.parsed.append(&page_off.base); } fn parseSubtractor(parser: *Parser, rel: macho.relocation_info) !void { const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_SUBTRACTOR); assert(rel.r_pcrel == 0); assert(parser.subtractor == null); parser.subtractor = Relocation.Target.from_reloc(rel); // Verify SUBTRACTOR is followed by UNSIGNED. const next = @intToEnum(macho.reloc_type_arm64, parser.it.peek().r_type); if (next != .ARM64_RELOC_UNSIGNED) { log.err("unexpected relocation type: expected UNSIGNED, found {s}", .{next}); return error.UnexpectedRelocationType; } } fn parseUnsigned(parser: *Parser, rel: macho.relocation_info) !void { defer { // Reset parser's subtractor state parser.subtractor = null; } const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); assert(rel_type == .ARM64_RELOC_UNSIGNED); assert(rel.r_pcrel == 0); var unsigned = try parser.allocator.create(reloc.Unsigned); errdefer parser.allocator.destroy(unsigned); const target = Relocation.Target.from_reloc(rel); const is_64bit: bool = switch (rel.r_length) { 3 => true, 2 => false, else => unreachable, }; const offset = @intCast(u32, rel.r_address); const addend: i64 = if (is_64bit) mem.readIntLittle(i64, parser.code[offset..][0..8]) else mem.readIntLittle(i32, parser.code[offset..][0..4]); unsigned.* = .{ .base = .{ .@"type" = .unsigned, .code = if (is_64bit) parser.code[offset..][0..8] else parser.code[offset..][0..4], .offset = offset, .target = target, }, .subtractor = parser.subtractor, .is_64bit = is_64bit, .addend = addend, }; log.debug(" | emitting {}", .{unsigned}); try parser.parsed.append(&unsigned.base); } }; fn isArithmeticOp(inst: *const [4]u8) callconv(.Inline) bool { const group_decode = @truncate(u5, inst[3]); return ((group_decode >> 2) == 4); }
src/link/MachO/reloc/aarch64.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const os = std.os; const linux = os.linux; const IO_Uring = linux.IO_Uring; const log = std.log.scoped(.server); pub fn main() anyerror!void { std.log.info("All your codebase are belong to us.", .{}); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer if (@import("builtin").mode == .Debug) { std.debug.assert(!gpa.deinit()); }; var server = try Server.init(gpa.allocator(), 512, 0); try server.listen(try std.net.Address.parseIp("0.0.0.0", 8080)); try server.run(); } const Ring = struct { io: IO_Uring, first: ?*Completion = null, last: ?*Completion = null, /// Represents a completed event const Completion = struct { /// Result, context dependent and should always /// be verified by checking errNo() result: i32 = undefined, /// The next completion in line next: ?*Completion = null, /// The operation that was/is queued op: Op, /// Erased pointer to a context type context: ?*anyopaque, /// The callback to call upon completion callback: fn (completion: *Completion, result: anyerror!i32) void, fn from_addr(ptr: u64) *Completion { return @intToPtr(*Completion, ptr); } fn as_addr(self: *Completion) u64 { return @ptrToInt(self); } fn get_context(self: *Completion, comptime T: type) T { return @ptrCast(T, @alignCast(@alignOf(T), self.context)); } }; /// Defines an operator to be queued/completed. /// The max size of each tag is 28 bytes /// /// TODO: See if we can somehow lower those 28 bytes const Op = union(enum) { accept: struct { socket: i32, address: linux.sockaddr, address_len: linux.socklen_t, flags: u32, }, recv: struct { socket: i32, buffer: []u8, flags: u32, }, send: struct { socket: i32, buffer: []const u8, flags: u32, }, }; /// Ensures we get a new queue submission, /// by flushing the completion queue and submitting all current /// submittions when we failed to get a free submittion entry. fn get_sqe(self: *Ring) !*linux.io_uring_sqe { while (true) { return self.io.get_sqe() catch { try self.flush(); _ = try self.io.submit(); continue; }; } } /// Copies all completed queue entries and appends /// each `Completion` to the intrusive linked list, allowing us /// to trigger those first when polling, rather than asking the /// kernel for more completions. fn flush(self: *Ring) !void { var queue: [256]linux.io_uring_cqe = undefined; while (true) { const found = try self.io.copy_cqes(&queue, 0); if (found == 0) { return; // no completions } // For each completed entry, add them to our linked-list for (queue[0..found]) |cqe| { const completed = Completion.from_addr(cqe.user_data); completed.result = cqe.res; if (self.first == null) { self.first = completed; } if (self.last) |last| { last.next = completed; } completed.next = null; self.last = completed; } } } fn submit(self: *Ring, completion: *Completion) !void { const sqe = try self.get_sqe(); switch (completion.op) { .accept => |*op| linux.io_uring_prep_accept( sqe, op.socket, &op.address, &op.address_len, op.flags, ), .recv => |op| linux.io_uring_prep_recv( sqe, op.socket, op.buffer, op.flags, ), .send => |op| linux.io_uring_prep_send( sqe, op.socket, op.buffer, op.flags, ), } sqe.user_data = completion.as_addr(); } fn err(maybe_err_no: i32) linux.E { return if (maybe_err_no > -4096 and maybe_err_no < 0) @intToEnum(linux.E, -maybe_err_no) else .SUCCESS; } fn complete(self: *Ring, completion: *Ring.Completion) !void { switch (completion.op) { .accept => { const result = switch (err(completion.result)) { .SUCCESS => completion.result, .INTR, .AGAIN => { try self.submit(completion); return; }, else => |err_no| return os.unexpectedErrno(err_no), }; completion.callback(completion, result); }, .recv => { const result = switch (err(completion.result)) { .SUCCESS => completion.result, .INTR => { try self.submit(completion); return; }, .CONNRESET => error.PeerResetConnection, else => |err_no| return os.unexpectedErrno(err_no), }; completion.callback(completion, result); }, .send => { const result = switch (err(completion.result)) { .SUCCESS => completion.result, .INTR => { try self.submit(completion); return; }, .CONNRESET => error.PeerResetConnection, .PIPE => error.BrokenPipe, else => |err_no| return os.unexpectedErrno(err_no), }; completion.callback(completion, result); }, } } /// For all completed entries, calls its callback. /// Then, submits all entries and waits until at least 1 entry has been submitted. /// Finally, copies all completed entries (if any) and stores them in a linked list for later /// consumptions. fn tick(self: *Ring) !void { while (self.first) |completion| { self.first = completion.next; if (self.first == null) { self.last = null; } try self.complete(completion); } _ = try self.io.submit_and_wait(1); try self.flush(); } }; const Server = struct { clients: [128]Client, free_client_slots: std.ArrayListUnmanaged(u7) = .{}, gpa: Allocator, ring: Ring, socket: os.socket_t, completion: Ring.Completion, /// Initializes a new `Server` instance as well as an `IO_Uring` instance. /// `entries` must be a power of two, between 1 and 4049. pub fn init(gpa: Allocator, entries: u13, flags: u32) !Server { return Server{ .ring = .{ .io = try os.linux.IO_Uring.init(entries, flags) }, .clients = undefined, .gpa = gpa, .socket = undefined, .completion = undefined, }; } fn setup_free_slots(self: *Server) void { for (self.clients) |_, index| { self.free_client_slots.appendAssumeCapacity(@intCast(u7, index)); } } fn stop(self: *Server) void { _ = self; @panic("TODO"); } /// Appends a new submission to accept a new client connection fn accept(self: *Server) !void { const accept_callback = struct { fn callback(completion: *Ring.Completion, result: anyerror!i32) void { _ = result catch {}; const server = completion.get_context(*Server); defer server.accept() catch |err| { log.err("Unexpected error: {s}, shutting down", .{@errorName(err)}); server.stop(); }; const socket = completion.result; const index = server.free_client_slots.pop(); Client.init(&server.clients[index], index, socket, &server.ring) catch |err| { log.warn("Failed to initialize client: {s}", .{@errorName(err)}); os.close(socket); server.free_client_slots.appendAssumeCapacity(index); return; }; } }.callback; self.completion = .{ .context = self, .callback = accept_callback, .op = .{ .accept = .{ .socket = self.socket, .address = undefined, .address_len = @sizeOf(linux.sockaddr), .flags = os.SOCK.NONBLOCK | os.SOCK.CLOEXEC, }, }, }; try self.ring.submit(&self.completion); } /// Creates a new socket for the server to listen on, binds it to the given /// `address` and finally starts listening to new connections. pub fn listen(self: *Server, address: std.net.Address) !void { self.socket = try os.socket( os.AF.INET, os.SOCK.STREAM | os.SOCK.NONBLOCK | os.SOCK.CLOEXEC, os.IPPROTO.TCP, ); errdefer os.close(self.socket); try os.setsockopt( self.socket, os.SOL.SOCKET, os.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)), ); const socklen = address.getOsSockLen(); try os.bind(self.socket, &address.any, socklen); try os.listen(self.socket, 128); } /// Starts accepting new connections and initializes /// new clients for those, to read requests and send responses. pub fn run(self: *Server) !void { try self.free_client_slots.ensureTotalCapacity(self.gpa, 128); defer self.free_client_slots.deinit(self.gpa); self.setup_free_slots(); try self.accept(); while (true) { try self.ring.tick(); } } }; const Client = struct { /// Client ID assigned by the server, /// It is not safe to store this information as new connections /// may be assigned this ID when this Client has disconnected. index: u7, /// The file descriptor of this Client connection. socket: i32, /// Pointer to the io-uring object, allowing us to queue /// submissions to perform syscalls such as reads and writes. ring: *Ring, /// Frame of the client frame: @Frame(run), pub fn init(self: *Client, index: u7, socket: i32, ring: *Ring) !void { try std.os.setsockopt(socket, 6, os.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1))); self.index = index; self.socket = socket; self.ring = ring; self.frame = async self.run(); } fn run(self: *Client) !void { while (true) { var buf: [4096]u8 = undefined; try self.recv(&buf); try self.send(HTTP_RESPONSE); } } fn recv(self: *Client, buffer: []u8) !void { var completion: Ring.Completion = .{ .context = @frame(), .callback = recv_callback, .op = .{ .recv = .{ .buffer = buffer, .socket = self.socket, .flags = os.linux.SOCK.CLOEXEC | os.linux.SOCK.NONBLOCK, } }, }; suspend try self.ring.submit(&completion); } fn recv_callback(completion: *Ring.Completion, result: anyerror!i32) void { resume completion.get_context(anyframe); _ = result catch return; } fn send(self: *Client, buffer: []const u8) !void { var completion: Ring.Completion = .{ .context = @frame(), .callback = send_callback, .op = .{ .send = .{ .buffer = buffer, .socket = self.socket, .flags = os.linux.SOCK.CLOEXEC | os.linux.SOCK.NONBLOCK, }, }, }; suspend try self.ring.submit(&completion); } fn send_callback(completion: *Ring.Completion, result: anyerror!i32) void { resume completion.get_context(anyframe); _ = result catch return; } }; const HTTP_RESPONSE = "HTTP/1.1 200 Ok\r\n" ++ "Content-Length: 11\r\n" ++ "Content-Type: text/plain; charset=utf8\r\n" ++ "Date: Thu, 19 Nov 2021 15:26:34 GMT\r\n" ++ "Server: uring-example\r\n" ++ "\r\n" ++ "Hello World";
src/hybrid.zig
const std = @import("std"); const assert = std.debug.assert; const c = @cImport({ @cInclude("cgltf.h"); }); const Error = @import("main.zig").Error; const mem = @import("memory.zig"); pub const DataHandle = *opaque {}; pub fn parseAndLoadFile(gltf_path: [:0]const u8) Error!DataHandle { var options = std.mem.zeroes(c.cgltf_options); options.memory = .{ .alloc = mem.zmeshAllocUser, .free = mem.zmeshFreeUser, .user_data = null, }; var data: *c.cgltf_data = undefined; const parse = c.cgltf_parse_file(&options, gltf_path.ptr, @ptrCast([*c][*c]c.cgltf_data, &data)); if (parse != c.cgltf_result_success) { return error.FileNotFound; } errdefer c.cgltf_free(data); const load = c.cgltf_load_buffers(&options, data, gltf_path.ptr); if (load != c.cgltf_result_success) { return error.FileNotFound; } return @ptrCast(DataHandle, data); } pub fn freeData(data_handle: DataHandle) void { const data = @ptrCast( *c.cgltf_data, @alignCast(@alignOf(c.cgltf_data), data_handle), ); c.cgltf_free(data); } pub fn getNumMeshes(data_handle: DataHandle) u32 { const data = @ptrCast( *c.cgltf_data, @alignCast(@alignOf(c.cgltf_data), data_handle), ); return @intCast(u32, data.meshes_count); } pub fn getNumMeshPrimitives(data_handle: DataHandle, mesh_index: u32) u32 { const data = @ptrCast( *c.cgltf_data, @alignCast(@alignOf(c.cgltf_data), data_handle), ); assert(mesh_index < data.meshes_count); return @intCast(u32, data.meshes[mesh_index].primitives_count); } pub fn appendMeshPrimitive( data_handle: DataHandle, mesh_index: u32, prim_index: u32, indices: *std.ArrayList(u32), positions: *std.ArrayList([3]f32), normals: ?*std.ArrayList([3]f32), texcoords0: ?*std.ArrayList([2]f32), tangents: ?*std.ArrayList([4]f32), ) void { const data = @ptrCast( *c.cgltf_data, @alignCast(@alignOf(c.cgltf_data), data_handle), ); assert(mesh_index < data.meshes_count); assert(prim_index < data.meshes[mesh_index].primitives_count); const num_vertices: u32 = @intCast( u32, data.meshes[mesh_index].primitives[prim_index].attributes[0].data.*.count, ); const num_indices: u32 = @intCast(u32, data.meshes[mesh_index].primitives[prim_index].indices.*.count); // Indices. { indices.ensureTotalCapacity(indices.items.len + num_indices) catch unreachable; const accessor = data.meshes[mesh_index].primitives[prim_index].indices; assert(accessor.*.buffer_view != null); assert(accessor.*.stride == accessor.*.buffer_view.*.stride or accessor.*.buffer_view.*.stride == 0); assert((accessor.*.stride * accessor.*.count) == accessor.*.buffer_view.*.size); assert(accessor.*.buffer_view.*.buffer.*.data != null); const data_addr = @alignCast(4, @ptrCast([*]const u8, accessor.*.buffer_view.*.buffer.*.data) + accessor.*.offset + accessor.*.buffer_view.*.offset); if (accessor.*.stride == 1) { assert(accessor.*.component_type == c.cgltf_component_type_r_8u); const src = @ptrCast([*]const u8, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.appendAssumeCapacity(src[i]); } } else if (accessor.*.stride == 2) { assert(accessor.*.component_type == c.cgltf_component_type_r_16u); const src = @ptrCast([*]const u16, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.appendAssumeCapacity(src[i]); } } else if (accessor.*.stride == 4) { assert(accessor.*.component_type == c.cgltf_component_type_r_32u); const src = @ptrCast([*]const u32, data_addr); var i: u32 = 0; while (i < num_indices) : (i += 1) { indices.appendAssumeCapacity(src[i]); } } else { unreachable; } } // Attributes. { positions.resize(positions.items.len + num_vertices) catch unreachable; if (normals != null) normals.?.resize(normals.?.items.len + num_vertices) catch unreachable; if (texcoords0 != null) texcoords0.?.resize(texcoords0.?.items.len + num_vertices) catch unreachable; if (tangents != null) tangents.?.resize(tangents.?.items.len + num_vertices) catch unreachable; const num_attribs: u32 = @intCast(u32, data.meshes[mesh_index].primitives[prim_index].attributes_count); var attrib_index: u32 = 0; while (attrib_index < num_attribs) : (attrib_index += 1) { const attrib = &data.meshes[mesh_index].primitives[prim_index].attributes[attrib_index]; const accessor = attrib.data; assert(accessor.*.buffer_view != null); assert(accessor.*.stride == accessor.*.buffer_view.*.stride or accessor.*.buffer_view.*.stride == 0); assert((accessor.*.stride * accessor.*.count) == accessor.*.buffer_view.*.size); assert(accessor.*.buffer_view.*.buffer.*.data != null); const data_addr = @ptrCast([*]const u8, accessor.*.buffer_view.*.buffer.*.data) + accessor.*.offset + accessor.*.buffer_view.*.offset; if (attrib.*.type == c.cgltf_attribute_type_position) { assert(accessor.*.type == c.cgltf_type_vec3); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); @memcpy( @ptrCast([*]u8, &positions.items[positions.items.len - num_vertices]), data_addr, accessor.*.count * accessor.*.stride, ); } else if (attrib.*.type == c.cgltf_attribute_type_normal and normals != null) { assert(accessor.*.type == c.cgltf_type_vec3); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); @memcpy( @ptrCast([*]u8, &normals.?.items[normals.?.items.len - num_vertices]), data_addr, accessor.*.count * accessor.*.stride, ); } else if (attrib.*.type == c.cgltf_attribute_type_texcoord and texcoords0 != null) { assert(accessor.*.type == c.cgltf_type_vec2); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); @memcpy( @ptrCast([*]u8, &texcoords0.?.items[texcoords0.?.items.len - num_vertices]), data_addr, accessor.*.count * accessor.*.stride, ); } else if (attrib.*.type == c.cgltf_attribute_type_tangent and tangents != null) { assert(accessor.*.type == c.cgltf_type_vec4); assert(accessor.*.component_type == c.cgltf_component_type_r_32f); @memcpy( @ptrCast([*]u8, &tangents.?.items[tangents.?.items.len - num_vertices]), data_addr, accessor.*.count * accessor.*.stride, ); } } } }
libs/zmesh/src/gltf.zig
const std = @import("std"); const assert = std.debug.assert; const _debug = if (false) std.debug.print else _noopDebugPrint; fn _noopDebugPrint(comptime fmt: []const u8, args: anytype) void { _ = fmt; _ = args; // do nothing } var _nxt: usize = 0; fn _debugGenNum() usize { _nxt += 1; return _nxt; } /// Returns an iterator (something with a `.next()` function) from the given generator. /// A generator is something with a `.run(y: *Yielder(...))` function. pub fn genIter(gen: anytype) GenIter(@TypeOf(gen), ValueTypeOfGenType(@TypeOf(gen))) { return GenIter(@TypeOf(gen), ValueTypeOfGenType(@TypeOf(gen))){ ._gen = gen }; } /// A type with a `yield()` function that is used to "return" values from a generator. /// /// As an implementation detail, this is a tagged union value that /// represents the current state of the generator iterator. pub const Yielder = GenIterState; fn ValueTypeOfGenType(comptime G: type) type { const RunFunction = @TypeOf(G.run); const run_function_args = @typeInfo(RunFunction).Fn.args; std.debug.assert(run_function_args.len == 2); // .run() is expected to have two arguments (self: *@This(), y: *Yielder(...)) const Yielder_T_Pointer = run_function_args[1].arg_type.?; const Yielder_T = @typeInfo(Yielder_T_Pointer).Pointer.child; // .run(...) takes a pointer (to a Yielder(...)) const GenIterState_T = Yielder_T; const GenIterState_T_valued = TypeOfNamedFieldIn(@typeInfo(GenIterState_T).Union.fields, "_valued"); // .run(...) takes a *Yielder(...) const Yielded_value = TypeOfNamedFieldIn(@typeInfo(GenIterState_T_valued).Struct.fields, "value"); const T = @typeInfo(Yielded_value).Optional.child; return T; } fn TypeOfNamedFieldIn(comptime fields: anytype, field_name: []const u8) type { for (fields) |f| { if (std.mem.eql(u8, f.name, field_name)) { return f.field_type; } } else @compileError("ziggen internal error: fields array doesn't contain expected field"); } fn GenIter(comptime G: anytype, comptime T: type) type { return struct { _gen: G, _state: GenIterState(T) = ._not_started, _frame: @Frame(@This()._run_gen) = undefined, /// This function is used to detect that `.run()` has returned fn _run_gen(self: *@This()) void { _debug("_run_gen(): enter\n", .{}); self._gen.run(&(self._state)); // the generator must have a .run(*Yielder(T)) function _debug("_run_gen(): after run() in state {}\n", .{@as(_StateTag, self._state)}); self._state._suspend_with_value(null); } /// Return the next value of this generator iterator. pub fn next(self: *@This()) ?T { _debug("next(): enter state {}\n", .{@as(_StateTag, self._state)}); if (self._state == ._not_started) { self._state = .{ ._running = null }; _debug("next(): to state {}\n", .{@as(_StateTag, self._state)}); const i = _debugGenNum(); _debug("> {}\n", .{i}); self._frame = async self._run_gen(); _debug("< {}\n", .{i}); } while (true) { switch (self._state) { ._not_started => unreachable, ._running => { // still running after previous `async` or `resume`: suspended outside yield() assert(self._state._running == null); // so we will not overwrite the frame pointer below if (@hasDecl(G, "is_async") and G.is_async == true) { self._state = .{ ._running = @frame() }; _debug("next(): to state {}\n", .{@as(_StateTag, self._state)}); _debug("next(): before suspend\n", .{}); suspend {} // ...so that this call of next() gets suspended, to be resumed by the client in yield(), or after, in _run_gen() _debug("next(): after suspend in state {}\n", .{@as(_StateTag, self._state)}); assert(self._state == ._valued); } else @panic("generator suspended but not in yield(); mark generator `const is_async = true;`?"); }, ._valued => |value_state| { if (value_state.value) |v| { // .yield(v) has been called self._state = .{ ._waiting = value_state.frame_pointer }; _debug("next(): to state {}\n", .{@as(_StateTag, self._state)}); return v; } else { // the generator function has returned, resume in _run_gen() _debug("next(): before resume\n", .{}); const i = _debugGenNum(); _debug("> {}\n", .{i}); resume value_state.frame_pointer; _debug("< {}\n", .{i}); _debug("next(): after resume\n", .{}); nosuspend await self._frame; // will never suspend anymore, so this next() call shouldn't either self._state = ._stopped; return null; } }, ._waiting => |fp| { self._state = .{ ._running = null }; _debug("next(): to state {}\n", .{@as(_StateTag, self._state)}); _debug("next(): before resume\n", .{}); const i = _debugGenNum(); _debug("> {}\n", .{i}); resume fp; // let the generator continue _debug("< {}\n", .{i}); _debug("next(): after resume\n", .{}); assert(self._state == ._valued or self._state == ._running); }, ._stopped => { return null; }, } } } }; } const _StateTag = enum { _not_started, _running, _valued, _waiting, _stopped }; fn GenIterState(comptime T: type) type { return union(_StateTag) { /// the generator function was not yet called _not_started: void, /// the generator function did not reach yield() after being called or resumed (whichever came last), /// but it optionally suspended in outside of yield(), as captured by next() _running: ?anyframe, /// the generator function has suspended in yield() or it has returned, and the value still has to be returned to the client _valued: struct { /// non-null if from yield(), null if the generator function returned value: ?T, /// the point where next() should resume frame_pointer: anyframe, }, /// the generator function has suspended in yield() or it has returned, and the value has already been returned _waiting: anyframe, /// the generator function has returned _stopped: void, /// Yield the given value from the generator that received this instance pub fn yield(self: *@This(), value: T) void { self._suspend_with_value(value); } fn _suspend_with_value(self: *@This(), value: ?T) void { const orig_self: @This() = self.*; assert(orig_self == ._running); _debug("_suspend_with_value(): enter state {} (with value? {})\n", .{ @as(_StateTag, orig_self), value != null }); self.* = .{ ._valued = .{ .value = value, .frame_pointer = @frame() } }; _debug("_suspend_with_value(): to state {}\n", .{@as(_StateTag, self.*)}); _debug("_suspend_with_value(): before suspend\n", .{}); suspend { if (orig_self._running) |fp| { const i = _debugGenNum(); _debug("> {}\n", .{i}); resume fp; // This point is only reached very late; when the event loop ends? // For some reason, at that point our local state, // the current stack frame, is not available anymore... // So we should not be doing anything context-dependent here... _debug("< ?\n", .{}); } } _debug("_suspend_with_value(): after suspend (elsewhere? {})\n", .{orig_self._running != null}); } }; } // TESTS AND EXAMPLES // ------------------ const expectEqual = std.testing.expectEqual; fn EmptySleeper(comptime asy: bool) type { return struct { pub const is_async = asy; sleep_time_ms: ?usize = null, pub fn run(self: *@This(), _: *Yielder(bool)) void { if (self.sleep_time_ms) |ms| { _debug("run(): before sleep\n", .{}); std.time.sleep(ms * std.time.ns_per_ms); _debug("run(): after sleep\n", .{}); } } }; } test "empty, sync" { _debug("\nSTART\n", .{}); defer _debug("END\n", .{}); var iter = genIter(EmptySleeper(false){ .sleep_time_ms = null }); try expectEqual(@as(?bool, null), iter.next()); try expectEqual(@as(?bool, null), iter.next()); } test "empty, async" { // auto-skipped if not --test-evented-io, because EmptySleeper(true) is an async generator assert(@import("root").io_mode == .evented); _debug("\nSTART\n", .{}); defer _debug("END\n", .{}); var iter = genIter(EmptySleeper(true){ .sleep_time_ms = null }); try expectEqual(@as(?bool, null), iter.next()); try expectEqual(@as(?bool, null), iter.next()); } test "empty sleeper, sync" { if (@import("root").io_mode == .evented) { // sleep() would suspend, making this non-async generator panic return error.SkipZigTest; } // blocking I/O, therefore sleep() does not suspend _debug("\nSTART\n", .{}); defer _debug("END\n", .{}); var iter = genIter(EmptySleeper(false){ .sleep_time_ms = 500 }); try expectEqual(@as(?bool, null), iter.next()); try expectEqual(@as(?bool, null), iter.next()); } test "empty sleeper, async" { // auto-skipped if not --test-evented-io, because EmptySleeper(true) is an async generator assert(@import("root").io_mode == .evented); _debug("\nSTART\n", .{}); defer _debug("END\n", .{}); var iter = genIter(EmptySleeper(true){ .sleep_time_ms = 500 }); try expectEqual(@as(?bool, null), iter.next()); try expectEqual(@as(?bool, null), iter.next()); } const Bits = struct { pub const is_async = true; sleep_time_ms: ?usize = null, pub fn run(self: *@This(), y: *Yielder(bool)) void { if (self.sleep_time_ms) |ms| { _debug("run(): before sleep\n", .{}); std.time.sleep(ms * std.time.ns_per_ms); _debug("run(): after sleep\n", .{}); } _debug("run(): before yield(false)\n", .{}); y.yield(false); _debug("run(): after yield(false)\n", .{}); if (self.sleep_time_ms) |ms| { _debug("run(): before sleep\n", .{}); std.time.sleep(ms * std.time.ns_per_ms); _debug("run(): after sleep\n", .{}); } _debug("run(): before yield(true)\n", .{}); y.yield(true); _debug("run(): after yield(true)\n", .{}); if (self.sleep_time_ms) |ms| { _debug("run(): before sleep\n", .{}); std.time.sleep(ms * std.time.ns_per_ms); _debug("run(): after sleep\n", .{}); } } }; test "generate all bits, finite iterator" { // auto-skipped if not --test-evented-io, because Bits is an async generator assert(@import("root").io_mode == .evented); _debug("\nSTART\n", .{}); defer _debug("END\n", .{}); var iter = genIter(Bits{ .sleep_time_ms = 500 }); _debug("client: before false\n", .{}); try expectEqual(@as(?bool, false), iter.next()); _debug("client: after false\n", .{}); _debug("client: before true\n", .{}); try expectEqual(@as(?bool, true), iter.next()); _debug("client: after true\n", .{}); try expectEqual(@as(?bool, null), iter.next()); try expectEqual(@as(?bool, null), iter.next()); } const Nats = struct { below: ?usize, pub fn run(self: *@This(), y: *Yielder(usize)) void { var i: usize = 0; while (self.below == null or i < self.below.?) : (i += 1) { y.yield(i); } } }; test "sum the first 7 natural numbers" { var iter = genIter(Nats{ .below = 7 }); var sum: usize = 0; while (iter.next()) |i| { sum += i; } try expectEqual(@as(usize, 21), sum); } test "generate all bits, bounded iterator" { var iter = genIter(Nats{ .below = 2 }); try expectEqual(@as(?usize, 0), iter.next()); try expectEqual(@as(?usize, 1), iter.next()); try expectEqual(@as(?usize, null), iter.next()); try expectEqual(@as(?usize, null), iter.next()); } test "sum by breaking infinite generator" { var iter = genIter(Nats{ .below = null }); var sum: usize = 0; while (iter.next()) |i| { if (i == 7) break; sum += i; } try expectEqual(@as(usize, 21), sum); }
ziggen.zig
const std = @import("std"); const mem = std.mem; const meta = std.meta; const net = std.net; usingnamespace @import("../frame.zig"); usingnamespace @import("../primitive_types.zig"); usingnamespace @import("../error.zig"); const testing = @import("../testing.zig"); /// ERROR is sent by a node if there's an error processing a request. /// /// Described in the protocol spec at §4.2.1. pub const ErrorFrame = struct { const Self = @This(); // TODO(vincent): extract this for use by the client error_code: ErrorCode, message: []const u8, unavailable_replicas: ?UnavailableReplicasError, function_failure: ?FunctionFailureError, write_timeout: ?WriteError.Timeout, read_timeout: ?ReadError.Timeout, write_failure: ?WriteError.Failure, read_failure: ?ReadError.Failure, cas_write_unknown: ?WriteError.CASUnknown, already_exists: ?AlreadyExistsError, unprepared: ?UnpreparedError, pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !Self { var frame = Self{ .error_code = undefined, .message = undefined, .unavailable_replicas = null, .function_failure = null, .write_timeout = null, .read_timeout = null, .write_failure = null, .read_failure = null, .cas_write_unknown = null, .already_exists = null, .unprepared = null, }; frame.error_code = @intToEnum(ErrorCode, try pr.readInt(u32)); frame.message = try pr.readString(allocator); switch (frame.error_code) { .UnavailableReplicas => { frame.unavailable_replicas = UnavailableReplicasError{ .consistency_level = try pr.readConsistency(), .required = try pr.readInt(u32), .alive = try pr.readInt(u32), }; }, .FunctionFailure => { frame.function_failure = FunctionFailureError{ .keyspace = try pr.readString(allocator), .function = try pr.readString(allocator), .arg_types = try pr.readStringList(allocator), }; }, .WriteTimeout => { var write_timeout = WriteError.Timeout{ .consistency_level = try pr.readConsistency(), .received = try pr.readInt(u32), .block_for = try pr.readInt(u32), .write_type = undefined, .contentions = null, }; const write_type_string = try pr.readString(allocator); defer allocator.free(write_type_string); write_timeout.write_type = meta.stringToEnum(WriteError.WriteType, write_type_string) orelse return error.InvalidWriteType; if (write_timeout.write_type == .CAS) { write_timeout.contentions = try pr.readInt(u16); } frame.write_timeout = write_timeout; }, .ReadTimeout => { frame.read_timeout = ReadError.Timeout{ .consistency_level = try pr.readConsistency(), .received = try pr.readInt(u32), .block_for = try pr.readInt(u32), .data_present = try pr.readByte(), }; }, .WriteFailure => { var write_failure = WriteError.Failure{ .consistency_level = try pr.readConsistency(), .received = try pr.readInt(u32), .block_for = try pr.readInt(u32), .reason_map = undefined, .write_type = undefined, }; // Read reason map // TODO(vincent): this is only correct for Protocol v5 // See point 10. in the the protocol v5 spec. var reason_map = std.ArrayList(WriteError.Failure.Reason).init(allocator); errdefer reason_map.deinit(); const n = try pr.readInt(u32); var i: usize = 0; while (i < n) : (i += 1) { const reason = WriteError.Failure.Reason{ .endpoint = try pr.readInetaddr(), .failure_code = try pr.readInt(u16), }; _ = try reason_map.append(reason); } write_failure.reason_map = reason_map.toOwnedSlice(); // Read the rest const write_type_string = try pr.readString(allocator); defer allocator.free(write_type_string); write_failure.write_type = meta.stringToEnum(WriteError.WriteType, write_type_string) orelse return error.InvalidWriteType; frame.write_failure = write_failure; }, .ReadFailure => { var read_failure = ReadError.Failure{ .consistency_level = try pr.readConsistency(), .received = try pr.readInt(u32), .block_for = try pr.readInt(u32), .reason_map = undefined, .data_present = undefined, }; // Read reason map var reason_map = std.ArrayList(ReadError.Failure.Reason).init(allocator); errdefer reason_map.deinit(); const n = try pr.readInt(u32); var i: usize = 0; while (i < n) : (i += 1) { const reason = ReadError.Failure.Reason{ .endpoint = try pr.readInetaddr(), .failure_code = try pr.readInt(u16), }; _ = try reason_map.append(reason); } read_failure.reason_map = reason_map.toOwnedSlice(); // Read the rest read_failure.data_present = try pr.readByte(); frame.read_failure = read_failure; }, .CASWriteUnknown => { frame.cas_write_unknown = WriteError.CASUnknown{ .consistency_level = try pr.readConsistency(), .received = try pr.readInt(u32), .block_for = try pr.readInt(u32), }; }, .AlreadyExists => { frame.already_exists = AlreadyExistsError{ .keyspace = try pr.readString(allocator), .table = try pr.readString(allocator), }; }, .Unprepared => { if (try pr.readShortBytes(allocator)) |statement_id| { frame.unprepared = UnpreparedError{ .statement_id = statement_id, }; } else { // TODO(vincent): make this a proper error ? return error.InvalidStatementID; } }, else => {}, } return frame; } }; test "error frame: invalid query, no keyspace specified" { var arena = testing.arenaAllocator(); defer arena.deinit(); const data = "\x84\x00\x00\x02\x00\x00\x00\x00\x5e\x00\x00\x22\x00\x00\x58\x4e\x6f\x20\x6b\x65\x79\x73\x70\x61\x63\x65\x20\x68\x61\x73\x20\x62\x65\x65\x6e\x20\x73\x70\x65\x63\x69\x66\x69\x65\x64\x2e\x20\x55\x53\x45\x20\x61\x20\x6b\x65\x79\x73\x70\x61\x63\x65\x2c\x20\x6f\x72\x20\x65\x78\x70\x6c\x69\x63\x69\x74\x6c\x79\x20\x73\x70\x65\x63\x69\x66\x79\x20\x6b\x65\x79\x73\x70\x61\x63\x65\x2e\x74\x61\x62\x6c\x65\x6e\x61\x6d\x65"; const raw_frame = try testing.readRawFrame(&arena.allocator, data); checkHeader(Opcode.Error, data.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try ErrorFrame.read(&arena.allocator, &pr); testing.expectEqual(ErrorCode.InvalidQuery, frame.error_code); testing.expectEqualStrings("No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename", frame.message); } test "error frame: already exists" { var arena = testing.arenaAllocator(); defer arena.deinit(); const data = "\x84\x00\x00\x23\x00\x00\x00\x00\x53\x00\x00\x24\x00\x00\x3e\x43\x61\x6e\x6e\x6f\x74\x20\x61\x64\x64\x20\x61\x6c\x72\x65\x61\x64\x79\x20\x65\x78\x69\x73\x74\x69\x6e\x67\x20\x74\x61\x62\x6c\x65\x20\x22\x68\x65\x6c\x6c\x6f\x22\x20\x74\x6f\x20\x6b\x65\x79\x73\x70\x61\x63\x65\x20\x22\x66\x6f\x6f\x62\x61\x72\x22\x00\x06\x66\x6f\x6f\x62\x61\x72\x00\x05\x68\x65\x6c\x6c\x6f"; const raw_frame = try testing.readRawFrame(&arena.allocator, data); checkHeader(Opcode.Error, data.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try ErrorFrame.read(&arena.allocator, &pr); testing.expectEqual(ErrorCode.AlreadyExists, frame.error_code); testing.expectEqualStrings("Cannot add already existing table \"hello\" to keyspace \"foobar\"", frame.message); const already_exists_error = frame.already_exists.?; testing.expectEqualStrings("foobar", already_exists_error.keyspace); testing.expectEqualStrings("hello", already_exists_error.table); } test "error frame: syntax error" { var arena = testing.arenaAllocator(); defer arena.deinit(); const data = "\x84\x00\x00\x2f\x00\x00\x00\x00\x41\x00\x00\x20\x00\x00\x3b\x6c\x69\x6e\x65\x20\x32\x3a\x30\x20\x6d\x69\x73\x6d\x61\x74\x63\x68\x65\x64\x20\x69\x6e\x70\x75\x74\x20\x27\x3b\x27\x20\x65\x78\x70\x65\x63\x74\x69\x6e\x67\x20\x4b\x5f\x46\x52\x4f\x4d\x20\x28\x73\x65\x6c\x65\x63\x74\x2a\x5b\x3b\x5d\x29"; const raw_frame = try testing.readRawFrame(&arena.allocator, data); checkHeader(Opcode.Error, data.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try ErrorFrame.read(&arena.allocator, &pr); testing.expectEqual(ErrorCode.SyntaxError, frame.error_code); testing.expectEqualStrings("line 2:0 mismatched input ';' expecting K_FROM (select*[;])", frame.message); }
src/frames/error.zig
const std = @import("std"); const Entity = @import("Entity.zig").Entity; const EntityManager = @import("EntityManager.zig").EntityManager; const behaviourSystems = @import("BehaviourSystems.zig"); const ComponentManager = @import("ComponentData.zig").ComponentManager; const debug = std.debug; const time = std.time; const Timer = time.Timer; const ArrayList = std.ArrayList; const allocator = std.heap.direct_allocator; var instance: GameWorld = undefined; pub const fixedDeltaTime: comptime f32 = 1.0 / 60.0; pub var deltaTime: comptime f32 = 1.0 / 60.0; pub const GameWorld = struct { m_entityManager: EntityManager, m_componentManager: ComponentManager, m_updateBehaviours: [behaviourSystems.s_update.len]fn () void = behaviourSystems.s_update, m_fixedUpdateBehaviours: [behaviourSystems.s_fixedUpdate.len]fn () void = behaviourSystems.s_fixedUpdate, m_onSpawnBehaviours: [behaviourSystems.s_onSpawn.len]fn (u32) void = behaviourSystems.s_onSpawn, m_onDestroyBehaviours: [behaviourSystems.s_onDestroy.len]fn (u32) void = behaviourSystems.s_onDestroy, pub fn Update(self: *GameWorld, deltaT: f32) void { deltaTime = deltaT; var i: u32 = 0; while (i < self.m_updateBehaviours.len) { defer i += 1; self.m_updateBehaviours[i](); } } pub fn FixedUpdate(self: *GameWorld) void { var i: u32 = 0; while (i < self.m_fixedUpdateBehaviours.len) { defer i += 1; self.m_fixedUpdateBehaviours[i](); } } pub fn CreateEntity(self: *GameWorld) *Entity { const newEntity = instance.m_entityManager.CreateEntity() catch |err| { debug.panic("{}", .{err}); }; var i: u32 = 0; while (i < self.m_onSpawnBehaviours.len) { defer i += 1; self.m_onSpawnBehaviours[i](newEntity.m_eid); } return newEntity; } pub fn KillEntity(self: *GameWorld, eid: u32) bool { var i: u32 = 0; while (i < self.m_onDestroyBehaviours.len) { defer i += 1; self.m_onDestroyBehaviours[i](eid); } return self.m_entityManager.KillEntity(eid); } }; pub fn Initialize() void { instance = GameWorld{ .m_entityManager = EntityManager.Initialize(), .m_componentManager = ComponentManager.Initialize(), }; } pub fn Instance() *const GameWorld { return &instance; } pub fn WritableInstance() *GameWorld { return &instance; }
src/game/GameWorld.zig
const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const zigimg = @import("zigimg/zigimg.zig"); const IntegerColor8 = zigimg.color.IntegerColor8; const OctTreeQuantizer = zigimg.OctTreeQuantizer; const fs = std.fs; const mem = std.mem; const std = @import("std"); pub const ImageConverterError = error{InvalidPixelData}; const GBAColor = packed struct { r: u5, g: u5, b: u5, }; pub const ImageSourceTarget = struct { source: []const u8, target: []const u8, }; pub const ImageConverter = struct { pub fn convertMode4Image(allocator: *Allocator, images: []ImageSourceTarget, targetPaletteFilePath: []const u8) !void { var quantizer = OctTreeQuantizer.init(allocator); defer quantizer.deinit(); const ImageConvertInfo = struct { imageInfo: ImageSourceTarget, image: zigimg.Image, }; var imageConvertList = ArrayList(ImageConvertInfo).init(allocator); defer imageConvertList.deinit(); for (images) |imageInfo| { var convertInfo = try imageConvertList.addOne(); convertInfo.imageInfo = imageInfo; convertInfo.image = try zigimg.Image.fromFilePath(allocator, imageInfo.source); var colorIt = convertInfo.image.iterator(); while (colorIt.next()) |pixel| { try quantizer.addColor(pixel.premultipliedAlpha().toIntegerColor8()); } } var paletteStorage: [256]IntegerColor8 = undefined; var palette = try quantizer.makePalette(255, paletteStorage[0..]); var paletteFile = try openWriteFile(targetPaletteFilePath); defer paletteFile.close(); var paletteOutStream = paletteFile.writer(); // Write palette file var paletteCount: usize = 0; for (palette) |entry| { const gbaColor = colorToGBAColor(entry); try paletteOutStream.writeIntLittle(u15, @bitCast(u15, gbaColor)); paletteCount += 2; } // Align palette file to a power of 4 var diff = mem.alignForward(paletteCount, 4) - paletteCount; var index: usize = 0; while (index < diff) : (index += 1) { try paletteOutStream.writeIntLittle(u8, 0); } for (imageConvertList.items) |convertInfo| { var imageFile = try openWriteFile(convertInfo.imageInfo.target); defer imageFile.close(); var imageOutStream = imageFile.writer(); // Write image file var pixelCount: usize = 0; var colorIt = convertInfo.image.iterator(); while (colorIt.next()) |pixel| { var rawPaletteIndex: usize = try quantizer.getPaletteIndex(pixel.premultipliedAlpha().toIntegerColor8()); var paletteIndex: u8 = @intCast(u8, rawPaletteIndex); try imageOutStream.writeIntLittle(u8, paletteIndex); pixelCount += 1; } diff = mem.alignForward(pixelCount, 4) - pixelCount; index = 0; while (index < diff) : (index += 1) { try imageOutStream.writeIntLittle(u8, 0); } } } fn openWriteFile(path: []const u8) !fs.File { return try fs.cwd().createFile(path, fs.File.CreateFlags{}); } fn colorToGBAColor(color: IntegerColor8) GBAColor { return GBAColor{ .r = @intCast(u5, (color.R >> 3) & 0x1f), .g = @intCast(u5, (color.G >> 3) & 0x1f), .b = @intCast(u5, (color.B >> 3) & 0x1f), }; } };
GBA/assetconverter/image_converter.zig
const std = @import("std"); const bcm2835 = @import("bcm2835.zig"); const peripherals = @import("peripherals.zig"); /// enumerates the GPio level (high/low) pub const Level = enum(u1) { High = 0x1, Low = 0x0 }; /// enumerates the gpio functionality /// the enum values are the bits that need to be written into the /// appropriate bits of the function select registers for a bin /// see p 91,92 of http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf pub const Mode = enum(u3) { /// intput functionality Input = 0b000, /// output functionality Output = 0b001, /// not yet implemented Alternate0 = 0b100, /// not yet implemented Alternate1 = 0b101, /// not yet implemented Alternate2 = 0b110, /// not yet implemented Alternate3 = 0b111, /// not yet implemented Alternate4 = 0b011, /// not yet implemented Alternate5 = 0b010, }; pub const PullMode = enum(u2) { Off = 0b00, PullDown = 0b01, PullUp = 0b10 }; pub const Error = error{ /// not initialized Uninitialized, /// Pin number out of range (or not available for this functionality) IllegalPinNumber, /// a mode value that could not be recognized was read from the register IllegalMode, }; /// if initialized points to the memory block that is provided by the gpio /// memory mapping interface var g_gpio_registers: ?peripherals.GpioRegisterMemory = null; var is_init: bool = false; /// initialize the GPIO control with the given memory mapping pub fn init(memory_interface: *peripherals.GpioMemMapper) !void { g_gpio_registers = try memory_interface.memoryMap(); } /// deinitialize /// This function will not release access of the GPIO memory, instead /// it will perform some cleanup for the internals of this implementation pub fn deinit() void { g_gpio_registers = null; } // write the given level to the pin pub fn setLevel(pin_number: u8, level: Level) !void { try checkPinNumber(pin_number, bcm2835.BoardInfo); // register offset to find the correct set or clear register depending on the level: // setting works by writing a 1 to the bit that corresponds to the pin in the appropriate GPSET{n} register // and clearing works by writing a 1 to the bit that corresponds to the pin in the appropriate GPCLR{n} register // writing a 0 to those registers doesn't do anything const register_zero: u8 = switch (level) { .High => comptime gpioRegisterZeroIndex("gpset_registers", bcm2835.BoardInfo), // "set" GPSET{n} registers .Low => comptime gpioRegisterZeroIndex("gpclr_registers", bcm2835.BoardInfo), // "clear" GPCLR{n} registers }; try setPinSingleBit(g_gpio_registers, .{ .pin_number = pin_number, .register_zero = register_zero }, 1); } pub fn getLevel(pin_number: u8) !Level { const gplev_register_zero = comptime gpioRegisterZeroIndex("gplev_registers", bcm2835.BoardInfo); const bit: u1 = try getPinSingleBit(g_gpio_registers, .{ .register_zero = gplev_register_zero, .pin_number = pin_number }); if (bit == 0) { return .Low; } else { return .High; } } // set the mode for the given pin. pub fn setMode(pin_number: u8, mode: Mode) Error!void { var registers = g_gpio_registers orelse return Error.Uninitialized; try checkPinNumber(pin_number, bcm2835.BoardInfo); // a series of @bitSizeOf(Mode) is necessary to encapsulate the function of one pin // this is why we have to calculate the amount of pins that fit into a register by dividing // the number of bits in the register by the number of bits for the function // as of now 3 bits for the function and 32 bits for the register make 10 pins per register const pins_per_register = comptime @divTrunc(@bitSizeOf(peripherals.GpioRegister), @bitSizeOf(Mode)); const gpfsel_register_zero = comptime gpioRegisterZeroIndex("gpfsel_registers", bcm2835.BoardInfo); const n: @TypeOf(pin_number) = @divTrunc(pin_number, pins_per_register); // set the bits of the corresponding pins to zero so that we can bitwise or the correct mask to it below registers[gpfsel_register_zero + n] &= clearMask(pin_number); // use bitwise-& here registers[gpfsel_register_zero + n] |= modeMask(pin_number, mode); // use bitwise-| here TODO, this is dumb, rework the mode setting mask to not have the inverse! } // read the mode of the given pin number pub fn getMode(pin_number: u8) !Mode { var registers = g_gpio_registers orelse return Error.Uninitialized; try checkPinNumber(pin_number, bcm2835.BoardInfo); const pins_per_register = comptime @divTrunc(@bitSizeOf(peripherals.GpioRegister), @bitSizeOf(Mode)); const gpfsel_register_zero = comptime gpioRegisterZeroIndex("gpfsel_registers", bcm2835.BoardInfo); const n: @TypeOf(pin_number) = @divTrunc(pin_number, pins_per_register); const ModeIntType = (@typeInfo(Mode).Enum.tag_type); const ones: peripherals.GpioRegister = std.math.maxInt(ModeIntType); const shift_count = @bitSizeOf(Mode) * @intCast(u5, pin_number % pins_per_register); const stencil_mask = ones << shift_count; const mode_value = @intCast(ModeIntType, (registers[gpfsel_register_zero + n] & stencil_mask) >> shift_count); inline for (std.meta.fields(Mode)) |mode| { if (mode.value == mode_value) { return @intToEnum(Mode, mode.value); } } return Error.IllegalMode; } pub fn setPull(pin_number: u8, mode: PullMode) Error!void { var registers = g_gpio_registers orelse return Error.Uninitialized; // see the GPPUCLK register description for how to set the pull up or pull down on a per pin basis const gppud_register_zero = comptime gpioRegisterZeroIndex("gppud_register", bcm2835.BoardInfo); const gppudclk_register_zero = comptime gpioRegisterZeroIndex("gppudclk_registers", bcm2835.BoardInfo); const ten_us_in_ns = 10 * 1000; registers[gppud_register_zero] = @enumToInt(mode); // TODO this may be janky, because no precision of timing is guaranteed // however, the manual only states that we have to wait 150 clock cycles // and we are being very generous here std.os.nanosleep(0, ten_us_in_ns); try setPinSingleBit(registers, .{ .pin_number = pin_number, .register_zero = gppudclk_register_zero }, 1); std.os.nanosleep(0, ten_us_in_ns); registers[gppud_register_zero] = @enumToInt(PullMode.Off); try setPinSingleBit(registers, .{ .pin_number = pin_number, .register_zero = gppudclk_register_zero }, 0); } const PinAndRegister = struct { pin_number: u8, register_zero: u8, }; /// helper function for simplifying working with those contiguous registers where one GPIO bin is represented by one bit /// needs the zero register for the set and the pin number and returns the bit (or an error) inline fn getPinSingleBit(gpio_registers: ?peripherals.GpioRegisterMemory, pin_and_register: PinAndRegister) !u1 { var registers = gpio_registers orelse return Error.Uninitialized; const pin_number = pin_and_register.pin_number; const register_zero = pin_and_register.register_zero; try checkPinNumber(pin_number, bcm2835.BoardInfo); const pins_per_register = comptime @bitSizeOf(peripherals.GpioRegister); const n = @divTrunc(pin_number, pins_per_register); const pin_shift = @intCast(u5, pin_number % pins_per_register); const pin_value = registers[register_zero + n] & (@intCast(peripherals.GpioRegister, 1) << pin_shift); if (pin_value == 0) { return 0; } else { return 1; } } /// helper function for simplifying the work with those contiguous registers where one GPIO pin is represented by one bit /// this function sets the respective bit to the given value inline fn setPinSingleBit(gpio_registers: ?peripherals.GpioRegisterMemory, pin_and_register: PinAndRegister, comptime value_to_set: u1) !void { var registers = gpio_registers orelse return Error.Uninitialized; const pin_number = pin_and_register.pin_number; const register_zero = pin_and_register.register_zero; try checkPinNumber(pin_number, bcm2835.BoardInfo); const pins_per_register = comptime @bitSizeOf(peripherals.GpioRegister); const n = @divTrunc(pin_number, pins_per_register); const pin_shift = @intCast(u5, pin_number % pins_per_register); if (value_to_set == 1) { registers[register_zero + n] |= (@intCast(peripherals.GpioRegister, 1) << pin_shift); } else { registers[register_zero + n] &= ~(@intCast(peripherals.GpioRegister, 1) << pin_shift); } } /// calculates that mask that sets the mode for a given pin in a GPFSEL register. /// ATTENTION: before this function is called, the clearMask must be applied to this register inline fn modeMask(pin_number: u8, mode: Mode) peripherals.GpioRegister { // a 32 bit register can only hold 10 pins, because a pin function is set by an u3 value. const pins_per_register = comptime @divTrunc(@bitSizeOf(peripherals.GpioRegister), @bitSizeOf(Mode)); const pin_bit_idx = pin_number % pins_per_register; // shift the mode to the correct bits for the pin. Mode mask 0...xxx...0 return @intCast(peripherals.GpioRegister, @enumToInt(mode)) << @intCast(u5, (pin_bit_idx * @bitSizeOf(Mode))); } fn gpioRegisterZeroIndex(comptime register_name: []const u8, board_info: anytype) comptime_int { return comptime std.math.divExact(comptime_int, @field(board_info, register_name).start - board_info.gpio_registers.start, @sizeOf(peripherals.GpioRegister)) catch @compileError("Offset not evenly divisible by register width"); } /// just a helper function that returns an error iff the given pin number is illegal /// the board info type must carry a NUM_GPIO_PINS member field indicating the number of gpio pins inline fn checkPinNumber(pin_number: u8, comptime BoardInfo: type) !void { if (@hasDecl(BoardInfo, "NUM_GPIO_PINS")) { if (pin_number < BoardInfo.NUM_GPIO_PINS) { return; } else { return Error.IllegalPinNumber; } } else { @compileError("BoardInfo type must have a constant field NUM_GPIO_PINS indicating the number of gpio pins"); } } /// make a binary mask for clearing the associated region of th GPFSET register /// this mask can be binary-ANDed to the GPFSEL register to set the bits of the given pin to 0 inline fn clearMask(pin_number: u8) peripherals.GpioRegister { const pins_per_register = comptime @divTrunc(@bitSizeOf(peripherals.GpioRegister), @bitSizeOf(Mode)); const pin_bit_idx = pin_number % pins_per_register; // the input config should be zero // if it is, then the following logic will work comptime std.debug.assert(@enumToInt(Mode.Input) == 0); // convert the mode to a 3 bit integer: 0b000 (binary) // then invert the mode 111 (binary) // then convert this to an integer 000...000111 (binary) of register width // shift this by the appropriate amount (right now 3 bits per pin in a register) // 000...111...000 // invert the whole thing and we end up with 111...000...111 // we can bitwise and this to the register to clear the mode of the given pin // and prepare it for the set mode mask (which is bitwise or'd); return (~(@intCast(peripherals.GpioRegister, ~@enumToInt(Mode.Input)) << @intCast(u5, (pin_bit_idx * @bitSizeOf(Mode))))); } const testing = std.testing; test "clearMask" { comptime std.debug.assert(@bitSizeOf(peripherals.GpioRegister) == 32); comptime std.debug.assert(@bitSizeOf(Mode) == 3); try testing.expect(clearMask(0) == 0b11111111111111111111111111111000); std.log.info("mode mask = {b}", .{modeMask(3, Mode.Input)}); try testing.expect(clearMask(3) == 0b11111111111111111111000111111111); try testing.expect(clearMask(13) == 0b11111111111111111111000111111111); } test "modeMask" { // since the code below is manually verified for 32bit registers and 3bit function info // we have to make sure this still holds at compile time. comptime std.debug.assert(@bitSizeOf(peripherals.GpioRegister) == 32); comptime std.debug.assert(@bitSizeOf(Mode) == 3); // see online hex editor, e.g. https://hexed.it/ try testing.expect(modeMask(0, Mode.Input) == 0); std.log.info("mode mask = {b}", .{modeMask(3, Mode.Input)}); try testing.expect(modeMask(0, Mode.Output) == 0b00000000000000000000000000000001); try testing.expect(modeMask(3, Mode.Output) == 0b00000000000000000000001000000000); try testing.expect(modeMask(13, Mode.Alternate3) == 0b00000000000000000000111000000000); } test "gpioRegisterZeroIndex" { // the test is hand verified for 4 byte registers as is the case in the bcm2835 // so we need to make sure this prerequisite is fulfilled comptime std.debug.assert(@sizeOf(peripherals.GpioRegister) == 4); // manually verified using the BCM2835 ARM Peripherals Manual const board_info = bcm2835.BoardInfo; try testing.expectEqual(0, gpioRegisterZeroIndex("gpfsel_registers", board_info)); try testing.expectEqual(7, gpioRegisterZeroIndex("gpset_registers", board_info)); try testing.expectEqual(10, gpioRegisterZeroIndex("gpclr_registers", board_info)); try testing.expectEqual(13, gpioRegisterZeroIndex("gplev_registers", board_info)); } test "checkPinNumber" { const MyBoardInfo = struct { pub const NUM_GPIO_PINS: u8 = 20; }; var pin: u8 = 0; while (pin < MyBoardInfo.NUM_GPIO_PINS) : (pin += 1) { try checkPinNumber(pin, MyBoardInfo); } while (pin < 2 * MyBoardInfo.NUM_GPIO_PINS) : (pin += 1) { try testing.expectError(Error.IllegalPinNumber, checkPinNumber(pin, MyBoardInfo)); } } test "getPinSingleBit" { try std.testing.expectError(Error.Uninitialized, getPinSingleBit(null, .{ .pin_number = 1, .register_zero = 0 })); var three_registers = [3]peripherals.GpioRegister{ std.math.maxInt(peripherals.GpioRegister), 3, 5 }; try std.testing.expectEqual(@intCast(u1, 1), try getPinSingleBit(&three_registers, .{ .pin_number = 0, .register_zero = 1 })); try std.testing.expectEqual(@intCast(u1, 1), try getPinSingleBit(&three_registers, .{ .pin_number = 1, .register_zero = 1 })); try std.testing.expectEqual(@intCast(u1, 0), try getPinSingleBit(&three_registers, .{ .pin_number = 2, .register_zero = 1 })); try std.testing.expectEqual(@intCast(u1, 1), try getPinSingleBit(&three_registers, .{ .pin_number = 32 + 0, .register_zero = 1 })); try std.testing.expectEqual(@intCast(u1, 0), try getPinSingleBit(&three_registers, .{ .pin_number = 32 + 1, .register_zero = 1 })); try std.testing.expectEqual(@intCast(u1, 1), try getPinSingleBit(&three_registers, .{ .pin_number = 32 + 2, .register_zero = 1 })); } test "setPinSingleBit" { var three_registers = [3]peripherals.GpioRegister{ 0, 0, 0 }; // try setting bits try setPinSingleBit(&three_registers, .{ .pin_number = 0, .register_zero = 1 }, 1); try setPinSingleBit(&three_registers, .{ .pin_number = 1, .register_zero = 1 }, 1); try setPinSingleBit(&three_registers, .{ .pin_number = 3, .register_zero = 1 }, 1); try setPinSingleBit(&three_registers, .{ .pin_number = 32 + 2, .register_zero = 1 }, 1); // and then also unset bits that are zero anyways (these should have no influence on the values) try setPinSingleBit(&three_registers, .{ .pin_number = 32 + 3, .register_zero = 1 }, 0); try setPinSingleBit(&three_registers, .{ .pin_number = 2, .register_zero = 1 }, 0); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 0), three_registers[0]); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 1 + 2 + 8), three_registers[1]); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 4), three_registers[2]); // now unset a bit try setPinSingleBit(&three_registers, .{ .pin_number = 1, .register_zero = 1 }, 0); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 0), three_registers[0]); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 1 + 0 + 8), three_registers[1]); try std.testing.expectEqual(@intCast(peripherals.GpioRegister, 4), three_registers[2]); }
src/gpio.zig
const std = @import("std"); const use_test_input = false; const filename = if (use_test_input) "day-4_test-input" else "day-4_real-input"; const draw_count = if (use_test_input) 27 else 100; const board_count = if (use_test_input) 3 else 100; pub fn main() !void { std.debug.print("--- Day 4 ---\n", .{}); var file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); var draw_numbers: [draw_count]u7 = undefined; { var i: usize = 0; while (i < draw_count - 1):(i += 1) { draw_numbers[i] = try drawNext(file, ','); } draw_numbers[i] = try drawNext(file, '\n'); } var last_board_index: usize = 127; var last_board_turn: u7 = 0; var last_board_score: u32 = 0; var board_index: usize = 0; while (board_index < board_count):(board_index += 1) { var board: [25]u7 = undefined; var draw_turns = [_]?u7 {null} ** 25; { try file.reader().skipUntilDelimiterOrEof('\n'); var buffer: [3]u8 = undefined; const whitespace = [_]u8 { ' ', '\n' }; var row: usize = 0; while (row < 5):(row += 1) { var column: usize = 0; while (column < 5):(column += 1) { const i = row * 5 + column; _ = try file.reader().read(buffer[0..]); const num_string = std.mem.trim(u8, buffer[0..], whitespace[0..]); board[i] = try std.fmt.parseInt(u7, num_string, 10); for (draw_numbers) |draw, turn| { if (draw == board[i]) { draw_turns[i] = @intCast(u7, turn); break; } } } } } var win_turn: u7 = 127; var o_winning_row: ?usize = null; { var row: usize = 0; while (row < 5):(row += 1) { var o_row_win_turn: ?u7 = null; var column: usize = 0; while (column < 5):(column += 1) { const i = row * 5 + column; if (draw_turns[i]) |turn| { if (o_row_win_turn) |row_win_turn| { o_row_win_turn = @maximum(turn, row_win_turn); } else { o_row_win_turn = turn; } } else { o_row_win_turn = null; break; } } if (o_row_win_turn) |row_win_turn| { if (row_win_turn < win_turn) { win_turn = row_win_turn; o_winning_row = row; } } } } var o_winning_column: ?usize = null; { var column: usize = 0; while (column < 5):(column += 1) { var o_column_win_turn: ?u7 = null; var row: usize = 0; while (row < 5):(row += 1) { const i = row * 5 + column; if (draw_turns[i]) |turn| { if (o_column_win_turn) |column_win_turn| { o_column_win_turn = @maximum(turn, column_win_turn); } else { o_column_win_turn = turn; } } else { o_column_win_turn = null; break; } } if (o_column_win_turn) |column_win_turn| { if (column_win_turn < win_turn) { win_turn = column_win_turn; o_winning_row = null; o_winning_column = column; } } } } var score: u32 = 0; for (board) |num, i| { if (draw_turns[i] == null or draw_turns[i].? > win_turn) { score += num; } } score *= draw_numbers[win_turn]; if (win_turn > last_board_turn) { last_board_turn = win_turn; last_board_score = score; last_board_index = board_index; } } std.debug.print( "board {} wins last at turn {} with score of {}\n", .{ last_board_index, last_board_turn, last_board_score }); } fn drawNext(file: std.fs.File, delimiter: u8) !u7 { var buffer: [2]u8 = undefined; const draw_string = try file.reader().readUntilDelimiter(buffer[0..], delimiter); const draw = try std.fmt.parseInt(u7, draw_string, 10); return draw; }
day-4.zig
pub const NETSH_ERROR_BASE = @as(u32, 15000); pub const ERROR_NO_ENTRIES = @as(u32, 15000); pub const ERROR_INVALID_SYNTAX = @as(u32, 15001); pub const ERROR_PROTOCOL_NOT_IN_TRANSPORT = @as(u32, 15002); pub const ERROR_NO_CHANGE = @as(u32, 15003); pub const ERROR_CMD_NOT_FOUND = @as(u32, 15004); pub const ERROR_ENTRY_PT_NOT_FOUND = @as(u32, 15005); pub const ERROR_DLL_LOAD_FAILED = @as(u32, 15006); pub const ERROR_INIT_DISPLAY = @as(u32, 15007); pub const ERROR_TAG_ALREADY_PRESENT = @as(u32, 15008); pub const ERROR_INVALID_OPTION_TAG = @as(u32, 15009); pub const ERROR_NO_TAG = @as(u32, 15010); pub const ERROR_MISSING_OPTION = @as(u32, 15011); pub const ERROR_TRANSPORT_NOT_PRESENT = @as(u32, 15012); pub const ERROR_SHOW_USAGE = @as(u32, 15013); pub const ERROR_INVALID_OPTION_VALUE = @as(u32, 15014); pub const ERROR_OKAY = @as(u32, 15015); pub const ERROR_CONTINUE_IN_PARENT_CONTEXT = @as(u32, 15016); pub const ERROR_SUPPRESS_OUTPUT = @as(u32, 15017); pub const ERROR_HELPER_ALREADY_REGISTERED = @as(u32, 15018); pub const ERROR_CONTEXT_ALREADY_REGISTERED = @as(u32, 15019); pub const ERROR_PARSING_FAILURE = @as(u32, 15020); pub const MAX_NAME_LEN = @as(u32, 48); pub const NETSH_VERSION_50 = @as(u32, 20480); pub const NETSH_MAX_TOKEN_LENGTH = @as(u32, 64); pub const NETSH_MAX_CMD_TOKEN_LENGTH = @as(u32, 128); pub const DEFAULT_CONTEXT_PRIORITY = @as(u32, 100); //-------------------------------------------------------------------------------- // Section: Types (20) //-------------------------------------------------------------------------------- pub const NS_CMD_FLAGS = enum(i32) { PRIVATE = 1, INTERACTIVE = 2, LOCAL = 8, ONLINE = 16, HIDDEN = 32, LIMIT_MASK = 65535, PRIORITY = -2147483648, }; pub const CMD_FLAG_PRIVATE = NS_CMD_FLAGS.PRIVATE; pub const CMD_FLAG_INTERACTIVE = NS_CMD_FLAGS.INTERACTIVE; pub const CMD_FLAG_LOCAL = NS_CMD_FLAGS.LOCAL; pub const CMD_FLAG_ONLINE = NS_CMD_FLAGS.ONLINE; pub const CMD_FLAG_HIDDEN = NS_CMD_FLAGS.HIDDEN; pub const CMD_FLAG_LIMIT_MASK = NS_CMD_FLAGS.LIMIT_MASK; pub const CMD_FLAG_PRIORITY = NS_CMD_FLAGS.PRIORITY; pub const NS_REQS = enum(i32) { ZERO = 0, PRESENT = 1, ALLOW_MULTIPLE = 2, ONE_OR_MORE = 3, }; pub const NS_REQ_ZERO = NS_REQS.ZERO; pub const NS_REQ_PRESENT = NS_REQS.PRESENT; pub const NS_REQ_ALLOW_MULTIPLE = NS_REQS.ALLOW_MULTIPLE; pub const NS_REQ_ONE_OR_MORE = NS_REQS.ONE_OR_MORE; pub const NS_EVENTS = enum(i32) { LOOP = 65536, LAST_N = 1, LAST_SECS = 2, FROM_N = 4, FROM_START = 8, }; pub const NS_EVENT_LOOP = NS_EVENTS.LOOP; pub const NS_EVENT_LAST_N = NS_EVENTS.LAST_N; pub const NS_EVENT_LAST_SECS = NS_EVENTS.LAST_SECS; pub const NS_EVENT_FROM_N = NS_EVENTS.FROM_N; pub const NS_EVENT_FROM_START = NS_EVENTS.FROM_START; pub const NS_MODE_CHANGE = enum(i32) { COMMIT = 0, UNCOMMIT = 1, FLUSH = 2, COMMIT_STATE = 3, SAVE = 4, }; pub const NETSH_COMMIT = NS_MODE_CHANGE.COMMIT; pub const NETSH_UNCOMMIT = NS_MODE_CHANGE.UNCOMMIT; pub const NETSH_FLUSH = NS_MODE_CHANGE.FLUSH; pub const NETSH_COMMIT_STATE = NS_MODE_CHANGE.COMMIT_STATE; pub const NETSH_SAVE = NS_MODE_CHANGE.SAVE; pub const TOKEN_VALUE = extern struct { pwszToken: ?[*:0]const u16, dwValue: u32, }; pub const PGET_RESOURCE_STRING_FN = fn( dwMsgID: u32, lpBuffer: ?PWSTR, nBufferMax: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_CONTEXT_COMMIT_FN = fn( dwAction: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_CONTEXT_CONNECT_FN = fn( pwszMachine: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_CONTEXT_DUMP_FN = fn( pwszRouter: ?[*:0]const u16, ppwcArguments: [*]?PWSTR, dwArgCount: u32, pvData: ?*const c_void, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_DLL_STOP_FN = fn( dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_HELPER_START_FN = fn( pguidParent: ?*const Guid, dwVersion: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_HELPER_STOP_FN = fn( dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_HANDLE_CMD = fn( pwszMachine: ?[*:0]const u16, ppwcArguments: [*]?PWSTR, dwCurrentIndex: u32, dwArgCount: u32, dwFlags: u32, pvData: ?*const c_void, pbDone: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PNS_OSVERSIONCHECK = fn( CIMOSType: u32, CIMOSProductSuite: u32, CIMOSVersion: ?[*:0]const u16, CIMOSBuildNumber: ?[*:0]const u16, CIMServicePackMajorVersion: ?[*:0]const u16, CIMServicePackMinorVersion: ?[*:0]const u16, uiReserved: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const NS_HELPER_ATTRIBUTES = extern struct { Anonymous: extern union { Anonymous: extern struct { dwVersion: u32, dwReserved: u32, }, _ullAlign: u64, }, guidHelper: Guid, pfnStart: ?PNS_HELPER_START_FN, pfnStop: ?PNS_HELPER_STOP_FN, }; pub const CMD_ENTRY = extern struct { pwszCmdToken: ?[*:0]const u16, pfnCmdHandler: ?PFN_HANDLE_CMD, dwShortCmdHelpToken: u32, dwCmdHlpToken: u32, dwFlags: u32, pOsVersionCheck: ?PNS_OSVERSIONCHECK, }; pub const CMD_GROUP_ENTRY = extern struct { pwszCmdGroupToken: ?[*:0]const u16, dwShortCmdHelpToken: u32, ulCmdGroupSize: u32, dwFlags: u32, pCmdGroup: ?*CMD_ENTRY, pOsVersionCheck: ?PNS_OSVERSIONCHECK, }; pub const NS_CONTEXT_ATTRIBUTES = extern struct { Anonymous: extern union { Anonymous: extern struct { dwVersion: u32, dwReserved: u32, }, _ullAlign: u64, }, pwszContext: ?PWSTR, guidHelper: Guid, dwFlags: u32, ulPriority: u32, ulNumTopCmds: u32, pTopCmds: ?*CMD_ENTRY, ulNumGroups: u32, pCmdGroups: ?*CMD_GROUP_ENTRY, pfnCommitFn: ?PNS_CONTEXT_COMMIT_FN, pfnDumpFn: ?PNS_CONTEXT_DUMP_FN, pfnConnectFn: ?PNS_CONTEXT_CONNECT_FN, pReserved: ?*c_void, pfnOsVersionCheck: ?PNS_OSVERSIONCHECK, }; pub const TAG_TYPE = extern struct { pwszTag: ?[*:0]const u16, dwRequired: u32, bPresent: BOOL, }; pub const PNS_DLL_INIT_FN = fn( dwNetshVersion: u32, pReserved: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Functions (8) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn MatchEnumTag( hModule: ?HANDLE, pwcArg: ?[*:0]const u16, dwNumArg: u32, pEnumTable: ?*const TOKEN_VALUE, pdwValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn MatchToken( pwszUserToken: ?[*:0]const u16, pwszCmdToken: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn PreprocessCommand( hModule: ?HANDLE, ppwcArguments: [*]?PWSTR, dwCurrentIndex: u32, dwArgCount: u32, pttTags: ?[*]TAG_TYPE, dwTagCount: u32, dwMinArgs: u32, dwMaxArgs: u32, pdwTagType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn PrintError( hModule: ?HANDLE, dwErrId: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn PrintMessageFromModule( hModule: ?HANDLE, dwMsgId: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn PrintMessage( pwszFormat: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn RegisterContext( pChildContext: ?*const NS_CONTEXT_ATTRIBUTES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETSH" fn RegisterHelper( pguidParentContext: ?*const Guid, pfnRegisterSubContext: ?*const NS_HELPER_ATTRIBUTES, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (4) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const HANDLE = @import("../foundation.zig").HANDLE; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PGET_RESOURCE_STRING_FN")) { _ = PGET_RESOURCE_STRING_FN; } if (@hasDecl(@This(), "PNS_CONTEXT_COMMIT_FN")) { _ = PNS_CONTEXT_COMMIT_FN; } if (@hasDecl(@This(), "PNS_CONTEXT_CONNECT_FN")) { _ = PNS_CONTEXT_CONNECT_FN; } if (@hasDecl(@This(), "PNS_CONTEXT_DUMP_FN")) { _ = PNS_CONTEXT_DUMP_FN; } if (@hasDecl(@This(), "PNS_DLL_STOP_FN")) { _ = PNS_DLL_STOP_FN; } if (@hasDecl(@This(), "PNS_HELPER_START_FN")) { _ = PNS_HELPER_START_FN; } if (@hasDecl(@This(), "PNS_HELPER_STOP_FN")) { _ = PNS_HELPER_STOP_FN; } if (@hasDecl(@This(), "PFN_HANDLE_CMD")) { _ = PFN_HANDLE_CMD; } if (@hasDecl(@This(), "PNS_OSVERSIONCHECK")) { _ = PNS_OSVERSIONCHECK; } if (@hasDecl(@This(), "PNS_DLL_INIT_FN")) { _ = PNS_DLL_INIT_FN; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/network_management/net_shell.zig
const c = @import("c.zig"); const nk = @import("../nuklear.zig"); const std = @import("std"); const testing = std.testing; pub const Buttons = enum(u8) { left = c.NK_BUTTON_LEFT, middle = c.NK_BUTTON_MIDDLE, right = c.NK_BUTTON_RIGHT, double = c.NK_BUTTON_DOUBLE, }; pub const Keys = enum(u8) { none = c.NK_KEY_NONE, shift = c.NK_KEY_SHIFT, ctrl = c.NK_KEY_CTRL, del = c.NK_KEY_DEL, enter = c.NK_KEY_ENTER, tab = c.NK_KEY_TAB, backspace = c.NK_KEY_BACKSPACE, copy = c.NK_KEY_COPY, cut = c.NK_KEY_CUT, paste = c.NK_KEY_PASTE, up = c.NK_KEY_UP, down = c.NK_KEY_DOWN, left = c.NK_KEY_LEFT, right = c.NK_KEY_RIGHT, text_insert_mode = c.NK_KEY_TEXT_INSERT_MODE, text_replace_mode = c.NK_KEY_TEXT_REPLACE_MODE, text_reset_mode = c.NK_KEY_TEXT_RESET_MODE, text_line_start = c.NK_KEY_TEXT_LINE_START, text_line_end = c.NK_KEY_TEXT_LINE_END, text_start = c.NK_KEY_TEXT_START, text_end = c.NK_KEY_TEXT_END, text_undo = c.NK_KEY_TEXT_UNDO, text_redo = c.NK_KEY_TEXT_REDO, text_select_all = c.NK_KEY_TEXT_SELECT_ALL, text_word_left = c.NK_KEY_TEXT_WORD_LEFT, text_word_right = c.NK_KEY_TEXT_WORD_RIGHT, scroll_start = c.NK_KEY_SCROLL_START, scroll_end = c.NK_KEY_SCROLL_END, scroll_down = c.NK_KEY_SCROLL_DOWN, scroll_up = c.NK_KEY_SCROLL_UP, }; const input = @This(); pub fn begin(ctx: *nk.Context) void { c.nk_input_begin(ctx); } pub fn motion(ctx: *nk.Context, x: c_int, y: c_int) void { c.nk_input_motion(ctx, x, y); } pub fn key(ctx: *nk.Context, keys: Keys, down: bool) void { c.nk_input_key(ctx, @intToEnum(c.enum_nk_keys, @enumToInt(keys)), @boolToInt(down)); } pub fn button(ctx: *nk.Context, bot: Buttons, x: c_int, y: c_int, down: bool) void { c.nk_input_button( ctx, @intToEnum(c.enum_nk_buttons, @enumToInt(bot)), x, y, @boolToInt(down), ); } pub fn scroll(ctx: *nk.Context, val: nk.Vec2) void { c.nk_input_scroll(ctx, val); } pub fn char(ctx: *nk.Context, ch: u8) void { c.nk_input_char(ctx, ch); } pub fn glyph(ctx: *nk.Context, gl: [4]u8) void { c.nk_input_glyph(ctx, &gl); } pub fn unicode(ctx: *nk.Context, cp: u21) void { c.nk_input_unicode(ctx, @intCast(c.nk_rune, cp)); } pub fn end(ctx: *nk.Context) void { c.nk_input_end(ctx); } pub fn hasMouseClick(in: nk.Input, bots: nk.Buttons) bool { return c.nk_input_has_mouse_click(&in, bots) != 0; } pub fn hasMouseClickInRect(in: nk.Input, bots: nk.Buttons, r: nk.Rect) bool { return c.nk_input_has_mouse_click_in_rect(&in, bots, r) != 0; } pub fn hasMouseClickDownInRect(in: nk.Input, bots: nk.Buttons, r: nk.Rect, down: bool) bool { return c.nk_input_has_mouse_click_down_in_rect(&in, bots, r, @boolToInt(down)) != 0; } pub fn isMouseClickInRect(in: nk.Input, bots: nk.Buttons, r: nk.Rect) bool { return c.nk_input_is_mouse_click_in_rect(&in, bots, r) != 0; } pub fn isMouseClickDownInRect(in: nk.Input, id: nk.Buttons, b: nk.Rect, down: bool) bool { return c.nk_input_is_mouse_click_down_in_rect(&in, id, b, @boolToInt(down)) != 0; } pub fn anyMouseClickInRect(in: nk.Input, r: nk.Rect) bool { return c.nk_input_any_mouse_click_in_rect(&in, r) != 0; } pub fn isMousePrevHoveringRect(in: nk.Input, r: nk.Rect) bool { return c.nk_input_is_mouse_prev_hovering_rect(&in, r) != 0; } pub fn isMouseHoveringRect(in: nk.Input, r: nk.Rect) bool { return c.nk_input_is_mouse_hovering_rect(&in, r) != 0; } pub fn mouseClicked(in: nk.Input, bots: nk.Buttons, r: nk.Rect) bool { return c.nk_input_mouse_clicked(&in, bots, r) != 0; } pub fn isMouseDown(in: nk.Input, bots: nk.Buttons) bool { return c.nk_input_is_mouse_down(&in, bots) != 0; } pub fn isMousePressed(in: nk.Input, bots: nk.Buttons) bool { return c.nk_input_is_mouse_pressed(&in, bots) != 0; } pub fn isMouseReleased(in: nk.Input, bots: nk.Buttons) bool { return c.nk_input_is_mouse_released(&in, bots) != 0; } pub fn isKeyPressed(in: nk.Input, keys: nk.Keys) bool { return c.nk_input_is_key_pressed(&in, keys) != 0; } pub fn isKeyReleased(in: nk.Input, keys: nk.Keys) bool { return c.nk_input_is_key_released(&in, keys) != 0; } pub fn isKeyDown(in: nk.Input, keys: nk.Keys) bool { return c.nk_input_is_key_down(&in, keys) != 0; } test { testing.refAllDecls(@This()); } test "input" { var ctx = &try nk.testing.init(); defer nk.free(ctx); input.begin(ctx); input.motion(ctx, 20, 20); input.key(ctx, .del, true); input.button(ctx, .left, 40, 40, true); input.scroll(ctx, nk.vec2(20.0, 20.0)); input.char(ctx, 'a'); input.glyph(ctx, "👀".*); input.unicode(ctx, '👀'); input.end(ctx); }
src/input.zig
const std = @import("std"); const math = std.math; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w32 = zwin32.base; const d3d12 = zwin32.d3d12; const hrPanicOnFail = zwin32.hrPanicOnFail; const hrPanic = zwin32.hrPanic; const zd3d12 = @import("zd3d12"); const common = @import("common"); const c = common.c; const vm = common.vectormath; const GuiRenderer = common.GuiRenderer; pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const num_mipmaps = 5; const Vertex = struct { position: vm.Vec3, uv: vm.Vec2, }; comptime { std.debug.assert(@sizeOf([2]Vertex) == 40); std.debug.assert(@alignOf([2]Vertex) == 4); } const DemoState = struct { const window_name = "zig-gamedev: textured quad"; const window_width = 1024; const window_height = 1024; window: w32.HWND, gctx: zd3d12.GraphicsContext, guir: GuiRenderer, frame_stats: common.FrameStats, pipeline: zd3d12.PipelineHandle, vertex_buffer: zd3d12.ResourceHandle, index_buffer: zd3d12.ResourceHandle, texture: zd3d12.ResourceHandle, texture_srv: d3d12.CPU_DESCRIPTOR_HANDLE, mipmap_level: i32, fn init(allocator: std.mem.Allocator) !DemoState { const window = try common.initWindow(allocator, window_name, window_width, window_height); var gctx = zd3d12.GraphicsContext.init(allocator, window); var arena_allocator_state = std.heap.ArenaAllocator.init(allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); const pipeline = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Texcoords", 0, .R32G32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; pso_desc.RasterizerState.CullMode = .NONE; pso_desc.DepthStencilState.DepthEnable = w32.FALSE; pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; break :blk gctx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/textured_quad.vs.cso", content_dir ++ "shaders/textured_quad.ps.cso", ); }; const vertex_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(num_mipmaps * 4 * @sizeOf(Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const index_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(4 * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); var mipgen = zd3d12.MipmapGenerator.init(arena_allocator, &gctx, .R8G8B8A8_UNORM, content_dir); gctx.beginFrame(); const guir = GuiRenderer.init(arena_allocator, &gctx, 1, content_dir); const texture = gctx.createAndUploadTex2dFromFile( content_dir ++ "genart_0025_5.png", .{}, // Create complete mipmap chain (up to 1x1). ) catch |err| hrPanic(err); mipgen.generateMipmaps(&gctx, texture); const texture_srv = gctx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); gctx.device.CreateShaderResourceView( gctx.lookupResource(texture).?, &d3d12.SHADER_RESOURCE_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURE2D, .Shader4ComponentMapping = d3d12.DEFAULT_SHADER_4_COMPONENT_MAPPING, .u = .{ .Texture2D = .{ .MostDetailedMip = 0, .MipLevels = 0xffff_ffff, .PlaneSlice = 0, .ResourceMinLODClamp = 0.0, }, }, }, texture_srv, ); // Fill vertex buffer. { const upload_verts = gctx.allocateUploadBufferRegion(Vertex, num_mipmaps * 4); var mipmap_index: u32 = 0; var r: f32 = 1.0; while (mipmap_index < num_mipmaps) : (mipmap_index += 1) { const index = mipmap_index * 4; upload_verts.cpu_slice[index] = .{ .position = vm.Vec3.init(-r, r, 0.0), .uv = vm.Vec2.init(0.0, 0.0), }; upload_verts.cpu_slice[index + 1] = .{ .position = vm.Vec3.init(r, r, 0.0), .uv = vm.Vec2.init(1.0, 0.0), }; upload_verts.cpu_slice[index + 2] = .{ .position = vm.Vec3.init(-r, -r, 0.0), .uv = vm.Vec2.init(0.0, 1.0), }; upload_verts.cpu_slice[index + 3] = .{ .position = vm.Vec3.init(r, -r, 0.0), .uv = vm.Vec2.init(1.0, 1.0), }; r *= 0.5; } gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(vertex_buffer).?, 0, upload_verts.buffer, upload_verts.buffer_offset, upload_verts.cpu_slice.len * @sizeOf(@TypeOf(upload_verts.cpu_slice[0])), ); } // Fill index buffer. { const upload_indices = gctx.allocateUploadBufferRegion(u32, 4); upload_indices.cpu_slice[0] = 0; upload_indices.cpu_slice[1] = 1; upload_indices.cpu_slice[2] = 2; upload_indices.cpu_slice[3] = 3; gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(index_buffer).?, 0, upload_indices.buffer, upload_indices.buffer_offset, upload_indices.cpu_slice.len * @sizeOf(@TypeOf(upload_indices.cpu_slice[0])), ); } gctx.addTransitionBarrier(vertex_buffer, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); gctx.addTransitionBarrier(index_buffer, d3d12.RESOURCE_STATE_INDEX_BUFFER); gctx.addTransitionBarrier(texture, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); gctx.flushResourceBarriers(); gctx.endFrame(); gctx.finishGpuCommands(); // NOTE(mziulek): // We need to call 'deinit' explicitly - we can't rely on 'defer' in this case because it runs *after* // 'gctx' is copied in 'return' statement below. mipgen.deinit(&gctx); return DemoState{ .gctx = gctx, .guir = guir, .window = window, .frame_stats = common.FrameStats.init(), .pipeline = pipeline, .vertex_buffer = vertex_buffer, .index_buffer = index_buffer, .texture = texture, .texture_srv = texture_srv, .mipmap_level = 1, }; } fn deinit(demo: *DemoState, allocator: std.mem.Allocator) void { demo.gctx.finishGpuCommands(); demo.guir.deinit(&demo.gctx); demo.gctx.deinit(allocator); common.deinitWindow(allocator); demo.* = undefined; } fn update(demo: *DemoState) void { demo.frame_stats.update(demo.gctx.window, window_name); common.newImGuiFrame(demo.frame_stats.delta_time); c.igSetNextWindowPos(.{ .x = 10.0, .y = 10.0 }, c.ImGuiCond_FirstUseEver, .{ .x = 0.0, .y = 0.0 }); c.igSetNextWindowSize(.{ .x = 600.0, .y = 0.0 }, c.ImGuiCond_FirstUseEver); _ = c.igBegin( "Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoSavedSettings, ); _ = c.igSliderInt("Mipmap Level", &demo.mipmap_level, 0, num_mipmaps - 1, null, c.ImGuiSliderFlags_None); c.igEnd(); } fn draw(demo: *DemoState) void { var gctx = &demo.gctx; gctx.beginFrame(); const back_buffer = gctx.getBackBuffer(); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); gctx.flushResourceBarriers(); gctx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w32.TRUE, null, ); gctx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.2, 0.4, 0.8, 1.0 }, 0, null, ); gctx.setCurrentPipeline(demo.pipeline); gctx.cmdlist.IASetPrimitiveTopology(.TRIANGLESTRIP); gctx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = gctx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = num_mipmaps * 4 * @sizeOf(Vertex), .StrideInBytes = @sizeOf(Vertex), }}); gctx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = gctx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = 4 * @sizeOf(u32), .Format = .R32_UINT, }); gctx.cmdlist.SetGraphicsRootDescriptorTable(0, gctx.copyDescriptorsToGpuHeap(1, demo.texture_srv)); gctx.cmdlist.DrawIndexedInstanced(4, 1, 0, demo.mipmap_level * 4, 0); demo.guir.draw(gctx); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); gctx.flushResourceBarriers(); gctx.endFrame(); } }; pub fn main() !void { common.init(); defer common.deinit(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var demo = try DemoState.init(allocator); defer demo.deinit(allocator); while (common.handleWindowEvents()) { demo.update(); demo.draw(); } }
samples/textured_quad/src/textured_quad.zig
const cmp = @import("cmp.zig"); const testing = @import("std").testing; fn test__cmpsi2(a: i32, b: i32, expected: i32) !void { var result = cmp.__cmpsi2(a, b); try testing.expectEqual(expected, result); } test "cmpsi2" { // minInt == -2147483648 // maxInt == 2147483647 // minInt/2 == -1073741824 // maxInt/2 == 1073741823 // 1. equality minInt, minInt+1, minInt/2, -1, 0, 1, maxInt/2, maxInt-1, maxInt try test__cmpsi2(-2147483648, -2147483648, 1); try test__cmpsi2(-2147483647, -2147483647, 1); try test__cmpsi2(-1073741824, -1073741824, 1); try test__cmpsi2(-1, -1, 1); try test__cmpsi2(0, 0, 1); try test__cmpsi2(1, 1, 1); try test__cmpsi2(1073741823, 1073741823, 1); try test__cmpsi2(2147483646, 2147483646, 1); try test__cmpsi2(2147483647, 2147483647, 1); // 2. cmp minInt, { minInt + 1, minInt/2, -1,0,1, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(-2147483648, -2147483647, 0); try test__cmpsi2(-2147483648, -1073741824, 0); try test__cmpsi2(-2147483648, -1, 0); try test__cmpsi2(-2147483648, 0, 0); try test__cmpsi2(-2147483648, 1, 0); try test__cmpsi2(-2147483648, 1073741823, 0); try test__cmpsi2(-2147483648, 2147483646, 0); try test__cmpsi2(-2147483648, 2147483647, 0); // 3. cmp minInt+1, {minInt, minInt/2, -1,0,1, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(-2147483647, -2147483648, 2); try test__cmpsi2(-2147483647, -1073741824, 0); try test__cmpsi2(-2147483647, -1, 0); try test__cmpsi2(-2147483647, 0, 0); try test__cmpsi2(-2147483647, 1, 0); try test__cmpsi2(-2147483647, 1073741823, 0); try test__cmpsi2(-2147483647, 2147483646, 0); try test__cmpsi2(-2147483647, 2147483647, 0); // 4. cmp minInt/2, {minInt, minInt + 1, -1,0,1, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(-1073741824, -2147483648, 2); try test__cmpsi2(-1073741824, -2147483647, 2); try test__cmpsi2(-1073741824, -1, 0); try test__cmpsi2(-1073741824, 0, 0); try test__cmpsi2(-1073741824, 1, 0); try test__cmpsi2(-1073741824, 1073741823, 0); try test__cmpsi2(-1073741824, 2147483646, 0); try test__cmpsi2(-1073741824, 2147483647, 0); // 5. cmp -1, {minInt, minInt + 1, minInt/2, 0,1, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(-1, -2147483648, 2); try test__cmpsi2(-1, -2147483647, 2); try test__cmpsi2(-1, -1073741824, 2); try test__cmpsi2(-1, 0, 0); try test__cmpsi2(-1, 1, 0); try test__cmpsi2(-1, 1073741823, 0); try test__cmpsi2(-1, 2147483646, 0); try test__cmpsi2(-1, 2147483647, 0); // 6. cmp 0, {minInt, minInt + 1, minInt/2, -1, 1, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(0, -2147483648, 2); try test__cmpsi2(0, -2147483647, 2); try test__cmpsi2(0, -1073741824, 2); try test__cmpsi2(0, -1, 2); try test__cmpsi2(0, 1, 0); try test__cmpsi2(0, 1073741823, 0); try test__cmpsi2(0, 2147483646, 0); try test__cmpsi2(0, 2147483647, 0); // 7. cmp 1, {minInt, minInt + 1, minInt/2, -1,0, maxInt/2, maxInt-1, maxInt} try test__cmpsi2(1, -2147483648, 2); try test__cmpsi2(1, -2147483647, 2); try test__cmpsi2(1, -1073741824, 2); try test__cmpsi2(1, -1, 2); try test__cmpsi2(1, 0, 2); try test__cmpsi2(1, 1073741823, 0); try test__cmpsi2(1, 2147483646, 0); try test__cmpsi2(1, 2147483647, 0); // 8. cmp maxInt/2, {minInt, minInt + 1, minInt/2, -1, 0, 1, maxInt-1, maxInt} try test__cmpsi2(1073741823, -2147483648, 2); try test__cmpsi2(1073741823, -2147483647, 2); try test__cmpsi2(1073741823, -1073741824, 2); try test__cmpsi2(1073741823, -1, 2); try test__cmpsi2(1073741823, 0, 2); try test__cmpsi2(1073741823, 1, 2); try test__cmpsi2(1073741823, 2147483646, 0); try test__cmpsi2(1073741823, 2147483647, 0); // 9. cmp maxInt-1, {minInt, minInt + 1, minInt/2, -1, 0, 1, maxInt/2, maxInt} try test__cmpsi2(2147483646, -2147483648, 2); try test__cmpsi2(2147483646, -2147483647, 2); try test__cmpsi2(2147483646, -1073741824, 2); try test__cmpsi2(2147483646, -1, 2); try test__cmpsi2(2147483646, 0, 2); try test__cmpsi2(2147483646, 1, 2); try test__cmpsi2(2147483646, 1073741823, 2); try test__cmpsi2(2147483646, 2147483647, 0); // 10.cmp maxInt, {minInt, minInt + 1, minInt/2, -1, 0, 1, maxInt/2, maxInt-1, } try test__cmpsi2(2147483647, -2147483648, 2); try test__cmpsi2(2147483647, -2147483647, 2); try test__cmpsi2(2147483647, -1073741824, 2); try test__cmpsi2(2147483647, -1, 2); try test__cmpsi2(2147483647, 0, 2); try test__cmpsi2(2147483647, 1, 2); try test__cmpsi2(2147483647, 1073741823, 2); try test__cmpsi2(2147483647, 2147483646, 2); }
lib/std/special/compiler_rt/cmpsi2_test.zig
const std = @import("std"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; pub fn __log2h(a: f16) callconv(.C) f16 { // TODO: more efficient implementation return @floatCast(f16, log2f(a)); } pub fn log2f(x_: f32) callconv(.C) f32 { const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var u = @bitCast(u32, x); var ix = u; var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (ix >> 31 != 0) { return math.nan(f32); } k -= 25; x *= 0x1.0p25; ix = @bitCast(u32, x); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; var hi = f - hfsq; u = @bitCast(u32, hi); u &= 0xFFFFF000; hi = @bitCast(f32, u); const lo = f - hi - hfsq + s * (hfsq + R); return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + @intToFloat(f32, k); } pub fn log2(x_: f64) callconv(.C) f64 { const ivln2hi: f64 = 1.44269504072144627571e+00; const ivln2lo: f64 = 1.67517131648865118353e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @bitCast(u64, x); var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f64); } // log(-#) = nan if (hx >> 31 != 0) { return math.nan(f64); } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = @intCast(u32, @bitCast(u64, x) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; // hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f) var hi = f - hfsq; var hii = @bitCast(u64, hi); hii &= @as(u64, maxInt(u64)) << 32; hi = @bitCast(f64, hii); const lo = f - hi - hfsq + s * (hfsq + R); var val_hi = hi * ivln2hi; var val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; // spadd(val_hi, val_lo, y) const y = @intToFloat(f64, k); const ww = y + val_hi; val_lo += (y - ww) + val_hi; val_hi = ww; return val_lo + val_hi; } pub fn __log2x(a: f80) callconv(.C) f80 { // TODO: more efficient implementation return @floatCast(f80, log2q(a)); } pub fn log2q(a: f128) callconv(.C) f128 { // TODO: more correct implementation return log2(@floatCast(f64, a)); } pub fn log2l(x: c_longdouble) callconv(.C) c_longdouble { switch (@typeInfo(c_longdouble).Float.bits) { 16 => return __log2h(x), 32 => return log2f(x), 64 => return log2(x), 80 => return __log2x(x), 128 => return log2q(x), else => @compileError("unreachable"), } } test "log2_32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, log2f(0.2), -2.321928, epsilon)); try expect(math.approxEqAbs(f32, log2f(0.8923), -0.164399, epsilon)); try expect(math.approxEqAbs(f32, log2f(1.5), 0.584962, epsilon)); try expect(math.approxEqAbs(f32, log2f(37.45), 5.226894, epsilon)); try expect(math.approxEqAbs(f32, log2f(123123.234375), 16.909744, epsilon)); } test "log2_64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, log2(0.2), -2.321928, epsilon)); try expect(math.approxEqAbs(f64, log2(0.8923), -0.164399, epsilon)); try expect(math.approxEqAbs(f64, log2(1.5), 0.584962, epsilon)); try expect(math.approxEqAbs(f64, log2(37.45), 5.226894, epsilon)); try expect(math.approxEqAbs(f64, log2(123123.234375), 16.909744, epsilon)); } test "log2_32.special" { try expect(math.isPositiveInf(log2f(math.inf(f32)))); try expect(math.isNegativeInf(log2f(0.0))); try expect(math.isNan(log2f(-1.0))); try expect(math.isNan(log2f(math.nan(f32)))); } test "log2_64.special" { try expect(math.isPositiveInf(log2(math.inf(f64)))); try expect(math.isNegativeInf(log2(0.0))); try expect(math.isNan(log2(-1.0))); try expect(math.isNan(log2(math.nan(f64)))); }
lib/compiler_rt/log2.zig